From 6eebb86acb8df41b6ea957e41ea2e0881212055f Mon Sep 17 00:00:00 2001 From: LordMZTE Date: Fri, 2 Dec 2022 16:30:12 +0100 Subject: [PATCH 1/4] deps: upgradle --- build.gradle | 56 +++++++---------- gradle/scripts/dependencies.gradle | 78 ++++++++++++------------ gradle/scripts/optional.gradle | 4 -- gradle/wrapper/gradle-wrapper.properties | 2 +- 4 files changed, 62 insertions(+), 78 deletions(-) diff --git a/build.gradle b/build.gradle index 5d081984..9bc787a2 100644 --- a/build.gradle +++ b/build.gradle @@ -1,21 +1,3 @@ -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - apply plugin: 'forge' apply plugin: 'maven-publish' @@ -43,7 +25,9 @@ buildscript { } dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' + classpath ('com.anatawa12.forge:ForgeGradle:1.2-1.0.+') { + changing = true + } } } @@ -100,24 +84,28 @@ sourceSets { resources { srcDir "src/main/resources/" - include "assets/appliedenergistics2/recipes/**/*.recipe", - "assets/appliedenergistics2/recipes/README.html", - "assets/appliedenergistics2/lang/*.lang", - "assets/appliedenergistics2/textures/blocks/*", - "assets/appliedenergistics2/textures/guis/*", - "assets/appliedenergistics2/textures/models/*", - "assets/appliedenergistics2/textures/items/*", - "assets/appliedenergistics2/meta/*", - "mcmod.info", - "pack.mcmeta" + include( + "assets/appliedenergistics2/recipes/**/*.recipe", + "assets/appliedenergistics2/recipes/README.html", + "assets/appliedenergistics2/lang/*.lang", + "assets/appliedenergistics2/textures/blocks/*", + "assets/appliedenergistics2/textures/guis/*", + "assets/appliedenergistics2/textures/models/*", + "assets/appliedenergistics2/textures/items/*", + "assets/appliedenergistics2/meta/*", + "mcmod.info", + "pack.mcmeta" + ) } } } processResources { - // replace stuff in mcmod.info, nothing else - from(sourceSets.main.resources.srcDirs) { - include 'mcmod.info' - expand 'version': project.version, 'mcversion': minecraft_version + inputs.property "version", project.version + inputs.property "mcversion", project.minecraft.version + + filesMatching('mcmod.info') { + expand 'version':project.version, 'mcversion':project.minecraft.version } -} \ No newline at end of file +} + diff --git a/gradle/scripts/dependencies.gradle b/gradle/scripts/dependencies.gradle index f618240c..c767e401 100644 --- a/gradle/scripts/dependencies.gradle +++ b/gradle/scripts/dependencies.gradle @@ -1,24 +1,3 @@ - -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - - - repositories { mavenLocal() // ChickenBones' maven repo is unavailable now... @@ -30,36 +9,54 @@ repositories { maven { name "Mobius" url "http://mobiusstrip.eu/maven" + metadataSources { + artifact() + } } maven { name = "Player" url = "http://maven.ic2.player.to/" + metadataSources { + artifact() + } } maven { name = "Tterrag" url = "http://maven.tterrag.com/" + metadataSources { + artifact() + } } maven { name "OpenComputers Repo" url = "http://maven.cil.li/" + metadataSources { + artifact() + } } maven { name = "MM repo" url = "http://maven.k-4u.nl/" + metadataSources { + artifact() + } } maven { name = "tilera" - url = "https://data.tilera.xyz/maven/" + url = "https://maven.tilera.xyz/" } ivy { name "BuildCraft" artifactPattern "http://www.mod-buildcraft.com/releases/BuildCraft/[revision]/[module]-[revision]-[classifier].[ext]" + metadataSources { + artifact() + } } ivy { @@ -67,6 +64,9 @@ repositories { layout "pattern", { artifact "[revision]/artifact/build/libs/[artifact]-0.9.3.[revision](-[classifier]).[ext]" } + metadataSources { + artifact() + } } // CurseForge DNS for TE is not available or I am just being unlucky, code part can stay since this is applicable to any other curseforge mod though @@ -106,7 +106,7 @@ dependencies { // mods "net.mcft.copy.betterstorage:BetterStorage:${minecraft_version}-${betterstorage_version}:deobf" mods "inventorytweaks:InventoryTweaks:${invtweaks_version}:deobf" mods "li.cil.oc:OpenComputers:MC${minecraft_version}-${opencomputers_version}:dev" - compile "logisticspipes:logisticspipes:${logisticspipes_build}:dev" + implementation "logisticspipes:logisticspipes:${logisticspipes_build}:dev" // mods name: 'CoFHLib', version: "[${minecraft_version}]${cofhlib_version}-dev", ext: 'jar' // mods name: 'CoFHCore', version: "[${minecraft_version}]${cofhcore_version}-dev", ext: 'jar' @@ -122,27 +122,27 @@ dependencies { compileOnly files("lib/CodeChickenCore-${minecraft_version}-${code_chicken_core_version}-dev.jar") compileOnly files("lib/NotEnoughItems-${minecraft_version}-${nei_version}-dev.jar") - compile files("lib/buildcraft-${bc_version}-dev.jar") - compile files("lib/PneumaticCraft-${minecraft_version}-${pneumaticcraft_version}-api.jar") + implementation files("lib/buildcraft-${bc_version}-dev.jar") + implementation files("lib/PneumaticCraft-${minecraft_version}-${pneumaticcraft_version}-api.jar") // provided APIs - compile files("lib/OpenComputers-MC${minecraft_version}-${opencomputers_version}-api.jar") - compile files("lib/industrialcraft-2-${ic2_version}-experimental-api.jar") - compile files("lib/BetterStorage-${minecraft_version}-${betterstorage_version}-api.jar") + implementation files("lib/OpenComputers-MC${minecraft_version}-${opencomputers_version}-api.jar") + implementation files("lib/industrialcraft-2-${ic2_version}-experimental-api.jar") + implementation files("lib/BetterStorage-${minecraft_version}-${betterstorage_version}-api.jar") // self compiled APIs - compile "appeng:Waila:${waila_version}_${minecraft_version}:api" - compile "appeng:RotaryCraft:${rotarycraft_version}:api" - compile "appeng:mekanism:${minecraft_version}-${mekansim_version}:api" - compile "appeng:InventoryTweaks:${invtweaks_version}:api" + implementation "appeng:Waila:${waila_version}_${minecraft_version}:api" + implementation "appeng:RotaryCraft:${rotarycraft_version}:api" + implementation "appeng:mekanism:${minecraft_version}-${mekansim_version}:api" + implementation "appeng:InventoryTweaks:${invtweaks_version}:api" // self compiled stubs - compile(group: 'api', name: 'coloredlightscore', version: "${api_coloredlightscore_version}") - compile(group: 'api', name: 'craftguide', version: "${api_craftguide_version}") - compile(group: 'api', name: 'immibis', version: "${api_immibis_version}") - compile(group: 'api', name: 'mfr', version: "${api_mfr_version}") - compile(group: 'api', name: 'railcraft', version: "${api_railcraft_version}") - compile(group: 'api', name: 'rf', version: "${api_rf_version}") + implementation(group: 'api', name: 'coloredlightscore', version: "${api_coloredlightscore_version}") + implementation(group: 'api', name: 'craftguide', version: "${api_craftguide_version}") + implementation(group: 'api', name: 'immibis', version: "${api_immibis_version}") + implementation(group: 'api', name: 'mfr', version: "${api_mfr_version}") + implementation(group: 'api', name: 'railcraft', version: "${api_railcraft_version}") + implementation(group: 'api', name: 'rf', version: "${api_rf_version}") - testCompile "junit:junit:4.12" + testImplementation "junit:junit:4.12" } diff --git a/gradle/scripts/optional.gradle b/gradle/scripts/optional.gradle index 66fd6587..a7eb8c71 100644 --- a/gradle/scripts/optional.gradle +++ b/gradle/scripts/optional.gradle @@ -1,7 +1,3 @@ -task wrapper(type: Wrapper) { - gradleVersion = "2.4" -} - // WAILA task installWaila(type: Copy, dependsOn: "deinstallWaila") { from { configurations.mods } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ac6055de..6e8be293 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip From ed0cc5f181c8a7663b615d2509e59da1bd098ebf Mon Sep 17 00:00:00 2001 From: LordMZTE Date: Fri, 2 Dec 2022 17:39:49 +0100 Subject: [PATCH 2/4] feat: add legacy wireless access point --- .../appeng/block/legacy/BlockTerminal.java | 28 +- .../legacy/BlockWirelessAccessPoint.java | 47 +++ .../block/networking/BlockWireless.java | 344 +++++++++--------- .../core/api/definitions/ApiBlocks.java | 8 +- .../appeng/tile/networking/TileWireless.java | 5 + .../appliedenergistics2/lang/en_US.lang | 3 +- .../recipes/legacy/index.recipe | 6 + .../blocks/BlockWirelessAccessPoint.png | Bin 0 -> 450 bytes 8 files changed, 254 insertions(+), 187 deletions(-) create mode 100644 src/main/java/appeng/block/legacy/BlockWirelessAccessPoint.java create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockWirelessAccessPoint.png diff --git a/src/main/java/appeng/block/legacy/BlockTerminal.java b/src/main/java/appeng/block/legacy/BlockTerminal.java index 997c20ea..a5e29b62 100644 --- a/src/main/java/appeng/block/legacy/BlockTerminal.java +++ b/src/main/java/appeng/block/legacy/BlockTerminal.java @@ -1,5 +1,7 @@ package appeng.block.legacy; +import java.util.EnumSet; + import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; @@ -10,26 +12,34 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - public class BlockTerminal extends AEBaseTileBlock { - public BlockTerminal() { super(Material.iron); this.setTileEntity(TileTerminal.class); - this.setFeature( EnumSet.of(AEFeature.Legacy) ); + this.setFeature(EnumSet.of(AEFeature.Legacy)); } @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 + ) { final TileTerminal tile = this.getTileEntity(w, x, y, z); - if( tile != null && !player.isSneaking() ) { - if( Platform.isClient() ) - { + if (tile != null && !player.isSneaking()) { + if (Platform.isClient()) { return true; } - Platform.openGUI(player, tile, ForgeDirection.getOrientation(side), GuiBridge.GUI_ME); + Platform.openGUI( + player, tile, ForgeDirection.getOrientation(side), GuiBridge.GUI_ME + ); return true; } diff --git a/src/main/java/appeng/block/legacy/BlockWirelessAccessPoint.java b/src/main/java/appeng/block/legacy/BlockWirelessAccessPoint.java new file mode 100644 index 00000000..fa8b1453 --- /dev/null +++ b/src/main/java/appeng/block/legacy/BlockWirelessAccessPoint.java @@ -0,0 +1,47 @@ +package appeng.block.legacy; + +import java.util.EnumSet; + +import appeng.block.AEBaseTileBlock; +import appeng.core.features.AEFeature; +import appeng.core.sync.GuiBridge; +import appeng.tile.networking.TileWireless; +import appeng.util.Platform; +import net.minecraft.block.material.Material; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + +public class BlockWirelessAccessPoint extends AEBaseTileBlock { + public BlockWirelessAccessPoint() { + super(Material.iron); + this.isOpaque = true; + this.setTileEntity(TileWireless.class); + this.setFeature(EnumSet.of(AEFeature.Legacy)); + } + + @Override + public boolean onBlockActivated( + World w, + int x, + int y, + int z, + EntityPlayer p, + int side, + // useless parameters + float alec1, + float alec2, + float alec3 + ) { + TileEntity tileEntity = w.getTileEntity(x, y, z); + if (tileEntity != null && !p.isSneaking()) { + Platform.openGUI( + p, tileEntity, ForgeDirection.getOrientation(side), GuiBridge.GUI_WIRELESS + ); + return true; + } else { + return false; + } + } +} diff --git a/src/main/java/appeng/block/networking/BlockWireless.java b/src/main/java/appeng/block/networking/BlockWireless.java index 690da0d1..b5960e51 100644 --- a/src/main/java/appeng/block/networking/BlockWireless.java +++ b/src/main/java/appeng/block/networking/BlockWireless.java @@ -1,23 +1,8 @@ -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - package appeng.block.networking; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockWireless; @@ -35,172 +20,183 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; +public class BlockWireless extends AEBaseTileBlock implements ICustomCollision { + public BlockWireless() { + super(AEGlassMaterial.INSTANCE); + this.setTileEntity(TileWireless.class); + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.Core, AEFeature.WirelessAccessTerminal)); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockWireless getRenderer() { + return new RenderBlockWireless(); + } -public class BlockWireless extends AEBaseTileBlock implements ICustomCollision -{ + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final TileWireless tg = this.getTileEntity(w, x, y, z); - public BlockWireless() - { - super( AEGlassMaterial.INSTANCE ); - this.setTileEntity( TileWireless.class ); - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.Core, AEFeature.WirelessAccessTerminal ) ); - } + if (tg != null && !p.isSneaking()) { + if (Platform.isServer()) { + Platform.openGUI( + p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_WIRELESS + ); + } + return true; + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockWireless getRenderer() - { - return new RenderBlockWireless(); - } + return super.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileWireless tg = this.getTileEntity( w, x, y, z ); + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + final TileWireless tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final ForgeDirection forward = tile.getForward(); - if( tg != null && !p.isSneaking() ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_WIRELESS ); - } - return true; - } + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; - return super.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } + 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; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final TileWireless tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final ForgeDirection forward = tile.getForward(); + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ) + ); + } + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(0.0, 0, 0.0, 1.0, 1.0, 1.0) + ); + } - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + final TileWireless tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final ForgeDirection forward = tile.getForward(); - 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; - } + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } + 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; + } - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final TileWireless tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final ForgeDirection forward = tile.getForward(); - - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; - - 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; - } - - out.add( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - else - { - out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } - } + out.add(AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); + } else { + out.add(AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiBlocks.java b/src/main/java/appeng/core/api/definitions/ApiBlocks.java index 128cc4e1..fbfa46b8 100644 --- a/src/main/java/appeng/core/api/definitions/ApiBlocks.java +++ b/src/main/java/appeng/core/api/definitions/ApiBlocks.java @@ -31,6 +31,7 @@ import appeng.block.legacy.BlockCraftMonitor; import appeng.block.legacy.BlockCraftTerminal; import appeng.block.legacy.BlockLegacyController; import appeng.block.legacy.BlockTerminal; +import appeng.block.legacy.BlockWirelessAccessPoint; import appeng.block.misc.*; import appeng.block.networking.*; import appeng.block.qnb.BlockQuantumLinkChamber; @@ -133,11 +134,12 @@ public final class ApiBlocks implements IBlocks private final Set orientables; - //Legacy + // Legacy private final ITileDefinition terminal; private final ITileDefinition craftTerminal; private final ITileDefinition craftMonitor; private final ITileDefinition legacyController; + private final ITileDefinition legacyWirelessAccessPoint; public ApiBlocks( final DefinitionConstructor constructor ) { @@ -228,12 +230,12 @@ public final class ApiBlocks implements IBlocks this.phantomNode = constructor.registerBlockDefinition( new BlockPhantomNode() ); this.cubeGenerator = constructor.registerBlockDefinition( new BlockCubeGenerator() ); - //Legacy + // Legacy this.terminal = constructor.registerTileDefinition( new BlockTerminal() ); this.craftTerminal = constructor.registerTileDefinition( new BlockCraftTerminal() ); this.craftMonitor = constructor.registerTileDefinition( new BlockCraftMonitor() ); this.legacyController = constructor.registerTileDefinition( new BlockLegacyController() ); - + this.legacyWirelessAccessPoint = constructor.registerTileDefinition(new BlockWirelessAccessPoint()); } @Override diff --git a/src/main/java/appeng/tile/networking/TileWireless.java b/src/main/java/appeng/tile/networking/TileWireless.java index cbdb63ba..83302e85 100644 --- a/src/main/java/appeng/tile/networking/TileWireless.java +++ b/src/main/java/appeng/tile/networking/TileWireless.java @@ -29,6 +29,7 @@ import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.api.networking.events.MENetworkPowerStatusChange; import appeng.api.util.AECableType; import appeng.api.util.DimensionalCoord; +import appeng.block.legacy.BlockWirelessAccessPoint; import appeng.core.AEConfig; import appeng.me.GridAccessException; import appeng.tile.TileEvent; @@ -66,7 +67,11 @@ public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoi public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) { super.setOrientation( inForward, inUp ); + if (this.worldObj.getBlock(this.xCoord, this.yCoord, this.zCoord) instanceof BlockWirelessAccessPoint) { + this.getProxy().setValidSides( EnumSet.allOf(ForgeDirection.class) ); + } else { this.getProxy().setValidSides( EnumSet.of( this.getForward().getOpposite() ) ); + } } @MENetworkEventSubscribe diff --git a/src/main/resources/assets/appliedenergistics2/lang/en_US.lang b/src/main/resources/assets/appliedenergistics2/lang/en_US.lang index f77e8ea0..cd3ce152 100644 --- a/src/main/resources/assets/appliedenergistics2/lang/en_US.lang +++ b/src/main/resources/assets/appliedenergistics2/lang/en_US.lang @@ -51,11 +51,12 @@ tile.appliedenergistics2.BlockCraftingAccelerator.name=Crafting Co-Processing Un tile.appliedenergistics2.BlockCraftingUnit.name=Crafting Unit tile.appliedenergistics2.BlockMolecularAssembler.name=Molecular Assembler -#Legacy +# Legacy tile.appliedenergistics2.BlockTerminal.name=ME Access Terminal tile.appliedenergistics2.BlockCraftTerminal.name=ME Crafting Terminal tile.appliedenergistics2.BlockCraftMonitor.name=ME Crafting Monitor tile.appliedenergistics2.BlockLegacyController.name=ME Controller (W.I.P) +tile.appliedenergistics2.BlockWirelessAccessPoint.name=Wireless Access Point item.appliedenergistics2.ItemMaterial.ConversionMatrix.name=Conversion Matrix diff --git a/src/main/resources/assets/appliedenergistics2/recipes/legacy/index.recipe b/src/main/resources/assets/appliedenergistics2/recipes/legacy/index.recipe index 6fb58e26..e6f7e1a2 100644 --- a/src/main/resources/assets/appliedenergistics2/recipes/legacy/index.recipe +++ b/src/main/resources/assets/appliedenergistics2/recipes/legacy/index.recipe @@ -33,3 +33,9 @@ shaped= fluixCrystal ae2:ItemMaterial.EngProcessor fluixCrystal, oredictionary:ingotIron fluixCrystal oredictionary:ingotIron -> ae2:BlockLegacyController + +shaped= + oredictionary:ingotIron glass oredictionary:ingotIron, + ae2:CableGlass.Fluix ae2:ItemMaterial.Wireless glass, + oredictionary:ingotIron glass oredictionary:ingotIron, + -> ae2:BlockWirelessAccessPoint diff --git a/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockWirelessAccessPoint.png b/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockWirelessAccessPoint.png new file mode 100644 index 0000000000000000000000000000000000000000..7b5d12798bcc10edc83b83ba47ca759fdfcce8e2 GIT binary patch literal 450 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstU$g(vPY0F z14ES>14Ba#1H&(%P{RubhEf9thF1v;3|2E37{m+a>8tws`mTEYKd|M0;GzEv?fiE%zHJO6IyOvA&Iray{( zpqJ6{{$$3?_DfOHy8mbA%~#&>MQmrQN9a?*8pgX1ShxP16*2{ApK6I~L`h0wNvc(H zQ7VvPFfuSS)-^EJH8ct_u&^>VwlcKPH88a@Fu3M=azBcO-29Zxv`V-J1CtOVV=Dt7 zGSM|K18Vqsm3uu*ARs=V?9$nLj!{^MGJwd7(8A5 KT-G@yGywp-5RLEv literal 0 HcmV?d00001 From f67fb6a129f0e25079e5af695bc4144ea3050abf Mon Sep 17 00:00:00 2001 From: LordMZTE Date: Fri, 2 Dec 2022 17:40:47 +0100 Subject: [PATCH 3/4] chore: format code --- src/api/java/appeng/api/AEApi.java | 76 +- src/api/java/appeng/api/IAppEngApi.java | 117 +- .../appeng/api/config/AccessRestriction.java | 74 +- .../java/appeng/api/config/ActionItems.java | 6 +- .../java/appeng/api/config/Actionable.java | 20 +- .../appeng/api/config/CondenserOutput.java | 14 +- src/api/java/appeng/api/config/CopyMode.java | 6 +- .../java/appeng/api/config/FullnessMode.java | 6 +- src/api/java/appeng/api/config/FuzzyMode.java | 33 +- .../appeng/api/config/IncludeExclude.java | 6 +- .../appeng/api/config/ItemSubstitution.java | 6 +- .../appeng/api/config/LevelEmitterMode.java | 8 +- src/api/java/appeng/api/config/LevelType.java | 8 +- .../java/appeng/api/config/ModSettings.java | 4 +- .../appeng/api/config/NetworkEmitterMode.java | 10 +- .../java/appeng/api/config/OperationMode.java | 6 +- .../java/appeng/api/config/OutputMode.java | 6 +- .../appeng/api/config/PowerMultiplier.java | 29 +- .../java/appeng/api/config/PowerUnits.java | 69 +- .../java/appeng/api/config/RedstoneMode.java | 6 +- .../appeng/api/config/RelativeDirection.java | 6 +- .../appeng/api/config/SchedulingMode.java | 6 +- .../java/appeng/api/config/SearchBoxMode.java | 6 +- .../api/config/SecurityPermissions.java | 70 +- src/api/java/appeng/api/config/Settings.java | 73 +- src/api/java/appeng/api/config/SortDir.java | 6 +- src/api/java/appeng/api/config/SortOrder.java | 6 +- .../java/appeng/api/config/StorageFilter.java | 8 +- .../java/appeng/api/config/TerminalStyle.java | 10 +- .../java/appeng/api/config/TunnelType.java | 24 +- src/api/java/appeng/api/config/Upgrades.java | 162 +- src/api/java/appeng/api/config/ViewItems.java | 6 +- src/api/java/appeng/api/config/YesNo.java | 6 +- .../java/appeng/api/definitions/Blocks.java | 101 +- .../api/definitions/IBlockDefinition.java | 41 +- .../java/appeng/api/definitions/IBlocks.java | 176 +- .../definitions/IComparableDefinition.java | 44 +- .../appeng/api/definitions/IDefinitions.java | 36 +- .../api/definitions/IItemDefinition.java | 29 +- .../java/appeng/api/definitions/IItems.java | 81 +- .../appeng/api/definitions/IMaterials.java | 112 +- .../java/appeng/api/definitions/IParts.java | 81 +- .../api/definitions/ITileDefinition.java | 13 +- .../java/appeng/api/definitions/Items.java | 79 +- .../appeng/api/definitions/Materials.java | 113 +- .../java/appeng/api/definitions/Parts.java | 75 +- .../api/events/LocatableEventAnnounce.java | 28 +- .../api/exceptions/AppEngException.java | 14 +- .../exceptions/CoreInaccessibleException.java | 11 +- .../ExistingConnectionException.java | 33 +- .../api/exceptions/FailedConnection.java | 19 +- .../api/exceptions/MissingDefinition.java | 11 +- .../exceptions/MissingIngredientError.java | 14 +- .../api/exceptions/ModNotInstalled.java | 14 +- .../NullNodeConnectionException.java | 25 +- .../appeng/api/exceptions/RecipeError.java | 14 +- .../api/exceptions/RegistrationError.java | 14 +- .../SecurityConnectionException.java | 24 +- .../appeng/api/features/IGrinderEntry.java | 154 +- .../appeng/api/features/IGrinderRegistry.java | 104 +- .../appeng/api/features/IInscriberRecipe.java | 79 +- .../api/features/IInscriberRecipeBuilder.java | 125 +- .../api/features/IInscriberRegistry.java | 102 +- .../appeng/api/features/IItemComparison.java | 8 +- .../api/features/IItemComparisonProvider.java | 36 +- .../java/appeng/api/features/ILocatable.java | 18 +- .../api/features/ILocatableRegistry.java | 38 +- .../features/IMatterCannonAmmoRegistry.java | 35 +- .../api/features/INetworkEncodable.java | 36 +- .../api/features/IP2PTunnelRegistry.java | 40 +- .../appeng/api/features/IPlayerRegistry.java | 45 +- .../api/features/IRecipeHandlerRegistry.java | 80 +- .../api/features/IRegistryContainer.java | 121 +- .../features/ISpecialComparisonRegistry.java | 32 +- .../api/features/IWirelessTermHandler.java | 63 +- .../api/features/IWirelessTermRegistry.java | 50 +- .../java/appeng/api/features/IWorldGen.java | 21 +- .../api/features/InscriberProcessType.java | 20 +- .../implementations/ICraftingPatternItem.java | 22 +- .../implementations/IPowerChannelState.java | 21 +- .../api/implementations/IUpgradeableHost.java | 26 +- .../api/implementations/TransitionResult.java | 17 +- .../implementations/guiobjects/IGuiItem.java | 8 +- .../guiobjects/IGuiItemObject.java | 8 +- .../guiobjects/INetworkTool.java | 8 +- .../guiobjects/IPortableCell.java | 8 +- .../items/IAEItemPowerStorage.java | 66 +- .../api/implementations/items/IAEWrench.java | 26 +- .../implementations/items/IBiometricCard.java | 93 +- .../items/IGrowableCrystal.java | 10 +- .../api/implementations/items/IItemGroup.java | 22 +- .../implementations/items/IMemoryCard.java | 72 +- .../items/ISpatialStorageCell.java | 102 +- .../implementations/items/IStorageCell.java | 134 +- .../items/IStorageComponent.java | 38 +- .../implementations/items/IUpgradeModule.java | 16 +- .../items/MemoryCardMessages.java | 9 +- .../api/implementations/parts/IPartCable.java | 80 +- .../implementations/parts/IPartMonitor.java | 16 +- .../parts/IPartStorageMonitor.java | 28 +- .../implementations/tiles/IChestOrDrive.java | 59 +- .../implementations/tiles/IColorableTile.java | 10 +- .../tiles/ICraftingMachine.java | 43 +- .../api/implementations/tiles/ICrankable.java | 34 +- .../tiles/ICrystalGrowthAccelerator.java | 7 +- .../api/implementations/tiles/IMEChest.java | 7 +- .../tiles/ISegmentedInventory.java | 23 +- .../tiles/ITileStorageMonitorable.java | 11 +- .../tiles/IViewCellStorage.java | 18 +- .../tiles/IWirelessAccessPoint.java | 38 +- .../api/integration/IBeeComparison.java | 14 +- .../appeng/api/movable/IMovableHandler.java | 72 +- .../appeng/api/movable/IMovableRegistry.java | 150 +- .../java/appeng/api/movable/IMovableTile.java | 27 +- .../java/appeng/api/networking/GridFlags.java | 67 +- .../api/networking/GridNotification.java | 12 +- src/api/java/appeng/api/networking/IGrid.java | 101 +- .../appeng/api/networking/IGridBlock.java | 133 +- .../appeng/api/networking/IGridCache.java | 103 +- .../api/networking/IGridCacheRegistry.java | 36 +- .../api/networking/IGridConnection.java | 82 +- .../networking/IGridConnectionVisitor.java | 17 +- .../java/appeng/api/networking/IGridHost.java | 50 +- .../api/networking/IGridMultiblock.java | 27 +- .../java/appeng/api/networking/IGridNode.java | 209 +- .../appeng/api/networking/IGridStorage.java | 22 +- .../appeng/api/networking/IGridVisitor.java | 24 +- .../appeng/api/networking/IMachineSet.java | 14 +- .../networking/crafting/CraftingItemList.java | 6 +- .../api/networking/crafting/ICraftingCPU.java | 46 +- .../crafting/ICraftingCallback.java | 17 +- .../networking/crafting/ICraftingGrid.java | 136 +- .../api/networking/crafting/ICraftingJob.java | 47 +- .../networking/crafting/ICraftingLink.java | 59 +- .../networking/crafting/ICraftingMedium.java | 36 +- .../crafting/ICraftingPatternDetails.java | 117 +- .../crafting/ICraftingProvider.java | 22 +- .../crafting/ICraftingProviderHelper.java | 22 +- .../crafting/ICraftingRequester.java | 51 +- .../networking/crafting/ICraftingWatcher.java | 9 +- .../crafting/ICraftingWatcherHost.java | 35 +- .../networking/energy/IAEPowerStorage.java | 69 +- .../api/networking/energy/IEnergyGrid.java | 129 +- .../energy/IEnergyGridProvider.java | 31 +- .../api/networking/energy/IEnergySource.java | 23 +- .../api/networking/energy/IEnergyWatcher.java | 7 +- .../networking/energy/IEnergyWatcherHost.java | 32 +- .../events/MENetworkBootingStatusChange.java | 7 +- .../events/MENetworkCellArrayUpdate.java | 6 +- .../events/MENetworkChannelChanged.java | 19 +- .../events/MENetworkChannelsChanged.java | 7 +- .../events/MENetworkControllerChange.java | 6 +- .../events/MENetworkCraftingCpuChange.java | 15 +- .../MENetworkCraftingPatternChange.java | 19 +- .../api/networking/events/MENetworkEvent.java | 74 +- .../events/MENetworkEventSubscribe.java | 13 +- .../MENetworkPostCacheConstruction.java | 6 +- .../events/MENetworkPowerIdleChange.java | 15 +- .../events/MENetworkPowerStatusChange.java | 7 +- .../events/MENetworkPowerStorage.java | 40 +- .../events/MENetworkSecurityChange.java | 6 +- .../events/MENetworkSpatialEvent.java | 26 +- .../events/MENetworkStorageEvent.java | 29 +- .../networking/pathing/ControllerState.java | 36 +- .../api/networking/pathing/IPathingGrid.java | 32 +- .../networking/security/BaseActionSource.java | 19 +- .../api/networking/security/IActionHost.java | 24 +- .../networking/security/ISecurityGrid.java | 55 +- .../security/ISecurityProvider.java | 49 +- .../security/ISecurityRegistry.java | 22 +- .../networking/security/MachineSource.java | 23 +- .../api/networking/security/PlayerSource.java | 28 +- .../api/networking/spatial/ISpatialCache.java | 55 +- .../api/networking/storage/IBaseMonitor.java | 23 +- .../api/networking/storage/IStackWatcher.java | 9 +- .../networking/storage/IStackWatcherHost.java | 47 +- .../api/networking/storage/IStorageGrid.java | 55 +- .../api/networking/ticking/IGridTickable.java | 83 +- .../api/networking/ticking/ITickManager.java | 51 +- .../ticking/TickRateModulation.java | 52 +- .../networking/ticking/TickingRequest.java | 72 +- src/api/java/appeng/api/package-info.java | 8 +- src/api/java/appeng/api/parts/BusSupport.java | 10 +- .../appeng/api/parts/CableRenderMode.java | 21 +- .../java/appeng/api/parts/IAlphaPassItem.java | 21 +- .../java/appeng/api/parts/IBoxProvider.java | 17 +- .../appeng/api/parts/IFacadeContainer.java | 106 +- .../java/appeng/api/parts/IFacadePart.java | 107 +- src/api/java/appeng/api/parts/IPart.java | 438 +- .../api/parts/IPartCollisionHelper.java | 65 +- .../java/appeng/api/parts/IPartHelper.java | 104 +- src/api/java/appeng/api/parts/IPartHost.java | 234 +- src/api/java/appeng/api/parts/IPartItem.java | 37 +- .../appeng/api/parts/IPartRenderHelper.java | 313 +- .../appeng/api/parts/ISimplifiedBundle.java | 6 +- src/api/java/appeng/api/parts/LayerBase.java | 73 +- src/api/java/appeng/api/parts/LayerFlags.java | 6 +- .../java/appeng/api/parts/PartItemStack.java | 14 +- .../java/appeng/api/parts/SelectedPart.java | 63 +- .../appeng/api/recipes/ICraftHandler.java | 39 +- .../java/appeng/api/recipes/IIngredient.java | 102 +- .../appeng/api/recipes/IRecipeHandler.java | 27 +- .../appeng/api/recipes/IRecipeLoader.java | 19 +- .../appeng/api/recipes/ISubItemResolver.java | 16 +- .../appeng/api/recipes/ResolverResult.java | 36 +- .../appeng/api/recipes/ResolverResultSet.java | 21 +- .../appeng/api/storage/ICellContainer.java | 22 +- .../java/appeng/api/storage/ICellHandler.java | 160 +- .../appeng/api/storage/ICellInventory.java | 142 +- .../api/storage/ICellInventoryHandler.java | 20 +- .../appeng/api/storage/ICellProvider.java | 41 +- .../appeng/api/storage/ICellRegistry.java | 76 +- .../api/storage/ICellWorkbenchItem.java | 66 +- .../api/storage/IExternalStorageHandler.java | 56 +- .../api/storage/IExternalStorageRegistry.java | 42 +- .../java/appeng/api/storage/IMEInventory.java | 77 +- .../api/storage/IMEInventoryHandler.java | 102 +- .../java/appeng/api/storage/IMEMonitor.java | 32 +- .../storage/IMEMonitorHandlerReceiver.java | 45 +- .../appeng/api/storage/ISaveProvider.java | 7 +- .../appeng/api/storage/IStorageHelper.java | 140 +- .../api/storage/IStorageMonitorable.java | 28 +- .../appeng/api/storage/ITerminalHost.java | 7 +- .../appeng/api/storage/MEMonitorHandler.java | 290 +- .../appeng/api/storage/StorageChannel.java | 48 +- .../api/storage/data/IAEFluidStack.java | 58 +- .../appeng/api/storage/data/IAEItemStack.java | 126 +- .../appeng/api/storage/data/IAEStack.java | 290 +- .../api/storage/data/IAETagCompound.java | 39 +- .../api/storage/data/IItemContainer.java | 52 +- .../appeng/api/storage/data/IItemList.java | 82 +- src/api/java/appeng/api/util/AECableType.java | 44 +- src/api/java/appeng/api/util/AEColor.java | 135 +- .../api/util/AEColoredItemDefinition.java | 64 +- .../appeng/api/util/AEItemDefinition.java | 106 +- .../appeng/api/util/DimensionalCoord.java | 100 +- src/api/java/appeng/api/util/ICommonTile.java | 30 +- .../java/appeng/api/util/IConfigManager.java | 88 +- .../appeng/api/util/IConfigurableObject.java | 13 +- .../appeng/api/util/INetworkToolAgent.java | 11 +- src/api/java/appeng/api/util/IOrientable.java | 49 +- .../appeng/api/util/IOrientableBlock.java | 30 +- .../appeng/api/util/IReadOnlyCollection.java | 29 +- src/api/java/appeng/api/util/WorldCoord.java | 216 +- src/main/java/appeng/block/AEBaseBlock.java | 1123 ++--- .../java/appeng/block/AEBaseItemBlock.java | 305 +- .../block/AEBaseItemBlockChargeable.java | 185 +- .../appeng/block/AEBaseItemBlockSlab.java | 18 +- .../java/appeng/block/AEBaseSlabBlock.java | 177 +- .../java/appeng/block/AEBaseStairBlock.java | 43 +- .../java/appeng/block/AEBaseTileBlock.java | 517 ++- .../java/appeng/block/AEDecorativeBlock.java | 31 +- .../block/crafting/BlockCraftingMonitor.java | 77 +- .../block/crafting/BlockCraftingStorage.java | 118 +- .../block/crafting/BlockCraftingUnit.java | 217 +- .../crafting/BlockMolecularAssembler.java | 102 +- .../block/crafting/ItemCraftingStorage.java | 40 +- .../appeng/block/grindstone/BlockCrank.java | 223 +- .../appeng/block/grindstone/BlockGrinder.java | 53 +- .../block/legacy/BlockCraftMonitor.java | 32 +- .../block/legacy/BlockCraftTerminal.java | 31 +- .../block/legacy/BlockLegacyController.java | 27 +- .../appeng/block/misc/BlockCellWorkbench.java | 66 +- .../java/appeng/block/misc/BlockCharger.java | 282 +- .../appeng/block/misc/BlockCondenser.java | 66 +- .../appeng/block/misc/BlockInscriber.java | 78 +- .../appeng/block/misc/BlockInterface.java | 98 +- .../appeng/block/misc/BlockLightDetector.java | 248 +- .../java/appeng/block/misc/BlockPaint.java | 169 +- .../misc/BlockQuartzGrowthAccelerator.java | 214 +- .../appeng/block/misc/BlockQuartzTorch.java | 238 +- .../java/appeng/block/misc/BlockSecurity.java | 76 +- .../appeng/block/misc/BlockSkyCompass.java | 285 +- .../java/appeng/block/misc/BlockTinyTNT.java | 275 +- .../block/misc/BlockVibrationChamber.java | 167 +- .../block/networking/BlockCableBus.java | 982 +++-- .../block/networking/BlockController.java | 50 +- .../networking/BlockCreativeEnergyCell.java | 19 +- .../networking/BlockDenseEnergyCell.java | 72 +- .../block/networking/BlockEnergyAcceptor.java | 19 +- .../block/networking/BlockEnergyCell.java | 117 +- .../appeng/block/qnb/BlockQuantumBase.java | 80 +- .../block/qnb/BlockQuantumLinkChamber.java | 136 +- .../appeng/block/qnb/BlockQuantumRing.java | 88 +- .../java/appeng/block/solids/BlockFluix.java | 16 +- .../java/appeng/block/solids/BlockQuartz.java | 17 +- .../block/solids/BlockQuartzChiseled.java | 17 +- .../appeng/block/solids/BlockQuartzGlass.java | 56 +- .../appeng/block/solids/BlockQuartzLamp.java | 58 +- .../block/solids/BlockQuartzPillar.java | 36 +- .../appeng/block/solids/BlockSkyStone.java | 278 +- .../java/appeng/block/solids/OreQuartz.java | 226 +- .../appeng/block/solids/OreQuartzCharged.java | 148 +- .../block/spatial/BlockMatrixFrame.java | 136 +- .../block/spatial/BlockSpatialIOPort.java | 84 +- .../block/spatial/BlockSpatialPylon.java | 67 +- .../block/stair/ChiseledQuartzStairBlock.java | 14 +- .../appeng/block/stair/FluixStairBlock.java | 14 +- .../block/stair/QuartzPillarStairBlock.java | 14 +- .../appeng/block/stair/QuartzStairBlock.java | 14 +- .../block/stair/SkyStoneBlockStairBlock.java | 14 +- .../block/stair/SkyStoneBrickStairBlock.java | 14 +- .../stair/SkyStoneSmallBrickStairBlock.java | 14 +- .../block/stair/SkyStoneStairBlock.java | 14 +- .../java/appeng/block/storage/BlockChest.java | 96 +- .../java/appeng/block/storage/BlockDrive.java | 74 +- .../appeng/block/storage/BlockIOPort.java | 81 +- .../appeng/block/storage/BlockSkyChest.java | 235 +- src/main/java/appeng/client/ClientHelper.java | 648 +-- src/main/java/appeng/client/EffectType.java | 6 +- .../java/appeng/client/gui/AEBaseGui.java | 1756 ++++---- .../java/appeng/client/gui/AEBaseMEGui.java | 205 +- src/main/java/appeng/client/gui/GuiNull.java | 28 +- .../appeng/client/gui/config/AEConfigGui.java | 65 +- .../client/gui/config/AEConfigGuiFactory.java | 43 +- .../gui/implementations/GuiCellWorkbench.java | 332 +- .../client/gui/implementations/GuiChest.java | 82 +- .../gui/implementations/GuiCondenser.java | 108 +- .../gui/implementations/GuiCraftAmount.java | 450 +- .../gui/implementations/GuiCraftConfirm.java | 1048 +++-- .../gui/implementations/GuiCraftingCPU.java | 886 ++-- .../implementations/GuiCraftingStatus.java | 228 +- .../gui/implementations/GuiCraftingTerm.java | 106 +- .../client/gui/implementations/GuiDrive.java | 82 +- .../implementations/GuiFormationPlane.java | 117 +- .../gui/implementations/GuiGrinder.java | 43 +- .../client/gui/implementations/GuiIOPort.java | 153 +- .../gui/implementations/GuiInscriber.java | 106 +- .../gui/implementations/GuiInterface.java | 146 +- .../implementations/GuiInterfaceTerminal.java | 588 ++- .../gui/implementations/GuiLevelEmitter.java | 422 +- .../client/gui/implementations/GuiMAC.java | 98 +- .../gui/implementations/GuiMEMonitorable.java | 1005 ++--- .../implementations/GuiMEPortableCell.java | 31 +- .../gui/implementations/GuiNetworkStatus.java | 458 +- .../gui/implementations/GuiNetworkTool.java | 105 +- .../gui/implementations/GuiPatternTerm.java | 263 +- .../gui/implementations/GuiPriority.java | 414 +- .../client/gui/implementations/GuiQNB.java | 43 +- .../gui/implementations/GuiQuartzKnife.java | 115 +- .../gui/implementations/GuiSecurity.java | 224 +- .../gui/implementations/GuiSkyChest.java | 52 +- .../gui/implementations/GuiSpatialIOPort.java | 121 +- .../gui/implementations/GuiStorageBus.java | 189 +- .../gui/implementations/GuiUpgradeable.java | 281 +- .../implementations/GuiVibrationChamber.java | 93 +- .../gui/implementations/GuiWireless.java | 107 +- .../gui/implementations/GuiWirelessTerm.java | 24 +- .../client/gui/widgets/GuiImgButton.java | 1117 +++-- .../client/gui/widgets/GuiNumberBox.java | 63 +- .../client/gui/widgets/GuiProgressBar.java | 204 +- .../client/gui/widgets/GuiScrollbar.java | 201 +- .../client/gui/widgets/GuiTabButton.java | 231 +- .../client/gui/widgets/GuiToggleButton.java | 202 +- .../client/gui/widgets/IScrollSource.java | 7 +- .../client/gui/widgets/ISortSource.java | 30 +- .../appeng/client/gui/widgets/ITooltip.java | 73 +- .../client/gui/widgets/MEGuiTextField.java | 102 +- .../appeng/client/me/ClientDCInternalInv.java | 70 +- .../java/appeng/client/me/InternalSlotME.java | 64 +- src/main/java/appeng/client/me/ItemRepo.java | 414 +- .../appeng/client/me/SlotDisconnected.java | 127 +- src/main/java/appeng/client/me/SlotME.java | 123 +- .../client/render/AppEngRenderItem.java | 217 +- .../appeng/client/render/BaseBlockRender.java | 1751 ++++---- .../appeng/client/render/BlockRenderInfo.java | 229 +- .../appeng/client/render/BusRenderHelper.java | 1250 +++--- .../appeng/client/render/BusRenderer.java | 235 +- .../client/render/CableRenderHelper.java | 429 +- .../appeng/client/render/ItemRenderer.java | 70 +- .../client/render/RenderBlocksWorkaround.java | 1526 +++---- .../client/render/SpatialSkyRender.java | 252 +- .../appeng/client/render/TESRWrapper.java | 90 +- .../appeng/client/render/WorldRender.java | 139 +- .../render/blocks/RenderBlockAssembler.java | 536 ++- .../render/blocks/RenderBlockCharger.java | 239 +- .../render/blocks/RenderBlockController.java | 274 +- .../render/blocks/RenderBlockCraftingCPU.java | 692 +-- .../blocks/RenderBlockCraftingCPUMonitor.java | 232 +- .../render/blocks/RenderBlockCrank.java | 150 +- .../render/blocks/RenderBlockEnergyCube.java | 79 +- .../render/blocks/RenderBlockInscriber.java | 548 ++- .../render/blocks/RenderBlockInterface.java | 53 +- .../render/blocks/RenderBlockPaint.java | 386 +- .../blocks/RenderBlockQuartzAccelerator.java | 58 +- .../render/blocks/RenderBlockSkyChest.java | 177 +- .../render/blocks/RenderBlockSkyCompass.java | 339 +- .../render/blocks/RenderBlockWireless.java | 539 ++- .../client/render/blocks/RenderDrive.java | 885 ++-- .../client/render/blocks/RenderMEChest.java | 268 +- .../client/render/blocks/RenderNull.java | 42 +- .../client/render/blocks/RenderQNB.java | 438 +- .../render/blocks/RenderQuartzGlass.java | 446 +- .../client/render/blocks/RenderQuartzOre.java | 66 +- .../render/blocks/RenderQuartzTorch.java | 456 +- .../render/blocks/RenderSpatialPylon.java | 355 +- .../client/render/blocks/RenderTinyTNT.java | 54 +- .../render/blocks/RendererCableBus.java | 87 +- .../render/blocks/RendererSecurity.java | 127 +- .../client/render/effects/AssemblerFX.java | 120 +- .../client/render/effects/ChargedOreFX.java | 43 +- .../client/render/effects/CraftingFx.java | 186 +- .../client/render/effects/EnergyFx.java | 172 +- .../client/render/effects/LightningArcFX.java | 82 +- .../client/render/effects/LightningFX.java | 368 +- .../client/render/effects/MatterCannonFX.java | 148 +- .../client/render/effects/VibrantFX.java | 94 +- .../items/ItemEncodedPatternRenderer.java | 78 +- .../client/render/items/PaintBallRender.java | 181 +- .../render/items/ToolBiometricCardRender.java | 210 +- .../items/ToolColorApplicatorRender.java | 212 +- .../client/render/model/ModelCompass.java | 154 +- .../client/texture/CableBusTextures.java | 198 +- .../client/texture/ExtraBlockTextures.java | 175 +- .../client/texture/ExtraItemTextures.java | 65 +- .../appeng/client/texture/FlippableIcon.java | 219 +- .../java/appeng/client/texture/FullIcon.java | 133 +- .../appeng/client/texture/MissingIcon.java | 109 +- .../appeng/client/texture/OffsetIcon.java | 141 +- .../appeng/client/texture/TaughtIcon.java | 165 +- .../client/texture/TmpFlippableIcon.java | 60 +- .../appeng/container/AEBaseContainer.java | 2397 +++++------ .../java/appeng/container/ContainerNull.java | 15 +- .../container/ContainerOpenContext.java | 111 +- .../appeng/container/guisync/GuiSync.java | 12 +- .../appeng/container/guisync/SyncData.java | 281 +- .../ContainerCellWorkbench.java | 510 ++- .../implementations/ContainerChest.java | 28 +- .../implementations/ContainerCondenser.java | 109 +- .../implementations/ContainerCraftAmount.java | 81 +- .../ContainerCraftConfirm.java | 791 ++-- .../implementations/ContainerCraftingCPU.java | 393 +- .../ContainerCraftingStatus.java | 224 +- .../ContainerCraftingTerm.java | 136 +- .../implementations/ContainerDrive.java | 34 +- .../ContainerFormationPlane.java | 190 +- .../implementations/ContainerGrinder.java | 50 +- .../implementations/ContainerIOPort.java | 196 +- .../implementations/ContainerInscriber.java | 308 +- .../implementations/ContainerInterface.java | 134 +- .../ContainerInterfaceTerminal.java | 633 ++- .../ContainerLevelEmitter.java | 243 +- .../implementations/ContainerMAC.java | 228 +- .../ContainerMEMonitorable.java | 621 ++- .../ContainerMEPortableCell.java | 132 +- .../ContainerNetworkStatus.java | 233 +- .../implementations/ContainerNetworkTool.java | 120 +- .../implementations/ContainerPatternTerm.java | 997 +++-- .../implementations/ContainerPriority.java | 89 +- .../implementations/ContainerQNB.java | 25 +- .../implementations/ContainerQuartzKnife.java | 319 +- .../implementations/ContainerSecurity.java | 252 +- .../implementations/ContainerSkyChest.java | 46 +- .../ContainerSpatialIOPort.java | 159 +- .../implementations/ContainerStorageBus.java | 281 +- .../implementations/ContainerUpgradeable.java | 477 ++- .../ContainerVibrationChamber.java | 90 +- .../implementations/ContainerWireless.java | 85 +- .../ContainerWirelessTerm.java | 51 +- .../implementations/CraftingCPURecord.java | 77 +- .../interfaces/IInventorySlotAware.java | 70 +- .../interfaces/IProgressProvider.java | 97 +- .../container/slot/AppEngCraftingSlot.java | 272 +- .../appeng/container/slot/AppEngSlot.java | 328 +- .../container/slot/IOptionalSlotHost.java | 7 +- .../java/appeng/container/slot/NullSlot.java | 106 +- .../container/slot/OptionalSlotFake.java | 112 +- .../slot/OptionalSlotFakeTypeOnly.java | 51 +- .../container/slot/OptionalSlotNormal.java | 44 +- .../slot/OptionalSlotRestrictedInput.java | 46 +- .../container/slot/QuartzKnifeOutput.java | 15 +- .../container/slot/SlotCraftingMatrix.java | 67 +- .../container/slot/SlotCraftingTerm.java | 419 +- .../appeng/container/slot/SlotDisabled.java | 33 +- .../java/appeng/container/slot/SlotFake.java | 64 +- .../container/slot/SlotFakeBlacklist.java | 49 +- .../slot/SlotFakeCraftingMatrix.java | 15 +- .../container/slot/SlotFakeTypeOnly.java | 44 +- .../container/slot/SlotInaccessible.java | 69 +- .../container/slot/SlotInaccessibleHD.java | 15 +- .../appeng/container/slot/SlotMACPattern.java | 32 +- .../appeng/container/slot/SlotNormal.java | 15 +- .../appeng/container/slot/SlotOutput.java | 26 +- .../container/slot/SlotPatternOutputs.java | 40 +- .../container/slot/SlotPatternTerm.java | 84 +- .../container/slot/SlotPlayerHotBar.java | 17 +- .../appeng/container/slot/SlotPlayerInv.java | 20 +- .../container/slot/SlotRestrictedInput.java | 450 +- src/main/java/appeng/core/AEConfig.java | 1048 ++--- src/main/java/appeng/core/AELog.java | 615 ++- src/main/java/appeng/core/Api.java | 146 +- src/main/java/appeng/core/ApiDefinitions.java | 87 +- src/main/java/appeng/core/AppEng.java | 327 +- src/main/java/appeng/core/CommonHelper.java | 60 +- src/main/java/appeng/core/CreativeTab.java | 75 +- .../java/appeng/core/CreativeTabFacade.java | 50 +- src/main/java/appeng/core/FacadeConfig.java | 94 +- .../appeng/core/FeatureHandlerRegistry.java | 23 +- .../java/appeng/core/FeatureRegistry.java | 23 +- src/main/java/appeng/core/IMCHandler.java | 111 +- src/main/java/appeng/core/RecipeLoader.java | 144 +- src/main/java/appeng/core/Registration.java | 1312 +++--- src/main/java/appeng/core/api/ApiPart.java | 503 ++- src/main/java/appeng/core/api/ApiStorage.java | 100 +- .../appeng/core/api/ICraftingTerminal.java | 2 - .../java/appeng/core/api/IIMCProcessor.java | 7 +- .../core/api/definitions/ApiBlocks.java | 1177 +++--- .../appeng/core/api/definitions/ApiItems.java | 599 +-- .../core/api/definitions/ApiMaterials.java | 1018 ++--- .../appeng/core/api/definitions/ApiParts.java | 571 +-- .../definitions/DefinitionConstructor.java | 117 +- .../core/api/imc/IMCBlackListSpatial.java | 34 +- .../java/appeng/core/api/imc/IMCGrinder.java | 66 +- .../appeng/core/api/imc/IMCMatterCannon.java | 30 +- .../appeng/core/api/imc/IMCP2PAttunement.java | 67 +- .../java/appeng/core/api/imc/IMCSpatial.java | 34 +- .../core/crash/BaseCrashEnhancement.java | 36 +- .../java/appeng/core/crash/CrashInfo.java | 6 +- .../crash/IntegrationCrashEnhancement.java | 12 +- .../core/crash/ModCrashEnhancement.java | 23 +- .../core/features/AEBlockFeatureHandler.java | 81 +- .../features/AECableBusFeatureHandler.java | 97 +- .../java/appeng/core/features/AEFeature.java | 282 +- .../features/AETileBlockFeatureHandler.java | 101 +- .../appeng/core/features/ActivityState.java | 26 +- .../appeng/core/features/BlockDefinition.java | 226 +- .../appeng/core/features/BlockStackSrc.java | 73 +- .../core/features/ColoredItemDefinition.java | 106 +- .../core/features/DamagedItemDefinition.java | 126 +- .../core/features/DefinitionConverter.java | 217 +- .../core/features/FeatureNameExtractor.java | 83 +- .../core/features/FeaturedActiveChecker.java | 35 +- .../java/appeng/core/features/IAEFeature.java | 8 +- .../appeng/core/features/IFeatureHandler.java | 11 +- .../java/appeng/core/features/IStackSrc.java | 14 +- .../appeng/core/features/ItemDefinition.java | 101 +- .../core/features/ItemFeatureHandler.java | 100 +- .../appeng/core/features/ItemStackSrc.java | 73 +- .../core/features/MaterialStackSrc.java | 52 +- .../appeng/core/features/NameResolver.java | 78 +- .../features/SlabBlockFeatureHandler.java | 84 +- .../features/StairBlockFeatureHandler.java | 75 +- .../appeng/core/features/TileDefinition.java | 62 +- .../features/WrappedDamageItemDefinition.java | 146 +- .../features/registries/CellRegistry.java | 119 +- .../registries/ExternalStorageRegistry.java | 63 +- .../registries/GridCacheRegistry.java | 110 +- .../registries/GrinderRecipeManager.java | 459 +- .../registries/InscriberRegistry.java | 254 +- .../registries/LocatableRegistry.java | 73 +- .../registries/MatterCannonAmmoRegistry.java | 216 +- .../registries/MovableTileRegistry.java | 212 +- .../registries/P2PTunnelRegistry.java | 267 +- .../features/registries/PlayerRegistry.java | 44 +- .../registries/RecipeHandlerRegistry.java | 118 +- .../registries/RegistryContainer.java | 158 +- .../registries/SpecialComparisonRegistry.java | 51 +- .../features/registries/WirelessRegistry.java | 139 +- .../features/registries/WorldGenRegistry.java | 139 +- .../entries/AppEngGrinderRecipe.java | 191 +- .../registries/entries/BasicCellHandler.java | 105 +- .../entries/CreativeCellHandler.java | 95 +- .../registries/entries/ExternalIInv.java | 43 +- .../entries/InscriberInscribeRecipe.java | 23 +- .../registries/entries/InscriberRecipe.java | 185 +- .../core/localization/ButtonToolTips.java | 153 +- .../appeng/core/localization/GuiText.java | 211 +- .../core/localization/PlayerMessages.java | 41 +- .../appeng/core/localization/WailaText.java | 54 +- .../java/appeng/core/settings/TickRates.java | 90 +- .../stats/AchievementCraftingHandler.java | 71 +- .../core/stats/AchievementHierarchy.java | 41 +- .../core/stats/AchievementPickupHandler.java | 51 +- .../appeng/core/stats/AchievementType.java | 9 +- .../java/appeng/core/stats/Achievements.java | 303 +- .../core/stats/PlayerDifferentiator.java | 35 +- .../core/stats/PlayerStatsRegistration.java | 141 +- src/main/java/appeng/core/stats/Stats.java | 51 +- .../java/appeng/core/sync/AppEngPacket.java | 77 +- .../core/sync/AppEngPacketHandlerBase.java | 132 +- src/main/java/appeng/core/sync/GuiBridge.java | 1057 ++--- .../java/appeng/core/sync/GuiHostType.java | 22 +- .../network/AppEngClientPacketHandler.java | 58 +- .../network/AppEngServerPacketHandler.java | 56 +- .../core/sync/network/INetworkInfo.java | 6 +- .../core/sync/network/IPacketHandler.java | 8 +- .../core/sync/network/NetworkHandler.java | 165 +- .../packets/PacketAssemblerAnimation.java | 92 +- .../appeng/core/sync/packets/PacketClick.java | 139 +- .../sync/packets/PacketCompassRequest.java | 89 +- .../sync/packets/PacketCompassResponse.java | 81 +- .../sync/packets/PacketCompressedNBT.java | 116 +- .../core/sync/packets/PacketConfigButton.java | 78 +- .../core/sync/packets/PacketCraftRequest.java | 147 +- .../sync/packets/PacketInventoryAction.java | 224 +- .../core/sync/packets/PacketLightning.java | 86 +- .../sync/packets/PacketMEInventoryUpdate.java | 276 +- .../core/sync/packets/PacketMatterCannon.java | 131 +- .../sync/packets/PacketMockExplosion.java | 65 +- .../core/sync/packets/PacketMultiPart.java | 47 +- .../core/sync/packets/PacketNEIRecipe.java | 398 +- .../packets/PacketNewStorageDimension.java | 60 +- .../sync/packets/PacketPaintedEntity.java | 60 +- .../sync/packets/PacketPartPlacement.java | 87 +- .../core/sync/packets/PacketPartialItem.java | 82 +- .../core/sync/packets/PacketPatternSlot.java | 125 +- .../core/sync/packets/PacketProgressBar.java | 78 +- .../core/sync/packets/PacketSwapSlots.java | 55 +- .../core/sync/packets/PacketSwitchGuis.java | 81 +- .../sync/packets/PacketTransitionEffect.java | 142 +- .../core/sync/packets/PacketValueConfig.java | 351 +- .../appeng/core/worlddata/CompassData.java | 44 +- .../appeng/core/worlddata/DimensionData.java | 202 +- .../core/worlddata/IOnWorldStartable.java | 6 +- .../core/worlddata/IOnWorldStoppable.java | 6 +- .../core/worlddata/IWorldCompassData.java | 7 +- .../appeng/core/worlddata/IWorldData.java | 29 +- .../core/worlddata/IWorldDimensionData.java | 15 +- .../core/worlddata/IWorldGridStorageData.java | 21 +- .../core/worlddata/IWorldPlayerData.java | 13 +- .../core/worlddata/IWorldPlayerMapping.java | 43 +- .../core/worlddata/IWorldSpawnData.java | 15 +- .../core/worlddata/MeteorDataNameEncoder.java | 98 +- .../appeng/core/worlddata/PlayerData.java | 149 +- .../appeng/core/worlddata/PlayerMapping.java | 56 +- .../worlddata/PlayerMappingsInitializer.java | 106 +- .../java/appeng/core/worlddata/SpawnData.java | 277 +- .../appeng/core/worlddata/StorageData.java | 218 +- .../java/appeng/core/worlddata/WorldData.java | 277 +- .../appeng/crafting/CraftBranchFailure.java | 21 +- .../crafting/CraftingCalculationFailure.java | 21 +- .../java/appeng/crafting/CraftingJob.java | 575 ++- .../java/appeng/crafting/CraftingLink.java | 277 +- .../appeng/crafting/CraftingLinkNexus.java | 220 +- .../appeng/crafting/CraftingTreeNode.java | 580 ++- .../appeng/crafting/CraftingTreeProcess.java | 482 ++- .../java/appeng/crafting/CraftingWatcher.java | 272 +- .../appeng/crafting/MECraftingInventory.java | 500 +-- .../java/appeng/debug/BlockChunkloader.java | 41 +- .../java/appeng/debug/BlockCubeGenerator.java | 58 +- src/main/java/appeng/debug/BlockItemGen.java | 30 +- .../java/appeng/debug/BlockPhantomNode.java | 53 +- .../java/appeng/debug/TileChunkLoader.java | 93 +- .../java/appeng/debug/TileCubeGenerator.java | 150 +- src/main/java/appeng/debug/TileItemGen.java | 179 +- .../java/appeng/debug/TilePhantomNode.java | 57 +- src/main/java/appeng/debug/ToolDebugCard.java | 309 +- src/main/java/appeng/debug/ToolEraser.java | 144 +- .../appeng/debug/ToolMeteoritePlacer.java | 67 +- .../java/appeng/debug/ToolReplicatorCard.java | 264 +- .../java/appeng/entity/AEBaseEntityItem.java | 37 +- .../appeng/entity/EntityChargedQuartz.java | 203 +- .../appeng/entity/EntityFloatingItem.java | 84 +- .../appeng/entity/EntityGrowingCrystal.java | 245 +- src/main/java/appeng/entity/EntityIds.java | 52 +- .../java/appeng/entity/EntitySingularity.java | 199 +- .../appeng/entity/EntityTinyTNTPrimed.java | 287 +- .../appeng/entity/RenderFloatingItem.java | 65 +- .../appeng/entity/RenderTinyTNTPrimed.java | 125 +- .../java/appeng/facade/FacadeContainer.java | 358 +- src/main/java/appeng/facade/FacadePart.java | 1097 ++--- src/main/java/appeng/facade/IFacadeItem.java | 14 +- src/main/java/appeng/fmp/CableBusPart.java | 1184 +++--- src/main/java/appeng/fmp/FMPEvent.java | 207 +- .../java/appeng/fmp/FMPPlacementHelper.java | 434 +- src/main/java/appeng/fmp/PartRegistry.java | 91 +- src/main/java/appeng/fmp/QuartzTorchPart.java | 122 +- .../java/appeng/helpers/AEGlassMaterial.java | 25 +- src/main/java/appeng/helpers/AEMultiTile.java | 7 +- .../java/appeng/helpers/DualityInterface.java | 2288 +++++----- .../helpers/IContainerCraftingPacket.java | 48 +- .../java/appeng/helpers/ICustomCollision.java | 15 +- .../appeng/helpers/ICustomNameObject.java | 9 +- .../java/appeng/helpers/IInterfaceHost.java | 17 +- .../java/appeng/helpers/IMouseWheelItem.java | 8 +- .../java/appeng/helpers/IPriorityHost.java | 21 +- .../java/appeng/helpers/InventoryAction.java | 27 +- .../java/appeng/helpers/LocationRotation.java | 72 +- .../java/appeng/helpers/MetaRotation.java | 86 +- .../appeng/helpers/MultiCraftingTracker.java | 383 +- .../appeng/helpers/NonNullArrayIterator.java | 55 +- .../java/appeng/helpers/NullRotation.java | 45 +- .../java/appeng/helpers/PatternHelper.java | 761 ++-- .../appeng/helpers/PlayerSecurityWrapper.java | 31 +- src/main/java/appeng/helpers/Reflected.java | 13 +- src/main/java/appeng/helpers/Splotch.java | 140 +- .../helpers/WirelessTerminalGuiObject.java | 531 ++- src/main/java/appeng/hooks/AETrading.java | 158 +- .../java/appeng/hooks/CompassManager.java | 164 +- src/main/java/appeng/hooks/CompassResult.java | 70 +- .../hooks/DispenserBehaviorTinyTNT.java | 34 +- .../java/appeng/hooks/DispenserBlockTool.java | 54 +- .../appeng/hooks/DispenserMatterCannon.java | 63 +- src/main/java/appeng/hooks/IBlockTool.java | 19 +- src/main/java/appeng/hooks/TickHandler.java | 459 +- .../integration/IIntegrationModule.java | 8 +- .../appeng/integration/IntegrationHelper.java | 12 +- .../appeng/integration/IntegrationNode.java | 251 +- .../integration/IntegrationRegistry.java | 142 +- .../appeng/integration/IntegrationSide.java | 6 +- .../appeng/integration/IntegrationStage.java | 11 +- .../appeng/integration/IntegrationType.java | 72 +- .../abstraction/IBetterStorage.java | 10 +- .../abstraction/IBuildCraftCore.java | 65 +- .../abstraction/IBuildCraftTransport.java | 134 +- .../integration/abstraction/ICLApi.java | 8 +- .../appeng/integration/abstraction/IDSU.java | 10 +- .../appeng/integration/abstraction/IFMP.java | 14 +- .../appeng/integration/abstraction/IFZ.java | 22 +- .../integration/abstraction/IForestry.java | 8 +- .../appeng/integration/abstraction/IGT.java | 10 +- .../appeng/integration/abstraction/IIC2.java | 14 +- .../abstraction/IImmibisMicroblocks.java | 18 +- .../integration/abstraction/IInvTweaks.java | 8 +- .../appeng/integration/abstraction/ILP.java | 26 +- .../abstraction/ILogisticsPipes.java | 19 +- .../integration/abstraction/IMekanism.java | 10 +- .../appeng/integration/abstraction/INEI.java | 10 +- .../appeng/integration/abstraction/IRC.java | 8 +- .../appeng/integration/abstraction/ITE.java | 16 +- .../BCHelpers/AECableSchematicTile.java | 192 +- .../BCHelpers/AEGenericSchematicTile.java | 75 +- .../BCHelpers/AERotatableBlockSchematic.java | 24 +- .../modules/BCHelpers/BCPipeHandler.java | 52 +- .../modules/BCHelpers/BCPipeInventory.java | 91 +- .../integration/modules/BetterStorage.java | 62 +- .../modules/BuildCraftBuilder.java | 138 +- .../integration/modules/BuildCraftCore.java | 101 +- .../modules/BuildCraftTransport.java | 466 ++- .../appeng/integration/modules/CLApi.java | 52 +- .../integration/modules/CraftGuide.java | 756 ++-- .../java/appeng/integration/modules/DSU.java | 55 +- .../java/appeng/integration/modules/FMP.java | 263 +- .../java/appeng/integration/modules/FZ.java | 264 +- .../java/appeng/integration/modules/IC2.java | 130 +- .../modules/ImmibisMicroblocks.java | 179 +- .../appeng/integration/modules/InvTweaks.java | 55 +- .../modules/LPHelpers/LPPipeHandler.java | 36 +- .../modules/LPHelpers/LPPipeInventory.java | 139 +- .../integration/modules/LogisticsPipes.java | 82 +- .../java/appeng/integration/modules/MFR.java | 34 +- .../appeng/integration/modules/Mekanism.java | 75 +- .../java/appeng/integration/modules/NEI.java | 267 +- .../NEIHelpers/NEIAEShapedRecipeHandler.java | 367 +- .../NEIAEShapelessRecipeHandler.java | 365 +- .../NEIHelpers/NEICraftingHandler.java | 147 +- .../NEIHelpers/NEIFacadeRecipeHandler.java | 348 +- .../NEIHelpers/NEIGrinderRecipeHandler.java | 346 +- .../NEIHelpers/NEIInscriberRecipeHandler.java | 263 +- .../NEIHelpers/NEIWorldCraftingHandler.java | 339 +- .../TerminalCraftingSlotFinder.java | 31 +- .../integration/modules/OpenComputers.java | 92 +- .../integration/modules/PneumaticCraft.java | 83 +- .../java/appeng/integration/modules/RC.java | 48 +- .../java/appeng/integration/modules/RF.java | 112 +- .../appeng/integration/modules/RFItem.java | 31 +- .../integration/modules/RotaryCraft.java | 36 +- .../appeng/integration/modules/Waila.java | 67 +- .../integration/modules/helpers/BSCrate.java | 94 +- .../modules/helpers/BSCrateHandler.java | 41 +- .../helpers/BSCrateStorageAdaptor.java | 302 +- .../modules/helpers/FMPPacketEvent.java | 22 +- .../modules/helpers/FactorizationBarrel.java | 228 +- .../modules/helpers/FactorizationHandler.java | 43 +- .../modules/helpers/MFRDSUHandler.java | 41 +- .../MinefactoryReloadedDeepStorageUnit.java | 182 +- .../modules/helpers/NullRFHandler.java | 44 +- .../modules/waila/BaseWailaDataProvider.java | 76 +- .../modules/waila/PartWailaDataProvider.java | 256 +- .../modules/waila/TileWailaDataProvider.java | 134 +- .../waila/part/BasePartWailaDataProvider.java | 81 +- .../waila/part/ChannelWailaDataProvider.java | 203 +- .../waila/part/IPartWailaDataProvider.java | 44 +- .../waila/part/P2PStateWailaDataProvider.java | 238 +- .../modules/waila/part/PartAccessor.java | 52 +- .../part/PartStackWailaDataProvider.java | 20 +- .../part/PowerStateWailaDataProvider.java | 91 +- .../part/StorageMonitorWailaDataProvider.java | 79 +- .../modules/waila/part/Tracer.java | 110 +- .../waila/tile/ChargerWailaDataProvider.java | 67 +- .../CraftingMonitorWailaDataProvider.java | 62 +- .../tile/PowerStateWailaDataProvider.java | 71 +- .../tile/PowerStorageWailaDataProvider.java | 218 +- src/main/java/appeng/items/AEBaseItem.java | 129 +- .../appeng/items/contents/CellConfig.java | 28 +- .../appeng/items/contents/CellUpgrades.java | 27 +- .../items/contents/NetworkToolViewer.java | 170 +- .../items/contents/PortableCellViewer.java | 121 +- .../appeng/items/contents/QuartzKnifeObj.java | 24 +- .../items/materials/ItemMultiMaterial.java | 687 ++- .../appeng/items/materials/MaterialType.java | 335 +- .../appeng/items/misc/ItemCrystalSeed.java | 452 +- .../appeng/items/misc/ItemEncodedPattern.java | 262 +- .../java/appeng/items/misc/ItemPaintBall.java | 113 +- .../java/appeng/items/parts/ItemFacade.java | 399 +- .../appeng/items/parts/ItemMultiPart.java | 589 ++- .../java/appeng/items/parts/PartType.java | 414 +- .../items/storage/ItemBasicStorageCell.java | 474 ++- .../storage/ItemCreativeStorageCell.java | 60 +- .../items/storage/ItemSpatialStorageCell.java | 307 +- .../appeng/items/storage/ItemViewCell.java | 197 +- .../appeng/items/tools/ToolBiometricCard.java | 279 +- .../appeng/items/tools/ToolMemoryCard.java | 254 +- .../appeng/items/tools/ToolNetworkTool.java | 342 +- .../items/tools/powered/ToolChargedStaff.java | 76 +- .../tools/powered/ToolColorApplicator.java | 966 +++-- .../tools/powered/ToolEntropyManipulator.java | 644 +-- .../items/tools/powered/ToolMassCannon.java | 849 ++-- .../items/tools/powered/ToolPortableCell.java | 241 +- .../tools/powered/ToolWirelessTerminal.java | 186 +- .../powered/powersink/AEBasePoweredItem.java | 14 +- .../powered/powersink/AERootPoweredItem.java | 282 +- .../items/tools/powered/powersink/IC2.java | 175 +- .../tools/powered/powersink/RedstoneFlux.java | 54 +- .../powersink/UniversalElectricity.java | 2 - .../items/tools/quartz/ToolQuartzAxe.java | 52 +- .../tools/quartz/ToolQuartzCuttingKnife.java | 128 +- .../items/tools/quartz/ToolQuartzHoe.java | 54 +- .../items/tools/quartz/ToolQuartzPickaxe.java | 54 +- .../items/tools/quartz/ToolQuartzSpade.java | 52 +- .../items/tools/quartz/ToolQuartzSword.java | 52 +- .../items/tools/quartz/ToolQuartzWrench.java | 148 +- src/main/java/appeng/me/Grid.java | 395 +- .../java/appeng/me/GridAccessException.java | 7 +- src/main/java/appeng/me/GridCacheWrapper.java | 87 +- src/main/java/appeng/me/GridConnection.java | 403 +- src/main/java/appeng/me/GridException.java | 15 +- src/main/java/appeng/me/GridNode.java | 1239 +++--- .../java/appeng/me/GridNodeCollection.java | 101 +- src/main/java/appeng/me/GridNodeIterator.java | 83 +- src/main/java/appeng/me/GridPropagator.java | 34 +- .../java/appeng/me/GridSplitDetector.java | 47 +- src/main/java/appeng/me/GridStorage.java | 199 +- .../java/appeng/me/GridStorageSearch.java | 76 +- src/main/java/appeng/me/MachineSet.java | 28 +- src/main/java/appeng/me/NetworkEventBus.java | 310 +- src/main/java/appeng/me/NetworkList.java | 125 +- .../appeng/me/cache/CraftingGridCache.java | 1137 +++-- .../java/appeng/me/cache/EnergyGridCache.java | 1092 +++-- .../appeng/me/cache/GridStorageCache.java | 587 ++- .../java/appeng/me/cache/NetworkMonitor.java | 479 +-- src/main/java/appeng/me/cache/P2PCache.java | 298 +- .../java/appeng/me/cache/PathGridCache.java | 768 ++-- .../java/appeng/me/cache/SecurityCache.java | 244 +- .../appeng/me/cache/SpatialPylonCache.java | 343 +- .../appeng/me/cache/TickManagerCache.java | 352 +- .../me/cache/helpers/ConnectionWrapper.java | 29 +- .../appeng/me/cache/helpers/Connections.java | 88 +- .../appeng/me/cache/helpers/TickTracker.java | 178 +- .../me/cache/helpers/TunnelCollection.java | 67 +- .../me/cache/helpers/TunnelConnection.java | 33 +- .../me/cache/helpers/TunnelIterator.java | 77 +- .../java/appeng/me/cluster/IAECluster.java | 14 +- .../java/appeng/me/cluster/IAEMultiBlock.java | 11 +- .../java/appeng/me/cluster/MBCalculator.java | 349 +- .../CraftingCPUCalculator.java | 175 +- .../implementations/CraftingCPUCluster.java | 2413 +++++------ .../implementations/QuantumCalculator.java | 221 +- .../implementations/QuantumCluster.java | 431 +- .../SpatialPylonCalculator.java | 127 +- .../implementations/SpatialPylonCluster.java | 166 +- .../appeng/me/energy/EnergyThreshold.java | 66 +- .../java/appeng/me/energy/EnergyWatcher.java | 271 +- .../appeng/me/helpers/AENetworkProxy.java | 605 ++- .../me/helpers/AENetworkProxyMultiblock.java | 43 +- .../appeng/me/helpers/ChannelPowerSrc.java | 37 +- .../me/helpers/GenericInterestManager.java | 150 +- .../appeng/me/helpers/IGridProxyable.java | 12 +- .../me/pathfinding/AdHocChannelUpdater.java | 47 +- .../pathfinding/ControllerChannelUpdater.java | 30 +- .../me/pathfinding/ControllerValidator.java | 115 +- .../java/appeng/me/pathfinding/IPathItem.java | 56 +- .../appeng/me/pathfinding/PathSegment.java | 221 +- .../appeng/me/storage/AEExternalHandler.java | 96 +- .../java/appeng/me/storage/CellInventory.java | 1069 +++-- .../me/storage/CellInventoryHandler.java | 173 +- .../me/storage/CreativeCellInventory.java | 158 +- .../java/appeng/me/storage/DriveWatcher.java | 88 +- .../java/appeng/me/storage/ItemWatcher.java | 258 +- .../me/storage/MEIInventoryWrapper.java | 282 +- .../appeng/me/storage/MEInventoryHandler.java | 257 +- .../me/storage/MEMonitorIInventory.java | 500 +-- .../me/storage/MEMonitorPassThrough.java | 221 +- .../java/appeng/me/storage/MEPassThrough.java | 132 +- .../me/storage/NetworkInventoryHandler.java | 469 +-- .../java/appeng/me/storage/NullInventory.java | 98 +- .../appeng/me/storage/SecurityInventory.java | 256 +- .../appeng/me/storage/VoidFluidInventory.java | 123 +- .../appeng/me/storage/VoidItemInventory.java | 123 +- src/main/java/appeng/parts/AEBasePart.java | 981 ++--- .../java/appeng/parts/BusCollisionHelper.java | 259 +- .../java/appeng/parts/CableBusContainer.java | 1927 ++++----- .../java/appeng/parts/CableBusStorage.java | 172 +- .../java/appeng/parts/ICableBusContainer.java | 38 +- .../appeng/parts/NullCableBusContainer.java | 125 +- .../java/appeng/parts/PartBasicState.java | 237 +- src/main/java/appeng/parts/PartPlacement.java | 949 +++-- .../automation/BlockUpgradeInventory.java | 46 +- .../DefinitionUpgradeInventory.java | 43 +- .../automation/PartAnnihilationPlane.java | 1153 ++--- .../parts/automation/PartExportBus.java | 557 +-- .../parts/automation/PartFormationPlane.java | 1164 +++--- .../PartIdentityAnnihilationPlane.java | 123 +- .../parts/automation/PartImportBus.java | 520 +-- .../parts/automation/PartLevelEmitter.java | 1381 +++--- .../parts/automation/PartSharedItemBus.java | 248 +- .../parts/automation/PartUpgradeable.java | 214 +- .../automation/StackUpgradeInventory.java | 43 +- .../parts/automation/UpgradeInventory.java | 260 +- .../appeng/parts/layers/InvLayerData.java | 179 +- src/main/java/appeng/parts/layers/InvSot.java | 61 +- .../parts/layers/LayerIEnergyHandler.java | 100 +- .../appeng/parts/layers/LayerIEnergySink.java | 257 +- .../parts/layers/LayerIEnergySource.java | 265 +- .../parts/layers/LayerIFluidHandler.java | 121 +- .../parts/layers/LayerIPipeConnection.java | 25 +- .../parts/layers/LayerISidedInventory.java | 351 +- .../layers/LayerITileStorageMonitorable.java | 26 +- .../appeng/parts/layers/LayerPressure.java | 29 +- .../parts/layers/LayerSidedEnvironment.java | 45 +- .../appeng/parts/misc/PartCableAnchor.java | 354 +- .../java/appeng/parts/misc/PartInterface.java | 581 ++- .../parts/misc/PartInvertedToggleBus.java | 31 +- .../appeng/parts/misc/PartStorageBus.java | 997 ++--- .../java/appeng/parts/misc/PartToggleBus.java | 333 +- .../appeng/parts/networking/PartCable.java | 1825 ++++---- .../parts/networking/PartCableCovered.java | 374 +- .../parts/networking/PartCableGlass.java | 14 +- .../parts/networking/PartCableSmart.java | 642 +-- .../parts/networking/PartDenseCable.java | 918 ++-- .../parts/networking/PartQuartzFiber.java | 313 +- .../appeng/parts/p2p/PartP2PIC2Power.java | 348 +- .../java/appeng/parts/p2p/PartP2PItems.java | 526 ++- .../java/appeng/parts/p2p/PartP2PLight.java | 294 +- .../java/appeng/parts/p2p/PartP2PLiquids.java | 416 +- .../parts/p2p/PartP2POpenComputers.java | 210 +- .../appeng/parts/p2p/PartP2PPressure.java | 228 +- .../java/appeng/parts/p2p/PartP2PRFPower.java | 358 +- .../appeng/parts/p2p/PartP2PRedstone.java | 274 +- .../java/appeng/parts/p2p/PartP2PTunnel.java | 837 ++-- .../appeng/parts/p2p/PartP2PTunnelME.java | 353 +- .../parts/reporting/AbstractPartDisplay.java | 206 +- .../parts/reporting/AbstractPartMonitor.java | 568 ++- .../parts/reporting/AbstractPartPanel.java | 162 +- .../reporting/AbstractPartReporting.java | 450 +- .../parts/reporting/AbstractPartTerminal.java | 202 +- .../reporting/PartConversionMonitor.java | 255 +- .../parts/reporting/PartCraftingTerminal.java | 150 +- .../appeng/parts/reporting/PartDarkPanel.java | 24 +- .../reporting/PartInterfaceTerminal.java | 83 +- .../appeng/parts/reporting/PartPanel.java | 25 +- .../parts/reporting/PartPatternTerminal.java | 312 +- .../parts/reporting/PartSemiDarkPanel.java | 30 +- .../parts/reporting/PartStorageMonitor.java | 53 +- .../appeng/parts/reporting/PartTerminal.java | 49 +- .../java/appeng/recipes/AEItemResolver.java | 248 +- .../appeng/recipes/CustomRecipeConfig.java | 6 +- .../CustomRecipeForgeConfiguration.java | 32 +- .../java/appeng/recipes/GroupIngredient.java | 204 +- src/main/java/appeng/recipes/Ingredient.java | 385 +- .../java/appeng/recipes/IngredientSet.java | 150 +- .../appeng/recipes/MissedIngredientSet.java | 24 +- src/main/java/appeng/recipes/RecipeData.java | 22 +- .../java/appeng/recipes/RecipeHandler.java | 1272 +++--- .../recipes/game/DisassembleRecipe.java | 218 +- .../appeng/recipes/game/FacadeRecipe.java | 102 +- .../appeng/recipes/game/IRecipeBakeable.java | 7 +- .../appeng/recipes/game/ShapedRecipe.java | 461 +- .../appeng/recipes/game/ShapelessRecipe.java | 236 +- .../java/appeng/recipes/handlers/Crusher.java | 93 +- .../java/appeng/recipes/handlers/Grind.java | 79 +- .../java/appeng/recipes/handlers/GrindFZ.java | 93 +- .../appeng/recipes/handlers/HCCrusher.java | 105 +- .../recipes/handlers/IWebsiteSerializer.java | 10 +- .../appeng/recipes/handlers/Inscribe.java | 55 +- .../recipes/handlers/InscriberProcess.java | 159 +- .../appeng/recipes/handlers/Macerator.java | 93 +- .../appeng/recipes/handlers/MekCrusher.java | 93 +- .../recipes/handlers/MekEnrichment.java | 93 +- .../recipes/handlers/OreRegistration.java | 49 +- .../java/appeng/recipes/handlers/Press.java | 55 +- .../appeng/recipes/handlers/Pulverizer.java | 87 +- .../java/appeng/recipes/handlers/Shaped.java | 223 +- .../appeng/recipes/handlers/Shapeless.java | 164 +- .../java/appeng/recipes/handlers/Smelt.java | 92 +- .../appeng/recipes/loader/ConfigLoader.java | 50 +- .../java/appeng/recipes/loader/JarLoader.java | 36 +- .../recipes/loader/RecipeResourceCopier.java | 383 +- .../appeng/recipes/ores/IOreListener.java | 22 +- .../recipes/ores/OreDictionaryHandler.java | 142 +- src/main/java/appeng/server/AECommand.java | 142 +- src/main/java/appeng/server/AccessType.java | 52 +- src/main/java/appeng/server/Commands.java | 32 +- src/main/java/appeng/server/ISubCommand.java | 10 +- src/main/java/appeng/server/ServerHelper.java | 234 +- .../server/subcommands/ChunkLogger.java | 120 +- .../appeng/server/subcommands/Supporters.java | 33 +- .../java/appeng/services/CompassService.java | 501 ++- .../java/appeng/services/VersionChecker.java | 245 +- .../services/compass/CompassException.java | 16 +- .../services/compass/CompassReader.java | 86 +- .../services/compass/CompassRegion.java | 283 +- .../compass/CompassThreadFactory.java | 20 +- .../services/compass/ICompassCallback.java | 24 +- .../appeng/services/export/CheckType.java | 23 +- .../java/appeng/services/export/Checker.java | 19 +- .../appeng/services/export/ExportConfig.java | 94 +- .../appeng/services/export/ExportMode.java | 20 +- .../appeng/services/export/ExportProcess.java | 147 +- .../java/appeng/services/export/Exporter.java | 12 +- .../services/export/ForgeExportConfig.java | 176 +- .../export/MinecraftItemCSVExporter.java | 414 +- .../services/export/ModListChecker.java | 87 +- .../appeng/services/export/package-info.java | 12 +- .../appeng/services/version/BaseVersion.java | 159 +- .../java/appeng/services/version/Channel.java | 12 +- .../services/version/DefaultVersion.java | 50 +- .../services/version/DoNotCheckVersion.java | 29 +- .../services/version/MissingVersion.java | 37 +- .../services/version/ModVersionFetcher.java | 77 +- .../java/appeng/services/version/Version.java | 63 +- .../version/VersionCheckerConfig.java | 176 +- .../services/version/VersionFetcher.java | 6 +- .../services/version/VersionParser.java | 249 +- .../exceptions/InvalidBuildException.java | 13 +- .../exceptions/InvalidChannelException.java | 16 +- .../exceptions/InvalidRevisionException.java | 17 +- .../exceptions/InvalidVersionException.java | 19 +- .../exceptions/MissingSeparatorException.java | 13 +- .../exceptions/VersionCheckerException.java | 14 +- .../github/DefaultFormattedRelease.java | 44 +- .../version/github/FormattedRelease.java | 24 +- .../github/MissingFormattedRelease.java | 48 +- .../services/version/github/Release.java | 22 +- .../version/github/ReleaseFetcher.java | 131 +- .../java/appeng/spatial/BiomeGenStorage.java | 33 +- src/main/java/appeng/spatial/CachedPlane.java | 731 ++-- .../appeng/spatial/DefaultSpatialHandler.java | 60 +- .../java/appeng/spatial/ISpatialVisitor.java | 7 +- .../appeng/spatial/StorageChunkProvider.java | 103 +- .../java/appeng/spatial/StorageHelper.java | 601 +-- .../appeng/spatial/StorageWorldProvider.java | 188 +- src/main/java/appeng/tile/AEBaseInvTile.java | 231 +- src/main/java/appeng/tile/AEBaseTile.java | 1004 +++-- src/main/java/appeng/tile/TileEvent.java | 12 +- .../crafting/TileCraftingMonitorTile.java | 221 +- .../crafting/TileCraftingStorageTile.java | 117 +- .../tile/crafting/TileCraftingTile.java | 523 ++- .../tile/crafting/TileMolecularAssembler.java | 1123 +++-- .../tile/events/AETileEventHandler.java | 193 +- .../appeng/tile/events/TileEventType.java | 19 +- .../appeng/tile/grid/AENetworkInvTile.java | 107 +- .../appeng/tile/grid/AENetworkPowerTile.java | 125 +- .../java/appeng/tile/grid/AENetworkTile.java | 129 +- .../appeng/tile/grindstone/TileCrank.java | 261 +- .../appeng/tile/grindstone/TileGrinder.java | 262 +- .../inventory/AppEngInternalAEInventory.java | 374 +- .../inventory/AppEngInternalInventory.java | 417 +- .../tile/inventory/AppEngNullInventory.java | 121 +- .../tile/inventory/IAEAppEngInventory.java | 16 +- .../appeng/tile/inventory/InvOperation.java | 8 +- .../appeng/tile/legacy/TileCraftTerminal.java | 33 +- .../tile/legacy/TileCraftingMonitor.java | 3 +- .../tile/legacy/TileLegacyController.java | 54 +- .../java/appeng/tile/legacy/TileTerminal.java | 44 +- .../appeng/tile/misc/TileCellWorkbench.java | 341 +- .../java/appeng/tile/misc/TileCharger.java | 429 +- .../java/appeng/tile/misc/TileCondenser.java | 398 +- .../java/appeng/tile/misc/TileInscriber.java | 972 +++-- .../java/appeng/tile/misc/TileInterface.java | 413 +- .../appeng/tile/misc/TileLightDetector.java | 63 +- src/main/java/appeng/tile/misc/TilePaint.java | 359 +- .../misc/TileQuartzGrowthAccelerator.java | 129 +- .../java/appeng/tile/misc/TileSecurity.java | 470 +-- .../java/appeng/tile/misc/TileSkyCompass.java | 15 +- .../tile/misc/TileVibrationChamber.java | 446 +- .../appeng/tile/networking/TileCableBus.java | 547 ++- .../tile/networking/TileCableBusTESR.java | 36 +- .../tile/networking/TileController.java | 291 +- .../networking/TileCreativeEnergyCell.java | 77 +- .../tile/networking/TileDenseEnergyCell.java | 12 +- .../tile/networking/TileEnergyAcceptor.java | 139 +- .../tile/networking/TileEnergyCell.java | 322 +- .../appeng/tile/networking/TileWireless.java | 281 +- .../tile/powersink/AEBasePoweredTile.java | 6 +- .../tile/powersink/AERootPoweredTile.java | 311 +- src/main/java/appeng/tile/powersink/IC2.java | 151 +- .../java/appeng/tile/powersink/MekJoules.java | 71 +- .../appeng/tile/powersink/RedstoneFlux.java | 59 +- .../appeng/tile/powersink/RotaryCraft.java | 228 +- .../tile/powersink/UniversalElectricity.java | 13 +- .../appeng/tile/qnb/TileQuantumBridge.java | 453 +- .../tile/spatial/TileSpatialIOPort.java | 261 +- .../appeng/tile/spatial/TileSpatialPylon.java | 332 +- .../java/appeng/tile/storage/TileChest.java | 1690 ++++---- .../java/appeng/tile/storage/TileDrive.java | 568 ++- .../java/appeng/tile/storage/TileIOPort.java | 993 +++-- .../appeng/tile/storage/TileSkyChest.java | 204 +- .../java/appeng/transformer/AppEngCore.java | 144 +- .../appeng/transformer/MissingCoreMod.java | 171 +- .../transformer/annotations/Integration.java | 41 +- .../transformer/asm/ASMIntegration.java | 366 +- .../appeng/transformer/asm/ASMTweaker.java | 262 +- .../appeng/transformer/asm/ApiRepairer.java | 99 +- src/main/java/appeng/util/BlockUpdate.java | 41 +- .../java/appeng/util/ClassInstantiation.java | 166 +- src/main/java/appeng/util/ConfigManager.java | 164 +- .../java/appeng/util/IConfigManagerHost.java | 8 +- .../util/ISlimReadableNumberConverter.java | 28 +- .../util/IWideReadableNumberConverter.java | 31 +- src/main/java/appeng/util/IWorldCallable.java | 35 +- .../util/InWorldToolOperationResult.java | 92 +- .../java/appeng/util/InventoryAdaptor.java | 119 +- src/main/java/appeng/util/ItemSorters.java | 248 +- src/main/java/appeng/util/LookDirection.java | 33 +- src/main/java/appeng/util/Platform.java | 3709 ++++++++--------- .../java/appeng/util/ReadOnlyCollection.java | 53 +- .../appeng/util/ReadableNumberConverter.java | 140 +- src/main/java/appeng/util/SettingsFrom.java | 12 +- src/main/java/appeng/util/UUIDMatcher.java | 43 +- .../java/appeng/util/inv/AdaptorBCPipe.java | 163 +- .../appeng/util/inv/AdaptorIInventory.java | 550 ++- .../java/appeng/util/inv/AdaptorList.java | 323 +- .../appeng/util/inv/AdaptorPlayerHand.java | 329 +- .../util/inv/AdaptorPlayerInventory.java | 151 +- .../util/inv/IInventoryDestination.java | 8 +- .../appeng/util/inv/IInventoryWrapper.java | 8 +- src/main/java/appeng/util/inv/IMEAdaptor.java | 282 +- .../appeng/util/inv/IMEAdaptorIterator.java | 87 +- .../util/inv/IMEInventoryDestination.java | 42 +- .../util/inv/ItemListIgnoreCrafting.java | 127 +- src/main/java/appeng/util/inv/ItemSlot.java | 84 +- .../java/appeng/util/inv/WrapperBCPipe.java | 140 +- .../util/inv/WrapperChainedInventory.java | 320 +- .../java/appeng/util/inv/WrapperInvSlot.java | 166 +- .../util/inv/WrapperInventoryRange.java | 234 +- .../util/inv/WrapperMCISidedInventory.java | 80 +- .../java/appeng/util/item/AEFluidStack.java | 547 ++- src/main/java/appeng/util/item/AEItemDef.java | 298 +- .../java/appeng/util/item/AEItemStack.java | 1333 +++--- .../java/appeng/util/item/AESharedNBT.java | 289 +- src/main/java/appeng/util/item/AEStack.java | 265 +- src/main/java/appeng/util/item/FluidList.java | 253 +- src/main/java/appeng/util/item/ItemList.java | 300 +- .../java/appeng/util/item/ItemModList.java | 94 +- .../util/item/MeaningfulFluidIterator.java | 75 +- .../util/item/MeaningfulItemIterator.java | 75 +- src/main/java/appeng/util/item/OreHelper.java | 282 +- .../java/appeng/util/item/OreReference.java | 61 +- .../appeng/util/item/SharedSearchObject.java | 97 +- .../appeng/util/iterators/AEInvIterator.java | 53 +- .../util/iterators/ChainedIterator.java | 47 +- .../appeng/util/iterators/InvIterator.java | 53 +- .../appeng/util/iterators/NullIterator.java | 31 +- .../util/iterators/ProxyNodeIterator.java | 45 +- .../util/iterators/StackToSlotIterator.java | 54 +- .../util/prioitylist/DefaultPriorityList.java | 37 +- .../util/prioitylist/FuzzyPriorityList.java | 50 +- .../util/prioitylist/IPartitionList.java | 11 +- .../util/prioitylist/MergedPriorityList.java | 91 +- .../util/prioitylist/PrecisePriorityList.java | 42 +- .../java/appeng/worldgen/MeteoritePlacer.java | 1013 +++-- .../appeng/worldgen/MeteoriteWorldGen.java | 204 +- .../java/appeng/worldgen/QuartzWorldGen.java | 103 +- .../appeng/worldgen/meteorite/ChunkOnly.java | 157 +- .../appeng/worldgen/meteorite/Fallout.java | 111 +- .../worldgen/meteorite/FalloutCopy.java | 96 +- .../worldgen/meteorite/FalloutSand.java | 50 +- .../worldgen/meteorite/FalloutSnow.java | 58 +- .../worldgen/meteorite/IMeteoriteWorld.java | 31 +- .../meteorite/MeteoriteBlockPutter.java | 44 +- .../worldgen/meteorite/StandardWorld.java | 182 +- .../worlddata/MeteorDataNameEncoderTest.java | 57 +- .../version/ModVersionFetcherTest.java | 53 +- .../services/version/VersionParserTest.java | 139 +- .../appeng/services/version/VersionTest.java | 141 +- .../util/SlimReadableNumberConverterTest.java | 170 +- .../java/appeng/util/UUIDMatcherTest.java | 49 +- .../util/WideReadableNumberConverterTest.java | 170 +- 1179 files changed, 102807 insertions(+), 106963 deletions(-) diff --git a/src/api/java/appeng/api/AEApi.java b/src/api/java/appeng/api/AEApi.java index dd5005f4..83026cb1 100644 --- a/src/api/java/appeng/api/AEApi.java +++ b/src/api/java/appeng/api/AEApi.java @@ -23,56 +23,52 @@ package appeng.api; - -import appeng.api.exceptions.CoreInaccessibleException; - import java.lang.reflect.Field; +import appeng.api.exceptions.CoreInaccessibleException; /** * Entry point for api. *

* Available IMCs: */ -public enum AEApi -{ - ; +public enum AEApi { + ; - private static final String CORE_API_FQN = "appeng.core.Api"; - private static final String CORE_API_FIELD = "INSTANCE"; - private static final IAppEngApi HELD_API; + private static final String CORE_API_FQN = "appeng.core.Api"; + private static final String CORE_API_FIELD = "INSTANCE"; + private static final IAppEngApi HELD_API; - static - { - try - { - final Class apiClass = Class.forName( CORE_API_FQN ); - final Field apiField = apiClass.getField( CORE_API_FIELD ); + static { + try { + final Class apiClass = Class.forName(CORE_API_FQN); + final Field apiField = apiClass.getField(CORE_API_FIELD); - HELD_API = (IAppEngApi) apiField.get( apiClass ); - } - catch( final ClassNotFoundException e ) - { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FQN + " class, without it being declared." ); - } - catch( final NoSuchFieldException e ) - { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FIELD + " field in " + CORE_API_FQN + " without it being declared." ); - } - catch( final IllegalAccessException e ) - { - throw new CoreInaccessibleException( "AE2 API tried to access the " + CORE_API_FIELD + " field in " + CORE_API_FQN + " without enough access permissions." ); - } - } - - /** - * API Entry Point. - * - * @return the {@link IAppEngApi} - */ - public static IAppEngApi instance() - { - return HELD_API; - } + HELD_API = (IAppEngApi) apiField.get(apiClass); + } catch (final ClassNotFoundException e) { + throw new CoreInaccessibleException( + "AE2 API tried to access the " + CORE_API_FQN + + " class, without it being declared." + ); + } catch (final NoSuchFieldException e) { + throw new CoreInaccessibleException( + "AE2 API tried to access the " + CORE_API_FIELD + " field in " + + CORE_API_FQN + " without it being declared." + ); + } catch (final IllegalAccessException e) { + throw new CoreInaccessibleException( + "AE2 API tried to access the " + CORE_API_FIELD + " field in " + + CORE_API_FQN + " without enough access permissions." + ); + } + } + /** + * API Entry Point. + * + * @return the {@link IAppEngApi} + */ + public static IAppEngApi instance() { + return HELD_API; + } } diff --git a/src/api/java/appeng/api/IAppEngApi.java b/src/api/java/appeng/api/IAppEngApi.java index 453ec979..06827bea 100644 --- a/src/api/java/appeng/api/IAppEngApi.java +++ b/src/api/java/appeng/api/IAppEngApi.java @@ -23,7 +23,6 @@ package appeng.api; - import appeng.api.definitions.*; import appeng.api.exceptions.FailedConnection; import appeng.api.features.IRegistryContainer; @@ -33,72 +32,70 @@ import appeng.api.networking.IGridNode; import appeng.api.parts.IPartHelper; import appeng.api.storage.IStorageHelper; +public interface IAppEngApi { + /** + * @return Registry Container for the numerous registries in AE2. + */ + IRegistryContainer registries(); -public interface IAppEngApi -{ + /** + * @return helper for working with storage data types. + */ + IStorageHelper storage(); - /** - * @return Registry Container for the numerous registries in AE2. - */ - IRegistryContainer registries(); + /** + * @return helper for working with grids, and buses. + */ + IPartHelper partHelper(); - /** - * @return helper for working with storage data types. - */ - IStorageHelper storage(); + /** + * @return an accessible list of all of AE's Items + * @deprecated use {@link appeng.api.definitions.IDefinitions#items()} + */ + @Deprecated + Items items(); - /** - * @return helper for working with grids, and buses. - */ - IPartHelper partHelper(); + /** + * @return an accessible list of all of AE's materials; materials are items + * @deprecated use {@link appeng.api.definitions.IDefinitions#materials()} + */ + @Deprecated + Materials materials(); - /** - * @return an accessible list of all of AE's Items - * @deprecated use {@link appeng.api.definitions.IDefinitions#items()} - */ - @Deprecated - Items items(); + /** + * @return an accessible list of all of AE's blocks + * @deprecated use {@link appeng.api.definitions.IDefinitions#blocks()} + */ + @Deprecated + Blocks blocks(); - /** - * @return an accessible list of all of AE's materials; materials are items - * @deprecated use {@link appeng.api.definitions.IDefinitions#materials()} - */ - @Deprecated - Materials materials(); + /** + * @return an accessible list of all of AE's parts, parts are items + * @deprecated use {@link appeng.api.definitions.IDefinitions#parts()} + */ + @Deprecated + Parts parts(); - /** - * @return an accessible list of all of AE's blocks - * @deprecated use {@link appeng.api.definitions.IDefinitions#blocks()} - */ - @Deprecated - Blocks blocks(); + /** + * @return an accessible list of all AE definitions + */ + IDefinitions definitions(); - /** - * @return an accessible list of all of AE's parts, parts are items - * @deprecated use {@link appeng.api.definitions.IDefinitions#parts()} - */ - @Deprecated - Parts parts(); + /** + * create a grid node for your {@link appeng.api.networking.IGridHost} + * + * @param block grid block + * @return grid node of block + */ + IGridNode createGridNode(IGridBlock block); - /** - * @return an accessible list of all AE definitions - */ - IDefinitions definitions(); - - /** - * create a grid node for your {@link appeng.api.networking.IGridHost} - * - * @param block grid block - * @return grid node of block - */ - IGridNode createGridNode( IGridBlock block ); - - /** - * create a connection between two {@link appeng.api.networking.IGridNode} - * - * @param a to be connected gridnode - * @param b to be connected gridnode - * @throws appeng.api.exceptions.FailedConnection - */ - IGridConnection createGridConnection( IGridNode a, IGridNode b ) throws FailedConnection; + /** + * create a connection between two {@link appeng.api.networking.IGridNode} + * + * @param a to be connected gridnode + * @param b to be connected gridnode + * @throws appeng.api.exceptions.FailedConnection + */ + IGridConnection createGridConnection(IGridNode a, IGridNode b) + throws FailedConnection; } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/AccessRestriction.java b/src/api/java/appeng/api/config/AccessRestriction.java index 6788d744..ffb6c6ca 100644 --- a/src/api/java/appeng/api/config/AccessRestriction.java +++ b/src/api/java/appeng/api/config/AccessRestriction.java @@ -23,51 +23,45 @@ package appeng.api.config; +public enum AccessRestriction { + NO_ACCESS(0), + READ(1), + WRITE(2), + READ_WRITE(3); -public enum AccessRestriction -{ - NO_ACCESS( 0 ), READ( 1 ), WRITE( 2 ), READ_WRITE( 3 ); + private final int permissionBit; - private final int permissionBit; + AccessRestriction(final int v) { + this.permissionBit = v; + } - AccessRestriction( final int v ) - { - this.permissionBit = v; - } + public boolean hasPermission(final AccessRestriction ar) { + return (this.permissionBit & ar.permissionBit) == ar.permissionBit; + } - public boolean hasPermission( final AccessRestriction ar ) - { - return ( this.permissionBit & ar.permissionBit ) == ar.permissionBit; - } + public AccessRestriction restrictPermissions(final AccessRestriction ar) { + return this.getPermByBit(this.permissionBit & ar.permissionBit); + } - public AccessRestriction restrictPermissions( final AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit & ar.permissionBit ); - } + private AccessRestriction getPermByBit(final int bit) { + switch (bit) { + default: + case 0: + return NO_ACCESS; + case 1: + return READ; + case 2: + return WRITE; + case 3: + return READ_WRITE; + } + } - private AccessRestriction getPermByBit( final int bit ) - { - switch( bit ) - { - default: - case 0: - return NO_ACCESS; - case 1: - return READ; - case 2: - return WRITE; - case 3: - return READ_WRITE; - } - } + public AccessRestriction addPermissions(final AccessRestriction ar) { + return this.getPermByBit(this.permissionBit | ar.permissionBit); + } - public AccessRestriction addPermissions( final AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit | ar.permissionBit ); - } - - public AccessRestriction removePermissions( final AccessRestriction ar ) - { - return this.getPermByBit( this.permissionBit & ( ~ar.permissionBit ) ); - } + public AccessRestriction removePermissions(final AccessRestriction ar) { + return this.getPermByBit(this.permissionBit & (~ar.permissionBit)); + } } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/ActionItems.java b/src/api/java/appeng/api/config/ActionItems.java index 9cb6fbf2..4c4a84f6 100644 --- a/src/api/java/appeng/api/config/ActionItems.java +++ b/src/api/java/appeng/api/config/ActionItems.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum ActionItems -{ - WRENCH, CLOSE, STASH, ENCODE, SUBSTITUTION -} \ No newline at end of file +public enum ActionItems { WRENCH, CLOSE, STASH, ENCODE, SUBSTITUTION } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/Actionable.java b/src/api/java/appeng/api/config/Actionable.java index 8e5f1f54..93835e62 100644 --- a/src/api/java/appeng/api/config/Actionable.java +++ b/src/api/java/appeng/api/config/Actionable.java @@ -23,16 +23,14 @@ package appeng.api.config; +public enum Actionable { + /** + * Perform the intended action. + */ + MODULATE, -public enum Actionable -{ - /** - * Perform the intended action. - */ - MODULATE, - - /** - * Pretend to perform the action. - */ - SIMULATE + /** + * Pretend to perform the action. + */ + SIMULATE } diff --git a/src/api/java/appeng/api/config/CondenserOutput.java b/src/api/java/appeng/api/config/CondenserOutput.java index cb9efae0..082dc33d 100644 --- a/src/api/java/appeng/api/config/CondenserOutput.java +++ b/src/api/java/appeng/api/config/CondenserOutput.java @@ -23,16 +23,12 @@ package appeng.api.config; +public enum CondenserOutput { + TRASH, // 0 -public enum CondenserOutput -{ + MATTER_BALLS, // 256 - TRASH, // 0 - - MATTER_BALLS, // 256 - - SINGULARITY; // 250,000 - - public int requiredPower = 0; + SINGULARITY; // 250,000 + public int requiredPower = 0; } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/CopyMode.java b/src/api/java/appeng/api/config/CopyMode.java index 7f2f3996..aad2ab7e 100644 --- a/src/api/java/appeng/api/config/CopyMode.java +++ b/src/api/java/appeng/api/config/CopyMode.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum CopyMode -{ - CLEAR_ON_REMOVE, KEEP_ON_REMOVE -} +public enum CopyMode { CLEAR_ON_REMOVE, KEEP_ON_REMOVE } diff --git a/src/api/java/appeng/api/config/FullnessMode.java b/src/api/java/appeng/api/config/FullnessMode.java index c52d4228..19ea31c4 100644 --- a/src/api/java/appeng/api/config/FullnessMode.java +++ b/src/api/java/appeng/api/config/FullnessMode.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum FullnessMode -{ - EMPTY, HALF, FULL -} \ No newline at end of file +public enum FullnessMode { EMPTY, HALF, FULL } \ 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 665dd551..4f438adb 100644 --- a/src/api/java/appeng/api/config/FuzzyMode.java +++ b/src/api/java/appeng/api/config/FuzzyMode.java @@ -23,24 +23,23 @@ package appeng.api.config; +public enum FuzzyMode { + // Note that percentage damaged, is the inverse of percentage durability. + IGNORE_ALL(-1), + PERCENT_99(0), + PERCENT_75(25), + PERCENT_50(50), + PERCENT_25(75); -public enum FuzzyMode -{ - // Note that percentage damaged, is the inverse of percentage durability. - IGNORE_ALL( -1 ), PERCENT_99( 0 ), PERCENT_75( 25 ), PERCENT_50( 50 ), PERCENT_25( 75 ); + public final float breakPoint; + public final float percentage; - public final float breakPoint; - public final float percentage; - - FuzzyMode( final float p ) - { - this.percentage = p; - this.breakPoint = p / 100.0f; - } - - public int calculateBreakPoint( final int maxDamage ) - { - return (int) ( ( this.percentage * maxDamage ) / 100.0f ); - } + FuzzyMode(final float p) { + this.percentage = p; + this.breakPoint = p / 100.0f; + } + public int calculateBreakPoint(final int maxDamage) { + return (int) ((this.percentage * maxDamage) / 100.0f); + } } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/IncludeExclude.java b/src/api/java/appeng/api/config/IncludeExclude.java index 53f0bbeb..bf76f60c 100644 --- a/src/api/java/appeng/api/config/IncludeExclude.java +++ b/src/api/java/appeng/api/config/IncludeExclude.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum IncludeExclude -{ - WHITELIST, BLACKLIST -} \ No newline at end of file +public enum IncludeExclude { WHITELIST, BLACKLIST } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/ItemSubstitution.java b/src/api/java/appeng/api/config/ItemSubstitution.java index 9c4b4706..7e84caa9 100644 --- a/src/api/java/appeng/api/config/ItemSubstitution.java +++ b/src/api/java/appeng/api/config/ItemSubstitution.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum ItemSubstitution -{ - ENABLED, DISABLED -} +public enum ItemSubstitution { ENABLED, DISABLED } diff --git a/src/api/java/appeng/api/config/LevelEmitterMode.java b/src/api/java/appeng/api/config/LevelEmitterMode.java index dcdd0ef8..352c966f 100644 --- a/src/api/java/appeng/api/config/LevelEmitterMode.java +++ b/src/api/java/appeng/api/config/LevelEmitterMode.java @@ -23,12 +23,10 @@ package appeng.api.config; +public enum LevelEmitterMode { -public enum LevelEmitterMode -{ + STORED_AMOUNT, - STORED_AMOUNT, - - STORABLE_AMOUNT + STORABLE_AMOUNT } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/LevelType.java b/src/api/java/appeng/api/config/LevelType.java index 0787abb7..86acc0e8 100644 --- a/src/api/java/appeng/api/config/LevelType.java +++ b/src/api/java/appeng/api/config/LevelType.java @@ -23,12 +23,10 @@ package appeng.api.config; +public enum LevelType { -public enum LevelType -{ + ITEM_LEVEL, - ITEM_LEVEL, - - ENERGY_LEVEL + ENERGY_LEVEL } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/ModSettings.java b/src/api/java/appeng/api/config/ModSettings.java index b1225844..8805bcc7 100644 --- a/src/api/java/appeng/api/config/ModSettings.java +++ b/src/api/java/appeng/api/config/ModSettings.java @@ -23,8 +23,6 @@ package appeng.api.config; - -public enum ModSettings -{ +public enum ModSettings { } diff --git a/src/api/java/appeng/api/config/NetworkEmitterMode.java b/src/api/java/appeng/api/config/NetworkEmitterMode.java index 03efd7c9..022cb033 100644 --- a/src/api/java/appeng/api/config/NetworkEmitterMode.java +++ b/src/api/java/appeng/api/config/NetworkEmitterMode.java @@ -23,14 +23,12 @@ package appeng.api.config; +public enum NetworkEmitterMode { -public enum NetworkEmitterMode -{ + POWER_LEVEL, - POWER_LEVEL, + BOOTING, - BOOTING, - - CHANNEL_ERROR + CHANNEL_ERROR } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/OperationMode.java b/src/api/java/appeng/api/config/OperationMode.java index f2c8ff30..93681783 100644 --- a/src/api/java/appeng/api/config/OperationMode.java +++ b/src/api/java/appeng/api/config/OperationMode.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum OperationMode -{ - FILL, EMPTY -} \ No newline at end of file +public enum OperationMode { FILL, EMPTY } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/OutputMode.java b/src/api/java/appeng/api/config/OutputMode.java index f9bcffa5..6975a646 100644 --- a/src/api/java/appeng/api/config/OutputMode.java +++ b/src/api/java/appeng/api/config/OutputMode.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum OutputMode -{ - EXPORT_ONLY, EXPORT_OR_CRAFT, CRAFT_ONLY -} +public enum OutputMode { EXPORT_ONLY, EXPORT_OR_CRAFT, CRAFT_ONLY } diff --git a/src/api/java/appeng/api/config/PowerMultiplier.java b/src/api/java/appeng/api/config/PowerMultiplier.java index dd50e79e..3f2bc472 100644 --- a/src/api/java/appeng/api/config/PowerMultiplier.java +++ b/src/api/java/appeng/api/config/PowerMultiplier.java @@ -23,23 +23,20 @@ package appeng.api.config; +public enum PowerMultiplier { + ONE, + CONFIG; -public enum PowerMultiplier -{ - ONE, CONFIG; + /** + * please do not edit this value, it is set when AE loads its config files. + */ + public double multiplier = 1.0; - /** - * please do not edit this value, it is set when AE loads its config files. - */ - public double multiplier = 1.0; + public double multiply(final double in) { + return in * this.multiplier; + } - public double multiply( final double in ) - { - return in * this.multiplier; - } - - public double divide( final double in ) - { - return in / this.multiplier; - } + public double divide(final double in) { + return in / this.multiplier; + } } diff --git a/src/api/java/appeng/api/config/PowerUnits.java b/src/api/java/appeng/api/config/PowerUnits.java index b6389413..71dd7a6e 100644 --- a/src/api/java/appeng/api/config/PowerUnits.java +++ b/src/api/java/appeng/api/config/PowerUnits.java @@ -23,43 +23,40 @@ package appeng.api.config; +public enum PowerUnits { + AE("gui.appliedenergistics2.units.appliedenergstics"), // Native Units - AE Energy + EU("gui.appliedenergistics2.units.ic2"), // IndustrialCraft 2 - Energy Units + WA("gui.appliedenergistics2.units.rotarycraft"), // RotaryCraft - Watts + RF("gui.appliedenergistics2.units.thermalexpansion" + ), // ThermalExpansion - Redstone Flux + MK("gui.appliedenergistics2.units.mekanism"); // Mekanism - Joules -public enum PowerUnits -{ - AE( "gui.appliedenergistics2.units.appliedenergstics" ), // Native Units - AE Energy - EU( "gui.appliedenergistics2.units.ic2" ), // IndustrialCraft 2 - Energy Units - WA( "gui.appliedenergistics2.units.rotarycraft" ), // RotaryCraft - Watts - RF( "gui.appliedenergistics2.units.thermalexpansion" ), // ThermalExpansion - Redstone Flux - MK( "gui.appliedenergistics2.units.mekanism" ); // Mekanism - Joules + /** + * unlocalized name for the power unit. + */ + public final 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. - */ - public final String unlocalizedName; - /** - * please do not edit this value, it is set when AE loads its config files. - */ - public double conversionRatio = 1.0; - - PowerUnits( final String un ) - { - this.unlocalizedName = un; - } - - /** - * do power conversion using AE's conversion rates. - *

- * Example: PowerUnits.EU.convertTo( PowerUnits.AE, 32 ); - *

- * will normally returns 64, as it will convert the EU, to AE with AE's power settings. - * - * @param target target power unit - * @param value value - * @return value converted to target units, from this units. - */ - public double convertTo( final PowerUnits target, final double value ) - { - return ( value * this.conversionRatio ) / target.conversionRatio; - } + PowerUnits(final String un) { + this.unlocalizedName = un; + } + /** + * do power conversion using AE's conversion rates. + *

+ * Example: PowerUnits.EU.convertTo( PowerUnits.AE, 32 ); + *

+ * will normally returns 64, as it will convert the EU, to AE with AE's power + * settings. + * + * @param target target power unit + * @param value value + * @return value converted to target units, from this units. + */ + public double convertTo(final PowerUnits target, final double value) { + return (value * this.conversionRatio) / target.conversionRatio; + } } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/RedstoneMode.java b/src/api/java/appeng/api/config/RedstoneMode.java index 0bb5a54d..f69d4751 100644 --- a/src/api/java/appeng/api/config/RedstoneMode.java +++ b/src/api/java/appeng/api/config/RedstoneMode.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum RedstoneMode -{ - IGNORE, LOW_SIGNAL, HIGH_SIGNAL, SIGNAL_PULSE -} \ No newline at end of file +public enum RedstoneMode { IGNORE, LOW_SIGNAL, HIGH_SIGNAL, SIGNAL_PULSE } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/RelativeDirection.java b/src/api/java/appeng/api/config/RelativeDirection.java index a81d2047..850e09f7 100644 --- a/src/api/java/appeng/api/config/RelativeDirection.java +++ b/src/api/java/appeng/api/config/RelativeDirection.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum RelativeDirection -{ - LEFT, RIGHT, UP, DOW -} \ No newline at end of file +public enum RelativeDirection { LEFT, RIGHT, UP, DOW } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/SchedulingMode.java b/src/api/java/appeng/api/config/SchedulingMode.java index 395bf1ec..21a3d71d 100644 --- a/src/api/java/appeng/api/config/SchedulingMode.java +++ b/src/api/java/appeng/api/config/SchedulingMode.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum SchedulingMode -{ - DEFAULT, ROUNDROBIN, RANDOM -} +public enum SchedulingMode { DEFAULT, ROUNDROBIN, RANDOM } diff --git a/src/api/java/appeng/api/config/SearchBoxMode.java b/src/api/java/appeng/api/config/SearchBoxMode.java index f2f2408e..552fd125 100644 --- a/src/api/java/appeng/api/config/SearchBoxMode.java +++ b/src/api/java/appeng/api/config/SearchBoxMode.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum SearchBoxMode -{ - AUTOSEARCH, MANUAL_SEARCH, NEI_AUTOSEARCH, NEI_MANUAL_SEARCH -} +public enum SearchBoxMode { AUTOSEARCH, MANUAL_SEARCH, NEI_AUTOSEARCH, NEI_MANUAL_SEARCH } diff --git a/src/api/java/appeng/api/config/SecurityPermissions.java b/src/api/java/appeng/api/config/SecurityPermissions.java index c3e69062..5caae68f 100644 --- a/src/api/java/appeng/api/config/SecurityPermissions.java +++ b/src/api/java/appeng/api/config/SecurityPermissions.java @@ -23,49 +23,47 @@ package appeng.api.config; - /** - * Represent the security systems basic permissions, these are not for anti-griefing, they are part of the mod as a - * gameplay feature. + * Represent the security systems basic permissions, these are not for anti-griefing, they + * are part of the mod as a gameplay feature. */ -public enum SecurityPermissions -{ - /** - * required to insert items into the network via terminal ( also used for machines based on the owner of the - * network, which is determined by its Security Block. ) - */ - INJECT, +public enum SecurityPermissions { + /** + * required to insert items into the network via terminal ( also used for machines + * based on the owner of the network, which is determined by its Security Block. ) + */ + INJECT, - /** - * required to extract items from the network via terminal ( also used for machines based on the owner of the - * network, which is determined by its Security Block. ) - */ - EXTRACT, + /** + * required to extract items from the network via terminal ( also used for machines + * based on the owner of the network, which is determined by its Security Block. ) + */ + EXTRACT, - /** - * required to request crafting from the network via terminal. - */ - CRAFT, + /** + * required to request crafting from the network via terminal. + */ + CRAFT, - /** - * required to modify automation, and make modifications to the networks physical layout. - */ - BUILD, + /** + * required to modify automation, and make modifications to the networks physical + * layout. + */ + BUILD, - /** - * required to modify the security blocks settings. - */ - SECURITY; + /** + * required to modify the security blocks settings. + */ + SECURITY; - private final String unlocalizedName = "gui.appliedenergistics2.security." + this.name().toLowerCase(); + private final String unlocalizedName + = "gui.appliedenergistics2.security." + this.name().toLowerCase(); - public String getUnlocalizedName() - { - return this.unlocalizedName + ".name"; - } + public String getUnlocalizedName() { + return this.unlocalizedName + ".name"; + } - public String getUnlocalizedTip() - { - return this.unlocalizedName + ".tip"; - } + public String getUnlocalizedTip() { + return this.unlocalizedName + ".tip"; + } } diff --git a/src/api/java/appeng/api/config/Settings.java b/src/api/java/appeng/api/config/Settings.java index 672b0306..ed2b5834 100644 --- a/src/api/java/appeng/api/config/Settings.java +++ b/src/api/java/appeng/api/config/Settings.java @@ -23,56 +23,63 @@ package appeng.api.config; - -import javax.annotation.Nonnull; import java.util.EnumSet; +import javax.annotation.Nonnull; +public enum Settings { + LEVEL_EMITTER_MODE(EnumSet.allOf(LevelEmitterMode.class)), -public enum Settings -{ - LEVEL_EMITTER_MODE( EnumSet.allOf( LevelEmitterMode.class ) ), + REDSTONE_EMITTER(EnumSet.of(RedstoneMode.HIGH_SIGNAL, RedstoneMode.LOW_SIGNAL)), + REDSTONE_CONTROLLED(EnumSet.allOf(RedstoneMode.class)), - REDSTONE_EMITTER( EnumSet.of( RedstoneMode.HIGH_SIGNAL, RedstoneMode.LOW_SIGNAL ) ), REDSTONE_CONTROLLED( EnumSet.allOf( RedstoneMode.class ) ), + CONDENSER_OUTPUT(EnumSet.allOf(CondenserOutput.class)), - CONDENSER_OUTPUT( EnumSet.allOf( CondenserOutput.class ) ), + POWER_UNITS(EnumSet.allOf(PowerUnits.class)), + ACCESS(EnumSet.of( + AccessRestriction.READ_WRITE, AccessRestriction.READ, AccessRestriction.WRITE + )), - POWER_UNITS( EnumSet.allOf( PowerUnits.class ) ), ACCESS( EnumSet.of( AccessRestriction.READ_WRITE, AccessRestriction.READ, AccessRestriction.WRITE ) ), + SORT_DIRECTION(EnumSet.allOf(SortDir.class)), + SORT_BY(EnumSet.allOf(SortOrder.class)), - SORT_DIRECTION( EnumSet.allOf( SortDir.class ) ), SORT_BY( EnumSet.allOf( SortOrder.class ) ), + SEARCH_TOOLTIPS(EnumSet.of(YesNo.YES, YesNo.NO)), + VIEW_MODE(EnumSet.allOf(ViewItems.class)), + SEARCH_MODE(EnumSet.allOf(SearchBoxMode.class)), - SEARCH_TOOLTIPS( EnumSet.of( YesNo.YES, YesNo.NO ) ), VIEW_MODE( EnumSet.allOf( ViewItems.class ) ), SEARCH_MODE( EnumSet.allOf( SearchBoxMode.class ) ), + ACTIONS(EnumSet.allOf(ActionItems.class)), + IO_DIRECTION(EnumSet.of(RelativeDirection.LEFT, RelativeDirection.RIGHT)), - ACTIONS( EnumSet.allOf( ActionItems.class ) ), IO_DIRECTION( EnumSet.of( RelativeDirection.LEFT, RelativeDirection.RIGHT ) ), + BLOCK(EnumSet.of(YesNo.YES, YesNo.NO)), + OPERATION_MODE(EnumSet.allOf(OperationMode.class)), - BLOCK( EnumSet.of( YesNo.YES, YesNo.NO ) ), OPERATION_MODE( EnumSet.allOf( OperationMode.class ) ), + FULLNESS_MODE(EnumSet.allOf(FullnessMode.class)), + CRAFT_ONLY(EnumSet.of(YesNo.YES, YesNo.NO)), - FULLNESS_MODE( EnumSet.allOf( FullnessMode.class ) ), CRAFT_ONLY( EnumSet.of( YesNo.YES, YesNo.NO ) ), + FUZZY_MODE(EnumSet.allOf(FuzzyMode.class)), + LEVEL_TYPE(EnumSet.allOf(LevelType.class)), - FUZZY_MODE( EnumSet.allOf( FuzzyMode.class ) ), LEVEL_TYPE( EnumSet.allOf( LevelType.class ) ), + TERMINAL_STYLE(EnumSet.of(TerminalStyle.TALL, TerminalStyle.SMALL)), + COPY_MODE(EnumSet.allOf(CopyMode.class)), - TERMINAL_STYLE( EnumSet.of( TerminalStyle.TALL, TerminalStyle.SMALL ) ), COPY_MODE( EnumSet.allOf( CopyMode.class ) ), + INTERFACE_TERMINAL(EnumSet.of(YesNo.YES, YesNo.NO)), + CRAFT_VIA_REDSTONE(EnumSet.of(YesNo.YES, YesNo.NO)), - INTERFACE_TERMINAL( EnumSet.of( YesNo.YES, YesNo.NO ) ), CRAFT_VIA_REDSTONE( EnumSet.of( YesNo.YES, YesNo.NO ) ), + STORAGE_FILTER(EnumSet.allOf(StorageFilter.class)), + PLACE_BLOCK(EnumSet.of(YesNo.YES, YesNo.NO)), - STORAGE_FILTER( EnumSet.allOf( StorageFilter.class ) ), PLACE_BLOCK( EnumSet.of( YesNo.YES, YesNo.NO ) ), + SCHEDULING_MODE(EnumSet.allOf(SchedulingMode.class)); - SCHEDULING_MODE( EnumSet.allOf( SchedulingMode.class ) ); + private final EnumSet> values; - private final EnumSet> values; + Settings(@Nonnull final EnumSet> possibleOptions) { + if (possibleOptions.isEmpty()) { + throw new IllegalArgumentException("Tried to instantiate an empty setting."); + } - Settings( @Nonnull final EnumSet> possibleOptions ) - { - if( possibleOptions.isEmpty() ) - { - throw new IllegalArgumentException( "Tried to instantiate an empty setting." ); - } - - this.values = possibleOptions; - } - - public EnumSet> getPossibleValues() - { - return this.values; - } + this.values = possibleOptions; + } + public EnumSet> getPossibleValues() { + return this.values; + } } diff --git a/src/api/java/appeng/api/config/SortDir.java b/src/api/java/appeng/api/config/SortDir.java index 654fda0d..a39e4997 100644 --- a/src/api/java/appeng/api/config/SortDir.java +++ b/src/api/java/appeng/api/config/SortDir.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum SortDir -{ - ASCENDING, DESCENDING -} \ No newline at end of file +public enum SortDir { ASCENDING, DESCENDING } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/SortOrder.java b/src/api/java/appeng/api/config/SortOrder.java index 51cde4e6..b76f0e8f 100644 --- a/src/api/java/appeng/api/config/SortOrder.java +++ b/src/api/java/appeng/api/config/SortOrder.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum SortOrder -{ - NAME, AMOUNT, MOD, INVTWEAKS -} \ No newline at end of file +public enum SortOrder { NAME, AMOUNT, MOD, INVTWEAKS } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/StorageFilter.java b/src/api/java/appeng/api/config/StorageFilter.java index 64f63f70..83a08d7b 100644 --- a/src/api/java/appeng/api/config/StorageFilter.java +++ b/src/api/java/appeng/api/config/StorageFilter.java @@ -23,12 +23,10 @@ package appeng.api.config; +public enum StorageFilter { -public enum StorageFilter -{ + NONE, - NONE, - - EXTRACTABLE_ONLY + EXTRACTABLE_ONLY } diff --git a/src/api/java/appeng/api/config/TerminalStyle.java b/src/api/java/appeng/api/config/TerminalStyle.java index d8687e1a..6197b382 100644 --- a/src/api/java/appeng/api/config/TerminalStyle.java +++ b/src/api/java/appeng/api/config/TerminalStyle.java @@ -23,14 +23,12 @@ package appeng.api.config; +public enum TerminalStyle { -public enum TerminalStyle -{ + TALL, - TALL, + FULL, - FULL, - - SMALL + SMALL } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/TunnelType.java b/src/api/java/appeng/api/config/TunnelType.java index 77f2a616..2df83bea 100644 --- a/src/api/java/appeng/api/config/TunnelType.java +++ b/src/api/java/appeng/api/config/TunnelType.java @@ -23,17 +23,15 @@ package appeng.api.config; - -public enum TunnelType -{ - ME, // Network Tunnel - IC2_POWER, // EU Tunnel - RF_POWER, // RF Tunnel - REDSTONE, // Redstone Tunnel - FLUID, // Fluid Tunnel - ITEM, // Item Tunnel - LIGHT, // Light Tunnel - BUNDLED_REDSTONE, // Bundled Redstone Tunnel - COMPUTER_MESSAGE, // Computer Message Tunnel - PRESSURE // PneumaticCraft Tunnel +public enum TunnelType { + ME, // Network Tunnel + IC2_POWER, // EU Tunnel + RF_POWER, // RF Tunnel + REDSTONE, // Redstone Tunnel + FLUID, // Fluid Tunnel + ITEM, // Item Tunnel + LIGHT, // Light Tunnel + BUNDLED_REDSTONE, // Bundled Redstone Tunnel + COMPUTER_MESSAGE, // Computer Message Tunnel + PRESSURE // PneumaticCraft Tunnel } diff --git a/src/api/java/appeng/api/config/Upgrades.java b/src/api/java/appeng/api/config/Upgrades.java index 6667d117..8a5790cf 100644 --- a/src/api/java/appeng/api/config/Upgrades.java +++ b/src/api/java/appeng/api/config/Upgrades.java @@ -23,105 +23,97 @@ package appeng.api.config; +import java.util.HashMap; +import java.util.Map; import appeng.api.definitions.IItemDefinition; import appeng.api.util.AEItemDefinition; import com.google.common.base.Optional; import net.minecraft.item.ItemStack; -import java.util.HashMap; -import java.util.Map; +public enum Upgrades { + /** + * Gold Tier Upgrades. + */ + CAPACITY(0), + REDSTONE(0), + CRAFTING(0), + /** + * Diamond Tier Upgrades. + */ + FUZZY(1), + SPEED(1), + INVERTER(1); -public enum Upgrades -{ - /** - * Gold Tier Upgrades. - */ - CAPACITY( 0 ), REDSTONE( 0 ), CRAFTING( 0 ), + /** + * @deprecated use {@link Upgrades#getTier()} + */ + @Deprecated + public final int tier; - /** - * Diamond Tier Upgrades. - */ - FUZZY( 1 ), SPEED( 1 ), INVERTER( 1 ); + /** + * @deprecated use {@link Upgrades#getSupported()} + */ + @Deprecated + private final Map supportedMax + = new HashMap(); - /** - * @deprecated use {@link Upgrades#getTier()} - */ - @Deprecated - public final int tier; + Upgrades(final int tier) { + this.tier = tier; + } - /** - * @deprecated use {@link Upgrades#getSupported()} - */ - @Deprecated - private final Map supportedMax = new HashMap(); + /** + * @return list of Items/Blocks that support this upgrade, and how many it supports. + */ + public Map getSupported() { + return this.supportedMax; + } - Upgrades( final int tier ) - { - this.tier = tier; - } + /** + * 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 + */ + public void registerItem(final IItemDefinition item, final int maxSupported) { + final Optional maybeStack = item.maybeStack(1); + for (final ItemStack stack : maybeStack.asSet()) { + this.registerItem(stack, maxSupported); + } + } - /** - * @return list of Items/Blocks that support this upgrade, and how many it supports. - */ - public Map getSupported() - { - return this.supportedMax; - } + /** + * 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(final ItemStack stack, final 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 - */ - public void registerItem( final IItemDefinition item, final int maxSupported ) - { - final Optional maybeStack = item.maybeStack( 1 ); - for( final ItemStack stack : maybeStack.asSet() ) - { - this.registerItem( 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)} + */ + @Deprecated + public void registerItem(final AEItemDefinition item, final int maxSupported) { + if (item != null) { + final ItemStack stack = item.stack(1); - /** - * 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( final ItemStack stack, final int maxSupported ) - { - if( stack != null ) - { - this.supportedMax.put( stack, maxSupported ); - } - } + if (stack != null) { + this.registerItem(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)} - */ - @Deprecated - public void registerItem( final AEItemDefinition item, final int maxSupported ) - { - if( item != null ) - { - final ItemStack stack = item.stack( 1 ); - - if( stack != null ) - { - this.registerItem( stack, maxSupported ); - } - } - } - - public int getTier() - { - return this.tier; - } + public int getTier() { + return this.tier; + } } diff --git a/src/api/java/appeng/api/config/ViewItems.java b/src/api/java/appeng/api/config/ViewItems.java index a87e0aa2..02b4090e 100644 --- a/src/api/java/appeng/api/config/ViewItems.java +++ b/src/api/java/appeng/api/config/ViewItems.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum ViewItems -{ - ALL, STORED, CRAFTABLE -} \ No newline at end of file +public enum ViewItems { ALL, STORED, CRAFTABLE } \ No newline at end of file diff --git a/src/api/java/appeng/api/config/YesNo.java b/src/api/java/appeng/api/config/YesNo.java index c6bfcd60..9ac3fe2f 100644 --- a/src/api/java/appeng/api/config/YesNo.java +++ b/src/api/java/appeng/api/config/YesNo.java @@ -23,8 +23,4 @@ package appeng.api.config; - -public enum YesNo -{ - YES, NO, UNDECIDED -} +public enum YesNo { YES, NO, UNDECIDED } diff --git a/src/api/java/appeng/api/definitions/Blocks.java b/src/api/java/appeng/api/definitions/Blocks.java index ec67d54e..c6aee30e 100644 --- a/src/api/java/appeng/api/definitions/Blocks.java +++ b/src/api/java/appeng/api/definitions/Blocks.java @@ -23,109 +23,106 @@ package appeng.api.definitions; - import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IBlocks} now */ @Deprecated -public class Blocks -{ - public AEItemDefinition blockQuartzOre; +public class Blocks { + public AEItemDefinition blockQuartzOre; - public AEItemDefinition blockQuartzOreCharged; + public AEItemDefinition blockQuartzOreCharged; - public AEItemDefinition blockMatrixFrame; + public AEItemDefinition blockMatrixFrame; - public AEItemDefinition blockQuartz; + public AEItemDefinition blockQuartz; - public AEItemDefinition blockQuartzPillar; + public AEItemDefinition blockQuartzPillar; - public AEItemDefinition blockQuartzChiseled; + public AEItemDefinition blockQuartzChiseled; - public AEItemDefinition blockQuartzGlass; + public AEItemDefinition blockQuartzGlass; - public AEItemDefinition blockQuartzVibrantGlass; + public AEItemDefinition blockQuartzVibrantGlass; - public AEItemDefinition blockQuartzTorch; + public AEItemDefinition blockQuartzTorch; - public AEItemDefinition blockFluix; + public AEItemDefinition blockFluix; - public AEItemDefinition blockSkyStone; + public AEItemDefinition blockSkyStone; - public AEItemDefinition blockSkyChest; + public AEItemDefinition blockSkyChest; - public AEItemDefinition blockSkyCompass; + public AEItemDefinition blockSkyCompass; - public AEItemDefinition blockGrindStone; + public AEItemDefinition blockGrindStone; - public AEItemDefinition blockCrankHandle; + public AEItemDefinition blockCrankHandle; - public AEItemDefinition blockInscriber; + public AEItemDefinition blockInscriber; - public AEItemDefinition blockWireless; + public AEItemDefinition blockWireless; - public AEItemDefinition blockCharger; + public AEItemDefinition blockCharger; - public AEItemDefinition blockTinyTNT; + public AEItemDefinition blockTinyTNT; - public AEItemDefinition blockSecurity; + public AEItemDefinition blockSecurity; - public AEItemDefinition blockQuantumRing; + public AEItemDefinition blockQuantumRing; - public AEItemDefinition blockQuantumLink; + public AEItemDefinition blockQuantumLink; - public AEItemDefinition blockSpatialPylon; + public AEItemDefinition blockSpatialPylon; - public AEItemDefinition blockSpatialIOPort; + public AEItemDefinition blockSpatialIOPort; - public AEItemDefinition blockMultiPart; + public AEItemDefinition blockMultiPart; - public AEItemDefinition blockController; + public AEItemDefinition blockController; - public AEItemDefinition blockDrive; + public AEItemDefinition blockDrive; - public AEItemDefinition blockChest; + public AEItemDefinition blockChest; - public AEItemDefinition blockInterface; + public AEItemDefinition blockInterface; - public AEItemDefinition blockCellWorkbench; + public AEItemDefinition blockCellWorkbench; - public AEItemDefinition blockIOPort; + public AEItemDefinition blockIOPort; - public AEItemDefinition blockCondenser; + public AEItemDefinition blockCondenser; - public AEItemDefinition blockEnergyAcceptor; + public AEItemDefinition blockEnergyAcceptor; - public AEItemDefinition blockVibrationChamber; + public AEItemDefinition blockVibrationChamber; - public AEItemDefinition blockQuartzGrowthAccelerator; + public AEItemDefinition blockQuartzGrowthAccelerator; - public AEItemDefinition blockEnergyCell; + public AEItemDefinition blockEnergyCell; - public AEItemDefinition blockEnergyCellDense; + public AEItemDefinition blockEnergyCellDense; - public AEItemDefinition blockEnergyCellCreative; + public AEItemDefinition blockEnergyCellCreative; - public AEItemDefinition blockCraftingUnit; + public AEItemDefinition blockCraftingUnit; - public AEItemDefinition blockCraftingAccelerator; + public AEItemDefinition blockCraftingAccelerator; - public AEItemDefinition blockCraftingStorage1k; + public AEItemDefinition blockCraftingStorage1k; - public AEItemDefinition blockCraftingStorage4k; + public AEItemDefinition blockCraftingStorage4k; - public AEItemDefinition blockCraftingStorage16k; + public AEItemDefinition blockCraftingStorage16k; - public AEItemDefinition blockCraftingStorage64k; + public AEItemDefinition blockCraftingStorage64k; - public AEItemDefinition blockCraftingMonitor; + public AEItemDefinition blockCraftingMonitor; - public AEItemDefinition blockMolecularAssembler; + public AEItemDefinition blockMolecularAssembler; - public AEItemDefinition blockLightDetector; + public AEItemDefinition blockLightDetector; - public AEItemDefinition blockPaint; + public AEItemDefinition blockPaint; } diff --git a/src/api/java/appeng/api/definitions/IBlockDefinition.java b/src/api/java/appeng/api/definitions/IBlockDefinition.java index a08795e1..f5ef6770 100644 --- a/src/api/java/appeng/api/definitions/IBlockDefinition.java +++ b/src/api/java/appeng/api/definitions/IBlockDefinition.java @@ -1,32 +1,29 @@ package appeng.api.definitions; - import com.google.common.base.Optional; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.world.IBlockAccess; +public interface IBlockDefinition extends IItemDefinition { + /** + * @return the {@link Block} implementation if applicable + */ + Optional maybeBlock(); -public interface IBlockDefinition extends IItemDefinition -{ - /** - * @return the {@link Block} implementation if applicable - */ - Optional maybeBlock(); + /** + * @return the {@link ItemBlock} implementation if applicable + */ + Optional maybeItemBlock(); - /** - * @return the {@link ItemBlock} implementation if applicable - */ - Optional maybeItemBlock(); - - /** - * 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 - * @return if the block is placed in the world at the specific location. - */ - boolean isSameAs( IBlockAccess world, int x, int y, int z ); + /** + * 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 + * @return if the block is placed in the world at the specific location. + */ + boolean isSameAs(IBlockAccess world, int x, int y, int z); } diff --git a/src/api/java/appeng/api/definitions/IBlocks.java b/src/api/java/appeng/api/definitions/IBlocks.java index e4a5368c..a0c39692 100644 --- a/src/api/java/appeng/api/definitions/IBlocks.java +++ b/src/api/java/appeng/api/definitions/IBlocks.java @@ -23,159 +23,157 @@ package appeng.api.definitions; - /** * A list of all blocks in AE */ -public interface IBlocks -{ - /* - * world gen - */ - IBlockDefinition quartzOre(); +public interface IBlocks { + /* + * world gen + */ + IBlockDefinition quartzOre(); - IBlockDefinition quartzOreCharged(); + IBlockDefinition quartzOreCharged(); - IBlockDefinition matrixFrame(); + IBlockDefinition matrixFrame(); - /* - * decorative - */ - IBlockDefinition quartz(); + /* + * decorative + */ + IBlockDefinition quartz(); - IBlockDefinition quartzPillar(); + IBlockDefinition quartzPillar(); - IBlockDefinition quartzChiseled(); + IBlockDefinition quartzChiseled(); - IBlockDefinition quartzGlass(); + IBlockDefinition quartzGlass(); - IBlockDefinition quartzVibrantGlass(); + IBlockDefinition quartzVibrantGlass(); - IBlockDefinition quartzTorch(); + IBlockDefinition quartzTorch(); - IBlockDefinition fluix(); + IBlockDefinition fluix(); - IBlockDefinition skyStone(); + IBlockDefinition skyStone(); - IBlockDefinition skyChest(); + IBlockDefinition skyChest(); - IBlockDefinition skyCompass(); + IBlockDefinition skyCompass(); - IBlockDefinition skyStoneStair(); + IBlockDefinition skyStoneStair(); - IBlockDefinition skyStoneBlockStair(); + IBlockDefinition skyStoneBlockStair(); - IBlockDefinition skyStoneBrickStair(); + IBlockDefinition skyStoneBrickStair(); - IBlockDefinition skyStoneSmallBrickStair(); + IBlockDefinition skyStoneSmallBrickStair(); - IBlockDefinition fluixStair(); + IBlockDefinition fluixStair(); - IBlockDefinition quartzStair(); + IBlockDefinition quartzStair(); - IBlockDefinition chiseledQuartzStair(); + IBlockDefinition chiseledQuartzStair(); - IBlockDefinition quartzPillarStair(); + IBlockDefinition quartzPillarStair(); - IBlockDefinition skyStoneSlab(); + IBlockDefinition skyStoneSlab(); - IBlockDefinition skyStoneBlockSlab(); + IBlockDefinition skyStoneBlockSlab(); - IBlockDefinition skyStoneBrickSlab(); + IBlockDefinition skyStoneBrickSlab(); - IBlockDefinition skyStoneSmallBrickSlab(); + IBlockDefinition skyStoneSmallBrickSlab(); - IBlockDefinition fluixSlab(); + IBlockDefinition fluixSlab(); - IBlockDefinition quartzSlab(); + IBlockDefinition quartzSlab(); - IBlockDefinition chiseledQuartzSlab(); + IBlockDefinition chiseledQuartzSlab(); - IBlockDefinition quartzPillarSlab(); + IBlockDefinition quartzPillarSlab(); - /* - * misc - */ - ITileDefinition grindStone(); + /* + * misc + */ + ITileDefinition grindStone(); - ITileDefinition crankHandle(); + ITileDefinition crankHandle(); - ITileDefinition inscriber(); + ITileDefinition inscriber(); - ITileDefinition wireless(); + ITileDefinition wireless(); - ITileDefinition charger(); + ITileDefinition charger(); - IBlockDefinition tinyTNT(); + IBlockDefinition tinyTNT(); - ITileDefinition security(); + ITileDefinition security(); - /* - * quantum Network Bridge - */ - ITileDefinition quantumRing(); + /* + * quantum Network Bridge + */ + ITileDefinition quantumRing(); - ITileDefinition quantumLink(); + ITileDefinition quantumLink(); - /* - * spatial iO - */ - ITileDefinition spatialPylon(); + /* + * spatial iO + */ + ITileDefinition spatialPylon(); - ITileDefinition spatialIOPort(); + ITileDefinition spatialIOPort(); - /* - * Bus / cables - */ - ITileDefinition multiPart(); + /* + * Bus / cables + */ + ITileDefinition multiPart(); - /* - * machines - */ - ITileDefinition controller(); + /* + * machines + */ + ITileDefinition controller(); - ITileDefinition drive(); + ITileDefinition drive(); - ITileDefinition chest(); + ITileDefinition chest(); - ITileDefinition iface(); + ITileDefinition iface(); - ITileDefinition cellWorkbench(); + ITileDefinition cellWorkbench(); - ITileDefinition iOPort(); + ITileDefinition iOPort(); - ITileDefinition condenser(); + ITileDefinition condenser(); - ITileDefinition energyAcceptor(); + ITileDefinition energyAcceptor(); - ITileDefinition vibrationChamber(); + ITileDefinition vibrationChamber(); - ITileDefinition quartzGrowthAccelerator(); + ITileDefinition quartzGrowthAccelerator(); - ITileDefinition energyCell(); + ITileDefinition energyCell(); - ITileDefinition energyCellDense(); + ITileDefinition energyCellDense(); - ITileDefinition energyCellCreative(); + ITileDefinition energyCellCreative(); - // rv1 - ITileDefinition craftingUnit(); + // rv1 + ITileDefinition craftingUnit(); - ITileDefinition craftingAccelerator(); + ITileDefinition craftingAccelerator(); - ITileDefinition craftingStorage1k(); + ITileDefinition craftingStorage1k(); - ITileDefinition craftingStorage4k(); + ITileDefinition craftingStorage4k(); - ITileDefinition craftingStorage16k(); + ITileDefinition craftingStorage16k(); - ITileDefinition craftingStorage64k(); + ITileDefinition craftingStorage64k(); - ITileDefinition craftingMonitor(); + ITileDefinition craftingMonitor(); - ITileDefinition molecularAssembler(); + ITileDefinition molecularAssembler(); - ITileDefinition lightDetector(); + ITileDefinition lightDetector(); - ITileDefinition paint(); + ITileDefinition paint(); } diff --git a/src/api/java/appeng/api/definitions/IComparableDefinition.java b/src/api/java/appeng/api/definitions/IComparableDefinition.java index c172c5ef..eb8a6262 100644 --- a/src/api/java/appeng/api/definitions/IComparableDefinition.java +++ b/src/api/java/appeng/api/definitions/IComparableDefinition.java @@ -1,10 +1,8 @@ package appeng.api.definitions; - import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; - /** * Interface to compare a definition with an itemstack or a block * @@ -12,26 +10,26 @@ import net.minecraft.world.IBlockAccess; * @version rv2 * @since rv2 */ -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 ); +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); - /** - * 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 - * @return if the block is placed in the world at the specific location. - * @deprecated moved to {@link IBlockDefinition}. Is removed in the next major release rv3 - */ - @Deprecated - boolean isSameAs( IBlockAccess world, int x, int y, int z ); + /** + * 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 + * @return if the block is placed in the world at the specific location. + * @deprecated moved to {@link IBlockDefinition}. Is removed in the next major release + * rv3 + */ + @Deprecated + boolean isSameAs(IBlockAccess world, int x, int y, int z); } diff --git a/src/api/java/appeng/api/definitions/IDefinitions.java b/src/api/java/appeng/api/definitions/IDefinitions.java index 354f8899..c07968ab 100644 --- a/src/api/java/appeng/api/definitions/IDefinitions.java +++ b/src/api/java/appeng/api/definitions/IDefinitions.java @@ -23,29 +23,27 @@ package appeng.api.definitions; - /** * All definitions in AE */ -public interface IDefinitions -{ - /** - * @return an accessible list of all of AE's blocks - */ - IBlocks blocks(); +public interface IDefinitions { + /** + * @return an accessible list of all of AE's blocks + */ + IBlocks blocks(); - /** - * @return an accessible list of all of AE's Items - */ - IItems items(); + /** + * @return an accessible list of all of AE's Items + */ + IItems items(); - /** - * @return an accessible list of all of AE's materials; materials are items - */ - IMaterials materials(); + /** + * @return an accessible list of all of AE's materials; materials are items + */ + IMaterials materials(); - /** - * @return an accessible list of all of AE's parts, parts are items - */ - IParts parts(); + /** + * @return an accessible list of all of AE's parts, parts are items + */ + IParts parts(); } diff --git a/src/api/java/appeng/api/definitions/IItemDefinition.java b/src/api/java/appeng/api/definitions/IItemDefinition.java index 80ca2d7d..10c68345 100644 --- a/src/api/java/appeng/api/definitions/IItemDefinition.java +++ b/src/api/java/appeng/api/definitions/IItemDefinition.java @@ -23,26 +23,23 @@ package appeng.api.definitions; - import com.google.common.base.Optional; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public interface IItemDefinition extends IComparableDefinition { + /** + * @return the {@link Item} Implementation if applicable + */ + Optional maybeItem(); -public interface IItemDefinition extends IComparableDefinition -{ - /** - * @return the {@link Item} Implementation if applicable - */ - Optional maybeItem(); + /** + * @return an {@link ItemStack} with specified quantity of this item. + */ + Optional maybeStack(int stackSize); - /** - * @return an {@link ItemStack} with specified quantity of this item. - */ - Optional maybeStack( int stackSize ); - - /** - * @return true if definition is enabled - */ - boolean isEnabled(); + /** + * @return true if definition is enabled + */ + boolean isEnabled(); } diff --git a/src/api/java/appeng/api/definitions/IItems.java b/src/api/java/appeng/api/definitions/IItems.java index 5ea20f2a..d8486a29 100644 --- a/src/api/java/appeng/api/definitions/IItems.java +++ b/src/api/java/appeng/api/definitions/IItems.java @@ -23,87 +23,84 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; - /** * A list of all items in AE */ -public interface IItems -{ - IItemDefinition certusQuartzAxe(); +public interface IItems { + IItemDefinition certusQuartzAxe(); - IItemDefinition certusQuartzHoe(); + IItemDefinition certusQuartzHoe(); - IItemDefinition certusQuartzShovel(); + IItemDefinition certusQuartzShovel(); - IItemDefinition certusQuartzPick(); + IItemDefinition certusQuartzPick(); - IItemDefinition certusQuartzSword(); + IItemDefinition certusQuartzSword(); - IItemDefinition certusQuartzWrench(); + IItemDefinition certusQuartzWrench(); - IItemDefinition certusQuartzKnife(); + IItemDefinition certusQuartzKnife(); - IItemDefinition netherQuartzAxe(); + IItemDefinition netherQuartzAxe(); - IItemDefinition netherQuartzHoe(); + IItemDefinition netherQuartzHoe(); - IItemDefinition netherQuartzShovel(); + IItemDefinition netherQuartzShovel(); - IItemDefinition netherQuartzPick(); + IItemDefinition netherQuartzPick(); - IItemDefinition netherQuartzSword(); + IItemDefinition netherQuartzSword(); - IItemDefinition netherQuartzWrench(); + IItemDefinition netherQuartzWrench(); - IItemDefinition netherQuartzKnife(); + IItemDefinition netherQuartzKnife(); - IItemDefinition entropyManipulator(); + IItemDefinition entropyManipulator(); - IItemDefinition wirelessTerminal(); + IItemDefinition wirelessTerminal(); - IItemDefinition biometricCard(); + IItemDefinition biometricCard(); - IItemDefinition chargedStaff(); + IItemDefinition chargedStaff(); - IItemDefinition massCannon(); + IItemDefinition massCannon(); - IItemDefinition memoryCard(); + IItemDefinition memoryCard(); - IItemDefinition networkTool(); + IItemDefinition networkTool(); - IItemDefinition portableCell(); + IItemDefinition portableCell(); - IItemDefinition cellCreative(); + IItemDefinition cellCreative(); - IItemDefinition viewCell(); + IItemDefinition viewCell(); - IItemDefinition cell1k(); + IItemDefinition cell1k(); - IItemDefinition cell4k(); + IItemDefinition cell4k(); - IItemDefinition cell16k(); + IItemDefinition cell16k(); - IItemDefinition cell64k(); + IItemDefinition cell64k(); - IItemDefinition spatialCell2(); + IItemDefinition spatialCell2(); - IItemDefinition spatialCell16(); + IItemDefinition spatialCell16(); - IItemDefinition spatialCell128(); + IItemDefinition spatialCell128(); - IItemDefinition facade(); + IItemDefinition facade(); - IItemDefinition crystalSeed(); + IItemDefinition crystalSeed(); - // rv1 - IItemDefinition encodedPattern(); + // rv1 + IItemDefinition encodedPattern(); - IItemDefinition colorApplicator(); + IItemDefinition colorApplicator(); - AEColoredItemDefinition coloredPaintBall(); + AEColoredItemDefinition coloredPaintBall(); - AEColoredItemDefinition coloredLumenPaintBall(); + AEColoredItemDefinition coloredLumenPaintBall(); } diff --git a/src/api/java/appeng/api/definitions/IMaterials.java b/src/api/java/appeng/api/definitions/IMaterials.java index 8a52bfd5..4527deb1 100644 --- a/src/api/java/appeng/api/definitions/IMaterials.java +++ b/src/api/java/appeng/api/definitions/IMaterials.java @@ -23,117 +23,115 @@ package appeng.api.definitions; - /** * A list of all materials in AE */ -public interface IMaterials -{ - IItemDefinition cell2SpatialPart(); +public interface IMaterials { + IItemDefinition cell2SpatialPart(); - IItemDefinition cell16SpatialPart(); + IItemDefinition cell16SpatialPart(); - IItemDefinition cell128SpatialPart(); + IItemDefinition cell128SpatialPart(); - IItemDefinition silicon(); + IItemDefinition silicon(); - IItemDefinition skyDust(); + IItemDefinition skyDust(); - IItemDefinition calcProcessorPress(); + IItemDefinition calcProcessorPress(); - IItemDefinition engProcessorPress(); + IItemDefinition engProcessorPress(); - IItemDefinition logicProcessorPress(); + IItemDefinition logicProcessorPress(); - IItemDefinition calcProcessorPrint(); + IItemDefinition calcProcessorPrint(); - IItemDefinition engProcessorPrint(); + IItemDefinition engProcessorPrint(); - IItemDefinition logicProcessorPrint(); + IItemDefinition logicProcessorPrint(); - IItemDefinition siliconPress(); + IItemDefinition siliconPress(); - IItemDefinition siliconPrint(); + IItemDefinition siliconPrint(); - IItemDefinition namePress(); + IItemDefinition namePress(); - IItemDefinition logicProcessor(); + IItemDefinition logicProcessor(); - IItemDefinition calcProcessor(); + IItemDefinition calcProcessor(); - IItemDefinition engProcessor(); + IItemDefinition engProcessor(); - IItemDefinition basicCard(); + IItemDefinition basicCard(); - IItemDefinition advCard(); + IItemDefinition advCard(); - IItemDefinition purifiedCertusQuartzCrystal(); + IItemDefinition purifiedCertusQuartzCrystal(); - IItemDefinition purifiedNetherQuartzCrystal(); + IItemDefinition purifiedNetherQuartzCrystal(); - IItemDefinition purifiedFluixCrystal(); + IItemDefinition purifiedFluixCrystal(); - IItemDefinition cell1kPart(); + IItemDefinition cell1kPart(); - IItemDefinition cell4kPart(); + IItemDefinition cell4kPart(); - IItemDefinition cell16kPart(); + IItemDefinition cell16kPart(); - IItemDefinition cell64kPart(); + IItemDefinition cell64kPart(); - IItemDefinition emptyStorageCell(); + IItemDefinition emptyStorageCell(); - IItemDefinition cardRedstone(); + IItemDefinition cardRedstone(); - IItemDefinition cardSpeed(); + IItemDefinition cardSpeed(); - IItemDefinition cardCapacity(); + IItemDefinition cardCapacity(); - IItemDefinition cardFuzzy(); + IItemDefinition cardFuzzy(); - IItemDefinition cardInverter(); + IItemDefinition cardInverter(); - IItemDefinition cardCrafting(); + IItemDefinition cardCrafting(); - IItemDefinition enderDust(); + IItemDefinition enderDust(); - IItemDefinition flour(); + IItemDefinition flour(); - IItemDefinition goldDust(); + IItemDefinition goldDust(); - IItemDefinition ironDust(); + IItemDefinition ironDust(); - IItemDefinition fluixDust(); + IItemDefinition fluixDust(); - IItemDefinition certusQuartzDust(); + IItemDefinition certusQuartzDust(); - IItemDefinition netherQuartzDust(); + IItemDefinition netherQuartzDust(); - IItemDefinition matterBall(); + IItemDefinition matterBall(); - IItemDefinition ironNugget(); + IItemDefinition ironNugget(); - IItemDefinition certusQuartzCrystal(); + IItemDefinition certusQuartzCrystal(); - IItemDefinition certusQuartzCrystalCharged(); + IItemDefinition certusQuartzCrystalCharged(); - IItemDefinition fluixCrystal(); + IItemDefinition fluixCrystal(); - IItemDefinition fluixPearl(); + IItemDefinition fluixPearl(); - IItemDefinition woodenGear(); + IItemDefinition woodenGear(); - IItemDefinition wireless(); + IItemDefinition wireless(); - IItemDefinition wirelessBooster(); + IItemDefinition wirelessBooster(); - IItemDefinition annihilationCore(); + IItemDefinition annihilationCore(); - IItemDefinition formationCore(); + IItemDefinition formationCore(); - IItemDefinition singularity(); + IItemDefinition singularity(); - IItemDefinition qESingularity(); + IItemDefinition qESingularity(); - IItemDefinition blankPattern(); + IItemDefinition blankPattern(); } diff --git a/src/api/java/appeng/api/definitions/IParts.java b/src/api/java/appeng/api/definitions/IParts.java index 79f83dd8..eac85d2c 100644 --- a/src/api/java/appeng/api/definitions/IParts.java +++ b/src/api/java/appeng/api/definitions/IParts.java @@ -23,88 +23,85 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; - /** * A list of all parts in AE */ -public interface IParts -{ - AEColoredItemDefinition cableSmart(); +public interface IParts { + AEColoredItemDefinition cableSmart(); - AEColoredItemDefinition cableCovered(); + AEColoredItemDefinition cableCovered(); - AEColoredItemDefinition cableGlass(); + AEColoredItemDefinition cableGlass(); - AEColoredItemDefinition cableDense(); + AEColoredItemDefinition cableDense(); - AEColoredItemDefinition lumenCableSmart(); + AEColoredItemDefinition lumenCableSmart(); - AEColoredItemDefinition lumenCableCovered(); + AEColoredItemDefinition lumenCableCovered(); - AEColoredItemDefinition lumenCableGlass(); + AEColoredItemDefinition lumenCableGlass(); - AEColoredItemDefinition lumenCableDense(); + AEColoredItemDefinition lumenCableDense(); - IItemDefinition quartzFiber(); + IItemDefinition quartzFiber(); - IItemDefinition toggleBus(); + IItemDefinition toggleBus(); - IItemDefinition invertedToggleBus(); + IItemDefinition invertedToggleBus(); - IItemDefinition storageBus(); + IItemDefinition storageBus(); - IItemDefinition importBus(); + IItemDefinition importBus(); - IItemDefinition exportBus(); + IItemDefinition exportBus(); - IItemDefinition iface(); + IItemDefinition iface(); - IItemDefinition levelEmitter(); + IItemDefinition levelEmitter(); - IItemDefinition annihilationPlane(); + IItemDefinition annihilationPlane(); - IItemDefinition identityAnnihilationPlane(); + IItemDefinition identityAnnihilationPlane(); - IItemDefinition formationPlane(); + IItemDefinition formationPlane(); - IItemDefinition p2PTunnelME(); + IItemDefinition p2PTunnelME(); - IItemDefinition p2PTunnelRedstone(); + IItemDefinition p2PTunnelRedstone(); - IItemDefinition p2PTunnelItems(); + IItemDefinition p2PTunnelItems(); - IItemDefinition p2PTunnelLiquids(); + IItemDefinition p2PTunnelLiquids(); - IItemDefinition p2PTunnelEU(); + IItemDefinition p2PTunnelEU(); - IItemDefinition p2PTunnelRF(); + IItemDefinition p2PTunnelRF(); - IItemDefinition p2PTunnelLight(); + IItemDefinition p2PTunnelLight(); - IItemDefinition p2PTunnelOpenComputers(); + IItemDefinition p2PTunnelOpenComputers(); - IItemDefinition p2PTunnelPneumaticCraft(); + IItemDefinition p2PTunnelPneumaticCraft(); - IItemDefinition cableAnchor(); + IItemDefinition cableAnchor(); - IItemDefinition monitor(); + IItemDefinition monitor(); - IItemDefinition semiDarkMonitor(); + IItemDefinition semiDarkMonitor(); - IItemDefinition darkMonitor(); + IItemDefinition darkMonitor(); - IItemDefinition interfaceTerminal(); + IItemDefinition interfaceTerminal(); - IItemDefinition patternTerminal(); + IItemDefinition patternTerminal(); - IItemDefinition craftingTerminal(); + IItemDefinition craftingTerminal(); - IItemDefinition terminal(); + IItemDefinition terminal(); - IItemDefinition storageMonitor(); + IItemDefinition storageMonitor(); - IItemDefinition conversionMonitor(); + IItemDefinition conversionMonitor(); } diff --git a/src/api/java/appeng/api/definitions/ITileDefinition.java b/src/api/java/appeng/api/definitions/ITileDefinition.java index 8660fa60..794c20ce 100644 --- a/src/api/java/appeng/api/definitions/ITileDefinition.java +++ b/src/api/java/appeng/api/definitions/ITileDefinition.java @@ -1,14 +1,11 @@ package appeng.api.definitions; - import com.google.common.base.Optional; import net.minecraft.tileentity.TileEntity; - -public interface ITileDefinition extends IBlockDefinition -{ - /** - * @return the {@link TileEntity} Class if applicable. - */ - Optional> maybeEntity(); +public interface ITileDefinition extends IBlockDefinition { + /** + * @return the {@link TileEntity} Class if applicable. + */ + Optional> maybeEntity(); } diff --git a/src/api/java/appeng/api/definitions/Items.java b/src/api/java/appeng/api/definitions/Items.java index 09c24262..d0061338 100644 --- a/src/api/java/appeng/api/definitions/Items.java +++ b/src/api/java/appeng/api/definitions/Items.java @@ -23,88 +23,85 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IItems} */ @Deprecated -public class Items -{ - public AEItemDefinition itemCertusQuartzAxe; +public class Items { + public AEItemDefinition itemCertusQuartzAxe; - public AEItemDefinition itemCertusQuartzHoe; + public AEItemDefinition itemCertusQuartzHoe; - public AEItemDefinition itemCertusQuartzShovel; + public AEItemDefinition itemCertusQuartzShovel; - public AEItemDefinition itemCertusQuartzPick; + public AEItemDefinition itemCertusQuartzPick; - public AEItemDefinition itemCertusQuartzSword; + public AEItemDefinition itemCertusQuartzSword; - public AEItemDefinition itemCertusQuartzWrench; + public AEItemDefinition itemCertusQuartzWrench; - public AEItemDefinition itemCertusQuartzKnife; + public AEItemDefinition itemCertusQuartzKnife; - public AEItemDefinition itemNetherQuartzAxe; + public AEItemDefinition itemNetherQuartzAxe; - public AEItemDefinition itemNetherQuartzHoe; + public AEItemDefinition itemNetherQuartzHoe; - public AEItemDefinition itemNetherQuartzShovel; + public AEItemDefinition itemNetherQuartzShovel; - public AEItemDefinition itemNetherQuartzPick; + public AEItemDefinition itemNetherQuartzPick; - public AEItemDefinition itemNetherQuartzSword; + public AEItemDefinition itemNetherQuartzSword; - public AEItemDefinition itemNetherQuartzWrench; + public AEItemDefinition itemNetherQuartzWrench; - public AEItemDefinition itemNetherQuartzKnife; + public AEItemDefinition itemNetherQuartzKnife; - public AEItemDefinition itemEntropyManipulator; + public AEItemDefinition itemEntropyManipulator; - public AEItemDefinition itemWirelessTerminal; + public AEItemDefinition itemWirelessTerminal; - public AEItemDefinition itemBiometricCard; + public AEItemDefinition itemBiometricCard; - public AEItemDefinition itemChargedStaff; + public AEItemDefinition itemChargedStaff; - public AEItemDefinition itemMassCannon; + public AEItemDefinition itemMassCannon; - public AEItemDefinition itemMemoryCard; + public AEItemDefinition itemMemoryCard; - public AEItemDefinition itemNetworkTool; + public AEItemDefinition itemNetworkTool; - public AEItemDefinition itemPortableCell; + public AEItemDefinition itemPortableCell; - public AEItemDefinition itemCellCreative; + public AEItemDefinition itemCellCreative; - public AEItemDefinition itemViewCell; + public AEItemDefinition itemViewCell; - public AEItemDefinition itemCell1k; + public AEItemDefinition itemCell1k; - public AEItemDefinition itemCell4k; + public AEItemDefinition itemCell4k; - public AEItemDefinition itemCell16k; + public AEItemDefinition itemCell16k; - public AEItemDefinition itemCell64k; + public AEItemDefinition itemCell64k; - public AEItemDefinition itemSpatialCell2; + public AEItemDefinition itemSpatialCell2; - public AEItemDefinition itemSpatialCell16; + public AEItemDefinition itemSpatialCell16; - public AEItemDefinition itemSpatialCell128; + public AEItemDefinition itemSpatialCell128; - public AEItemDefinition itemFacade; + public AEItemDefinition itemFacade; - public AEItemDefinition itemCrystalSeed; + public AEItemDefinition itemCrystalSeed; - public AEItemDefinition itemEncodedPattern; + public AEItemDefinition itemEncodedPattern; - public AEItemDefinition itemColorApplicator; + public AEItemDefinition itemColorApplicator; - public AEColoredItemDefinition itemPaintBall; + public AEColoredItemDefinition itemPaintBall; - public AEColoredItemDefinition itemLumenPaintBall; + public AEColoredItemDefinition itemLumenPaintBall; } diff --git a/src/api/java/appeng/api/definitions/Materials.java b/src/api/java/appeng/api/definitions/Materials.java index 88696474..e47827cb 100644 --- a/src/api/java/appeng/api/definitions/Materials.java +++ b/src/api/java/appeng/api/definitions/Materials.java @@ -23,121 +23,118 @@ package appeng.api.definitions; - import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IMaterials} */ @Deprecated -public class Materials -{ - public AEItemDefinition materialCell2SpatialPart; +public class Materials { + public AEItemDefinition materialCell2SpatialPart; - public AEItemDefinition materialCell16SpatialPart; + public AEItemDefinition materialCell16SpatialPart; - public AEItemDefinition materialCell128SpatialPart; + public AEItemDefinition materialCell128SpatialPart; - public AEItemDefinition materialSilicon; + public AEItemDefinition materialSilicon; - public AEItemDefinition materialSkyDust; + public AEItemDefinition materialSkyDust; - public AEItemDefinition materialCalcProcessorPress; + public AEItemDefinition materialCalcProcessorPress; - public AEItemDefinition materialEngProcessorPress; + public AEItemDefinition materialEngProcessorPress; - public AEItemDefinition materialLogicProcessorPress; + public AEItemDefinition materialLogicProcessorPress; - public AEItemDefinition materialCalcProcessorPrint; + public AEItemDefinition materialCalcProcessorPrint; - public AEItemDefinition materialEngProcessorPrint; + public AEItemDefinition materialEngProcessorPrint; - public AEItemDefinition materialLogicProcessorPrint; + public AEItemDefinition materialLogicProcessorPrint; - public AEItemDefinition materialSiliconPress; + public AEItemDefinition materialSiliconPress; - public AEItemDefinition materialSiliconPrint; + public AEItemDefinition materialSiliconPrint; - public AEItemDefinition materialNamePress; + public AEItemDefinition materialNamePress; - public AEItemDefinition materialLogicProcessor; + public AEItemDefinition materialLogicProcessor; - public AEItemDefinition materialCalcProcessor; + public AEItemDefinition materialCalcProcessor; - public AEItemDefinition materialEngProcessor; + public AEItemDefinition materialEngProcessor; - public AEItemDefinition materialBasicCard; + public AEItemDefinition materialBasicCard; - public AEItemDefinition materialAdvCard; + public AEItemDefinition materialAdvCard; - public AEItemDefinition materialPurifiedCertusQuartzCrystal; + public AEItemDefinition materialPurifiedCertusQuartzCrystal; - public AEItemDefinition materialPurifiedNetherQuartzCrystal; + public AEItemDefinition materialPurifiedNetherQuartzCrystal; - public AEItemDefinition materialPurifiedFluixCrystal; + public AEItemDefinition materialPurifiedFluixCrystal; - public AEItemDefinition materialCell1kPart; + public AEItemDefinition materialCell1kPart; - public AEItemDefinition materialCell4kPart; + public AEItemDefinition materialCell4kPart; - public AEItemDefinition materialCell16kPart; + public AEItemDefinition materialCell16kPart; - public AEItemDefinition materialCell64kPart; + public AEItemDefinition materialCell64kPart; - public AEItemDefinition materialEmptyStorageCell; + public AEItemDefinition materialEmptyStorageCell; - public AEItemDefinition materialCardRedstone; + public AEItemDefinition materialCardRedstone; - public AEItemDefinition materialCardSpeed; + public AEItemDefinition materialCardSpeed; - public AEItemDefinition materialCardCapacity; + public AEItemDefinition materialCardCapacity; - public AEItemDefinition materialCardFuzzy; + public AEItemDefinition materialCardFuzzy; - public AEItemDefinition materialCardInverter; + public AEItemDefinition materialCardInverter; - public AEItemDefinition materialCardCrafting; + public AEItemDefinition materialCardCrafting; - public AEItemDefinition materialEnderDust; + public AEItemDefinition materialEnderDust; - public AEItemDefinition materialFlour; + public AEItemDefinition materialFlour; - public AEItemDefinition materialGoldDust; + public AEItemDefinition materialGoldDust; - public AEItemDefinition materialIronDust; + public AEItemDefinition materialIronDust; - public AEItemDefinition materialFluixDust; + public AEItemDefinition materialFluixDust; - public AEItemDefinition materialCertusQuartzDust; + public AEItemDefinition materialCertusQuartzDust; - public AEItemDefinition materialNetherQuartzDust; + public AEItemDefinition materialNetherQuartzDust; - public AEItemDefinition materialMatterBall; + public AEItemDefinition materialMatterBall; - public AEItemDefinition materialIronNugget; + public AEItemDefinition materialIronNugget; - public AEItemDefinition materialCertusQuartzCrystal; + public AEItemDefinition materialCertusQuartzCrystal; - public AEItemDefinition materialCertusQuartzCrystalCharged; + public AEItemDefinition materialCertusQuartzCrystalCharged; - public AEItemDefinition materialFluixCrystal; + public AEItemDefinition materialFluixCrystal; - public AEItemDefinition materialFluixPearl; + public AEItemDefinition materialFluixPearl; - public AEItemDefinition materialWoodenGear; + public AEItemDefinition materialWoodenGear; - public AEItemDefinition materialWireless; + public AEItemDefinition materialWireless; - public AEItemDefinition materialWirelessBooster; + public AEItemDefinition materialWirelessBooster; - public AEItemDefinition materialAnnihilationCore; + public AEItemDefinition materialAnnihilationCore; - public AEItemDefinition materialFormationCore; + public AEItemDefinition materialFormationCore; - public AEItemDefinition materialSingularity; + public AEItemDefinition materialSingularity; - public AEItemDefinition materialQESingularity; + public AEItemDefinition materialQESingularity; - public AEItemDefinition materialBlankPattern; + public AEItemDefinition materialBlankPattern; } diff --git a/src/api/java/appeng/api/definitions/Parts.java b/src/api/java/appeng/api/definitions/Parts.java index 1d728a35..af7a36b6 100644 --- a/src/api/java/appeng/api/definitions/Parts.java +++ b/src/api/java/appeng/api/definitions/Parts.java @@ -23,84 +23,81 @@ package appeng.api.definitions; - import appeng.api.util.AEColoredItemDefinition; import appeng.api.util.AEItemDefinition; - /** * @deprecated use {@link IParts} */ @Deprecated -public class Parts -{ - public AEColoredItemDefinition partCableSmart; +public class Parts { + public AEColoredItemDefinition partCableSmart; - public AEColoredItemDefinition partCableCovered; + public AEColoredItemDefinition partCableCovered; - public AEColoredItemDefinition partCableGlass; + public AEColoredItemDefinition partCableGlass; - public AEColoredItemDefinition partCableDense; + public AEColoredItemDefinition partCableDense; - public AEColoredItemDefinition partLumenCableSmart; + public AEColoredItemDefinition partLumenCableSmart; - public AEColoredItemDefinition partLumenCableCovered; + public AEColoredItemDefinition partLumenCableCovered; - public AEColoredItemDefinition partLumenCableGlass; + public AEColoredItemDefinition partLumenCableGlass; - public AEColoredItemDefinition partLumenCableDense; + public AEColoredItemDefinition partLumenCableDense; - public AEItemDefinition partQuartzFiber; + public AEItemDefinition partQuartzFiber; - public AEItemDefinition partToggleBus; + public AEItemDefinition partToggleBus; - public AEItemDefinition partInvertedToggleBus; + public AEItemDefinition partInvertedToggleBus; - public AEItemDefinition partStorageBus; + public AEItemDefinition partStorageBus; - public AEItemDefinition partImportBus; + public AEItemDefinition partImportBus; - public AEItemDefinition partExportBus; + public AEItemDefinition partExportBus; - public AEItemDefinition partInterface; + public AEItemDefinition partInterface; - public AEItemDefinition partLevelEmitter; + public AEItemDefinition partLevelEmitter; - public AEItemDefinition partAnnihilationPlane; + public AEItemDefinition partAnnihilationPlane; - public AEItemDefinition partFormationPlane; + public AEItemDefinition partFormationPlane; - public AEItemDefinition partP2PTunnelME; + public AEItemDefinition partP2PTunnelME; - public AEItemDefinition partP2PTunnelRedstone; + public AEItemDefinition partP2PTunnelRedstone; - public AEItemDefinition partP2PTunnelItems; + public AEItemDefinition partP2PTunnelItems; - public AEItemDefinition partP2PTunnelLiquids; + public AEItemDefinition partP2PTunnelLiquids; - public AEItemDefinition partP2PTunnelEU; + public AEItemDefinition partP2PTunnelEU; - public AEItemDefinition partP2PTunnelRF; + public AEItemDefinition partP2PTunnelRF; - public AEItemDefinition partP2PTunnelLight; + public AEItemDefinition partP2PTunnelLight; - public AEItemDefinition partCableAnchor; + public AEItemDefinition partCableAnchor; - public AEItemDefinition partMonitor; + public AEItemDefinition partMonitor; - public AEItemDefinition partSemiDarkMonitor; + public AEItemDefinition partSemiDarkMonitor; - public AEItemDefinition partDarkMonitor; + public AEItemDefinition partDarkMonitor; - public AEItemDefinition partInterfaceTerminal; + public AEItemDefinition partInterfaceTerminal; - public AEItemDefinition partPatternTerminal; + public AEItemDefinition partPatternTerminal; - public AEItemDefinition partCraftingTerminal; + public AEItemDefinition partCraftingTerminal; - public AEItemDefinition partTerminal; + public AEItemDefinition partTerminal; - public AEItemDefinition partStorageMonitor; + public AEItemDefinition partStorageMonitor; - public AEItemDefinition partConversionMonitor; + public AEItemDefinition partConversionMonitor; } diff --git a/src/api/java/appeng/api/events/LocatableEventAnnounce.java b/src/api/java/appeng/api/events/LocatableEventAnnounce.java index af641544..95baf4e3 100644 --- a/src/api/java/appeng/api/events/LocatableEventAnnounce.java +++ b/src/api/java/appeng/api/events/LocatableEventAnnounce.java @@ -23,31 +23,25 @@ package appeng.api.events; - import appeng.api.features.ILocatable; import cpw.mods.fml.common.eventhandler.Event; - /** * Input Event: *

* Used to Notify the Location Registry of objects, and their availability. */ -public class LocatableEventAnnounce extends Event -{ +public class LocatableEventAnnounce extends Event { + public final ILocatable target; + public final LocatableEvent change; - public final ILocatable target; - public final LocatableEvent change; + public LocatableEventAnnounce(final ILocatable o, final LocatableEvent ev) { + this.target = o; + this.change = ev; + } - public LocatableEventAnnounce( final ILocatable o, final LocatableEvent ev ) - { - this.target = o; - this.change = ev; - } - - public enum LocatableEvent - { - Register, // Adds the locatable to the registry - Unregister // Removes the locatable from the registry - } + 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/exceptions/AppEngException.java b/src/api/java/appeng/api/exceptions/AppEngException.java index 478cfd77..d68c24fe 100644 --- a/src/api/java/appeng/api/exceptions/AppEngException.java +++ b/src/api/java/appeng/api/exceptions/AppEngException.java @@ -23,14 +23,10 @@ package appeng.api.exceptions; +public class AppEngException extends Exception { + private static final long serialVersionUID = -9051434206368465494L; -public class AppEngException extends Exception -{ - - private static final long serialVersionUID = -9051434206368465494L; - - public AppEngException( final String t ) - { - super( t ); - } + public AppEngException(final String t) { + super(t); + } } diff --git a/src/api/java/appeng/api/exceptions/CoreInaccessibleException.java b/src/api/java/appeng/api/exceptions/CoreInaccessibleException.java index 88a5725f..ed8480e4 100644 --- a/src/api/java/appeng/api/exceptions/CoreInaccessibleException.java +++ b/src/api/java/appeng/api/exceptions/CoreInaccessibleException.java @@ -1,10 +1,7 @@ package appeng.api.exceptions; - -public class CoreInaccessibleException extends RuntimeException -{ - public CoreInaccessibleException( final String message ) - { - super( message ); - } +public class CoreInaccessibleException extends RuntimeException { + public CoreInaccessibleException(final String message) { + super(message); + } } diff --git a/src/api/java/appeng/api/exceptions/ExistingConnectionException.java b/src/api/java/appeng/api/exceptions/ExistingConnectionException.java index 4d2cb082..7112fa1e 100644 --- a/src/api/java/appeng/api/exceptions/ExistingConnectionException.java +++ b/src/api/java/appeng/api/exceptions/ExistingConnectionException.java @@ -23,34 +23,27 @@ package appeng.api.exceptions; - import appeng.api.networking.IGridNode; - /** - * Exception occurred because of an already existing connection between the two {@link IGridNode}s - *

- * Intended to signal an internal exception and not intended to be thrown by - * any 3rd party module. + * Exception occurred because of an already existing connection between the two {@link + * IGridNode}s

Intended to signal an internal exception and not intended to be thrown + * by any 3rd party module. * * @author yueh * @version rv3 * @since rv3 */ -public class ExistingConnectionException extends FailedConnection -{ +public class ExistingConnectionException extends FailedConnection { + private static final long serialVersionUID = 2975450379720353182L; + private static final String DEFAULT_MESSAGE + = "Connection between both nodes already exists."; - private static final long serialVersionUID = 2975450379720353182L; - private static final String DEFAULT_MESSAGE = "Connection between both nodes already exists."; - - public ExistingConnectionException() - { - super( DEFAULT_MESSAGE ); - } - - public ExistingConnectionException( String message ) - { - super( message ); - } + public ExistingConnectionException() { + super(DEFAULT_MESSAGE); + } + public ExistingConnectionException(String message) { + super(message); + } } diff --git a/src/api/java/appeng/api/exceptions/FailedConnection.java b/src/api/java/appeng/api/exceptions/FailedConnection.java index 65072eea..516410df 100644 --- a/src/api/java/appeng/api/exceptions/FailedConnection.java +++ b/src/api/java/appeng/api/exceptions/FailedConnection.java @@ -23,10 +23,8 @@ package appeng.api.exceptions; - import appeng.api.networking.IGridNode; - /** * Exception indicating a failed connection between two {@link IGridNode}s. *

@@ -40,17 +38,12 @@ import appeng.api.networking.IGridNode; * @version rv3 * @since rv0 */ -public class FailedConnection extends Exception -{ +public class FailedConnection extends Exception { + private static final long serialVersionUID = -2544208090248293753L; - private static final long serialVersionUID = -2544208090248293753L; + public FailedConnection() {} - public FailedConnection() - { - } - - public FailedConnection( String message ) - { - super( message ); - } + public FailedConnection(String message) { + super(message); + } } diff --git a/src/api/java/appeng/api/exceptions/MissingDefinition.java b/src/api/java/appeng/api/exceptions/MissingDefinition.java index f920a9e9..c7bcba3c 100644 --- a/src/api/java/appeng/api/exceptions/MissingDefinition.java +++ b/src/api/java/appeng/api/exceptions/MissingDefinition.java @@ -1,10 +1,7 @@ package appeng.api.exceptions; - -public class MissingDefinition extends RuntimeException -{ - public MissingDefinition( final String message ) - { - super( message ); - } +public class MissingDefinition extends RuntimeException { + public MissingDefinition(final String message) { + super(message); + } } diff --git a/src/api/java/appeng/api/exceptions/MissingIngredientError.java b/src/api/java/appeng/api/exceptions/MissingIngredientError.java index 81fe40d3..88b60dd9 100644 --- a/src/api/java/appeng/api/exceptions/MissingIngredientError.java +++ b/src/api/java/appeng/api/exceptions/MissingIngredientError.java @@ -23,14 +23,10 @@ package appeng.api.exceptions; +public class MissingIngredientError extends Exception { + private static final long serialVersionUID = -998858343831371697L; -public class MissingIngredientError extends Exception -{ - - private static final long serialVersionUID = -998858343831371697L; - - public MissingIngredientError( final String n ) - { - super( n ); - } + public MissingIngredientError(final String n) { + super(n); + } } diff --git a/src/api/java/appeng/api/exceptions/ModNotInstalled.java b/src/api/java/appeng/api/exceptions/ModNotInstalled.java index a3c5eb05..fa2383ec 100644 --- a/src/api/java/appeng/api/exceptions/ModNotInstalled.java +++ b/src/api/java/appeng/api/exceptions/ModNotInstalled.java @@ -23,14 +23,10 @@ package appeng.api.exceptions; +public class ModNotInstalled extends Exception { + private static final long serialVersionUID = -9052435206368425494L; -public class ModNotInstalled extends Exception -{ - - private static final long serialVersionUID = -9052435206368425494L; - - public ModNotInstalled( final String t ) - { - super( t ); - } + public ModNotInstalled(final String t) { + super(t); + } } diff --git a/src/api/java/appeng/api/exceptions/NullNodeConnectionException.java b/src/api/java/appeng/api/exceptions/NullNodeConnectionException.java index 30f3fe0c..493909f1 100644 --- a/src/api/java/appeng/api/exceptions/NullNodeConnectionException.java +++ b/src/api/java/appeng/api/exceptions/NullNodeConnectionException.java @@ -23,7 +23,6 @@ package appeng.api.exceptions; - /** * Exception due to trying to connect one or more null values. *

@@ -34,20 +33,16 @@ package appeng.api.exceptions; * @version rv3 * @since rv3 */ -public class NullNodeConnectionException extends FailedConnection -{ +public class NullNodeConnectionException extends FailedConnection { + private static final long serialVersionUID = -2143719383495321764L; + private static final String DEFAULT_MESSAGE + = "Connection forged between null entities."; - private static final long serialVersionUID = -2143719383495321764L; - private static final String DEFAULT_MESSAGE = "Connection forged between null entities."; - - public NullNodeConnectionException() - { - super( DEFAULT_MESSAGE ); - } - - public NullNodeConnectionException( String message ) - { - super( message ); - } + public NullNodeConnectionException() { + super(DEFAULT_MESSAGE); + } + public NullNodeConnectionException(String message) { + super(message); + } } diff --git a/src/api/java/appeng/api/exceptions/RecipeError.java b/src/api/java/appeng/api/exceptions/RecipeError.java index d4d6f90a..160b892a 100644 --- a/src/api/java/appeng/api/exceptions/RecipeError.java +++ b/src/api/java/appeng/api/exceptions/RecipeError.java @@ -23,14 +23,10 @@ package appeng.api.exceptions; +public class RecipeError extends Exception { + private static final long serialVersionUID = -6602870588617670262L; -public class RecipeError extends Exception -{ - - private static final long serialVersionUID = -6602870588617670262L; - - public RecipeError( final String n ) - { - super( n ); - } + public RecipeError(final String n) { + super(n); + } } diff --git a/src/api/java/appeng/api/exceptions/RegistrationError.java b/src/api/java/appeng/api/exceptions/RegistrationError.java index 205df3e9..65414a04 100644 --- a/src/api/java/appeng/api/exceptions/RegistrationError.java +++ b/src/api/java/appeng/api/exceptions/RegistrationError.java @@ -23,14 +23,10 @@ package appeng.api.exceptions; +public class RegistrationError extends Exception { + private static final long serialVersionUID = -6602870588617670263L; -public class RegistrationError extends Exception -{ - - private static final long serialVersionUID = -6602870588617670263L; - - public RegistrationError( final String n ) - { - super( n ); - } + public RegistrationError(final String n) { + super(n); + } } diff --git a/src/api/java/appeng/api/exceptions/SecurityConnectionException.java b/src/api/java/appeng/api/exceptions/SecurityConnectionException.java index 267377da..492c2707 100644 --- a/src/api/java/appeng/api/exceptions/SecurityConnectionException.java +++ b/src/api/java/appeng/api/exceptions/SecurityConnectionException.java @@ -23,7 +23,6 @@ package appeng.api.exceptions; - /** * Exception due to trying to connect different security realms. *

@@ -34,19 +33,16 @@ package appeng.api.exceptions; * @version rv3 * @since rv3 */ -public class SecurityConnectionException extends FailedConnection -{ - private static final long serialVersionUID = 5048714900434215426L; - private static final String DEFAULT_MESSAGE = "Connection failed due to different security realms."; +public class SecurityConnectionException extends FailedConnection { + private static final long serialVersionUID = 5048714900434215426L; + private static final String DEFAULT_MESSAGE + = "Connection failed due to different security realms."; - public SecurityConnectionException() - { - super( DEFAULT_MESSAGE ); - } - - public SecurityConnectionException( String message ) - { - super( message ); - } + public SecurityConnectionException() { + super(DEFAULT_MESSAGE); + } + public SecurityConnectionException(String message) { + super(message); + } } diff --git a/src/api/java/appeng/api/features/IGrinderEntry.java b/src/api/java/appeng/api/features/IGrinderEntry.java index 1667f12c..4cec6d96 100644 --- a/src/api/java/appeng/api/features/IGrinderEntry.java +++ b/src/api/java/appeng/api/features/IGrinderEntry.java @@ -23,99 +23,95 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; - /** * Registration Records for {@link IGrinderRegistry} */ -public interface IGrinderEntry -{ +public interface IGrinderEntry { + /** + * the current input + * + * @return input that the grinder will accept. + */ + ItemStack getInput(); - /** - * the current input - * - * @return input that the grinder will accept. - */ - ItemStack getInput(); + /** + * lets you change the grinder recipe by changing its input. + * + * @param input input item + */ + void setInput(ItemStack input); - /** - * lets you change the grinder recipe by changing its input. - * - * @param input input item - */ - void setInput( ItemStack input ); + /** + * gets the current output + * + * @return output that the grinder will produce + */ + ItemStack getOutput(); - /** - * gets the current output - * - * @return output that the grinder will produce - */ - ItemStack getOutput(); + /** + * allows you to change the output. + * + * @param output output item + */ + void setOutput(ItemStack output); - /** - * allows you to change the output. - * - * @param output output item - */ - void setOutput( ItemStack output ); + /** + * gets the current output + * + * @return output that the grinder will produce + */ + ItemStack getOptionalOutput(); - /** - * gets the current output - * - * @return output that the grinder will produce - */ - ItemStack getOptionalOutput(); + /** + * gets the current output + * + * @return output that the grinder will produce + */ + ItemStack getSecondOptionalOutput(); - /** - * gets the current output - * - * @return output that the grinder will produce - */ - ItemStack getSecondOptionalOutput(); + /** + * stack, and 0.0-1.0 chance that it will be generated. + * + * @param output output item + * @param chance generation chance + */ + void setOptionalOutput(ItemStack output, float chance); - /** - * stack, and 0.0-1.0 chance that it will be generated. - * - * @param output output item - * @param chance generation chance - */ - void setOptionalOutput( ItemStack output, float chance ); + /** + * 0.0 - 1.0 the chance that the optional output will be generated. + * + * @return chance of optional output + */ + float getOptionalChance(); - /** - * 0.0 - 1.0 the chance that the optional output will be generated. - * - * @return chance of optional output - */ - float getOptionalChance(); + /** + * stack, and 0.0-1.0 chance that it will be generated. + * + * @param output second optional output item + * @param chance second optional output chance + */ + void setSecondOptionalOutput(ItemStack output, float chance); - /** - * stack, and 0.0-1.0 chance that it will be generated. - * - * @param output second optional output item - * @param chance second optional output chance - */ - void setSecondOptionalOutput( ItemStack output, float chance ); + /** + * 0.0 - 1.0 the chance that the optional output will be generated. + * + * @return second optional output chance + */ + float getSecondOptionalChance(); - /** - * 0.0 - 1.0 the chance that the optional output will be generated. - * - * @return second optional output chance - */ - float getSecondOptionalChance(); + /** + * Energy cost, in turns. + * + * @return number of turns it takes to produce the output from the input. + */ + int getEnergyCost(); - /** - * Energy cost, in turns. - * - * @return number of turns it takes to produce the output from the input. - */ - int getEnergyCost(); - - /** - * Allows you to adjust the number of turns - * - * @param c number of turns to produce output. - */ - void setEnergyCost( int c ); + /** + * Allows you to adjust the number of turns + * + * @param c number of turns to produce output. + */ + void setEnergyCost(int c); } diff --git a/src/api/java/appeng/api/features/IGrinderRegistry.java b/src/api/java/appeng/api/features/IGrinderRegistry.java index 9fc9f74d..88948aff 100644 --- a/src/api/java/appeng/api/features/IGrinderRegistry.java +++ b/src/api/java/appeng/api/features/IGrinderRegistry.java @@ -23,63 +23,69 @@ package appeng.api.features; - -import net.minecraft.item.ItemStack; - import java.util.List; +import net.minecraft.item.ItemStack; /** * Lets you manipulate Grinder Recipes, by adding or editing existing ones. */ -public interface IGrinderRegistry -{ +public interface IGrinderRegistry { + /** + * Current list of registered recipes, you can modify this if you want too. + * + * @return currentlyRegisteredRecipes + */ + List getRecipes(); - /** - * Current list of registered recipes, you can modify this if you want too. - * - * @return currentlyRegisteredRecipes - */ - List getRecipes(); + /** + * add a new recipe the easy way, in → out, how many turns., duplicates will not + * be added. + * + * @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); - /** - * add a new recipe the easy way, in → out, how many turns., duplicates will not be added. - * - * @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 ); + /** + * 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 turns amount of turns to turn the input into the outputs + */ + void + addRecipe(ItemStack in, ItemStack out, ItemStack optional, float chance, int turns); - /** - * 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 turns amount of turns to turn the input into the outputs - */ - void addRecipe( ItemStack in, ItemStack out, ItemStack optional, float chance, int turns ); + /** + * 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 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 + */ + void addRecipe( + ItemStack in, + ItemStack out, + ItemStack optional, + float chance, + ItemStack optional2, + float chance2, + int turns + ); - /** - * 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 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 - */ - void addRecipe( ItemStack in, ItemStack out, ItemStack optional, float chance, ItemStack optional2, float chance2, int turns ); - - /** - * Searches for a recipe for a given input, and returns it. - * - * @param input input - * @return identified recipe or null - */ - IGrinderEntry getRecipeForInput( ItemStack input ); + /** + * Searches for a recipe for a given input, and returns it. + * + * @param input input + * @return identified recipe or null + */ + IGrinderEntry getRecipeForInput(ItemStack input); } diff --git a/src/api/java/appeng/api/features/IInscriberRecipe.java b/src/api/java/appeng/api/features/IInscriberRecipe.java index 1137436d..370480cc 100644 --- a/src/api/java/appeng/api/features/IInscriberRecipe.java +++ b/src/api/java/appeng/api/features/IInscriberRecipe.java @@ -1,13 +1,11 @@ package appeng.api.features; +import java.util.List; +import javax.annotation.Nonnull; import com.google.common.base.Optional; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import java.util.List; - - /** * Registration Records for {@link IInscriberRegistry} *

@@ -20,45 +18,44 @@ import java.util.List; * @version rv2 * @since rv2 */ -public interface IInscriberRecipe -{ - /** - * the current inputs - * - * @return inputs the inscriber will accept - */ - @Nonnull - List getInputs(); +public interface IInscriberRecipe { + /** + * the current inputs + * + * @return inputs the inscriber will accept + */ + @Nonnull + List getInputs(); - /** - * gets the current output - * - * @return output that the recipe will produce - */ - @Nonnull - ItemStack getOutput(); + /** + * gets the current output + * + * @return output that the recipe will produce + */ + @Nonnull + ItemStack getOutput(); - /** - * gets the top optional - * - * @return item which is used top - */ - @Nonnull - Optional getTopOptional(); + /** + * gets the top optional + * + * @return item which is used top + */ + @Nonnull + Optional getTopOptional(); - /** - * gets the bottom optional - * - * @return item which is used bottom - */ - @Nonnull - Optional getBottomOptional(); + /** + * gets the bottom optional + * + * @return item which is used bottom + */ + @Nonnull + Optional getBottomOptional(); - /** - * type of inscriber process - * - * @return type of process the inscriber is doing - */ - @Nonnull - InscriberProcessType getProcessType(); + /** + * type of inscriber process + * + * @return type of process the inscriber is doing + */ + @Nonnull + InscriberProcessType getProcessType(); } diff --git a/src/api/java/appeng/api/features/IInscriberRecipeBuilder.java b/src/api/java/appeng/api/features/IInscriberRecipeBuilder.java index 99e2fdaf..5bd4bc99 100644 --- a/src/api/java/appeng/api/features/IInscriberRecipeBuilder.java +++ b/src/api/java/appeng/api/features/IInscriberRecipeBuilder.java @@ -1,12 +1,10 @@ package appeng.api.features; +import java.util.Collection; +import javax.annotation.Nonnull; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import java.util.Collection; - - /** * Builder for an inscriber recipe * @@ -14,69 +12,68 @@ import java.util.Collection; * @version rv2 * @since rv2 */ -public interface IInscriberRecipeBuilder -{ - /** - * Creates an inscriber recipe with inputs. - * Needs to be invoked. - * - * @param inputs new inputs for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withInputs( @Nonnull Collection inputs ); +public interface IInscriberRecipeBuilder { + /** + * Creates an inscriber recipe with inputs. + * Needs to be invoked. + * + * @param inputs new inputs for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withInputs(@Nonnull Collection inputs); - /** - * Creates an inscriber recipe with output. - * Needs to be invoked. - * - * @param output new output for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withOutput( @Nonnull ItemStack output ); + /** + * Creates an inscriber recipe with output. + * Needs to be invoked. + * + * @param output new output for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withOutput(@Nonnull ItemStack output); - /** - * Creates an inscriber recipe with top. - * Either this or bot needs to be invoked. - * - * @param topOptional new top for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withTopOptional( @Nonnull ItemStack topOptional ); + /** + * Creates an inscriber recipe with top. + * Either this or bot needs to be invoked. + * + * @param topOptional new top for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withTopOptional(@Nonnull ItemStack topOptional); - /** - * Creates an inscriber recipe with bot. - * Either this or top needs to be invoked. - * - * @param bottomOptional new bot for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withBottomOptional( @Nonnull ItemStack bottomOptional ); + /** + * Creates an inscriber recipe with bot. + * Either this or top needs to be invoked. + * + * @param bottomOptional new bot for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withBottomOptional(@Nonnull ItemStack bottomOptional); - /** - * Creates an inscriber recipe with type. - * Needs to be invoked. - * - * @param type new type for the recipe - * @return currently used builder - */ - @Nonnull - IInscriberRecipeBuilder withProcessType( @Nonnull InscriberProcessType type ); + /** + * Creates an inscriber recipe with type. + * Needs to be invoked. + * + * @param type new type for the recipe + * @return currently used builder + */ + @Nonnull + IInscriberRecipeBuilder withProcessType(@Nonnull InscriberProcessType type); - /** - * Finalizes the process of making the recipe. - * Needs to be invoked to fetch inscriber recipe. - * - * @return legal inscriber recipe - * @throws IllegalStateException when input is not defined - * @throws IllegalStateException when input has no size - * @throws IllegalStateException when output is not defined - * @throws IllegalStateException when both optionals are not defined - * @throws IllegalStateException when process type is not defined - */ - @Nonnull - IInscriberRecipe build(); + /** + * Finalizes the process of making the recipe. + * Needs to be invoked to fetch inscriber recipe. + * + * @return legal inscriber recipe + * @throws IllegalStateException when input is not defined + * @throws IllegalStateException when input has no size + * @throws IllegalStateException when output is not defined + * @throws IllegalStateException when both optionals are not defined + * @throws IllegalStateException when process type is not defined + */ + @Nonnull + IInscriberRecipe build(); } diff --git a/src/api/java/appeng/api/features/IInscriberRegistry.java b/src/api/java/appeng/api/features/IInscriberRegistry.java index c4337332..bb82933e 100644 --- a/src/api/java/appeng/api/features/IInscriberRegistry.java +++ b/src/api/java/appeng/api/features/IInscriberRegistry.java @@ -1,12 +1,10 @@ package appeng.api.features; - -import net.minecraft.item.ItemStack; - -import javax.annotation.Nonnull; import java.util.Collection; import java.util.Set; +import javax.annotation.Nonnull; +import net.minecraft.item.ItemStack; /** * Lets you manipulate Inscriber Recipes, by adding or editing existing ones. @@ -15,58 +13,56 @@ import java.util.Set; * @version rv3 * @since rv2 */ -public interface IInscriberRegistry -{ - /** - * An immutable copy of currently registered recipes. - *

- * Use the provided methods to actually modify the inscriber recipes. - * - * @return currentlyRegisteredRecipes - * @see IInscriberRegistry#addRecipe(IInscriberRecipe) - * @see IInscriberRegistry#removeRecipe(IInscriberRecipe) - */ - @Nonnull - Collection getRecipes(); +public interface IInscriberRegistry { + /** + * An immutable copy of currently registered recipes. + *

+ * Use the provided methods to actually modify the inscriber recipes. + * + * @return currentlyRegisteredRecipes + * @see IInscriberRegistry#addRecipe(IInscriberRecipe) + * @see IInscriberRegistry#removeRecipe(IInscriberRecipe) + */ + @Nonnull + Collection getRecipes(); - /** - * Optional items which are used in the top or bottom slot. - * - * @return set of all optional items - */ - @Nonnull - Set getOptionals(); + /** + * Optional items which are used in the top or bottom slot. + * + * @return set of all optional items + */ + @Nonnull + Set getOptionals(); - /** - * Get all registered items which are valid inputs. - * - * @return set of all input items - */ - @Nonnull - Set getInputs(); + /** + * Get all registered items which are valid inputs. + * + * @return set of all input items + */ + @Nonnull + Set getInputs(); - /** - * Extensible way to create an inscriber recipe. - * - * @return builder for inscriber recipes - */ - @Nonnull - IInscriberRecipeBuilder builder(); + /** + * Extensible way to create an inscriber recipe. + * + * @return builder for inscriber recipes + */ + @Nonnull + IInscriberRecipeBuilder builder(); - /** - * add a new recipe the easy way, duplicates will not be added. - * Added recipes will be automatically added to the optionals and inputs. - * - * @param recipe new recipe - * @throws IllegalArgumentException if null is added - */ - void addRecipe( IInscriberRecipe recipe ); - - /** - * Removes all equal recipes from the registry. - * - * @param toBeRemovedRecipe to be removed recipe, can be null, makes just no sense. - */ - void removeRecipe( IInscriberRecipe toBeRemovedRecipe ); + /** + * add a new recipe the easy way, duplicates will not be added. + * Added recipes will be automatically added to the optionals and inputs. + * + * @param recipe new recipe + * @throws IllegalArgumentException if null is added + */ + void addRecipe(IInscriberRecipe recipe); + /** + * Removes all equal recipes from the registry. + * + * @param toBeRemovedRecipe to be removed recipe, can be null, makes just no sense. + */ + void removeRecipe(IInscriberRecipe toBeRemovedRecipe); } diff --git a/src/api/java/appeng/api/features/IItemComparison.java b/src/api/java/appeng/api/features/IItemComparison.java index b7d2b982..ce2ef184 100644 --- a/src/api/java/appeng/api/features/IItemComparison.java +++ b/src/api/java/appeng/api/features/IItemComparison.java @@ -23,10 +23,8 @@ package appeng.api.features; +public interface IItemComparison { + boolean sameAsPrecise(IItemComparison comp); -public interface IItemComparison -{ - boolean sameAsPrecise( IItemComparison comp ); - - boolean sameAsFuzzy( IItemComparison comp ); + boolean sameAsFuzzy(IItemComparison comp); } diff --git a/src/api/java/appeng/api/features/IItemComparisonProvider.java b/src/api/java/appeng/api/features/IItemComparisonProvider.java index 4c21c3a8..b13fbd55 100644 --- a/src/api/java/appeng/api/features/IItemComparisonProvider.java +++ b/src/api/java/appeng/api/features/IItemComparisonProvider.java @@ -23,32 +23,28 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; - /** * Provider for special comparisons. when an item is encountered AE Will request * if the comparison function handles the item, by trying to request a * IItemComparison class. */ -public interface IItemComparisonProvider -{ +public interface IItemComparisonProvider { + /** + * should return a new IItemComparison, or return null if it doesn't handle + * the supplied item. + * + * @param is item + * @return IItemComparison, or null + */ + IItemComparison getComparison(ItemStack is); - /** - * should return a new IItemComparison, or return null if it doesn't handle - * the supplied item. - * - * @param is item - * @return IItemComparison, or null - */ - IItemComparison getComparison( ItemStack is ); - - /** - * Simple test for support ( AE generally skips this and calls the above function. ) - * - * @param stack item - * @return true, if getComparison will return a valid IItemComparison Object - */ - boolean canHandle( ItemStack stack ); + /** + * Simple test for support ( AE generally skips this and calls the above function. ) + * + * @param stack item + * @return true, if getComparison will return a valid IItemComparison Object + */ + boolean canHandle(ItemStack stack); } \ No newline at end of file diff --git a/src/api/java/appeng/api/features/ILocatable.java b/src/api/java/appeng/api/features/ILocatable.java index c64a937f..02cfdd6f 100644 --- a/src/api/java/appeng/api/features/ILocatable.java +++ b/src/api/java/appeng/api/features/ILocatable.java @@ -23,19 +23,15 @@ package appeng.api.features; - import appeng.api.events.LocatableEventAnnounce; - /** - * A registration record for the {@link ILocatableRegistry} use the {@link LocatableEventAnnounce} event on the Forge - * Event bus to update the registry. + * A registration record for the {@link ILocatableRegistry} use the {@link + * LocatableEventAnnounce} event on the Forge Event bus to update the registry. */ -public interface ILocatable -{ - - /** - * @return the serial for a locatable object - */ - long getLocatableSerial(); +public interface ILocatable { + /** + * @return the serial for a locatable object + */ + long getLocatableSerial(); } \ No newline at end of file diff --git a/src/api/java/appeng/api/features/ILocatableRegistry.java b/src/api/java/appeng/api/features/ILocatableRegistry.java index 853638b8..ee002436 100644 --- a/src/api/java/appeng/api/features/ILocatableRegistry.java +++ b/src/api/java/appeng/api/features/ILocatableRegistry.java @@ -23,28 +23,26 @@ package appeng.api.features; - /** * A Registry for locatable items, works based on serial numbers. */ -public interface ILocatableRegistry -{ - /** - * Attempts to find the object with the serial specified, if it can it - * returns the object. - * - * @param serial serial - * @return requestedObject, or null - * @deprecated use {@link ILocatableRegistry#getLocatableBy(long)} - */ - @Deprecated - Object findLocatableBySerial( long serial ); +public interface ILocatableRegistry { + /** + * Attempts to find the object with the serial specified, if it can it + * returns the object. + * + * @param serial serial + * @return requestedObject, or null + * @deprecated use {@link ILocatableRegistry#getLocatableBy(long)} + */ + @Deprecated + Object findLocatableBySerial(long serial); - /** - * Gets the {@link ILocatable} with the registered serial, if available - * - * @param serial serial - * @return requestedObject, or null, if the object does not exist anymore - */ - ILocatable getLocatableBy( long serial ); + /** + * Gets the {@link ILocatable} with the registered serial, if available + * + * @param serial serial + * @return requestedObject, or null, if the object does not exist anymore + */ + ILocatable getLocatableBy(long serial); } \ No newline at end of file diff --git a/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java b/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java index c73eff50..b08ae3ce 100644 --- a/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java +++ b/src/api/java/appeng/api/features/IMatterCannonAmmoRegistry.java @@ -23,26 +23,23 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; +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 weight atomic weight + */ + void registerAmmo(ItemStack ammo, double weight); -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 weight atomic weight - */ - void registerAmmo( ItemStack ammo, double weight ); - - /** - * get the penetration value for a particular ammo, 0 indicates a non-ammo. - * - * @param is ammo - * @return 0 or a valid penetration value. - */ - float getPenetration( ItemStack is ); + /** + * get the penetration value for a particular ammo, 0 indicates a non-ammo. + * + * @param is ammo + * @return 0 or a valid penetration value. + */ + float getPenetration(ItemStack is); } diff --git a/src/api/java/appeng/api/features/INetworkEncodable.java b/src/api/java/appeng/api/features/INetworkEncodable.java index 91dc8ceb..1280990e 100644 --- a/src/api/java/appeng/api/features/INetworkEncodable.java +++ b/src/api/java/appeng/api/features/INetworkEncodable.java @@ -23,27 +23,23 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; +public interface INetworkEncodable { + /** + * Used to get the current key from the item. + * + * @param item item + * @return string key of item + */ + String getEncryptionKey(ItemStack item); -public interface INetworkEncodable -{ - - /** - * Used to get the current key from the item. - * - * @param item item - * @return string key of item - */ - String getEncryptionKey( ItemStack item ); - - /** - * Encode the wireless frequency via the Controller. - * - * @param item the wireless terminal. - * @param encKey the wireless encryption key. - * @param name null for now. - */ - void setEncryptionKey( ItemStack item, String encKey, String name ); + /** + * Encode the wireless frequency via the Controller. + * + * @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 137d731b..b1ddcc6b 100644 --- a/src/api/java/appeng/api/features/IP2PTunnelRegistry.java +++ b/src/api/java/appeng/api/features/IP2PTunnelRegistry.java @@ -23,34 +23,30 @@ package appeng.api.features; +import javax.annotation.Nullable; import appeng.api.config.TunnelType; import net.minecraft.item.ItemStack; -import javax.annotation.Nullable; - - /** * A Registry for how p2p Tunnels are attuned */ -public interface IP2PTunnelRegistry -{ +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. Nullable, but then ignored + * @param type - the type of tunnel. Nullable, but then ignored + */ + void addNewAttunement(@Nullable ItemStack trigger, @Nullable TunnelType type); - /** - * Allows third parties to register items from their mod as potential - * attunements for AE's P2P Tunnels - * - * @param trigger - the item which triggers attunement. Nullable, but then ignored - * @param type - the type of tunnel. Nullable, but then ignored - */ - void addNewAttunement( @Nullable ItemStack trigger, @Nullable TunnelType type ); - - /** - * returns null if no attunement can be found. - * - * @param trigger attunement trigger - * @return null if no attunement can be found or attunement - */ - @Nullable - TunnelType getTunnelTypeByItem( ItemStack trigger ); + /** + * returns null if no attunement can be found. + * + * @param trigger attunement trigger + * @return null if no attunement can be found or attunement + */ + @Nullable + TunnelType getTunnelTypeByItem(ItemStack trigger); } \ No newline at end of file diff --git a/src/api/java/appeng/api/features/IPlayerRegistry.java b/src/api/java/appeng/api/features/IPlayerRegistry.java index 18219b76..22438fe6 100644 --- a/src/api/java/appeng/api/features/IPlayerRegistry.java +++ b/src/api/java/appeng/api/features/IPlayerRegistry.java @@ -23,36 +23,33 @@ package appeng.api.features; +import javax.annotation.Nullable; import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; -import javax.annotation.Nullable; - - /** - * Maintains a save specific list of userids and username combinations this greatly simplifies storage internally and - * gives a common place to look up and get IDs for the security framework. + * Maintains a save specific list of userids and username combinations this greatly + * simplifies storage internally and gives a common place to look up and get IDs for the + * security framework. */ -public interface IPlayerRegistry -{ +public interface IPlayerRegistry { + /** + * @param gameProfile user game profile + * @return user id of a username. + */ + int getID(GameProfile gameProfile); - /** - * @param gameProfile user game profile - * @return user id of a username. - */ - int getID( GameProfile gameProfile ); + /** + * @param player player + * @return user id of a player entity. + */ + int getID(EntityPlayer player); - /** - * @param player player - * @return user id of a player entity. - */ - int getID( EntityPlayer player ); - - /** - * @param playerID to be found player id - * @return PlayerEntity, or null if the player could not be found. - */ - @Nullable - EntityPlayer findPlayer( int playerID ); + /** + * @param playerID to be found player id + * @return PlayerEntity, or null if the player could not be found. + */ + @Nullable + EntityPlayer findPlayer(int playerID); } diff --git a/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java b/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java index 1e225c22..c6cf3ad5 100644 --- a/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java +++ b/src/api/java/appeng/api/features/IRecipeHandlerRegistry.java @@ -23,61 +23,57 @@ package appeng.api.features; +import javax.annotation.Nullable; import appeng.api.recipes.ICraftHandler; import appeng.api.recipes.IRecipeHandler; import appeng.api.recipes.ISubItemResolver; -import javax.annotation.Nullable; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv3 - 10.08.2015 * @since rv0 */ -public interface IRecipeHandlerRegistry -{ +public interface IRecipeHandlerRegistry { + /** + * Add a new Recipe Handler to the parser. + *

+ * MUST BE CALLED IN PRE-INIT + * + * @param name name of crafthandler + * @param handler class of crafthandler + */ + void addNewCraftHandler(String name, Class handler); - /** - * Add a new Recipe Handler to the parser. - *

- * MUST BE CALLED IN PRE-INIT - * - * @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 + */ + void addNewSubItemResolver(ISubItemResolver sir); - /** - * Add a new resolver to the parser. - *

- * MUST BE CALLED IN PRE-INIT - * - * @param sir sub item resolver - */ - void addNewSubItemResolver( ISubItemResolver sir ); + /** + * @param name name of crafting handler + * @return A recipe handler by name, returns null on failure. + */ + @Nullable + ICraftHandler getCraftHandlerFor(String name); - /** - * @param name name of crafting handler - * @return A recipe handler by name, returns null on failure. - */ - @Nullable - ICraftHandler getCraftHandlerFor( String name ); + /** + * @return a new recipe handler, which can be used to parse, and read recipe files. + */ + IRecipeHandler createNewRecipehandler(); - /** - * @return a new recipe handler, which can be used to parse, and read recipe files. - */ - IRecipeHandler createNewRecipehandler(); - - /** - * resolve sub items by name. - * - * @param nameSpace namespace of item - * @param itemName full name of item - * @return ResolverResult or ResolverResultSet or null if could not resolve - */ - @Nullable - Object resolveItem( String nameSpace, String itemName ); + /** + * resolve sub items by name. + * + * @param nameSpace namespace of item + * @param itemName full name of item + * @return ResolverResult or ResolverResultSet or null if could not resolve + */ + @Nullable + Object resolveItem(String nameSpace, String itemName); } diff --git a/src/api/java/appeng/api/features/IRegistryContainer.java b/src/api/java/appeng/api/features/IRegistryContainer.java index 9b3a7e10..c92ab554 100644 --- a/src/api/java/appeng/api/features/IRegistryContainer.java +++ b/src/api/java/appeng/api/features/IRegistryContainer.java @@ -23,90 +23,87 @@ package appeng.api.features; - import appeng.api.movable.IMovableRegistry; import appeng.api.networking.IGridCacheRegistry; import appeng.api.storage.ICellRegistry; import appeng.api.storage.IExternalStorageRegistry; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public interface IRegistryContainer -{ +public interface IRegistryContainer { + /** + * Use the movable registry to white list your tiles. + */ + IMovableRegistry movable(); - /** - * Use the movable registry to white list your tiles. - */ - IMovableRegistry movable(); + /** + * Add new Grid Caches for use during run time, only use during loading phase. + */ + IGridCacheRegistry gridCache(); - /** - * Add new Grid Caches for use during run time, only use during loading phase. - */ - IGridCacheRegistry gridCache(); + /** + * Add additional storage bus handlers to improve interplay with mod blocks that + * contains special inventories that function unlike vanilla chests. AE uses this + * internally for barrels, DSU's, quantum chests, AE Networks and more. + */ + IExternalStorageRegistry externalStorage(); - /** - * Add additional storage bus handlers to improve interplay with mod blocks that contains special inventories that - * function unlike vanilla chests. AE uses this internally for barrels, DSU's, quantum chests, AE Networks and more. - */ - IExternalStorageRegistry externalStorage(); + /** + * Add additional special comparison functionality, AE Uses this internally for Bees. + */ + ISpecialComparisonRegistry specialComparison(); - /** - * Add additional special comparison functionality, AE Uses this internally for Bees. - */ - ISpecialComparisonRegistry specialComparison(); + /** + * Lets you register your items as wireless terminals + */ + IWirelessTermRegistry wireless(); - /** - * Lets you register your items as wireless terminals - */ - IWirelessTermRegistry wireless(); + /** + * Allows you to register new cell types, these will function in drives + */ + ICellRegistry cell(); - /** - * Allows you to register new cell types, these will function in drives - */ - ICellRegistry cell(); + /** + * Manage grinder recipes via API + */ + IGrinderRegistry grinder(); - /** - * Manage grinder recipes via API - */ - IGrinderRegistry grinder(); + /** + * Manage inscriber recipes via API + */ + IInscriberRegistry inscriber(); - /** - * Manage inscriber recipes via API - */ - IInscriberRegistry inscriber(); + /** + * get access to the locatable registry + */ + ILocatableRegistry locatable(); - /** - * get access to the locatable registry - */ - ILocatableRegistry locatable(); + /** + * get access to the p2p tunnel registry. + */ + IP2PTunnelRegistry p2pTunnel(); - /** - * get access to the p2p tunnel registry. - */ - IP2PTunnelRegistry p2pTunnel(); + /** + * get access to the ammo registry. + */ + IMatterCannonAmmoRegistry matterCannon(); - /** - * get access to the ammo registry. - */ - IMatterCannonAmmoRegistry matterCannon(); + /** + * get access to the player registry + */ + IPlayerRegistry players(); - /** - * get access to the player registry - */ - IPlayerRegistry players(); + /** + * get access to the ae2 recipe api + */ + IRecipeHandlerRegistry recipes(); - /** - * get access to the ae2 recipe api - */ - IRecipeHandlerRegistry recipes(); - - /** - * get access to the world-gen api. - */ - IWorldGen worldgen(); + /** + * get access to the world-gen api. + */ + IWorldGen worldgen(); } diff --git a/src/api/java/appeng/api/features/ISpecialComparisonRegistry.java b/src/api/java/appeng/api/features/ISpecialComparisonRegistry.java index 43fdf6eb..115ba06b 100644 --- a/src/api/java/appeng/api/features/ISpecialComparisonRegistry.java +++ b/src/api/java/appeng/api/features/ISpecialComparisonRegistry.java @@ -23,28 +23,24 @@ package appeng.api.features; - import net.minecraft.item.ItemStack; - /** * A Registry of any special comparison handlers for AE To use. */ -public interface ISpecialComparisonRegistry -{ +public interface ISpecialComparisonRegistry { + /** + * return TheHandler or null. + * + * @param stack item + * @return a handler it found for a specific item + */ + IItemComparison getSpecialComparison(ItemStack stack); - /** - * return TheHandler or null. - * - * @param stack item - * @return a handler it found for a specific item - */ - IItemComparison getSpecialComparison( ItemStack stack ); - - /** - * Register a new special comparison function with AE. - * - * @param prov comparison provider - */ - void addComparisonProvider( IItemComparisonProvider prov ); + /** + * Register a new special comparison function with AE. + * + * @param prov comparison provider + */ + void addComparisonProvider(IItemComparisonProvider prov); } \ No newline at end of file diff --git a/src/api/java/appeng/api/features/IWirelessTermHandler.java b/src/api/java/appeng/api/features/IWirelessTermHandler.java index b1da6d72..fad796f4 100644 --- a/src/api/java/appeng/api/features/IWirelessTermHandler.java +++ b/src/api/java/appeng/api/features/IWirelessTermHandler.java @@ -23,47 +23,44 @@ package appeng.api.features; - import appeng.api.util.IConfigManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; - /** * A handler for a wireless terminal. */ -public interface IWirelessTermHandler extends INetworkEncodable -{ +public interface IWirelessTermHandler extends INetworkEncodable { + /** + * @param is wireless terminal + * @return true, if usePower, hasPower, etc... can be called for the provided item + */ + boolean canHandle(ItemStack is); - /** - * @param is wireless terminal - * @return true, if usePower, hasPower, etc... can be called for the provided item - */ - boolean canHandle( ItemStack is ); + /** + * 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 + * @return true if wireless terminal uses power + */ + boolean usePower(EntityPlayer player, double amount, ItemStack is); - /** - * 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 - * @return true if wireless terminal uses power - */ - boolean usePower( EntityPlayer player, double amount, ItemStack is ); + /** + * gets the power status of the item. + * + * @param is wireless terminal + * @return returns true if there is any power left. + */ + boolean hasPower(EntityPlayer player, double amount, ItemStack is); - /** - * gets the power status of the item. - * - * @param is wireless terminal - * @return returns true if there is any power left. - */ - boolean hasPower( EntityPlayer player, double amount, ItemStack is ); - - /** - * Return the config manager for the wireless terminal. - * - * @param is wireless terminal - * @return config manager of wireless terminal - */ - IConfigManager getConfigManager( ItemStack is ); + /** + * Return the config manager for the wireless terminal. + * + * @param is wireless terminal + * @return config manager of wireless terminal + */ + IConfigManager getConfigManager(ItemStack is); } \ No newline at end of file diff --git a/src/api/java/appeng/api/features/IWirelessTermRegistry.java b/src/api/java/appeng/api/features/IWirelessTermRegistry.java index aea2b71c..03667fbe 100644 --- a/src/api/java/appeng/api/features/IWirelessTermRegistry.java +++ b/src/api/java/appeng/api/features/IWirelessTermRegistry.java @@ -23,41 +23,37 @@ package appeng.api.features; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Registration record for a Custom Cell handler. */ -public interface IWirelessTermRegistry -{ +public interface IWirelessTermRegistry { + /** + * add this handler to the list of other wireless handler. + * + * @param handler wireless handler + */ + void registerWirelessHandler(IWirelessTermHandler handler); - /** - * add this handler to the list of other wireless handler. - * - * @param handler wireless handler - */ - void registerWirelessHandler( IWirelessTermHandler handler ); + /** + * @param is item which might have a handler + * @return true if there is a handler for this item + */ + boolean isWirelessTerminal(ItemStack is); - /** - * @param is item which might have a handler - * @return true if there is a handler for this item - */ - boolean isWirelessTerminal( ItemStack is ); + /** + * @param is item with handler + * @return a register handler for the item in question, or null if there + * isn't one + */ + IWirelessTermHandler getWirelessTerminalHandler(ItemStack is); - /** - * @param is item with handler - * @return a register handler for the item in question, or null if there - * isn't one - */ - IWirelessTermHandler getWirelessTerminalHandler( ItemStack is ); - - /** - * opens the wireless terminal gui, the wireless terminal item, must be in - * the active slot on the tool bar. - */ - void openWirelessTerminalGui( ItemStack item, World w, EntityPlayer player ); + /** + * opens the wireless terminal gui, the wireless terminal item, must be in + * the active slot on the tool bar. + */ + void openWirelessTerminalGui(ItemStack item, World w, EntityPlayer player); } diff --git a/src/api/java/appeng/api/features/IWorldGen.java b/src/api/java/appeng/api/features/IWorldGen.java index 8e5a9c73..e1f86ff8 100644 --- a/src/api/java/appeng/api/features/IWorldGen.java +++ b/src/api/java/appeng/api/features/IWorldGen.java @@ -23,24 +23,19 @@ package appeng.api.features; - import net.minecraft.world.World; import net.minecraft.world.WorldProvider; +public interface IWorldGen { + void disableWorldGenForProviderID( + WorldGenType type, Class provider + ); -public interface IWorldGen -{ + void enableWorldGenForDimension(WorldGenType type, int dimID); - void disableWorldGenForProviderID( WorldGenType type, Class provider ); + void disableWorldGenForDimension(WorldGenType type, int dimID); - void enableWorldGenForDimension( WorldGenType type, int dimID ); + boolean isWorldGenEnabled(WorldGenType type, World w); - void disableWorldGenForDimension( WorldGenType type, int dimID ); - - boolean isWorldGenEnabled( WorldGenType type, World w ); - - enum WorldGenType - { - CertusQuartz, ChargedCertusQuartz, Meteorites - } + enum WorldGenType { CertusQuartz, ChargedCertusQuartz, Meteorites } } diff --git a/src/api/java/appeng/api/features/InscriberProcessType.java b/src/api/java/appeng/api/features/InscriberProcessType.java index 70aaa9f7..bf505861 100644 --- a/src/api/java/appeng/api/features/InscriberProcessType.java +++ b/src/api/java/appeng/api/features/InscriberProcessType.java @@ -1,15 +1,13 @@ package appeng.api.features; +public enum InscriberProcessType { + /** + * uses the optionals as catalyst + */ + Inscribe, -public enum InscriberProcessType -{ - /** - * uses the optionals as catalyst - */ - Inscribe, - - /** - * spends the optionals - */ - Press + /** + * spends the optionals + */ + Press } diff --git a/src/api/java/appeng/api/implementations/ICraftingPatternItem.java b/src/api/java/appeng/api/implementations/ICraftingPatternItem.java index 132a5ef0..a0f0acd5 100644 --- a/src/api/java/appeng/api/implementations/ICraftingPatternItem.java +++ b/src/api/java/appeng/api/implementations/ICraftingPatternItem.java @@ -23,25 +23,21 @@ package appeng.api.implementations; - import appeng.api.networking.crafting.ICraftingPatternDetails; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Implemented on {@link Item} */ -public interface ICraftingPatternItem -{ - - /** - * Access Details about a pattern - * - * @param is pattern - * @param w crafting world - * @return details of pattern - */ - ICraftingPatternDetails getPatternForItem( ItemStack is, World w ); +public interface ICraftingPatternItem { + /** + * Access Details about a pattern + * + * @param is pattern + * @param w crafting world + * @return details of pattern + */ + ICraftingPatternDetails getPatternForItem(ItemStack is, World w); } diff --git a/src/api/java/appeng/api/implementations/IPowerChannelState.java b/src/api/java/appeng/api/implementations/IPowerChannelState.java index ee558792..d718b8a1 100644 --- a/src/api/java/appeng/api/implementations/IPowerChannelState.java +++ b/src/api/java/appeng/api/implementations/IPowerChannelState.java @@ -23,20 +23,17 @@ package appeng.api.implementations; - /** * This is intended for use on the client side to provide details to WAILA. */ -public interface IPowerChannelState -{ +public interface IPowerChannelState { + /** + * @return true if the part/tile is powered. + */ + boolean isPowered(); - /** - * @return true if the part/tile is powered. - */ - boolean isPowered(); - - /** - * @return true if the part/tile isActive - */ - boolean isActive(); + /** + * @return true if the part/tile isActive + */ + boolean isActive(); } diff --git a/src/api/java/appeng/api/implementations/IUpgradeableHost.java b/src/api/java/appeng/api/implementations/IUpgradeableHost.java index 7abc93f9..b7f1d1c9 100644 --- a/src/api/java/appeng/api/implementations/IUpgradeableHost.java +++ b/src/api/java/appeng/api/implementations/IUpgradeableHost.java @@ -23,25 +23,21 @@ package appeng.api.implementations; - import appeng.api.config.Upgrades; import appeng.api.implementations.tiles.ISegmentedInventory; import appeng.api.util.IConfigurableObject; import net.minecraft.tileentity.TileEntity; +public interface IUpgradeableHost extends IConfigurableObject, ISegmentedInventory { + /** + * determine how many of an upgrade are installed. + */ + int getInstalledUpgrades(Upgrades u); -public interface IUpgradeableHost extends IConfigurableObject, ISegmentedInventory -{ - - /** - * determine how many of an upgrade are installed. - */ - int getInstalledUpgrades( Upgrades u ); - - /** - * the tile... - * - * @return tile entity - */ - TileEntity getTile(); + /** + * the tile... + * + * @return tile entity + */ + TileEntity getTile(); } diff --git a/src/api/java/appeng/api/implementations/TransitionResult.java b/src/api/java/appeng/api/implementations/TransitionResult.java index 9eec763e..b8335777 100644 --- a/src/api/java/appeng/api/implementations/TransitionResult.java +++ b/src/api/java/appeng/api/implementations/TransitionResult.java @@ -23,19 +23,16 @@ package appeng.api.implementations; - /** * Defines the result of performing a transition from the world into a storage * cell, if its possible, and what the energy usage is. */ -public class TransitionResult -{ - public final boolean success; - public final double energyUsage; +public class TransitionResult { + public final boolean success; + public final double energyUsage; - public TransitionResult( final boolean _success, final double power ) - { - this.success = _success; - this.energyUsage = power; - } + public TransitionResult(final boolean _success, final double power) { + this.success = _success; + this.energyUsage = power; + } } diff --git a/src/api/java/appeng/api/implementations/guiobjects/IGuiItem.java b/src/api/java/appeng/api/implementations/guiobjects/IGuiItem.java index 269eea2a..499df409 100644 --- a/src/api/java/appeng/api/implementations/guiobjects/IGuiItem.java +++ b/src/api/java/appeng/api/implementations/guiobjects/IGuiItem.java @@ -23,17 +23,13 @@ package appeng.api.implementations.guiobjects; - import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Implemented on Item objects, to return objects used to manage, and interact * with the contents. */ -public interface IGuiItem -{ - - IGuiItemObject getGuiObject( ItemStack is, World world, int x, int y, int z ); +public interface IGuiItem { + IGuiItemObject getGuiObject(ItemStack is, World world, int x, int y, int z); } diff --git a/src/api/java/appeng/api/implementations/guiobjects/IGuiItemObject.java b/src/api/java/appeng/api/implementations/guiobjects/IGuiItemObject.java index 34218739..7b43ce9f 100644 --- a/src/api/java/appeng/api/implementations/guiobjects/IGuiItemObject.java +++ b/src/api/java/appeng/api/implementations/guiobjects/IGuiItemObject.java @@ -23,12 +23,8 @@ package appeng.api.implementations.guiobjects; - import net.minecraft.item.ItemStack; - -public interface IGuiItemObject -{ - - ItemStack getItemStack(); +public interface IGuiItemObject { + ItemStack getItemStack(); } diff --git a/src/api/java/appeng/api/implementations/guiobjects/INetworkTool.java b/src/api/java/appeng/api/implementations/guiobjects/INetworkTool.java index 931b5234..a0ae2b3c 100644 --- a/src/api/java/appeng/api/implementations/guiobjects/INetworkTool.java +++ b/src/api/java/appeng/api/implementations/guiobjects/INetworkTool.java @@ -23,16 +23,12 @@ package appeng.api.implementations.guiobjects; - import appeng.api.networking.IGridHost; import net.minecraft.inventory.IInventory; - /** * Obtained via {@link IGuiItem} getGuiObject */ -public interface INetworkTool extends IInventory, IGuiItemObject -{ - - IGridHost getGridHost(); // null for most purposes. +public interface INetworkTool extends IInventory, IGuiItemObject { + IGridHost getGridHost(); // null for most purposes. } diff --git a/src/api/java/appeng/api/implementations/guiobjects/IPortableCell.java b/src/api/java/appeng/api/implementations/guiobjects/IPortableCell.java index 7a80a00b..b7c9d127 100644 --- a/src/api/java/appeng/api/implementations/guiobjects/IPortableCell.java +++ b/src/api/java/appeng/api/implementations/guiobjects/IPortableCell.java @@ -23,17 +23,13 @@ package appeng.api.implementations.guiobjects; - import appeng.api.networking.energy.IEnergySource; import appeng.api.storage.IMEMonitor; import appeng.api.storage.ITerminalHost; import appeng.api.storage.data.IAEItemStack; - /** * Obtained via {@link IGuiItem} getGuiObject */ -public interface IPortableCell extends ITerminalHost, IMEMonitor, IEnergySource, IGuiItemObject -{ - -} +public interface IPortableCell + extends ITerminalHost, IMEMonitor, IEnergySource, IGuiItemObject {} diff --git a/src/api/java/appeng/api/implementations/items/IAEItemPowerStorage.java b/src/api/java/appeng/api/implementations/items/IAEItemPowerStorage.java index fe7daf0b..a638b170 100644 --- a/src/api/java/appeng/api/implementations/items/IAEItemPowerStorage.java +++ b/src/api/java/appeng/api/implementations/items/IAEItemPowerStorage.java @@ -23,50 +23,46 @@ package appeng.api.implementations.items; - import appeng.api.config.AccessRestriction; import appeng.api.networking.energy.IAEPowerStorage; import net.minecraft.item.ItemStack; - /** * Basically the same as {@link IAEPowerStorage}, but for items. */ -public interface IAEItemPowerStorage -{ +public interface IAEItemPowerStorage { + /** + * Inject amt, power into the device, it will store what it can, and return + * the amount unable to be stored. + * + * @return amount unable to be stored + */ + double injectAEPower(ItemStack is, double amt); - /** - * Inject amt, power into the device, it will store what it can, and return - * the amount unable to be stored. - * - * @return amount unable to be stored - */ - double injectAEPower( ItemStack is, double amt ); + /** + * Attempt to extract power from the device, it will extract what it can and + * return it. + * + * @param amt to be extracted power from device + * @return what it could extract + */ + double extractAEPower(ItemStack is, double amt); - /** - * Attempt to extract power from the device, it will extract what it can and - * return it. - * - * @param amt to be extracted power from device - * @return what it could extract - */ - double extractAEPower( ItemStack is, double amt ); + /** + * @return the current maximum power ( this can change :P ) + */ + double getAEMaxPower(ItemStack is); - /** - * @return the current maximum power ( this can change :P ) - */ - double getAEMaxPower( ItemStack is ); + /** + * @return the current AE Power Level, this may exceed getMEMaxPower() + */ + double getAECurrentPower(ItemStack is); - /** - * @return the current AE Power Level, this may exceed getMEMaxPower() - */ - double getAECurrentPower( ItemStack is ); - - /** - * Control the power flow by telling what the network can do, either add? or - * subtract? or both! - * - * @return access restriction of network - */ - AccessRestriction getPowerFlow( ItemStack is ); + /** + * Control the power flow by telling what the network can do, either add? or + * subtract? or both! + * + * @return access restriction of network + */ + AccessRestriction getPowerFlow(ItemStack is); } \ No newline at end of file diff --git a/src/api/java/appeng/api/implementations/items/IAEWrench.java b/src/api/java/appeng/api/implementations/items/IAEWrench.java index 48bedac6..747a4c9b 100644 --- a/src/api/java/appeng/api/implementations/items/IAEWrench.java +++ b/src/api/java/appeng/api/implementations/items/IAEWrench.java @@ -23,26 +23,22 @@ package appeng.api.implementations.items; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; - /** * Implemented on AE's wrench(s) as a substitute for if BC's API is not * available. */ -public interface IAEWrench -{ - - /** - * Check if the wrench can be used. - * - * @param player wrenching player - * @param x x pos of wrenched block - * @param y y pos of wrenched block - * @param z z pos of wrenched block - * @return true if wrench can be used - */ - boolean canWrench( ItemStack wrench, EntityPlayer player, int x, int y, int z ); +public interface IAEWrench { + /** + * Check if the wrench can be used. + * + * @param player wrenching player + * @param x x pos of wrenched block + * @param y y pos of wrenched block + * @param z z pos of wrenched block + * @return true if wrench can be used + */ + boolean canWrench(ItemStack wrench, EntityPlayer player, int x, int y, int z); } diff --git a/src/api/java/appeng/api/implementations/items/IBiometricCard.java b/src/api/java/appeng/api/implementations/items/IBiometricCard.java index 3a06b9e7..7c493a03 100644 --- a/src/api/java/appeng/api/implementations/items/IBiometricCard.java +++ b/src/api/java/appeng/api/implementations/items/IBiometricCard.java @@ -23,6 +23,7 @@ package appeng.api.implementations.items; +import java.util.EnumSet; import appeng.api.config.SecurityPermissions; import appeng.api.features.IPlayerRegistry; @@ -30,58 +31,54 @@ import appeng.api.networking.security.ISecurityRegistry; import com.mojang.authlib.GameProfile; import net.minecraft.item.ItemStack; -import java.util.EnumSet; +public interface IBiometricCard { + /** + * Set the {@link GameProfile} to null, to clear it. + */ + void setProfile(ItemStack itemStack, GameProfile username); + /** + * @return {@link GameProfile} of the player encoded on this card, or a blank string. + */ + GameProfile getProfile(ItemStack is); -public interface IBiometricCard -{ + /** + * @param itemStack card + * @return the full list of permissions encoded on the card. + */ + EnumSet getPermissions(ItemStack itemStack); - /** - * Set the {@link GameProfile} to null, to clear it. - */ - void setProfile( ItemStack itemStack, GameProfile username ); + /** + * Check if a permission is encoded on the card. + * + * @param permission card + * @return true if this permission is set on the card. + */ + boolean hasPermission(ItemStack is, SecurityPermissions permission); - /** - * @return {@link GameProfile} of the player encoded on this card, or a blank string. - */ - GameProfile getProfile( ItemStack is ); + /** + * remove a permission from the item stack. + * + * @param itemStack card + * @param permission to be removed permission + */ + void removePermission(ItemStack itemStack, SecurityPermissions permission); - /** - * @param itemStack card - * @return the full list of permissions encoded on the card. - */ - EnumSet getPermissions( ItemStack itemStack ); + /** + * add a permission to the item stack. + * + * @param itemStack card + * @param permission to be added permission + */ + void addPermission(ItemStack itemStack, SecurityPermissions permission); - /** - * Check if a permission is encoded on the card. - * - * @param permission card - * @return true if this permission is set on the card. - */ - boolean hasPermission( ItemStack is, SecurityPermissions permission ); - - /** - * remove a permission from the item stack. - * - * @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 permission to be added permission - */ - void addPermission( ItemStack itemStack, SecurityPermissions permission ); - - /** - * lets you handle submission of security values on the card for custom behavior. - * - * @param registry security registry - * @param pr player registry - * @param is card - */ - void registerPermissions( ISecurityRegistry registry, IPlayerRegistry pr, ItemStack is ); + /** + * lets you handle submission of security values on the card for custom behavior. + * + * @param registry security registry + * @param pr player registry + * @param is card + */ + void + registerPermissions(ISecurityRegistry registry, IPlayerRegistry pr, ItemStack is); } diff --git a/src/api/java/appeng/api/implementations/items/IGrowableCrystal.java b/src/api/java/appeng/api/implementations/items/IGrowableCrystal.java index 489e2b89..4fbae7b8 100644 --- a/src/api/java/appeng/api/implementations/items/IGrowableCrystal.java +++ b/src/api/java/appeng/api/implementations/items/IGrowableCrystal.java @@ -23,16 +23,12 @@ package appeng.api.implementations.items; - import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.ItemStack; +public interface IGrowableCrystal { + ItemStack triggerGrowth(ItemStack is); -public interface IGrowableCrystal -{ - - ItemStack triggerGrowth( ItemStack is ); - - float getMultiplier( Block blk, Material mat ); + float getMultiplier(Block blk, Material mat); } diff --git a/src/api/java/appeng/api/implementations/items/IItemGroup.java b/src/api/java/appeng/api/implementations/items/IItemGroup.java index 0b01aeba..2dd35582 100644 --- a/src/api/java/appeng/api/implementations/items/IItemGroup.java +++ b/src/api/java/appeng/api/implementations/items/IItemGroup.java @@ -23,23 +23,19 @@ package appeng.api.implementations.items; - -import net.minecraft.item.ItemStack; - import java.util.Set; +import net.minecraft.item.ItemStack; /** * Lets you specify the name of the group of items this falls under. */ -public interface IItemGroup -{ - - /** - * returning null, is the same as not implementing the interface at all. - * - * @param is item - * @return an unlocalized string to use for the items group name. - */ - String getUnlocalizedGroupName( Set otherItems, ItemStack is ); +public interface IItemGroup { + /** + * returning null, is the same as not implementing the interface at all. + * + * @param is item + * @return an unlocalized string to use for the items group name. + */ + String getUnlocalizedGroupName(Set otherItems, ItemStack is); } diff --git a/src/api/java/appeng/api/implementations/items/IMemoryCard.java b/src/api/java/appeng/api/implementations/items/IMemoryCard.java index 380063f8..9354c857 100644 --- a/src/api/java/appeng/api/implementations/items/IMemoryCard.java +++ b/src/api/java/appeng/api/implementations/items/IMemoryCard.java @@ -23,54 +23,50 @@ package appeng.api.implementations.items; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; - /** * Memory Card API *

* AE's Memory Card Item Class implements this interface. */ -public interface IMemoryCard -{ +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. + */ + void setMemoryCardContents(ItemStack is, String SettingsName, NBTTagCompound data); - /** - * 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. - */ - void setMemoryCardContents( ItemStack is, String SettingsName, NBTTagCompound data ); + /** + * returns the settings name provided by a previous call to + * setMemoryCardContents, or "AppEng.GuiITooltip.Blank" if there was no + * previous call to setMemoryCardContents. + * + * @param is item + * @return setting name + */ + String getSettingsName(ItemStack is); - /** - * returns the settings name provided by a previous call to - * setMemoryCardContents, or "AppEng.GuiITooltip.Blank" if there was no - * previous call to setMemoryCardContents. - * - * @param is item - * @return setting name - */ - String getSettingsName( ItemStack is ); + /** + * @param is item + * @return the NBT Data previously saved by setMemoryCardContents, or an + * empty NBTCompound + */ + NBTTagCompound getData(ItemStack is); - /** - * @param is item - * @return the NBT Data previously saved by setMemoryCardContents, or an - * empty NBTCompound - */ - NBTTagCompound getData( ItemStack is ); - - /** - * notify the user of a outcome related to the memory card. - * - * @param player that used the card. - * @param msg which message to send. - */ - void notifyUser( EntityPlayer player, MemoryCardMessages msg ); + /** + * notify the user of a outcome related to the memory card. + * + * @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 c84fc67a..f782f7fb 100644 --- a/src/api/java/appeng/api/implementations/items/ISpatialStorageCell.java +++ b/src/api/java/appeng/api/implementations/items/ISpatialStorageCell.java @@ -23,71 +23,69 @@ package appeng.api.implementations.items; - import appeng.api.implementations.TransitionResult; import appeng.api.util.WorldCoord; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * Implemented on a {@link Item} */ -public interface ISpatialStorageCell -{ +public interface ISpatialStorageCell { + /** + * @param is spatial storage cell + * @return true if this item is a spatial storage cell + */ + boolean isSpatialStorage(ItemStack is); - /** - * @param is spatial storage cell - * @return true if this item is a spatial storage cell - */ - boolean isSpatialStorage( ItemStack is ); + /** + * @param is spatial storage cell + * @return the maximum size of the spatial storage cell along any given axis + */ + int getMaxStoredDim(ItemStack is); - /** - * @param is spatial storage cell - * @return the maximum size of the spatial storage cell along any given axis - */ - int getMaxStoredDim( ItemStack is ); + /** + * @param is spatial storage cell + * @return the world for this cell + */ + World getWorld(ItemStack is); - /** - * @param is spatial storage cell - * @return the world for this cell - */ - World getWorld( ItemStack is ); + /** + * get the currently stored size. + * + * @param is spatial storage cell + * @return size of spatial + */ + WorldCoord getStoredSize(ItemStack is); - /** - * get the currently stored size. - * - * @param is spatial storage cell - * @return size of spatial - */ - WorldCoord getStoredSize( ItemStack is ); + /** + * Minimum coordinates in its world for the storage cell. + * + * @param is spatial storage cell + * @return minimum coordinate of dimension + */ + WorldCoord getMin(ItemStack is); - /** - * Minimum coordinates in its world for the storage cell. - * - * @param is spatial storage cell - * @return minimum coordinate of dimension - */ - WorldCoord getMin( ItemStack is ); + /** + * Maximum coordinates in its world for the storage cell. + * + * @param is spatial storage cell + * @return maximum coordinate of dimension + */ + WorldCoord getMax(ItemStack is); - /** - * Maximum coordinates in its world for the storage cell. - * - * @param is spatial storage cell - * @return maximum coordinate of dimension - */ - WorldCoord getMax( ItemStack is ); - - /** - * 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 doTransition transition - * @return result of transition - */ - TransitionResult doSpatialTransition( ItemStack is, World w, WorldCoord min, WorldCoord max, boolean doTransition ); + /** + * 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 doTransition transition + * @return result of transition + */ + TransitionResult doSpatialTransition( + ItemStack is, World w, WorldCoord min, WorldCoord max, boolean doTransition + ); } \ No newline at end of file diff --git a/src/api/java/appeng/api/implementations/items/IStorageCell.java b/src/api/java/appeng/api/implementations/items/IStorageCell.java index 4dd8ceb2..62ef8a2e 100644 --- a/src/api/java/appeng/api/implementations/items/IStorageCell.java +++ b/src/api/java/appeng/api/implementations/items/IStorageCell.java @@ -23,12 +23,10 @@ package appeng.api.implementations.items; - import appeng.api.storage.ICellWorkbenchItem; import appeng.api.storage.data.IAEItemStack; import net.minecraft.item.ItemStack; - /** * Any item which implements this can be treated as an IMEInventory via * Util.getCell / Util.isCell It automatically handles the internals and NBT @@ -39,78 +37,76 @@ import net.minecraft.item.ItemStack; *

* The standard AE implementation only provides 1-63 Types */ -public interface IStorageCell extends ICellWorkbenchItem -{ +public interface IStorageCell extends ICellWorkbenchItem { + /** + * It wont work if the return is not a multiple of 8. + * The limit is ({@link Integer#MAX_VALUE} + 1) / 8. + * + * @param cellItem item + * @return number of bytes + */ + int getBytes(ItemStack cellItem); - /** - * It wont work if the return is not a multiple of 8. - * The limit is ({@link Integer#MAX_VALUE} + 1) / 8. - * - * @param cellItem item - * @return number of bytes - */ - int getBytes( ItemStack cellItem ); + /** + * Determines the number of bytes used for any type included on the cell. + * + * @param cellItem item + * @return number of bytes + * @deprecated use {@link IStorageCell#getBytesPerType(ItemStack)} + */ + @Deprecated + int BytePerType(ItemStack cellItem); - /** - * Determines the number of bytes used for any type included on the cell. - * - * @param cellItem item - * @return number of bytes - * @deprecated use {@link IStorageCell#getBytesPerType(ItemStack)} - */ - @Deprecated - int BytePerType( ItemStack cellItem ); + /** + * Determines the number of bytes used for any type included on the cell. + * + * @param cellItem item + * @return number of bytes + */ + int getBytesPerType(ItemStack cellItem); - /** - * Determines the number of bytes used for any type included on the cell. - * - * @param cellItem item - * @return number of bytes - */ - int getBytesPerType( ItemStack cellItem ); + /** + * Must be between 1 and 63, indicates how many types you want to store on + * the item. + * + * @param cellItem item + * @return number of types + */ + int getTotalTypes(ItemStack cellItem); - /** - * Must be between 1 and 63, indicates how many types you want to store on - * the item. - * - * @param cellItem item - * @return number of types - */ - int getTotalTypes( ItemStack cellItem ); + /** + * 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 requestedAddition requested addition + * @return true to preventAdditionOfItem + */ + boolean isBlackListed(ItemStack cellItem, IAEItemStack requestedAddition); - /** - * 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 requestedAddition requested addition - * @return true to preventAdditionOfItem - */ - boolean isBlackListed( ItemStack cellItem, IAEItemStack requestedAddition ); + /** + * Allows you to specify if this storage cell can be stored inside other + * storage cells, only set this for special items like the matter cannon + * that are not general purpose storage. + * + * @return true if the storage cell can be stored inside other storage + * cells, this is generally false, except for certain situations + * such as the matter cannon. + */ + boolean storableInStorageCell(); - /** - * Allows you to specify if this storage cell can be stored inside other - * storage cells, only set this for special items like the matter cannon - * that are not general purpose storage. - * - * @return true if the storage cell can be stored inside other storage - * cells, this is generally false, except for certain situations - * such as the matter cannon. - */ - boolean storableInStorageCell(); + /** + * Allows an item to selectively enable or disable its status as a storage + * cell. + * + * @param i item + * @return if the ItemStack should behavior as a storage cell. + */ + boolean isStorageCell(ItemStack i); - /** - * Allows an item to selectively enable or disable its status as a storage - * cell. - * - * @param i item - * @return if the ItemStack should behavior as a storage cell. - */ - boolean isStorageCell( ItemStack i ); - - /** - * @return drain in ae/t this storage cell will use. - */ - double getIdleDrain(); + /** + * @return drain in ae/t this storage cell will use. + */ + double getIdleDrain(); } diff --git a/src/api/java/appeng/api/implementations/items/IStorageComponent.java b/src/api/java/appeng/api/implementations/items/IStorageComponent.java index 8a1f1f58..99e13e60 100644 --- a/src/api/java/appeng/api/implementations/items/IStorageComponent.java +++ b/src/api/java/appeng/api/implementations/items/IStorageComponent.java @@ -23,32 +23,28 @@ package appeng.api.implementations.items; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - /** * Implemented on a {@link Item} */ -public interface IStorageComponent -{ +public interface IStorageComponent { + /** + * This isn't necessarily the same as if you make a storage cell out of it, + * but all of AE's default cells do it that way, its currently only used for + * the condenser. + * + * @param is item + * @return number of bytes + */ + int getBytes(ItemStack is); - /** - * This isn't necessarily the same as if you make a storage cell out of it, - * but all of AE's default cells do it that way, its currently only used for - * the condenser. - * - * @param is item - * @return number of bytes - */ - int getBytes( ItemStack is ); - - /** - * Just true or false for the item stack. - * - * @param is item - * @return true if item is a storage component - */ - boolean isStorageComponent( ItemStack is ); + /** + * Just true or false for the item stack. + * + * @param is item + * @return true if item is a storage component + */ + boolean isStorageComponent(ItemStack is); } diff --git a/src/api/java/appeng/api/implementations/items/IUpgradeModule.java b/src/api/java/appeng/api/implementations/items/IUpgradeModule.java index 1ee3c32b..911d0f95 100644 --- a/src/api/java/appeng/api/implementations/items/IUpgradeModule.java +++ b/src/api/java/appeng/api/implementations/items/IUpgradeModule.java @@ -23,17 +23,13 @@ package appeng.api.implementations.items; - import appeng.api.config.Upgrades; import net.minecraft.item.ItemStack; - -public interface IUpgradeModule -{ - - /** - * @param itemstack item with potential upgrades - * @return null, or a valid upgrade type. - */ - Upgrades getType( ItemStack itemstack ); +public interface IUpgradeModule { + /** + * @param itemstack item with potential upgrades + * @return null, or a valid upgrade type. + */ + Upgrades getType(ItemStack itemstack); } diff --git a/src/api/java/appeng/api/implementations/items/MemoryCardMessages.java b/src/api/java/appeng/api/implementations/items/MemoryCardMessages.java index 01621314..cca2b33e 100644 --- a/src/api/java/appeng/api/implementations/items/MemoryCardMessages.java +++ b/src/api/java/appeng/api/implementations/items/MemoryCardMessages.java @@ -23,11 +23,12 @@ package appeng.api.implementations.items; - /** * Status Results for use with {@link IMemoryCard} */ -public enum MemoryCardMessages -{ - INVALID_MACHINE, SETTINGS_LOADED, SETTINGS_SAVED, SETTINGS_CLEARED +public enum MemoryCardMessages { + INVALID_MACHINE, + SETTINGS_LOADED, + SETTINGS_SAVED, + SETTINGS_CLEARED } diff --git a/src/api/java/appeng/api/implementations/parts/IPartCable.java b/src/api/java/appeng/api/implementations/parts/IPartCable.java index 0ffceb44..75555c54 100644 --- a/src/api/java/appeng/api/implementations/parts/IPartCable.java +++ b/src/api/java/appeng/api/implementations/parts/IPartCable.java @@ -23,6 +23,7 @@ package appeng.api.implementations.parts; +import java.util.EnumSet; import appeng.api.networking.IGridHost; import appeng.api.parts.BusSupport; @@ -33,53 +34,50 @@ import appeng.api.util.AEColor; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - /** - * Implemented on the {@link IPart}s cable objects that can be placed at {@link ForgeDirection}.UNKNOWN in + * Implemented on the {@link IPart}s cable objects that can be placed at {@link + * ForgeDirection}.UNKNOWN in * {@link IPartHost}s */ -public interface IPartCable extends IPart, IGridHost -{ +public interface IPartCable extends IPart, IGridHost { + /** + * does this cable support buses? + */ + BusSupport supportsBuses(); - /** - * does this cable support buses? - */ - BusSupport supportsBuses(); + /** + * @return the current color of the cable. + */ + AEColor getCableColor(); - /** - * @return the current color of the cable. - */ - AEColor getCableColor(); + /** + * @return the Cable type. + */ + AECableType getCableConnectionType(); - /** - * @return the Cable type. - */ - AECableType getCableConnectionType(); + /** + * Change the color of the cable, this should cost a small amount of dye, or + * something. + * + * @param newColor new color + * @return if the color change was successful. + */ + boolean changeColor(AEColor newColor, EntityPlayer who); - /** - * Change the color of the cable, this should cost a small amount of dye, or something. - * - * @param newColor new color - * @return if the color change was successful. - */ - boolean changeColor( AEColor newColor, EntityPlayer who ); + /** + * Change sides on the cables node. + *

+ * Called by AE, do not invoke. + * + * @param sides sides of cable + */ + void setValidSides(EnumSet sides); - /** - * Change sides on the cables node. - *

- * Called by AE, do not invoke. - * - * @param sides sides of cable - */ - void setValidSides( EnumSet sides ); - - /** - * used to tests if a cable connects to neighbors visually. - * - * @param side neighbor side - * @return true if this side is currently connects to an external block. - */ - boolean isConnected( ForgeDirection side ); + /** + * used to tests if a cable connects to neighbors visually. + * + * @param side neighbor side + * @return true if this side is currently connects to an external block. + */ + boolean isConnected(ForgeDirection side); } diff --git a/src/api/java/appeng/api/implementations/parts/IPartMonitor.java b/src/api/java/appeng/api/implementations/parts/IPartMonitor.java index 8b788e84..bf0ab738 100644 --- a/src/api/java/appeng/api/implementations/parts/IPartMonitor.java +++ b/src/api/java/appeng/api/implementations/parts/IPartMonitor.java @@ -23,20 +23,16 @@ package appeng.api.implementations.parts; - import appeng.api.networking.IGridHost; import appeng.api.parts.IPart; - /** * Implemented by all screen like parts provided by AE. */ -public interface IPartMonitor extends IPart, IGridHost -{ - - /** - * @return if the device is online you should check this before providing - * any other information. - */ - boolean isPowered(); +public interface IPartMonitor extends IPart, IGridHost { + /** + * @return if the device is online you should check this before providing + * any other information. + */ + boolean isPowered(); } diff --git a/src/api/java/appeng/api/implementations/parts/IPartStorageMonitor.java b/src/api/java/appeng/api/implementations/parts/IPartStorageMonitor.java index 9bdfe650..4d1a9c9a 100644 --- a/src/api/java/appeng/api/implementations/parts/IPartStorageMonitor.java +++ b/src/api/java/appeng/api/implementations/parts/IPartStorageMonitor.java @@ -23,28 +23,26 @@ package appeng.api.implementations.parts; - import appeng.api.networking.IGridHost; import appeng.api.parts.IPart; import appeng.api.storage.data.IAEStack; import appeng.api.util.INetworkToolAgent; - /** * The Storage monitor is a {@link IPart} located on the sides of a IPartHost */ -public interface IPartStorageMonitor extends IPartMonitor, IPart, IGridHost, INetworkToolAgent -{ +public interface IPartStorageMonitor + extends IPartMonitor, IPart, IGridHost, INetworkToolAgent { + /** + * @return the item being displayed on the storage monitor, in AEStack Form, can be + * either a IAEItemStack or an + * IAEFluidStack the quantity is important remember to use getStackSize() on the + * IAEStack, and not on the FluidStack/ItemStack acquired from it. + */ + IAEStack getDisplayed(); - /** - * @return the item being displayed on the storage monitor, in AEStack Form, can be either a IAEItemStack or an - * IAEFluidStack the quantity is important remember to use getStackSize() on the IAEStack, and not on the - * FluidStack/ItemStack acquired from it. - */ - IAEStack getDisplayed(); - - /** - * @return the current locked state of the Storage Monitor - */ - boolean isLocked(); + /** + * @return the current locked state of the Storage Monitor + */ + boolean isLocked(); } \ No newline at end of file diff --git a/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java b/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java index f1ae1573..b2cf5e04 100644 --- a/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java +++ b/src/api/java/appeng/api/implementations/tiles/IChestOrDrive.java @@ -23,42 +23,39 @@ 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 { + /** + * @return how many slots are available. Chest has 1, Drive has 10. + */ + int getCellCount(); -public interface IChestOrDrive extends ICellContainer, IGridHost, IOrientable -{ + /** + * 0 - cell is missing. + *

+ * 1 - green, + *

+ * 2 - orange, + *

+ * 3 - red + * + * @param slot slot index + * @return status of the slot, one of the above indices. + */ + int getCellStatus(int slot); - /** - * @return how many slots are available. Chest has 1, Drive has 10. - */ - int getCellCount(); + /** + * @return if the device is online you should check this before providing any other + * information. + */ + boolean isPowered(); - /** - * 0 - cell is missing. - *

- * 1 - green, - *

- * 2 - orange, - *

- * 3 - red - * - * @param slot slot index - * @return status of the slot, one of the above indices. - */ - int getCellStatus( int slot ); - - /** - * @return if the device is online you should check this before providing any other information. - */ - boolean isPowered(); - - /** - * @param slot slot index - * @return is the cell currently blinking to show activity. - */ - boolean isCellBlinking( int slot ); + /** + * @param slot slot index + * @return is the cell currently blinking to show activity. + */ + boolean isCellBlinking(int slot); } diff --git a/src/api/java/appeng/api/implementations/tiles/IColorableTile.java b/src/api/java/appeng/api/implementations/tiles/IColorableTile.java index 469c00d2..bec59b02 100644 --- a/src/api/java/appeng/api/implementations/tiles/IColorableTile.java +++ b/src/api/java/appeng/api/implementations/tiles/IColorableTile.java @@ -23,16 +23,12 @@ package appeng.api.implementations.tiles; - import appeng.api.util.AEColor; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.util.ForgeDirection; +public interface IColorableTile { + AEColor getColor(); -public interface IColorableTile -{ - - AEColor getColor(); - - boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ); + boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who); } diff --git a/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java b/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java index 0a4c9b99..d533d895 100644 --- a/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java +++ b/src/api/java/appeng/api/implementations/tiles/ICraftingMachine.java @@ -23,30 +23,31 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.crafting.ICraftingPatternDetails; import net.minecraft.inventory.InventoryCrafting; import net.minecraftforge.common.util.ForgeDirection; +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 ejectionDirection ejection direction + * @return if it was accepted, all or nothing. + */ + boolean pushPattern( + ICraftingPatternDetails patternDetails, + InventoryCrafting table, + ForgeDirection ejectionDirection + ); -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 ejectionDirection ejection direction - * @return if it was accepted, all or nothing. - */ - 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, - * you can try inserting into the inventory instead. - * - * @return true, if pushPattern can complete, if its false push will always be false. - */ - boolean acceptsPlans(); + /** + * check if the crafting machine is accepting pushes via pushPattern, if this is + * false, all calls to push will fail, you can try inserting into the inventory + * instead. + * + * @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 37bb2e95..7ec6e05e 100644 --- a/src/api/java/appeng/api/implementations/tiles/ICrankable.java +++ b/src/api/java/appeng/api/implementations/tiles/ICrankable.java @@ -23,10 +23,8 @@ package appeng.api.implementations.tiles; - import net.minecraftforge.common.util.ForgeDirection; - /** * Crank/Crankable API, *

@@ -37,23 +35,21 @@ import net.minecraftforge.common.util.ForgeDirection; *

* This interface must be implemented by a tile entity. */ -public interface ICrankable -{ +public interface ICrankable { + /** + * Test if the crank can turn, return false if there is no work to be done. + * + * @return if crank should be allowed to turn. + */ + boolean canTurn(); - /** - * Test if the crank can turn, return false if there is no work to be done. - * - * @return if crank should be allowed to turn. - */ - boolean canTurn(); + /** + * The crank has completed one turn. + */ + void applyTurn(); - /** - * The crank has completed one turn. - */ - void applyTurn(); - - /** - * @return true if the crank can attach on the given side. - */ - boolean canCrankAttach( ForgeDirection directionToCrank ); + /** + * @return true if the crank can attach on the given side. + */ + boolean canCrankAttach(ForgeDirection directionToCrank); } diff --git a/src/api/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java b/src/api/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java index 9d8a9c29..6b3af644 100644 --- a/src/api/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java +++ b/src/api/java/appeng/api/implementations/tiles/ICrystalGrowthAccelerator.java @@ -23,9 +23,6 @@ package appeng.api.implementations.tiles; - -public interface ICrystalGrowthAccelerator -{ - - boolean isPowered(); +public interface ICrystalGrowthAccelerator { + boolean isPowered(); } diff --git a/src/api/java/appeng/api/implementations/tiles/IMEChest.java b/src/api/java/appeng/api/implementations/tiles/IMEChest.java index bbe957a9..a5f74bf7 100644 --- a/src/api/java/appeng/api/implementations/tiles/IMEChest.java +++ b/src/api/java/appeng/api/implementations/tiles/IMEChest.java @@ -23,11 +23,6 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.energy.IEnergySource; - -public interface IMEChest extends IChestOrDrive, ITileStorageMonitorable, IEnergySource -{ - -} +public interface IMEChest extends IChestOrDrive, ITileStorageMonitorable, IEnergySource {} diff --git a/src/api/java/appeng/api/implementations/tiles/ISegmentedInventory.java b/src/api/java/appeng/api/implementations/tiles/ISegmentedInventory.java index 401516c2..2aec19d3 100644 --- a/src/api/java/appeng/api/implementations/tiles/ISegmentedInventory.java +++ b/src/api/java/appeng/api/implementations/tiles/ISegmentedInventory.java @@ -23,19 +23,16 @@ package appeng.api.implementations.tiles; - import net.minecraft.inventory.IInventory; - -public interface ISegmentedInventory -{ - - /** - * Access an internal inventory, note, not all inventories contain real items, some may be ghost items, and treating - * them a real inventories will result in duplication. - * - * @param name inventory name - * @return inventory with inventory name - */ - IInventory getInventoryByName( String name ); +public interface ISegmentedInventory { + /** + * Access an internal inventory, note, not all inventories contain real items, some + * may be ghost items, and treating them a real inventories will result in + * duplication. + * + * @param name inventory name + * @return inventory with inventory name + */ + IInventory getInventoryByName(String name); } diff --git a/src/api/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java b/src/api/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java index b84135a4..44c1683d 100644 --- a/src/api/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java +++ b/src/api/java/appeng/api/implementations/tiles/ITileStorageMonitorable.java @@ -23,17 +23,14 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IStorageMonitorable; import net.minecraftforge.common.util.ForgeDirection; - /** - * Implemented on inventories that can share their inventories with other networks, best example, ME Interface. + * Implemented on inventories that can share their inventories with other networks, best + * example, ME Interface. */ -public interface ITileStorageMonitorable -{ - - IStorageMonitorable getMonitorable( ForgeDirection side, BaseActionSource src ); +public interface ITileStorageMonitorable { + IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src); } diff --git a/src/api/java/appeng/api/implementations/tiles/IViewCellStorage.java b/src/api/java/appeng/api/implementations/tiles/IViewCellStorage.java index 4a81ae12..39332e16 100644 --- a/src/api/java/appeng/api/implementations/tiles/IViewCellStorage.java +++ b/src/api/java/appeng/api/implementations/tiles/IViewCellStorage.java @@ -23,17 +23,13 @@ package appeng.api.implementations.tiles; - import net.minecraft.inventory.IInventory; - -public interface IViewCellStorage -{ - - /** - * should contains at least 5 slot, the first 5 - * - * @return inventory with at least 5 slot - */ - IInventory getViewCellStorage(); +public interface IViewCellStorage { + /** + * should contains at least 5 slot, the first 5 + * + * @return inventory with at least 5 slot + */ + IInventory getViewCellStorage(); } diff --git a/src/api/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java b/src/api/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java index 038bc52d..cfd2c880 100644 --- a/src/api/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java +++ b/src/api/java/appeng/api/implementations/tiles/IWirelessAccessPoint.java @@ -23,32 +23,28 @@ package appeng.api.implementations.tiles; - import appeng.api.networking.IGrid; import appeng.api.networking.security.IActionHost; import appeng.api.util.DimensionalCoord; +public interface IWirelessAccessPoint extends IActionHost { + /** + * @return location of WAP + */ + DimensionalCoord getLocation(); -public interface IWirelessAccessPoint extends IActionHost -{ + /** + * @return max range for this WAP + */ + double getRange(); - /** - * @return location of WAP - */ - DimensionalCoord getLocation(); + /** + * @return can you use this WAP? + */ + boolean isActive(); - /** - * @return max range for this WAP - */ - double getRange(); - - /** - * @return can you use this WAP? - */ - boolean isActive(); - - /** - * @return grid of linked WAP - */ - IGrid getGrid(); + /** + * @return grid of linked WAP + */ + IGrid getGrid(); } diff --git a/src/api/java/appeng/api/integration/IBeeComparison.java b/src/api/java/appeng/api/integration/IBeeComparison.java index 73bffa23..f0138153 100644 --- a/src/api/java/appeng/api/integration/IBeeComparison.java +++ b/src/api/java/appeng/api/integration/IBeeComparison.java @@ -23,7 +23,6 @@ package appeng.api.integration; - /** * An interface to get access to the individual settings for AE's Internal Bee * Comparison handler. @@ -33,11 +32,10 @@ package appeng.api.integration; *

* If you don't have the forestry API, just delete this file when using the API. */ -public interface IBeeComparison -{ - - /** - * @return the Forestry IIndividual for this comparison object - cast this to a IIndividual if you want to use it. - */ - Object getIndividual(); +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 ae9bbd6b..d67411c3 100644 --- a/src/api/java/appeng/api/movable/IMovableHandler.java +++ b/src/api/java/appeng/api/movable/IMovableHandler.java @@ -23,46 +23,42 @@ package appeng.api.movable; - import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public interface IMovableHandler { + /** + * if you return true from this, your saying you can handle the class, not + * that single entity, you cannot opt out of single entities. + * + * @param myClass tile entity class + * @param tile tile entity + * @return true if it can handle moving + */ + boolean canHandle(Class myClass, TileEntity tile); -public interface IMovableHandler -{ - - /** - * if you return true from this, your saying you can handle the class, not - * that single entity, you cannot opt out of single entities. - * - * @param myClass tile entity class - * @param tile tile entity - * @return true if it can handle moving - */ - boolean canHandle( Class myClass, TileEntity tile ); - - /** - * request that the handler move the the tile from its current location to - * the new one. the tile has already been invalidated, and the blocks have - * already been fully moved. - *

- * Potential Example: - *

- *

-	 * {@code
-	 * Chunk c = world.getChunkFromBlockCoords( x, z ); c.setChunkBlockTileEntity( x
-	 * & 0xF, y + y, z & 0xF, tile );
-	 *
-	 * if ( c.isChunkLoaded ) { world.addTileEntity( tile ); world.markBlockForUpdate( x,
-	 * y, z ); }
-	 * }
-	 * 
- * - * @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 - */ - void moveTile( TileEntity tile, World world, int x, int y, int z ); + /** + * request that the handler move the the tile from its current location to + * the new one. the tile has already been invalidated, and the blocks have + * already been fully moved. + *

+ * Potential Example: + *

+ *

+     * {@code
+     * Chunk c = world.getChunkFromBlockCoords( x, z ); c.setChunkBlockTileEntity( x
+     * & 0xF, y + y, z & 0xF, tile );
+     *
+     * if ( c.isChunkLoaded ) { world.addTileEntity( tile ); world.markBlockForUpdate( x,
+     * y, z ); }
+     * }
+     * 
+ * + * @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 + */ + 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 ffd00394..d575e267 100644 --- a/src/api/java/appeng/api/movable/IMovableRegistry.java +++ b/src/api/java/appeng/api/movable/IMovableRegistry.java @@ -23,99 +23,89 @@ 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... - *

+ * Used to determine if a tile is marked as movable, a block will be considered movable, + * if...

* 1. The Tile or its super classes have been white listed with whiteListTileEntity. *

- * 2. The Tile has been register with the IMC ( which basically calls whiteListTileEntity. ) + * 2. The Tile has been register with the IMC ( which basically calls whiteListTileEntity. + * )

+ * 3. The Tile implements IMovableTile 4. A IMovableHandler is register that returns + * canHandle = true for the Tile Entity Class

IMC Example: + * FMLInterModComms.sendMessage( "appliedenergistics2", "movabletile", + * "appeng.common.AppEngTile" );

The movement process is as follows,

+ * 1. IMovableTile.prepareToMove() or TileEntity.invalidate() depending on your opt-in + * method. 2. The tile will be removed from the world. 3. Its world, coordinates will be + * changed. *** this can be overridden with a IMovableHandler + * *** 4. It will then be re-added to the world, or a new world. 5. + * TileEntity.validate() 6. IMovableTile.doneMoving ( if you implemented IMovableTile ) *

- * 3. The Tile implements IMovableTile 4. A IMovableHandler is register that returns canHandle = true for the Tile - * Entity Class - *

- * IMC Example: FMLInterModComms.sendMessage( "appliedenergistics2", "movabletile", "appeng.common.AppEngTile" ); - *

- * The movement process is as follows, - *

- * 1. IMovableTile.prepareToMove() or TileEntity.invalidate() depending on your opt-in method. 2. The tile will be - * removed from the world. 3. Its world, coordinates will be changed. *** this can be overridden with a IMovableHandler - * *** 4. It will then be re-added to the world, or a new world. 5. TileEntity.validate() 6. IMovableTile.doneMoving ( - * if you implemented IMovableTile ) - *

- * Please note, this is a 100% white list only feature, I will never opt in any non-vanilla, non-AE blocks. If you do - * not want to support your tiles being moved, you don't have to do anything. - *

- * I appreciate anyone that takes the effort to get their tiles to work with this system to create a better use - * experience. - *

- * If you need a build of deobf build of AE for testing, do not hesitate to ask. + * Please note, this is a 100% white list only feature, I will never opt in any + * non-vanilla, non-AE blocks. If you do not want to support your tiles being moved, you + * don't have to do anything.

I appreciate anyone that takes the effort to get their + * tiles to work with this system to create a better use experience.

If you need a + * build of deobf build of AE for testing, do not hesitate to ask. */ -public interface IMovableRegistry -{ +public interface IMovableRegistry { + /** + * Black list a block from movement, please only use this to prevent exploits. + *

+ * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", + * "whitelist-spatial", "appeng.common.AppEngTile" ); + * + * @param blk block + */ + void blacklistBlock(Block blk); - /** - * Black list a block from movement, please only use this to prevent exploits. - *

- * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", - * "appeng.common.AppEngTile" ); - * - * @param blk block - */ - void blacklistBlock( Block blk ); + /** + * White list your tile entity with the registry. + *

+ * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", + * "blacklist-block-spatial", new ItemStack(...) );

If you tile is handled with + * IMovableHandler or IMovableTile you do not need to white list it. + */ + void whiteListTileEntity(Class c); - /** - * White list your tile entity with the registry. - *

- * You can also use the IMC, FMLInterModComms.sendMessage( "appliedenergistics2", "blacklist-block-spatial", new - * ItemStack(...) ); - *

- * If you tile is handled with IMovableHandler or IMovableTile you do not need to white list it. - */ - 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); - /** - * @param te to be moved tile entity - * @return true if the tile has accepted your request to move it - */ - boolean askToMove( TileEntity te ); + /** + * tells the tile you are done moving it. + * + * @param te moved tile entity + */ + void doneMoving(TileEntity te); - /** - * tells the tile you are done moving it. - * - * @param te moved tile entity - */ - void doneMoving( TileEntity te ); + /** + * add a new handler movable handler. + * + * @param handler moving handler + */ + void addHandler(IMovableHandler handler); - /** - * add a new handler movable handler. - * - * @param handler moving handler - */ - void addHandler( IMovableHandler handler ); + /** + * handlers are used to perform movement, this allows you to override AE's internal + * version.

only valid after askToMove(...) = true + * + * @param te tile entity + * @return moving handler of tile entity + */ + IMovableHandler getHandler(TileEntity te); - /** - * handlers are used to perform movement, this allows you to override AE's internal version. - *

- * only valid after askToMove(...) = true - * - * @param te tile entity - * @return moving handler of tile entity - */ - IMovableHandler getHandler( TileEntity te ); + /** + * @return a copy of the default handler + */ + IMovableHandler getDefaultHandler(); - /** - * @return a copy of the default handler - */ - IMovableHandler getDefaultHandler(); - - /** - * @param blk block - * @return true if this block is blacklisted - */ - boolean isBlacklisted( Block blk ); + /** + * @param blk block + * @return true if this block is blacklisted + */ + boolean isBlacklisted(Block blk); } \ No newline at end of file diff --git a/src/api/java/appeng/api/movable/IMovableTile.java b/src/api/java/appeng/api/movable/IMovableTile.java index feaaff28..efbee9cf 100644 --- a/src/api/java/appeng/api/movable/IMovableTile.java +++ b/src/api/java/appeng/api/movable/IMovableTile.java @@ -23,24 +23,21 @@ package appeng.api.movable; - /** * You can implement this, or use the IMovableRegistry to white list your tile, * please see the registry for more information. */ -public interface IMovableTile -{ +public interface IMovableTile { + /** + * notification that your block will be moved, called instead of invalidate, + * return false to prevent movement. + * + * @return false to prevent movement + */ + boolean prepareToMove(); - /** - * notification that your block will be moved, called instead of invalidate, - * return false to prevent movement. - * - * @return false to prevent movement - */ - boolean prepareToMove(); - - /** - * notification that your block was moved, called after validate. - */ - void doneMoving(); + /** + * notification that your block was moved, called after validate. + */ + void doneMoving(); } diff --git a/src/api/java/appeng/api/networking/GridFlags.java b/src/api/java/appeng/api/networking/GridFlags.java index b698fb93..f7e0d9cd 100644 --- a/src/api/java/appeng/api/networking/GridFlags.java +++ b/src/api/java/appeng/api/networking/GridFlags.java @@ -23,47 +23,46 @@ package appeng.api.networking; - /** * Various flags to determine network node behavior. */ -public enum GridFlags -{ - /** - * import/export buses, terminals, and other devices that use network features, will use this setting. - */ - REQUIRE_CHANNEL, +public enum GridFlags { + /** + * import/export buses, terminals, and other devices that use network features, will + * use this setting. + */ + REQUIRE_CHANNEL, - /** - * P2P ME tunnels use this setting. - */ - COMPRESSED_CHANNEL, + /** + * P2P ME tunnels use this setting. + */ + COMPRESSED_CHANNEL, - /** - * cannot carry channels over this node. - */ - CANNOT_CARRY, + /** + * cannot carry channels over this node. + */ + CANNOT_CARRY, - /** - * Used by P2P Tunnels to prevent tunnels from tunneling recursively. - */ - CANNOT_CARRY_COMPRESSED, + /** + * Used by P2P Tunnels to prevent tunnels from tunneling recursively. + */ + CANNOT_CARRY_COMPRESSED, - /** - * This node can transmit 32 signals, this should only apply to Tier2 Cable, P2P Tunnels, and Quantum Network - * Bridges. - */ - DENSE_CAPACITY, + /** + * This node can transmit 32 signals, this should only apply to Tier2 Cable, P2P + * Tunnels, and Quantum Network Bridges. + */ + DENSE_CAPACITY, - /** - * This block is part of a multiblock, used in conjunction with REQUIRE_CHANNEL, and {@link IGridMultiblock} see this - * interface for details. - */ - MULTIBLOCK, + /** + * This block is part of a multiblock, used in conjunction with REQUIRE_CHANNEL, and + * {@link IGridMultiblock} see this interface for details. + */ + MULTIBLOCK, - /** - * Indicates which path might be preferred, this only matters if two routes of equal length exist, ad only changes - * the order they are processed in. - */ - PREFERRED + /** + * Indicates which path might be preferred, this only matters if two routes of equal + * length exist, ad only changes the order they are processed in. + */ + PREFERRED } diff --git a/src/api/java/appeng/api/networking/GridNotification.java b/src/api/java/appeng/api/networking/GridNotification.java index b53188d7..99f0d42c 100644 --- a/src/api/java/appeng/api/networking/GridNotification.java +++ b/src/api/java/appeng/api/networking/GridNotification.java @@ -23,11 +23,9 @@ package appeng.api.networking; - -public enum GridNotification -{ - /** - * the visible connections for this node have changed, useful for cable. - */ - ConnectionsChanged, +public enum GridNotification { + /** + * the visible connections for this node have changed, useful for cable. + */ + ConnectionsChanged, } diff --git a/src/api/java/appeng/api/networking/IGrid.java b/src/api/java/appeng/api/networking/IGrid.java index 8cd6ffaf..da3a96ec 100644 --- a/src/api/java/appeng/api/networking/IGrid.java +++ b/src/api/java/appeng/api/networking/IGrid.java @@ -23,71 +23,68 @@ package appeng.api.networking; - import appeng.api.networking.events.MENetworkEvent; import appeng.api.util.IReadOnlyCollection; - /** * Gives you access to Grid based information. *

* Don't Implement. */ -public interface IGrid -{ +public interface IGrid { + /** + * Get Access to various grid modules + * + * @param iface face + * @return the IGridCache you requested. + */ + C getCache(Class iface); - /** - * Get Access to various grid modules - * - * @param iface face - * @return the IGridCache you requested. - */ - C getCache( Class iface ); + /** + * Post an event into the network event bus. + * + * @param ev - event to post + * @return returns ev back to original poster + */ + MENetworkEvent postEvent(MENetworkEvent ev); - /** - * Post an event into the network event bus. - * - * @param ev - event to post - * @return returns ev back to original poster - */ - MENetworkEvent postEvent( MENetworkEvent ev ); + /** + * Post an event into the network event bus, but direct it at a single node. + * + * @param ev event to post + * @return returns ev back to original poster + */ + MENetworkEvent postEventTo(IGridNode node, MENetworkEvent ev); - /** - * Post an event into the network event bus, but direct it at a single node. - * - * @param ev event to post - * @return returns ev back to original poster - */ - MENetworkEvent postEventTo( IGridNode node, MENetworkEvent ev ); + /** + * get a list of the diversity of classes, you can use this to better detect which + * machines your interested in, rather then iterating the entire grid to test them. + * + * @return IReadOnlyCollection of all available host types (Of Type IGridHost). + */ + IReadOnlyCollection> getMachinesClasses(); - /** - * get a list of the diversity of classes, you can use this to better detect which machines your interested in, - * rather then iterating the entire grid to test them. - * - * @return IReadOnlyCollection of all available host types (Of Type IGridHost). - */ - IReadOnlyCollection> getMachinesClasses(); + /** + * 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); - /** - * 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 ); + /** + * @return IReadOnlyCollection for all nodes on the network, node visitors are + * preferred. + */ + IReadOnlyCollection getNodes(); - /** - * @return IReadOnlyCollection for all nodes on the network, node visitors are preferred. - */ - IReadOnlyCollection getNodes(); + /** + * @return true if the last node has been removed from the grid. + */ + boolean isEmpty(); - /** - * @return true if the last node has been removed from the grid. - */ - boolean isEmpty(); - - /** - * @return the node considered the pivot point of the grid. - */ - IGridNode getPivot(); + /** + * @return the node considered the pivot point of the grid. + */ + IGridNode getPivot(); } \ No newline at end of file diff --git a/src/api/java/appeng/api/networking/IGridBlock.java b/src/api/java/appeng/api/networking/IGridBlock.java index e311d14e..958ceca4 100644 --- a/src/api/java/appeng/api/networking/IGridBlock.java +++ b/src/api/java/appeng/api/networking/IGridBlock.java @@ -23,6 +23,7 @@ package appeng.api.networking; +import java.util.EnumSet; import appeng.api.parts.IPart; import appeng.api.util.AEColor; @@ -30,85 +31,85 @@ import appeng.api.util.DimensionalCoord; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - /** * An Implementation is required to create your node for IGridHost *

* Implement for use with IGridHost */ -public interface IGridBlock -{ +public interface IGridBlock { + /** + * how much power to drain per tick as part of idle network usage. + *

+ * if the value of this changes, you must post a MENetworkPowerIdleChange + * + * @return ae/t to use. + */ + double getIdlePowerUsage(); - /** - * how much power to drain per tick as part of idle network usage. - *

- * if the value of this changes, you must post a MENetworkPowerIdleChange - * - * @return ae/t to use. - */ - double getIdlePowerUsage(); + /** + * Various flags that AE uses to modify basic behavior for various parts of the + * network. + * + * @return Set of flags for this IGridBlock + */ + EnumSet getFlags(); - /** - * Various flags that AE uses to modify basic behavior for various parts of the network. - * - * @return Set of flags for this IGridBlock - */ - EnumSet getFlags(); + /** + * generally speaking you will return true for this, the one exception is buses, or + * worm holes where the node represents something that isn't a real connection in the + * world, but rather one represented internally to the block. + * + * @return if the world can connect to this node, and the node can connect to the + * world. + */ + boolean isWorldAccessible(); - /** - * generally speaking you will return true for this, the one exception is buses, or worm holes where the node - * represents something that isn't a real connection in the world, but rather one represented internally to the - * block. - * - * @return if the world can connect to this node, and the node can connect to the world. - */ - boolean isWorldAccessible(); + /** + * @return current location of this node + */ + DimensionalCoord getLocation(); - /** - * @return current location of this node - */ - DimensionalCoord getLocation(); + /** + * @return Transparent, or a valid color, NULL IS NOT A VALID RETURN + */ + AEColor getGridColor(); - /** - * @return Transparent, or a valid color, NULL IS NOT A VALID RETURN - */ - AEColor getGridColor(); + /** + * Notifies your IGridBlock that changes were made to your connections + */ + void onGridNotification(GridNotification notification); - /** - * Notifies your IGridBlock that changes were made to your connections - */ - void onGridNotification( GridNotification notification ); + /** + * Update Blocks network/connection/booting status. grid, + * + * @param grid grid + * @param channelsInUse used channels + */ + void setNetworkStatus(IGrid grid, int channelsInUse); - /** - * Update Blocks network/connection/booting status. grid, - * - * @param grid grid - * @param channelsInUse used channels - */ - void setNetworkStatus( IGrid grid, int channelsInUse ); + /** + * Determine which sides of the block can be connected too, only used when + * isWorldAccessible returns true, not used for {@link IPart} implementations. + */ + EnumSet getConnectableSides(); - /** - * Determine which sides of the block can be connected too, only used when isWorldAccessible returns true, not used - * for {@link IPart} implementations. - */ - EnumSet getConnectableSides(); + /** + * @return the IGridHost for the node, this will be an IGridPart or a TileEntity + * generally speaking. + */ + IGridHost getMachine(); - /** - * @return the IGridHost for the node, this will be an IGridPart or a TileEntity generally speaking. - */ - IGridHost getMachine(); + /** + * called when the grid for the node has changed, the general grid state should not be + * trusted at this point. + */ + void gridChanged(); - /** - * called when the grid for the node has changed, the general grid state should not be trusted at this point. - */ - void gridChanged(); - - /** - * Determines what item stack is used to render this node in the GUI. - * - * @return the render item stack to use to render this node, null is valid, and will not show this node. - */ - ItemStack getMachineRepresentation(); + /** + * Determines what item stack is used to render this node in the GUI. + * + * @return the render item stack to use to render this node, null is valid, and will + * not show this node. + */ + ItemStack getMachineRepresentation(); } diff --git a/src/api/java/appeng/api/networking/IGridCache.java b/src/api/java/appeng/api/networking/IGridCache.java index 15ce7562..43cedbdb 100644 --- a/src/api/java/appeng/api/networking/IGridCache.java +++ b/src/api/java/appeng/api/networking/IGridCache.java @@ -23,7 +23,6 @@ package appeng.api.networking; - /** * Allows you to create a network wise service, AE2 uses these for providing * item, spatial, and tunnel services. @@ -31,61 +30,59 @@ package appeng.api.networking; * Any Class that implements this, should have a public default constructor that * takes a single argument of type IGrid. */ -public interface IGridCache -{ +public interface IGridCache { + /** + * Called each tick for the network, allows you to have active network wide + * behaviors. + */ + void onUpdateTick(); - /** - * Called each tick for the network, allows you to have active network wide - * behaviors. - */ - void onUpdateTick(); + /** + * inform your cache, that a machine was removed from the grid. + *

+ * Important: Do not trust the grids state in this method, interact only + * with the node you are passed, if you need to manage other grid + * information, do it on the next updateTick. + * + * @param gridNode removed from that grid + * @param machine to be removed machine + */ + void removeNode(IGridNode gridNode, IGridHost machine); - /** - * inform your cache, that a machine was removed from the grid. - *

- * Important: Do not trust the grids state in this method, interact only - * with the node you are passed, if you need to manage other grid - * information, do it on the next updateTick. - * - * @param gridNode removed from that grid - * @param machine to be removed machine - */ - void removeNode( IGridNode gridNode, IGridHost machine ); + /** + * informs you cache that a machine was added to the grid. + *

+ * Important: Do not trust the grids state in this method, interact only + * with the node you are passed, if you need to manage other grid + * information, do it on the next updateTick. + * + * @param gridNode added to grid node + * @param machine to be added machine + */ + void addNode(IGridNode gridNode, IGridHost machine); - /** - * informs you cache that a machine was added to the grid. - *

- * Important: Do not trust the grids state in this method, interact only - * with the node you are passed, if you need to manage other grid - * information, do it on the next updateTick. - * - * @param gridNode added to grid node - * @param machine to be added machine - */ - void addNode( IGridNode gridNode, IGridHost machine ); + /** + * Called when a grid splits into two grids, AE will call a split as it + * Iteratively processes changes. The destination should receive half, and + * the current cache should receive half. + * + * @param destinationStorage storage which receives half of old grid + */ + void onSplit(IGridStorage destinationStorage); - /** - * Called when a grid splits into two grids, AE will call a split as it - * Iteratively processes changes. The destination should receive half, and - * the current cache should receive half. - * - * @param destinationStorage storage which receives half of old grid - */ - void onSplit( IGridStorage destinationStorage ); + /** + * Called when two grids merge into one, AE will call a join as it + * Iteratively processes changes. Use this method to incorporate all the + * data from the source into your cache. + * + * @param sourceStorage old storage + */ + void onJoin(IGridStorage sourceStorage); - /** - * Called when two grids merge into one, AE will call a join as it - * Iteratively processes changes. Use this method to incorporate all the - * data from the source into your cache. - * - * @param sourceStorage old storage - */ - void onJoin( IGridStorage sourceStorage ); - - /** - * Called when saving changes, - * - * @param destinationStorage storage - */ - void populateGridStorage( IGridStorage destinationStorage ); + /** + * Called when saving changes, + * + * @param destinationStorage storage + */ + void populateGridStorage(IGridStorage destinationStorage); } diff --git a/src/api/java/appeng/api/networking/IGridCacheRegistry.java b/src/api/java/appeng/api/networking/IGridCacheRegistry.java index b5547632..aaf92e66 100644 --- a/src/api/java/appeng/api/networking/IGridCacheRegistry.java +++ b/src/api/java/appeng/api/networking/IGridCacheRegistry.java @@ -23,28 +23,28 @@ package appeng.api.networking; - import java.util.HashMap; - /** * A registry of grid caches to extend grid functionality. */ -public interface IGridCacheRegistry -{ +public interface IGridCacheRegistry { + /** + * Register a new grid cache for use during operation, must be called during the + * loading phase. + * + * @param iface grid cache class + */ + void registerGridCache( + Class iface, Class implementation + ); - /** - * Register a new grid cache for use during operation, must be called during the loading phase. - * - * @param iface grid cache class - */ - void registerGridCache( Class iface, Class implementation ); - - /** - * requests a new INSTANCE of a grid cache for use, used internally - * - * @param grid grid - * @return a new HashMap of IGridCaches from the registry, called from IGrid when constructing a new grid. - */ - HashMap, IGridCache> createCacheInstance( IGrid grid ); + /** + * requests a new INSTANCE of a grid cache for use, used internally + * + * @param grid grid + * @return a new HashMap of IGridCaches from the registry, called from IGrid when + * constructing a new grid. + */ + HashMap, IGridCache> createCacheInstance(IGrid grid); } diff --git a/src/api/java/appeng/api/networking/IGridConnection.java b/src/api/java/appeng/api/networking/IGridConnection.java index a4b04893..af4573cd 100644 --- a/src/api/java/appeng/api/networking/IGridConnection.java +++ b/src/api/java/appeng/api/networking/IGridConnection.java @@ -23,60 +23,54 @@ package appeng.api.networking; - import net.minecraftforge.common.util.ForgeDirection; - /** * Access to AE's internal grid connections. *

- * Messing with connection is generally completely unnecessary, you should be able to just use IGridNode.updateState() - * to have AE manage them for you. - *

- * Don't Implement. + * Messing with connection is generally completely unnecessary, you should be able to just + * use IGridNode.updateState() to have AE manage them for you.

Don't Implement. */ -public interface IGridConnection -{ +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); - /** - * 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 ); + /** + * 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); - /** - * 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 ); + /** + * by destroying a connection you may create new grids, and trigger un-expected + * behavior, you should only destroy connections if you created them. + */ + void destroy(); - /** - * by destroying a connection you may create new grids, and trigger un-expected behavior, you should only destroy - * connections if you created them. - */ - void destroy(); + /** + * @return node A + */ + IGridNode a(); - /** - * @return node A - */ - IGridNode a(); + /** + * @return node B + */ + IGridNode b(); - /** - * @return node B - */ - IGridNode b(); + /** + * @return if the connection is invisible this returns false + */ + boolean hasDirection(); - /** - * @return if the connection is invisible this returns false - */ - boolean hasDirection(); - - /** - * @return how many channels pass over this connections. - */ - int getUsedChannels(); + /** + * @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 1842589e..5e562a5f 100644 --- a/src/api/java/appeng/api/networking/IGridConnectionVisitor.java +++ b/src/api/java/appeng/api/networking/IGridConnectionVisitor.java @@ -23,14 +23,11 @@ package appeng.api.networking; - -public interface IGridConnectionVisitor extends IGridVisitor -{ - - /** - * Called for each connection on the network. - * - * @param n the connection. - */ - void visitConnection( IGridConnection n ); +public interface IGridConnectionVisitor extends IGridVisitor { + /** + * Called for each connection on the network. + * + * @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 dfe67a11..c8279e10 100644 --- a/src/api/java/appeng/api/networking/IGridHost.java +++ b/src/api/java/appeng/api/networking/IGridHost.java @@ -23,42 +23,38 @@ package appeng.api.networking; - import appeng.api.parts.IPart; import appeng.api.util.AECableType; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * 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 -{ +public interface IGridHost { + /** + * get the grid node for a particular side of a block, you can return null, + * 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 + * for every side. + * @return a new IGridNode, create these with + * AEApi.INSTANCE().createGridNode( MyIGridBlock ) + */ + IGridNode getGridNode(ForgeDirection dir); - /** - * get the grid node for a particular side of a block, you can return null, - * 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 - * for every side. - * @return a new IGridNode, create these with - * AEApi.INSTANCE().createGridNode( MyIGridBlock ) - */ - IGridNode getGridNode( ForgeDirection dir ); + /** + * Determines how cables render when they connect to this block. Priority is + * Smart > Covered > Glass + * + * @param dir direction + */ + AECableType getCableConnectionType(ForgeDirection dir); - /** - * Determines how cables render when they connect to this block. Priority is - * Smart > Covered > Glass - * - * @param dir direction - */ - AECableType getCableConnectionType( ForgeDirection dir ); - - /** - * break this host, its violating security rules, just break your block, or part. - */ - void securityBreak(); + /** + * break this host, its violating security rules, just break your block, or part. + */ + void securityBreak(); } diff --git a/src/api/java/appeng/api/networking/IGridMultiblock.java b/src/api/java/appeng/api/networking/IGridMultiblock.java index 7c3844bb..753e2f1f 100644 --- a/src/api/java/appeng/api/networking/IGridMultiblock.java +++ b/src/api/java/appeng/api/networking/IGridMultiblock.java @@ -23,22 +23,21 @@ package appeng.api.networking; - import java.util.Iterator; - /** - * An extension of IGridBlock, only means something when your getFlags() contains REQUIRE_CHANNEL, when done properly it - * will call the method to get a list of all related nodes and give each of them a channel simultaneously for the entire - * set. This means your entire Multiblock can work with a single channel, instead of one channel per block. + * An extension of IGridBlock, only means something when your getFlags() contains + * REQUIRE_CHANNEL, when done properly it will call the method to get a list of all + * related nodes and give each of them a channel simultaneously for the entire set. This + * means your entire Multiblock can work with a single channel, instead of one channel per + * block. */ -public interface IGridMultiblock extends IGridBlock -{ - - /** - * Used to acquire a list of all nodes that are part of the multiblock. - * - * @return an iterator that will iterate all the nodes for the multiblock. ( read-only iterator expected. ) - */ - Iterator getMultiblockNodes(); +public interface IGridMultiblock extends IGridBlock { + /** + * Used to acquire a list of all nodes that are part of the multiblock. + * + * @return an iterator that will iterate all the nodes for the multiblock. ( read-only + * iterator expected. ) + */ + Iterator getMultiblockNodes(); } diff --git a/src/api/java/appeng/api/networking/IGridNode.java b/src/api/java/appeng/api/networking/IGridNode.java index bb57f777..f465c6a8 100644 --- a/src/api/java/appeng/api/networking/IGridNode.java +++ b/src/api/java/appeng/api/networking/IGridNode.java @@ -23,6 +23,7 @@ package appeng.api.networking; +import java.util.EnumSet; import appeng.api.IAppEngApi; import appeng.api.util.IReadOnlyCollection; @@ -30,9 +31,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - - /** * Gives you a view into your Nodes connections and information. *

@@ -40,122 +38,121 @@ import java.util.EnumSet; *

* Don't Implement; Acquire from {@link IAppEngApi}.createGridNode */ -public interface IGridNode -{ +public interface IGridNode { + /** + * lets you walk the grid stating at the current node using a IGridVisitor, generally + * not needed, please use only if required. + * + * @param visitor visitor + */ + void beginVisit(IGridVisitor visitor); - /** - * lets you walk the grid stating at the current node using a IGridVisitor, generally not needed, please use only if - * required. - * - * @param visitor visitor - */ - void beginVisit( IGridVisitor visitor ); + /** + * inform the node that your IGridBlock has changed its internal state, and force the + * node to update.

ALWAYS make sure that your tile entity is in the world, and has + * its node properly saved to be returned from the host before updating state,

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(); - /** - * inform the node that your IGridBlock has changed its internal state, and force the node to update. - *

- * ALWAYS make sure that your tile entity is in the world, and has its node properly saved to be returned from the - * host before updating state, - *

- * 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(); + /** + * get the machine represented by the node. + * + * @return grid host + */ + IGridHost getMachine(); - /** - * get the machine represented by the node. - * - * @return grid host - */ - IGridHost getMachine(); + /** + * get the grid for the node, this can change at a moments notice. + * + * @return grid + */ + IGrid getGrid(); - /** - * get the grid for the node, this can change at a moments notice. - * - * @return grid - */ - IGrid getGrid(); + /** + * By destroying your node, you destroy any connections, and its existence in the + * grid, use in invalidate, or onChunkUnload + */ + void destroy(); - /** - * By destroying your node, you destroy any connections, and its existence in the grid, use in invalidate, or - * onChunkUnload - */ - void destroy(); + /** + * @return the world the node is located in + */ + World getWorld(); - /** - * @return the world the node is located in - */ - World getWorld(); + /** + * @return a set of the connected sides, UNKNOWN represents an invisible connection + */ + EnumSet getConnectedSides(); - /** - * @return a set of the connected sides, UNKNOWN represents an invisible connection - */ - EnumSet getConnectedSides(); + /** + * lets you iterate a nodes connections + * + * @return grid connections + */ + IReadOnlyCollection getConnections(); - /** - * lets you iterate a nodes connections - * - * @return grid connections - */ - IReadOnlyCollection getConnections(); + /** + * @return the IGridBlock for this node + */ + IGridBlock getGridBlock(); - /** - * @return the IGridBlock for this node - */ - IGridBlock getGridBlock(); + /** + * Reflects the networks status, returns true only if the network is powered, and the + * network is not booting, this also takes into account channels. + * + * @return true if is Network node active, and participating. + */ + boolean isActive(); - /** - * Reflects the networks status, returns true only if the network is powered, and the network is not booting, this - * also takes into account channels. - * - * @return true if is Network node active, and participating. - */ - boolean isActive(); + /** + * this should be called for each node you create, if you have a nodeData compound to + * load from, you can store all your nods on a single compound using name.

+ * Important: You must call this before updateState. + * + * @param name nbt name + * @param nodeData to be loaded data + */ + void loadFromNBT(String name, NBTTagCompound nodeData); - /** - * this should be called for each node you create, if you have a nodeData compound to load from, you can store all - * your nods on a single compound using name. - *

- * Important: You must call this before updateState. - * - * @param name nbt name - * @param nodeData to be loaded data - */ - 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 nodeData to be saved data + */ + void saveToNBT(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 nodeData to be saved data - */ - 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. + */ + boolean meetsChannelRequirements(); - /** - * @return if the node's channel requirements are currently met, use this for display purposes, use isActive for - * status. - */ - boolean meetsChannelRequirements(); + /** + * see if this node has a certain flag + * + * @param flag flags + * @return true if has flag + */ + boolean hasFlag(GridFlags flag); - /** - * see if this node has a certain flag - * - * @param flag flags - * @return true if has flag - */ - boolean hasFlag( GridFlags flag ); + /** + * @return the ownerID this represents the person who placed the node. + */ + int getPlayerID(); - /** - * @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 - * security system. Called instead of loadFromNBT when initially placed, once set never required again, the value is saved with the Node NBT. - * - * @param playerID new player id - */ - void setPlayerID( int playerID ); + /** + * tell the node who was responsible for placing it, failure to do this may result in + * in-compatibility with the security system. Called instead of loadFromNBT when + * initially placed, once set never required again, the value is saved with the Node + * NBT. + * + * @param playerID new player id + */ + void setPlayerID(int playerID); } \ No newline at end of file diff --git a/src/api/java/appeng/api/networking/IGridStorage.java b/src/api/java/appeng/api/networking/IGridStorage.java index 0f9e9b7b..ed2b73bd 100644 --- a/src/api/java/appeng/api/networking/IGridStorage.java +++ b/src/api/java/appeng/api/networking/IGridStorage.java @@ -23,20 +23,16 @@ package appeng.api.networking; - import net.minecraft.nbt.NBTTagCompound; +public interface IGridStorage { + /** + * @return an NBTTagCompound that can be read, and written too. + */ + NBTTagCompound dataObject(); -public interface IGridStorage -{ - - /** - * @return an NBTTagCompound that can be read, and written too. - */ - NBTTagCompound dataObject(); - - /** - * @return the id for this grid storage object, used internally - */ - long getID(); + /** + * @return the id for this grid storage object, used internally + */ + long getID(); } diff --git a/src/api/java/appeng/api/networking/IGridVisitor.java b/src/api/java/appeng/api/networking/IGridVisitor.java index ca693496..7e4eeddf 100644 --- a/src/api/java/appeng/api/networking/IGridVisitor.java +++ b/src/api/java/appeng/api/networking/IGridVisitor.java @@ -23,20 +23,18 @@ package appeng.api.networking; - /** * Simple Visitor pattern access to network nodes. */ -public interface IGridVisitor -{ - - /** - * Called for each node on the network. - *

- * By returning false your informing the host to stop visiting nodes beyond the current node. - * - * @param n the current node. - * @return true to continue visiting nodes beyond this node. - */ - boolean visitNode( IGridNode n ); +public interface IGridVisitor { + /** + * Called for each node on the network. + *

+ * By returning false your informing the host to stop visiting nodes beyond 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/IMachineSet.java b/src/api/java/appeng/api/networking/IMachineSet.java index 7d57b52c..6d83f0cf 100644 --- a/src/api/java/appeng/api/networking/IMachineSet.java +++ b/src/api/java/appeng/api/networking/IMachineSet.java @@ -23,15 +23,11 @@ package appeng.api.networking; - import appeng.api.util.IReadOnlyCollection; - -public interface IMachineSet extends IReadOnlyCollection -{ - - /** - * @return the machine class for this set. - */ - Class getMachineClass(); +public interface IMachineSet extends IReadOnlyCollection { + /** + * @return the machine class for this set. + */ + Class getMachineClass(); } diff --git a/src/api/java/appeng/api/networking/crafting/CraftingItemList.java b/src/api/java/appeng/api/networking/crafting/CraftingItemList.java index c84c275d..e09c5c3a 100644 --- a/src/api/java/appeng/api/networking/crafting/CraftingItemList.java +++ b/src/api/java/appeng/api/networking/crafting/CraftingItemList.java @@ -23,8 +23,4 @@ package appeng.api.networking.crafting; - -public enum CraftingItemList -{ - ALL, STORAGE, ACTIVE, PENDING -} +public enum CraftingItemList { ALL, STORAGE, ACTIVE, PENDING } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingCPU.java b/src/api/java/appeng/api/networking/crafting/ICraftingCPU.java index 5dbc40e8..55ab2ff2 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingCPU.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingCPU.java @@ -23,37 +23,33 @@ package appeng.api.networking.crafting; - import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.data.IAEItemStack; +public interface ICraftingCPU extends IBaseMonitor { + /** + * @return true if the CPU currently has a job. + */ + boolean isBusy(); -public interface ICraftingCPU extends IBaseMonitor -{ + /** + * @return the action source for the CPU. + */ + BaseActionSource getActionSource(); - /** - * @return true if the CPU currently has a job. - */ - boolean isBusy(); + /** + * @return the available storage in bytes + */ + long getAvailableStorage(); - /** - * @return the action source for the CPU. - */ - BaseActionSource getActionSource(); + /** + * @return the number of co-processors in the CPU. + */ + int getCoProcessors(); - /** - * @return the available storage in bytes - */ - long getAvailableStorage(); - - /** - * @return the number of co-processors in the CPU. - */ - int getCoProcessors(); - - /** - * @return an empty string or the name of the cpu. - */ - String getName(); + /** + * @return an empty string or the name of the cpu. + */ + String getName(); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java b/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java index 096b7226..0c7739d2 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingCallback.java @@ -23,14 +23,11 @@ package appeng.api.networking.crafting; - -public interface ICraftingCallback -{ - - /** - * this call back is synchronized with the world you passed. - * - * @param job - final job - */ - void calculationComplete( ICraftingJob job ); +public interface ICraftingCallback { + /** + * this call back is synchronized with the world you passed. + * + * @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 9fef2339..b8623853 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingGrid.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingGrid.java @@ -23,6 +23,7 @@ package appeng.api.networking.crafting; +import java.util.concurrent.Future; import appeng.api.networking.IGrid; import appeng.api.networking.IGridCache; @@ -32,68 +33,85 @@ import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableSet; import net.minecraft.world.World; -import java.util.concurrent.Future; +public interface ICraftingGrid extends IGridCache { + /** + * @param whatToCraft requested craft + * @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 + ); + /** + * Begin calculating a crafting job. + * + * @param world crafting world + * @param grid network + * @param actionSrc source + * @param craftWhat result + * @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. + */ + Future beginCraftingJob( + World world, + IGrid grid, + BaseActionSource actionSrc, + IAEItemStack craftWhat, + ICraftingCallback callback + ); -public interface ICraftingGrid extends IGridCache -{ + /** + * 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. + * @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. + */ + ICraftingLink submitJob( + ICraftingJob job, + ICraftingRequester requestingMachine, + ICraftingCPU target, + boolean prioritizePower, + BaseActionSource src + ); - /** - * @param whatToCraft requested craft - * @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 ); + /** + * @return list of all the crafting cpus on the grid + */ + ImmutableSet getCpus(); - /** - * Begin calculating a crafting job. - * - * @param world crafting world - * @param grid network - * @param actionSrc source - * @param craftWhat result - * @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. - */ - Future beginCraftingJob( World world, IGrid grid, BaseActionSource actionSrc, IAEItemStack craftWhat, ICraftingCallback callback ); + /** + * @param what to be requested item + * @return true if the item can be requested via a crafting emitter. + */ + boolean canEmitFor(IAEItemStack what); - /** - * 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. - * @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. - */ - ICraftingLink submitJob( ICraftingJob job, ICraftingRequester requestingMachine, ICraftingCPU target, boolean prioritizePower, BaseActionSource src ); - - /** - * @return list of all the crafting cpus on the grid - */ - ImmutableSet getCpus(); - - /** - * @param what to be requested item - * @return true if the item can be requested via a crafting emitter. - */ - 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 ); + /** + * is this item being crafted? + * + * @param aeStackInSlot item being crafted + * @return true if it is being crafting + */ + boolean isRequesting(IAEItemStack aeStackInSlot); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingJob.java b/src/api/java/appeng/api/networking/crafting/ICraftingJob.java index 55901230..539ade2d 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingJob.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingJob.java @@ -23,35 +23,32 @@ package appeng.api.networking.crafting; - import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; +public interface ICraftingJob { + /** + * @return if this job is a simulation, simulations cannot be submitted and only + * represent 1 possible future + * crafting job with fake items. + */ + boolean isSimulation(); -public interface ICraftingJob -{ + /** + * @return total number of bytes to process this job. + */ + long getByteTotal(); - /** - * @return if this job is a simulation, simulations cannot be submitted and only represent 1 possible future - * crafting job with fake items. - */ - boolean isSimulation(); + /** + * Populates the plan list with stack size, and requestable values that represent the + * stored, and crafting job contents respectively. + * + * @param plan plan + */ + void populatePlan(IItemList plan); - /** - * @return total number of bytes to process this job. - */ - long getByteTotal(); - - /** - * Populates the plan list with stack size, and requestable values that represent the stored, and crafting job - * contents respectively. - * - * @param plan plan - */ - void populatePlan( IItemList plan ); - - /** - * @return the final output of the job. - */ - IAEItemStack getOutput(); + /** + * @return the final output of the job. + */ + IAEItemStack getOutput(); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingLink.java b/src/api/java/appeng/api/networking/crafting/ICraftingLink.java index b3976724..04adf6c7 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingLink.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingLink.java @@ -23,42 +23,39 @@ package appeng.api.networking.crafting; - import net.minecraft.nbt.NBTTagCompound; +public interface ICraftingLink { + /** + * @return true if the job was canceled. + */ + boolean isCanceled(); -public interface ICraftingLink -{ + /** + * @return true if the job was completed. + */ + boolean isDone(); - /** - * @return true if the job was canceled. - */ - boolean isCanceled(); + /** + * cancels the job. + */ + void cancel(); - /** - * @return true if the job was completed. - */ - boolean isDone(); + /** + * @return true if this link was generated without a requesting machine, such as a + * player generated request. + */ + boolean isStandalone(); - /** - * cancels the job. - */ - void cancel(); + /** + * write the link to an NBT Tag + * + * @param tag to be written data + */ + void writeToNBT(NBTTagCompound tag); - /** - * @return true if this link was generated without a requesting machine, such as a player generated request. - */ - boolean isStandalone(); - - /** - * write the link to an NBT Tag - * - * @param tag to be written data - */ - void writeToNBT( NBTTagCompound tag ); - - /** - * @return the crafting ID for this link. - */ - String getCraftingID(); + /** + * @return the crafting ID for this link. + */ + String getCraftingID(); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingMedium.java b/src/api/java/appeng/api/networking/crafting/ICraftingMedium.java index 78b46894..411dab95 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingMedium.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingMedium.java @@ -23,28 +23,26 @@ package appeng.api.networking.crafting; - import net.minecraft.inventory.InventoryCrafting; - /** - * A place to send Items for crafting purposes, this is considered part of AE's External crafting system. + * A place to send Items for crafting purposes, this is considered part of AE's External + * crafting system. */ -public interface ICraftingMedium -{ +public interface ICraftingMedium { + /** + * instruct a medium to create the item represented by the pattern+details, the items + * on the table, and where if possible the output should be directed. + * + * @param patternDetails details + * @param table crafting table + * @return if the pattern was successfully pushed. + */ + boolean pushPattern(ICraftingPatternDetails patternDetails, InventoryCrafting table); - /** - * instruct a medium to create the item represented by the pattern+details, the items on the table, and where if - * possible the output should be directed. - * - * @param patternDetails details - * @param table crafting table - * @return if the pattern was successfully pushed. - */ - boolean pushPattern( ICraftingPatternDetails patternDetails, InventoryCrafting table ); - - /** - * @return if this is false, the crafting engine will refuse to send new jobs to this medium. - */ - boolean isBusy(); + /** + * @return if this is false, the crafting engine will refuse to send new jobs to this + * medium. + */ + boolean isBusy(); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java b/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java index c18305ff..2be4566c 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingPatternDetails.java @@ -23,85 +23,82 @@ package appeng.api.networking.crafting; - import appeng.api.implementations.ICraftingPatternItem; import appeng.api.storage.data.IAEItemStack; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; - /** * do not implement provided by {@link ICraftingPatternItem} *

* caching this INSTANCE will increase performance of validation and checks. */ -public interface ICraftingPatternDetails -{ +public interface ICraftingPatternDetails { + /** + * @return source item. + */ + ItemStack getPattern(); - /** - * @return source item. - */ - ItemStack getPattern(); + /** + * @param slotIndex specific slot index + * @param itemStack item in slot + * @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); - /** - * @param slotIndex specific slot index - * @param itemStack item in slot - * @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 ); + /** + * @return if this pattern is a crafting pattern ( work bench ) + */ + boolean isCraftable(); - /** - * @return if this pattern is a crafting pattern ( work bench ) - */ - boolean isCraftable(); + /** + * @return a list of the inputs, will include nulls. + */ + IAEItemStack[] getInputs(); - /** - * @return a list of the inputs, will include nulls. - */ - IAEItemStack[] getInputs(); + /** + * @return a list of the inputs, will be clean + */ + IAEItemStack[] getCondensedInputs(); - /** - * @return a list of the inputs, will be clean - */ - IAEItemStack[] getCondensedInputs(); + /** + * @return a list of the outputs, will be clean + */ + IAEItemStack[] getCondensedOutputs(); - /** - * @return a list of the outputs, will be clean - */ - IAEItemStack[] getCondensedOutputs(); + /** + * @return a list of the outputs, will include nulls. + */ + IAEItemStack[] getOutputs(); - /** - * @return a list of the outputs, will include nulls. - */ - IAEItemStack[] getOutputs(); + /** + * @return if this pattern is enabled to support substitutions. + */ + boolean canSubstitute(); - /** - * @return if this pattern is enabled to support substitutions. - */ - boolean canSubstitute(); + /** + * Allow using this INSTANCE of the pattern details to preform the crafting action + * with performance enhancements. + * + * @param craftingInv inventory + * @param world crafting world + * @return the crafted ( work bench ) item. + */ + ItemStack getOutput(InventoryCrafting craftingInv, World world); - /** - * Allow using this INSTANCE of the pattern details to preform the crafting action with performance enhancements. - * - * @param craftingInv inventory - * @param world crafting world - * @return the crafted ( work bench ) item. - */ - ItemStack getOutput( InventoryCrafting craftingInv, World world ); + /** + * Get the priority of this pattern + * + * @return the priority of this pattern + */ + int getPriority(); - /** - * Get the priority of this pattern - * - * @return the priority of this pattern - */ - int getPriority(); - - /** - * Set the priority the of this pattern. - * - * @param priority priority of pattern - */ - void setPriority( int priority ); + /** + * 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/ICraftingProvider.java b/src/api/java/appeng/api/networking/crafting/ICraftingProvider.java index 79f89d44..d7bf22f1 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingProvider.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingProvider.java @@ -23,21 +23,17 @@ package appeng.api.networking.crafting; - import appeng.api.networking.events.MENetworkCraftingPatternChange; - /** - * Allows a IGridHost to provide crafting patterns to the network, post a {@link MENetworkCraftingPatternChange} to tell - * AE2 to update. + * Allows a IGridHost to provide crafting patterns to the network, post a {@link + * MENetworkCraftingPatternChange} to tell AE2 to update. */ -public interface ICraftingProvider extends ICraftingMedium -{ - - /** - * called when the network is looking for possible crafting jobs. - * - * @param craftingTracker crafting helper - */ - void provideCrafting( ICraftingProviderHelper craftingTracker ); +public interface ICraftingProvider extends ICraftingMedium { + /** + * called when the network is looking for possible crafting jobs. + * + * @param craftingTracker crafting helper + */ + void provideCrafting(ICraftingProviderHelper craftingTracker); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingProviderHelper.java b/src/api/java/appeng/api/networking/crafting/ICraftingProviderHelper.java index ba666de9..096eb9bd 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingProviderHelper.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingProviderHelper.java @@ -23,23 +23,19 @@ package appeng.api.networking.crafting; - import appeng.api.storage.data.IAEItemStack; - /** * Passed to a ICraftingProvider as a interface to manipulate the available crafting jobs. */ -public interface ICraftingProviderHelper -{ +public interface ICraftingProviderHelper { + /** + * Add new Pattern to AE's crafting cache. + */ + void addCraftingOption(ICraftingMedium medium, ICraftingPatternDetails api); - /** - * Add new Pattern to AE's crafting cache. - */ - void addCraftingOption( ICraftingMedium medium, ICraftingPatternDetails api ); - - /** - * Set an item can Emitable - */ - void setEmitable( IAEItemStack what ); + /** + * Set an item can Emitable + */ + void setEmitable(IAEItemStack what); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java b/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java index 414d3eed..e4703558 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingRequester.java @@ -23,38 +23,35 @@ package appeng.api.networking.crafting; - import appeng.api.config.Actionable; import appeng.api.networking.security.IActionHost; import appeng.api.storage.data.IAEItemStack; import com.google.common.collect.ImmutableSet; +public interface ICraftingRequester extends IActionHost { + /** + * called when the host is added to the grid, and should return all crafting links it + * poses so they can be connected with the cpu that hosts the job. + * + * @return set of jobs, or an empty list. + */ + ImmutableSet getRequestedJobs(); -public interface ICraftingRequester extends IActionHost -{ + /** + * items are injected into the requester as they are completed, any items that cannot + * be taken, or are unwanted can be returned. + * + * @param items item + * @param mode action mode + * @return unwanted item + */ + IAEItemStack + injectCraftedItems(ICraftingLink link, IAEItemStack items, Actionable mode); - /** - * called when the host is added to the grid, and should return all crafting links it poses so they can be connected - * with the cpu that hosts the job. - * - * @return set of jobs, or an empty list. - */ - ImmutableSet getRequestedJobs(); - - /** - * items are injected into the requester as they are completed, any items that cannot be taken, or are unwanted can - * be returned. - * - * @param items item - * @param mode action mode - * @return unwanted item - */ - 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 ); + /** + * 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); } diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingWatcher.java b/src/api/java/appeng/api/networking/crafting/ICraftingWatcher.java index 080d36d9..3f413253 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingWatcher.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingWatcher.java @@ -23,13 +23,8 @@ package appeng.api.networking.crafting; +import java.util.Collection; import appeng.api.storage.data.IAEStack; -import java.util.Collection; - - -public interface ICraftingWatcher extends Collection -{ - -} +public interface ICraftingWatcher extends Collection {} diff --git a/src/api/java/appeng/api/networking/crafting/ICraftingWatcherHost.java b/src/api/java/appeng/api/networking/crafting/ICraftingWatcherHost.java index ed6f6f9c..d96bab37 100644 --- a/src/api/java/appeng/api/networking/crafting/ICraftingWatcherHost.java +++ b/src/api/java/appeng/api/networking/crafting/ICraftingWatcherHost.java @@ -23,26 +23,23 @@ package appeng.api.networking.crafting; - import appeng.api.storage.data.IAEItemStack; +public interface ICraftingWatcherHost { + /** + * provides the ICraftingWatcher for this host, for the current network, is called + * when the hot changes networks. You do not need to clear your old watcher, its + * already been removed by the time this gets called. + * + * @param newWatcher crafting watcher for this host + */ + void updateWatcher(ICraftingWatcher newWatcher); -public interface ICraftingWatcherHost -{ - - /** - * provides the ICraftingWatcher for this host, for the current network, is called when the hot changes networks. - * You do not need to clear your old watcher, its already been removed by the time this gets called. - * - * @param newWatcher crafting watcher for this host - */ - void updateWatcher( ICraftingWatcher newWatcher ); - - /** - * Called when a crafting status changes. - * - * @param craftingGrid current crafting grid - * @param what change - */ - void onRequestChange( ICraftingGrid craftingGrid, IAEItemStack what ); + /** + * Called when a crafting status changes. + * + * @param craftingGrid current crafting grid + * @param what change + */ + void onRequestChange(ICraftingGrid craftingGrid, IAEItemStack what); } diff --git a/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java b/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java index 715a61f5..d8310f6d 100644 --- a/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java +++ b/src/api/java/appeng/api/networking/energy/IAEPowerStorage.java @@ -23,48 +23,47 @@ 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. + * Used to access information about AE's various power accepting blocks for monitoring + * purposes. */ -public interface IAEPowerStorage extends IEnergySource -{ +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 mode action mode + * @return amount of power which was unable to be stored + */ + double injectAEPower(double amt, Actionable mode); - /** - * 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 mode action mode - * @return amount of power which was unable to be stored - */ - double injectAEPower( double amt, Actionable mode ); + /** + * @return the current maximum power ( this can change :P ) + */ + double getAEMaxPower(); - /** - * @return the current maximum power ( this can change :P ) - */ - double getAEMaxPower(); + /** + * @return the current AE Power Level, this may exceed getMEMaxPower() + */ + double getAECurrentPower(); - /** - * @return the current AE Power Level, this may exceed getMEMaxPower() - */ - double getAECurrentPower(); + /** + * Checked on network reset to see if your block can be used as a public power storage + * ( use getPowerFlow to control the behavior ) + * + * @return true if it can be used as a public power storage + */ + boolean isAEPublicPowerStorage(); - /** - * Checked on network reset to see if your block can be used as a public power storage ( use getPowerFlow to control - * the behavior ) - * - * @return true if it can be used as a public power storage - */ - boolean isAEPublicPowerStorage(); - - /** - * Control the power flow by telling what the network can do, either add? or subtract? or both! - * - * @return access restriction what the network can do - */ - AccessRestriction getPowerFlow(); + /** + * Control the power flow by telling what the network can do, either add? or subtract? + * or both! + * + * @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 ba6105cf..8114814d 100644 --- a/src/api/java/appeng/api/networking/energy/IEnergyGrid.java +++ b/src/api/java/appeng/api/networking/energy/IEnergyGrid.java @@ -23,82 +23,83 @@ 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. */ -public interface IEnergyGrid extends IGridCache, IEnergySource, IEnergyGridProvider -{ +public interface IEnergyGrid extends IGridCache, IEnergySource, IEnergyGridProvider { + /** + * @return the current calculated idle energy drain each tick, is used internally to + * drain power for each tick. + */ + double getIdlePowerUsage(); - /** - * @return the current calculated idle energy drain each tick, is used internally to drain power for each tick. - */ - double getIdlePowerUsage(); + /** + * @return the average power drain over the past 10 ticks, includes idle usage during + * this time, and all use of + * extractPower. + */ + double getAvgPowerUsage(); - /** - * @return the average power drain over the past 10 ticks, includes idle usage during this time, and all use of - * extractPower. - */ - double getAvgPowerUsage(); + /** + * @return the average energy injected into the system per tick, for the last 10 + * ticks. + */ + double getAvgPowerInjection(); - /** - * @return the average energy injected into the system per tick, for the last 10 ticks. - */ - double getAvgPowerInjection(); + /** + * AE maintains an idle draw of power separate from active power draw, it condenses + * this into a single operation that determines the networks "powered state" if the + * network is considered off-line, your machines should not function.

+ * {@link MENetworkPowerStatusChange} events are posted when this value changes if you + * need to be notified of the change, most machines can simply test the value when + * they operate. + * + * @return if the network is powered or not. + */ + boolean isNetworkPowered(); - /** - * AE maintains an idle draw of power separate from active power draw, it condenses this into a single operation - * that determines the networks "powered state" if the network is considered off-line, your machines should not - * function. - *

- * {@link MENetworkPowerStatusChange} events are posted when this value changes if you need to be notified of the - * change, most machines can simply test the value when they operate. - * - * @return if the network is powered or not. - */ - boolean isNetworkPowered(); + /** + * AE will accept any power, and store it, to maintain sanity please don't send more + * then 10,000 at a time.

IMPORTANT: Network power knows no bounds, for less spamy + * power flow, networks can store more then their allotted storage, however, it should + * be kept to a minimum, to help with this, this method returns the networks current + * OVERFLOW, this is not energy you can store some where else, its already stored in + * the network, you can extract it if you want, however it it owned by the network, + * this is different then IAEEnergyStore

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? + * @return the amount of power that the network has OVER the limit. + */ + double injectPower(double amt, Actionable mode); - /** - * AE will accept any power, and store it, to maintain sanity please don't send more then 10,000 at a time. - *

- * IMPORTANT: Network power knows no bounds, for less spamy power flow, networks can store more then their allotted - * storage, however, it should be kept to a minimum, to help with this, this method returns the networks current - * OVERFLOW, this is not energy you can store some where else, its already stored in the network, you can extract it - * if you want, however it it owned by the network, this is different then IAEEnergyStore - *

- * 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? - * @return the amount of power that the network has OVER the limit. - */ - double injectPower( double amt, Actionable mode ); + /** + * this is should be considered an estimate, and not relied upon for real + * calculations. + * + * @return estimated available power. + */ + double getStoredPower(); - /** - * this is should be considered an estimate, and not relied upon for real calculations. - * - * @return estimated available power. - */ - double getStoredPower(); + /** + * this is should be considered an estimate, and not relied upon for real + * calculations. + * + * @return estimated available power. + */ + double getMaxStoredPower(); - /** - * this is should be considered an estimate, and not relied upon for real calculations. - * - * @return estimated available power. - */ - double getMaxStoredPower(); - - /** - * Calculation will be capped at maxRequired, this improves performance by limiting the number of nodes needed to - * calculate the demand. - * - * @return Amount of power required to charge the grid, in AE. - */ - double getEnergyDemand( double maxRequired ); + /** + * Calculation will be capped at maxRequired, this improves performance by limiting + * the number of nodes needed to calculate the demand. + * + * @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/IEnergyGridProvider.java b/src/api/java/appeng/api/networking/energy/IEnergyGridProvider.java index 1714fa81..c6f9ed3b 100644 --- a/src/api/java/appeng/api/networking/energy/IEnergyGridProvider.java +++ b/src/api/java/appeng/api/networking/energy/IEnergyGridProvider.java @@ -23,29 +23,26 @@ package appeng.api.networking.energy; - -import appeng.api.config.Actionable; - import java.util.Set; +import appeng.api.config.Actionable; /** * internal use only. */ -public interface IEnergyGridProvider -{ - /** - * internal use only - */ - double extractAEPower( double amt, Actionable mode, Set seen ); +public interface IEnergyGridProvider { + /** + * internal use only + */ + double extractAEPower(double amt, Actionable mode, Set seen); - /** - * internal use only - */ - double injectAEPower( double amt, Actionable mode, Set seen ); + /** + * internal use only + */ + double injectAEPower(double amt, Actionable mode, Set seen); - /** - * internal use only - */ - double getEnergyDemand( double d, Set seen ); + /** + * internal use only + */ + double getEnergyDemand(double d, Set seen); } diff --git a/src/api/java/appeng/api/networking/energy/IEnergySource.java b/src/api/java/appeng/api/networking/energy/IEnergySource.java index bffc5833..d28da293 100644 --- a/src/api/java/appeng/api/networking/energy/IEnergySource.java +++ b/src/api/java/appeng/api/networking/energy/IEnergySource.java @@ -23,20 +23,17 @@ 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 mode should the action be simulated or performed? - * @return returns extracted power. - */ - double extractAEPower( double amt, Actionable mode, PowerMultiplier usePowerMultiplier ); +public interface IEnergySource { + /** + * Extract power from the network. + * + * @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/energy/IEnergyWatcher.java b/src/api/java/appeng/api/networking/energy/IEnergyWatcher.java index 5543df6d..554fbf1c 100644 --- a/src/api/java/appeng/api/networking/energy/IEnergyWatcher.java +++ b/src/api/java/appeng/api/networking/energy/IEnergyWatcher.java @@ -23,11 +23,6 @@ package appeng.api.networking.energy; - import java.util.Collection; - -public interface IEnergyWatcher extends Collection -{ - -} +public interface IEnergyWatcher extends Collection {} diff --git a/src/api/java/appeng/api/networking/energy/IEnergyWatcherHost.java b/src/api/java/appeng/api/networking/energy/IEnergyWatcherHost.java index 5f5237f0..93d689ef 100644 --- a/src/api/java/appeng/api/networking/energy/IEnergyWatcherHost.java +++ b/src/api/java/appeng/api/networking/energy/IEnergyWatcherHost.java @@ -23,22 +23,20 @@ package appeng.api.networking.energy; +public interface IEnergyWatcherHost { + /** + * provides the IEnergyWatcher for this host, for the current network, is called when + * the hot changes networks. You do not need to clear your old watcher, its already + * been removed by the time this gets called. + * + * @param newWatcher new watcher + */ + void updateWatcher(IEnergyWatcher newWatcher); -public interface IEnergyWatcherHost -{ - - /** - * provides the IEnergyWatcher for this host, for the current network, is called when the hot changes networks. You - * do not need to clear your old watcher, its already been removed by the time this gets called. - * - * @param newWatcher new watcher - */ - void updateWatcher( IEnergyWatcher newWatcher ); - - /** - * Called when a threshold is crossed. - * - * @param energyGrid grid - */ - void onThresholdPass( IEnergyGrid energyGrid ); + /** + * Called when a threshold is crossed. + * + * @param energyGrid grid + */ + void onThresholdPass(IEnergyGrid energyGrid); } diff --git a/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java b/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java index b668a818..58f6cac5 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkBootingStatusChange.java @@ -23,17 +23,12 @@ 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() *

* Note: Most machines just need to check {@link IGridNode}.isActive() */ -public class MENetworkBootingStatusChange extends MENetworkEvent -{ - -} +public class MENetworkBootingStatusChange extends MENetworkEvent {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java b/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java index 7fce5b45..8c4372a2 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java +++ b/src/api/java/appeng/api/networking/events/MENetworkCellArrayUpdate.java @@ -23,7 +23,6 @@ package appeng.api.networking.events; - /** * Posted by storage devices to inform AE to refresh its storage structure. *

@@ -33,7 +32,4 @@ package appeng.api.networking.events; * you do not need to send this event when your node is added / removed from the * grid. */ -public class MENetworkCellArrayUpdate extends MENetworkEvent -{ - -} +public class MENetworkCellArrayUpdate extends MENetworkEvent {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkChannelChanged.java b/src/api/java/appeng/api/networking/events/MENetworkChannelChanged.java index b8663114..4423c144 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkChannelChanged.java +++ b/src/api/java/appeng/api/networking/events/MENetworkChannelChanged.java @@ -23,21 +23,16 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; - /** - * Posted by storage devices to inform AE the channel cache that the included node has changed its mind about its - * channel requirements. + * Posted by storage devices to inform AE the channel cache that the included node has + * changed its mind about its channel requirements. */ -public class MENetworkChannelChanged extends MENetworkEvent -{ +public class MENetworkChannelChanged extends MENetworkEvent { + public final IGridNode node; - public final IGridNode node; - - public MENetworkChannelChanged( final IGridNode n ) - { - this.node = n; - } + public MENetworkChannelChanged(final IGridNode n) { + this.node = n; + } } diff --git a/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java b/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java index 722b7902..966433ff 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java +++ b/src/api/java/appeng/api/networking/events/MENetworkChannelsChanged.java @@ -23,16 +23,11 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridHost; - /** * Posted to the {@link IGridHost} when the channels on the node connections are altered. *

* Never posted IGridCaches. */ -public class MENetworkChannelsChanged extends MENetworkEvent -{ - -} +public class MENetworkChannelsChanged extends MENetworkEvent {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkControllerChange.java b/src/api/java/appeng/api/networking/events/MENetworkControllerChange.java index 040a3d4a..b2ec9a12 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkControllerChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkControllerChange.java @@ -23,13 +23,9 @@ package appeng.api.networking.events; - /** * Event posted when the networks controller state changes, this can be from no * controller to 1 controller, or any time the network changes from conflicted * to not conflicted. */ -public class MENetworkControllerChange extends MENetworkEvent -{ - -} +public class MENetworkControllerChange extends MENetworkEvent {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java b/src/api/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java index 4a92e28c..4a648f9d 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkCraftingCpuChange.java @@ -23,17 +23,12 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; +public class MENetworkCraftingCpuChange extends MENetworkEvent { + public final IGridNode node; -public class MENetworkCraftingCpuChange extends MENetworkEvent -{ - - public final IGridNode node; - - public MENetworkCraftingCpuChange( final IGridNode n ) - { - this.node = n; - } + public MENetworkCraftingCpuChange(final IGridNode n) { + this.node = n; + } } diff --git a/src/api/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java b/src/api/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java index 77b6a2e3..5f2ddcf6 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkCraftingPatternChange.java @@ -23,20 +23,15 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingProvider; +public class MENetworkCraftingPatternChange extends MENetworkEvent { + public final ICraftingProvider provider; + public final IGridNode node; -public class MENetworkCraftingPatternChange extends MENetworkEvent -{ - - public final ICraftingProvider provider; - public final IGridNode node; - - public MENetworkCraftingPatternChange( final ICraftingProvider p, final IGridNode n ) - { - this.provider = p; - this.node = n; - } + public MENetworkCraftingPatternChange(final ICraftingProvider p, final IGridNode n) { + this.provider = p; + this.node = n; + } } diff --git a/src/api/java/appeng/api/networking/events/MENetworkEvent.java b/src/api/java/appeng/api/networking/events/MENetworkEvent.java index f40b183a..f9d56c1e 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkEvent.java +++ b/src/api/java/appeng/api/networking/events/MENetworkEvent.java @@ -23,56 +23,48 @@ package appeng.api.networking.events; - import appeng.api.networking.IGrid; - /** * Part of AE's Event Bus. *

* Posted via {@link IGrid}.postEvent or {@link IGrid}.postEventTo */ -public class MENetworkEvent -{ +public class MENetworkEvent { + private int visited = 0; + private boolean canceled = false; - private int visited = 0; - private boolean canceled = false; + /** + * Call to prevent AE from posting the event to any further objects. + */ + public void cancel() { + this.canceled = true; + } - /** - * Call to prevent AE from posting the event to any further objects. - */ - public void cancel() - { - this.canceled = true; - } + /** + * called by AE after each object is called to cancel any future calls. + * + * @return true to cancel future calls + */ + public boolean isCanceled() { + return this.canceled; + } - /** - * called by AE after each object is called to cancel any future calls. - * - * @return true to cancel future calls - */ - public boolean isCanceled() - { - return this.canceled; - } + /** + * the number of objects that were visited by the event. + * + * @return number of visitors + */ + public int getVisitedObjects() { + return this.visited; + } - /** - * the number of objects that were visited by the event. - * - * @return number of visitors - */ - public int getVisitedObjects() - { - return this.visited; - } - - /** - * Called by AE after iterating the event subscribers. - * - * @param v current number of visitors - */ - public void setVisitedObjects( final int v ) - { - this.visited = v; - } + /** + * Called by AE after iterating the event subscribers. + * + * @param v current number of visitors + */ + public void setVisitedObjects(final int v) { + this.visited = v; + } } diff --git a/src/api/java/appeng/api/networking/events/MENetworkEventSubscribe.java b/src/api/java/appeng/api/networking/events/MENetworkEventSubscribe.java index c66e69b6..48d679a7 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkEventSubscribe.java +++ b/src/api/java/appeng/api/networking/events/MENetworkEventSubscribe.java @@ -23,19 +23,14 @@ package appeng.api.networking.events; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import appeng.api.networking.IGridCache; import appeng.api.networking.IGridHost; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - - /** * Usable on any {@link IGridHost}, or {@link IGridCache} */ -@Retention( RetentionPolicy.RUNTIME ) -public @interface MENetworkEventSubscribe -{ - -} +@Retention(RetentionPolicy.RUNTIME) +public @interface MENetworkEventSubscribe {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java b/src/api/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java index 1fddaa8a..7f5727ea 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java +++ b/src/api/java/appeng/api/networking/events/MENetworkPostCacheConstruction.java @@ -23,12 +23,8 @@ package appeng.api.networking.events; - /** * Posted after all the caches are available, but before the grid is fully * constructed, can be used to perform cross cache construction processes. */ -public class MENetworkPostCacheConstruction extends MENetworkEvent -{ - -} +public class MENetworkPostCacheConstruction extends MENetworkEvent {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java b/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java index 85915e84..1380c206 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkPowerIdleChange.java @@ -23,10 +23,8 @@ 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 @@ -34,13 +32,10 @@ import appeng.api.networking.IGridNode; *

* you do not need to send this event when your node is added / removed from the grid. */ -public class MENetworkPowerIdleChange extends MENetworkEvent -{ +public class MENetworkPowerIdleChange extends MENetworkEvent { + public final IGridNode node; - public final IGridNode node; - - public MENetworkPowerIdleChange( final IGridNode nodeThatChanged ) - { - this.node = nodeThatChanged; - } + public MENetworkPowerIdleChange(final 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 a2d2d163..6d4e1e25 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkPowerStatusChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkPowerStatusChange.java @@ -23,11 +23,9 @@ 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 @@ -35,7 +33,4 @@ import appeng.api.networking.energy.IEnergyGrid; *

* Note: Most machines just need to check {@link IGridNode}.isActive() */ -public class MENetworkPowerStatusChange extends MENetworkEvent -{ - -} +public class MENetworkPowerStatusChange extends MENetworkEvent {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java b/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java index c97c05f3..c12ffa79 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java +++ b/src/api/java/appeng/api/networking/events/MENetworkPowerStorage.java @@ -23,10 +23,8 @@ 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. @@ -36,28 +34,24 @@ import appeng.api.networking.energy.IAEPowerStorage; *

* you do not need to send this event when your node is added / removed from the grid. */ -public class MENetworkPowerStorage extends MENetworkEvent -{ +public class MENetworkPowerStorage extends MENetworkEvent { + public final IAEPowerStorage storage; + public final PowerEventType type; - public final IAEPowerStorage storage; - public final PowerEventType type; + public MENetworkPowerStorage(final IAEPowerStorage t, final PowerEventType y) { + this.storage = t; + this.type = y; + } - public MENetworkPowerStorage( final IAEPowerStorage t, final PowerEventType y ) - { - this.storage = t; - this.type = y; - } + public enum PowerEventType { + /** + * informs the network this tile is ready to receive power again. + */ + REQUEST_POWER, - public enum PowerEventType - { - /** - * informs the network this tile is ready to receive power again. - */ - REQUEST_POWER, - - /** - * informs the network this tile is ready to provide power again. - */ - PROVIDE_POWER - } + /** + * informs the network this tile is ready to provide power again. + */ + PROVIDE_POWER + } } diff --git a/src/api/java/appeng/api/networking/events/MENetworkSecurityChange.java b/src/api/java/appeng/api/networking/events/MENetworkSecurityChange.java index 968d8475..d2e7e036 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkSecurityChange.java +++ b/src/api/java/appeng/api/networking/events/MENetworkSecurityChange.java @@ -23,11 +23,7 @@ package appeng.api.networking.events; - /** * Posted by the security framework when permissions change */ -public class MENetworkSecurityChange extends MENetworkEvent -{ - -} +public class MENetworkSecurityChange extends MENetworkEvent {} diff --git a/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java b/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java index ea666a12..0f9ca24f 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java +++ b/src/api/java/appeng/api/networking/events/MENetworkSpatialEvent.java @@ -23,25 +23,21 @@ package appeng.api.networking.events; - import appeng.api.networking.IGridHost; - /** * An event that is posted whenever a spatial IO is active, called for IGridCache */ -public class MENetworkSpatialEvent extends MENetworkEvent -{ - public final IGridHost host; - public final double spatialEnergyUsage; +public class MENetworkSpatialEvent extends MENetworkEvent { + public final IGridHost host; + public final double spatialEnergyUsage; - /** - * @param SpatialIO ( INSTANCE of the SpatialIO block ) - * @param EnergyUsage ( the amount of energy that the SpatialIO uses) - */ - public MENetworkSpatialEvent( final IGridHost SpatialIO, final double EnergyUsage ) - { - this.host = SpatialIO; - this.spatialEnergyUsage = EnergyUsage; - } + /** + * @param SpatialIO ( INSTANCE of the SpatialIO block ) + * @param EnergyUsage ( the amount of energy that the SpatialIO uses) + */ + public MENetworkSpatialEvent(final IGridHost SpatialIO, final double EnergyUsage) { + this.host = SpatialIO; + this.spatialEnergyUsage = EnergyUsage; + } } diff --git a/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java b/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java index a919da07..050414b4 100644 --- a/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java +++ b/src/api/java/appeng/api/networking/events/MENetworkStorageEvent.java @@ -23,28 +23,21 @@ 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. - *

- * this is the least useful method of getting info about changes in the network. - *

- * Do not modify the list or its contents in anyway. + * posted by the network when the networks Storage Changes, you can use the currentItems + * list to check levels, and update status.

this is the least useful method of getting + * info about changes in the network.

Do not modify the list or its contents in + * anyway. */ -public class MENetworkStorageEvent extends MENetworkEvent -{ +public class MENetworkStorageEvent extends MENetworkEvent { + public final IMEMonitor monitor; + public final StorageChannel channel; - public final IMEMonitor monitor; - public final StorageChannel channel; - - public MENetworkStorageEvent( final IMEMonitor o, final StorageChannel chan ) - { - this.monitor = o; - this.channel = chan; - } + public MENetworkStorageEvent(final IMEMonitor o, final StorageChannel chan) { + this.monitor = o; + this.channel = chan; + } } diff --git a/src/api/java/appeng/api/networking/pathing/ControllerState.java b/src/api/java/appeng/api/networking/pathing/ControllerState.java index c027d673..ede4d143 100644 --- a/src/api/java/appeng/api/networking/pathing/ControllerState.java +++ b/src/api/java/appeng/api/networking/pathing/ControllerState.java @@ -23,26 +23,24 @@ package appeng.api.networking.pathing; +public enum ControllerState { + /** + * No controller blocks are present in the network. + */ + NO_CONTROLLER, -public enum ControllerState -{ - /** - * No controller blocks are present in the network. - */ - NO_CONTROLLER, + /** + * Controller rules followed, booting enabled. + */ + CONTROLLER_ONLINE, - /** - * Controller rules followed, booting enabled. - */ - CONTROLLER_ONLINE, + /** + * Controller rules not followed, lock up while booting. + */ + CONTROLLER_CONFLICT, - /** - * Controller rules not followed, lock up while booting. - */ - CONTROLLER_CONFLICT, - - /** - * Controller is online and has infinite channels - */ - CONTROLLER_INFINITE + /** + * Controller is online and has infinite channels + */ + CONTROLLER_INFINITE } diff --git a/src/api/java/appeng/api/networking/pathing/IPathingGrid.java b/src/api/java/appeng/api/networking/pathing/IPathingGrid.java index f9a592ee..dd195bd4 100644 --- a/src/api/java/appeng/api/networking/pathing/IPathingGrid.java +++ b/src/api/java/appeng/api/networking/pathing/IPathingGrid.java @@ -23,26 +23,22 @@ package appeng.api.networking.pathing; - import appeng.api.networking.IGridCache; +public interface IPathingGrid extends IGridCache { + /** + * @return true if the network is in its booting stage + */ + boolean isNetworkBooting(); -public interface IPathingGrid extends IGridCache -{ + /** + * @return the controller state of the network, useful if you want to + * require a controller for a feature. + */ + ControllerState getControllerState(); - /** - * @return true if the network is in its booting stage - */ - boolean isNetworkBooting(); - - /** - * @return the controller state of the network, useful if you want to - * require a controller for a feature. - */ - ControllerState getControllerState(); - - /** - * trigger a network reset, booting, path-finding and all. - */ - void repath(); + /** + * trigger a network reset, booting, path-finding and all. + */ + void repath(); } \ No newline at end of file diff --git a/src/api/java/appeng/api/networking/security/BaseActionSource.java b/src/api/java/appeng/api/networking/security/BaseActionSource.java index bfaa66a2..e0dbd61a 100644 --- a/src/api/java/appeng/api/networking/security/BaseActionSource.java +++ b/src/api/java/appeng/api/networking/security/BaseActionSource.java @@ -23,17 +23,12 @@ package appeng.api.networking.security; +public class BaseActionSource { + public boolean isPlayer() { + return false; + } -public class BaseActionSource -{ - - public boolean isPlayer() - { - return false; - } - - public boolean isMachine() - { - return false; - } + public boolean isMachine() { + return false; + } } diff --git a/src/api/java/appeng/api/networking/security/IActionHost.java b/src/api/java/appeng/api/networking/security/IActionHost.java index 90c056d8..ada2f498 100644 --- a/src/api/java/appeng/api/networking/security/IActionHost.java +++ b/src/api/java/appeng/api/networking/security/IActionHost.java @@ -23,21 +23,17 @@ package appeng.api.networking.security; - import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; - -public interface IActionHost extends IGridHost -{ - - /** - * Used to for calculating security rules, you must supply a node from your - * IGridHost for the security test, this should be the primary node for the - * machine, unless the action is preformed by a non primary node. - * - * @return the the gridnode that actions from this IGridHost are preformed - * by. - */ - IGridNode getActionableNode(); +public interface IActionHost extends IGridHost { + /** + * Used to for calculating security rules, you must supply a node from your + * IGridHost for the security test, this should be the primary node for the + * machine, unless the action is preformed by a non primary node. + * + * @return the the gridnode that actions from this IGridHost are preformed + * by. + */ + IGridNode getActionableNode(); } diff --git a/src/api/java/appeng/api/networking/security/ISecurityGrid.java b/src/api/java/appeng/api/networking/security/ISecurityGrid.java index ef1d73d4..9db95573 100644 --- a/src/api/java/appeng/api/networking/security/ISecurityGrid.java +++ b/src/api/java/appeng/api/networking/security/ISecurityGrid.java @@ -23,40 +23,37 @@ package appeng.api.networking.security; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGridCache; import net.minecraft.entity.player.EntityPlayer; +public interface ISecurityGrid extends IGridCache { + /** + * @return true if a security provider is in the network ( and only 1 ) + */ + boolean isAvailable(); -public interface ISecurityGrid extends IGridCache -{ + /** + * Check if a player has permissions. + * + * @param player to be checked player + * @param perm checked permissions + * @return true if the player has permissions. + */ + boolean hasPermission(EntityPlayer player, SecurityPermissions perm); - /** - * @return true if a security provider is in the network ( and only 1 ) - */ - boolean isAvailable(); + /** + * Check if a player has permissions. + * + * @param playerID id of player + * @param perm checked permissions + * @return true if the player has permissions. + */ + boolean hasPermission(int playerID, SecurityPermissions perm); - /** - * Check if a player has permissions. - * - * @param player to be checked player - * @param perm checked permissions - * @return true if the player has permissions. - */ - boolean hasPermission( EntityPlayer player, SecurityPermissions perm ); - - /** - * Check if a player has permissions. - * - * @param playerID id of player - * @param perm checked permissions - * @return true if the player has permissions. - */ - boolean hasPermission( int playerID, SecurityPermissions perm ); - - /** - * @return PlayerID of the admin, or owner, this is the person who placed the security block. - */ - int getOwner(); + /** + * @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/ISecurityProvider.java b/src/api/java/appeng/api/networking/security/ISecurityProvider.java index 8ff1a5fd..6a9661e1 100644 --- a/src/api/java/appeng/api/networking/security/ISecurityProvider.java +++ b/src/api/java/appeng/api/networking/security/ISecurityProvider.java @@ -23,40 +23,37 @@ package appeng.api.networking.security; - -import appeng.api.config.SecurityPermissions; - import java.util.EnumSet; import java.util.HashMap; +import appeng.api.config.SecurityPermissions; /** * Implemented on Security Terminal to interface with security cache. */ -public interface ISecurityProvider -{ +public interface ISecurityProvider { + /** + * used to represent the security key for the network, should be based on a unique + * timestamp. + * + * @return unique key. + */ + long getSecurityKey(); - /** - * used to represent the security key for the network, should be based on a unique timestamp. - * - * @return unique key. - */ - long getSecurityKey(); + /** + * Push permission data into security cache. + * + * @param playerPerms player permissions + */ + void readPermissions(HashMap> playerPerms); - /** - * Push permission data into security cache. - * - * @param playerPerms player permissions - */ - void readPermissions( HashMap> playerPerms ); + /** + * @return is security on or off? + */ + boolean isSecurityEnabled(); - /** - * @return is security on or off? - */ - boolean isSecurityEnabled(); - - /** - * @return player ID for who placed the security provider. - */ - int getOwner(); + /** + * @return player ID for who placed the security provider. + */ + 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 e2070186..4ad95481 100644 --- a/src/api/java/appeng/api/networking/security/ISecurityRegistry.java +++ b/src/api/java/appeng/api/networking/security/ISecurityRegistry.java @@ -23,23 +23,19 @@ package appeng.api.networking.security; - -import appeng.api.config.SecurityPermissions; - import java.util.EnumSet; +import appeng.api.config.SecurityPermissions; /** * Used by vanilla Security Terminal to post biometric data into the security cache. */ -public interface ISecurityRegistry -{ - - /** - * Submit Permissions into the register. - * - * @param playerID player id - * @param permissions permissions of player - */ - void addPlayer( int playerID, EnumSet permissions ); +public interface ISecurityRegistry { + /** + * Submit Permissions into the register. + * + * @param playerID player id + * @param permissions permissions of player + */ + 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 40a46536..8a6d797b 100644 --- a/src/api/java/appeng/api/networking/security/MachineSource.java +++ b/src/api/java/appeng/api/networking/security/MachineSource.java @@ -23,20 +23,15 @@ package appeng.api.networking.security; +public class MachineSource extends BaseActionSource { + public final IActionHost via; -public class MachineSource extends BaseActionSource -{ + public MachineSource(final IActionHost v) { + this.via = v; + } - public final IActionHost via; - - public MachineSource( final IActionHost v ) - { - this.via = v; - } - - @Override - public boolean isMachine() - { - return true; - } + @Override + public boolean isMachine() { + return true; + } } diff --git a/src/api/java/appeng/api/networking/security/PlayerSource.java b/src/api/java/appeng/api/networking/security/PlayerSource.java index fc6cb37e..69009ae3 100644 --- a/src/api/java/appeng/api/networking/security/PlayerSource.java +++ b/src/api/java/appeng/api/networking/security/PlayerSource.java @@ -23,25 +23,19 @@ package appeng.api.networking.security; - import net.minecraft.entity.player.EntityPlayer; +public class PlayerSource extends BaseActionSource { + public final EntityPlayer player; + public final IActionHost via; -public class PlayerSource extends BaseActionSource -{ + public PlayerSource(final EntityPlayer p, final IActionHost v) { + this.player = p; + this.via = v; + } - public final EntityPlayer player; - public final IActionHost via; - - public PlayerSource( final EntityPlayer p, final IActionHost v ) - { - this.player = p; - this.via = v; - } - - @Override - public boolean isPlayer() - { - return true; - } + @Override + public boolean isPlayer() { + return true; + } } diff --git a/src/api/java/appeng/api/networking/spatial/ISpatialCache.java b/src/api/java/appeng/api/networking/spatial/ISpatialCache.java index d70b9bda..041e49a8 100644 --- a/src/api/java/appeng/api/networking/spatial/ISpatialCache.java +++ b/src/api/java/appeng/api/networking/spatial/ISpatialCache.java @@ -23,41 +23,38 @@ package appeng.api.networking.spatial; - import appeng.api.networking.IGridCache; import appeng.api.util.DimensionalCoord; +public interface ISpatialCache extends IGridCache { + /** + * @return true if a region is defined at all, it doesn't have to be valid, but all + * points must be in the same world. + */ + boolean hasRegion(); -public interface ISpatialCache extends IGridCache -{ + /** + * @return true if the region defined is valid according to all rules. + */ + boolean isValidRegion(); - /** - * @return true if a region is defined at all, it doesn't have to be valid, but all points must be in the same world. - */ - boolean hasRegion(); + /** + * @return the minimum anchor point for the spatial region. + */ + DimensionalCoord getMin(); - /** - * @return true if the region defined is valid according to all rules. - */ - boolean isValidRegion(); + /** + * @return the maximum anchor point for the spatial region. + */ + DimensionalCoord getMax(); - /** - * @return the minimum anchor point for the spatial region. - */ - DimensionalCoord getMin(); + /** + * @return how many AE units are required to preform the activation + */ + long requiredPower(); - /** - * @return the maximum anchor point for the spatial region. - */ - DimensionalCoord getMax(); - - /** - * @return how many AE units are required to preform the activation - */ - long requiredPower(); - - /** - * @return current 100% - 0% efficiency. - */ - float currentEfficiency(); + /** + * @return current 100% - 0% efficiency. + */ + float currentEfficiency(); } diff --git a/src/api/java/appeng/api/networking/storage/IBaseMonitor.java b/src/api/java/appeng/api/networking/storage/IBaseMonitor.java index 2d906ee3..b8932eb6 100644 --- a/src/api/java/appeng/api/networking/storage/IBaseMonitor.java +++ b/src/api/java/appeng/api/networking/storage/IBaseMonitor.java @@ -23,21 +23,18 @@ package appeng.api.networking.storage; - import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.data.IAEStack; +public interface IBaseMonitor { + /** + * add a new Listener to the monitor, be sure to properly remove yourself when your + * done. + */ + void addListener(IMEMonitorHandlerReceiver l, Object verificationToken); -public interface IBaseMonitor -{ - - /** - * add a new Listener to the monitor, be sure to properly remove yourself when your done. - */ - void addListener( IMEMonitorHandlerReceiver l, Object verificationToken ); - - /** - * remove a Listener to the monitor. - */ - void removeListener( IMEMonitorHandlerReceiver l ); + /** + * remove a Listener to the monitor. + */ + void removeListener(IMEMonitorHandlerReceiver l); } diff --git a/src/api/java/appeng/api/networking/storage/IStackWatcher.java b/src/api/java/appeng/api/networking/storage/IStackWatcher.java index 6e829088..518746d3 100644 --- a/src/api/java/appeng/api/networking/storage/IStackWatcher.java +++ b/src/api/java/appeng/api/networking/storage/IStackWatcher.java @@ -23,13 +23,8 @@ package appeng.api.networking.storage; +import java.util.Collection; import appeng.api.storage.data.IAEStack; -import java.util.Collection; - - -public interface IStackWatcher extends Collection -{ - -} +public interface IStackWatcher extends Collection {} diff --git a/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java b/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java index f2a9f3dc..0f861840 100644 --- a/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java +++ b/src/api/java/appeng/api/networking/storage/IStackWatcherHost.java @@ -23,32 +23,35 @@ 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 { + /** + * provides the IStackWatcher for this host, for the current network, is called when + * the hot changes networks. You do not need to clear your old watcher, its already + * been removed by the time this gets called. + * + * @param newWatcher stack watcher + */ + void updateWatcher(IStackWatcher newWatcher); -public interface IStackWatcherHost -{ - - /** - * provides the IStackWatcher for this host, for the current network, is called when the hot changes networks. You - * do not need to clear your old watcher, its already been removed by the time this gets called. - * - * @param newWatcher stack watcher - */ - void updateWatcher( IStackWatcher newWatcher ); - - /** - * Called when a watched item changes amounts. - * - * @param o changed item list - * @param fullStack old stack - * @param diffStack new stack - * @param src action source - * @param chan storage channel - */ - void onStackChange( IItemList o, IAEStack fullStack, IAEStack diffStack, BaseActionSource src, StorageChannel chan ); + /** + * Called when a watched item changes amounts. + * + * @param o changed item list + * @param fullStack old stack + * @param diffStack new stack + * @param src action source + * @param chan storage channel + */ + 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 101ad2fe..d3094e36 100644 --- a/src/api/java/appeng/api/networking/storage/IStorageGrid.java +++ b/src/api/java/appeng/api/networking/storage/IStorageGrid.java @@ -23,7 +23,6 @@ package appeng.api.networking.storage; - import appeng.api.networking.IGridCache; import appeng.api.networking.IGridHost; import appeng.api.networking.security.BaseActionSource; @@ -33,37 +32,35 @@ import appeng.api.storage.IStorageMonitorable; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; - /** * Common base class for item / fluid storage caches. */ -public interface IStorageGrid extends IGridCache, IStorageMonitorable -{ +public interface IStorageGrid extends IGridCache, IStorageMonitorable { + /** + * Used to inform the network of alterations to the storage system that fall outside + * of the standard Network operations, Examples, ME Chest inputs from the world, or a + * Storage Bus detecting modifications made to the chest by an outside force.

+ * Expects the input to have either a negative or a positive stack size to correspond + * to the injection, or extraction operation. + * + * @param input injected items + */ + void postAlterationOfStoredItems( + StorageChannel chan, Iterable input, BaseActionSource src + ); - /** - * Used to inform the network of alterations to the storage system that fall outside of the standard Network - * operations, Examples, ME Chest inputs from the world, or a Storage Bus detecting modifications made to the chest - * by an outside force. - *

- * Expects the input to have either a negative or a positive stack size to correspond to the injection, or - * extraction operation. - * - * @param input injected items - */ - void postAlterationOfStoredItems( StorageChannel chan, Iterable input, BaseActionSource src ); + /** + * Used to add a cell provider to the storage system + *

+ * THIS IT NOT FOR USE {@link IGridHost} THAT PROVIDE {@link ICellContainer} - those + * are automatically handled by the storage system. + * + * @param cc to be added cell provider + */ + void registerCellProvider(ICellProvider cc); - /** - * Used to add a cell provider to the storage system - *

- * THIS IT NOT FOR USE {@link IGridHost} THAT PROVIDE {@link ICellContainer} - those are automatically handled by - * the storage system. - * - * @param cc to be added cell provider - */ - void registerCellProvider( ICellProvider cc ); - - /** - * remove a provider added with addCellContainer - */ - void unregisterCellProvider( ICellProvider cc ); + /** + * remove a provider added with addCellContainer + */ + 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 10035323..15c6734a 100644 --- a/src/api/java/appeng/api/networking/ticking/IGridTickable.java +++ b/src/api/java/appeng/api/networking/ticking/IGridTickable.java @@ -23,54 +23,51 @@ package appeng.api.networking.ticking; - import appeng.api.networking.IGridNode; - /** * Implement on IGridHosts which want to use AE's Network Ticking Feature. */ -public interface IGridTickable -{ +public interface IGridTickable { + /** + * Important note regarding IGridTickables with more then one one node, + * + * If your IGridHost hosts multiple nodes, it may be on multiple grids, or + * its node may be present on the same grid multiple times, this is as + * designed, however if you choose to use the grid to tick these Hosts you + * must be aware that they they should probably pick a single node to tick + * for, and not tick for each node. + * + */ - /** - * Important note regarding IGridTickables with more then one one node, - * - * If your IGridHost hosts multiple nodes, it may be on multiple grids, or - * its node may be present on the same grid multiple times, this is as - * designed, however if you choose to use the grid to tick these Hosts you - * must be aware that they they should probably pick a single node to tick - * for, and not tick for each node. - * - */ + /** + * You can return null, if you wish to tick using MC's ticking mechanism, or + * you can return a valid TickingRequest to tell AE a guide for which type + * of responsiveness your device wants. + *

+ * this will be called for your tile any time your tile changes grids, this + * can happen at any time, so if your using the sleep feature you may wish + * to preserve your sleep, in the result of this method. or you can simply + * reset it. + * + * @return null or a valid new TickingRequest + */ + TickingRequest getTickingRequest(IGridNode node); - /** - * You can return null, if you wish to tick using MC's ticking mechanism, or - * you can return a valid TickingRequest to tell AE a guide for which type - * of responsiveness your device wants. - *

- * this will be called for your tile any time your tile changes grids, this - * can happen at any time, so if your using the sleep feature you may wish - * to preserve your sleep, in the result of this method. or you can simply - * reset it. - * - * @return null or a valid new TickingRequest - */ - TickingRequest getTickingRequest( IGridNode node ); - - /** - * AE lets you adjust your tick rate based on the results of your tick, if - * your block as accomplished work you may wish to increase the ticking - * speed, if your block is idle you may wish to slow it down. - *

- * Its up to you. - *

- * 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. - * @return tick rate adjustment. - */ - TickRateModulation tickingRequest( IGridNode node, int TicksSinceLastCall ); + /** + * AE lets you adjust your tick rate based on the results of your tick, if + * your block as accomplished work you may wish to increase the ticking + * speed, if your block is idle you may wish to slow it down. + *

+ * Its up to you. + *

+ * 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. + * @return tick rate adjustment. + */ + 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 4a70a7fa..a3165047 100644 --- a/src/api/java/appeng/api/networking/ticking/ITickManager.java +++ b/src/api/java/appeng/api/networking/ticking/ITickManager.java @@ -23,40 +23,35 @@ package appeng.api.networking.ticking; - import appeng.api.networking.IGridCache; import appeng.api.networking.IGridNode; - /** * The network tick manager. */ -public interface ITickManager extends IGridCache -{ +public interface ITickManager extends IGridCache { + /** + * immediately sets the node to tick, only valid if your node is marked as "Alertable" + * in its TickingRequest

Sleeping Devices Still Alertable, when your tile is + * alerted its new status is determined by the result of its tick. + * + * @param node gridnode + */ + boolean alertDevice(IGridNode node); - /** - * immediately sets the node to tick, only valid if your node is marked as "Alertable" in its TickingRequest - *

- * Sleeping Devices Still Alertable, when your tile is alerted its new status is determined by the result of its - * tick. - * - * @param node gridnode - */ - boolean alertDevice( IGridNode node ); + /** + * disables ticking for your device. + * + * @param node gridnode + * @return if the call was successful. + */ + boolean sleepDevice(IGridNode node); - /** - * disables ticking for your device. - * - * @param node gridnode - * @return if the call was successful. - */ - 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 ); + /** + * enables ticking for your device, undoes a sleepDevice call. + * + * @param node gridnode + * @return if the call was successful. + */ + boolean wakeDevice(IGridNode node); } diff --git a/src/api/java/appeng/api/networking/ticking/TickRateModulation.java b/src/api/java/appeng/api/networking/ticking/TickRateModulation.java index 35e83b92..a83f2fbd 100644 --- a/src/api/java/appeng/api/networking/ticking/TickRateModulation.java +++ b/src/api/java/appeng/api/networking/ticking/TickRateModulation.java @@ -23,36 +23,34 @@ package appeng.api.networking.ticking; +public enum TickRateModulation { + /** + * same as idle, but also puts the node to sleep. + */ + SLEEP, -public enum TickRateModulation -{ - /** - * same as idle, but also puts the node to sleep. - */ - SLEEP, + /** + * set tick rate to maximum. + */ + IDLE, - /** - * set tick rate to maximum. - */ - IDLE, + /** + * decrease the tick rate marginally. + */ + SLOWER, - /** - * decrease the tick rate marginally. - */ - SLOWER, + /** + * continue at current rate. + */ + SAME, - /** - * continue at current rate. - */ - SAME, + /** + * increase the tick rate marginally. + */ + FASTER, - /** - * increase the tick rate marginally. - */ - FASTER, - - /** - * changes the tick rate to the minimum tick rate. - */ - URGENT + /** + * changes the tick rate to the minimum tick rate. + */ + URGENT } diff --git a/src/api/java/appeng/api/networking/ticking/TickingRequest.java b/src/api/java/appeng/api/networking/ticking/TickingRequest.java index 6d46e235..32da2595 100644 --- a/src/api/java/appeng/api/networking/ticking/TickingRequest.java +++ b/src/api/java/appeng/api/networking/ticking/TickingRequest.java @@ -23,48 +23,46 @@ package appeng.api.networking.ticking; - /** * Describes how your tiles ticking is executed. */ -public class TickingRequest -{ +public class TickingRequest { + /** + * the minimum number of ticks that must pass between ticks. + *

+ * Valid Values are : 1+ + *

+ * Suggested is 5-20 + */ + public final int minTickRate; - /** - * the minimum number of ticks that must pass between ticks. - *

- * Valid Values are : 1+ - *

- * Suggested is 5-20 - */ - public final int minTickRate; + /** + * the maximum number of ticks that can pass between ticks, if this value is + * exceeded the tile must tick. + *

+ * Valid Values are 1+ + *

+ * Suggested is 20-40 + */ + public final int maxTickRate; - /** - * the maximum number of ticks that can pass between ticks, if this value is - * exceeded the tile must tick. - *

- * 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; - /** - * 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; - /** - * True only if you call {@link ITickManager}.alertDevice( IGridNode ); - */ - public final boolean canBeAlerted; - - public TickingRequest( final int min, final int max, final boolean sleep, final boolean alertable ) - { - this.minTickRate = min; - this.maxTickRate = max; - this.isSleeping = sleep; - this.canBeAlerted = alertable; - } + public TickingRequest( + final int min, final int max, final boolean sleep, final boolean alertable + ) { + this.minTickRate = min; + this.maxTickRate = max; + this.isSleeping = sleep; + this.canBeAlerted = alertable; + } } diff --git a/src/api/java/appeng/api/package-info.java b/src/api/java/appeng/api/package-info.java index 336bffbb..2a00b4b9 100644 --- a/src/api/java/appeng/api/package-info.java +++ b/src/api/java/appeng/api/package-info.java @@ -21,9 +21,11 @@ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -@API( apiVersion = "@aeversion@", owner = "appliedenergistics2", provides = "appliedenergistics2|API" ) +@API( + apiVersion = "@aeversion@", + owner = "appliedenergistics2", + provides = "appliedenergistics2|API" +) package appeng.api; - import cpw.mods.fml.common.API; - diff --git a/src/api/java/appeng/api/parts/BusSupport.java b/src/api/java/appeng/api/parts/BusSupport.java index 03c54de4..3255ed9d 100644 --- a/src/api/java/appeng/api/parts/BusSupport.java +++ b/src/api/java/appeng/api/parts/BusSupport.java @@ -23,12 +23,10 @@ package appeng.api.parts; +public enum BusSupport { + CABLE, -public enum BusSupport -{ - CABLE, + DENSE_CABLE, - DENSE_CABLE, - - NO_PARTS + NO_PARTS } diff --git a/src/api/java/appeng/api/parts/CableRenderMode.java b/src/api/java/appeng/api/parts/CableRenderMode.java index d9e80bfc..db524c1a 100644 --- a/src/api/java/appeng/api/parts/CableRenderMode.java +++ b/src/api/java/appeng/api/parts/CableRenderMode.java @@ -23,19 +23,16 @@ package appeng.api.parts; +public enum CableRenderMode { + Standard(false), -public enum CableRenderMode -{ - Standard( false ), + CableView(true); - CableView( true ); + public final boolean transparentFacades; + public final boolean opaqueFacades; - public final boolean transparentFacades; - public final boolean opaqueFacades; - - CableRenderMode( final boolean hideFacades ) - { - this.transparentFacades = hideFacades; - this.opaqueFacades = !hideFacades; - } + CableRenderMode(final boolean hideFacades) { + this.transparentFacades = hideFacades; + this.opaqueFacades = !hideFacades; + } } diff --git a/src/api/java/appeng/api/parts/IAlphaPassItem.java b/src/api/java/appeng/api/parts/IAlphaPassItem.java index db20111d..4c2c3b0f 100644 --- a/src/api/java/appeng/api/parts/IAlphaPassItem.java +++ b/src/api/java/appeng/api/parts/IAlphaPassItem.java @@ -23,18 +23,15 @@ package appeng.api.parts; - import net.minecraft.item.ItemStack; - -public interface IAlphaPassItem -{ - - /** - * Extend, and return true to enable a second pass for your parts in the bus rendering pipe line. - * - * @param is item - * @return true to enable a second pass for your parts in the bus rendering pipe line. - */ - boolean useAlphaPass( ItemStack is ); +public interface IAlphaPassItem { + /** + * Extend, and return true to enable a second pass for your parts in the bus rendering + * pipe line. + * + * @param is item + * @return true to enable a second pass for your parts in the bus rendering pipe line. + */ + boolean useAlphaPass(ItemStack is); } diff --git a/src/api/java/appeng/api/parts/IBoxProvider.java b/src/api/java/appeng/api/parts/IBoxProvider.java index a03230ef..922312ba 100644 --- a/src/api/java/appeng/api/parts/IBoxProvider.java +++ b/src/api/java/appeng/api/parts/IBoxProvider.java @@ -23,14 +23,11 @@ package appeng.api.parts; - -public interface IBoxProvider -{ - - /** - * add your collision information to the the list. - * - * @param boxes collision boxes - */ - void getBoxes( IPartCollisionHelper boxes ); +public interface IBoxProvider { + /** + * add your collision information to the the list. + * + * @param boxes collision boxes + */ + void getBoxes(IPartCollisionHelper boxes); } diff --git a/src/api/java/appeng/api/parts/IFacadeContainer.java b/src/api/java/appeng/api/parts/IFacadeContainer.java index c34d6d13..8bafcdf0 100644 --- a/src/api/java/appeng/api/parts/IFacadeContainer.java +++ b/src/api/java/appeng/api/parts/IFacadeContainer.java @@ -23,77 +23,73 @@ package appeng.api.parts; +import java.io.IOException; import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - /** * Used Internally. *

* not intended for implementation. */ -public interface IFacadeContainer -{ +public interface IFacadeContainer { + /** + * Attempts to add the {@link IFacadePart} to the given side. + * + * @return true if the facade as successfully added. + */ + boolean addFacade(IFacadePart a); - /** - * Attempts to add the {@link IFacadePart} to the given side. - * - * @return true if the facade as successfully added. - */ - boolean addFacade( IFacadePart a ); + /** + * Removed the facade on the given side, or does nothing. + */ + void removeFacade(IPartHost host, ForgeDirection side); - /** - * Removed the facade on the given side, or does nothing. - */ - void removeFacade( IPartHost host, ForgeDirection side ); + /** + * @return the {@link IFacadePart} for a given side, or null. + */ + IFacadePart getFacade(ForgeDirection s); - /** - * @return the {@link IFacadePart} for a given side, or null. - */ - IFacadePart getFacade( ForgeDirection s ); + /** + * rotate the facades left. + */ + void rotateLeft(); - /** - * rotate the facades left. - */ - void rotateLeft(); + /** + * write nbt data + * + * @param data to be written data + */ + void writeToNBT(NBTTagCompound data); - /** - * write nbt data - * - * @param data to be written 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; - /** - * read from stream - * - * @param data to be read data - * @return true if it was readable - * @throws IOException - */ - boolean readFromStream( ByteBuf data ) throws IOException; + /** + * read from NBT + * + * @param data to be read data + */ + void readFromNBT(NBTTagCompound data); - /** - * read from NBT - * - * @param data to be read data - */ - void readFromNBT( NBTTagCompound data ); + /** + * write to stream + * + * @param data to be written data + * @throws IOException + */ + void writeToStream(ByteBuf data) throws IOException; - /** - * write to stream - * - * @param data to be written data - * @throws IOException - */ - void writeToStream( ByteBuf data ) throws IOException; - - /** - * @return true if there are no facades. - */ - boolean isEmpty(); + /** + * @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 37893802..4b4ef73c 100644 --- a/src/api/java/appeng/api/parts/IFacadePart.java +++ b/src/api/java/appeng/api/parts/IFacadePart.java @@ -23,7 +23,6 @@ package appeng.api.parts; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.RenderBlocks; @@ -33,69 +32,75 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.util.ForgeDirection; - /** * Used Internally. *

* not intended for implementation. */ -public interface IFacadePart -{ +public interface IFacadePart { + /** + * used to save the part. + */ + ItemStack getItemStack(); - /** - * used to save the part. - */ - ItemStack getItemStack(); + /** + * used to collide, and pick the part + * + * @param ch collision helper + * @param e colliding entity + */ + void getBoxes(IPartCollisionHelper ch, Entity e); - /** - * used to collide, and pick the part - * - * @param ch collision helper - * @param e colliding entity - */ - 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 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 + ); - /** - * 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 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 ); + /** + * render the part in inventory. + * + * @param instance render helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderInventory(IPartRenderHelper instance, RenderBlocks renderer); - /** - * render the part in inventory. - * - * @param instance render helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventory( IPartRenderHelper instance, RenderBlocks renderer ); + /** + * @return side the facade is in + */ + ForgeDirection getSide(); - /** - * @return side the facade is in - */ - ForgeDirection getSide(); + /** + * @return the box for the face of the facade + */ + AxisAlignedBB getPrimaryBox(); - /** - * @return the box for the face of the facade - */ - AxisAlignedBB getPrimaryBox(); + Item getItem(); - Item getItem(); + int getItemDamage(); - int getItemDamage(); + boolean notAEFacade(); - boolean notAEFacade(); + void setThinFacades(boolean useThinFacades); - void setThinFacades( boolean useThinFacades ); - - boolean isTransparent(); + boolean isTransparent(); } \ No newline at end of file diff --git a/src/api/java/appeng/api/parts/IPart.java b/src/api/java/appeng/api/parts/IPart.java index 02e59753..67d503d1 100644 --- a/src/api/java/appeng/api/parts/IPart.java +++ b/src/api/java/appeng/api/parts/IPart.java @@ -23,6 +23,9 @@ package appeng.api.parts; +import java.io.IOException; +import java.util.List; +import java.util.Random; import appeng.api.networking.IGridNode; import cpw.mods.fml.relauncher.Side; @@ -40,250 +43,251 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; -import java.util.Random; +public interface IPart extends IBoxProvider { + /** + * get an ItemStack that represents the bus, should contain the settings for whatever, + * can also be used in conjunction with removePart to take a part off and drop it or + * something.

This is used to drop the bus, and to save the bus, when saving the + * bus, wrenched is false, and writeToNBT will be called to save important details + * about the part, if the part is wrenched include in your NBT Data any settings you + * might want to keep around, you can restore those settings when constructing your + * part. + * + * @param type , what kind of ItemStack to return? + * @return item of part + */ + ItemStack getItemStack(PartItemStack type); + /** + * render item form for inventory, or entity. + *

+ * GL Available + * + * @param rh helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderInventory(IPartRenderHelper rh, RenderBlocks renderer); -public interface IPart extends IBoxProvider -{ + /** + * render world renderer ( preferred ) + *

+ * GL is NOT Available + * + * @param x x coord + * @param y y coord + * @param z z coord + * @param rh helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer); - /** - * get an ItemStack that represents the bus, should contain the settings for whatever, can also be used in - * conjunction with removePart to take a part off and drop it or something. - *

- * This is used to drop the bus, and to save the bus, when saving the bus, wrenched is false, and writeToNBT will be - * called to save important details about the part, if the part is wrenched include in your NBT Data any settings - * you might want to keep around, you can restore those settings when constructing your part. - * - * @param type , what kind of ItemStack to return? - * @return item of part - */ - ItemStack getItemStack( PartItemStack type ); + /** + * render TESR. + *

+ * GL Available + * + * @param x x coord + * @param y y coord + * @param z z coord + * @param rh helper + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderDynamic( + double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer + ); - /** - * render item form for inventory, or entity. - *

- * GL Available - * - * @param rh helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventory( IPartRenderHelper rh, RenderBlocks renderer ); + /** + * @return the Block sheet icon used when rendering the breaking particles, return + * null to use the ItemStack + * texture. + */ + @SideOnly(Side.CLIENT) + IIcon getBreakingTexture(); - /** - * render world renderer ( preferred ) - *

- * GL is NOT Available - * - * @param x x coord - * @param y y coord - * @param z z coord - * @param rh helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderStatic( int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer ); + /** + * return true only if your part require dynamic rendering, must be consistent. + * + * @return true to enable renderDynamic + */ + boolean requireDynamicRender(); - /** - * render TESR. - *

- * GL Available - * - * @param x x coord - * @param y y coord - * @param z z coord - * @param rh helper - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderDynamic( double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer ); + /** + * @return if the bus has a solid side, and you can place random stuff on it like + * torches or levers + */ + boolean isSolid(); - /** - * @return the Block sheet icon used when rendering the breaking particles, return null to use the ItemStack - * texture. - */ - @SideOnly( Side.CLIENT ) - IIcon getBreakingTexture(); + /** + * @return true if this part can connect to redstone ( also MFR Rednet ) + */ + boolean canConnectRedstone(); - /** - * return true only if your part require dynamic rendering, must be consistent. - * - * @return true to enable renderDynamic - */ - boolean requireDynamicRender(); + /** + * Write the part information for saving, the part will be saved with + * getItemStack(false) and this method will be called after to load settings, + * inventory or other values from the world. + * + * @param data to be written nbt data + */ + void writeToNBT(NBTTagCompound data); - /** - * @return if the bus has a solid side, and you can place random stuff on it like torches or levers - */ - boolean isSolid(); + /** + * Read the previously written NBT Data. this is the mirror for writeToNBT + * + * @param data to be read nbt data + */ + void readFromNBT(NBTTagCompound data); - /** - * @return true if this part can connect to redstone ( also MFR Rednet ) - */ - boolean canConnectRedstone(); + /** + * @return get the amount of light produced by the bus + */ + int getLightLevel(); - /** - * Write the part information for saving, the part will be saved with getItemStack(false) and this method will be - * called after to load settings, inventory or other values from the world. - * - * @param data to be written nbt data - */ - void writeToNBT( NBTTagCompound data ); + /** + * does this part act like a ladder? + * + * @param entity climbing entity + * @return true if entity can climb + */ + boolean isLadder(EntityLivingBase entity); - /** - * Read the previously written NBT Data. this is the mirror for writeToNBT - * - * @param data to be read nbt data - */ - void readFromNBT( NBTTagCompound data ); + /** + * a block around the bus's host has been changed. + */ + void onNeighborChanged(); - /** - * @return get the amount of light produced by the bus - */ - int getLightLevel(); + /** + * @return output redstone on facing side + */ + int isProvidingStrongPower(); - /** - * does this part act like a ladder? - * - * @param entity climbing entity - * @return true if entity can climb - */ - boolean isLadder( EntityLivingBase entity ); + /** + * @return output redstone on facing side + */ + int isProvidingWeakPower(); - /** - * a block around the bus's host has been changed. - */ - void onNeighborChanged(); + /** + * write data to bus packet. + * + * @param data to be written data + * @throws IOException + */ + void writeToStream(ByteBuf data) throws IOException; - /** - * @return output redstone on facing side - */ - int isProvidingStrongPower(); + /** + * read data from bus packet. + * + * @param data to be read data + * @return true will re-draw the part. + * @throws IOException + */ + boolean readFromStream(ByteBuf data) throws IOException; - /** - * @return output redstone on facing side - */ - int isProvidingWeakPower(); + /** + * get the Grid Node for the Bus, be sure your IGridBlock is NOT isWorldAccessible, if + * it is your going to cause crashes.

or null if you don't have a grid node. + * + * @return grid node + */ + IGridNode getGridNode(); - /** - * write data to bus packet. - * - * @param data to be written data - * @throws IOException - */ - void writeToStream( ByteBuf data ) throws IOException; + /** + * called when an entity collides with the bus. + * + * @param entity colliding entity + */ + void onEntityCollision(Entity entity); - /** - * read data from bus packet. - * - * @param data to be read data - * @return true will re-draw the part. - * @throws IOException - */ - boolean readFromStream( ByteBuf data ) throws IOException; + /** + * called when your part is being removed from the world. + */ + void removeFromWorld(); - /** - * get the Grid Node for the Bus, be sure your IGridBlock is NOT isWorldAccessible, if it is your going to cause - * crashes. - *

- * or null if you don't have a grid node. - * - * @return grid node - */ - IGridNode getGridNode(); + /** + * called when your part is being added to the world. + */ + void addToWorld(); - /** - * called when an entity collides with the bus. - * - * @param entity colliding entity - */ - void onEntityCollision( Entity entity ); + /** + * used for tunnels. + * + * @return a grid node that represents the external facing side, these must be + * isWorldAccessible with the correct + * faces marked as external + */ + IGridNode getExternalFacingNode(); - /** - * called when your part is being removed from the world. - */ - void removeFromWorld(); + /** + * called by the Part host to keep your part informed. + * + * @param host part side + * @param tile tile entity of part + */ + void setPartHostInfo(ForgeDirection side, IPartHost host, TileEntity tile); - /** - * called when your part is being added to the world. - */ - void addToWorld(); + /** + * Called when you right click the part, very similar to Block.onActivateBlock + * + * @param player right clicking player + * @param pos position of block + * @return if your activate method performed something. + */ + boolean onActivate(EntityPlayer player, Vec3 pos); - /** - * used for tunnels. - * - * @return a grid node that represents the external facing side, these must be isWorldAccessible with the correct - * faces marked as external - */ - IGridNode getExternalFacingNode(); + /** + * Called when you right click the part, very similar to Block.onActivateBlock + * + * @param player shift right clicking player + * @param pos position of block + * @return if your activate method performed something, you should use false unless + * you really need it. + */ + boolean onShiftActivate(EntityPlayer player, Vec3 pos); - /** - * called by the Part host to keep your part informed. - * - * @param host part side - * @param tile tile entity of part - */ - void setPartHostInfo( ForgeDirection side, IPartHost host, TileEntity tile ); + /** + * Add drops to the items being dropped into the world, if your item stores its + * contents when wrenched use the wrenched boolean to control what data is saved vs + * dropped when it is broken. + * + * @param drops item drops if wrenched + * @param wrenched control flag for wrenched vs broken + */ + void getDrops(List drops, boolean wrenched); - /** - * Called when you right click the part, very similar to Block.onActivateBlock - * - * @param player right clicking player - * @param pos position of block - * @return if your activate method performed something. - */ - boolean onActivate( EntityPlayer player, Vec3 pos ); + /** + * @return 0 - 8, reasonable default 3-4, this controls the cable connection to the + * node. + */ + int cableConnectionRenderTo(); - /** - * Called when you right click the part, very similar to Block.onActivateBlock - * - * @param player shift right clicking player - * @param pos position of block - * @return if your activate method performed something, you should use false unless you really need it. - */ - boolean onShiftActivate( EntityPlayer player, Vec3 pos ); + /** + * same as Block.randomDisplayTick, for but parts. + * + * @param world world of block + * @param x x coord of block + * @param y y coord of block + * @param z z coord of block + * @param r random + */ + void randomDisplayTick(World world, int x, int y, int z, Random r); - /** - * Add drops to the items being dropped into the world, if your item stores its contents when wrenched use the - * wrenched boolean to control what data is saved vs dropped when it is broken. - * - * @param drops item drops if wrenched - * @param wrenched control flag for wrenched vs broken - */ - void getDrops( List drops, boolean wrenched ); + /** + * Called when placed in the world by a player, this happens before addWorld. + * + * @param player placing player + * @param held held item + * @param side placing side + */ + void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side); - /** - * @return 0 - 8, reasonable default 3-4, this controls the cable connection to the node. - */ - int cableConnectionRenderTo(); - - /** - * same as Block.randomDisplayTick, for but parts. - * - * @param world world of block - * @param x x coord of block - * @param y y coord of block - * @param z z coord of block - * @param r random - */ - void randomDisplayTick( World world, int x, int y, int z, Random r ); - - /** - * Called when placed in the world by a player, this happens before addWorld. - * - * @param player placing player - * @param held held item - * @param side placing side - */ - void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ); - - /** - * Used to determine which parts can be placed on what cables. - * - * @param what placed part - * @return true if the part can be placed on this support. - */ - boolean canBePlacedOn( BusSupport what ); + /** + * Used to determine which parts can be placed on what cables. + * + * @param what placed part + * @return true if the part can be placed on this support. + */ + boolean canBePlacedOn(BusSupport what); } \ 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 84c35bf2..86407958 100644 --- a/src/api/java/appeng/api/parts/IPartCollisionHelper.java +++ b/src/api/java/appeng/api/parts/IPartCollisionHelper.java @@ -23,44 +23,41 @@ package appeng.api.parts; - import net.minecraftforge.common.util.ForgeDirection; +public interface IPartCollisionHelper { + /** + * add a collision box, expects 0.0 - 16.0 block coords. + *

+ * No complaints about the size, I like using pixels :P + * + * @param minX minimal x collision + * @param minY minimal y collision + * @param minZ minimal z collision + * @param maxX maximal x collision + * @param maxY maximal y collision + * @param maxZ maximal z collision + */ + void + addBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ); -public interface IPartCollisionHelper -{ + /** + * @return east in world space. + */ + ForgeDirection getWorldX(); - /** - * add a collision box, expects 0.0 - 16.0 block coords. - *

- * No complaints about the size, I like using pixels :P - * - * @param minX minimal x collision - * @param minY minimal y collision - * @param minZ minimal z collision - * @param maxX maximal x collision - * @param maxY maximal y collision - * @param maxZ maximal z collision - */ - void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ); + /** + * @return up in world space. + */ + ForgeDirection getWorldY(); - /** - * @return east in world space. - */ - ForgeDirection getWorldX(); + /** + * @return forward in world space. + */ + ForgeDirection getWorldZ(); - /** - * @return up in world space. - */ - ForgeDirection getWorldY(); - - /** - * @return forward in world space. - */ - ForgeDirection getWorldZ(); - - /** - * @return true if this test is to get the BB Collision information. - */ - boolean isBBCollision(); + /** + * @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 d42d812e..1d665847 100644 --- a/src/api/java/appeng/api/parts/IPartHelper.java +++ b/src/api/java/appeng/api/parts/IPartHelper.java @@ -23,64 +23,62 @@ package appeng.api.parts; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; +public interface IPartHelper { + /** + * Register a new layer with the part layer system, this allows you to write + * an in between between tile entities and parts. + *

+ * AE By Default includes, + *

+ * 1. ISidedInventory ( and by extension IInventory. ) + *

+ * 2. IFluidHandler Forge Fluids + *

+ * 3. IPowerEmitter BC Power output. + *

+ * 4. IPowerReceptor BC Power input. + *

+ * 5. IEnergySink IC2 Power input. + *

+ * 6. IEnergySource IC2 Power output. + *

+ * 7. IPipeConnection BC Pipe Connections + *

+ * As long as a valid layer is registered for a interface you can simply + * implement that interface on a part get implement it. + * + * @return true on success, false on failure, usually a error will be logged + * as well. + */ + boolean registerNewLayer(String string, String layerInterface); -public interface IPartHelper -{ + /** + * Register IBusItem with renderer + */ + void setItemBusRenderer(IPartItem i); - /** - * Register a new layer with the part layer system, this allows you to write - * an in between between tile entities and parts. - *

- * AE By Default includes, - *

- * 1. ISidedInventory ( and by extension IInventory. ) - *

- * 2. IFluidHandler Forge Fluids - *

- * 3. IPowerEmitter BC Power output. - *

- * 4. IPowerReceptor BC Power input. - *

- * 5. IEnergySink IC2 Power input. - *

- * 6. IEnergySource IC2 Power output. - *

- * 7. IPipeConnection BC Pipe Connections - *

- * As long as a valid layer is registered for a interface you can simply - * implement that interface on a part get implement it. - * - * @return true on success, false on failure, usually a error will be logged - * as well. - */ - boolean registerNewLayer( String string, String layerInterface ); + /** + * 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 player player placing part + * @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 + ); - /** - * Register IBusItem with renderer - */ - 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 player player placing part - * @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 ); - - /** - * @return the render mode - */ - CableRenderMode getCableRenderMode(); + /** + * @return the render mode + */ + CableRenderMode getCableRenderMode(); } diff --git a/src/api/java/appeng/api/parts/IPartHost.java b/src/api/java/appeng/api/parts/IPartHost.java index c59afe1c..594ef536 100644 --- a/src/api/java/appeng/api/parts/IPartHost.java +++ b/src/api/java/appeng/api/parts/IPartHost.java @@ -23,6 +23,7 @@ package appeng.api.parts; +import java.util.Set; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; @@ -32,145 +33,144 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Set; - - /** * Implemented on AE's TileEntity or AE's FMP Part. *

* Do Not Implement */ -public interface IPartHost -{ +public interface IPartHost { + /** + * @return the facade container + */ + IFacadeContainer getFacadeContainer(); - /** - * @return the facade container - */ - IFacadeContainer getFacadeContainer(); + /** + * Test if you can add a part to the specified side of the Part Host, {@link + * ForgeDirection}.UNKNOWN is used to represent the cable in the middle. + * + * @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); - /** - * Test if you can add a part to the specified side of the Part Host, {@link ForgeDirection}.UNKNOWN is used to - * represent the cable in the middle. - * - * @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 ); + /** + * 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 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 ) + */ + ForgeDirection addPart(ItemStack is, ForgeDirection side, EntityPlayer owner); - /** - * 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 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 ) - */ - 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); - /** - * 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 ); + /** + * removes the part on the side, this doesn't drop it or anything, if you don't do + * something with it, its just "gone" and its never coming back; think about it.

+ * 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. + */ + void removePart(ForgeDirection side, boolean suppressUpdate); - /** - * removes the part on the side, this doesn't drop it or anything, if you don't do something with it, its just - * "gone" and its never coming back; think about it. - *

- * 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. - */ - void removePart( ForgeDirection side, boolean suppressUpdate ); + /** + * something changed, might want to send a packet to clients to update state. + */ + void markForUpdate(); - /** - * something changed, might want to send a packet to clients to update state. - */ - void markForUpdate(); + /** + * @return the physical location of the part host in the universe. + */ + DimensionalCoord getLocation(); - /** - * @return the physical location of the part host in the universe. - */ - DimensionalCoord getLocation(); + /** + * @return the tile entity for the host, this can either be an FMP tile, or a AE tile + */ + TileEntity getTile(); - /** - * @return the tile entity for the host, this can either be an FMP tile, or a AE tile - */ - TileEntity getTile(); + /** + * @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. + */ + AEColor getColor(); - /** - * @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. - */ - AEColor getColor(); + /** + * destroys the part container, for internal use. + */ + void clearContainer(); - /** - * destroys the part container, for internal use. - */ - void clearContainer(); + /** + * Used to test for FMP microblock blocking internally. + * + * @return returns if microblocks are blocking this cable path. + */ + boolean isBlocked(ForgeDirection side); - /** - * Used to test for FMP microblock blocking internally. - * - * @return returns if microblocks are blocking this cable path. - */ - 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); - /** - * 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 ); + /** + * can be used by parts to trigger the tile or part to save. + */ + void markForSave(); - /** - * can be used by parts to trigger the tile or part to save. - */ - void markForSave(); + /** + * part of the {@link LayerBase} + */ + void partChanged(); - /** - * part of the {@link LayerBase} - */ - void partChanged(); + /** + * 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); - /** - * 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 ); + /** + * returns false if this block contains any parts or facades, true other wise. + */ + boolean isEmpty(); - /** - * returns false if this block contains any parts or facades, true other wise. - */ - boolean isEmpty(); + /** + * @return a mutable list of flags you can adjust to track state. + */ + Set getLayerFlags(); - /** - * @return a mutable list of flags you can adjust to track state. - */ - Set getLayerFlags(); + /** + * remove host from world... + */ + void cleanup(); - /** - * remove host from world... - */ - void cleanup(); + /** + * notify neighbors uf updated status. + */ + void notifyNeighbors(); - /** - * notify neighbors uf updated status. - */ - void notifyNeighbors(); - - /** - * true if the tile is in the world, other wise false. - * - * @return true if tile is in world - */ - boolean isInWorld(); + /** + * true if the tile is in the world, other wise false. + * + * @return true if tile is in world + */ + boolean isInWorld(); } \ No newline at end of file diff --git a/src/api/java/appeng/api/parts/IPartItem.java b/src/api/java/appeng/api/parts/IPartItem.java index 9458452f..5fe90fd7 100644 --- a/src/api/java/appeng/api/parts/IPartItem.java +++ b/src/api/java/appeng/api/parts/IPartItem.java @@ -23,21 +23,17 @@ package appeng.api.parts; +import javax.annotation.Nullable; import net.minecraft.item.ItemStack; -import javax.annotation.Nullable; - //@formatter:off - /** - * This is a pretty basic requirement, once you implement the interface, and createPartFromItemStack - *

- * you must register your bus with the Bus renderer, using AEApi.INSTANCE().partHelper().setItemBusRenderer( this ); - *

- * then simply add these two methods, which tell MC to use the Block Textures, and call AE's Bus Placement Code. - *

+ * This is a pretty basic requirement, once you implement the interface, and + * createPartFromItemStack

you must register your bus with the Bus renderer, using + * AEApi.INSTANCE().partHelper().setItemBusRenderer( this );

then simply add these two + * methods, which tell MC to use the Block Textures, and call AE's Bus Placement Code.

*

  * 
  * {@literal @}Override
@@ -48,22 +44,21 @@ import javax.annotation.Nullable;
  * }
  *
  * {@literal @}Override
- * public boolean onItemUse(ItemStack is, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ)
+ * public boolean onItemUse(ItemStack is, EntityPlayer player, World world, 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, world );
  * }
  * 
  * 
*/ -public interface IPartItem -{ - - /** - * create a new part INSTANCE, from the item stack. - * - * @param is item - * @return part from item - */ - @Nullable - IPart createPartFromItemStack( ItemStack is ); +public interface IPartItem { + /** + * create a new part INSTANCE, from the item stack. + * + * @param is item + * @return part from item + */ + @Nullable + IPart createPartFromItemStack(ItemStack is); } diff --git a/src/api/java/appeng/api/parts/IPartRenderHelper.java b/src/api/java/appeng/api/parts/IPartRenderHelper.java index 339b5f49..58370977 100644 --- a/src/api/java/appeng/api/parts/IPartRenderHelper.java +++ b/src/api/java/appeng/api/parts/IPartRenderHelper.java @@ -23,6 +23,7 @@ package appeng.api.parts; +import java.util.EnumSet; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -31,173 +32,181 @@ import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public interface IPartRenderHelper { + /** + * sets the Render Helpers Block Bounds. 0.0 - 16.0 block coords. + *

+ * No complaints about the size, I like using pixels :P + * + * @param minX minimal x bound + * @param minY minimal y bound + * @param minZ minimal z bound + * @param maxX maximal x bound + * @param maxY maximal y bound + * @param maxZ maximal z bound + */ + 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 renderer renderer of part + */ + @SideOnly(Side.CLIENT) + void renderFace( + int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer + ); -public interface IPartRenderHelper -{ + /** + * 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 edgeThickness thickness of the edge + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderFaceCutout( + int x, + int y, + int z, + IIcon ico, + ForgeDirection face, + float edgeThickness, + RenderBlocks renderer + ); - /** - * sets the Render Helpers Block Bounds. 0.0 - 16.0 block coords. - *

- * No complaints about the size, I like using pixels :P - * - * @param minX minimal x bound - * @param minY minimal y bound - * @param minZ minimal z bound - * @param maxX maximal x bound - * @param maxY maximal y bound - * @param maxZ maximal z bound - */ - void setBounds( float minX, float minY, float minZ, float maxX, float maxY, float maxZ ); + /** + * 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 renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderBlock(int x, int y, int z, RenderBlocks renderer); - /** - * 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 renderer renderer of part - */ - @SideOnly( Side.CLIENT ) - void renderFace( int x, int y, int z, IIcon ico, ForgeDirection face, RenderBlocks renderer ); + /** + * render a single face in inventory renderer. + * + * @param IIcon icon of part + * @param direction face of part + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void + renderInventoryFace(IIcon IIcon, ForgeDirection direction, 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 edgeThickness thickness of the edge - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderFaceCutout( int x, int y, int z, IIcon ico, ForgeDirection face, float edgeThickness, RenderBlocks renderer ); + /** + * render a box in inventory renderer. + * + * @param renderer renderer + */ + @SideOnly(Side.CLIENT) + void renderInventoryBox(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 renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderBlock( int x, int y, int z, RenderBlocks renderer ); + /** + * inventory, and static renderer. + *

+ * set unique icons for each side of the block. + * + * @param down down face + * @param up up face + * @param north north face + * @param south south face + * @param west west face + * @param east east face + */ + void + setTexture(IIcon down, IIcon up, IIcon north, IIcon south, IIcon west, IIcon east); - /** - * render a single face in inventory renderer. - * - * @param IIcon icon of part - * @param direction face of part - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventoryFace( IIcon IIcon, ForgeDirection direction, RenderBlocks renderer ); + /** + * inventory, and static renderer. + *

+ * set all sides to a single IIcon. + * + * @param ico to be set icon + */ + void setTexture(IIcon ico); - /** - * render a box in inventory renderer. - * - * @param renderer renderer - */ - @SideOnly( Side.CLIENT ) - void renderInventoryBox( RenderBlocks renderer ); + /** + * configure the color multiplier for the inventory renderer. + * + * @param whiteVariant color multiplier + */ + void setInvColor(int whiteVariant); - /** - * inventory, and static renderer. - *

- * set unique icons for each side of the block. - * - * @param down down face - * @param up up face - * @param north north face - * @param south south face - * @param west west face - * @param east east face - */ - void setTexture( IIcon down, IIcon up, IIcon north, IIcon south, IIcon west, IIcon east ); + /** + * @return the block used for rendering, might need it for some reason... + */ + Block getBlock(); - /** - * inventory, and static renderer. - *

- * set all sides to a single IIcon. - * - * @param ico to be set icon - */ - void setTexture( IIcon ico ); + /** + * @return the east vector in world directions, rather then renderer + */ + ForgeDirection getWorldX(); - /** - * configure the color multiplier for the inventory renderer. - * - * @param whiteVariant color multiplier - */ - void setInvColor( int whiteVariant ); + /** + * @return the up vector in world directions, rather then renderer. + */ + ForgeDirection getWorldY(); - /** - * @return the block used for rendering, might need it for some reason... - */ - Block getBlock(); + /** + * @return the forward vector in world directions, rather then renderer. + */ + ForgeDirection getWorldZ(); - /** - * @return the east vector in world directions, rather then renderer - */ - ForgeDirection getWorldX(); + /** + * Pre-Calculates default lighting for the part, call this before using the render + * helper to render anything else to get simplified, but faster lighting for more then + * one block.

Only worth it if you render more then 1 block. + */ + ISimplifiedBundle + useSimplifiedRendering(int x, int y, int z, IBoxProvider p, ISimplifiedBundle sim); - /** - * @return the up vector in world directions, rather then renderer. - */ - ForgeDirection getWorldY(); + /** + * disables, useSimplifiedRendering. + */ + void normalRendering(); - /** - * @return the forward vector in world directions, rather then renderer. - */ - ForgeDirection getWorldZ(); + /** + * 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 renderer renderer of part + */ + @SideOnly(Side.CLIENT) + void renderBlockCurrentBounds(int x, int y, int z, RenderBlocks renderer); - /** - * Pre-Calculates default lighting for the part, call this before using the render helper to render anything else to - * get simplified, but faster lighting for more then one block. - *

- * Only worth it if you render more then 1 block. - */ - ISimplifiedBundle useSimplifiedRendering( int x, int y, int z, IBoxProvider p, ISimplifiedBundle sim ); + /** + * allow you to enable your part to render during the alpha pass or the standard pass. + * + * @param pass render pass + */ + void renderForPass(int pass); - /** - * disables, useSimplifiedRendering. - */ - void normalRendering(); - - /** - * 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 renderer renderer of part - */ - @SideOnly( Side.CLIENT ) - 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 ); - - /** - * Set which faces to render, remember to set back to ALL when you are done. - * - * @param complementOf sides to render - */ - void setFacesToRender( EnumSet complementOf ); + /** + * Set which faces to render, remember to set back to ALL when you are done. + * + * @param complementOf sides to render + */ + void setFacesToRender(EnumSet complementOf); } \ No newline at end of file diff --git a/src/api/java/appeng/api/parts/ISimplifiedBundle.java b/src/api/java/appeng/api/parts/ISimplifiedBundle.java index ad16791f..baad8781 100644 --- a/src/api/java/appeng/api/parts/ISimplifiedBundle.java +++ b/src/api/java/appeng/api/parts/ISimplifiedBundle.java @@ -23,8 +23,4 @@ package appeng.api.parts; - -public interface ISimplifiedBundle -{ - -} +public interface ISimplifiedBundle {} diff --git a/src/api/java/appeng/api/parts/LayerBase.java b/src/api/java/appeng/api/parts/LayerBase.java index 9a7bed93..f4b567ad 100644 --- a/src/api/java/appeng/api/parts/LayerBase.java +++ b/src/api/java/appeng/api/parts/LayerBase.java @@ -23,57 +23,48 @@ package appeng.api.parts; +import java.util.Set; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Set; - - /** - * 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. + * 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. */ public abstract class LayerBase extends TileEntity // implements IPartHost { + /** + * Grants access for the layer to the parts of the host. + *

+ * 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(final ForgeDirection side) { + return null; // place holder. + } - /** - * Grants access for the layer to the parts of the host. - *

- * 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( final ForgeDirection side ) - { - return null; // place holder. - } + /** + * called when the parts change in the container, YOU MUST CALL super.PartChanged(); + */ + public void notifyNeighbors() {} - /** - * called when the parts change in the container, YOU MUST CALL super.PartChanged(); - */ - public void notifyNeighbors() - { - } + /** + * called when the parts change in the container, YOU MUST CALL super.PartChanged(); + */ + public void partChanged() {} - /** - * called when the parts change in the container, YOU MUST CALL super.PartChanged(); - */ - public void partChanged() - { - } + /** + * @return a mutable list of flags you can adjust to track state. + */ + public Set getLayerFlags() { + return null; // place holder. + } - /** - * @return a mutable list of flags you can adjust to track state. - */ - public Set getLayerFlags() - { - return null; // place holder. - } - - public void markForSave() - { - // something! - } + public void markForSave() { + // something! + } } diff --git a/src/api/java/appeng/api/parts/LayerFlags.java b/src/api/java/appeng/api/parts/LayerFlags.java index af04459b..f73bbaff 100644 --- a/src/api/java/appeng/api/parts/LayerFlags.java +++ b/src/api/java/appeng/api/parts/LayerFlags.java @@ -23,10 +23,8 @@ package appeng.api.parts; +public enum LayerFlags { -public enum LayerFlags -{ - - IC2_ENET + IC2_ENET } diff --git a/src/api/java/appeng/api/parts/PartItemStack.java b/src/api/java/appeng/api/parts/PartItemStack.java index 795dd491..07be0d13 100644 --- a/src/api/java/appeng/api/parts/PartItemStack.java +++ b/src/api/java/appeng/api/parts/PartItemStack.java @@ -23,16 +23,14 @@ package appeng.api.parts; +public enum PartItemStack { + Pick, -public enum PartItemStack -{ - Pick, + Break, - Break, + Wrench, - Wrench, + Network, - Network, - - World + World } diff --git a/src/api/java/appeng/api/parts/SelectedPart.java b/src/api/java/appeng/api/parts/SelectedPart.java index bc308db3..b3f91b3a 100644 --- a/src/api/java/appeng/api/parts/SelectedPart.java +++ b/src/api/java/appeng/api/parts/SelectedPart.java @@ -23,49 +23,42 @@ package appeng.api.parts; - import net.minecraftforge.common.util.ForgeDirection; - /** * Reports a selected part from th IPartHost */ -public class SelectedPart -{ +public class SelectedPart { + /** + * selected part. + */ + public final IPart part; - /** - * selected part. - */ - public final IPart part; + /** + * facade part. + */ + public final IFacadePart facade; - /** - * facade part. - */ - public final IFacadePart facade; + /** + * side the part is mounted too, or {@link ForgeDirection}.UNKNOWN for cables. + */ + public final ForgeDirection side; - /** - * side the part is mounted too, or {@link ForgeDirection}.UNKNOWN for cables. - */ - public final ForgeDirection side; + public SelectedPart() { + this.part = null; + this.facade = null; + this.side = ForgeDirection.UNKNOWN; + } - public SelectedPart() - { - this.part = null; - this.facade = null; - this.side = ForgeDirection.UNKNOWN; - } + public SelectedPart(final IPart part, final ForgeDirection side) { + this.part = part; + this.facade = null; + this.side = side; + } - public SelectedPart( final IPart part, final ForgeDirection side ) - { - this.part = part; - this.facade = null; - this.side = side; - } - - public SelectedPart( final IFacadePart facade, final ForgeDirection side ) - { - this.part = null; - this.facade = facade; - this.side = side; - } + public SelectedPart(final IFacadePart facade, final ForgeDirection side) { + this.part = null; + this.facade = facade; + this.side = side; + } } diff --git a/src/api/java/appeng/api/recipes/ICraftHandler.java b/src/api/java/appeng/api/recipes/ICraftHandler.java index 19ca1ff9..aec4d4c4 100644 --- a/src/api/java/appeng/api/recipes/ICraftHandler.java +++ b/src/api/java/appeng/api/recipes/ICraftHandler.java @@ -23,31 +23,28 @@ package appeng.api.recipes; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; import appeng.api.exceptions.RegistrationError; -import java.util.List; +public interface ICraftHandler { + /** + * Called when your recipe handler receives a newly parsed list of inputs/outputs. + * + * @param input parsed inputs + * @param output parsed outputs + * @throws RecipeError + */ + void setup(List> input, List> output) + throws RecipeError; - -public interface ICraftHandler -{ - - /** - * Called when your recipe handler receives a newly parsed list of inputs/outputs. - * - * @param input parsed inputs - * @param output parsed outputs - * @throws RecipeError - */ - void setup( List> input, List> output ) throws RecipeError; - - /** - * called when all recipes are parsed, and your required to register your recipe. - * - * @throws RegistrationError - * @throws MissingIngredientError - */ - void register() throws RegistrationError, MissingIngredientError; + /** + * called when all recipes are parsed, and your required to register your recipe. + * + * @throws RegistrationError + * @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 7117a221..d47d5789 100644 --- a/src/api/java/appeng/api/recipes/IIngredient.java +++ b/src/api/java/appeng/api/recipes/IIngredient.java @@ -23,67 +23,65 @@ package appeng.api.recipes; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import net.minecraft.item.ItemStack; +public interface IIngredient { + /** + * Acquire a single input stack for the current recipe, if more then one ItemStack is + * possible a RegistrationError exception will be thrown, ignore these and let the + * system handle the error. + * + * @return a single ItemStack for the recipe handler. + * @throws RegistrationError + * @throws MissingIngredientError + */ + ItemStack getItemStack() throws RegistrationError, MissingIngredientError; -public interface IIngredient -{ + /** + * Acquire a list of all the input stacks for the current recipe, this is for handlers + * that support multiple inputs per slot. + * + * @return an array of ItemStacks for the recipe handler. + * @throws RegistrationError + * @throws MissingIngredientError + */ + ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError; - /** - * Acquire a single input stack for the current recipe, if more then one ItemStack is possible a - * RegistrationError exception will be thrown, ignore these and let the system handle the error. - * - * @return a single ItemStack for the recipe handler. - * @throws RegistrationError - * @throws MissingIngredientError - */ - ItemStack getItemStack() throws RegistrationError, MissingIngredientError; + /** + * If you wish to support air, you must test before getting the ItemStack, or + * ItemStackSet + * + * @return true if this slot contains no ItemStack, this is passed as "_" + */ + boolean isAir(); - /** - * Acquire a list of all the input stacks for the current recipe, this is for handlers that support - * multiple inputs per slot. - * - * @return an array of ItemStacks for the recipe handler. - * @throws RegistrationError - * @throws MissingIngredientError - */ - ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError; + /** + * @return The Name Space of the item. Prefer getItemStack or getItemStackSet + */ + String getNameSpace(); - /** - * If you wish to support air, you must test before getting the ItemStack, or ItemStackSet - * - * @return true if this slot contains no ItemStack, this is passed as "_" - */ - boolean isAir(); + /** + * @return The Name of the item. Prefer getItemStack or getItemStackSet + */ + String getItemName(); - /** - * @return The Name Space of the item. Prefer getItemStack or getItemStackSet - */ - String getNameSpace(); + /** + * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet + */ + int getDamageValue(); - /** - * @return The Name of the item. Prefer getItemStack or getItemStackSet - */ - String getItemName(); + /** + * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet + */ + int getQty(); - /** - * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet - */ - int getDamageValue(); - - /** - * @return The Damage Value of the item. Prefer getItemStack or getItemStackSet - */ - int getQty(); - - /** - * Bakes the lists in for faster runtime look-ups. - * - * @throws MissingIngredientError - * @throws RegistrationError - */ - void bake() throws RegistrationError, MissingIngredientError; + /** + * 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/recipes/IRecipeHandler.java b/src/api/java/appeng/api/recipes/IRecipeHandler.java index 5c7b32e0..f56b09c5 100644 --- a/src/api/java/appeng/api/recipes/IRecipeHandler.java +++ b/src/api/java/appeng/api/recipes/IRecipeHandler.java @@ -23,23 +23,20 @@ package appeng.api.recipes; - /** * Represents the AE2 Recipe Loading/Reading Class */ -public interface IRecipeHandler -{ +public interface IRecipeHandler { + /** + * Call when you want to read recipes in from a file based on a loader + * + * @param loader recipe loader + * @param path path of file + */ + void parseRecipes(IRecipeLoader loader, String path); - /** - * Call when you want to read recipes in from a file based on a loader - * - * @param loader recipe loader - * @param path path of file - */ - void parseRecipes( IRecipeLoader loader, String path ); - - /** - * this loads the read recipes into minecraft, should be called in Init. - */ - void injectRecipes(); + /** + * this loads the read recipes into minecraft, should be called in Init. + */ + void injectRecipes(); } diff --git a/src/api/java/appeng/api/recipes/IRecipeLoader.java b/src/api/java/appeng/api/recipes/IRecipeLoader.java index fe1e485c..bb69f245 100644 --- a/src/api/java/appeng/api/recipes/IRecipeLoader.java +++ b/src/api/java/appeng/api/recipes/IRecipeLoader.java @@ -23,17 +23,14 @@ package appeng.api.recipes; - -import javax.annotation.Nonnull; import java.io.BufferedReader; +import javax.annotation.Nonnull; - -public interface IRecipeLoader -{ - /** - * @param filePath the path to the to be loaded file - * @return reader handler of the file - * @throws Exception if reading goes wrong - */ - BufferedReader getFile( @Nonnull String filePath ) throws Exception; +public interface IRecipeLoader { + /** + * @param filePath the path to the to be loaded file + * @return reader handler of the file + * @throws Exception if reading goes wrong + */ + BufferedReader getFile(@Nonnull String filePath) throws Exception; } diff --git a/src/api/java/appeng/api/recipes/ISubItemResolver.java b/src/api/java/appeng/api/recipes/ISubItemResolver.java index 3ef2bd09..3c311b0a 100644 --- a/src/api/java/appeng/api/recipes/ISubItemResolver.java +++ b/src/api/java/appeng/api/recipes/ISubItemResolver.java @@ -23,13 +23,11 @@ package appeng.api.recipes; - -public interface ISubItemResolver -{ - /** - * @param namespace namespace of sub item - * @param fullName name of sub item - * @return either a ResolveResult, or a ResolverResultSet - */ - Object resolveItemByName( String namespace, String fullName ); +public interface ISubItemResolver { + /** + * @param namespace namespace of sub item + * @param fullName name of sub item + * @return either a ResolveResult, or a ResolverResultSet + */ + Object resolveItemByName(String namespace, String fullName); } diff --git a/src/api/java/appeng/api/recipes/ResolverResult.java b/src/api/java/appeng/api/recipes/ResolverResult.java index 51405576..2878e649 100644 --- a/src/api/java/appeng/api/recipes/ResolverResult.java +++ b/src/api/java/appeng/api/recipes/ResolverResult.java @@ -23,28 +23,24 @@ package appeng.api.recipes; - import net.minecraft.nbt.NBTTagCompound; +public class ResolverResult { + public final String itemName; + public final int damageValue; + public final NBTTagCompound compound; -public class ResolverResult -{ + public ResolverResult(final String name, final int damage) { + this.itemName = name; + this.damageValue = damage; + this.compound = null; + } - public final String itemName; - public final int damageValue; - public final NBTTagCompound compound; - - public ResolverResult( final String name, final int damage ) - { - this.itemName = name; - this.damageValue = damage; - this.compound = null; - } - - public ResolverResult( final String name, final int damage, final NBTTagCompound data ) - { - this.itemName = name; - this.damageValue = damage; - this.compound = data; - } + public ResolverResult( + final String name, final int damage, final NBTTagCompound data + ) { + this.itemName = name; + this.damageValue = damage; + this.compound = data; + } } diff --git a/src/api/java/appeng/api/recipes/ResolverResultSet.java b/src/api/java/appeng/api/recipes/ResolverResultSet.java index 0531ba61..eb00da67 100644 --- a/src/api/java/appeng/api/recipes/ResolverResultSet.java +++ b/src/api/java/appeng/api/recipes/ResolverResultSet.java @@ -23,22 +23,17 @@ package appeng.api.recipes; - -import net.minecraft.item.ItemStack; - import java.util.Arrays; import java.util.List; +import net.minecraft.item.ItemStack; -public class ResolverResultSet -{ +public class ResolverResultSet { + public final String name; + public final List results; - public final String name; - public final List results; - - public ResolverResultSet( final String myName, final ItemStack... set ) - { - this.results = Arrays.asList( set ); - this.name = myName; - } + public ResolverResultSet(final String myName, final ItemStack... set) { + this.results = Arrays.asList(set); + this.name = myName; + } } diff --git a/src/api/java/appeng/api/storage/ICellContainer.java b/src/api/java/appeng/api/storage/ICellContainer.java index 4445dd3e..87e2d8d1 100644 --- a/src/api/java/appeng/api/storage/ICellContainer.java +++ b/src/api/java/appeng/api/storage/ICellContainer.java @@ -23,20 +23,18 @@ package appeng.api.storage; - import appeng.api.networking.security.IActionHost; - /** - * Represents an {@link appeng.api.networking.IGridHost} that contributes to storage, such as a ME Chest, or ME Drive. + * Represents an {@link appeng.api.networking.IGridHost} that contributes to storage, such + * as a ME Chest, or ME Drive. */ -public interface ICellContainer extends IActionHost, ICellProvider, ISaveProvider -{ - - /** - * tell the Cell container that this slot should blink, the slot number is relative to the - * - * @param slot slot index - */ - void blinkCell( int slot ); +public interface ICellContainer extends IActionHost, ICellProvider, ISaveProvider { + /** + * tell the Cell container that this slot should blink, the slot number is relative to + * the + * + * @param slot slot index + */ + void blinkCell(int slot); } diff --git a/src/api/java/appeng/api/storage/ICellHandler.java b/src/api/java/appeng/api/storage/ICellHandler.java index 005659ed..270917c5 100644 --- a/src/api/java/appeng/api/storage/ICellHandler.java +++ b/src/api/java/appeng/api/storage/ICellHandler.java @@ -23,7 +23,6 @@ package appeng.api.storage; - import appeng.api.implementations.tiles.IChestOrDrive; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -31,88 +30,99 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; - /** * Registration record for {@link ICellRegistry} */ -public interface ICellHandler -{ +public interface ICellHandler { + /** + * return true if the provided item is handled by your cell handler. ( AE May choose + * to skip this method, and just request a handler ) + * + * @param is to be checked item + * @return return true, if getCellHandler will not return null. + */ + boolean isCell(ItemStack is); - /** - * return true if the provided item is handled by your cell handler. ( AE May choose to skip this method, and just - * request a handler ) - * - * @param is to be checked item - * @return return true, if getCellHandler will not return null. - */ - 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. + * @return a new IMEHandler for the provided item + */ + IMEInventoryHandler + getCellInventory(ItemStack is, ISaveProvider host, StorageChannel channel); - /** - * 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. - * @return a new IMEHandler for the provided item - */ - 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. + */ + @SideOnly(Side.CLIENT) + IIcon getTopTexture_Light(); - /** - * @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. - */ - @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. + */ + @SideOnly(Side.CLIENT) + IIcon getTopTexture_Medium(); - /** - * @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. - */ - @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. + */ + @SideOnly(Side.CLIENT) + IIcon getTopTexture_Dark(); - /** - * @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. - */ - @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 cellHandler cell handler + * @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 + ); - /** - * 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 cellHandler cell handler - * @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 ); + /** + * 0 - cell is missing. + *

+ * 1 - green, ( usually means available room for types or items. ) + *

+ * 2 - orange, ( usually means available room for items, but not types. ) + *

+ * 3 - red, ( usually means the cell is 100% full ) + * + * @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); - /** - * 0 - cell is missing. - *

- * 1 - green, ( usually means available room for types or items. ) - *

- * 2 - orange, ( usually means available room for items, but not types. ) - *

- * 3 - red, ( usually means the cell is 100% full ) - * - * @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 ); - - /** - * @return the ae/t to drain for this storage cell inside a chest/drive. - */ - double cellIdleDrain( ItemStack is, IMEInventory handler ); + /** + * @return the ae/t to drain for this storage cell inside a chest/drive. + */ + double cellIdleDrain(ItemStack is, IMEInventory handler); } \ No newline at end of file diff --git a/src/api/java/appeng/api/storage/ICellInventory.java b/src/api/java/appeng/api/storage/ICellInventory.java index c711ce6a..31b62b35 100644 --- a/src/api/java/appeng/api/storage/ICellInventory.java +++ b/src/api/java/appeng/api/storage/ICellInventory.java @@ -23,98 +23,94 @@ package appeng.api.storage; - import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public interface ICellInventory extends IMEInventory { + /** + * @return the item stack of this storage cell. + */ + ItemStack getItemStack(); -public interface ICellInventory extends IMEInventory -{ + /** + * @return idle cost for this Storage Cell + */ + double getIdleDrain(); - /** - * @return the item stack of this storage cell. - */ - ItemStack getItemStack(); + /** + * @return fuzzy setting + */ + FuzzyMode getFuzzyMode(); - /** - * @return idle cost for this Storage Cell - */ - double getIdleDrain(); + /** + * @return access configured list + */ + IInventory getConfigInventory(); - /** - * @return fuzzy setting - */ - FuzzyMode getFuzzyMode(); + /** + * @return access installed upgrades. + */ + IInventory getUpgradesInventory(); - /** - * @return access configured list - */ - IInventory getConfigInventory(); + /** + * @return How many bytes are used for each type? + */ + int getBytesPerType(); - /** - * @return access installed upgrades. - */ - IInventory getUpgradesInventory(); + /** + * @return true if a new item type can be added. + */ + boolean canHoldNewItem(); - /** - * @return How many bytes are used for each type? - */ - int getBytesPerType(); + /** + * @return total byte storage. + */ + long getTotalBytes(); - /** - * @return true if a new item type can be added. - */ - boolean canHoldNewItem(); + /** + * @return how many bytes are free. + */ + long getFreeBytes(); - /** - * @return total byte storage. - */ - long getTotalBytes(); + /** + * @return how many bytes are in use. + */ + long getUsedBytes(); - /** - * @return how many bytes are free. - */ - long getFreeBytes(); + /** + * @return max number of types. + */ + long getTotalItemTypes(); - /** - * @return how many bytes are in use. - */ - long getUsedBytes(); + /** + * @return how many items are stored. + */ + long getStoredItemCount(); - /** - * @return max number of types. - */ - long getTotalItemTypes(); + /** + * @return how many items types are currently stored. + */ + long getStoredItemTypes(); - /** - * @return how many items are stored. - */ - long getStoredItemCount(); + /** + * @return how many item types remain. + */ + long getRemainingItemTypes(); - /** - * @return how many items types are currently stored. - */ - long getStoredItemTypes(); + /** + * @return how many more items can be stored. + */ + long getRemainingItemCount(); - /** - * @return how many item types remain. - */ - long getRemainingItemTypes(); + /** + * @return how many items can be added without consuming another byte. + */ + int getUnusedItemCount(); - /** - * @return how many more items can be stored. - */ - long getRemainingItemCount(); - - /** - * @return how many items can be added without consuming another byte. - */ - int getUnusedItemCount(); - - /** - * @return the status number for this drive. - */ - int getStatusForCell(); + /** + * @return the status number for this drive. + */ + int getStatusForCell(); } diff --git a/src/api/java/appeng/api/storage/ICellInventoryHandler.java b/src/api/java/appeng/api/storage/ICellInventoryHandler.java index 3f1e77ad..cbb6e4f5 100644 --- a/src/api/java/appeng/api/storage/ICellInventoryHandler.java +++ b/src/api/java/appeng/api/storage/ICellInventoryHandler.java @@ -23,22 +23,18 @@ package appeng.api.storage; - import appeng.api.config.IncludeExclude; import appeng.api.storage.data.IAEItemStack; +public interface ICellInventoryHandler extends IMEInventoryHandler { + /** + * @return get access to the Cell Inventory. + */ + ICellInventory getCellInv(); -public interface ICellInventoryHandler extends IMEInventoryHandler -{ + boolean isPreformatted(); - /** - * @return get access to the Cell Inventory. - */ - ICellInventory getCellInv(); + boolean isFuzzy(); - boolean isPreformatted(); - - boolean isFuzzy(); - - IncludeExclude getIncludeExcludeMode(); + IncludeExclude getIncludeExcludeMode(); } diff --git a/src/api/java/appeng/api/storage/ICellProvider.java b/src/api/java/appeng/api/storage/ICellProvider.java index 589ca335..a70e432d 100644 --- a/src/api/java/appeng/api/storage/ICellProvider.java +++ b/src/api/java/appeng/api/storage/ICellProvider.java @@ -23,31 +23,28 @@ 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. + * 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. */ -public interface ICellProvider -{ +public interface ICellProvider { + /** + * Inventory of the tile for use with ME, should always return an valid list, never + * NULL.

You must return the correct Handler for the correct channel, if your + * handler returns a IAEItemStack handler, for a Fluid Channel stuffs going to + * explode, same with the reverse. + * + * @return a valid list of handlers, NEVER NULL + */ + List getCellArray(StorageChannel channel); - /** - * Inventory of the tile for use with ME, should always return an valid list, never NULL. - *

- * You must return the correct Handler for the correct channel, if your handler returns a IAEItemStack handler, for - * a Fluid Channel stuffs going to explode, same with the reverse. - * - * @return a valid list of handlers, NEVER NULL - */ - List getCellArray( StorageChannel channel ); - - /** - * the storage's priority. - *

- * Positive and negative are supported - */ - int getPriority(); + /** + * the storage's priority. + *

+ * 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 c2000bd0..a5198c08 100644 --- a/src/api/java/appeng/api/storage/ICellRegistry.java +++ b/src/api/java/appeng/api/storage/ICellRegistry.java @@ -23,51 +23,49 @@ package appeng.api.storage; - import appeng.api.IAppEngApi; import net.minecraft.item.ItemStack; - /** - * 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. - *

- * Do not Implement, obtained via {@link IAppEngApi}.getCellRegistry() + * 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.

Do not Implement, obtained + * via {@link IAppEngApi}.getCellRegistry() */ -public interface ICellRegistry -{ +public interface ICellRegistry { + /** + * Register a new handler. + * + * @param handler cell handler + */ + void addCellHandler(ICellHandler handler); - /** - * Register a new handler. - * - * @param handler cell 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. ) + */ + boolean isCellHandled(ItemStack is); - /** - * 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. ) - */ - 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); - /** - * 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 ); - - /** - * returns an IMEInventoryHandler for the provided item. - * - * @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 ); + /** + * returns an IMEInventoryHandler for the provided item. + * + * @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); } \ 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 e4830807..55deb7b3 100644 --- a/src/api/java/appeng/api/storage/ICellWorkbenchItem.java +++ b/src/api/java/appeng/api/storage/ICellWorkbenchItem.java @@ -23,47 +23,43 @@ package appeng.api.storage; - import appeng.api.config.FuzzyMode; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +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); -public interface ICellWorkbenchItem -{ + /** + * used to edit the upgrade slots on your cell, should have a capacity of 0-24, you + * are also responsible for implementing the valid checks, and any storage/usage of + * them.

onInventoryChange will be called when saving is needed. + */ + IInventory getUpgradesInventory(ItemStack is); - /** - * 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 ); + /** + * Used to extract, or mirror the contents of the work bench onto the cell. + *

+ * - This should have exactly 63 slots, any more, or less might cause issues. + *

+ * onInventoryChange will be called when saving is needed. + */ + IInventory getConfigInventory(ItemStack is); - /** - * used to edit the upgrade slots on your cell, should have a capacity of 0-24, you are also responsible for - * implementing the valid checks, and any storage/usage of them. - *

- * onInventoryChange will be called when saving is needed. - */ - IInventory getUpgradesInventory( ItemStack is ); + /** + * @return the current fuzzy status. + */ + FuzzyMode getFuzzyMode(ItemStack is); - /** - * Used to extract, or mirror the contents of the work bench onto the cell. - *

- * - This should have exactly 63 slots, any more, or less might cause issues. - *

- * onInventoryChange will be called when saving is needed. - */ - IInventory getConfigInventory( ItemStack is ); - - /** - * @return the current fuzzy status. - */ - FuzzyMode getFuzzyMode( ItemStack is ); - - /** - * sets the setting on the cell. - */ - void setFuzzyMode( ItemStack is, FuzzyMode fzMode ); + /** + * sets the setting on the cell. + */ + 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 e3c421c0..b20ab99b 100644 --- a/src/api/java/appeng/api/storage/IExternalStorageHandler.java +++ b/src/api/java/appeng/api/storage/IExternalStorageHandler.java @@ -23,39 +23,41 @@ package appeng.api.storage; - import appeng.api.networking.security.BaseActionSource; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * A Registration Record for {@link IExternalStorageRegistry} */ -public interface IExternalStorageHandler -{ +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 mySrc source + * @return true, if it can get a handler via getInventory + */ + boolean canHandle( + TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource mySrc + ); - /** - * 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 mySrc source - * @return true, if it can get a handler via getInventory - */ - 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 - *

- * 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 channel channel - * @param src source - * @return The Handler for the inventory - */ - IMEInventory getInventory( TileEntity te, ForgeDirection d, StorageChannel channel, BaseActionSource src ); + /** + * if this can handle the given inventory, return the a IMEInventory implementing + * class for it, if not return null

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 channel channel + * @param src source + * @return The Handler for the inventory + */ + 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 0be24a55..0e3b5fef 100644 --- a/src/api/java/appeng/api/storage/IExternalStorageRegistry.java +++ b/src/api/java/appeng/api/storage/IExternalStorageRegistry.java @@ -23,34 +23,36 @@ package appeng.api.storage; - import appeng.api.IAppEngApi; import appeng.api.networking.security.BaseActionSource; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * A Registry of External Storage handlers. *

- * Do not implement obtain via {@link IAppEngApi}.registries().getExternalStorageRegistry() + * Do not implement obtain via {@link + * IAppEngApi}.registries().getExternalStorageRegistry() */ -public interface IExternalStorageRegistry -{ +public interface IExternalStorageRegistry { + /** + * A registry for StorageBus interactions + * + * @param esh storage handler + */ + void addExternalStorageInterface(IExternalStorageHandler esh); - /** - * A registry for StorageBus interactions - * - * @param esh storage handler - */ - void addExternalStorageInterface( IExternalStorageHandler esh ); - - /** - * @param te tile entity - * @param opposite direction - * @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 ); + /** + * @param te tile entity + * @param opposite direction + * @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 + ); } \ 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 51f4a790..d82fc838 100644 --- a/src/api/java/appeng/api/storage/IMEInventory.java +++ b/src/api/java/appeng/api/storage/IMEInventory.java @@ -23,55 +23,50 @@ 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. - *

- * Implementations should COMPLETELY ignore stack size limits from an external view point, Meaning that you can inject - * Integer.MAX_VALUE items and it should work as defined, or be able to extract Integer.MAX_VALUE and have it work as - * defined, Translations to MC's max stack size are external to the AE API. - *

- * If you want to request a stack of an item, you should should determine that prior to requesting the stack from the - * inventory. + * AE's Equivalent to IInventory, used to reading contents, and manipulating contents of + * ME Inventories.

Implementations should COMPLETELY ignore stack size limits from an + * external view point, Meaning that you can inject Integer.MAX_VALUE items and it should + * work as defined, or be able to extract Integer.MAX_VALUE and have it work as defined, + * Translations to MC's max stack size are external to the AE API.

If you want to + * request a stack of an item, you should should determine that prior to requesting the + * stack from the inventory. */ -public interface IMEInventory -{ +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 + * @return returns the number of items not added. + */ + StackType injectItems(StackType input, Actionable type, BaseActionSource src); - /** - * 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 - * @return returns the number of items not added. - */ - StackType injectItems( StackType input, Actionable type, BaseActionSource src ); + /** + * Extract the specified item from the ME Inventory + * + * @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); - /** - * Extract the specified item from the ME Inventory - * - * @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 ); + /** + * request a full report of all available items, storage. + * + * @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); - /** - * request a full report of all available items, storage. - * - * @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 ); - - /** - * @return the type of channel your handler should be part of - */ - StorageChannel getChannel(); + /** + * @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 52806c52..79051be9 100644 --- a/src/api/java/appeng/api/storage/IMEInventoryHandler.java +++ b/src/api/java/appeng/api/storage/IMEInventoryHandler.java @@ -23,67 +23,67 @@ 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. + * 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. * * @param */ -public interface IMEInventoryHandler extends IMEInventory -{ +public interface IMEInventoryHandler + extends IMEInventory { + /** + * determine if items can be injected/extracted. + * + * @return the access + */ + AccessRestriction getAccess(); - /** - * determine if items can be injected/extracted. - * - * @return the access - */ - AccessRestriction getAccess(); + /** + * 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 + * @return if its prioritized + */ + boolean isPrioritized(StackType input); - /** - * 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 - * @return if its prioritized - */ - boolean isPrioritized( StackType input ); + /** + * determine if an item can be accepted and stored. + * + * @param input - item that might be added + * @return if the item can be added + */ + boolean canAccept(StackType input); - /** - * determine if an item can be accepted and stored. - * - * @param input - item that might be added - * @return if the item can be added - */ - boolean canAccept( StackType input ); + /** + * determine what the priority of the inventory is. + * + * @return the priority, zero is default, positive and negative are supported. + */ + int getPriority(); - /** - * determine what the priority of the inventory is. - * - * @return the priority, zero is default, positive and negative are supported. - */ - int getPriority(); + /** + * 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. + */ + int getSlot(); - /** - * 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. - */ - int getSlot(); - - /** - * AE Uses a two pass placement system, the first pass checks contents and tries to find a place where the item - * 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 ) - * @return true, if this inventory is valid for this pass. - */ - boolean validForPass( int i ); + /** + * AE Uses a two pass placement system, the first pass checks contents and tries to + * find a place where the item 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 ) + * @return true, if this inventory is valid for this pass. + */ + boolean validForPass(int i); } diff --git a/src/api/java/appeng/api/storage/IMEMonitor.java b/src/api/java/appeng/api/storage/IMEMonitor.java index 752691e2..eb3461f4 100644 --- a/src/api/java/appeng/api/storage/IMEMonitor.java +++ b/src/api/java/appeng/api/storage/IMEMonitor.java @@ -23,26 +23,24 @@ package appeng.api.storage; - import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public interface IMEMonitor + extends IMEInventoryHandler, IBaseMonitor { + /** + * This method is discouraged when accessing data via a IMEMonitor + */ + @Override + @Deprecated + IItemList getAvailableItems(IItemList out); -public interface IMEMonitor extends IMEInventoryHandler, IBaseMonitor -{ - - /** - * This method is discouraged when accessing data via a IMEMonitor - */ - @Override - @Deprecated - IItemList getAvailableItems( IItemList out ); - - /** - * Get access to the full item list of the network, preferred over {@link IMEInventory} .getAvailableItems(...) - * - * @return full storage list. - */ - IItemList getStorageList(); + /** + * Get access to the full item list of the network, preferred over {@link + * IMEInventory} .getAvailableItems(...) + * + * @return full storage list. + */ + IItemList getStorageList(); } diff --git a/src/api/java/appeng/api/storage/IMEMonitorHandlerReceiver.java b/src/api/java/appeng/api/storage/IMEMonitorHandlerReceiver.java index 9b8a9f5f..06479545 100644 --- a/src/api/java/appeng/api/storage/IMEMonitorHandlerReceiver.java +++ b/src/api/java/appeng/api/storage/IMEMonitorHandlerReceiver.java @@ -23,32 +23,33 @@ package appeng.api.storage; - import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IBaseMonitor; import appeng.api.storage.data.IAEStack; +public interface IMEMonitorHandlerReceiver { + /** + * return true if this object should remain as a listener. + * + * @param verificationToken to be checked object + * @return true if object should remain as a listener + */ + boolean isValid(Object verificationToken); -public interface IMEMonitorHandlerReceiver -{ + /** + * called when changes are made to the Monitor, but only if listener is still valid. + * + * @param change done change + */ + void postChange( + IBaseMonitor monitor, + Iterable change, + BaseActionSource actionSource + ); - /** - * return true if this object should remain as a listener. - * - * @param verificationToken to be checked object - * @return true if object should remain as a listener - */ - boolean isValid( Object verificationToken ); - - /** - * called when changes are made to the Monitor, but only if listener is still valid. - * - * @param change done change - */ - void postChange( IBaseMonitor monitor, Iterable change, BaseActionSource actionSource ); - - /** - * called when the list updates its contents, this is mostly for handling power events. - */ - void onListUpdate(); + /** + * called when the list updates its contents, this is mostly for handling power + * events. + */ + void onListUpdate(); } diff --git a/src/api/java/appeng/api/storage/ISaveProvider.java b/src/api/java/appeng/api/storage/ISaveProvider.java index 7c046826..99878902 100644 --- a/src/api/java/appeng/api/storage/ISaveProvider.java +++ b/src/api/java/appeng/api/storage/ISaveProvider.java @@ -23,9 +23,6 @@ package appeng.api.storage; - -public interface ISaveProvider -{ - - void saveChanges( IMEInventory cellInventory ); +public interface ISaveProvider { + void saveChanges(IMEInventory cellInventory); } diff --git a/src/api/java/appeng/api/storage/IStorageHelper.java b/src/api/java/appeng/api/storage/IStorageHelper.java index 22d2997b..2d663373 100644 --- a/src/api/java/appeng/api/storage/IStorageHelper.java +++ b/src/api/java/appeng/api/storage/IStorageHelper.java @@ -23,6 +23,7 @@ package appeng.api.storage; +import java.io.IOException; import appeng.api.networking.crafting.ICraftingLink; import appeng.api.networking.crafting.ICraftingRequester; @@ -36,79 +37,84 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; -import java.io.IOException; +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); + /** + * @param is An ItemStack + * @return a new INSTANCE of {@link IAEItemStack} from a MC {@link ItemStack} + */ + IAEItemStack createItemStack(ItemStack is); -public interface IStorageHelper -{ + /** + * @param is A FluidStack + * @return a new INSTANCE of {@link IAEFluidStack} from a Forge {@link FluidStack} + */ + IAEFluidStack createFluidStack(FluidStack is); - /** - * load a crafting link from nbt data. - * - * @param data to be loaded data - * @return crafting link - */ - ICraftingLink loadCraftingLink( NBTTagCompound data, ICraftingRequester req ); + /** + * @return a new INSTANCE of {@link IItemList} for items + */ + IItemList createItemList(); - /** - * @param is An ItemStack - * @return a new INSTANCE of {@link IAEItemStack} from a MC {@link ItemStack} - */ - IAEItemStack createItemStack( ItemStack is ); + /** + * @return a new INSTANCE of {@link IItemList} for fluids + */ + IItemList createFluidList(); - /** - * @param is A FluidStack - * @return a new INSTANCE of {@link IAEFluidStack} from a Forge {@link FluidStack} - */ - IAEFluidStack createFluidStack( FluidStack is ); + /** + * 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; - /** - * @return a new INSTANCE of {@link IItemList} for items - */ - IItemList createItemList(); + /** + * 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; - /** - * @return a new INSTANCE of {@link IItemList} for fluids - */ - IItemList createFluidList(); + /** + * 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 request requested items + * @param src action source + * @return items that successfully extracted. + */ + IAEItemStack poweredExtraction( + IEnergySource energy, + IMEInventory cell, + IAEItemStack request, + BaseActionSource src + ); - /** - * 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; - - /** - * 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; - - /** - * 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 request requested items - * @param src action source - * @return items that successfully extracted. - */ - 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 - * @return items that failed to insert. - */ - IAEItemStack poweredInsert( IEnergySource energy, IMEInventory cell, IAEItemStack input, 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 + * @return items that failed to insert. + */ + 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 251b7ebe..0eadec50 100644 --- a/src/api/java/appeng/api/storage/IStorageMonitorable.java +++ b/src/api/java/appeng/api/storage/IStorageMonitorable.java @@ -23,27 +23,23 @@ 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. - *

- * never check a tile for this, always go though ITileStorageMonitorable if you wish to use this interface. + * represents the internal behavior of a {@link ITileStorageMonitorable} use it to get + * this value for a tile, or part.

never check a tile for this, always go though + * ITileStorageMonitorable if you wish to use this interface. */ -public interface IStorageMonitorable -{ +public interface IStorageMonitorable { + /** + * Access the item inventory for the monitorable storage. + */ + IMEMonitor getItemInventory(); - /** - * Access the item inventory for the monitorable storage. - */ - IMEMonitor getItemInventory(); - - /** - * Access the fluid inventory for the monitorable storage. - */ - IMEMonitor getFluidInventory(); + /** + * Access the fluid inventory for the monitorable storage. + */ + IMEMonitor getFluidInventory(); } diff --git a/src/api/java/appeng/api/storage/ITerminalHost.java b/src/api/java/appeng/api/storage/ITerminalHost.java index f802b6d6..742ced27 100644 --- a/src/api/java/appeng/api/storage/ITerminalHost.java +++ b/src/api/java/appeng/api/storage/ITerminalHost.java @@ -23,11 +23,6 @@ package appeng.api.storage; - import appeng.api.util.IConfigurableObject; - -public interface ITerminalHost extends IStorageMonitorable, IConfigurableObject -{ - -} +public interface ITerminalHost extends IStorageMonitorable, IConfigurableObject {} diff --git a/src/api/java/appeng/api/storage/MEMonitorHandler.java b/src/api/java/appeng/api/storage/MEMonitorHandler.java index 41450151..57de98c2 100644 --- a/src/api/java/appeng/api/storage/MEMonitorHandler.java +++ b/src/api/java/appeng/api/storage/MEMonitorHandler.java @@ -23,6 +23,9 @@ package appeng.api.storage; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -31,184 +34,169 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; import com.google.common.collect.ImmutableList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; - - /** - * Common implementation of a simple class that monitors injection/extraction of a inventory to send events to a list of - * listeners. + * Common implementation of a simple class that monitors injection/extraction of a + * inventory to send events to a list of listeners. * * @param */ -public class MEMonitorHandler implements IMEMonitor -{ +public class MEMonitorHandler + implements IMEMonitor { + private final IMEInventoryHandler internalHandler; + private final IItemList cachedList; + private final HashMap, Object> listeners + = new HashMap, Object>(); - private final IMEInventoryHandler internalHandler; - private final IItemList cachedList; - private final HashMap, Object> listeners = new HashMap, Object>(); + protected boolean hasChanged = true; - protected boolean hasChanged = true; + public MEMonitorHandler(final IMEInventoryHandler t) { + this.internalHandler = t; + this.cachedList = (IItemList) t.getChannel().createList(); + } - public MEMonitorHandler( final IMEInventoryHandler t ) - { - this.internalHandler = t; - this.cachedList = (IItemList) t.getChannel().createList(); - } + public MEMonitorHandler( + final IMEInventoryHandler t, final StorageChannel chan + ) { + this.internalHandler = t; + this.cachedList = (IItemList) chan.createList(); + } - public MEMonitorHandler( final IMEInventoryHandler t, final StorageChannel chan ) - { - this.internalHandler = t; - this.cachedList = (IItemList) chan.createList(); - } + @Override + public void addListener( + final IMEMonitorHandlerReceiver l, final Object verificationToken + ) { + this.listeners.put(l, verificationToken); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public StackType injectItems( + final StackType input, final Actionable mode, final 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 injectItems( final StackType input, final Actionable mode, final 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; + } - protected IMEInventoryHandler getHandler() - { - return this.internalHandler; - } + private StackType monitorDifference( + final IAEStack original, + final StackType leftOvers, + final boolean extraction, + final BaseActionSource src + ) { + final StackType diff = (StackType) original.copy(); - private StackType monitorDifference( final IAEStack original, final StackType leftOvers, final boolean extraction, final BaseActionSource src ) - { - final StackType diff = (StackType) original.copy(); + if (extraction) { + diff.setStackSize(leftOvers == null ? 0 : -leftOvers.getStackSize()); + } else if (leftOvers != null) { + diff.decStackSize(leftOvers.getStackSize()); + } - 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); + } - if( diff.getStackSize() != 0 ) - { - this.postChangesToListeners( ImmutableList.of( diff ), src ); - } + return leftOvers; + } - return leftOvers; - } + protected void postChangesToListeners( + final Iterable changes, final BaseActionSource src + ) { + this.notifyListenersOfChange(changes, src); + } - protected void postChangesToListeners( final Iterable changes, final BaseActionSource src ) - { - this.notifyListenersOfChange( changes, src ); - } + protected void + notifyListenersOfChange(final Iterable diff, final BaseActionSource src) { + this.hasChanged = true; // need to update the cache. + final Iterator, Object>> i + = this.getListeners(); + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + if (receiver.isValid(o.getValue())) { + receiver.postChange(this, diff, src); + } else { + i.remove(); + } + } + } - protected void notifyListenersOfChange( final Iterable diff, final BaseActionSource src ) - { - this.hasChanged = true;// need to update the cache. - final Iterator, Object>> i = this.getListeners(); - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final 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 Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } + @Override + public StackType extractItems( + final StackType request, final Actionable mode, final BaseActionSource src + ) { + 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 StackType extractItems( final StackType request, final Actionable mode, final BaseActionSource src ) - { - 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 StorageChannel getChannel() { + return this.getHandler().getChannel(); + } - @Override - public StorageChannel getChannel() - { - return this.getHandler().getChannel(); - } + @Override + public AccessRestriction getAccess() { + return this.getHandler().getAccess(); + } - @Override - 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); + } - @Override - public IItemList getStorageList() - { - if( this.hasChanged ) - { - this.hasChanged = false; - this.cachedList.resetStatus(); - return this.getAvailableItems( this.cachedList ); - } + return this.cachedList; + } - return this.cachedList; - } + @Override + public boolean isPrioritized(final StackType input) { + return this.getHandler().isPrioritized(input); + } - @Override - public boolean isPrioritized( final StackType input ) - { - return this.getHandler().isPrioritized( input ); - } + @Override + public boolean canAccept(final StackType input) { + return this.getHandler().canAccept(input); + } - @Override - public boolean canAccept( final StackType input ) - { - return this.getHandler().canAccept( input ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.getHandler().getAvailableItems(out); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.getHandler().getAvailableItems( out ); - } + @Override + public int getPriority() { + return this.getHandler().getPriority(); + } - @Override - public int getPriority() - { - return this.getHandler().getPriority(); - } - - @Override - public int getSlot() - { - return this.getHandler().getSlot(); - } - - @Override - public boolean validForPass( final int i ) - { - return this.getHandler().validForPass( i ); - } + @Override + public int getSlot() { + return this.getHandler().getSlot(); + } + @Override + public boolean validForPass(final 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 2e57310f..018c2b11 100644 --- a/src/api/java/appeng/api/storage/StorageChannel.java +++ b/src/api/java/appeng/api/storage/StorageChannel.java @@ -23,42 +23,34 @@ package appeng.api.storage; - import appeng.api.AEApi; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public enum StorageChannel { + /** + * AE2's Default Storage. + */ + ITEMS(IAEItemStack.class), -public enum StorageChannel -{ - /** - * AE2's Default Storage. - */ - ITEMS( IAEItemStack.class ), + /** + * AE2's Fluid Based Storage ( mainly added to better support ExtraCells ) + */ + FLUIDS(IAEFluidStack.class); - /** - * AE2's Fluid Based Storage ( mainly added to better support ExtraCells ) - */ - FLUIDS( IAEFluidStack.class ); + public final Class type; - public final Class type; + StorageChannel(final Class t) { + this.type = t; + } - StorageChannel( final Class t ) - { - this.type = t; - } - - public IItemList createList() - { - if( this == ITEMS ) - { - return AEApi.instance().storage().createItemList(); - } - else - { - return AEApi.instance().storage().createFluidList(); - } - } + public IItemList createList() { + 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 3ffb5a4f..e660dcf0 100644 --- a/src/api/java/appeng/api/storage/data/IAEFluidStack.java +++ b/src/api/java/appeng/api/storage/data/IAEFluidStack.java @@ -23,11 +23,9 @@ 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. @@ -39,36 +37,34 @@ import net.minecraftforge.fluids.FluidStack; *

* Construct with Util.createFluidStack( FluidStack ) */ -public interface IAEFluidStack extends IAEStack -{ +public interface IAEFluidStack extends IAEStack { + /** + * creates a standard Forge FluidStack for the fluid. + * + * @return new FluidStack + */ + FluidStack getFluidStack(); - /** - * creates a standard Forge FluidStack for the fluid. - * - * @return new FluidStack - */ - FluidStack getFluidStack(); + /** + * Combines two IAEItemStacks via addition. + * + * @param option , to add to the current one. + */ + @Override + void add(IAEFluidStack option); - /** - * Combines two IAEItemStacks via addition. - * - * @param option , to add to the current one. - */ - @Override - void add( IAEFluidStack option ); + /** + * create a AE Fluid clone. + * + * @return the copy. + */ + @Override + IAEFluidStack copy(); - /** - * create a AE Fluid clone. - * - * @return the copy. - */ - @Override - IAEFluidStack copy(); - - /** - * quick way to get access to the Forge Fluid Definition. - * - * @return fluid definition - */ - Fluid getFluid(); + /** + * 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 883479d6..6172e8a7 100644 --- a/src/api/java/appeng/api/storage/data/IAEItemStack.java +++ b/src/api/java/appeng/api/storage/data/IAEItemStack.java @@ -23,84 +23,76 @@ 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. - *

- * You may hold on to these if you want, just make sure you let go of them when your not using them. - *

- * Don't Implement. - *

- * Construct with Util.createItemStack( 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.

You may hold on to these + * if you want, just make sure you let go of them when your not using them.

Don't + * Implement.

Construct with Util.createItemStack( ItemStack ) */ -public interface IAEItemStack extends IAEStack -{ +public interface IAEItemStack extends IAEStack { + /** + * creates a standard MC ItemStack for the item. + * + * @return new ItemStack + */ + ItemStack getItemStack(); - /** - * creates a standard MC ItemStack for the item. - * - * @return new ItemStack - */ - ItemStack getItemStack(); + /** + * is there NBT Data for this item? + * + * @return if there is + */ + boolean hasTagCompound(); - /** - * is there NBT Data for this item? - * - * @return if there is - */ - boolean hasTagCompound(); + /** + * Combines two IAEItemStacks via addition. + * + * @param option to add to the current one. + */ + @Override + void add(IAEItemStack option); - /** - * Combines two IAEItemStacks via addition. - * - * @param option to add to the current one. - */ - @Override - void add( IAEItemStack option ); + /** + * create a AE Item clone + * + * @return the copy + */ + @Override + IAEItemStack copy(); - /** - * create a AE Item clone - * - * @return the copy - */ - @Override - IAEItemStack copy(); + /** + * quick way to get access to the MC Item Definition. + * + * @return item definition + */ + Item getItem(); - /** - * quick way to get access to the MC Item Definition. - * - * @return item definition - */ - Item getItem(); + /** + * @return the items damage value + */ + int getItemDamage(); - /** - * @return the items damage value - */ - int getItemDamage(); + /** + * Compare the Ore Dictionary ID for this to another item. + */ + boolean sameOre(IAEItemStack is); - /** - * Compare the Ore Dictionary ID for this to another item. - */ - 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); - /** - * 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 ); - - /** - * 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 ); + /** + * 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); } \ 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 4548fe49..4dc697da 100644 --- a/src/api/java/appeng/api/storage/data/IAEStack.java +++ b/src/api/java/appeng/api/storage/data/IAEStack.java @@ -23,179 +23,175 @@ package appeng.api.storage.data; +import java.io.IOException; import appeng.api.config.FuzzyMode; import appeng.api.storage.StorageChannel; import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; -import java.io.IOException; +public interface IAEStack { + /** + * add two stacks together + * + * @param is added item + */ + void add(StackType is); + /** + * number of items in the stack. + * + * @return basically ItemStack.stackSize + */ + long getStackSize(); -public interface IAEStack -{ + /** + * changes the number of items in the stack. + * + * @param stackSize , ItemStack.stackSize = N + */ + StackType setStackSize(long stackSize); - /** - * add two stacks together - * - * @param is added item - */ - void add( StackType is ); + /** + * Same as getStackSize, but for requestable items. ( LP ) + * + * @return basically itemStack.stackSize but for requestable items. + */ + long getCountRequestable(); - /** - * number of items in the stack. - * - * @return basically ItemStack.stackSize - */ - long getStackSize(); + /** + * Same as setStackSize, but for requestable items. ( LP ) + * + * @return basically itemStack.stackSize = N but for setStackSize items. + */ + StackType setCountRequestable(long countRequestable); - /** - * changes the number of items in the stack. - * - * @param stackSize , ItemStack.stackSize = N - */ - StackType setStackSize( long stackSize ); + /** + * true, if the item can be crafted. + * + * @return true, if it can be crafted. + */ + boolean isCraftable(); - /** - * Same as getStackSize, but for requestable items. ( LP ) - * - * @return basically itemStack.stackSize but for requestable items. - */ - long getCountRequestable(); + /** + * change weather the item can be crafted. + * + * @param isCraftable can item be crafted + */ + StackType setCraftable(boolean isCraftable); - /** - * Same as setStackSize, but for requestable items. ( LP ) - * - * @return basically itemStack.stackSize = N but for setStackSize items. - */ - StackType setCountRequestable( long countRequestable ); + /** + * clears, requestable, craftable, and stack sizes. + */ + StackType reset(); - /** - * true, if the item can be crafted. - * - * @return true, if it can be crafted. - */ - boolean isCraftable(); + /** + * returns true, if the item can be crafted, requested, or extracted. + * + * @return isThisRecordMeaningful + */ + boolean isMeaningful(); - /** - * change weather the item can be crafted. - * - * @param isCraftable can item be crafted - */ - StackType setCraftable( boolean isCraftable ); + /** + * Adds more to the stack size... + * + * @param i additional stack size + */ + void incStackSize(long i); - /** - * clears, requestable, craftable, and stack sizes. - */ - StackType reset(); + /** + * removes some from the stack size. + */ + void decStackSize(long i); - /** - * returns true, if the item can be crafted, requested, or extracted. - * - * @return isThisRecordMeaningful - */ - boolean isMeaningful(); + /** + * adds items to the requestable + * + * @param i increased amount of requested items + */ + void incCountRequestable(long i); - /** - * Adds more to the stack size... - * - * @param i additional stack size - */ - void incStackSize( long i ); + /** + * removes items from the requestable + * + * @param i decreased amount of requested items + */ + void decCountRequestable(long i); - /** - * removes some from the stack size. - */ - void decStackSize( long i ); + /** + * write to a NBTTagCompound. + * + * @param i to be written data + */ + void writeToNBT(NBTTagCompound i); - /** - * adds items to the requestable - * - * @param i increased amount of requested items - */ - void incCountRequestable( long i ); + /** + * Compare stacks using precise logic. + *

+ * a IAEItemStack to another AEItemStack or a ItemStack. + *

+ * or + *

+ * IAEFluidStack, FluidStack + * + * @param obj compared object + * @return true if they are the same. + */ + @Override + boolean equals(Object obj); - /** - * removes items from the requestable - * - * @param i decreased amount of requested items - */ - void decCountRequestable( long i ); + /** + * compare stacks using fuzzy logic + *

+ * a IAEItemStack to another AEItemStack or a ItemStack. + * + * @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); - /** - * write to a NBTTagCompound. - * - * @param i to be written data - */ - void writeToNBT( NBTTagCompound i ); + /** + * Slower for disk saving, but smaller/more efficient for packets. + * + * @param data to be written data + * @throws IOException + */ + void writeToPacket(ByteBuf data) throws IOException; - /** - * Compare stacks using precise logic. - *

- * a IAEItemStack to another AEItemStack or a ItemStack. - *

- * or - *

- * IAEFluidStack, FluidStack - * - * @param obj compared object - * @return true if they are the same. - */ - @Override - boolean equals( Object obj ); + /** + * Clone the Item / Fluid Stack + * + * @return a new Stack, which is copied from the original. + */ + StackType copy(); - /** - * compare stacks using fuzzy logic - *

- * a IAEItemStack to another AEItemStack or a ItemStack. - * - * @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 ); + /** + * create an empty stack. + * + * @return a new stack, which represents an empty copy of the original. + */ + StackType empty(); - /** - * Slower for disk saving, but smaller/more efficient for packets. - * - * @param data to be written data - * @throws IOException - */ - void writeToPacket( ByteBuf data ) throws IOException; + /** + * obtain the NBT Data for the item. + * + * @return nbt data + */ + IAETagCompound getTagCompound(); - /** - * Clone the Item / Fluid Stack - * - * @return a new Stack, which is copied from the original. - */ - StackType copy(); + /** + * @return true if the stack is a {@link IAEItemStack} + */ + boolean isItem(); - /** - * create an empty stack. - * - * @return a new stack, which represents an empty copy of the original. - */ - StackType empty(); + /** + * @return true if the stack is a {@link IAEFluidStack} + */ + boolean isFluid(); - /** - * obtain the NBT Data for the item. - * - * @return nbt data - */ - IAETagCompound getTagCompound(); - - /** - * @return true if the stack is a {@link IAEItemStack} - */ - boolean isItem(); - - /** - * @return true if the stack is a {@link IAEFluidStack} - */ - boolean isFluid(); - - /** - * @return ITEM or FLUID - */ - StorageChannel getChannel(); + /** + * @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 64973739..630b6ef8 100644 --- a/src/api/java/appeng/api/storage/data/IAETagCompound.java +++ b/src/api/java/appeng/api/storage/data/IAETagCompound.java @@ -23,35 +23,32 @@ package appeng.api.storage.data; - import appeng.api.features.IItemComparison; import net.minecraft.nbt.NBTTagCompound; - /** * Don't cast this... either compare with it, or copy it. *

* Don't Implement. */ -public interface IAETagCompound -{ +public interface IAETagCompound { + /** + * @return a copy ( the copy will not be a IAETagCompound, it will be a NBTTagCompound + * ) + */ + NBTTagCompound getNBTTagCompoundCopy(); - /** - * @return a copy ( the copy will not be a IAETagCompound, it will be a NBTTagCompound ) - */ - NBTTagCompound getNBTTagCompoundCopy(); + /** + * compare to other NBTTagCompounds or IAETagCompounds + * + * @param a compared object + * @return true, if they are the same. + */ + @Override + boolean equals(Object a); - /** - * compare to other NBTTagCompounds or IAETagCompounds - * - * @param a compared object - * @return true, if they are the same. - */ - @Override - boolean equals( Object a ); - - /** - * @return the special comparison for this tag - */ - IItemComparison getSpecialComparison(); + /** + * @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 b47c3a37..f6df35d2 100644 --- a/src/api/java/appeng/api/storage/data/IItemContainer.java +++ b/src/api/java/appeng/api/storage/data/IItemContainer.java @@ -23,11 +23,9 @@ package appeng.api.storage.data; - -import appeng.api.config.FuzzyMode; - import java.util.Collection; +import appeng.api.config.FuzzyMode; /** * Represents a list of items in AE. @@ -36,31 +34,31 @@ import java.util.Collection; *

* Construct with Util.createItemList() */ -public interface IItemContainer -{ +public interface IItemContainer { + /** + * add a stack to the list, this will merge the stack with an item already in the list + * if found. + * + * @param option added stack + */ + void add(StackType option); // adds stack as is - /** - * add a stack to the list, this will merge the stack with an item already in the list if found. - * - * @param option added stack - */ - void add( StackType option ); // adds stack as is + /** + * @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 + */ + StackType findPrecise(StackType i); - /** - * @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 - */ - StackType findPrecise( StackType i ); + /** + * @param input compared item + * @return a list of relevant fuzzy matched stacks + */ + Collection findFuzzy(StackType input, FuzzyMode fuzzy); - /** - * @param input compared item - * @return a list of relevant fuzzy matched stacks - */ - Collection findFuzzy( StackType input, FuzzyMode fuzzy ); - - /** - * @return true if there are no items in the list - */ - boolean isEmpty(); + /** + * @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 2a07c11c..d2d694de 100644 --- a/src/api/java/appeng/api/storage/data/IItemList.java +++ b/src/api/java/appeng/api/storage/data/IItemList.java @@ -23,10 +23,8 @@ package appeng.api.storage.data; - import java.util.Iterator; - /** * Represents a list of items in AE. *

@@ -34,50 +32,50 @@ import java.util.Iterator; *

* Construct with Util.createItemList() */ -public interface IItemList extends IItemContainer, Iterable -{ +public interface IItemList + extends IItemContainer, Iterable { + /** + * add a stack to the list stackSize is used to add to stackSize, this will merge the + * stack with an item already in the list if found. + * + * @param option stacktype option + */ + void addStorage(StackType option); // adds a stack as stored - /** - * add a stack to the list stackSize is used to add to stackSize, this will merge the stack with an item already in - * the list if found. - * - * @param option stacktype option - */ - void addStorage( StackType option ); // adds a stack as stored + /** + * add a stack to the list as craftable, this will merge the stack with an item + * already in the list if found. + * + * @param option stacktype option + */ + void addCrafting(StackType option); - /** - * add a stack to the list as craftable, this will merge the stack with an item already in the list if found. - * - * @param option stacktype option - */ - void addCrafting( StackType option ); + /** + * add a stack to the list, stack size is used to add to requestable, this will merge + * the stack with an item already in the list if found. + * + * @param option stacktype option + */ + void addRequestable(StackType option); // adds a stack as requestable - /** - * add a stack to the list, stack size is used to add to requestable, this will merge the stack with an item already - * in the list if found. - * - * @param option stacktype option - */ - void addRequestable( StackType option ); // adds a stack as requestable + /** + * @return the first item in the list + */ + StackType getFirstItem(); - /** - * @return the first item in the list - */ - StackType getFirstItem(); + /** + * @return the number of items in the list + */ + int size(); - /** - * @return the number of items in the list - */ - int size(); + /** + * allows you to iterate the list. + */ + @Override + Iterator iterator(); - /** - * allows you to iterate the list. - */ - @Override - Iterator iterator(); - - /** - * resets stack sizes to 0. - */ - void resetStatus(); + /** + * resets stack sizes to 0. + */ + void resetStatus(); } \ No newline at end of file diff --git a/src/api/java/appeng/api/util/AECableType.java b/src/api/java/appeng/api/util/AECableType.java index 5d6f3464..239fd66a 100644 --- a/src/api/java/appeng/api/util/AECableType.java +++ b/src/api/java/appeng/api/util/AECableType.java @@ -23,32 +23,30 @@ package appeng.api.util; +public enum AECableType { + /** + * No Cable present. + */ + NONE, -public enum AECableType -{ - /** - * No Cable present. - */ - NONE, + /** + * Connections to this block should render as glass. + */ + GLASS, - /** - * Connections to this block should render as glass. - */ - GLASS, + /** + * Connections to this block should render as covered. + */ + COVERED, - /** - * Connections to this block should render as covered. - */ - COVERED, + /** + * Connections to this block should render as smart. + */ + SMART, - /** - * Connections to this block should render as smart. - */ - SMART, - - /** - * Dense Cable, represents a tier 2 block that can carry 32 channels. - */ - DENSE, + /** + * Dense Cable, represents a tier 2 block that can carry 32 channels. + */ + DENSE, } diff --git a/src/api/java/appeng/api/util/AEColor.java b/src/api/java/appeng/api/util/AEColor.java index 0b0fc276..a3b87107 100644 --- a/src/api/java/appeng/api/util/AEColor.java +++ b/src/api/java/appeng/api/util/AEColor.java @@ -23,97 +23,112 @@ package appeng.api.util; - -import net.minecraft.util.StatCollector; - import java.util.Arrays; import java.util.List; +import net.minecraft.util.StatCollector; /** * List of all colors supported by AE, their names, and various colors for display. *

* Should be the same order as Dyes, excluding Transparent. */ -public enum AEColor -{ +public enum AEColor { + White("gui.appliedenergistics2.White", 0xBEBEBE, 0xDBDBDB, 0xFAFAFA), - White( "gui.appliedenergistics2.White", 0xBEBEBE, 0xDBDBDB, 0xFAFAFA ), + Orange("gui.appliedenergistics2.Orange", 0xF99739, 0xFAAE44, 0xF4DEC3), - Orange( "gui.appliedenergistics2.Orange", 0xF99739, 0xFAAE44, 0xF4DEC3 ), + Magenta("gui.appliedenergistics2.Magenta", 0x821E82, 0xB82AB8, 0xC598C8), - Magenta( "gui.appliedenergistics2.Magenta", 0x821E82, 0xB82AB8, 0xC598C8 ), + LightBlue("gui.appliedenergistics2.LightBlue", 0x628DCB, 0x82ACE7, 0xD8F6FF), - LightBlue( "gui.appliedenergistics2.LightBlue", 0x628DCB, 0x82ACE7, 0xD8F6FF ), + Yellow("gui.appliedenergistics2.Yellow", 0xFFF7AA, 0xF8FF4A, 0xFFFFE8), - Yellow( "gui.appliedenergistics2.Yellow", 0xFFF7AA, 0xF8FF4A, 0xFFFFE8 ), + Lime("gui.appliedenergistics2.Lime", 0x7CFF4A, 0xBBFF51, 0xE7F7D7), - Lime( "gui.appliedenergistics2.Lime", 0x7CFF4A, 0xBBFF51, 0xE7F7D7 ), + Pink("gui.appliedenergistics2.Pink", 0xDC8DB5, 0xF8B5D7, 0xF7DEEB), - Pink( "gui.appliedenergistics2.Pink", 0xDC8DB5, 0xF8B5D7, 0xF7DEEB ), + Gray("gui.appliedenergistics2.Gray", 0x7C7C7C, 0xA0A0A0, 0xC9C9C9), - Gray( "gui.appliedenergistics2.Gray", 0x7C7C7C, 0xA0A0A0, 0xC9C9C9 ), + LightGray("gui.appliedenergistics2.LightGray", 0x9D9D9D, 0xCDCDCD, 0xEFEFEF), - LightGray( "gui.appliedenergistics2.LightGray", 0x9D9D9D, 0xCDCDCD, 0xEFEFEF ), + Cyan("gui.appliedenergistics2.Cyan", 0x2F9BA5, 0x51AAC6, 0xAEDDF4), - Cyan( "gui.appliedenergistics2.Cyan", 0x2F9BA5, 0x51AAC6, 0xAEDDF4 ), + Purple("gui.appliedenergistics2.Purple", 0x8230B2, 0xA453CE, 0xC7A3CC), - Purple( "gui.appliedenergistics2.Purple", 0x8230B2, 0xA453CE, 0xC7A3CC ), + Blue("gui.appliedenergistics2.Blue", 0x2D29A0, 0x514AFF, 0xDDE6FF), - Blue( "gui.appliedenergistics2.Blue", 0x2D29A0, 0x514AFF, 0xDDE6FF ), + Brown("gui.appliedenergistics2.Brown", 0x724E35, 0xB7967F, 0xE0D2C8), - Brown( "gui.appliedenergistics2.Brown", 0x724E35, 0xB7967F, 0xE0D2C8 ), + Green("gui.appliedenergistics2.Green", 0x45A021, 0x60E32E, 0xE3F2E3), - Green( "gui.appliedenergistics2.Green", 0x45A021, 0x60E32E, 0xE3F2E3 ), + Red("gui.appliedenergistics2.Red", 0xA50029, 0xFF003C, 0xFFE6ED), - Red( "gui.appliedenergistics2.Red", 0xA50029, 0xFF003C, 0xFFE6ED ), + Black("gui.appliedenergistics2.Black", 0x2B2B2B, 0x565656, 0x848484), - Black( "gui.appliedenergistics2.Black", 0x2B2B2B, 0x565656, 0x848484 ), + Transparent("gui.appliedenergistics2.Fluix", 0x1B2344, 0x895CA8, 0xD7BBEC); - Transparent( "gui.appliedenergistics2.Fluix", 0x1B2344, 0x895CA8, 0xD7BBEC ); + public static final List VALID_COLORS = Arrays.asList( + White, + Orange, + Magenta, + LightBlue, + Yellow, + Lime, + Pink, + Gray, + LightGray, + Cyan, + Purple, + Blue, + Brown, + Green, + Red, + Black + ); - public static final List VALID_COLORS = Arrays.asList( White, Orange, Magenta, LightBlue, Yellow, Lime, Pink, Gray, LightGray, Cyan, Purple, Blue, Brown, Green, Red, Black ); + /** + * Unlocalized name for color. + */ + public final String unlocalizedName; - /** - * Unlocalized name for color. - */ - public final String unlocalizedName; + /** + * Darkest Variant of the color, nearly black; as a RGB HEX Integer + */ + public final int blackVariant; - /** - * Darkest Variant of the color, nearly black; as a RGB HEX Integer - */ - public final int blackVariant; + /** + * The Variant of the color that is used to represent the color normally; as a RGB HEX + * Integer + */ + public final int mediumVariant; - /** - * The Variant of the color that is used to represent the color normally; as a RGB HEX Integer - */ - public final int mediumVariant; + /** + * Lightest Variant of the color, nearly white; as a RGB HEX Integer + */ + public final int whiteVariant; - /** - * Lightest Variant of the color, nearly white; as a RGB HEX Integer - */ - public final int whiteVariant; + AEColor( + final String unlocalizedName, + final int blackHex, + final int medHex, + final int whiteHex + ) { + this.unlocalizedName = unlocalizedName; + this.blackVariant = blackHex; + this.mediumVariant = medHex; + this.whiteVariant = whiteHex; + } - AEColor( final String unlocalizedName, final int blackHex, final int medHex, final int whiteHex ) - { - this.unlocalizedName = unlocalizedName; - this.blackVariant = blackHex; - this.mediumVariant = medHex; - this.whiteVariant = whiteHex; - } - - /** - * Logic to see which colors match each other.. special handle for Transparent - */ - public boolean matches( final AEColor color ) - { - return this == Transparent || color == Transparent || this == color; - } - - @Override - public String toString() - { - return StatCollector.translateToLocal( this.unlocalizedName ); - } + /** + * Logic to see which colors match each other.. special handle for Transparent + */ + public boolean matches(final AEColor color) { + return this == Transparent || color == Transparent || this == color; + } + @Override + public String toString() { + return StatCollector.translateToLocal(this.unlocalizedName); + } } diff --git a/src/api/java/appeng/api/util/AEColoredItemDefinition.java b/src/api/java/appeng/api/util/AEColoredItemDefinition.java index 331adca1..68eab8f2 100644 --- a/src/api/java/appeng/api/util/AEColoredItemDefinition.java +++ b/src/api/java/appeng/api/util/AEColoredItemDefinition.java @@ -23,48 +23,44 @@ package appeng.api.util; - import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public interface AEColoredItemDefinition { + /** + * @return the {@link Block} Implementation if applicable + */ + Block block(AEColor color); -public interface AEColoredItemDefinition -{ + /** + * @return the {@link Item} Implementation if applicable + */ + Item item(AEColor color); - /** - * @return the {@link Block} Implementation if applicable - */ - Block block( AEColor color ); + /** + * @return the {@link TileEntity} Class if applicable. + */ + Class entity(AEColor color); - /** - * @return the {@link Item} Implementation if applicable - */ - Item item( AEColor color ); + /** + * @return an {@link ItemStack} with specified quantity of this item. + */ + ItemStack stack(AEColor color, int stackSize); - /** - * @return the {@link TileEntity} Class if applicable. - */ - Class entity( AEColor color ); + /** + * @param stackSize - stack size of the result. + * @return an array of all colors. + */ + ItemStack[] allStacks(int stackSize); - /** - * @return an {@link ItemStack} with specified quantity of this item. - */ - ItemStack stack( AEColor color, int stackSize ); - - /** - * @param stackSize - stack size of the result. - * @return an array of all colors. - */ - ItemStack[] allStacks( int stackSize ); - - /** - * Compare {@link ItemStack} with this - * - * @param color compared color of item - * @param comparableItem compared item - * @return true if the item stack is a matching item. - */ - boolean sameAs( AEColor color, ItemStack comparableItem ); + /** + * Compare {@link ItemStack} with this + * + * @param color compared color of item + * @param comparableItem compared item + * @return true if the item stack is a matching item. + */ + boolean sameAs(AEColor color, ItemStack comparableItem); } diff --git a/src/api/java/appeng/api/util/AEItemDefinition.java b/src/api/java/appeng/api/util/AEItemDefinition.java index 1db0adf3..39a867b6 100644 --- a/src/api/java/appeng/api/util/AEItemDefinition.java +++ b/src/api/java/appeng/api/util/AEItemDefinition.java @@ -23,6 +23,7 @@ package appeng.api.util; +import javax.annotation.Nullable; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IComparableDefinition; @@ -34,69 +35,66 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; -import javax.annotation.Nullable; - - /** * Gives easy access to different part of the various, items/blocks/materials in AE. * * @deprecated use {@link ITileDefinition} and its sub-classes */ @Deprecated -public interface AEItemDefinition -{ - /** - * @return the {@link Block} Implementation if applicable - * @deprecated use {@link IBlockDefinition#maybeBlock()} - */ - @Deprecated - @Nullable - Block block(); +public interface AEItemDefinition { + /** + * @return the {@link Block} Implementation if applicable + * @deprecated use {@link IBlockDefinition#maybeBlock()} + */ + @Deprecated + @Nullable + Block block(); - /** - * @return the {@link Item} Implementation if applicable - * @deprecated use {@link IItemDefinition#maybeItem()} - */ - @Deprecated - @Nullable - Item item(); + /** + * @return the {@link Item} Implementation if applicable + * @deprecated use {@link IItemDefinition#maybeItem()} + */ + @Deprecated + @Nullable + Item item(); - /** - * @return the {@link TileEntity} Class if applicable. - * @deprecated use {@link ITileDefinition#maybeEntity()} - */ - @Deprecated - @Nullable - Class entity(); + /** + * @return the {@link TileEntity} Class if applicable. + * @deprecated use {@link ITileDefinition#maybeEntity()} + */ + @Deprecated + @Nullable + Class entity(); - /** - * @return an {@link ItemStack} with specified quantity of this item. - * @deprecated use {@link IItemDefinition#maybeStack(int)} - */ - @Deprecated - @Nullable - ItemStack stack( int stackSize ); + /** + * @return an {@link ItemStack} with specified quantity of this item. + * @deprecated use {@link IItemDefinition#maybeStack(int)} + */ + @Deprecated + @Nullable + ItemStack stack(int stackSize); - /** - * Compare {@link ItemStack} with this - * - * @param comparableItem compared item - * @return true if the item stack is a matching item. - * @deprecated use {@link IComparableDefinition#isSameAs(ItemStack)} - */ - @Deprecated - boolean sameAsStack( ItemStack comparableItem ); + /** + * Compare {@link ItemStack} with this + * + * @param comparableItem compared item + * @return true if the item stack is a matching item. + * @deprecated use {@link IComparableDefinition#isSameAs(ItemStack)} + */ + @Deprecated + boolean sameAsStack(ItemStack comparableItem); - /** - * 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 - * @return if the block is placed in the world at the specific location. - * @deprecated use {@link IComparableDefinition#isSameAs(IBlockAccess, int, int, int)} } - */ - @Deprecated - boolean sameAsBlock( IBlockAccess world, int x, int y, int z ); + /** + * 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 + * @return if the block is placed in the world at the specific location. + * @deprecated use {@link IComparableDefinition#isSameAs(IBlockAccess, int, int, int)} + * } + */ + @Deprecated + boolean sameAsBlock(IBlockAccess world, int x, int y, int z); } diff --git a/src/api/java/appeng/api/util/DimensionalCoord.java b/src/api/java/appeng/api/util/DimensionalCoord.java index 8099a773..c831bd9e 100644 --- a/src/api/java/appeng/api/util/DimensionalCoord.java +++ b/src/api/java/appeng/api/util/DimensionalCoord.java @@ -23,77 +23,63 @@ package appeng.api.util; - import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; - /** * Represents a location in the Minecraft Universe */ -public class DimensionalCoord extends WorldCoord -{ +public class DimensionalCoord extends WorldCoord { + private final World w; + private final int dimId; - private final World w; - private final int dimId; + public DimensionalCoord(final DimensionalCoord s) { + super(s.x, s.y, s.z); + this.w = s.w; + this.dimId = s.dimId; + } - public DimensionalCoord( final DimensionalCoord s ) - { - super( s.x, s.y, s.z ); - this.w = s.w; - this.dimId = s.dimId; - } + public DimensionalCoord(final TileEntity s) { + super(s); + this.w = s.getWorldObj(); + this.dimId = this.w.provider.dimensionId; + } - public DimensionalCoord( final TileEntity s ) - { - super( s ); - this.w = s.getWorldObj(); - this.dimId = this.w.provider.dimensionId; - } + public DimensionalCoord(final World _w, final int _x, final int _y, final int _z) { + super(_x, _y, _z); + this.w = _w; + this.dimId = _w.provider.dimensionId; + } - public DimensionalCoord( final World _w, final int _x, final int _y, final int _z ) - { - super( _x, _y, _z ); - this.w = _w; - this.dimId = _w.provider.dimensionId; - } + @Override + public DimensionalCoord copy() { + return new DimensionalCoord(this); + } - @Override - public DimensionalCoord copy() - { - return new DimensionalCoord( this ); - } + @Override + public int hashCode() { + return super.hashCode() ^ this.dimId; + } - @Override - public int hashCode() - { - return super.hashCode() ^ this.dimId; - } + @Override + public boolean equals(final Object obj) { + return obj instanceof DimensionalCoord && this.isEqual((DimensionalCoord) obj); + } - @Override - public boolean equals( final Object obj ) - { - return obj instanceof DimensionalCoord && this.isEqual( (DimensionalCoord) obj ); - } + public boolean isEqual(final DimensionalCoord c) { + return this.x == c.x && this.y == c.y && this.z == c.z && c.w == this.w; + } - public boolean isEqual( final DimensionalCoord c ) - { - return this.x == c.x && this.y == c.y && this.z == c.z && c.w == this.w; - } + @Override + public String toString() { + return "dimension=" + this.dimId + ", " + super.toString(); + } - @Override - public String toString() - { - return "dimension=" + this.dimId + ", " + super.toString(); - } + public boolean isInWorld(final World world) { + return this.w == world; + } - public boolean isInWorld( final World world ) - { - return this.w == world; - } - - public World getWorld() - { - return this.w; - } + public World getWorld() { + return this.w; + } } diff --git a/src/api/java/appeng/api/util/ICommonTile.java b/src/api/java/appeng/api/util/ICommonTile.java index 6465e57d..c424caed 100644 --- a/src/api/java/appeng/api/util/ICommonTile.java +++ b/src/api/java/appeng/api/util/ICommonTile.java @@ -23,25 +23,21 @@ package appeng.api.util; +import java.util.List; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import java.util.List; - - -public interface ICommonTile -{ - - /** - * implemented on AE's Tile Entities, Gets a list of drops that the entity will normally drop, this doesn't include - * the block itself. - * - * @param world world of tile entity - * @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 - */ - void getDrops( World world, int x, int y, int z, List drops ); +public interface ICommonTile { + /** + * implemented on AE's Tile Entities, Gets a list of drops that the entity will + * normally drop, this doesn't include the block itself. + * + * @param world world of tile entity + * @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 + */ + void getDrops(World world, int x, int y, int z, List drops); } \ No newline at end of file diff --git a/src/api/java/appeng/api/util/IConfigManager.java b/src/api/java/appeng/api/util/IConfigManager.java index 553b1982..b532be7e 100644 --- a/src/api/java/appeng/api/util/IConfigManager.java +++ b/src/api/java/appeng/api/util/IConfigManager.java @@ -23,64 +23,60 @@ package appeng.api.util; +import java.util.Set; import appeng.api.config.Settings; import net.minecraft.nbt.NBTTagCompound; -import java.util.Set; - - /** * Used to adjust settings on an object, *

* Obtained via {@link IConfigurableObject} */ -public interface IConfigManager -{ +public interface IConfigManager { + /** + * get a list of different settings + * + * @return enum set of settings + */ + Set getSettings(); - /** - * get a list of different settings - * - * @return enum set of settings - */ - Set getSettings(); + /** + * used to initialize the configuration manager, should be called for all settings. + * + * @param settingName name of setting + * @param defaultValue default value of setting + */ + void registerSetting(Settings settingName, Enum defaultValue); - /** - * used to initialize the configuration manager, should be called for all settings. - * - * @param settingName name of setting - * @param defaultValue default value of setting - */ - 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); - /** - * Get Value of a particular setting - * - * @param settingName name of setting - * @return value of setting - */ - Enum getSetting( Settings settingName ); + /** + * Change setting + * + * @param settingName to be changed setting + * @param newValue new value for setting + * @return changed setting + */ + Enum putSetting(Settings settingName, Enum newValue); - /** - * Change setting - * - * @param settingName to be changed setting - * @param newValue new value for setting - * @return changed setting - */ - 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); - /** - * write all settings to the NBT Tag so they can be read later. - * - * @param destination to be written nbt tag - */ - void writeToNBT( NBTTagCompound destination ); - - /** - * Only works after settings have been registered - * - * @param src to be read nbt tag - */ - void readFromNBT( NBTTagCompound src ); + /** + * Only works after settings have been registered + * + * @param src to be read nbt tag + */ + void readFromNBT(NBTTagCompound src); } diff --git a/src/api/java/appeng/api/util/IConfigurableObject.java b/src/api/java/appeng/api/util/IConfigurableObject.java index e25e7403..47e88879 100644 --- a/src/api/java/appeng/api/util/IConfigurableObject.java +++ b/src/api/java/appeng/api/util/IConfigurableObject.java @@ -23,15 +23,12 @@ package appeng.api.util; - /** * Implemented by various Tiles or Parts in AE */ -public interface IConfigurableObject -{ - - /** - * get the config manager for the object. - */ - IConfigManager getConfigManager(); +public interface IConfigurableObject { + /** + * get the config manager for the object. + */ + IConfigManager getConfigManager(); } diff --git a/src/api/java/appeng/api/util/INetworkToolAgent.java b/src/api/java/appeng/api/util/INetworkToolAgent.java index 915df02c..7f48b18d 100644 --- a/src/api/java/appeng/api/util/INetworkToolAgent.java +++ b/src/api/java/appeng/api/util/INetworkToolAgent.java @@ -23,15 +23,12 @@ package appeng.api.util; - import net.minecraft.util.MovingObjectPosition; - /** - * Implement on Tile or part to customize if the info gui opens, or an action is preformed. + * Implement on Tile or part to customize if the info gui opens, or an action is + * preformed. */ -public interface INetworkToolAgent -{ - - boolean showNetworkInfo( MovingObjectPosition where ); +public interface INetworkToolAgent { + boolean showNetworkInfo(MovingObjectPosition where); } diff --git a/src/api/java/appeng/api/util/IOrientable.java b/src/api/java/appeng/api/util/IOrientable.java index fa53913c..1b5dbc51 100644 --- a/src/api/java/appeng/api/util/IOrientable.java +++ b/src/api/java/appeng/api/util/IOrientable.java @@ -23,40 +23,35 @@ package appeng.api.util; - import net.minecraftforge.common.util.ForgeDirection; - /** * Nearly all of AE's Tile Entities implement IOrientable. *

- * and it can be used to manipulate the direction of some machines, most of these orientations are purely visual. - *

- * AE also responds to Block.rotateBlock + * and it can be used to manipulate the direction of some machines, most of these + * orientations are purely visual.

AE also responds to Block.rotateBlock */ -public interface IOrientable -{ +public interface IOrientable { + /** + * @return true or false, if the tile rotation is meaningful, or even changeable + */ + boolean canBeRotated(); - /** - * @return true or false, if the tile rotation is meaningful, or even changeable - */ - boolean canBeRotated(); + /** + * @return the direction the tile is facing + */ + ForgeDirection getForward(); - /** - * @return the direction the tile is facing - */ - ForgeDirection getForward(); + /** + * @return the direction top of the tile + */ + ForgeDirection getUp(); - /** - * @return the direction top of the tile - */ - ForgeDirection getUp(); - - /** - * Update the orientation - * - * @param Forward new forward direction - * @param Up new upwards direction - */ - void setOrientation( ForgeDirection Forward, ForgeDirection Up ); + /** + * Update the orientation + * + * @param Forward new forward direction + * @param Up new upwards direction + */ + void setOrientation(ForgeDirection Forward, ForgeDirection Up); } \ No newline at end of file diff --git a/src/api/java/appeng/api/util/IOrientableBlock.java b/src/api/java/appeng/api/util/IOrientableBlock.java index dea99d14..1e7fcf6e 100644 --- a/src/api/java/appeng/api/util/IOrientableBlock.java +++ b/src/api/java/appeng/api/util/IOrientableBlock.java @@ -23,27 +23,23 @@ package appeng.api.util; - import net.minecraft.world.IBlockAccess; - /** * Implemented on many of AE's non Tile Entity Blocks as a way to get a IOrientable. */ -public interface IOrientableBlock -{ +public interface IOrientableBlock { + /** + * @return if this block uses metadata to store its rotation. + */ + boolean usesMetadata(); - /** - * @return if this block uses metadata to store its rotation. - */ - boolean usesMetadata(); - - /** - * @param world world of block - * @param x x pos of block - * @param y y pos of block - * @param z z pos of block - * @return a IOrientable if applicable - */ - IOrientable getOrientable( IBlockAccess world, int x, int y, int z ); + /** + * @param world world of block + * @param x x pos of block + * @param y y pos of block + * @param z z pos of block + * @return a IOrientable if applicable + */ + IOrientable getOrientable(IBlockAccess world, int x, int y, int z); } \ No newline at end of file diff --git a/src/api/java/appeng/api/util/IReadOnlyCollection.java b/src/api/java/appeng/api/util/IReadOnlyCollection.java index 84e042ae..a2324829 100644 --- a/src/api/java/appeng/api/util/IReadOnlyCollection.java +++ b/src/api/java/appeng/api/util/IReadOnlyCollection.java @@ -23,22 +23,19 @@ package appeng.api.util; +public interface IReadOnlyCollection extends Iterable { + /** + * @return the objects in in the set. + */ + int size(); -public interface IReadOnlyCollection extends Iterable -{ + /** + * @return true if there are objects in the set + */ + boolean isEmpty(); - /** - * @return the objects in in the set. - */ - int size(); - - /** - * @return true if there are objects in the set - */ - boolean isEmpty(); - - /** - * @return return true if the object is part of the set. - */ - boolean contains( Object node ); + /** + * @return return true if the object is part of the set. + */ + boolean contains(Object node); } diff --git a/src/api/java/appeng/api/util/WorldCoord.java b/src/api/java/appeng/api/util/WorldCoord.java index 2e09d1dd..957d5587 100644 --- a/src/api/java/appeng/api/util/WorldCoord.java +++ b/src/api/java/appeng/api/util/WorldCoord.java @@ -23,153 +23,129 @@ package appeng.api.util; - import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - /** * Represents a relative coordinate, either relative to another object, or * relative to the origin of a dimension. */ -public class WorldCoord -{ +public class WorldCoord { + public int x; + public int y; + public int z; - public int x; - public int y; - public int z; + public WorldCoord(final TileEntity s) { + this(s.xCoord, s.yCoord, s.zCoord); + } - public WorldCoord( final TileEntity s ) - { - this( s.xCoord, s.yCoord, s.zCoord ); - } + public WorldCoord(final int _x, final int _y, final int _z) { + this.x = _x; + this.y = _y; + this.z = _z; + } - public WorldCoord( final int _x, final int _y, final int _z ) - { - this.x = _x; - this.y = _y; - this.z = _z; - } + public WorldCoord subtract(final ForgeDirection direction, final int length) { + this.x -= direction.offsetX * length; + this.y -= direction.offsetY * length; + this.z -= direction.offsetZ * length; + return this; + } - public WorldCoord subtract( final ForgeDirection direction, final int length ) - { - this.x -= direction.offsetX * length; - this.y -= direction.offsetY * length; - this.z -= direction.offsetZ * length; - return this; - } + public WorldCoord add(final int _x, final int _y, final int _z) { + this.x += _x; + this.y += _y; + this.z += _z; + return this; + } - public WorldCoord add( final int _x, final int _y, final int _z ) - { - this.x += _x; - this.y += _y; - this.z += _z; - return this; - } + public WorldCoord subtract(final int _x, final int _y, final int _z) { + this.x -= _x; + this.y -= _y; + this.z -= _z; + return this; + } - public WorldCoord subtract( final int _x, final int _y, final int _z ) - { - this.x -= _x; - this.y -= _y; - this.z -= _z; - return this; - } + public WorldCoord multiple(final int _x, final int _y, final int _z) { + this.x *= _x; + this.y *= _y; + this.z *= _z; + return this; + } - public WorldCoord multiple( final int _x, final int _y, final int _z ) - { - this.x *= _x; - this.y *= _y; - this.z *= _z; - return this; - } + public WorldCoord divide(final int _x, final int _y, final int _z) { + this.x /= _x; + this.y /= _y; + this.z /= _z; + return this; + } - public WorldCoord divide( final int _x, final int _y, final int _z ) - { - this.x /= _x; - this.y /= _y; - this.z /= _z; - return this; - } + /** + * Will Return NULL if it's at some diagonal! + */ + public ForgeDirection directionTo(final WorldCoord loc) { + final int ox = this.x - loc.x; + final int oy = this.y - loc.y; + final int oz = this.z - loc.z; - /** - * Will Return NULL if it's at some diagonal! - */ - public ForgeDirection directionTo( final WorldCoord loc ) - { - final int ox = this.x - loc.x; - final int oy = this.y - loc.y; - final int oz = this.z - loc.z; + final int xlen = Math.abs(ox); + final int ylen = Math.abs(oy); + final int zlen = Math.abs(oz); - final int xlen = Math.abs( ox ); - final int ylen = Math.abs( oy ); - final int zlen = Math.abs( oz ); + if (loc.isEqual(this.copy().add(ForgeDirection.EAST, xlen))) { + return ForgeDirection.EAST; + } - if( loc.isEqual( this.copy().add( ForgeDirection.EAST, xlen ) ) ) - { - return ForgeDirection.EAST; - } + if (loc.isEqual(this.copy().add(ForgeDirection.WEST, xlen))) { + return ForgeDirection.WEST; + } - if( loc.isEqual( this.copy().add( ForgeDirection.WEST, xlen ) ) ) - { - return ForgeDirection.WEST; - } + if (loc.isEqual(this.copy().add(ForgeDirection.NORTH, zlen))) { + return ForgeDirection.NORTH; + } - if( loc.isEqual( this.copy().add( ForgeDirection.NORTH, zlen ) ) ) - { - return ForgeDirection.NORTH; - } + if (loc.isEqual(this.copy().add(ForgeDirection.SOUTH, zlen))) { + return ForgeDirection.SOUTH; + } - if( loc.isEqual( this.copy().add( ForgeDirection.SOUTH, zlen ) ) ) - { - return ForgeDirection.SOUTH; - } + if (loc.isEqual(this.copy().add(ForgeDirection.UP, ylen))) { + return ForgeDirection.UP; + } - if( loc.isEqual( this.copy().add( ForgeDirection.UP, ylen ) ) ) - { - return ForgeDirection.UP; - } + if (loc.isEqual(this.copy().add(ForgeDirection.DOWN, ylen))) { + return ForgeDirection.DOWN; + } - if( loc.isEqual( this.copy().add( ForgeDirection.DOWN, ylen ) ) ) - { - return ForgeDirection.DOWN; - } + return null; + } - return null; - } + public boolean isEqual(final WorldCoord c) { + return this.x == c.x && this.y == c.y && this.z == c.z; + } - public boolean isEqual( final WorldCoord c ) - { - return this.x == c.x && this.y == c.y && this.z == c.z; - } + public WorldCoord add(final ForgeDirection direction, final int length) { + this.x += direction.offsetX * length; + this.y += direction.offsetY * length; + this.z += direction.offsetZ * length; + return this; + } - public WorldCoord add( final ForgeDirection direction, final 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); + } - 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 int hashCode() - { - return ( this.y << 24 ) ^ this.x ^ this.z; - } + @Override + public boolean equals(final Object obj) { + return obj instanceof WorldCoord && this.isEqual((WorldCoord) obj); + } - @Override - public boolean equals( final Object obj ) - { - return obj instanceof WorldCoord && this.isEqual( (WorldCoord) obj ); - } - - @Override - public String toString() - { - return "x=" + this.x + ", y=" + this.y + ", z=" + this.z; - } + @Override + public String toString() { + return "x=" + this.x + ", y=" + this.y + ", z=" + this.z; + } } diff --git a/src/main/java/appeng/block/AEBaseBlock.java b/src/main/java/appeng/block/AEBaseBlock.java index 3b0e55fb..d66d665e 100644 --- a/src/main/java/appeng/block/AEBaseBlock.java +++ b/src/main/java/appeng/block/AEBaseBlock.java @@ -18,6 +18,9 @@ package appeng.block; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; @@ -50,564 +53,564 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; - - -public abstract class AEBaseBlock extends Block implements IAEFeature -{ - private final String featureFullName; - protected final Optional featureSubName; - protected boolean isOpaque = true; - protected boolean isFullSize = true; - protected boolean hasSubtypes = false; - protected boolean isInventory = false; - private IFeatureHandler handler; - @SideOnly( Side.CLIENT ) - private BlockRenderInfo renderInfo; - - protected AEBaseBlock( final Material mat ) - { - this( mat, Optional.absent() ); - this.setLightOpacity( 255 ); - this.setLightLevel( 0 ); - this.setHardness( 2.2F ); - this.setHarvestLevel( "pickaxe", 0 ); - } - - protected AEBaseBlock( final Material mat, final Optional subName ) - { - super( mat ); - - if( mat == AEGlassMaterial.INSTANCE || mat == Material.glass ) - { - this.setStepSound( Block.soundTypeGlass ); - } - else if( mat == Material.rock ) - { - this.setStepSound( Block.soundTypeStone ); - } - else if( mat == Material.wood ) - { - this.setStepSound( Block.soundTypeWood ); - } - else - { - this.setStepSound( Block.soundTypeMetal ); - } - - this.featureFullName = new FeatureNameExtractor( this.getClass(), subName ).get(); - this.featureSubName = subName; - } - - @Override - public String toString() - { - return this.featureFullName; - } - - public void registerNoIcons() - { - final BlockRenderInfo info = this.getRendererInstance(); - final FlippableIcon i = new FlippableIcon( new MissingIcon( this ) ); - info.updateIcons( i, i, i, i, i, i ); - } - - @SideOnly( Side.CLIENT ) - public BlockRenderInfo getRendererInstance() - { - if( this.renderInfo != null ) - { - return this.renderInfo; - } - - final BaseBlockRender renderer = this.getRenderer(); - this.renderInfo = new BlockRenderInfo( renderer ); - - return this.renderInfo; - } - - /** - * Factory method to create a new render instance. - * - * @return the newly created instance. - */ - @SideOnly( Side.CLIENT ) - protected BaseBlockRender getRenderer() - { - return new BaseBlockRender(); - } - - IIcon unmappedGetIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return super.getIcon( w, x, y, z, s ); - } - - protected void setFeature( final EnumSet f ) - { - final AEBlockFeatureHandler featureHandler = new AEBlockFeatureHandler( f, this, this.featureSubName ); - this.setHandler( featureHandler ); - } - - @Override - public final IFeatureHandler handler() - { - return this.handler; - } - - protected final void setHandler( final IFeatureHandler handler ) - { - this.handler = handler; - } - - @Override - public void postInit() - { - // override! - } - - public boolean isOpaque() - { - return this.isOpaque; - } - - @Override - public boolean renderAsNormalBlock() - { - return this.isFullSize && this.isOpaque; - } - - @Override - @SideOnly( Side.CLIENT ) - public int getRenderType() - { - return WorldRender.INSTANCE.getRenderId(); - } - - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return this.getIcon( this.mapRotation( w, x, y, z, s ), w.getBlockMetadata( x, y, z ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final int metadata ) - { - return this.getRendererInstance().getTexture( ForgeDirection.getOrientation( direction ) ); - } - - protected ICustomCollision getCustomCollision( final World w, final int x, final int y, final int z ) - { - if( this instanceof ICustomCollision ) - { - return (ICustomCollision) this; - } - return null; - } - - @Override - @SuppressWarnings( "unchecked" ) - // NOTE: WAS FINAL, changed for Immibis - public void addCollisionBoxesToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, x, y, z ); - - if( collisionHandler != null && bb != null ) - { - final List tmp = new ArrayList(); - collisionHandler.addCollidingBlockToList( w, x, y, z, bb, tmp, e ); - for( final AxisAlignedBB b : tmp ) - { - b.minX += x; - b.minY += y; - b.minZ += z; - b.maxX += x; - b.maxY += y; - b.maxZ += z; - if( bb.intersectsWith( b ) ) - { - out.add( b ); - } - } - } - else - { - super.addCollisionBoxesToList( w, x, y, z, bb, out, e ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public final AxisAlignedBB getSelectedBoundingBoxFromPool( final World w, final int x, final int y, final int z ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, x, y, z ); - - if( collisionHandler != null ) - { - if( Platform.isClient() ) - { - final EntityPlayer player = Minecraft.getMinecraft().thePlayer; - final LookDirection ld = Platform.getPlayerRay( player, Platform.getEyeOffset( player ) ); - - final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool( w, x, y, z, Minecraft.getMinecraft().thePlayer, true ); - AxisAlignedBB br = null; - - double lastDist = 0; - - for( final AxisAlignedBB bb : bbs ) - { - this.setBlockBounds( (float) bb.minX, (float) bb.minY, (float) bb.minZ, (float) bb.maxX, (float) bb.maxY, (float) bb.maxZ ); - - final MovingObjectPosition r = super.collisionRayTrace( w, x, y, z, ld.getA(), ld.getB() ); - - this.setBlockBounds( 0, 0, 0, 1, 1, 1 ); - - if( r != null ) - { - final double xLen = ( ld.getA().xCoord - r.hitVec.xCoord ); - final double yLen = ( ld.getA().yCoord - r.hitVec.yCoord ); - final double zLen = ( ld.getA().zCoord - r.hitVec.zCoord ); - - final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; - - if( br == null || lastDist > thisDist ) - { - lastDist = thisDist; - br = bb; - } - } - } - - if( br != null ) - { - br.setBounds( br.minX + x, br.minY + y, br.minZ + z, br.maxX + x, br.maxY + y, br.maxZ + z ); - return br; - } - } - - final AxisAlignedBB b = AxisAlignedBB.getBoundingBox( 16d, 16d, 16d, 0d, 0d, 0d ); - - for( final AxisAlignedBB bx : collisionHandler.getSelectedBoundingBoxesFromPool( w, x, y, z, null, false ) ) - { - final double minX = Math.min( b.minX, bx.minX ); - final double minY = Math.min( b.minY, bx.minY ); - final double minZ = Math.min( b.minZ, bx.minZ ); - final double maxX = Math.max( b.maxX, bx.maxX ); - final double maxY = Math.max( b.maxY, bx.maxY ); - final double maxZ = Math.max( b.maxZ, bx.maxZ ); - - b.setBounds( minX, minY, minZ, maxX, maxY, maxZ ); - } - - b.setBounds( b.minX + x, b.minY + y, b.minZ + z, b.maxX + x, b.maxY + y, b.maxZ + z ); - - return b; - } - - return super.getSelectedBoundingBoxFromPool( w, x, y, z ); - } - - @Override - public final boolean isOpaqueCube() - { - return this.isOpaque; - } - - @Override - public MovingObjectPosition collisionRayTrace( final World w, final int x, final int y, final int z, final Vec3 a, final Vec3 b ) - { - final ICustomCollision collisionHandler = this.getCustomCollision( w, x, y, z ); - - if( collisionHandler != null ) - { - final Iterable bbs = collisionHandler.getSelectedBoundingBoxesFromPool( w, x, y, z, null, true ); - MovingObjectPosition br = null; - - double lastDist = 0; - - for( final AxisAlignedBB bb : bbs ) - { - this.setBlockBounds( (float) bb.minX, (float) bb.minY, (float) bb.minZ, (float) bb.maxX, (float) bb.maxY, (float) bb.maxZ ); - - final MovingObjectPosition r = super.collisionRayTrace( w, x, y, z, a, b ); - - this.setBlockBounds( 0, 0, 0, 1, 1, 1 ); - - if( r != null ) - { - final double xLen = ( a.xCoord - r.hitVec.xCoord ); - final double yLen = ( a.yCoord - r.hitVec.yCoord ); - final double zLen = ( a.zCoord - r.hitVec.zCoord ); - - final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; - if( br == null || lastDist > thisDist ) - { - lastDist = thisDist; - br = r; - } - } - } - - if( br != null ) - { - return br; - } - - return null; - } - - this.setBlockBounds( 0, 0, 0, 1, 1, 1 ); - return super.collisionRayTrace( w, x, y, z, a, b ); - } - - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - @SuppressWarnings( "unchecked" ) - public final void getSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - this.getCheckedSubBlocks( item, tabs, itemStacks ); - } - - @Override - public boolean hasComparatorInputOverride() - { - return this.isInventory; - } - - @Override - public int getComparatorInputOverride( final World w, final int x, final int y, final int z, final int s ) - { - return 0; - } - - @Override - @SideOnly( Side.CLIENT ) - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - final BlockRenderInfo info = this.getRendererInstance(); - final FlippableIcon topIcon = this.optionalIcon( iconRegistry, this.getTextureName(), null ); - final FlippableIcon bottomIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Bottom", topIcon ); - final FlippableIcon sideIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Side", topIcon ); - final FlippableIcon eastIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "East", sideIcon ); - final FlippableIcon westIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "West", sideIcon ); - final FlippableIcon southIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Front", sideIcon ); - final FlippableIcon northIcon = this.optionalIcon( iconRegistry, this.getTextureName() + "Back", sideIcon ); - - this.blockIcon = topIcon; - - info.updateIcons( bottomIcon, topIcon, northIcon, southIcon, eastIcon, westIcon ); - } - - @Override - public final boolean isNormalCube( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isFullSize; - } - - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - if( this instanceof IOrientableBlock ) - { - return this.getOrientable( w, x, y, z ); - } - return null; - } - - @Override - public final boolean rotateBlock( final World w, final int x, final int y, final int z, final ForgeDirection axis ) - { - final IOrientable rotatable = this.getOrientable( w, x, y, z ); - - if( rotatable != null && rotatable.canBeRotated() ) - { - if( this.hasCustomRotation() ) - { - this.customRotateBlock( rotatable, axis ); - return true; - } - else - { - ForgeDirection forward = rotatable.getForward(); - ForgeDirection up = rotatable.getUp(); - - for( int rs = 0; rs < 4; rs++ ) - { - forward = Platform.rotateAround( forward, axis ); - up = Platform.rotateAround( up, axis ); - - if( this.isValidOrientation( w, x, y, z, forward, up ) ) - { - rotatable.setOrientation( forward, up ); - return true; - } - } - } - } - - return super.rotateBlock( w, x, y, z, axis ); - } - - protected boolean hasCustomRotation() - { - return false; - } - - protected void customRotateBlock( final IOrientable rotatable, final ForgeDirection axis ) - { - - } - - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - return true; - } - - @Override - public ForgeDirection[] getValidRotations( final World w, final int x, final int y, final int z ) - { - return new ForgeDirection[0]; - } - - @SideOnly( Side.CLIENT ) - private FlippableIcon optionalIcon( final IIconRegister ir, final String name, IIcon substitute ) - { - // if the input is an flippable IIcon find the original. - while( substitute instanceof FlippableIcon ) - { - substitute = ( (FlippableIcon) substitute ).getOriginal(); - } - - if( substitute != null ) - { - try - { - ResourceLocation resLoc = new ResourceLocation( name ); - resLoc = new ResourceLocation( resLoc.getResourceDomain(), String.format( "%s/%s%s", "textures/blocks", resLoc.getResourcePath(), ".png" ) ); - - final IResource res = Minecraft.getMinecraft().getResourceManager().getResource( resLoc ); - if( res != null ) - { - return new FlippableIcon( ir.registerIcon( name ) ); - } - } - catch( final Throwable e ) - { - return new FlippableIcon( substitute ); - } - } - - return new FlippableIcon( ir.registerIcon( name ) ); - } - - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - super.getSubBlocks( item, tabs, itemStacks ); - } - - private int mapRotation( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - final IOrientable ori = this.getOrientable( w, x, y, z ); - - if( ori != null && ori.canBeRotated() ) - { - return this.mapRotation( ori, ForgeDirection.getOrientation( s ) ).ordinal(); - } - - return s; - } - - public ForgeDirection mapRotation( final IOrientable ori, final ForgeDirection dir ) - { - // case DOWN: return bottomIcon; - // case UP: return blockIcon; - // case NORTH: return northIcon; - // case SOUTH: return southIcon; - // case WEST: return sideIcon; - // case EAST: return sideIcon; - - final ForgeDirection forward = ori.getForward(); - final ForgeDirection up = ori.getUp(); - - if( forward == null || up == null ) - { - return dir; - } - - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - - ForgeDirection west = ForgeDirection.UNKNOWN; - for( final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS ) - { - if( dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z ) - { - west = dx; - } - } - - if( dir == forward ) - { - return ForgeDirection.SOUTH; - } - if( dir == forward.getOpposite() ) - { - return ForgeDirection.NORTH; - } - - if( dir == up ) - { - return ForgeDirection.UP; - } - if( dir == up.getOpposite() ) - { - return ForgeDirection.DOWN; - } - - if( dir == west ) - { - return ForgeDirection.WEST; - } - if( dir == west.getOpposite() ) - { - return ForgeDirection.EAST; - } - - return ForgeDirection.UNKNOWN; - } - - @SideOnly( Side.CLIENT ) - public void setRenderStateByMeta( final int itemDamage ) - { - - } - - public String getUnlocalizedName( final ItemStack is ) - { - return this.getUnlocalizedName(); - } - - void addInformation( final ItemStack is, final EntityPlayer player, final List lines, final boolean advancedItemTooltips ) - { - - } - - public Class getItemBlockClass() - { - return AEBaseItemBlock.class; - } - - public boolean hasSubtypes() - { - return this.hasSubtypes; - } - +public abstract class AEBaseBlock extends Block implements IAEFeature { + private final String featureFullName; + protected final Optional featureSubName; + protected boolean isOpaque = true; + protected boolean isFullSize = true; + protected boolean hasSubtypes = false; + protected boolean isInventory = false; + private IFeatureHandler handler; + @SideOnly(Side.CLIENT) + private BlockRenderInfo renderInfo; + + protected AEBaseBlock(final Material mat) { + this(mat, Optional.absent()); + this.setLightOpacity(255); + this.setLightLevel(0); + this.setHardness(2.2F); + this.setHarvestLevel("pickaxe", 0); + } + + protected AEBaseBlock(final Material mat, final Optional subName) { + super(mat); + + if (mat == AEGlassMaterial.INSTANCE || mat == Material.glass) { + this.setStepSound(Block.soundTypeGlass); + } else if (mat == Material.rock) { + this.setStepSound(Block.soundTypeStone); + } else if (mat == Material.wood) { + this.setStepSound(Block.soundTypeWood); + } else { + this.setStepSound(Block.soundTypeMetal); + } + + this.featureFullName = new FeatureNameExtractor(this.getClass(), subName).get(); + this.featureSubName = subName; + } + + @Override + public String toString() { + return this.featureFullName; + } + + public void registerNoIcons() { + final BlockRenderInfo info = this.getRendererInstance(); + final FlippableIcon i = new FlippableIcon(new MissingIcon(this)); + info.updateIcons(i, i, i, i, i, i); + } + + @SideOnly(Side.CLIENT) + public BlockRenderInfo getRendererInstance() { + if (this.renderInfo != null) { + return this.renderInfo; + } + + final BaseBlockRender renderer + = this.getRenderer(); + this.renderInfo = new BlockRenderInfo(renderer); + + return this.renderInfo; + } + + /** + * Factory method to create a new render instance. + * + * @return the newly created instance. + */ + @SideOnly(Side.CLIENT) + protected BaseBlockRender getRenderer() { + return new BaseBlockRender(); + } + + IIcon unmappedGetIcon( + final IBlockAccess w, final int x, final int y, final int z, final int s + ) { + return super.getIcon(w, x, y, z, s); + } + + protected void setFeature(final EnumSet f) { + final AEBlockFeatureHandler featureHandler + = new AEBlockFeatureHandler(f, this, this.featureSubName); + this.setHandler(featureHandler); + } + + @Override + public final IFeatureHandler handler() { + return this.handler; + } + + protected final void setHandler(final IFeatureHandler handler) { + this.handler = handler; + } + + @Override + public void postInit() { + // override! + } + + public boolean isOpaque() { + return this.isOpaque; + } + + @Override + public boolean renderAsNormalBlock() { + return this.isFullSize && this.isOpaque; + } + + @Override + @SideOnly(Side.CLIENT) + public int getRenderType() { + return WorldRender.INSTANCE.getRenderId(); + } + + @Override + public IIcon + getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + return this.getIcon(this.mapRotation(w, x, y, z, s), w.getBlockMetadata(x, y, z)); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final int metadata) { + return this.getRendererInstance().getTexture( + ForgeDirection.getOrientation(direction) + ); + } + + protected ICustomCollision + getCustomCollision(final World w, final int x, final int y, final int z) { + if (this instanceof ICustomCollision) { + return (ICustomCollision) this; + } + return null; + } + + @Override + @SuppressWarnings("unchecked") + // NOTE: WAS FINAL, changed for Immibis + public void addCollisionBoxesToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, x, y, z); + + if (collisionHandler != null && bb != null) { + final List tmp = new ArrayList(); + collisionHandler.addCollidingBlockToList(w, x, y, z, bb, tmp, e); + for (final AxisAlignedBB b : tmp) { + b.minX += x; + b.minY += y; + b.minZ += z; + b.maxX += x; + b.maxY += y; + b.maxZ += z; + if (bb.intersectsWith(b)) { + out.add(b); + } + } + } else { + super.addCollisionBoxesToList(w, x, y, z, bb, out, e); + } + } + + @Override + @SideOnly(Side.CLIENT) + public final AxisAlignedBB + getSelectedBoundingBoxFromPool(final World w, final int x, final int y, final int z) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, x, y, z); + + if (collisionHandler != null) { + if (Platform.isClient()) { + final EntityPlayer player = Minecraft.getMinecraft().thePlayer; + final LookDirection ld + = Platform.getPlayerRay(player, Platform.getEyeOffset(player)); + + final Iterable bbs + = collisionHandler.getSelectedBoundingBoxesFromPool( + w, x, y, z, Minecraft.getMinecraft().thePlayer, true + ); + AxisAlignedBB br = null; + + double lastDist = 0; + + for (final AxisAlignedBB bb : bbs) { + this.setBlockBounds( + (float) bb.minX, + (float) bb.minY, + (float) bb.minZ, + (float) bb.maxX, + (float) bb.maxY, + (float) bb.maxZ + ); + + final MovingObjectPosition r + = super.collisionRayTrace(w, x, y, z, ld.getA(), ld.getB()); + + this.setBlockBounds(0, 0, 0, 1, 1, 1); + + if (r != null) { + final double xLen = (ld.getA().xCoord - r.hitVec.xCoord); + final double yLen = (ld.getA().yCoord - r.hitVec.yCoord); + final double zLen = (ld.getA().zCoord - r.hitVec.zCoord); + + final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; + + if (br == null || lastDist > thisDist) { + lastDist = thisDist; + br = bb; + } + } + } + + if (br != null) { + br.setBounds( + br.minX + x, + br.minY + y, + br.minZ + z, + br.maxX + x, + br.maxY + y, + br.maxZ + z + ); + return br; + } + } + + final AxisAlignedBB b + = AxisAlignedBB.getBoundingBox(16d, 16d, 16d, 0d, 0d, 0d); + + for (final AxisAlignedBB bx : + collisionHandler.getSelectedBoundingBoxesFromPool( + w, x, y, z, null, false + )) { + final double minX = Math.min(b.minX, bx.minX); + final double minY = Math.min(b.minY, bx.minY); + final double minZ = Math.min(b.minZ, bx.minZ); + final double maxX = Math.max(b.maxX, bx.maxX); + final double maxY = Math.max(b.maxY, bx.maxY); + final double maxZ = Math.max(b.maxZ, bx.maxZ); + + b.setBounds(minX, minY, minZ, maxX, maxY, maxZ); + } + + b.setBounds( + b.minX + x, b.minY + y, b.minZ + z, b.maxX + x, b.maxY + y, b.maxZ + z + ); + + return b; + } + + return super.getSelectedBoundingBoxFromPool(w, x, y, z); + } + + @Override + public final boolean isOpaqueCube() { + return this.isOpaque; + } + + @Override + public MovingObjectPosition collisionRayTrace( + final World w, final int x, final int y, final int z, final Vec3 a, final Vec3 b + ) { + final ICustomCollision collisionHandler = this.getCustomCollision(w, x, y, z); + + if (collisionHandler != null) { + final Iterable bbs + = collisionHandler.getSelectedBoundingBoxesFromPool( + w, x, y, z, null, true + ); + MovingObjectPosition br = null; + + double lastDist = 0; + + for (final AxisAlignedBB bb : bbs) { + this.setBlockBounds( + (float) bb.minX, + (float) bb.minY, + (float) bb.minZ, + (float) bb.maxX, + (float) bb.maxY, + (float) bb.maxZ + ); + + final MovingObjectPosition r = super.collisionRayTrace(w, x, y, z, a, b); + + this.setBlockBounds(0, 0, 0, 1, 1, 1); + + if (r != null) { + final double xLen = (a.xCoord - r.hitVec.xCoord); + final double yLen = (a.yCoord - r.hitVec.yCoord); + final double zLen = (a.zCoord - r.hitVec.zCoord); + + final double thisDist = xLen * xLen + yLen * yLen + zLen * zLen; + if (br == null || lastDist > thisDist) { + lastDist = thisDist; + br = r; + } + } + } + + if (br != null) { + return br; + } + + return null; + } + + this.setBlockBounds(0, 0, 0, 1, 1, 1); + return super.collisionRayTrace(w, x, y, z, a, b); + } + + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + return false; + } + + @Override + @SideOnly(Side.CLIENT) + @SuppressWarnings("unchecked") + public final void + getSubBlocks(final Item item, final CreativeTabs tabs, final List itemStacks) { + this.getCheckedSubBlocks(item, tabs, itemStacks); + } + + @Override + public boolean hasComparatorInputOverride() { + return this.isInventory; + } + + @Override + public int getComparatorInputOverride( + final World w, final int x, final int y, final int z, final int s + ) { + return 0; + } + + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(final IIconRegister iconRegistry) { + final BlockRenderInfo info = this.getRendererInstance(); + final FlippableIcon topIcon + = this.optionalIcon(iconRegistry, this.getTextureName(), null); + final FlippableIcon bottomIcon + = this.optionalIcon(iconRegistry, this.getTextureName() + "Bottom", topIcon); + final FlippableIcon sideIcon + = this.optionalIcon(iconRegistry, this.getTextureName() + "Side", topIcon); + final FlippableIcon eastIcon + = this.optionalIcon(iconRegistry, this.getTextureName() + "East", sideIcon); + final FlippableIcon westIcon + = this.optionalIcon(iconRegistry, this.getTextureName() + "West", sideIcon); + final FlippableIcon southIcon + = this.optionalIcon(iconRegistry, this.getTextureName() + "Front", sideIcon); + final FlippableIcon northIcon + = this.optionalIcon(iconRegistry, this.getTextureName() + "Back", sideIcon); + + this.blockIcon = topIcon; + + info.updateIcons(bottomIcon, topIcon, northIcon, southIcon, eastIcon, westIcon); + } + + @Override + public final boolean + isNormalCube(final IBlockAccess world, final int x, final int y, final int z) { + return this.isFullSize; + } + + public IOrientable + getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + if (this instanceof IOrientableBlock) { + return this.getOrientable(w, x, y, z); + } + return null; + } + + @Override + public final boolean rotateBlock( + final World w, final int x, final int y, final int z, final ForgeDirection axis + ) { + final IOrientable rotatable = this.getOrientable(w, x, y, z); + + if (rotatable != null && rotatable.canBeRotated()) { + if (this.hasCustomRotation()) { + this.customRotateBlock(rotatable, axis); + return true; + } else { + ForgeDirection forward = rotatable.getForward(); + ForgeDirection up = rotatable.getUp(); + + for (int rs = 0; rs < 4; rs++) { + forward = Platform.rotateAround(forward, axis); + up = Platform.rotateAround(up, axis); + + if (this.isValidOrientation(w, x, y, z, forward, up)) { + rotatable.setOrientation(forward, up); + return true; + } + } + } + } + + return super.rotateBlock(w, x, y, z, axis); + } + + protected boolean hasCustomRotation() { + return false; + } + + protected void + customRotateBlock(final IOrientable rotatable, final ForgeDirection axis) {} + + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up + ) { + return true; + } + + @Override + public ForgeDirection[] getValidRotations( + final World w, final int x, final int y, final int z + ) { + return new ForgeDirection[0]; + } + + @SideOnly(Side.CLIENT) + private FlippableIcon + optionalIcon(final IIconRegister ir, final String name, IIcon substitute) { + // if the input is an flippable IIcon find the original. + while (substitute instanceof FlippableIcon) { + substitute = ((FlippableIcon) substitute).getOriginal(); + } + + if (substitute != null) { + try { + ResourceLocation resLoc = new ResourceLocation(name); + resLoc = new ResourceLocation( + resLoc.getResourceDomain(), + String.format( + "%s/%s%s", "textures/blocks", resLoc.getResourcePath(), ".png" + ) + ); + + final IResource res + = Minecraft.getMinecraft().getResourceManager().getResource(resLoc); + if (res != null) { + return new FlippableIcon(ir.registerIcon(name)); + } + } catch (final Throwable e) { + return new FlippableIcon(substitute); + } + } + + return new FlippableIcon(ir.registerIcon(name)); + } + + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + super.getSubBlocks(item, tabs, itemStacks); + } + + private int mapRotation( + final IBlockAccess w, final int x, final int y, final int z, final int s + ) { + final IOrientable ori = this.getOrientable(w, x, y, z); + + if (ori != null && ori.canBeRotated()) { + return this.mapRotation(ori, ForgeDirection.getOrientation(s)).ordinal(); + } + + return s; + } + + public ForgeDirection mapRotation(final IOrientable ori, final ForgeDirection dir) { + // case DOWN: return bottomIcon; + // case UP: return blockIcon; + // case NORTH: return northIcon; + // case SOUTH: return southIcon; + // case WEST: return sideIcon; + // case EAST: return sideIcon; + + final ForgeDirection forward = ori.getForward(); + final ForgeDirection up = ori.getUp(); + + if (forward == null || up == null) { + return dir; + } + + final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + + ForgeDirection west = ForgeDirection.UNKNOWN; + for (final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS) { + if (dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z) { + west = dx; + } + } + + if (dir == forward) { + return ForgeDirection.SOUTH; + } + if (dir == forward.getOpposite()) { + return ForgeDirection.NORTH; + } + + if (dir == up) { + return ForgeDirection.UP; + } + if (dir == up.getOpposite()) { + return ForgeDirection.DOWN; + } + + if (dir == west) { + return ForgeDirection.WEST; + } + if (dir == west.getOpposite()) { + return ForgeDirection.EAST; + } + + return ForgeDirection.UNKNOWN; + } + + @SideOnly(Side.CLIENT) + public void setRenderStateByMeta(final int itemDamage) {} + + public String getUnlocalizedName(final ItemStack is) { + return this.getUnlocalizedName(); + } + + void addInformation( + final ItemStack is, + final EntityPlayer player, + final List lines, + final boolean advancedItemTooltips + ) {} + + public Class getItemBlockClass() { + return AEBaseItemBlock.class; + } + + public boolean hasSubtypes() { + return this.hasSubtypes; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlock.java b/src/main/java/appeng/block/AEBaseItemBlock.java index f792b418..5777bd6f 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 appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; @@ -39,182 +40,170 @@ import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; +public class AEBaseItemBlock extends ItemBlock { + private final AEBaseBlock blockType; + public AEBaseItemBlock(final Block id) { + super(id); + this.blockType = (AEBaseBlock) id; + this.hasSubtypes = this.blockType.hasSubtypes; -public class AEBaseItemBlock extends ItemBlock -{ + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, ItemRenderer.INSTANCE); + } + } - private final AEBaseBlock blockType; + @Override + public int getMetadata(final int dmg) { + if (this.hasSubtypes) { + return dmg; + } + return 0; + } - public AEBaseItemBlock( final Block id ) - { - super( id ); - this.blockType = (AEBaseBlock) id; - this.hasSubtypes = this.blockType.hasSubtypes; + @Override + @SideOnly(Side.CLIENT) + @SuppressWarnings("unchecked") + public final void addInformation( + final ItemStack itemStack, + final EntityPlayer player, + final List toolTip, + final boolean advancedTooltips + ) { + this.addCheckedInformation(itemStack, player, toolTip, advancedTooltips); + } - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, ItemRenderer.INSTANCE ); - } - } + @SideOnly(Side.CLIENT) + public void addCheckedInformation( + final ItemStack itemStack, + final EntityPlayer player, + final List toolTip, + final boolean advancedToolTips + ) { + this.blockType.addInformation(itemStack, player, toolTip, advancedToolTips); + } - @Override - public int getMetadata( final int dmg ) - { - if( this.hasSubtypes ) - { - return dmg; - } - return 0; - } + @Override + public boolean + isBookEnchantable(final ItemStack itemstack1, final ItemStack itemstack2) { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - @SuppressWarnings( "unchecked" ) - public final void addInformation( final ItemStack itemStack, final EntityPlayer player, final List toolTip, final boolean advancedTooltips ) - { - this.addCheckedInformation( itemStack, player, toolTip, advancedTooltips ); - } + @Override + public String getUnlocalizedName(final ItemStack is) { + return this.blockType.getUnlocalizedName(is); + } - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack itemStack, final EntityPlayer player, final List toolTip, final boolean advancedToolTips ) - { - this.blockType.addInformation( itemStack, player, toolTip, advancedToolTips ); - } + @Override + public boolean placeBlockAt( + final ItemStack stack, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ, + final int metadata + ) { + ForgeDirection up = ForgeDirection.UNKNOWN; + ForgeDirection forward = ForgeDirection.UNKNOWN; - @Override - public boolean isBookEnchantable( final ItemStack itemstack1, final ItemStack itemstack2 ) - { - return false; - } + if (this.blockType instanceof AEBaseTileBlock) { + if (this.blockType instanceof BlockLightDetector) { + up = ForgeDirection.getOrientation(side); + if (up == ForgeDirection.UP || up == ForgeDirection.DOWN) { + forward = ForgeDirection.SOUTH; + } else { + forward = ForgeDirection.UP; + } + } else if (this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass) { + forward = ForgeDirection.getOrientation(side); + if (forward == ForgeDirection.UP || forward == ForgeDirection.DOWN) { + up = ForgeDirection.SOUTH; + } else { + up = ForgeDirection.UP; + } + } else { + up = ForgeDirection.UP; - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return this.blockType.getUnlocalizedName( is ); - } + final byte rotation = (byte + ) (MathHelper.floor_double((player.rotationYaw * 4F) / 360F + 2.5D) & 3); - @Override - public boolean placeBlockAt( final ItemStack stack, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ, final int metadata ) - { - ForgeDirection up = ForgeDirection.UNKNOWN; - ForgeDirection forward = ForgeDirection.UNKNOWN; + 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; + } - if( this.blockType instanceof AEBaseTileBlock ) - { - if( this.blockType instanceof BlockLightDetector ) - { - up = ForgeDirection.getOrientation( side ); - if( up == ForgeDirection.UP || up == ForgeDirection.DOWN ) - { - forward = ForgeDirection.SOUTH; - } - else - { - forward = ForgeDirection.UP; - } - } - else if( this.blockType instanceof BlockWireless || this.blockType instanceof BlockSkyCompass ) - { - forward = ForgeDirection.getOrientation( side ); - if( forward == ForgeDirection.UP || forward == ForgeDirection.DOWN ) - { - up = ForgeDirection.SOUTH; - } - else - { - up = ForgeDirection.UP; - } - } - else - { - up = ForgeDirection.UP; + if (player.rotationPitch > 65) { + up = forward.getOpposite(); + forward = ForgeDirection.UP; + } else if (player.rotationPitch < -65) { + up = forward.getOpposite(); + forward = ForgeDirection.DOWN; + } + } + } - final byte rotation = (byte) ( MathHelper.floor_double( ( player.rotationYaw * 4F ) / 360F + 2.5D ) & 3 ); + IOrientable ori = null; + if (this.blockType instanceof IOrientableBlock) { + ori = this.blockType.getOrientable(w, x, y, z); + up = ForgeDirection.getOrientation(side); + forward = ForgeDirection.SOUTH; + if (up.offsetY == 0) { + forward = ForgeDirection.UP; + } + } - 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; - } + if (!this.blockType.isValidOrientation(w, x, y, z, forward, up)) { + return false; + } - if( player.rotationPitch > 65 ) - { - up = forward.getOpposite(); - forward = ForgeDirection.UP; - } - else if( player.rotationPitch < -65 ) - { - up = forward.getOpposite(); - forward = ForgeDirection.DOWN; - } - } - } + if (super.placeBlockAt( + stack, player, w, x, y, z, side, hitX, hitY, hitZ, metadata + )) { + if (this.blockType instanceof AEBaseTileBlock + && !(this.blockType instanceof BlockLightDetector)) { + final AEBaseTile tile + = ((AEBaseTileBlock) this.blockType).getTileEntity(w, x, y, z); + ori = tile; - IOrientable ori = null; - if( this.blockType instanceof IOrientableBlock ) - { - ori = this.blockType.getOrientable( w, x, y, z ); - up = ForgeDirection.getOrientation( side ); - forward = ForgeDirection.SOUTH; - if( up.offsetY == 0 ) - { - forward = ForgeDirection.UP; - } - } + if (tile == null) { + return true; + } - if( !this.blockType.isValidOrientation( w, x, y, z, forward, up ) ) - { - return false; - } + if (ori.canBeRotated() && !this.blockType.hasCustomRotation()) { + if (ori.getForward() == null || ori.getUp() == null || // null + tile.getForward() == ForgeDirection.UNKNOWN + || ori.getUp() == ForgeDirection.UNKNOWN) { + ori.setOrientation(forward, up); + } + } - if( super.placeBlockAt( stack, player, w, x, y, z, side, hitX, hitY, hitZ, metadata ) ) - { - if( this.blockType instanceof AEBaseTileBlock && !( this.blockType instanceof BlockLightDetector ) ) - { - final AEBaseTile tile = ( (AEBaseTileBlock) this.blockType ).getTileEntity( w, x, y, z ); - ori = tile; + if (tile instanceof IGridProxyable) { + ((IGridProxyable) tile).getProxy().setOwner(player); + } - if( tile == null ) - { - return true; - } + tile.onPlacement(stack, player, side); + } else if (this.blockType instanceof IOrientableBlock) { + ori.setOrientation(forward, up); + } - if( ori.canBeRotated() && !this.blockType.hasCustomRotation() ) - { - if( ori.getForward() == null || ori.getUp() == null || // null - tile.getForward() == ForgeDirection.UNKNOWN || ori.getUp() == ForgeDirection.UNKNOWN ) - { - ori.setOrientation( forward, up ); - } - } - - if( tile instanceof IGridProxyable ) - { - ( (IGridProxyable) tile ).getProxy().setOwner( player ); - } - - tile.onPlacement( stack, player, side ); - } - else if( this.blockType instanceof IOrientableBlock ) - { - ori.setOrientation( forward, up ); - } - - return true; - } - return false; - } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java index e6c6a473..d0af7da2 100644 --- a/src/main/java/appeng/block/AEBaseItemBlockChargeable.java +++ b/src/main/java/appeng/block/AEBaseItemBlockChargeable.java @@ -18,6 +18,8 @@ package appeng.block; +import java.text.MessageFormat; +import java.util.List; import appeng.api.config.AccessRestriction; import appeng.api.config.PowerUnits; @@ -33,116 +35,105 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.text.MessageFormat; -import java.util.List; +public class AEBaseItemBlockChargeable + extends AEBaseItemBlock implements IAEItemPowerStorage { + public AEBaseItemBlockChargeable(final Block id) { + super(id); + } + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation( + final ItemStack itemStack, + final EntityPlayer player, + final List toolTip, + final boolean advancedTooltips + ) { + final NBTTagCompound tag = itemStack.getTagCompound(); + double internalCurrentPower = 0; + final double internalMaxPower = this.getMaxEnergyCapacity(); -public class AEBaseItemBlockChargeable extends AEBaseItemBlock implements IAEItemPowerStorage -{ + if (tag != null) { + internalCurrentPower = tag.getDouble("internalCurrentPower"); + } - public AEBaseItemBlockChargeable( final Block id ) - { - super( id ); - } + final double percent = internalCurrentPower / internalMaxPower; - @Override - @SideOnly( Side.CLIENT ) - public void addCheckedInformation( final ItemStack itemStack, final EntityPlayer player, final List toolTip, final boolean advancedTooltips ) - { - final NBTTagCompound tag = itemStack.getTagCompound(); - double internalCurrentPower = 0; - final double internalMaxPower = this.getMaxEnergyCapacity(); + toolTip.add( + GuiText.StoredEnergy.getLocal() + ':' + + MessageFormat.format(" {0,number,#} ", internalCurrentPower) + + Platform.gui_localize(PowerUnits.AE.unlocalizedName) + " - " + + MessageFormat.format(" {0,number,#.##%} ", percent) + ); + } - if( tag != null ) - { - internalCurrentPower = tag.getDouble( "internalCurrentPower" ); - } + private double getMaxEnergyCapacity() { + final Block blockID = Block.getBlockFromItem(this); + final IBlockDefinition energyCell + = Api.INSTANCE.definitions().blocks().energyCell(); + for (final Block block : energyCell.maybeBlock().asSet()) { + if (blockID == block) { + return 200000; + } else { + return 8 * 200000; + } + } - final double percent = internalCurrentPower / internalMaxPower; + return 0; + } - toolTip.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - } + @Override + public double injectAEPower(final ItemStack is, double amt) { + double internalCurrentPower = this.getInternal(is); + final double internalMaxPower = this.getMaxEnergyCapacity(); + internalCurrentPower += amt; + if (internalCurrentPower > internalMaxPower) { + amt = internalCurrentPower - internalMaxPower; + internalCurrentPower = internalMaxPower; + this.setInternal(is, internalCurrentPower); + return amt; + } - private double getMaxEnergyCapacity() - { - final Block blockID = Block.getBlockFromItem( this ); - final IBlockDefinition energyCell = Api.INSTANCE.definitions().blocks().energyCell(); - for( final Block block : energyCell.maybeBlock().asSet() ) - { - if( blockID == block ) - { - return 200000; - } - else - { - return 8 * 200000; - } - } + this.setInternal(is, internalCurrentPower); + return 0; + } - return 0; - } + private double getInternal(final ItemStack is) { + final NBTTagCompound nbt = Platform.openNbtData(is); + return nbt.getDouble("internalCurrentPower"); + } - @Override - public double injectAEPower( final ItemStack is, double amt ) - { - double internalCurrentPower = this.getInternal( is ); - final double internalMaxPower = this.getMaxEnergyCapacity(); - internalCurrentPower += amt; - if( internalCurrentPower > internalMaxPower ) - { - amt = internalCurrentPower - internalMaxPower; - internalCurrentPower = internalMaxPower; - this.setInternal( is, internalCurrentPower ); - return amt; - } + private void setInternal(final ItemStack is, final double amt) { + final NBTTagCompound nbt = Platform.openNbtData(is); + nbt.setDouble("internalCurrentPower", amt); + } - this.setInternal( is, internalCurrentPower ); - return 0; - } + @Override + public double extractAEPower(final ItemStack is, double amt) { + double internalCurrentPower = this.getInternal(is); + if (internalCurrentPower > amt) { + internalCurrentPower -= amt; + this.setInternal(is, internalCurrentPower); + return amt; + } - private double getInternal( final ItemStack is ) - { - final NBTTagCompound nbt = Platform.openNbtData( is ); - return nbt.getDouble( "internalCurrentPower" ); - } + amt = internalCurrentPower; + this.setInternal(is, 0); + return amt; + } - private void setInternal( final ItemStack is, final double amt ) - { - final NBTTagCompound nbt = Platform.openNbtData( is ); - nbt.setDouble( "internalCurrentPower", amt ); - } + @Override + public double getAEMaxPower(final ItemStack is) { + return this.getMaxEnergyCapacity(); + } - @Override - public double extractAEPower( final ItemStack is, double amt ) - { - double internalCurrentPower = this.getInternal( is ); - if( internalCurrentPower > amt ) - { - internalCurrentPower -= amt; - this.setInternal( is, internalCurrentPower ); - return amt; - } + @Override + public double getAECurrentPower(final ItemStack is) { + return this.getInternal(is); + } - amt = internalCurrentPower; - this.setInternal( is, 0 ); - return amt; - } - - @Override - public double getAEMaxPower( final ItemStack is ) - { - return this.getMaxEnergyCapacity(); - } - - @Override - public double getAECurrentPower( final ItemStack is ) - { - return this.getInternal( is ); - } - - @Override - public AccessRestriction getPowerFlow( final ItemStack is ) - { - return AccessRestriction.WRITE; - } + @Override + public AccessRestriction getPowerFlow(final ItemStack is) { + return AccessRestriction.WRITE; + } } diff --git a/src/main/java/appeng/block/AEBaseItemBlockSlab.java b/src/main/java/appeng/block/AEBaseItemBlockSlab.java index 40d05544..a5a5dfb9 100644 --- a/src/main/java/appeng/block/AEBaseItemBlockSlab.java +++ b/src/main/java/appeng/block/AEBaseItemBlockSlab.java @@ -1,15 +1,15 @@ package appeng.block; - import net.minecraft.block.Block; import net.minecraft.item.ItemSlab; - -public class AEBaseItemBlockSlab extends ItemSlab -{ - - public AEBaseItemBlockSlab( final Block block, final AEBaseSlabBlock singleSlab, final AEBaseSlabBlock doubleSlab, final Boolean isDoubleSlab ) - { - super( block, singleSlab, doubleSlab, isDoubleSlab ); - } +public class AEBaseItemBlockSlab extends ItemSlab { + public AEBaseItemBlockSlab( + final Block block, + final AEBaseSlabBlock singleSlab, + final AEBaseSlabBlock doubleSlab, + final Boolean isDoubleSlab + ) { + super(block, singleSlab, doubleSlab, isDoubleSlab); + } } diff --git a/src/main/java/appeng/block/AEBaseSlabBlock.java b/src/main/java/appeng/block/AEBaseSlabBlock.java index 3a47f45b..b73971b7 100644 --- a/src/main/java/appeng/block/AEBaseSlabBlock.java +++ b/src/main/java/appeng/block/AEBaseSlabBlock.java @@ -18,6 +18,8 @@ package appeng.block; +import java.util.EnumSet; +import java.util.Random; import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; @@ -31,108 +33,103 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -import java.util.EnumSet; -import java.util.Random; +public class AEBaseSlabBlock extends BlockSlab implements IAEFeature { + private final IFeatureHandler features; + private final AEBaseBlock block; + private final int meta; + private AEBaseSlabBlock slabs; + private AEBaseSlabBlock doubleSlabs; + private final String name; + public AEBaseSlabBlock( + final AEBaseBlock block, + final int meta, + final EnumSet features, + final boolean isDoubleSlab, + final String name + ) { + super(isDoubleSlab, block.getMaterial()); + this.block = block; + this.meta = meta; + this.name = name; + this.setBlockName("appliedenergistics2." + name); + this.setHardness(block.getBlockHardness(null, 0, 0, 0)); + this.setResistance(block.getExplosionResistance(null) * 5.0F / 3.0F); + this.setStepSound(block.stepSound); + this.useNeighborBrightness = true; + if (!this.field_150004_a) { + this.doubleSlabs + = new AEBaseSlabBlock(block, meta, features, true, name + ".double") + .setSlabs(this); + } + this.features + = !this.field_150004_a ? new SlabBlockFeatureHandler(features, this) : null; + } -public class AEBaseSlabBlock extends BlockSlab implements IAEFeature -{ - private final IFeatureHandler features; - private final AEBaseBlock block; - private final int meta; - private AEBaseSlabBlock slabs; - private AEBaseSlabBlock doubleSlabs; - private final String name; + private AEBaseSlabBlock setSlabs(final AEBaseSlabBlock slabs) { + this.slabs = slabs; + return this; + } - public AEBaseSlabBlock( final AEBaseBlock block, final int meta, final EnumSet features, final boolean isDoubleSlab, final String name ) - { - super( isDoubleSlab, block.getMaterial() ); - this.block = block; - this.meta = meta; - this.name = name; - this.setBlockName( "appliedenergistics2." + name ); - this.setHardness( block.getBlockHardness( null, 0, 0, 0 ) ); - this.setResistance( block.getExplosionResistance( null ) * 5.0F / 3.0F ); - this.setStepSound( block.stepSound ); - this.useNeighborBrightness = true; - if( !this.field_150004_a ) - { - this.doubleSlabs = new AEBaseSlabBlock( block, meta, features, true, name + ".double" ).setSlabs( this ); - } - this.features = !this.field_150004_a ? new SlabBlockFeatureHandler( features, this ) : null; - } + public AEBaseSlabBlock slabs() { + return this.slabs; + } - private AEBaseSlabBlock setSlabs( final AEBaseSlabBlock slabs ) - { - this.slabs = slabs; - return this; - } + public AEBaseSlabBlock doubleSlabs() { + return this.doubleSlabs; + } - public AEBaseSlabBlock slabs() - { - return this.slabs; - } + @Override + public IFeatureHandler handler() { + return this.features; + } - public AEBaseSlabBlock doubleSlabs() - { - return this.doubleSlabs; - } + @Override + public void postInit() { + // Override to do stuff + } - @Override - public IFeatureHandler handler() - { - return this.features; - } + @Override + public IIcon getIcon(final int dir, final int meta) { + return this.block.getIcon(dir, this.meta); + } - @Override - public void postInit() - { - // Override to do stuff - } + @Override + public String func_150002_b(final int p_150002_1_) { + return this.getUnlocalizedName(); + } - @Override - public IIcon getIcon( final int dir, final int meta ) - { - return this.block.getIcon( dir, this.meta ); - } + @Override + public void registerBlockIcons(final IIconRegister reg) {} - @Override - public String func_150002_b( final int p_150002_1_ ) - { - return this.getUnlocalizedName(); - } + @Override + public Item getItemDropped(final int meta, final Random rand, final int fortune) { + return this.field_150004_a ? Item.getItemFromBlock(this.slabs) + : Item.getItemFromBlock(this); + } - @Override - public void registerBlockIcons( final IIconRegister reg ) - { - } + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, + final World world, + final int x, + final int y, + final int z + ) { + AEBaseSlabBlock block = (AEBaseSlabBlock) world.getBlock(x, y, z); - @Override - public Item getItemDropped( final int meta, final Random rand, final int fortune ) - { - return this.field_150004_a ? Item.getItemFromBlock( this.slabs ) : Item.getItemFromBlock( this ); - } + if (block == null) { + return null; + } + if (block.field_150004_a) { + block = this.slabs; + } - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z ) - { - AEBaseSlabBlock block = (AEBaseSlabBlock) world.getBlock( x, y, z ); + final int meta = world.getBlockMetadata(x, y, z) & 7; + return new ItemStack(block, 1, meta); + } - if( block == null ) - { - return null; - } - if( block.field_150004_a ) - { - block = this.slabs; - } - - final int meta = world.getBlockMetadata( x, y, z ) & 7; - return new ItemStack( block, 1, meta ); - } - - public String name() - { - return this.name; - } + public String name() { + return this.name; + } } diff --git a/src/main/java/appeng/block/AEBaseStairBlock.java b/src/main/java/appeng/block/AEBaseStairBlock.java index a7881080..8678e795 100644 --- a/src/main/java/appeng/block/AEBaseStairBlock.java +++ b/src/main/java/appeng/block/AEBaseStairBlock.java @@ -18,6 +18,7 @@ package appeng.block; +import java.util.EnumSet; import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; @@ -27,32 +28,28 @@ import com.google.common.base.Optional; import net.minecraft.block.Block; import net.minecraft.block.BlockStairs; -import java.util.EnumSet; +public abstract class AEBaseStairBlock extends BlockStairs implements IAEFeature { + private final IFeatureHandler features; + protected AEBaseStairBlock( + final Block block, final int meta, final EnumSet features + ) { + super(block, meta); -public abstract class AEBaseStairBlock extends BlockStairs implements IAEFeature -{ - private final IFeatureHandler features; + this.features + = new StairBlockFeatureHandler(features, this, Optional.absent()); + this.setBlockName(block.getUnlocalizedName()); - protected AEBaseStairBlock( final Block block, final int meta, final EnumSet features ) - { - super( block, meta ); + this.setLightOpacity(0); + } - this.features = new StairBlockFeatureHandler( features, this, Optional.absent() ); - this.setBlockName( block.getUnlocalizedName() ); + @Override + public IFeatureHandler handler() { + return this.features; + } - this.setLightOpacity( 0 ); - } - - @Override - public IFeatureHandler handler() - { - return this.features; - } - - @Override - public void postInit() - { - // Override to do stuff - } + @Override + public void postInit() { + // Override to do stuff + } } diff --git a/src/main/java/appeng/block/AEBaseTileBlock.java b/src/main/java/appeng/block/AEBaseTileBlock.java index 0b4a655e..13f11d42 100644 --- a/src/main/java/appeng/block/AEBaseTileBlock.java +++ b/src/main/java/appeng/block/AEBaseTileBlock.java @@ -18,6 +18,11 @@ package appeng.block; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.implementations.items.IMemoryCard; import appeng.api.implementations.items.MemoryCardMessages; @@ -53,308 +58,300 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; +public abstract class AEBaseTileBlock + extends AEBaseBlock implements IAEFeature, ITileEntityProvider { + @Nonnull + private Class tileEntityType; + public AEBaseTileBlock(final Material mat) { + super(mat); + } -public abstract class AEBaseTileBlock extends AEBaseBlock implements IAEFeature, ITileEntityProvider -{ + protected AEBaseTileBlock(final Material mat, final Optional subName) { + super(mat, subName); + } - @Nonnull - private Class tileEntityType; + @Override + protected void setFeature(final EnumSet f) { + final AETileBlockFeatureHandler featureHandler + = new AETileBlockFeatureHandler(f, this, this.featureSubName); + this.setHandler(featureHandler); + } - public AEBaseTileBlock( final Material mat ) - { - super( mat ); - } + protected void setTileEntity(final Class c) { + this.tileEntityType = c; + this.isInventory = IInventory.class.isAssignableFrom(c); + this.setTileProvider(this.hasBlockTileEntity()); + } - protected AEBaseTileBlock( final Material mat, final Optional subName ) - { - super( mat, subName ); - } + // update Block value. + private void setTileProvider(final boolean b) { + ReflectionHelper.setPrivateValue(Block.class, this, b, "isTileProvider"); + } - @Override - protected void setFeature( final EnumSet f ) - { - final AETileBlockFeatureHandler featureHandler = new AETileBlockFeatureHandler( f, this, this.featureSubName ); - this.setHandler( featureHandler ); - } + private boolean hasBlockTileEntity() { + return this.tileEntityType != null; + } - protected void setTileEntity( final Class c ) - { - this.tileEntityType = c; - this.isInventory = IInventory.class.isAssignableFrom( c ); - this.setTileProvider( this.hasBlockTileEntity() ); - } + public Class getTileEntityClass() { + return this.tileEntityType; + } - // update Block value. - private void setTileProvider( final boolean b ) - { - ReflectionHelper.setPrivateValue( Block.class, this, b, "isTileProvider" ); - } + @Nullable + public + T getTileEntity(final IBlockAccess w, final int x, final int y, final int z) { + if (!this.hasBlockTileEntity()) { + return null; + } - private boolean hasBlockTileEntity() - { - return this.tileEntityType != null; - } + final TileEntity te = w.getTileEntity(x, y, z); + if (this.tileEntityType.isInstance(te)) { + return (T) te; + } - public Class getTileEntityClass() - { - return this.tileEntityType; - } + return null; + } - @Nullable - public T getTileEntity( final IBlockAccess w, final int x, final int y, final int z ) - { - if( !this.hasBlockTileEntity() ) - { - return null; - } + @Override + public final TileEntity createNewTileEntity(final World var1, final int var2) { + if (this.hasBlockTileEntity()) { + try { + return this.tileEntityType.newInstance(); + } catch (final InstantiationException e) { + throw new IllegalStateException( + "Failed to create a new instance of an illegal class " + + this.tileEntityType, + e + ); + } catch (final IllegalAccessException e) { + throw new IllegalStateException( + "Failed to create a new instance of " + this.tileEntityType + + ", because lack of permissions", + e + ); + } + } - final TileEntity te = w.getTileEntity( x, y, z ); - if( this.tileEntityType.isInstance( te ) ) - { - return (T) te; - } + return null; + } - return null; - } + @Override + public void breakBlock( + final World w, final int x, final int y, final int z, final Block a, final int b + ) { + final AEBaseTile te = this.getTileEntity(w, x, y, z); + if (te != null) { + final ArrayList drops = new ArrayList(); + if (te.dropItems()) { + te.getDrops(w, x, y, z, drops); + } else { + te.getNoDrops(w, x, y, z, drops); + } - @Override - public final TileEntity createNewTileEntity( final World var1, final int var2 ) - { - if( this.hasBlockTileEntity() ) - { - try - { - return this.tileEntityType.newInstance(); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( "Failed to create a new instance of an illegal class " + this.tileEntityType, e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( "Failed to create a new instance of " + this.tileEntityType + ", because lack of permissions", e ); - } - } + // Cry ;_; ... + Platform.spawnDrops(w, x, y, z, drops); + } - return null; - } + // super will remove the TE, as it is not an instance of BlockContainer + super.breakBlock(w, x, y, z, a, b); + } - @Override - public void breakBlock( final World w, final int x, final int y, final int z, final Block a, final int b ) - { - final AEBaseTile te = this.getTileEntity( w, x, y, z ); - if( te != null ) - { - final ArrayList drops = new ArrayList(); - if( te.dropItems() ) - { - te.getDrops( w, x, y, z, drops ); - } - else - { - te.getNoDrops( w, x, y, z, drops ); - } + @Override + public final ForgeDirection[] getValidRotations( + final World w, final int x, final int y, final int z + ) { + final AEBaseTile obj = this.getTileEntity(w, x, y, z); + if (obj != null && obj.canBeRotated()) { + return ForgeDirection.VALID_DIRECTIONS; + } - // Cry ;_; ... - Platform.spawnDrops( w, x, y, z, drops ); - } + return super.getValidRotations(w, x, y, z); + } - // super will remove the TE, as it is not an instance of BlockContainer - super.breakBlock( w, x, y, z, a, b ); - } + @Override + public boolean recolourBlock( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection side, + final int colour + ) { + final TileEntity te = this.getTileEntity(world, x, y, z); - @Override - public final ForgeDirection[] getValidRotations( final World w, final int x, final int y, final int z ) - { - final AEBaseTile obj = this.getTileEntity( w, x, y, z ); - if( obj != null && obj.canBeRotated() ) - { - return ForgeDirection.VALID_DIRECTIONS; - } + if (te instanceof IColorableTile) { + final IColorableTile ct = (IColorableTile) te; + final AEColor c = ct.getColor(); + final AEColor newColor = AEColor.values()[colour]; - return super.getValidRotations( w, x, y, z ); - } + if (c != newColor) { + ct.recolourBlock(side, newColor, null); + return true; + } + return false; + } - @Override - public boolean recolourBlock( final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour ) - { - final TileEntity te = this.getTileEntity( world, x, y, z ); + return super.recolourBlock(world, x, y, z, side, colour); + } - if( te instanceof IColorableTile ) - { - final IColorableTile ct = (IColorableTile) te; - final AEColor c = ct.getColor(); - final AEColor newColor = AEColor.values()[colour]; + @Override + public int getComparatorInputOverride( + final World w, final int x, final int y, final int z, final int s + ) { + final TileEntity te = this.getTileEntity(w, x, y, z); + if (te instanceof IInventory) { + return Container.calcRedstoneFromInventory((IInventory) te); + } + return 0; + } - if( c != newColor ) - { - ct.recolourBlock( side, newColor, null ); - return true; - } - return false; - } + @Override + public boolean onBlockEventReceived( + final World p_149696_1_, + final int p_149696_2_, + final int p_149696_3_, + final int p_149696_4_, + final int p_149696_5_, + final int p_149696_6_ + ) { + super.onBlockEventReceived( + p_149696_1_, p_149696_2_, p_149696_3_, p_149696_4_, p_149696_5_, p_149696_6_ + ); + final TileEntity tileentity + = p_149696_1_.getTileEntity(p_149696_2_, p_149696_3_, p_149696_4_); + return tileentity != null + && tileentity.receiveClientEvent(p_149696_5_, p_149696_6_); + } - return super.recolourBlock( world, x, y, z, side, colour ); - } + @Override + public void onBlockPlacedBy( + final World w, + final int x, + final int y, + final int z, + final EntityLivingBase player, + final ItemStack is + ) { + if (is.hasDisplayName()) { + final TileEntity te = this.getTileEntity(w, x, y, z); + if (te instanceof AEBaseTile) { + ((AEBaseTile) w.getTileEntity(x, y, z)).setName(is.getDisplayName()); + } + } + } - @Override - public int getComparatorInputOverride( final World w, final int x, final int y, final int z, final int s ) - { - final TileEntity te = this.getTileEntity( w, x, y, z ); - if( te instanceof IInventory ) - { - return Container.calcRedstoneFromInventory( (IInventory) te ); - } - return 0; - } + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (player != null && player.inventory.getCurrentItem() != null) { + final ItemStack heldItem = player.inventory.getCurrentItem(); + if (Platform.isWrench(player, heldItem, x, y, z) && player.isSneaking()) { + final Block block = w.getBlock(x, y, z); - @Override - public boolean onBlockEventReceived( final World p_149696_1_, final int p_149696_2_, final int p_149696_3_, final int p_149696_4_, final int p_149696_5_, final int p_149696_6_ ) - { - super.onBlockEventReceived( p_149696_1_, p_149696_2_, p_149696_3_, p_149696_4_, p_149696_5_, p_149696_6_ ); - final TileEntity tileentity = p_149696_1_.getTileEntity( p_149696_2_, p_149696_3_, p_149696_4_ ); - return tileentity != null && tileentity.receiveClientEvent( p_149696_5_, p_149696_6_ ); - } + if (block == null) { + return false; + } - @Override - public void onBlockPlacedBy( final World w, final int x, final int y, final int z, final EntityLivingBase player, final ItemStack is ) - { - if( is.hasDisplayName() ) - { - final TileEntity te = this.getTileEntity( w, x, y, z ); - if( te instanceof AEBaseTile ) - { - ( (AEBaseTile) w.getTileEntity( x, y, z ) ).setName( is.getDisplayName() ); - } - } - } + final AEBaseTile tile = this.getTileEntity(w, x, y, z); - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player != null && player.inventory.getCurrentItem() != null) - { - final ItemStack heldItem = player.inventory.getCurrentItem(); - if( Platform.isWrench( player, heldItem, x, y, z ) && player.isSneaking() ) - { - final Block block = w.getBlock( x, y, z ); + if (tile == null) { + return false; + } - if( block == null ) - { - return false; - } + if (tile instanceof TileCableBus || tile instanceof TileSkyChest) { + return false; + } - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); + BlockEvent.BreakEvent event + = new BlockEvent.BreakEvent(x, y, z, w, this, 0, player); + MinecraftForge.EVENT_BUS.post(event); + if (event.isCanceled()) { + return false; + } - if( tile == null ) - { - return false; - } + final ItemStack[] itemDropCandidates = Platform.getBlockDrops(w, x, y, z); + final ItemStack op = new ItemStack(this); - if( tile instanceof TileCableBus || tile instanceof TileSkyChest ) - { - return false; - } + for (final ItemStack ol : itemDropCandidates) { + if (Platform.isSameItemType(ol, op)) { + final NBTTagCompound tag + = tile.downloadSettings(SettingsFrom.DISMANTLE_ITEM); + if (tag != null) { + ol.setTagCompound(tag); + } + } + } - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, w, this, 0, player ); - MinecraftForge.EVENT_BUS.post( event ); - if( event.isCanceled() ) - { - return false; - } + if (block.removedByPlayer(w, player, x, y, z, false)) { + final List itemsToDrop + = Lists.newArrayList(itemDropCandidates); + Platform.spawnDrops(w, x, y, z, itemsToDrop); + w.setBlockToAir(x, y, z); + } - final ItemStack[] itemDropCandidates = Platform.getBlockDrops( w, x, y, z ); - final ItemStack op = new ItemStack( this ); + return false; + } - for( final ItemStack ol : itemDropCandidates ) - { - if( Platform.isSameItemType( ol, op ) ) - { - final NBTTagCompound tag = tile.downloadSettings( SettingsFrom.DISMANTLE_ITEM ); - if( tag != null ) - { - ol.setTagCompound( tag ); - } - } - } + if (heldItem.getItem() instanceof IMemoryCard + && !(this instanceof BlockCableBus)) { + final IMemoryCard memoryCard = (IMemoryCard) heldItem.getItem(); + final AEBaseTile tileEntity = this.getTileEntity(w, x, y, z); - if( block.removedByPlayer( w, player, x, y, z, false) ) - { - final List itemsToDrop = Lists.newArrayList( itemDropCandidates ); - Platform.spawnDrops( w, x, y, z, itemsToDrop ); - w.setBlockToAir( x, y, z ); - } + if (tileEntity == null) { + return false; + } - return false; + final String name = this.getUnlocalizedName(); - } + if (player.isSneaking()) { + final NBTTagCompound data + = tileEntity.downloadSettings(SettingsFrom.MEMORY_CARD); + if (data != null) { + memoryCard.setMemoryCardContents(heldItem, name, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + } + } else { + final String savedName = memoryCard.getSettingsName(heldItem); + final NBTTagCompound data = memoryCard.getData(heldItem); - if( heldItem.getItem() instanceof IMemoryCard && !( this instanceof BlockCableBus ) ) - { - final IMemoryCard memoryCard = (IMemoryCard) heldItem.getItem(); - final AEBaseTile tileEntity = this.getTileEntity( w, x, y, z ); + if (this.getUnlocalizedName().equals(savedName)) { + tileEntity.uploadSettings(SettingsFrom.MEMORY_CARD, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } else { + memoryCard.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } + } - if( tileEntity == null ) - { - return false; - } + return true; + } + } - final String name = this.getUnlocalizedName(); + return this.onActivated(w, x, y, z, player, side, hitX, hitY, hitZ); + } - if( player.isSneaking() ) - { - final NBTTagCompound data = tileEntity.downloadSettings( SettingsFrom.MEMORY_CARD ); - if( data != null ) - { - memoryCard.setMemoryCardContents( heldItem, name, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - } - } - else - { - final String savedName = memoryCard.getSettingsName( heldItem ); - final NBTTagCompound data = memoryCard.getData( heldItem ); + @Override + public IOrientable + getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + return this.getTileEntity(w, x, y, z); + } - if( this.getUnlocalizedName().equals( savedName ) ) - { - tileEntity.uploadSettings( SettingsFrom.MEMORY_CARD, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - else - { - memoryCard.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - } - - return true; - } - } - - return this.onActivated( w, x, y, z, player, side, hitX, hitY, hitZ ); - } - - @Override - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - return this.getTileEntity( w, x, y, z ); - } - - @Override - public ICustomCollision getCustomCollision( final World w, final int x, final int y, final int z ) - { - final AEBaseTile te = this.getTileEntity( w, x, y, z ); - if( te instanceof ICustomCollision ) - { - return (ICustomCollision) te; - } - - return super.getCustomCollision( w, x, y, z ); - } + @Override + public ICustomCollision + getCustomCollision(final World w, final int x, final int y, final int z) { + final AEBaseTile te = this.getTileEntity(w, x, y, z); + if (te instanceof ICustomCollision) { + return (ICustomCollision) te; + } + return super.getCustomCollision(w, x, y, z); + } } diff --git a/src/main/java/appeng/block/AEDecorativeBlock.java b/src/main/java/appeng/block/AEDecorativeBlock.java index 08d68287..da7b3942 100644 --- a/src/main/java/appeng/block/AEDecorativeBlock.java +++ b/src/main/java/appeng/block/AEDecorativeBlock.java @@ -18,28 +18,23 @@ package appeng.block; - import net.minecraft.block.material.Material; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; +public class AEDecorativeBlock extends AEBaseBlock { + public AEDecorativeBlock(final Material mat) { + super(mat); + } -public class AEDecorativeBlock extends AEBaseBlock -{ - public AEDecorativeBlock( final Material mat ) - { - super( mat ); - } + @Override + public int getRenderType() { + return 0; + } - @Override - public int getRenderType() - { - return 0; - } - - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return super.unmappedGetIcon( w, x, y, z, s ); - } + @Override + public IIcon + getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + return super.unmappedGetIcon(w, x, y, z, s); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java index c119001a..618f7a9a 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingMonitor.java @@ -18,6 +18,7 @@ package appeng.block.crafting; +import java.util.List; import appeng.api.AEApi; import appeng.client.render.blocks.RenderBlockCraftingCPUMonitor; @@ -32,48 +33,44 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; +public class BlockCraftingMonitor extends BlockCraftingUnit { + public BlockCraftingMonitor() { + this.setTileEntity(TileCraftingMonitorTile.class); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockCraftingCPUMonitor getRenderer() { + return new RenderBlockCraftingCPUMonitor(); + } -public class BlockCraftingMonitor extends BlockCraftingUnit -{ - public BlockCraftingMonitor() - { - this.setTileEntity( TileCraftingMonitorTile.class ); - } + @Override + public IIcon getIcon(final int direction, final int metadata) { + if (direction != ForgeDirection.SOUTH.ordinal()) { + for (final Block craftingUnitBlock : AEApi.instance() + .definitions() + .blocks() + .craftingUnit() + .maybeBlock() + .asSet()) { + return craftingUnitBlock.getIcon(direction, metadata); + } + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockCraftingCPUMonitor getRenderer() - { - return new RenderBlockCraftingCPUMonitor(); - } + switch (metadata) { + default: + case 0: + return super.getIcon(0, 0); + case FLAG_FORMED: + return ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon(); + } + } - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - if( direction != ForgeDirection.SOUTH.ordinal() ) - { - for( final Block craftingUnitBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) - { - return craftingUnitBlock.getIcon( direction, metadata ); - } - } - - switch( metadata ) - { - default: - case 0: - return super.getIcon( 0, 0 ); - case FLAG_FORMED: - return ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon(); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - itemStacks.add( new ItemStack( this, 1, 0 ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + itemStacks.add(new ItemStack(this, 1, 0)); + } } diff --git a/src/main/java/appeng/block/crafting/BlockCraftingStorage.java b/src/main/java/appeng/block/crafting/BlockCraftingStorage.java index c71b92d0..01034d36 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 appeng.client.texture.ExtraBlockTextures; import appeng.tile.crafting.TileCraftingStorageTile; @@ -28,77 +29,66 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import java.util.List; +public class BlockCraftingStorage extends BlockCraftingUnit { + public BlockCraftingStorage() { + this.setTileEntity(TileCraftingStorageTile.class); + } + @Override + public Class getItemBlockClass() { + return ItemCraftingStorage.class; + } -public class BlockCraftingStorage extends BlockCraftingUnit -{ - public BlockCraftingStorage() - { - this.setTileEntity( TileCraftingStorageTile.class ); - } + @Override + public IIcon getIcon(final int direction, final int metadata) { + switch (metadata & (~4)) { + default: - @Override - public Class getItemBlockClass() - { - return ItemCraftingStorage.class; - } + 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(); - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - switch( metadata & ( ~4 ) ) - { - default: + 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 0: - return super.getIcon( 0, 0 ); - case 1: - return ExtraBlockTextures.BlockCraftingStorage4k.getIcon(); - case 2: - return ExtraBlockTextures.BlockCraftingStorage16k.getIcon(); - case 3: - return ExtraBlockTextures.BlockCraftingStorage64k.getIcon(); + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final 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)); + } - 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 + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { + return "tile.appliedenergistics2.BlockCraftingStorage4k"; + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final 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 ) ); - } + if (is.getItemDamage() == 2) { + return "tile.appliedenergistics2.BlockCraftingStorage16k"; + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { - return "tile.appliedenergistics2.BlockCraftingStorage4k"; - } + if (is.getItemDamage() == 3) { + return "tile.appliedenergistics2.BlockCraftingStorage64k"; + } - if( is.getItemDamage() == 2 ) - { - return "tile.appliedenergistics2.BlockCraftingStorage16k"; - } - - if( is.getItemDamage() == 3 ) - { - return "tile.appliedenergistics2.BlockCraftingStorage64k"; - } - - return this.getItemUnlocalizedName( is ); - } + 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 1bc7dc0f..7b843197 100644 --- a/src/main/java/appeng/block/crafting/BlockCraftingUnit.java +++ b/src/main/java/appeng/block/crafting/BlockCraftingUnit.java @@ -18,6 +18,8 @@ package appeng.block.crafting; +import java.util.EnumSet; +import java.util.List; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockCraftingCPU; @@ -38,129 +40,128 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; +public class BlockCraftingUnit extends AEBaseTileBlock { + static final int FLAG_FORMED = 8; + public BlockCraftingUnit() { + super(Material.iron); -public class BlockCraftingUnit extends AEBaseTileBlock -{ - static final int FLAG_FORMED = 8; + this.hasSubtypes = true; + this.setTileEntity(TileCraftingTile.class); + this.setFeature(EnumSet.of(AEFeature.CraftingCPU)); + } - public BlockCraftingUnit() - { - super( Material.iron ); + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockCraftingCPU + getRenderer() { + return new RenderBlockCraftingCPU(); + } - this.hasSubtypes = true; - this.setTileEntity( TileCraftingTile.class ); - this.setFeature( EnumSet.of( AEFeature.CraftingCPU ) ); - } + @Override + public IIcon getIcon(final int direction, final 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 - @SideOnly( Side.CLIENT ) - protected RenderBlockCraftingCPU getRenderer() - { - return new RenderBlockCraftingCPU(); - } + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final TileCraftingTile tg = this.getTileEntity(w, x, y, z); + if (tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive()) { + if (Platform.isClient()) { + return true; + } - @Override - public IIcon getIcon( final int direction, final 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(); - } - } + Platform.openGUI( + p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_CRAFTING_CPU + ); + return true; + } - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileCraftingTile tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() && tg.isFormed() && tg.isActive() ) - { - if( Platform.isClient() ) - { - return true; - } + return super.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CRAFTING_CPU ); - return true; - } + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + itemStacks.add(new ItemStack(this, 1, 0)); + itemStacks.add(new ItemStack(this, 1, 1)); + } - return super.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } + @Override + public void setRenderStateByMeta(final int itemDamage) { + final IIcon front = this.getIcon(ForgeDirection.SOUTH.ordinal(), itemDamage); + final IIcon other = this.getIcon(ForgeDirection.NORTH.ordinal(), itemDamage); + this.getRendererInstance().setTemporaryRenderIcons( + other, other, front, other, other, other + ); + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - itemStacks.add( new ItemStack( this, 1, 0 ) ); - itemStacks.add( new ItemStack( this, 1, 1 ) ); - } + @Override + public void breakBlock( + final World w, final int x, final int y, final int z, final Block a, final int b + ) { + final TileCraftingTile cp = this.getTileEntity(w, x, y, z); + if (cp != null) { + cp.breakCluster(); + } - @Override - public void setRenderStateByMeta( final int itemDamage ) - { - final IIcon front = this.getIcon( ForgeDirection.SOUTH.ordinal(), itemDamage ); - final IIcon other = this.getIcon( ForgeDirection.NORTH.ordinal(), itemDamage ); - this.getRendererInstance().setTemporaryRenderIcons( other, other, front, other, other, other ); - } + super.breakBlock(w, x, y, z, a, b); + } - @Override - public void breakBlock( final World w, final int x, final int y, final int z, final Block a, final int b ) - { - final TileCraftingTile cp = this.getTileEntity( w, x, y, z ); - if( cp != null ) - { - cp.breakCluster(); - } + @Override + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { + return "tile.appliedenergistics2.BlockCraftingAccelerator"; + } - super.breakBlock( w, x, y, z, a, b ); - } + return this.getItemUnlocalizedName(is); + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { - return "tile.appliedenergistics2.BlockCraftingAccelerator"; - } + protected String getItemUnlocalizedName(final ItemStack is) { + return super.getUnlocalizedName(is); + } - return this.getItemUnlocalizedName( is ); - } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block junk + ) { + final TileCraftingTile cp = this.getTileEntity(w, x, y, z); + if (cp != null) { + cp.updateMultiBlock(); + } + } - protected String getItemUnlocalizedName( final ItemStack is ) - { - return super.getUnlocalizedName( is ); - } + @Override + public int damageDropped(final int meta) { + return meta & 3; + } - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileCraftingTile cp = this.getTileEntity( w, x, y, z ); - if( cp != null ) - { - cp.updateMultiBlock(); - } - } - - @Override - public int damageDropped( final int meta ) - { - return meta & 3; - } - - @Override - public int getDamageValue( final World w, final int x, final int y, final int z ) - { - final int meta = w.getBlockMetadata( x, y, z ); - return this.damageDropped( meta ); - } + @Override + public int getDamageValue(final World w, final int x, final int y, final int z) { + final 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 0dd83e91..11d031cd 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 appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockAssembler; @@ -32,63 +33,62 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockMolecularAssembler extends AEBaseTileBlock { + private static boolean booleanAlphaPass = false; + public BlockMolecularAssembler() { + super(Material.iron); -public class BlockMolecularAssembler extends AEBaseTileBlock -{ + this.setTileEntity(TileMolecularAssembler.class); + this.isOpaque = false; + this.lightOpacity = 1; + this.setFeature(EnumSet.of(AEFeature.MolecularAssembler)); + } - private static boolean booleanAlphaPass = false; + @Override + public int getRenderBlockPass() { + return 1; + } - public BlockMolecularAssembler() - { - super( Material.iron ); + @Override + public boolean canRenderInPass(final int pass) { + setBooleanAlphaPass(pass == 1); + return pass == 0 || pass == 1; + } - this.setTileEntity( TileMolecularAssembler.class ); - this.isOpaque = false; - this.lightOpacity = 1; - this.setFeature( EnumSet.of( AEFeature.MolecularAssembler ) ); - } + @Override + @SideOnly(Side.CLIENT) + public RenderBlockAssembler getRenderer() { + return new RenderBlockAssembler(); + } - @Override - public int getRenderBlockPass() - { - return 1; - } + @Override + public boolean onBlockActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final TileMolecularAssembler tg = this.getTileEntity(w, x, y, z); + if (tg != null && !p.isSneaking()) { + Platform.openGUI( + p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_MAC + ); + return true; + } + return super.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } - @Override - public boolean canRenderInPass( final int pass ) - { - setBooleanAlphaPass( pass == 1 ); - return pass == 0 || pass == 1; - } + public static boolean isBooleanAlphaPass() { + return booleanAlphaPass; + } - @Override - @SideOnly( Side.CLIENT ) - public RenderBlockAssembler getRenderer() - { - return new RenderBlockAssembler(); - } - - @Override - public boolean onBlockActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileMolecularAssembler tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_MAC ); - return true; - } - return super.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } - - public static boolean isBooleanAlphaPass() - { - return booleanAlphaPass; - } - - private static void setBooleanAlphaPass( final boolean booleanAlphaPass ) - { - BlockMolecularAssembler.booleanAlphaPass = booleanAlphaPass; - } + private static void setBooleanAlphaPass(final boolean booleanAlphaPass) { + BlockMolecularAssembler.booleanAlphaPass = booleanAlphaPass; + } } diff --git a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java index 885dbce7..902e3ec2 100644 --- a/src/main/java/appeng/block/crafting/ItemCraftingStorage.java +++ b/src/main/java/appeng/block/crafting/ItemCraftingStorage.java @@ -18,7 +18,6 @@ package appeng.block.crafting; - import appeng.api.AEApi; import appeng.block.AEBaseItemBlock; import appeng.core.AEConfig; @@ -26,29 +25,24 @@ import appeng.core.features.AEFeature; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; +public class ItemCraftingStorage extends AEBaseItemBlock { + public ItemCraftingStorage(final Block id) { + super(id); + } -public class ItemCraftingStorage extends AEBaseItemBlock -{ + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + for (final ItemStack stack : + AEApi.instance().definitions().blocks().craftingUnit().maybeStack(1).asSet( + )) { + return stack; + } - public ItemCraftingStorage( final Block id ) - { - super( id ); - } + return null; + } - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - for( final ItemStack stack : AEApi.instance().definitions().blocks().craftingUnit().maybeStack( 1 ).asSet() ) - { - return stack; - } - - return null; - } - - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return AEConfig.instance.isFeatureEnabled( AEFeature.EnableDisassemblyCrafting ); - } + @Override + public boolean hasContainerItem(final 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 56bbad6e..d5578625 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 appeng.api.implementations.tiles.ICrankable; import appeng.block.AEBaseTileBlock; @@ -38,123 +39,133 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockCrank extends AEBaseTileBlock { + public BlockCrank() { + super(Material.wood); + this.setTileEntity(TileCrank.class); + this.setLightOpacity(0); + this.setHarvestLevel("axe", 0); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.GrindStone)); + } -public class BlockCrank extends AEBaseTileBlock -{ + @Override + @SideOnly(Side.CLIENT) + public RenderBlockCrank getRenderer() { + return new RenderBlockCrank(); + } - public BlockCrank() - { - super( Material.wood ); + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (player instanceof FakePlayer || player == null) { + this.dropCrank(w, x, y, z); + return true; + } - this.setTileEntity( TileCrank.class ); - this.setLightOpacity( 0 ); - this.setHarvestLevel( "axe", 0 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.GrindStone ) ); - } + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + if (tile instanceof TileCrank) { + if (((TileCrank) tile).power()) { + Stats.TurnedCranks.addToPlayer(player, 1); + } + } - @Override - @SideOnly( Side.CLIENT ) - public RenderBlockCrank getRenderer() - { - return new RenderBlockCrank(); - } + return true; + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player instanceof FakePlayer || player == null ) - { - this.dropCrank( w, x, y, z ); - return true; - } + private void dropCrank(final World world, final int x, final int y, final int z) { + world.func_147480_a(x, y, z, true); // w.destroyBlock( x, y, z, true ); + world.markBlockForUpdate(x, y, z); + } - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if( tile instanceof TileCrank ) - { - if( ( (TileCrank) tile ).power() ) - { - Stats.TurnedCranks.addToPlayer( player, 1 ); - } - } + @Override + public void onBlockPlacedBy( + final World world, + final int x, + final int y, + final int z, + final EntityLivingBase placer, + final ItemStack itemStack + ) { + final AEBaseTile tile = this.getTileEntity(world, x, y, z); + if (tile != null) { + final ForgeDirection mnt = this.findCrankable(world, x, y, z); + ForgeDirection forward = ForgeDirection.UP; + if (mnt == ForgeDirection.UP || mnt == ForgeDirection.DOWN) { + forward = ForgeDirection.SOUTH; + } + tile.setOrientation(forward, mnt.getOpposite()); + } else { + this.dropCrank(world, x, y, z); + } + } - return true; - } + @Override + public boolean isValidOrientation( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up + ) { + final TileEntity te = world.getTileEntity(x, y, z); + return !(te instanceof TileCrank) + || this.isCrankable(world, x, y, z, up.getOpposite()); + } - private void dropCrank( final World world, final int x, final int y, final int z ) - { - world.func_147480_a( x, y, z, true ); // w.destroyBlock( x, y, z, true ); - world.markBlockForUpdate( x, y, z ); - } + private ForgeDirection + findCrankable(final World world, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.isCrankable(world, x, y, z, dir)) { + return dir; + } + } + return ForgeDirection.UNKNOWN; + } - @Override - public void onBlockPlacedBy( final World world, final int x, final int y, final int z, final EntityLivingBase placer, final ItemStack itemStack ) - { - final AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if( tile != null ) - { - final ForgeDirection mnt = this.findCrankable( world, x, y, z ); - ForgeDirection forward = ForgeDirection.UP; - if( mnt == ForgeDirection.UP || mnt == ForgeDirection.DOWN ) - { - forward = ForgeDirection.SOUTH; - } - tile.setOrientation( forward, mnt.getOpposite() ); - } - else - { - this.dropCrank( world, x, y, z ); - } - } + private boolean isCrankable( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection offset + ) { + final TileEntity te = world.getTileEntity( + x + offset.offsetX, y + offset.offsetY, z + offset.offsetZ + ); - @Override - public boolean isValidOrientation( final World world, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - return !( te instanceof TileCrank ) || this.isCrankable( world, x, y, z, up.getOpposite() ); - } + return te instanceof ICrankable + && ((ICrankable) te).canCrankAttach(offset.getOpposite()); + } - private ForgeDirection findCrankable( final World world, final int x, final int y, final int z ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.isCrankable( world, x, y, z, dir ) ) - { - return dir; - } - } - return ForgeDirection.UNKNOWN; - } + @Override + public void onNeighborBlockChange( + final World world, final int x, final int y, final int z, final Block block + ) { + final AEBaseTile tile = this.getTileEntity(world, x, y, z); + if (tile != null) { + if (!this.isCrankable(world, x, y, z, tile.getUp().getOpposite())) { + this.dropCrank(world, x, y, z); + } + } else { + this.dropCrank(world, x, y, z); + } + } - private boolean isCrankable( final World world, final int x, final int y, final int z, final ForgeDirection offset ) - { - final 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( final World world, final int x, final int y, final int z, final Block block ) - { - final AEBaseTile tile = this.getTileEntity( world, x, y, z ); - if( tile != null ) - { - if( !this.isCrankable( world, x, y, z, tile.getUp().getOpposite() ) ) - { - this.dropCrank( world, x, y, z ); - } - } - else - { - this.dropCrank( world, x, y, z ); - } - } - - @Override - public boolean canPlaceBlockAt( final World world, final int x, final int y, final int z ) - { - return this.findCrankable( world, x, y, z ) != ForgeDirection.UNKNOWN; - } + @Override + public boolean + canPlaceBlockAt(final World world, final int x, final int y, final 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 f93b03e4..82f8f553 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 appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; @@ -29,30 +30,34 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockGrinder extends AEBaseTileBlock { + public BlockGrinder() { + super(Material.rock); + this.setTileEntity(TileGrinder.class); + this.setHardness(3.2F); + this.setFeature(EnumSet.of(AEFeature.GrindStone)); + } -public class BlockGrinder extends AEBaseTileBlock -{ - - public BlockGrinder() - { - super( Material.rock ); - - this.setTileEntity( TileGrinder.class ); - this.setHardness( 3.2F ); - this.setFeature( EnumSet.of( AEFeature.GrindStone ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileGrinder tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_GRINDER ); - return true; - } - return false; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final TileGrinder tg = this.getTileEntity(w, x, y, z); + 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/legacy/BlockCraftMonitor.java b/src/main/java/appeng/block/legacy/BlockCraftMonitor.java index 4576460b..c79453b6 100644 --- a/src/main/java/appeng/block/legacy/BlockCraftMonitor.java +++ b/src/main/java/appeng/block/legacy/BlockCraftMonitor.java @@ -1,5 +1,7 @@ package appeng.block.legacy; +import java.util.EnumSet; + import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; @@ -10,28 +12,38 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - public class BlockCraftMonitor extends AEBaseTileBlock { - public BlockCraftMonitor() { super(Material.iron); this.setTileEntity(TileCraftingMonitor.class); - this.setFeature( EnumSet.of(AEFeature.Legacy) ); + this.setFeature(EnumSet.of(AEFeature.Legacy)); } @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 + ) { final TileCraftingMonitor tile = this.getTileEntity(w, x, y, z); - if( tile != null && !player.isSneaking() ) { - if( Platform.isClient() ) - { + if (tile != null && !player.isSneaking()) { + if (Platform.isClient()) { return true; } - Platform.openGUI(player, tile, ForgeDirection.getOrientation(side), GuiBridge.GUI_CRAFTING_STATUS); + Platform.openGUI( + player, + tile, + ForgeDirection.getOrientation(side), + GuiBridge.GUI_CRAFTING_STATUS + ); return true; } return false; } - } diff --git a/src/main/java/appeng/block/legacy/BlockCraftTerminal.java b/src/main/java/appeng/block/legacy/BlockCraftTerminal.java index 9e4136de..597168a0 100644 --- a/src/main/java/appeng/block/legacy/BlockCraftTerminal.java +++ b/src/main/java/appeng/block/legacy/BlockCraftTerminal.java @@ -1,5 +1,7 @@ package appeng.block.legacy; +import java.util.EnumSet; + import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.core.sync.GuiBridge; @@ -10,25 +12,36 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - public class BlockCraftTerminal extends AEBaseTileBlock { - public BlockCraftTerminal() { super(Material.iron); this.setTileEntity(TileCraftTerminal.class); - this.setFeature( EnumSet.of(AEFeature.Legacy) ); + this.setFeature(EnumSet.of(AEFeature.Legacy)); } @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 + ) { final TileCraftTerminal tile = this.getTileEntity(w, x, y, z); - if( tile != null && !player.isSneaking() ) { - if( Platform.isClient() ) - { + if (tile != null && !player.isSneaking()) { + if (Platform.isClient()) { return true; } - Platform.openGUI(player, tile, ForgeDirection.getOrientation(side), GuiBridge.GUI_CRAFTING_TERMINAL); + Platform.openGUI( + player, + tile, + ForgeDirection.getOrientation(side), + GuiBridge.GUI_CRAFTING_TERMINAL + ); return true; } return false; diff --git a/src/main/java/appeng/block/legacy/BlockLegacyController.java b/src/main/java/appeng/block/legacy/BlockLegacyController.java index 8dcb4bfa..8f36aec6 100644 --- a/src/main/java/appeng/block/legacy/BlockLegacyController.java +++ b/src/main/java/appeng/block/legacy/BlockLegacyController.java @@ -1,5 +1,7 @@ package appeng.block.legacy; +import java.util.EnumSet; + import appeng.block.AEBaseTileBlock; import appeng.client.texture.ExtraBlockTextures; import appeng.core.features.AEFeature; @@ -12,19 +14,31 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; - public class BlockLegacyController extends AEBaseTileBlock { - public BlockLegacyController() { super(Material.iron); this.setTileEntity(TileLegacyController.class); - this.setFeature( EnumSet.of(AEFeature.Legacy) ); + this.setFeature(EnumSet.of(AEFeature.Legacy)); } @Override - public boolean onActivated(World w, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { - Platform.openGUI(player, w.getTileEntity(x, y, z), ForgeDirection.getOrientation(side), GuiBridge.GUI_NETWORK_STATUS_BLOCK); + public boolean onActivated( + World w, + int x, + int y, + int z, + EntityPlayer player, + int side, + float hitX, + float hitY, + float hitZ + ) { + Platform.openGUI( + player, + w.getTileEntity(x, y, z), + ForgeDirection.getOrientation(side), + GuiBridge.GUI_NETWORK_STATUS_BLOCK + ); return true; } @@ -50,5 +64,4 @@ public class BlockLegacyController extends AEBaseTileBlock { } return super.getIcon(direction, metadata); } - } diff --git a/src/main/java/appeng/block/misc/BlockCellWorkbench.java b/src/main/java/appeng/block/misc/BlockCellWorkbench.java index 410d0886..bcddcd95 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 appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; @@ -29,37 +30,42 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockCellWorkbench extends AEBaseTileBlock { + public BlockCellWorkbench() { + super(Material.iron); + this.setTileEntity(TileCellWorkbench.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells)); + } -public class BlockCellWorkbench extends AEBaseTileBlock -{ + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - public BlockCellWorkbench() - { - super( Material.iron ); - - this.setTileEntity( TileCellWorkbench.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final TileCellWorkbench tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CELL_WORKBENCH ); - } - return true; - } - return false; - } + final TileCellWorkbench tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + 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 6d764e29..6e3b5e29 100644 --- a/src/main/java/appeng/block/misc/BlockCharger.java +++ b/src/main/java/appeng/block/misc/BlockCharger.java @@ -18,6 +18,10 @@ package appeng.block.misc; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import appeng.api.AEApi; import appeng.block.AEBaseTileBlock; @@ -40,148 +44,168 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; +public class BlockCharger extends AEBaseTileBlock implements ICustomCollision { + public BlockCharger() { + super(Material.iron); + this.setTileEntity(TileCharger.class); + this.setLightOpacity(2); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.Core)); + } -public class BlockCharger extends AEBaseTileBlock implements ICustomCollision -{ + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockCharger getRenderer() { + return new RenderBlockCharger(); + } - public BlockCharger() - { - super( Material.iron ); + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (player.isSneaking()) { + return false; + } - this.setTileEntity( TileCharger.class ); - this.setLightOpacity( 2 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + if (Platform.isServer()) { + final TileCharger tc = this.getTileEntity(w, x, y, z); + if (tc != null) { + tc.activate(player); + } + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockCharger getRenderer() - { - return new RenderBlockCharger(); - } + return true; + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World w, final int x, final int y, final int z, final Random r + ) { + if (!AEConfig.instance.enableEffects) { + return; + } - if( Platform.isServer() ) - { - final TileCharger tc = this.getTileEntity( w, x, y, z ); - if( tc != null ) - { - tc.activate( player ); - } - } + if (r.nextFloat() < 0.98) { + return; + } - return true; - } + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + if (tile instanceof TileCharger) { + final TileCharger tc = (TileCharger) tile; - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } + if (AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .isSameAs(tc.getStackInSlot(0))) { + final double xOff = 0.0; + final double yOff = 0.0; + final double zOff = 0.0; - if( r.nextFloat() < 0.98 ) - { - return; - } + for (int bolts = 0; bolts < 3; bolts++) { + if (CommonHelper.proxy.shouldAddParticles(r)) { + final 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); + } + } + } + } + } - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if( tile instanceof TileCharger ) - { - final TileCharger tc = (TileCharger) tile; + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + final TileCharger tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final double twoPixels = 2.0 / 16.0; + final ForgeDirection up = tile.getUp(); + final ForgeDirection forward = tile.getForward(); + final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( + twoPixels, + twoPixels, + twoPixels, + 1.0 - twoPixels, + 1.0 - twoPixels, + 1.0 - twoPixels + ); - if( AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( tc.getStackInSlot( 0 ) ) ) - { - final double xOff = 0.0; - final double yOff = 0.0; - final double zOff = 0.0; + if (up.offsetX != 0) { + bb.minX = 0; + bb.maxX = 1; + } + if (up.offsetY != 0) { + bb.minY = 0; + bb.maxY = 1; + } + if (up.offsetZ != 0) { + bb.minZ = 0; + bb.maxZ = 1; + } - for( int bolts = 0; bolts < 3; bolts++ ) - { - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final 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 ); - } - } - } - } - } + 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; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final TileCharger tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final double twoPixels = 2.0 / 16.0; - final ForgeDirection up = tile.getUp(); - final ForgeDirection forward = tile.getForward(); - final AxisAlignedBB bb = AxisAlignedBB.getBoundingBox( twoPixels, twoPixels, twoPixels, 1.0 - twoPixels, 1.0 - twoPixels, 1.0 - twoPixels ); + return Collections.singletonList(bb); + } + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(0.0, 0, 0.0, 1.0, 1.0, 1.0) + ); + } - if( up.offsetX != 0 ) - { - bb.minX = 0; - bb.maxX = 1; - } - if( up.offsetY != 0 ) - { - bb.minY = 0; - bb.maxY = 1; - } - if( up.offsetZ != 0 ) - { - bb.minZ = 0; - bb.maxZ = 1; - } - - 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; - } - - return Collections.singletonList( bb ); - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final 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 c8f1785a..cbd9aeba 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 appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; @@ -29,38 +30,43 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockCondenser extends AEBaseTileBlock { + public BlockCondenser() { + super(Material.iron); + this.setTileEntity(TileCondenser.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } -public class BlockCondenser extends AEBaseTileBlock -{ + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (player.isSneaking()) { + return false; + } - public BlockCondenser() - { - super( Material.iron ); + if (Platform.isServer()) { + final TileCondenser tc = this.getTileEntity(w, x, y, z); + if (tc != null && !player.isSneaking()) { + Platform.openGUI( + player, + tc, + ForgeDirection.getOrientation(side), + GuiBridge.GUI_CONDENSER + ); + return true; + } + } - this.setTileEntity( TileCondenser.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } - - if( Platform.isServer() ) - { - final TileCondenser tc = this.getTileEntity( w, x, y, z ); - if( tc != null && !player.isSneaking() ) - { - Platform.openGUI( player, tc, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CONDENSER ); - return true; - } - } - - 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 84afe2dc..46261de9 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 appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockInscriber; @@ -32,46 +33,47 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockInscriber extends AEBaseTileBlock { + public BlockInscriber() { + super(Material.iron); + this.setTileEntity(TileInscriber.class); + this.setLightOpacity(2); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.Inscriber)); + } -public class BlockInscriber extends AEBaseTileBlock -{ + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockInscriber getRenderer() { + return new RenderBlockInscriber(); + } - public BlockInscriber() - { - super( Material.iron ); + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - this.setTileEntity( TileInscriber.class ); - this.setLightOpacity( 2 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.Inscriber ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockInscriber getRenderer() - { - return new RenderBlockInscriber(); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final TileInscriber tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_INSCRIBER ); - } - return true; - } - return false; - } + final TileInscriber tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + 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 2fa5c0b9..7cd00055 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 appeng.api.util.IOrientable; import appeng.block.AEBaseTileBlock; @@ -33,59 +34,58 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockInterface extends AEBaseTileBlock { + public BlockInterface() { + super(Material.iron); + this.setTileEntity(TileInterface.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } -public class BlockInterface extends AEBaseTileBlock -{ + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockInterface getRenderer() { + return new RenderBlockInterface(); + } - public BlockInterface() - { - super( Material.iron ); + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - this.setTileEntity( TileInterface.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + final 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 - @SideOnly( Side.CLIENT ) - protected RenderBlockInterface getRenderer() - { - return new RenderBlockInterface(); - } + @Override + protected boolean hasCustomRotation() { + return true; + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final 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() - { - return true; - } - - @Override - protected void customRotateBlock( final IOrientable rotatable, final ForgeDirection axis ) - { - if( rotatable instanceof TileInterface ) - { - ( (TileInterface) rotatable ).setSide( axis ); - } - } + @Override + protected void + customRotateBlock(final IOrientable rotatable, final ForgeDirection axis) { + if (rotatable instanceof TileInterface) { + ((TileInterface) rotatable).setSide(axis); + } + } } diff --git a/src/main/java/appeng/block/misc/BlockLightDetector.java b/src/main/java/appeng/block/misc/BlockLightDetector.java index 79e16ebe..1ae099ba 100644 --- a/src/main/java/appeng/block/misc/BlockLightDetector.java +++ b/src/main/java/appeng/block/misc/BlockLightDetector.java @@ -18,6 +18,10 @@ package appeng.block.misc; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; @@ -37,133 +41,153 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; +public class BlockLightDetector + extends AEBaseTileBlock implements IOrientableBlock, ICustomCollision { + public BlockLightDetector() { + super(Material.circuits); + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; -public class BlockLightDetector extends AEBaseTileBlock implements IOrientableBlock, ICustomCollision -{ + this.setTileEntity(TileLightDetector.class); + this.setFeature(EnumSet.of(AEFeature.LightDetector)); + } - public BlockLightDetector() - { - super( Material.circuits ); + @Override + public int isProvidingWeakPower( + final IBlockAccess w, final int x, final int y, final int z, final int side + ) { + if (w instanceof World + && ((TileLightDetector) this.getTileEntity(w, x, y, z)).isReady()) { + return ((World) w).getBlockLightValue(x, y, z) - 6; + } - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; + return 0; + } - this.setTileEntity( TileLightDetector.class ); - this.setFeature( EnumSet.of( AEFeature.LightDetector ) ); - } + @Override + public void onNeighborChange( + final IBlockAccess world, + final int x, + final int y, + final int z, + final int tileX, + final int tileY, + final int tileZ + ) { + super.onNeighborChange(world, x, y, z, tileX, tileY, tileZ); - @Override - public int isProvidingWeakPower( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - if( w instanceof World && ( (TileLightDetector) this.getTileEntity( w, x, y, z ) ).isReady() ) - { - return ( (World) w ).getBlockLightValue( x, y, z ) - 6; - } + final TileLightDetector tld = this.getTileEntity(world, x, y, z); + if (tld != null) { + tld.updateLight(); + } + } - return 0; - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World w, final int x, final int y, final int z, final Random r + ) { + // cancel out lightning + } - @Override - public void onNeighborChange( final IBlockAccess world, final int x, final int y, final int z, final int tileX, final int tileY, final int tileZ ) - { - super.onNeighborChange( world, x, y, z, tileX, tileY, tileZ ); + @Override + @SideOnly(Side.CLIENT) + protected RenderQuartzTorch getRenderer() { + return new RenderQuartzTorch(); + } - final TileLightDetector tld = this.getTileEntity( world, x, y, z ); - if( tld != null ) - { - tld.updateLight(); - } - } + @Override + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up + ) { + return this.canPlaceAt(w, x, y, z, up.getOpposite()); + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - // cancel out lightning - } + private boolean canPlaceAt( + final World w, final int x, final int y, final int z, final ForgeDirection dir + ) { + return w.isSideSolid( + x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false + ); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderQuartzTorch getRenderer() - { - return new RenderQuartzTorch(); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 + )); + } - @Override - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - return this.canPlaceAt( w, x, y, z, up.getOpposite() ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final 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 + * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, + * zOff + (double) z + 0.85 ) ); + */ + } - private boolean canPlaceAt( final World w, final int x, final int y, final int z, final ForgeDirection dir ) - { - return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); - } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block id + ) { + final 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( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ) ); - } + private void dropTorch(final World w, final int x, final int y, final int z) { + w.func_147480_a(x, y, z, true); + // w.destroyBlock( x, y, z, true ); + w.markBlockForUpdate(x, y, z); + } - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final 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 - * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); - */ - } + @Override + public boolean canPlaceBlockAt(final World w, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.canPlaceAt(w, x, y, z, dir)) { + return true; + } + } + return false; + } - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - final 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 boolean usesMetadata() { + return true; + } - private void dropTorch( final World w, final int x, final int y, final 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( final World w, final int x, final int y, final int z ) - { - for( final 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 ); - } + @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/BlockPaint.java b/src/main/java/appeng/block/misc/BlockPaint.java index f80173f5..e1aa5015 100644 --- a/src/main/java/appeng/block/misc/BlockPaint.java +++ b/src/main/java/appeng/block/misc/BlockPaint.java @@ -18,6 +18,9 @@ package appeng.block.misc; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockPaint; @@ -36,105 +39,99 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; +public class BlockPaint extends AEBaseTileBlock { + public BlockPaint() { + super(new MaterialLiquid(MapColor.airColor)); + this.setTileEntity(TilePaint.class); + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.PaintBalls)); + } -public class BlockPaint extends AEBaseTileBlock -{ + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockPaint getRenderer() { + return new RenderBlockPaint(); + } - public BlockPaint() - { - super( new MaterialLiquid( MapColor.airColor ) ); + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + // do nothing + } - this.setTileEntity( TilePaint.class ); - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.PaintBalls ) ); - } + @Override + public AxisAlignedBB getCollisionBoundingBoxFromPool( + final World world, final int x, final int y, final int z + ) { + return null; + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockPaint getRenderer() - { - return new RenderBlockPaint(); - } + @Override + public boolean + canCollideCheck(final int metadata, final boolean isHoldingRightClick) { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - // do nothing - } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block junk + ) { + final TilePaint tp = this.getTileEntity(w, x, y, z); - @Override - public AxisAlignedBB getCollisionBoundingBoxFromPool( final World world, final int x, final int y, final int z ) - { - return null; - } + if (tp != null) { + tp.onNeighborBlockChange(); + } + } - @Override - public boolean canCollideCheck( final int metadata, final boolean isHoldingRightClick ) - { - return false; - } + @Override + public Item getItemDropped(final int meta, final Random random, final int fortune) { + return null; + } - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TilePaint tp = this.getTileEntity( w, x, y, z ); + @Override + public void dropBlockAsItemWithChance( + final World world, + final int x, + final int y, + final int z, + final int meta, + final float chance, + final int fortune + ) {} - if( tp != null ) - { - tp.onNeighborBlockChange(); - } - } + @Override + public void fillWithRain(final World w, final int x, final int y, final int z) { + if (Platform.isServer()) { + w.setBlock(x, y, z, Platform.AIR_BLOCK, 0, 3); + } + } - @Override - public Item getItemDropped( final int meta, final Random random, final int fortune ) - { - return null; - } + @Override + public int + getLightValue(final IBlockAccess w, final int x, final int y, final int z) { + final TilePaint tp = this.getTileEntity(w, x, y, z); - @Override - public void dropBlockAsItemWithChance( final World world, final int x, final int y, final int z, final int meta, final float chance, final int fortune ) - { + if (tp != null) { + return tp.getLightLevel(); + } - } + return 0; + } - @Override - public void fillWithRain( final World w, final int x, final int y, final int z ) - { - if( Platform.isServer() ) - { - w.setBlock( x, y, z, Platform.AIR_BLOCK, 0, 3 ); - } - } + @Override + public boolean + isReplaceable(final IBlockAccess world, final int x, final int y, final int z) { + return true; + } - @Override - public int getLightValue( final IBlockAccess w, final int x, final int y, final int z ) - { - final TilePaint tp = this.getTileEntity( w, x, y, z ); - - if( tp != null ) - { - return tp.getLightLevel(); - } - - return 0; - } - - @Override - public boolean isReplaceable( final IBlockAccess world, final int x, final int y, final int z ) - { - return true; - } - - @Override - public boolean isAir( final IBlockAccess world, final int x, final int y, final int z ) - { - return true; - } + @Override + public boolean + isAir(final IBlockAccess world, final int x, final int y, final 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 3fcb1b9d..d15c67b6 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java +++ b/src/main/java/appeng/block/misc/BlockQuartzGrowthAccelerator.java @@ -18,6 +18,8 @@ package appeng.block.misc; +import java.util.EnumSet; +import java.util.Random; import appeng.api.util.IOrientableBlock; import appeng.block.AEBaseTileBlock; @@ -36,116 +38,128 @@ import net.minecraft.client.Minecraft; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; +public class BlockQuartzGrowthAccelerator + extends AEBaseTileBlock implements IOrientableBlock { + public BlockQuartzGrowthAccelerator() { + super(Material.rock); + this.setStepSound(Block.soundTypeMetal); + this.setTileEntity(TileQuartzGrowthAccelerator.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockQuartzAccelerator getRenderer() { + return new RenderBlockQuartzAccelerator(); + } -public class BlockQuartzGrowthAccelerator extends AEBaseTileBlock implements IOrientableBlock -{ + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World w, final int x, final int y, final int z, final Random r + ) { + if (!AEConfig.instance.enableEffects) { + return; + } - public BlockQuartzGrowthAccelerator() - { - super( Material.rock ); - this.setStepSound( Block.soundTypeMetal ); - this.setTileEntity( TileQuartzGrowthAccelerator.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + final TileQuartzGrowthAccelerator cga = this.getTileEntity(w, x, y, z); - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockQuartzAccelerator getRenderer() - { - return new RenderBlockQuartzAccelerator(); - } + if (cga != null && cga.isPowered() && CommonHelper.proxy.shouldAddParticles(r)) { + final double d0 = r.nextFloat() - 0.5F; + final double d1 = r.nextFloat() - 0.5F; - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } + final ForgeDirection up = cga.getUp(); + final ForgeDirection forward = cga.getForward(); + final ForgeDirection west = Platform.crossProduct(forward, up); - final TileQuartzGrowthAccelerator cga = this.getTileEntity( w, x, y, z ); + double rx = 0.5 + x; + double ry = 0.5 + y; + double rz = 0.5 + z; - if( cga != null && cga.isPowered() && CommonHelper.proxy.shouldAddParticles( r ) ) - { - final double d0 = r.nextFloat() - 0.5F; - final double d1 = r.nextFloat() - 0.5F; + rx += up.offsetX * d0; + ry += up.offsetY * d0; + rz += up.offsetZ * d0; - final ForgeDirection up = cga.getUp(); - final ForgeDirection forward = cga.getForward(); - final ForgeDirection west = Platform.crossProduct( forward, up ); + double dz = 0; + double dx = 0; + 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; + } - double rx = 0.5 + x; - double ry = 0.5 + y; - double rz = 0.5 + z; + rx += dx * west.offsetX; + ry += dx * west.offsetY; + rz += dx * west.offsetZ; - rx += up.offsetX * d0; - ry += up.offsetY * d0; - rz += up.offsetZ * d0; + rx += dz * forward.offsetX; + ry += dz * forward.offsetY; + rz += dz * forward.offsetZ; - double dz = 0; - double dx = 0; - 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; - } + final LightningFX fx = new LightningFX(w, rx, ry, rz, 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } - rx += dx * west.offsetX; - ry += dx * west.offsetY; - rz += dx * west.offsetZ; - - rx += dz * forward.offsetX; - ry += dz * forward.offsetY; - rz += dz * forward.offsetZ; - - final LightningFX fx = new LightningFX( w, rx, ry, rz, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - - @Override - /** - * TODO: remove with 1.8 or later - * - * @Deprecated no longer true, only kept to prevent missing blocks. - */ - @Deprecated - public boolean usesMetadata() - { - return true; - } + @Override + /** + * TODO: remove with 1.8 or later + * + * @Deprecated no longer true, only kept to prevent missing blocks. + */ + @Deprecated + public boolean usesMetadata() { + return true; + } } diff --git a/src/main/java/appeng/block/misc/BlockQuartzTorch.java b/src/main/java/appeng/block/misc/BlockQuartzTorch.java index ff164a28..2e63a09f 100644 --- a/src/main/java/appeng/block/misc/BlockQuartzTorch.java +++ b/src/main/java/appeng/block/misc/BlockQuartzTorch.java @@ -18,6 +18,10 @@ package appeng.block.misc; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; @@ -40,130 +44,142 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; +public class BlockQuartzTorch + extends AEBaseBlock implements IOrientableBlock, ICustomCollision { + public BlockQuartzTorch() { + super(Material.circuits); + this.setFeature(EnumSet.of(AEFeature.DecorativeLights)); + this.setLightLevel(0.9375F); + this.setLightOpacity(0); + this.isFullSize = false; + this.isOpaque = false; + } -public class BlockQuartzTorch extends AEBaseBlock implements IOrientableBlock, ICustomCollision -{ - public BlockQuartzTorch() - { - super( Material.circuits ); + @Override + @SideOnly(Side.CLIENT) + protected RenderQuartzTorch getRenderer() { + return new RenderQuartzTorch(); + } - this.setFeature( EnumSet.of( AEFeature.DecorativeLights ) ); - this.setLightLevel( 0.9375F ); - this.setLightOpacity( 0 ); - this.isFullSize = false; - this.isOpaque = false; - } + @Override + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up + ) { + return this.canPlaceAt(w, x, y, z, up.getOpposite()); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderQuartzTorch getRenderer() - { - return new RenderQuartzTorch(); - } + private boolean canPlaceAt( + final World w, final int x, final int y, final int z, final ForgeDirection dir + ) { + return w.isSideSolid( + x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false + ); + } - @Override - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - return this.canPlaceAt( w, x, y, z, up.getOpposite() ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 + )); + } - private boolean canPlaceAt( final World w, final int x, final int y, final int z, final ForgeDirection dir ) - { - return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final 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 + * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, + * zOff + (double) z + 0.85 ) ); + */ + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World w, final int x, final int y, final int z, final Random r + ) { + if (!AEConfig.instance.enableEffects) { + return; + } - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final 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 - * + (double) z + 0.15,// ahh xOff + (double) x + 0.85, yOff + (double) y + 0.85, zOff + (double) z + 0.85 ) ); - */ - } + if (r.nextFloat() < 0.98) { + return; + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + for (int bolts = 0; bolts < 3; bolts++) { + if (CommonHelper.proxy.shouldAddParticles(r)) { + final LightningFX fx = new LightningFX( + w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D + ); - if( r.nextFloat() < 0.98 ) - { - return; - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } + } - final ForgeDirection up = this.getOrientable( w, x, y, z ).getUp(); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - for( int bolts = 0; bolts < 3; bolts++ ) - { - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final LightningFX fx = new LightningFX( w, xOff + 0.5 + x, yOff + 0.5 + y, zOff + 0.5 + z, 0.0D, 0.0D, 0.0D ); + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block id + ) { + final ForgeDirection up = this.getOrientable(w, x, y, z).getUp(); + if (!this.canPlaceAt(w, x, y, z, up.getOpposite())) { + this.dropTorch(w, x, y, z); + } + } - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - } + private void dropTorch(final World w, final int x, final int y, final int z) { + w.func_147480_a(x, y, z, true); + // w.destroyBlock( x, y, z, true ); + w.markBlockForUpdate(x, y, z); + } - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - final 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 boolean canPlaceBlockAt(final World w, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.canPlaceAt(w, x, y, z, dir)) { + return true; + } + } + return false; + } - private void dropTorch( final World w, final int x, final int y, final int z ) - { - w.func_147480_a( x, y, z, true ); - // w.destroyBlock( x, y, z, true ); - w.markBlockForUpdate( x, y, z ); - } + @Override + public boolean usesMetadata() { + return true; + } - @Override - public boolean canPlaceBlockAt( final World w, final int x, final int y, final int z ) - { - for( final 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 ); - } + @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 38f6088c..3c4322b7 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 appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RendererSecurity; @@ -32,46 +33,47 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockSecurity extends AEBaseTileBlock { + public BlockSecurity() { + super(Material.iron); + this.setTileEntity(TileSecurity.class); + this.setFeature(EnumSet.of(AEFeature.Security)); + } -public class BlockSecurity extends AEBaseTileBlock -{ + @Override + @SideOnly(Side.CLIENT) + protected RendererSecurity getRenderer() { + return new RendererSecurity(); + } - public BlockSecurity() - { - super( Material.iron ); + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - this.setTileEntity( TileSecurity.class ); - this.setFeature( EnumSet.of( AEFeature.Security ) ); - } + final TileSecurity tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isClient()) { + return true; + } - @Override - @SideOnly( Side.CLIENT ) - protected RendererSecurity getRenderer() - { - return new RendererSecurity(); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final TileSecurity tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_SECURITY ); - return true; - } - return false; - } + 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 4a1739c5..81fecb99 100644 --- a/src/main/java/appeng/block/misc/BlockSkyCompass.java +++ b/src/main/java/appeng/block/misc/BlockSkyCompass.java @@ -18,6 +18,9 @@ package appeng.block.misc; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockSkyCompass; @@ -36,155 +39,161 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; +public class BlockSkyCompass extends AEBaseTileBlock implements ICustomCollision { + public BlockSkyCompass() { + super(Material.iron); + this.setTileEntity(TileSkyCompass.class); + this.isOpaque = this.isFullSize = false; + this.lightOpacity = 0; + this.setFeature(EnumSet.of(AEFeature.MeteoriteCompass)); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockSkyCompass getRenderer() { + return new RenderBlockSkyCompass(); + } -public class BlockSkyCompass extends AEBaseTileBlock implements ICustomCollision -{ + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final int metadata) { + return Blocks.iron_block.getIcon(direction, metadata); + } - public BlockSkyCompass() - { - super( Material.iron ); - this.setTileEntity( TileSkyCompass.class ); - this.isOpaque = this.isFullSize = false; - this.lightOpacity = 0; - this.setFeature( EnumSet.of( AEFeature.MeteoriteCompass ) ); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + // :P + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockSkyCompass getRenderer() - { - return new RenderBlockSkyCompass(); - } + @Override + public boolean isValidOrientation( + final World w, + final int x, + final int y, + final int z, + final ForgeDirection forward, + final ForgeDirection up + ) { + final TileSkyCompass sc = this.getTileEntity(w, x, y, z); + if (sc != null) { + return false; + } + return this.canPlaceAt(w, x, y, z, forward.getOpposite()); + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final int metadata ) - { - return Blocks.iron_block.getIcon( direction, metadata ); - } + private boolean canPlaceAt( + final World w, final int x, final int y, final int z, final ForgeDirection dir + ) { + return w.isSideSolid( + x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false + ); + } - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - // :P - } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block id + ) { + final TileSkyCompass sc = this.getTileEntity(w, x, y, z); + final ForgeDirection up = sc.getForward(); + if (!this.canPlaceAt(w, x, y, z, up.getOpposite())) { + this.dropTorch(w, x, y, z); + } + } - @Override - public boolean isValidOrientation( final World w, final int x, final int y, final int z, final ForgeDirection forward, final ForgeDirection up ) - { - final TileSkyCompass sc = this.getTileEntity( w, x, y, z ); - if( sc != null ) - { - return false; - } - return this.canPlaceAt( w, x, y, z, forward.getOpposite() ); - } + private void dropTorch(final World w, final int x, final int y, final int z) { + w.func_147480_a(x, y, z, true); + // w.destroyBlock( x, y, z, true ); + w.markBlockForUpdate(x, y, z); + } - private boolean canPlaceAt( final World w, final int x, final int y, final int z, final ForgeDirection dir ) - { - return w.isSideSolid( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ, dir.getOpposite(), false ); - } + @Override + public boolean canPlaceBlockAt(final World w, final int x, final int y, final int z) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + if (this.canPlaceAt(w, x, y, z, dir)) { + return true; + } + } + return false; + } - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - final TileSkyCompass sc = this.getTileEntity( w, x, y, z ); - final ForgeDirection up = sc.getForward(); - if( !this.canPlaceAt( w, x, y, z, up.getOpposite() ) ) - { - this.dropTorch( w, x, y, z ); - } - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + final TileSkyCompass tile = this.getTileEntity(w, x, y, z); + if (tile != null) { + final ForgeDirection forward = tile.getForward(); - private void dropTorch( final World w, final int x, final int y, final int z ) - { - w.func_147480_a( x, y, z, true ); - // w.destroyBlock( x, y, z, true ); - w.markBlockForUpdate( x, y, z ); - } + double minX = 0; + double minY = 0; + double minZ = 0; + double maxX = 1; + double maxY = 1; + double maxZ = 1; - @Override - public boolean canPlaceBlockAt( final World w, final int x, final int y, final int z ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.canPlaceAt( w, x, y, z, dir ) ) - { - return true; - } - } - return false; - } + 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; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final TileSkyCompass tile = this.getTileEntity( w, x, y, z ); - if( tile != null ) - { - final ForgeDirection forward = tile.getForward(); + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ) + ); + } + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(0.0, 0, 0.0, 1.0, 1.0, 1.0) + ); + } - double minX = 0; - double minY = 0; - double minZ = 0; - double maxX = 1; - double maxY = 1; - double maxZ = 1; - - 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; - } - - return Collections.singletonList( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.0, 0, 0.0, 1.0, 1.0, 1.0 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) {} } diff --git a/src/main/java/appeng/block/misc/BlockTinyTNT.java b/src/main/java/appeng/block/misc/BlockTinyTNT.java index c7648d14..bd1d8e7d 100644 --- a/src/main/java/appeng/block/misc/BlockTinyTNT.java +++ b/src/main/java/appeng/block/misc/BlockTinyTNT.java @@ -18,6 +18,9 @@ package appeng.block.misc; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import appeng.block.AEBaseBlock; import appeng.client.render.blocks.RenderTinyTNT; @@ -47,141 +50,175 @@ import net.minecraft.util.IIcon; import net.minecraft.world.Explosion; import net.minecraft.world.World; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; +public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision { + public BlockTinyTNT() { + super(Material.tnt); + this.setLightOpacity(1); + this.setBlockBounds(0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f); + this.isFullSize = this.isOpaque = false; + this.setStepSound(soundTypeGrass); + this.setHardness(0F); + this.setFeature(EnumSet.of(AEFeature.TinyTNT)); + EntityRegistry.registerModEntity( + EntityTinyTNTPrimed.class, + "EntityTinyTNTPrimed", + EntityIds.get(EntityTinyTNTPrimed.class), + AppEng.instance(), + 16, + 4, + true + ); + } -public class BlockTinyTNT extends AEBaseBlock implements ICustomCollision -{ + @Override + @SideOnly(Side.CLIENT) + protected RenderTinyTNT getRenderer() { + return new RenderTinyTNT(); + } - public BlockTinyTNT() - { - super( Material.tnt ); - this.setLightOpacity( 1 ); - this.setBlockBounds( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); - this.isFullSize = this.isOpaque = false; - this.setStepSound( soundTypeGrass ); - this.setHardness( 0F ); - this.setFeature( EnumSet.of( AEFeature.TinyTNT ) ); + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject( + Item.getItemFromBlock(this), new DispenserBehaviorTinyTNT() + ); + } - EntityRegistry.registerModEntity( EntityTinyTNTPrimed.class, "EntityTinyTNTPrimed", EntityIds.get( EntityTinyTNTPrimed.class ), AppEng.instance(), 16, 4, true ); - } + @Override + public IIcon getIcon(final int direction, final int metadata) { + return new FullIcon(Blocks.tnt.getIcon(direction, metadata)); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderTinyTNT getRenderer() - { - return new RenderTinyTNT(); - } + @Override + public boolean onBlockActivated( + 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) { + this.startFuse(w, x, y, z, player); + w.setBlockToAir(x, y, z); + player.getCurrentEquippedItem().damageItem(1, player); - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( Item.getItemFromBlock( this ), new DispenserBehaviorTinyTNT() ); - } + return true; + } - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - return new FullIcon( Blocks.tnt.getIcon( direction, metadata ) ); - } + return super.onBlockActivated(w, x, y, z, player, side, hitX, hitY, hitZ); + } - @Override - public boolean onBlockActivated( 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 ) - { - this.startFuse( w, x, y, z, player ); - w.setBlockToAir( x, y, z ); - player.getCurrentEquippedItem().damageItem( 1, player ); + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + // no images required. + } - return true; - } + @Override + public void onBlockAdded(final World w, final int x, final int y, final int z) { + super.onBlockAdded(w, x, y, z); - return super.onBlockActivated( w, x, y, z, player, side, hitX, hitY, hitZ ); - } + if (w.isBlockIndirectlyGettingPowered(x, y, z)) { + this.startFuse(w, x, y, z, null); + w.setBlockToAir(x, y, z); + } + } - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - // no images required. - } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block id + ) { + if (w.isBlockIndirectlyGettingPowered(x, y, z)) { + this.startFuse(w, x, y, z, null); + w.setBlockToAir(x, y, z); + } + } - @Override - public void onBlockAdded( final World w, final int x, final int y, final int z ) - { - super.onBlockAdded( w, x, y, z ); + @Override + public void onBlockDestroyedByExplosion( + final World w, final int x, final int y, final int z, final Explosion exp + ) { + if (!w.isRemote) { + final 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); + } + } - if( w.isBlockIndirectlyGettingPowered( x, y, z ) ) - { - this.startFuse( w, x, y, z, null ); - w.setBlockToAir( x, y, z ); - } - } + @Override + public void onEntityCollidedWithBlock( + final World w, final int x, final int y, final int z, final Entity entity + ) { + if (entity instanceof EntityArrow && !w.isRemote) { + final EntityArrow entityarrow = (EntityArrow) entity; - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block id ) - { - if( w.isBlockIndirectlyGettingPowered( x, y, z ) ) - { - this.startFuse( w, x, y, z, null ); - w.setBlockToAir( x, y, z ); - } - } + 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 onBlockDestroyedByExplosion( final World w, final int x, final int y, final int z, final Explosion exp ) - { - if( !w.isRemote ) - { - final 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 boolean canDropFromExplosion(final Explosion exp) { + return false; + } - @Override - public void onEntityCollidedWithBlock( final World w, final int x, final int y, final int z, final Entity entity ) - { - if( entity instanceof EntityArrow && !w.isRemote ) - { - final EntityArrow entityarrow = (EntityArrow) entity; + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + return Collections.singletonList( + AxisAlignedBB.getBoundingBox(0.25, 0, 0.25, 0.75, 0.5, 0.75) + ); + } - 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 addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + out.add(AxisAlignedBB.getBoundingBox(0.25, 0, 0.25, 0.75, 0.5, 0.75)); + } - @Override - public boolean canDropFromExplosion( final Explosion exp ) - { - return false; - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - return Collections.singletonList( AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) ); - } - - public void startFuse( final World w, final int x, final int y, final int z, final EntityLivingBase igniter ) - { - if( !w.isRemote ) - { - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( w, x + 0.5F, y + 0.5F, z + 0.5F, igniter ); - w.spawnEntityInWorld( primedTinyTNTEntity ); - w.playSoundAtEntity( primedTinyTNTEntity, "game.tnt.primed", 1.0F, 1.0F ); - } - } + public void startFuse( + final World w, + final int x, + final int y, + final int z, + final EntityLivingBase igniter + ) { + if (!w.isRemote) { + final EntityTinyTNTPrimed primedTinyTNTEntity + = new EntityTinyTNTPrimed(w, x + 0.5F, y + 0.5F, z + 0.5F, igniter); + w.spawnEntityInWorld(primedTinyTNTEntity); + w.playSoundAtEntity(primedTinyTNTEntity, "game.tnt.primed", 1.0F, 1.0F); + } + } } diff --git a/src/main/java/appeng/block/misc/BlockVibrationChamber.java b/src/main/java/appeng/block/misc/BlockVibrationChamber.java index b1b7aaa1..beacac32 100644 --- a/src/main/java/appeng/block/misc/BlockVibrationChamber.java +++ b/src/main/java/appeng/block/misc/BlockVibrationChamber.java @@ -18,6 +18,8 @@ package appeng.block.misc; +import java.util.EnumSet; +import java.util.Random; import appeng.block.AEBaseTileBlock; import appeng.client.texture.ExtraBlockTextures; @@ -34,99 +36,104 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; +public final class BlockVibrationChamber extends AEBaseTileBlock { + public BlockVibrationChamber() { + super(Material.iron); + this.setTileEntity(TileVibrationChamber.class); + this.setHardness(4.2F); + this.setFeature(EnumSet.of(AEFeature.PowerGen)); + } + @Override + public IIcon + getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + final IIcon ico = super.getIcon(w, x, y, z, s); + final TileVibrationChamber tvc = this.getTileEntity(w, x, y, z); -public final class BlockVibrationChamber extends AEBaseTileBlock -{ + if (tvc != null && tvc.isOn + && ico == this.getRendererInstance().getTexture(ForgeDirection.SOUTH)) { + return ExtraBlockTextures.BlockVibrationChamberFrontOn.getIcon(); + } - public BlockVibrationChamber() - { - super( Material.iron ); - this.setTileEntity( TileVibrationChamber.class ); - this.setHardness( 4.2F ); - this.setFeature( EnumSet.of( AEFeature.PowerGen ) ); - } + return ico; + } - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - final IIcon ico = super.getIcon( w, x, y, z, s ); - final TileVibrationChamber tvc = this.getTileEntity( w, x, y, z ); + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (player.isSneaking()) { + return false; + } - if( tvc != null && tvc.isOn && ico == this.getRendererInstance().getTexture( ForgeDirection.SOUTH ) ) - { - return ExtraBlockTextures.BlockVibrationChamberFrontOn.getIcon(); - } + if (Platform.isServer()) { + final TileVibrationChamber tc = this.getTileEntity(w, x, y, z); + if (tc != null && !player.isSneaking()) { + Platform.openGUI( + player, + tc, + ForgeDirection.getOrientation(side), + GuiBridge.GUI_VIBRATION_CHAMBER + ); + return true; + } + } - return ico; - } + return true; + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( player.isSneaking() ) - { - return false; - } + @Override + public void randomDisplayTick( + final World w, final int x, final int y, final int z, final Random r + ) { + if (!AEConfig.instance.enableEffects) { + return; + } - if( Platform.isServer() ) - { - final TileVibrationChamber tc = this.getTileEntity( w, x, y, z ); - if( tc != null && !player.isSneaking() ) - { - Platform.openGUI( player, tc, ForgeDirection.getOrientation( side ), GuiBridge.GUI_VIBRATION_CHAMBER ); - return true; - } - } + final AEBaseTile tile = this.getTileEntity(w, x, y, z); + if (tile instanceof TileVibrationChamber) { + final TileVibrationChamber tc = (TileVibrationChamber) tile; + if (tc.isOn) { + float f1 = x + 0.5F; + float f2 = y + 0.5F; + float f3 = z + 0.5F; - return true; - } + final ForgeDirection forward = tc.getForward(); + final ForgeDirection up = tc.getUp(); - @Override - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } + final int west_x + = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y + = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z + = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - final AEBaseTile tile = this.getTileEntity( w, x, y, z ); - if( tile instanceof TileVibrationChamber ) - { - final TileVibrationChamber tc = (TileVibrationChamber) tile; - if( tc.isOn ) - { - float f1 = x + 0.5F; - float f2 = y + 0.5F; - float f3 = z + 0.5F; + f1 += forward.offsetX * 0.6; + f2 += forward.offsetY * 0.6; + f3 += forward.offsetZ * 0.6; - final ForgeDirection forward = tc.getForward(); - final ForgeDirection up = tc.getUp(); + final float ox = r.nextFloat(); + final float oy = r.nextFloat() * 0.2f; - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + f1 += up.offsetX * (-0.3 + oy); + f2 += up.offsetY * (-0.3 + oy); + f3 += up.offsetZ * (-0.3 + oy); - f1 += forward.offsetX * 0.6; - f2 += forward.offsetY * 0.6; - f3 += forward.offsetZ * 0.6; + f1 += west_x * (0.3 * ox - 0.15); + f2 += west_y * (0.3 * ox - 0.15); + f3 += west_z * (0.3 * ox - 0.15); - final float ox = r.nextFloat(); - final 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 += 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 ); - } - } - } + 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 66b2085a..91743357 100644 --- a/src/main/java/appeng/block/networking/BlockCableBus.java +++ b/src/main/java/appeng/block/networking/BlockCableBus.java @@ -18,6 +18,9 @@ package appeng.block.networking; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; @@ -69,465 +72,522 @@ import net.minecraftforge.common.util.ForgeDirection; import powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection; import powercrystals.minefactoryreloaded.api.rednet.connectivity.RedNetConnectionType; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -@Interface( iface = "powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection", iname = IntegrationType.MFR ) -public class BlockCableBus extends AEBaseTileBlock implements IRedNetConnection -{ - - private static final ICableBusContainer NULL_CABLE_BUS = new NullCableBusContainer(); - private static Class noTesrTile; - private static Class tesrTile; - - /** - * Immibis MB Support. - *

- * It will look for a field named ImmibisMicroblocks_TransformableBlockMarker or - * ImmibisMicroblocks_TransformableTileEntityMarker, modifiers, type, etc can be ignored. - */ - @Reflected - private static final boolean ImmibisMicroblocks_TransformableBlockMarker = true; - - private int myColorMultiplier = 0xffffff; - - public BlockCableBus() - { - super( AEGlassMaterial.INSTANCE ); - this.setLightOpacity( 0 ); - this.isFullSize = this.isOpaque = false; - - // this will actually be overwritten later through setupTile and the combined layers - this.setTileEntity( TileCableBus.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - this.cb( world, x, y, z ).randomDisplayTick( world, x, y, z, r ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block meh ) - { - this.cb( w, x, y, z ).onNeighborChanged(); - } - - @Override - public Item getItemDropped( final int i, final Random r, final int k ) - { - return null; - } - - @Override - public int getRenderBlockPass() - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) - { - return 1; - } - return 0; - } - - @Override - public int colorMultiplier( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.myColorMultiplier; - } - - @Override - public int isProvidingWeakPower( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - return this.cb( w, x, y, z ).isProvidingWeakPower( ForgeDirection.getOrientation( side ).getOpposite() ); - } - - @Override - public boolean canProvidePower() - { - return true; - } - - @Override - public void onEntityCollidedWithBlock( final World w, final int x, final int y, final int z, final Entity e ) - { - this.cb( w, x, y, z ).onEntityCollision( e ); - } - - @Override - public int isProvidingStrongPower( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - return this.cb( w, x, y, z ).isProvidingStrongPower( ForgeDirection.getOrientation( side ).getOpposite() ); - } - - @Override - public int getLightValue( final IBlockAccess world, final int x, final int y, final int z ) - { - final 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( final IBlockAccess world, final int x, final int y, final int z, final EntityLivingBase entity ) - { - return this.cb( world, x, y, z ).isLadder( entity ); - } - - @Override - public boolean isSideSolid( final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection side ) - { - return this.cb( w, x, y, z ).isSolidOnSide( side ); - } - - @Override - public boolean isReplaceable( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.cb( world, x, y, z ).isEmpty(); - } - - @SuppressWarnings( "deprecation" ) - @Override - public boolean removedByPlayer( final World world, final EntityPlayer player, final int x, final int y, final int z ) - { - if( player.capabilities.isCreativeMode ) - { - final 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( final IBlockAccess w, final int x, final int y, final int z, final 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( final int pass ) - { - BusRenderHelper.INSTANCE.setPass( pass ); - - if( AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) - { - return true; - } - - return pass == 0; - } - - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - final Vec3 v3 = target.hitVec.addVector( -x, -y, -z ); - final 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( final World world, final MovingObjectPosition target, final EffectRenderer effectRenderer ) - { - final Object object = this.cb( world, target.blockX, target.blockY, target.blockZ ); - if( object instanceof IPartHost ) - { - final IPartHost host = (IPartHost) object; - - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = host.getPart( side ); - final IIcon ico = this.getIcon( p ); - - if( ico == null ) - { - continue; - } - - final 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 ) - { - final double d0 = target.blockX + ( i1 + 0.5D ) / b0; - final double d1 = target.blockY + ( j1 + 0.5D ) / b0; - final double d2 = target.blockZ + ( k1 + 0.5D ) / b0; - - final double dd0 = target.hitVec.xCoord; - final double dd1 = target.hitVec.yCoord; - final double dd2 = target.hitVec.zCoord; - final 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( final World world, final int x, final int y, final int z, final int meta, final EffectRenderer effectRenderer ) - { - final Object object = this.cb( world, x, y, z ); - if( object instanceof IPartHost ) - { - final IPartHost host = (IPartHost) object; - - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = host.getPart( side ); - final IIcon ico = this.getIcon( p ); - - if( ico == null ) - { - continue; - } - - final byte b0 = 3; - - for( int i1 = 0; i1 < b0; ++i1 ) - { - for( int j1 = 0; j1 < b0; ++j1 ) - { - for( int k1 = 0; k1 < b0; ++k1 ) - { - final double d0 = x + ( i1 + 0.5D ) / b0; - final double d1 = y + ( j1 + 0.5D ) / b0; - final double d2 = z + ( k1 + 0.5D ) / b0; - final 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( final IBlockAccess w, final int x, final int y, final int z, final int tileX, final int tileY, final int tileZ ) - { - if( Platform.isServer() ) - { - this.cb( w, x, y, z ).onNeighborChanged(); - } - } - - private IIcon getIcon( final IPart p ) - { - if( p == null ) - { - return null; - } - - try - { - final IIcon ico = p.getBreakingTexture(); - if( ico != null ) - { - return ico; - } - } - catch( final Throwable t ) - { - // nothing. - } - - final ItemStack is = p.getItemStack( PartItemStack.Network ); - if( is == null || is.getItem() == null ) - { - return null; - } - - return is.getItem().getIcon( is, 0 ); - } - - private ICableBusContainer cb( final IBlockAccess w, final int x, final int y, final int z ) - { - final TileEntity te = w.getTileEntity( x, y, z ); - ICableBusContainer out = null; - - if( te instanceof TileCableBus ) - { - out = ( (TileCableBus) te ).getCableBus(); - } - else if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - out = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getCableContainer( te ); - } - - return out == null ? NULL_CABLE_BUS : out; - } - - @Override - @SideOnly( Side.CLIENT ) - protected RendererCableBus getRenderer() - { - return new RendererCableBus(); - } - - @Override - public IIcon getIcon( final IBlockAccess w, final int x, final int y, final int z, final int s ) - { - return this.getIcon( s, 0 ); - } - - @Override - public IIcon getIcon( final int direction, final int metadata ) - { - final IIcon i = super.getIcon( direction, metadata ); - if( i != null ) - { - return i; - } - - return ExtraBlockTextures.BlockQuartzGlassB.getIcon(); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - return this.cb( w, x, y, z ).activate( player, Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - - } - - @Override - public boolean recolourBlock( final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour ) - { - return this.recolourBlock( world, x, y, z, side, colour, null ); - } - - public boolean recolourBlock( final World world, final int x, final int y, final int z, final ForgeDirection side, final int colour, final EntityPlayer who ) - { - try - { - return this.cb( world, x, y, z ).recolourBlock( side, AEColor.values()[colour], who ); - } - catch( final Throwable ignored ) - { - } - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - // do nothing - } - - @Override - public T getTileEntity( final IBlockAccess w, final int x, final int y, final int z ) - { - final 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; - } - - @Override - protected void setFeature( final EnumSet f ) - { - final AECableBusFeatureHandler featureHandler = new AECableBusFeatureHandler( f, this, this.featureSubName ); - this.setHandler( featureHandler ); - } - - public void setupTile() - { - noTesrTile = Api.INSTANCE.partHelper().getCombinedInstance( TileCableBus.class.getName() ); - this.setTileEntity( noTesrTile ); - GameRegistry.registerTileEntity( noTesrTile, "BlockCableBus" ); - if( Platform.isClient() ) - { - tesrTile = Api.INSTANCE.partHelper().getCombinedInstance( TileCableBusTESR.class.getName() ); - GameRegistry.registerTileEntity( tesrTile, "ClientOnly_TESR_CableBus" ); - CommonHelper.proxy.bindTileEntitySpecialRenderer( tesrTile, this ); - } - } - - @Override - @Method( iname = IntegrationType.MFR ) - public RedNetConnectionType getConnectionType( final World world, final int x, final int y, final int z, final ForgeDirection side ) - { - return this.cb( world, x, y, z ).canConnectRedstone( EnumSet.allOf( ForgeDirection.class ) ) ? RedNetConnectionType.CableSingle : RedNetConnectionType.None; - } - - public void setRenderColor( final int color ) - { - this.myColorMultiplier = color; - } - - public static Class getTesrTile() - { - return BlockCableBus.tesrTile; - } - - public static Class getNoTesrTile() - { - return BlockCableBus.noTesrTile; - } +@Interface( + iface = "powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection", + iname = IntegrationType.MFR +) +public class BlockCableBus extends AEBaseTileBlock implements IRedNetConnection { + private static final ICableBusContainer NULL_CABLE_BUS = new NullCableBusContainer(); + private static Class noTesrTile; + private static Class tesrTile; + + /** + * Immibis MB Support. + *

+ * It will look for a field named ImmibisMicroblocks_TransformableBlockMarker or + * ImmibisMicroblocks_TransformableTileEntityMarker, modifiers, type, etc can be + * ignored. + */ + @Reflected + private static final boolean ImmibisMicroblocks_TransformableBlockMarker = true; + + private int myColorMultiplier = 0xffffff; + + public BlockCableBus() { + super(AEGlassMaterial.INSTANCE); + this.setLightOpacity(0); + this.isFullSize = this.isOpaque = false; + + // this will actually be overwritten later through setupTile and the combined + // layers + this.setTileEntity(TileCableBus.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } + + @Override + public void randomDisplayTick( + final World world, final int x, final int y, final int z, final Random r + ) { + this.cb(world, x, y, z).randomDisplayTick(world, x, y, z, r); + } + + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block meh + ) { + this.cb(w, x, y, z).onNeighborChanged(); + } + + @Override + public Item getItemDropped(final int i, final Random r, final int k) { + return null; + } + + @Override + public int getRenderBlockPass() { + if (AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass)) { + return 1; + } + return 0; + } + + @Override + public int + colorMultiplier(final IBlockAccess world, final int x, final int y, final int z) { + return this.myColorMultiplier; + } + + @Override + public int isProvidingWeakPower( + final IBlockAccess w, final int x, final int y, final int z, final int side + ) { + return this.cb(w, x, y, z) + .isProvidingWeakPower(ForgeDirection.getOrientation(side).getOpposite()); + } + + @Override + public boolean canProvidePower() { + return true; + } + + @Override + public void onEntityCollidedWithBlock( + final World w, final int x, final int y, final int z, final Entity e + ) { + this.cb(w, x, y, z).onEntityCollision(e); + } + + @Override + public int isProvidingStrongPower( + final IBlockAccess w, final int x, final int y, final int z, final int side + ) { + return this.cb(w, x, y, z) + .isProvidingStrongPower(ForgeDirection.getOrientation(side).getOpposite()); + } + + @Override + public int + getLightValue(final IBlockAccess world, final int x, final int y, final int z) { + final 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( + final IBlockAccess world, + final int x, + final int y, + final int z, + final EntityLivingBase entity + ) { + return this.cb(world, x, y, z).isLadder(entity); + } + + @Override + public boolean isSideSolid( + final IBlockAccess w, + final int x, + final int y, + final int z, + final ForgeDirection side + ) { + return this.cb(w, x, y, z).isSolidOnSide(side); + } + + @Override + public boolean + isReplaceable(final IBlockAccess world, final int x, final int y, final int z) { + return this.cb(world, x, y, z).isEmpty(); + } + + @SuppressWarnings("deprecation") + @Override + public boolean removedByPlayer( + final World world, + final EntityPlayer player, + final int x, + final int y, + final int z + ) { + if (player.capabilities.isCreativeMode) { + final 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( + final IBlockAccess w, final int x, final int y, final int z, final 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(final int pass) { + BusRenderHelper.INSTANCE.setPass(pass); + + if (AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass)) { + return true; + } + + return pass == 0; + } + + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player + ) { + final Vec3 v3 = target.hitVec.addVector(-x, -y, -z); + final 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( + final World world, + final MovingObjectPosition target, + final EffectRenderer effectRenderer + ) { + final Object object = this.cb(world, target.blockX, target.blockY, target.blockZ); + if (object instanceof IPartHost) { + final IPartHost host = (IPartHost) object; + + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = host.getPart(side); + final IIcon ico = this.getIcon(p); + + if (ico == null) { + continue; + } + + final 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) { + final double d0 = target.blockX + (i1 + 0.5D) / b0; + final double d1 = target.blockY + (j1 + 0.5D) / b0; + final double d2 = target.blockZ + (k1 + 0.5D) / b0; + + final double dd0 = target.hitVec.xCoord; + final double dd1 = target.hitVec.yCoord; + final double dd2 = target.hitVec.zCoord; + final 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( + final World world, + final int x, + final int y, + final int z, + final int meta, + final EffectRenderer effectRenderer + ) { + final Object object = this.cb(world, x, y, z); + if (object instanceof IPartHost) { + final IPartHost host = (IPartHost) object; + + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = host.getPart(side); + final IIcon ico = this.getIcon(p); + + if (ico == null) { + continue; + } + + final byte b0 = 3; + + for (int i1 = 0; i1 < b0; ++i1) { + for (int j1 = 0; j1 < b0; ++j1) { + for (int k1 = 0; k1 < b0; ++k1) { + final double d0 = x + (i1 + 0.5D) / b0; + final double d1 = y + (j1 + 0.5D) / b0; + final double d2 = z + (k1 + 0.5D) / b0; + final 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( + final IBlockAccess w, + final int x, + final int y, + final int z, + final int tileX, + final int tileY, + final int tileZ + ) { + if (Platform.isServer()) { + this.cb(w, x, y, z).onNeighborChanged(); + } + } + + private IIcon getIcon(final IPart p) { + if (p == null) { + return null; + } + + try { + final IIcon ico = p.getBreakingTexture(); + if (ico != null) { + return ico; + } + } catch (final Throwable t) { + // nothing. + } + + final ItemStack is = p.getItemStack(PartItemStack.Network); + if (is == null || is.getItem() == null) { + return null; + } + + return is.getItem().getIcon(is, 0); + } + + private ICableBusContainer + cb(final IBlockAccess w, final int x, final int y, final int z) { + final TileEntity te = w.getTileEntity(x, y, z); + ICableBusContainer out = null; + + if (te instanceof TileCableBus) { + out = ((TileCableBus) te).getCableBus(); + } else if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + out = ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)) + .getCableContainer(te); + } + + return out == null ? NULL_CABLE_BUS : out; + } + + @Override + @SideOnly(Side.CLIENT) + protected RendererCableBus getRenderer() { + return new RendererCableBus(); + } + + @Override + public IIcon + getIcon(final IBlockAccess w, final int x, final int y, final int z, final int s) { + return this.getIcon(s, 0); + } + + @Override + public IIcon getIcon(final int direction, final int metadata) { + final IIcon i = super.getIcon(direction, metadata); + if (i != null) { + return i; + } + + return ExtraBlockTextures.BlockQuartzGlassB.getIcon(); + } + + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + return this.cb(w, x, y, z) + .activate(player, Vec3.createVectorHelper(hitX, hitY, hitZ)); + } + + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) {} + + @Override + public boolean recolourBlock( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection side, + final int colour + ) { + return this.recolourBlock(world, x, y, z, side, colour, null); + } + + public boolean recolourBlock( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection side, + final int colour, + final EntityPlayer who + ) { + try { + return this.cb(world, x, y, z) + .recolourBlock(side, AEColor.values()[colour], who); + } catch (final Throwable ignored) {} + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + // do nothing + } + + @Override + public + T getTileEntity(final IBlockAccess w, final int x, final int y, final int z) { + final 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; + } + + @Override + protected void setFeature(final EnumSet f) { + final AECableBusFeatureHandler featureHandler + = new AECableBusFeatureHandler(f, this, this.featureSubName); + this.setHandler(featureHandler); + } + + public void setupTile() { + noTesrTile + = Api.INSTANCE.partHelper().getCombinedInstance(TileCableBus.class.getName()); + this.setTileEntity(noTesrTile); + GameRegistry.registerTileEntity(noTesrTile, "BlockCableBus"); + if (Platform.isClient()) { + tesrTile = Api.INSTANCE.partHelper().getCombinedInstance( + TileCableBusTESR.class.getName() + ); + GameRegistry.registerTileEntity(tesrTile, "ClientOnly_TESR_CableBus"); + CommonHelper.proxy.bindTileEntitySpecialRenderer(tesrTile, this); + } + } + + @Override + @Method(iname = IntegrationType.MFR) + public RedNetConnectionType getConnectionType( + final World world, + final int x, + final int y, + final int z, + final ForgeDirection side + ) { + return this.cb(world, x, y, z) + .canConnectRedstone(EnumSet.allOf(ForgeDirection.class)) + ? RedNetConnectionType.CableSingle + : RedNetConnectionType.None; + } + + public void setRenderColor(final int color) { + this.myColorMultiplier = color; + } + + public static Class getTesrTile() { + return BlockCableBus.tesrTile; + } + + public static Class getNoTesrTile() { + return BlockCableBus.noTesrTile; + } } diff --git a/src/main/java/appeng/block/networking/BlockController.java b/src/main/java/appeng/block/networking/BlockController.java index 034c6d41..92c059fc 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 appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderBlockController; @@ -29,34 +30,27 @@ import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.world.World; -import java.util.EnumSet; +public class BlockController extends AEBaseTileBlock { + public BlockController() { + super(Material.iron); + this.setTileEntity(TileController.class); + this.setHardness(6); + this.setFeature(EnumSet.of(AEFeature.Core)); + } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block neighborBlock + ) { + final TileController tc = this.getTileEntity(w, x, y, z); + if (tc != null) { + tc.onNeighborChange(false); + } + } -public class BlockController extends AEBaseTileBlock -{ - - public BlockController() - { - super( Material.iron ); - this.setTileEntity( TileController.class ); - this.setHardness( 6 ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block neighborBlock ) - { - final TileController tc = this.getTileEntity( w, x, y, z ); - if( tc != null ) - { - tc.onNeighborChange( false ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockController getRenderer() - { - return new RenderBlockController(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockController getRenderer() { + return new RenderBlockController(); + } } diff --git a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java index 92f22510..bdddfb45 100644 --- a/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockCreativeEnergyCell.java @@ -18,22 +18,17 @@ package appeng.block.networking; +import java.util.EnumSet; import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.helpers.AEGlassMaterial; import appeng.tile.networking.TileCreativeEnergyCell; -import java.util.EnumSet; - - -public class BlockCreativeEnergyCell extends AEBaseTileBlock -{ - - public BlockCreativeEnergyCell() - { - super( AEGlassMaterial.INSTANCE ); - this.setTileEntity( TileCreativeEnergyCell.class ); - this.setFeature( EnumSet.of( AEFeature.Creative ) ); - } +public class BlockCreativeEnergyCell extends AEBaseTileBlock { + public BlockCreativeEnergyCell() { + super(AEGlassMaterial.INSTANCE); + this.setTileEntity(TileCreativeEnergyCell.class); + this.setFeature(EnumSet.of(AEFeature.Creative)); + } } diff --git a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java index a34f65bf..ad571e0d 100644 --- a/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockDenseEnergyCell.java @@ -18,52 +18,44 @@ package appeng.block.networking; +import java.util.EnumSet; import appeng.client.texture.ExtraBlockTextures; import appeng.core.features.AEFeature; import appeng.tile.networking.TileDenseEnergyCell; import net.minecraft.util.IIcon; -import java.util.EnumSet; +public class BlockDenseEnergyCell extends BlockEnergyCell { + public BlockDenseEnergyCell() { + this.setTileEntity(TileDenseEnergyCell.class); + this.setFeature(EnumSet.of(AEFeature.DenseEnergyCells)); + } + @Override + public IIcon getIcon(final int direction, final int 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(); + } + return super.getIcon(direction, metadata); + } -public class BlockDenseEnergyCell extends BlockEnergyCell -{ - - public BlockDenseEnergyCell() - { - this.setTileEntity( TileDenseEnergyCell.class ); - this.setFeature( EnumSet.of( AEFeature.DenseEnergyCells ) ); - } - - @Override - public IIcon getIcon( final int direction, final int 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(); - } - return super.getIcon( direction, metadata ); - } - - @Override - public double getMaxPower() - { - return 200000.0 * 8.0; - } + @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 36272491..3e61a2e9 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java +++ b/src/main/java/appeng/block/networking/BlockEnergyAcceptor.java @@ -18,22 +18,17 @@ package appeng.block.networking; +import java.util.EnumSet; import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import appeng.tile.networking.TileEnergyAcceptor; import net.minecraft.block.material.Material; -import java.util.EnumSet; - - -public class BlockEnergyAcceptor extends AEBaseTileBlock -{ - - public BlockEnergyAcceptor() - { - super( Material.iron ); - this.setTileEntity( TileEnergyAcceptor.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } +public class BlockEnergyAcceptor extends AEBaseTileBlock { + public BlockEnergyAcceptor() { + super(Material.iron); + this.setTileEntity(TileEnergyAcceptor.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } } diff --git a/src/main/java/appeng/block/networking/BlockEnergyCell.java b/src/main/java/appeng/block/networking/BlockEnergyCell.java index 4a90d428..b3cadc0f 100644 --- a/src/main/java/appeng/block/networking/BlockEnergyCell.java +++ b/src/main/java/appeng/block/networking/BlockEnergyCell.java @@ -18,6 +18,8 @@ package appeng.block.networking; +import java.util.EnumSet; +import java.util.List; import appeng.block.AEBaseItemBlock; import appeng.block.AEBaseItemBlockChargeable; @@ -36,75 +38,64 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; -import java.util.EnumSet; -import java.util.List; +public class BlockEnergyCell extends AEBaseTileBlock { + public BlockEnergyCell() { + super(AEGlassMaterial.INSTANCE); + this.setTileEntity(TileEnergyCell.class); + this.setFeature(EnumSet.of(AEFeature.Core)); + } -public class BlockEnergyCell extends AEBaseTileBlock -{ + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockEnergyCube getRenderer() { + return new RenderBlockEnergyCube(); + } - public BlockEnergyCell() - { - super( AEGlassMaterial.INSTANCE ); + @Override + public IIcon getIcon(final int direction, final 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); + } - this.setTileEntity( TileEnergyCell.class ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + super.getCheckedSubBlocks(item, tabs, itemStacks); - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockEnergyCube getRenderer() - { - return new RenderBlockEnergyCube(); - } + final ItemStack charged = new ItemStack(this, 1); + final NBTTagCompound tag = Platform.openNbtData(charged); + tag.setDouble("internalCurrentPower", this.getMaxPower()); + tag.setDouble("internalMaxPower", this.getMaxPower()); - @Override - public IIcon getIcon( final int direction, final 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 ); - } + itemStacks.add(charged); + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - super.getCheckedSubBlocks( item, tabs, itemStacks ); + public double getMaxPower() { + return 200000.0; + } - final ItemStack charged = new ItemStack( this, 1 ); - final NBTTagCompound tag = Platform.openNbtData( charged ); - tag.setDouble( "internalCurrentPower", this.getMaxPower() ); - tag.setDouble( "internalMaxPower", this.getMaxPower() ); - - itemStacks.add( charged ); - } - - public double getMaxPower() - { - return 200000.0; - } - - @Override - public Class getItemBlockClass() - { - return AEBaseItemBlockChargeable.class; - } + @Override + public Class getItemBlockClass() { + return AEBaseItemBlockChargeable.class; + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumBase.java b/src/main/java/appeng/block/qnb/BlockQuantumBase.java index 81a6ab05..bbe793bb 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumBase.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumBase.java @@ -18,6 +18,7 @@ package appeng.block.qnb; +import java.util.EnumSet; import appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderQNB; @@ -30,50 +31,45 @@ import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.world.World; -import java.util.EnumSet; +public abstract class BlockQuantumBase + extends AEBaseTileBlock implements ICustomCollision { + public BlockQuantumBase(final Material mat) { + super(mat); + this.setTileEntity(TileQuantumBridge.class); + final float shave = 2.0f / 16.0f; + this.setBlockBounds( + shave, shave, shave, 1.0f - shave, 1.0f - shave, 1.0f - shave + ); + this.setLightOpacity(0); + this.isFullSize = this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.QuantumNetworkBridge)); + } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block pointlessNumber + ) { + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null) { + bridge.neighborUpdate(); + } + } -public abstract class BlockQuantumBase extends AEBaseTileBlock implements ICustomCollision -{ + @Override + public void breakBlock( + final World w, final int x, final int y, final int z, final Block a, final int b + ) { + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null) { + bridge.breakCluster(); + } - public BlockQuantumBase( final Material mat ) - { - super( mat ); - this.setTileEntity( TileQuantumBridge.class ); - final float shave = 2.0f / 16.0f; - this.setBlockBounds( shave, shave, shave, 1.0f - shave, 1.0f - shave, 1.0f - shave ); - this.setLightOpacity( 0 ); - this.isFullSize = this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.QuantumNetworkBridge ) ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block pointlessNumber ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null ) - { - bridge.neighborUpdate(); - } - } - - @Override - public void breakBlock( final World w, final int x, final int y, final int z, final Block a, final int b ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null ) - { - bridge.breakCluster(); - } - - super.breakBlock( w, x, y, z, a, b ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderQNB getRenderer() - { - return new RenderQNB(); - } + super.breakBlock(w, x, y, z, a, b); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderQNB getRenderer() { + return new RenderQNB(); + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java index b27ed494..4840b4ca 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumLinkChamber.java @@ -18,6 +18,9 @@ package appeng.block.qnb; +import java.util.Collections; +import java.util.List; +import java.util.Random; import appeng.client.EffectType; import appeng.core.CommonHelper; @@ -33,67 +36,84 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.List; -import java.util.Random; +public class BlockQuantumLinkChamber extends BlockQuantumBase { + public BlockQuantumLinkChamber() { + super(AEGlassMaterial.INSTANCE); + } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World w, final int bx, final int by, final int bz, final Random r + ) { + final TileQuantumBridge bridge = this.getTileEntity(w, bx, by, bz); + if (bridge != null) { + if (bridge.hasQES()) { + if (CommonHelper.proxy.shouldAddParticles(r)) { + CommonHelper.proxy.spawnEffect( + EffectType.Energy, w, bx + 0.5, by + 0.5, bz + 0.5, null + ); + } + } + } + } -public class BlockQuantumLinkChamber extends BlockQuantumBase -{ + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - public BlockQuantumLinkChamber() - { - super( AEGlassMaterial.INSTANCE ); - } + final TileQuantumBridge tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI( + p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_QNB + ); + } + return true; + } + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int bx, final int by, final int bz, final Random r ) - { - final TileQuantumBridge bridge = this.getTileEntity( w, bx, by, bz ); - if( bridge != null ) - { - if( bridge.hasQES() ) - { - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - CommonHelper.proxy.spawnEffect( EffectType.Energy, w, bx + 0.5, by + 0.5, bz + 0.5, null ); - } - } - } - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + final double onePixel = 2.0 / 16.0; + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel + )); + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final TileQuantumBridge tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_QNB ); - } - return true; - } - return false; - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final double onePixel = 2.0 / 16.0; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final double onePixel = 2.0 / 16.0; - out.add( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + final double onePixel = 2.0 / 16.0; + out.add(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel + )); + } } diff --git a/src/main/java/appeng/block/qnb/BlockQuantumRing.java b/src/main/java/appeng/block/qnb/BlockQuantumRing.java index 8eeccebe..32d51793 100644 --- a/src/main/java/appeng/block/qnb/BlockQuantumRing.java +++ b/src/main/java/appeng/block/qnb/BlockQuantumRing.java @@ -18,6 +18,8 @@ package appeng.block.qnb; +import java.util.Collections; +import java.util.List; import appeng.tile.qnb.TileQuantumBridge; import net.minecraft.block.material.Material; @@ -25,47 +27,51 @@ import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import java.util.Collections; -import java.util.List; +public class BlockQuantumRing extends BlockQuantumBase { + public BlockQuantumRing() { + super(Material.iron); + } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + double onePixel = 2.0 / 16.0; + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null && bridge.isCorner()) { + onePixel = 4.0 / 16.0; + } else if (bridge != null && bridge.isFormed()) { + onePixel = 1.0 / 16.0; + } + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel + )); + } -public class BlockQuantumRing extends BlockQuantumBase -{ - - public BlockQuantumRing() - { - super( Material.iron ); - } - - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - double onePixel = 2.0 / 16.0; - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null && bridge.isCorner() ) - { - onePixel = 4.0 / 16.0; - } - else if( bridge != null && bridge.isFormed() ) - { - onePixel = 1.0 / 16.0; - } - return Collections.singletonList( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - double onePixel = 2.0 / 16.0; - final TileQuantumBridge bridge = this.getTileEntity( w, x, y, z ); - if( bridge != null && bridge.isCorner() ) - { - onePixel = 4.0 / 16.0; - } - else if( bridge != null && bridge.isFormed() ) - { - onePixel = 1.0 / 16.0; - } - out.add( AxisAlignedBB.getBoundingBox( onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel ) ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + double onePixel = 2.0 / 16.0; + final TileQuantumBridge bridge = this.getTileEntity(w, x, y, z); + if (bridge != null && bridge.isCorner()) { + onePixel = 4.0 / 16.0; + } else if (bridge != null && bridge.isFormed()) { + onePixel = 1.0 / 16.0; + } + out.add(AxisAlignedBB.getBoundingBox( + onePixel, onePixel, onePixel, 1.0 - onePixel, 1.0 - onePixel, 1.0 - onePixel + )); + } } diff --git a/src/main/java/appeng/block/solids/BlockFluix.java b/src/main/java/appeng/block/solids/BlockFluix.java index df0e1aa5..4cc7dbc6 100644 --- a/src/main/java/appeng/block/solids/BlockFluix.java +++ b/src/main/java/appeng/block/solids/BlockFluix.java @@ -18,19 +18,15 @@ package appeng.block.solids; +import java.util.EnumSet; import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; import net.minecraft.block.material.Material; -import java.util.EnumSet; - - -public class BlockFluix extends AEDecorativeBlock -{ - public BlockFluix() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class BlockFluix extends AEDecorativeBlock { + public BlockFluix() { + super(Material.rock); + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/solids/BlockQuartz.java b/src/main/java/appeng/block/solids/BlockQuartz.java index 47cdf61c..f8f38779 100644 --- a/src/main/java/appeng/block/solids/BlockQuartz.java +++ b/src/main/java/appeng/block/solids/BlockQuartz.java @@ -18,20 +18,15 @@ package appeng.block.solids; +import java.util.EnumSet; import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; import net.minecraft.block.material.Material; -import java.util.EnumSet; - - -public class BlockQuartz extends AEDecorativeBlock -{ - - public BlockQuartz() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class BlockQuartz extends AEDecorativeBlock { + public BlockQuartz() { + super(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 008be1f1..81ffb9d8 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzChiseled.java +++ b/src/main/java/appeng/block/solids/BlockQuartzChiseled.java @@ -18,20 +18,15 @@ package appeng.block.solids; +import java.util.EnumSet; import appeng.block.AEDecorativeBlock; import appeng.core.features.AEFeature; import net.minecraft.block.material.Material; -import java.util.EnumSet; - - -public class BlockQuartzChiseled extends AEDecorativeBlock -{ - - public BlockQuartzChiseled() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class BlockQuartzChiseled extends AEDecorativeBlock { + public BlockQuartzChiseled() { + super(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 b7d4b607..3e28be16 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 appeng.block.AEBaseBlock; import appeng.client.render.blocks.RenderQuartzGlass; @@ -28,37 +29,30 @@ import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.material.Material; import net.minecraft.world.IBlockAccess; -import java.util.EnumSet; +public class BlockQuartzGlass extends AEBaseBlock { + public BlockQuartzGlass() { + super(Material.glass); + this.setLightOpacity(0); + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } + @Override + @SideOnly(Side.CLIENT) + public RenderQuartzGlass getRenderer() { + return new RenderQuartzGlass(); + } -public class BlockQuartzGlass extends AEBaseBlock -{ - public BlockQuartzGlass() - { - super( Material.glass ); - this.setLightOpacity( 0 ); - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - public RenderQuartzGlass getRenderer() - { - return new RenderQuartzGlass(); - } - - @Override - public boolean shouldSideBeRendered( final IBlockAccess w, final int x, final int y, final int z, final int side ) - { - final 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 ); - } + @Override + public boolean shouldSideBeRendered( + final IBlockAccess w, final int x, final int y, final int z, final int side + ) { + final 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 7162f4bc..5db56910 100644 --- a/src/main/java/appeng/block/solids/BlockQuartzLamp.java +++ b/src/main/java/appeng/block/solids/BlockQuartzLamp.java @@ -18,6 +18,8 @@ package appeng.block.solids; +import java.util.EnumSet; +import java.util.Random; import appeng.client.render.effects.VibrantFX; import appeng.core.AEConfig; @@ -28,38 +30,34 @@ import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; import net.minecraft.world.World; -import java.util.EnumSet; -import java.util.Random; +public class BlockQuartzLamp extends BlockQuartzGlass { + public BlockQuartzLamp() { + this.setLightLevel(1.0f); + this.setBlockTextureName("BlockQuartzGlass"); + this.setFeature( + EnumSet.of(AEFeature.DecorativeQuartzBlocks, AEFeature.DecorativeLights) + ); + } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World w, final int x, final int y, final int z, final Random r + ) { + if (!AEConfig.instance.enableEffects) { + return; + } -public class BlockQuartzLamp extends BlockQuartzGlass -{ + if (CommonHelper.proxy.shouldAddParticles(r)) { + final double d0 = (r.nextFloat() - 0.5F) * 0.96D; + final double d1 = (r.nextFloat() - 0.5F) * 0.96D; + final double d2 = (r.nextFloat() - 0.5F) * 0.96D; - public BlockQuartzLamp() - { - this.setLightLevel( 1.0f ); - this.setBlockTextureName( "BlockQuartzGlass" ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks, AEFeature.DecorativeLights ) ); - } + final VibrantFX fx = new VibrantFX( + w, 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D + ); - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } - - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final double d0 = ( r.nextFloat() - 0.5F ) * 0.96D; - final double d1 = ( r.nextFloat() - 0.5F ) * 0.96D; - final double d2 = ( r.nextFloat() - 0.5F ) * 0.96D; - - final 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 ); - } - } + 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 a2476cad..868535d9 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 appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; @@ -27,27 +28,20 @@ import appeng.helpers.MetaRotation; import net.minecraft.block.material.Material; import net.minecraft.world.IBlockAccess; -import java.util.EnumSet; +public class BlockQuartzPillar extends AEBaseBlock implements IOrientableBlock { + public BlockQuartzPillar() { + super(Material.rock); + this.setFeature(EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } + @Override + public boolean usesMetadata() { + return true; + } -public class BlockQuartzPillar extends AEBaseBlock implements IOrientableBlock -{ - - public BlockQuartzPillar() - { - super( Material.rock ); - this.setFeature( EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } - - @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 ); - } + @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 1d689968..f0f6917b 100644 --- a/src/main/java/appeng/block/solids/BlockSkyStone.java +++ b/src/main/java/appeng/block/solids/BlockSkyStone.java @@ -18,6 +18,8 @@ package appeng.block.solids; +import java.util.EnumSet; +import java.util.List; import appeng.api.util.IOrientable; import appeng.api.util.IOrientableBlock; @@ -44,173 +46,161 @@ import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerEvent; -import java.util.EnumSet; -import java.util.List; +public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock { + private static final float BLOCK_RESISTANCE = 150.0f; + private static final double BREAK_SPEAK_SCALAR = 0.1; + private static final double BREAK_SPEAK_THRESHOLD = 7.0; + @SideOnly(Side.CLIENT) + private IIcon block; -public class BlockSkyStone extends AEBaseBlock implements IOrientableBlock -{ - private static final float BLOCK_RESISTANCE = 150.0f; - private static final double BREAK_SPEAK_SCALAR = 0.1; - private static final double BREAK_SPEAK_THRESHOLD = 7.0; + @SideOnly(Side.CLIENT) + private IIcon brick; - @SideOnly( Side.CLIENT ) - private IIcon block; + @SideOnly(Side.CLIENT) + private IIcon smallBrick; - @SideOnly( Side.CLIENT ) - private IIcon brick; + public BlockSkyStone() { + super(Material.rock); + this.setHardness(50); + this.hasSubtypes = true; + this.blockResistance = BLOCK_RESISTANCE; + this.setHarvestLevel("pickaxe", 3, 0); + this.setFeature(EnumSet.of(AEFeature.Core)); - @SideOnly( Side.CLIENT ) - private IIcon smallBrick; + MinecraftForge.EVENT_BUS.register(this); + } - public BlockSkyStone() - { - super( Material.rock ); - this.setHardness( 50 ); - this.hasSubtypes = true; - this.blockResistance = BLOCK_RESISTANCE; - this.setHarvestLevel( "pickaxe", 3, 0 ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); + @SubscribeEvent + public void breakFaster(final PlayerEvent.BreakSpeed event) { + if (event.block == this && event.entityPlayer != null) { + final ItemStack is = event.entityPlayer.inventory.getCurrentItem(); + int level = -1; - MinecraftForge.EVENT_BUS.register( this ); - } + if (is != null && is.getItem() != null) { + level = is.getItem().getHarvestLevel(is, "pickaxe"); + } - @SubscribeEvent - public void breakFaster( final PlayerEvent.BreakSpeed event ) - { - if( event.block == this && event.entityPlayer != null ) - { - final ItemStack is = event.entityPlayer.inventory.getCurrentItem(); - int level = -1; + if (event.metadata > 0 || level >= 3 + || event.originalSpeed > BREAK_SPEAK_THRESHOLD) { + event.newSpeed /= BREAK_SPEAK_SCALAR; + } + } + } - if( is != null && is.getItem() != null ) - { - level = is.getItem().getHarvestLevel( is, "pickaxe" ); - } + @Override + public int damageDropped(final int meta) { + return meta; + } - if( event.metadata > 0 || level >= 3 || event.originalSpeed > BREAK_SPEAK_THRESHOLD ) - { - event.newSpeed /= BREAK_SPEAK_SCALAR; - } - } - } + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player + ) { + final ItemStack is = super.getPickBlock(target, world, x, y, z, player); + is.setItemDamage(world.getBlockMetadata(x, y, z)); - @Override - public int damageDropped( final int meta ) - { - return meta; - } + return is; + } - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - final ItemStack is = super.getPickBlock( target, world, x, y, z, player ); - is.setItemDamage( world.getBlockMetadata( x, y, z ) ); + @Override + public void onBlockAdded(final World w, final int x, final int y, final int z) { + super.onBlockAdded(w, x, y, z); + if (Platform.isServer()) { + WorldData.instance().compassData().service().updateArea(w, x, y, z); + } + } - return is; - } + @Override + public boolean usesMetadata() { + return false; + } - @Override - public void onBlockAdded( final World w, final int x, final int y, final int z ) - { - super.onBlockAdded( w, x, y, z ); - if( Platform.isServer() ) - { - WorldData.instance().compassData().service().updateArea( w, x, y, z ); - } - } + @Override + public IOrientable + getOrientable(final IBlockAccess w, final int x, final int y, final int z) { + if (w.getBlockMetadata(x, y, z) == 0) { + return new LocationRotation(w, x, y, z); + } - @Override - public boolean usesMetadata() - { - return false; - } + return new NullRotation(); + } - @Override - public IOrientable getOrientable( final IBlockAccess w, final int x, final int y, final int z ) - { - if( w.getBlockMetadata( x, y, z ) == 0 ) - { - return new LocationRotation( w, x, y, z ); - } + @Override + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { + return this.getUnlocalizedName() + ".Block"; + } - return new NullRotation(); - } + if (is.getItemDamage() == 2) { + return this.getUnlocalizedName() + ".Brick"; + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { - return this.getUnlocalizedName() + ".Block"; - } + if (is.getItemDamage() == 3) { + return this.getUnlocalizedName() + ".SmallBrick"; + } - if( is.getItemDamage() == 2 ) - { - return this.getUnlocalizedName() + ".Brick"; - } + return this.getUnlocalizedName(); + } - if( is.getItemDamage() == 3 ) - { - return this.getUnlocalizedName() + ".SmallBrick"; - } + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(final 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"); + } - return this.getUnlocalizedName(); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final 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 - @SideOnly( Side.CLIENT ) - public void registerBlockIcons( final 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 + public void setRenderStateByMeta(final int metadata) { + this.getRendererInstance().setTemporaryRenderIcon(this.getIcon(0, metadata)); + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final 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 + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + super.getCheckedSubBlocks(item, tabs, itemStacks); - @Override - public void setRenderStateByMeta( final int metadata ) - { - this.getRendererInstance().setTemporaryRenderIcon( this.getIcon( 0, metadata ) ); - } + itemStacks.add(new ItemStack(item, 1, 1)); + itemStacks.add(new ItemStack(item, 1, 2)); + itemStacks.add(new ItemStack(item, 1, 3)); + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final 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( final World w, final int x, final int y, final int z, final Block b, final int metadata ) - { - super.breakBlock( w, x, y, z, b, metadata ); - if( Platform.isServer() ) - { - WorldData.instance().compassData().service().updateArea( w, x, y, z ); - } - } + @Override + public void breakBlock( + final World w, + final int x, + final int y, + final int z, + final Block b, + final int metadata + ) { + super.breakBlock(w, x, y, z, b, metadata); + if (Platform.isServer()) { + WorldData.instance().compassData().service().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 a86cd72a..1ff2000e 100644 --- a/src/main/java/appeng/block/solids/OreQuartz.java +++ b/src/main/java/appeng/block/solids/OreQuartz.java @@ -18,6 +18,9 @@ package appeng.block.solids; +import java.util.EnumSet; +import java.util.Random; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; @@ -33,135 +36,134 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import javax.annotation.Nullable; -import java.util.EnumSet; -import java.util.Random; +public class OreQuartz extends AEBaseBlock { + private int boostBrightnessLow; + private int boostBrightnessHigh; + private boolean enhanceBrightness; + public OreQuartz() { + super(Material.rock); + this.setHardness(3.0F); + this.setResistance(5.0F); + this.boostBrightnessLow = 0; + this.boostBrightnessHigh = 1; + this.enhanceBrightness = false; + this.setFeature(EnumSet.of(AEFeature.Core)); + } -public class OreQuartz extends AEBaseBlock -{ - private int boostBrightnessLow; - private int boostBrightnessHigh; - private boolean enhanceBrightness; + @Override + @SideOnly(Side.CLIENT) + protected RenderQuartzOre getRenderer() { + return new RenderQuartzOre(); + } - public OreQuartz() - { - super( Material.rock ); - this.setHardness( 3.0F ); - this.setResistance( 5.0F ); - this.boostBrightnessLow = 0; - this.boostBrightnessHigh = 1; - this.enhanceBrightness = false; - this.setFeature( EnumSet.of( AEFeature.Core ) ); - } + @Override + public int getMixedBrightnessForBlock( + final IBlockAccess par1iBlockAccess, + final int par2, + final int par3, + final int par4 + ) { + int j1 = super.getMixedBrightnessForBlock(par1iBlockAccess, par2, par3, par4); + if (this.enhanceBrightness) { + j1 = Math.max(j1 >> 20, j1 >> 4); - @Override - @SideOnly( Side.CLIENT ) - protected RenderQuartzOre getRenderer() - { - return new RenderQuartzOre(); - } + if (j1 > 4) { + j1 += this.boostBrightnessHigh; + } else { + j1 += this.boostBrightnessLow; + } - @Override - public int getMixedBrightnessForBlock( final IBlockAccess par1iBlockAccess, final int par2, final int par3, final int par4 ) - { - int j1 = super.getMixedBrightnessForBlock( par1iBlockAccess, par2, par3, par4 ); - if( this.enhanceBrightness ) - { - j1 = Math.max( j1 >> 20, j1 >> 4 ); + if (j1 > 15) { + j1 = 15; + } + return j1 << 20 | j1 << 4; + } + return j1; + } - if( j1 > 4 ) - { - j1 += this.boostBrightnessHigh; - } - else - { - j1 += this.boostBrightnessLow; - } + @Override + public int quantityDropped(final Random rand) { + return 1 + rand.nextInt(2); + } - if( j1 > 15 ) - { - j1 = 15; - } - return j1 << 20 | j1 << 4; - } - return j1; - } + @Nullable + @Override + public Item getItemDropped(final int id, final Random rand, final int meta) { + for (final Item crystalItem : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystal() + .maybeItem() + .asSet()) { + return crystalItem; + } - @Override - public int quantityDropped( final Random rand ) - { - return 1 + rand.nextInt( 2 ); - } + throw new MissingDefinition( + "Tried to access certus quartz crystal, even though they are disabled" + ); + } - @Nullable - @Override - public Item getItemDropped( final int id, final Random rand, final int meta ) - { - for( final Item crystalItem : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeItem().asSet() ) - { - return crystalItem; - } + @Override + public void dropBlockAsItemWithChance( + final World w, + final int x, + final int y, + final int z, + final int blockID, + final float something, + final int meta + ) { + super.dropBlockAsItemWithChance(w, x, y, z, blockID, something, meta); - throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); - } + if (this.getItemDropped(blockID, w.rand, meta) != Item.getItemFromBlock(this)) { + final int xp = MathHelper.getRandomIntegerInRange(w.rand, 2, 5); - @Override - public void dropBlockAsItemWithChance( final World w, final int x, final int y, final int z, final int blockID, final float something, final int meta ) - { - super.dropBlockAsItemWithChance( w, x, y, z, blockID, something, meta ); + this.dropXpOnBlockBreak(w, x, y, z, xp); + } + } - if( this.getItemDropped( blockID, w.rand, meta ) != Item.getItemFromBlock( this ) ) - { - final int xp = MathHelper.getRandomIntegerInRange( w.rand, 2, 5 ); + @Override + public int damageDropped(final int id) { + for (final ItemStack crystalStack : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystal() + .maybeStack(1) + .asSet()) { + return crystalStack.getItemDamage(); + } - this.dropXpOnBlockBreak( w, x, y, z, xp ); - } - } + throw new MissingDefinition( + "Tried to access certus quartz crystal, even though they are disabled" + ); + } - @Override - public int damageDropped( final int id ) - { - for( final ItemStack crystalStack : AEApi.instance().definitions().materials().certusQuartzCrystal().maybeStack( 1 ).asSet() ) - { - return crystalStack.getItemDamage(); - } + @Override + public int quantityDroppedWithBonus(final int fortune, final Random rand) { + if (fortune > 0 + && Item.getItemFromBlock(this) != this.getItemDropped(0, rand, fortune)) { + int j = rand.nextInt(fortune + 2) - 1; - throw new MissingDefinition( "Tried to access certus quartz crystal, even though they are disabled" ); - } + if (j < 0) { + j = 0; + } - @Override - public int quantityDroppedWithBonus( final int fortune, final Random rand ) - { - if( fortune > 0 && Item.getItemFromBlock( this ) != this.getItemDropped( 0, rand, fortune ) ) - { - int j = rand.nextInt( fortune + 2 ) - 1; + return this.quantityDropped(rand) * (j + 1); + } else { + return this.quantityDropped(rand); + } + } - if( j < 0 ) - { - j = 0; - } + void setBoostBrightnessLow(final int boostBrightnessLow) { + this.boostBrightnessLow = boostBrightnessLow; + } - return this.quantityDropped( rand ) * ( j + 1 ); - } - else - { - return this.quantityDropped( rand ); - } - } + void setBoostBrightnessHigh(final int boostBrightnessHigh) { + this.boostBrightnessHigh = boostBrightnessHigh; + } - void setBoostBrightnessLow( final int boostBrightnessLow ) - { - this.boostBrightnessLow = boostBrightnessLow; - } - - void setBoostBrightnessHigh( final int boostBrightnessHigh ) - { - this.boostBrightnessHigh = boostBrightnessHigh; - } - - public void setEnhanceBrightness( final boolean enhanceBrightness ) - { - this.enhanceBrightness = enhanceBrightness; - } + public void setEnhanceBrightness(final boolean enhanceBrightness) { + this.enhanceBrightness = enhanceBrightness; + } } diff --git a/src/main/java/appeng/block/solids/OreQuartzCharged.java b/src/main/java/appeng/block/solids/OreQuartzCharged.java index ec30cf0c..75a3d5a7 100644 --- a/src/main/java/appeng/block/solids/OreQuartzCharged.java +++ b/src/main/java/appeng/block/solids/OreQuartzCharged.java @@ -18,6 +18,8 @@ package appeng.block.solids; +import java.util.Random; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; @@ -31,84 +33,86 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import javax.annotation.Nullable; -import java.util.Random; +public class OreQuartzCharged extends OreQuartz { + public OreQuartzCharged() { + this.setBoostBrightnessLow(2); + this.setBoostBrightnessHigh(5); + } + @Nullable + @Override + public Item getItemDropped(final int id, final Random rand, final int meta) { + for (final Item charged : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .maybeItem() + .asSet()) { + return charged; + } -public class OreQuartzCharged extends OreQuartz -{ + throw new MissingDefinition( + "Tried to access charged certus quartz crystal, even though they are disabled" + ); + } - public OreQuartzCharged() - { - this.setBoostBrightnessLow( 2 ); - this.setBoostBrightnessHigh( 5 ); - } + @Override + public int damageDropped(final int id) { + for (final ItemStack crystalStack : AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .maybeStack(1) + .asSet()) { + return crystalStack.getItemDamage(); + } - @Nullable - @Override - public Item getItemDropped( final int id, final Random rand, final int meta ) - { - for( final Item charged : AEApi.instance().definitions().materials().certusQuartzCrystalCharged().maybeItem().asSet() ) - { - return charged; - } + throw new MissingDefinition( + "Tried to access charged certus quartz crystal, even though they are disabled" + ); + } - throw new MissingDefinition( "Tried to access charged certus quartz crystal, even though they are disabled" ); - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World w, final int x, final int y, final int z, final Random r + ) { + if (!AEConfig.instance.enableEffects) { + return; + } - @Override - public int damageDropped( final int id ) - { - for( final ItemStack crystalStack : AEApi.instance().definitions().materials().certusQuartzCrystalCharged().maybeStack( 1 ).asSet() ) - { - return crystalStack.getItemDamage(); - } + double xOff = (r.nextFloat()); + double yOff = (r.nextFloat()); + double zOff = (r.nextFloat()); - throw new MissingDefinition( "Tried to access charged certus quartz crystal, even though they are disabled" ); - } + switch (r.nextInt(6)) { + case 0: + xOff = -0.01; + break; + case 1: + yOff = -0.01; + break; + case 2: + xOff = -0.01; + break; + case 3: + zOff = -0.01; + break; + case 4: + xOff = 1.01; + break; + case 5: + yOff = 1.01; + break; + case 6: + zOff = 1.01; + break; + } - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World w, final int x, final int y, final int z, final Random r ) - { - if( !AEConfig.instance.enableEffects ) - { - return; - } - - double xOff = ( r.nextFloat() ); - double yOff = ( r.nextFloat() ); - double zOff = ( r.nextFloat() ); - - switch( r.nextInt( 6 ) ) - { - case 0: - xOff = -0.01; - break; - case 1: - yOff = -0.01; - break; - case 2: - xOff = -0.01; - break; - case 3: - zOff = -0.01; - break; - case 4: - xOff = 1.01; - break; - case 5: - yOff = 1.01; - break; - case 6: - zOff = 1.01; - break; - } - - if( CommonHelper.proxy.shouldAddParticles( r ) ) - { - final ChargedOreFX fx = new ChargedOreFX( w, x + xOff, y + yOff, z + zOff, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + if (CommonHelper.proxy.shouldAddParticles(r)) { + final 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 2a09b5cc..2f7bcf8f 100644 --- a/src/main/java/appeng/block/spatial/BlockMatrixFrame.java +++ b/src/main/java/appeng/block/spatial/BlockMatrixFrame.java @@ -18,6 +18,9 @@ package appeng.block.spatial; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; import appeng.block.AEBaseBlock; import appeng.client.render.blocks.RenderNull; @@ -36,72 +39,85 @@ import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; +public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision { + public BlockMatrixFrame() { + super(Material.anvil); + this.setResistance(6000000.0F); + this.setBlockUnbreakable(); + this.setLightOpacity(0); + this.isOpaque = false; + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderNull getRenderer() { + return new RenderNull(); + } -public class BlockMatrixFrame extends AEBaseBlock implements ICustomCollision -{ + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) {} - public BlockMatrixFrame() - { - super( Material.anvil ); - this.setResistance( 6000000.0F ); - this.setBlockUnbreakable(); - this.setLightOpacity( 0 ); - this.isOpaque = false; - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - } + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + // do nothing + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderNull getRenderer() - { - return new RenderNull(); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + return Arrays.asList(new AxisAlignedBB[] {} + ); // AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) + // } ); + } - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + out.add(AxisAlignedBB.getBoundingBox(0.0, 0.0, 0.0, 1.0, 1.0, 1.0)); + } - } + @Override + public boolean + canPlaceBlockAt(final World world, final int x, final int y, final int z) { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - // do nothing - } + @Override + public void onBlockExploded( + final World world, + final int x, + final int y, + final int z, + final Explosion explosion + ) { + // Don't explode. + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - return Arrays.asList( new AxisAlignedBB[] {} );// AxisAlignedBB.getBoundingBox( 0.25, 0, 0.25, 0.75, 0.5, 0.75 ) - // } ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( AxisAlignedBB.getBoundingBox( 0.0, 0.0, 0.0, 1.0, 1.0, 1.0 ) ); - } - - @Override - public boolean canPlaceBlockAt( final World world, final int x, final int y, final int z ) - { - return false; - } - - @Override - public void onBlockExploded( final World world, final int x, final int y, final int z, final Explosion explosion ) - { - // Don't explode. - } - - @Override - public boolean canEntityDestroy( final IBlockAccess world, final int x, final int y, final int z, final Entity entity ) - { - return false; - } + @Override + public boolean canEntityDestroy( + final IBlockAccess world, + final int x, + final int y, + final int z, + final 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 4c6a00e3..b2e0b5bd 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 appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; @@ -30,46 +31,51 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockSpatialIOPort extends AEBaseTileBlock { + public BlockSpatialIOPort() { + super(Material.iron); + this.setTileEntity(TileSpatialIOPort.class); + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + } + @Override + public final void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block junk + ) { + final TileSpatialIOPort te = this.getTileEntity(w, x, y, z); + if (te != null) { + te.updateRedstoneState(); + } + } -public class BlockSpatialIOPort extends AEBaseTileBlock -{ + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - public BlockSpatialIOPort() - { - super( Material.iron ); - this.setTileEntity( TileSpatialIOPort.class ); - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - } - - @Override - public final void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileSpatialIOPort te = this.getTileEntity( w, x, y, z ); - if( te != null ) - { - te.updateRedstoneState(); - } - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final TileSpatialIOPort tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_SPATIAL_IO_PORT ); - } - return true; - } - return false; - } + final TileSpatialIOPort tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + 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 f715a64e..3e7b8a65 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 appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderSpatialPylon; @@ -30,44 +31,36 @@ import net.minecraft.block.Block; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -import java.util.EnumSet; +public class BlockSpatialPylon extends AEBaseTileBlock { + public BlockSpatialPylon() { + super(AEGlassMaterial.INSTANCE); + this.setTileEntity(TileSpatialPylon.class); + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + } + @Override + public void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block junk + ) { + final TileSpatialPylon tsp = this.getTileEntity(w, x, y, z); + if (tsp != null) { + tsp.onNeighborBlockChange(); + } + } -public class BlockSpatialPylon extends AEBaseTileBlock -{ + @Override + public int + getLightValue(final IBlockAccess w, final int x, final int y, final int z) { + final TileSpatialPylon tsp = this.getTileEntity(w, x, y, z); + if (tsp != null) { + return tsp.getLightValue(); + } + return super.getLightValue(w, x, y, z); + } - public BlockSpatialPylon() - { - super( AEGlassMaterial.INSTANCE ); - this.setTileEntity( TileSpatialPylon.class ); - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - } - - @Override - public void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileSpatialPylon tsp = this.getTileEntity( w, x, y, z ); - if( tsp != null ) - { - tsp.onNeighborBlockChange(); - } - } - - @Override - public int getLightValue( final IBlockAccess w, final int x, final int y, final int z ) - { - final TileSpatialPylon tsp = this.getTileEntity( w, x, y, z ); - if( tsp != null ) - { - return tsp.getLightValue(); - } - return super.getLightValue( w, x, y, z ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderSpatialPylon getRenderer() - { - return new RenderSpatialPylon(); - } + @Override + @SideOnly(Side.CLIENT) + protected RenderSpatialPylon getRenderer() { + return new RenderSpatialPylon(); + } } diff --git a/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java b/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java index 90a580cc..3f788b13 100644 --- a/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java +++ b/src/main/java/appeng/block/stair/ChiseledQuartzStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class ChiseledQuartzStairBlock extends AEBaseStairBlock -{ - public ChiseledQuartzStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class ChiseledQuartzStairBlock extends AEBaseStairBlock { + public ChiseledQuartzStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/FluixStairBlock.java b/src/main/java/appeng/block/stair/FluixStairBlock.java index 328b2613..ec765962 100644 --- a/src/main/java/appeng/block/stair/FluixStairBlock.java +++ b/src/main/java/appeng/block/stair/FluixStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class FluixStairBlock extends AEBaseStairBlock -{ - public FluixStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class FluixStairBlock extends AEBaseStairBlock { + public FluixStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java b/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java index f1454f6f..08891711 100644 --- a/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java +++ b/src/main/java/appeng/block/stair/QuartzPillarStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class QuartzPillarStairBlock extends AEBaseStairBlock -{ - public QuartzPillarStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class QuartzPillarStairBlock extends AEBaseStairBlock { + public QuartzPillarStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/QuartzStairBlock.java b/src/main/java/appeng/block/stair/QuartzStairBlock.java index 7b784916..deefbb7c 100644 --- a/src/main/java/appeng/block/stair/QuartzStairBlock.java +++ b/src/main/java/appeng/block/stair/QuartzStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class QuartzStairBlock extends AEBaseStairBlock -{ - public QuartzStairBlock( final Block block ) - { - super( block, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class QuartzStairBlock extends AEBaseStairBlock { + public QuartzStairBlock(final Block block) { + super(block, 0, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java index 05bca2b5..63e1a3c1 100644 --- a/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneBlockStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class SkyStoneBlockStairBlock extends AEBaseStairBlock -{ - public SkyStoneBlockStairBlock( final Block block, final Integer meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class SkyStoneBlockStairBlock extends AEBaseStairBlock { + public SkyStoneBlockStairBlock(final Block block, final Integer meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java index 46f78362..9a9731e5 100644 --- a/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneBrickStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class SkyStoneBrickStairBlock extends AEBaseStairBlock -{ - public SkyStoneBrickStairBlock( final Block block, final Integer meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class SkyStoneBrickStairBlock extends AEBaseStairBlock { + public SkyStoneBrickStairBlock(final Block block, final Integer meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } \ No newline at end of file diff --git a/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java index bf8338d5..e8fbac40 100644 --- a/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneSmallBrickStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class SkyStoneSmallBrickStairBlock extends AEBaseStairBlock -{ - public SkyStoneSmallBrickStairBlock( final Block block, final int meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class SkyStoneSmallBrickStairBlock extends AEBaseStairBlock { + public SkyStoneSmallBrickStairBlock(final Block block, final int meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } \ No newline at end of file diff --git a/src/main/java/appeng/block/stair/SkyStoneStairBlock.java b/src/main/java/appeng/block/stair/SkyStoneStairBlock.java index bd838311..56f6917f 100644 --- a/src/main/java/appeng/block/stair/SkyStoneStairBlock.java +++ b/src/main/java/appeng/block/stair/SkyStoneStairBlock.java @@ -18,18 +18,14 @@ package appeng.block.stair; +import java.util.EnumSet; import appeng.block.AEBaseStairBlock; import appeng.core.features.AEFeature; import net.minecraft.block.Block; -import java.util.EnumSet; - - -public class SkyStoneStairBlock extends AEBaseStairBlock -{ - public SkyStoneStairBlock( final Block block, final Integer meta ) - { - super( block, meta, EnumSet.of( AEFeature.DecorativeQuartzBlocks ) ); - } +public class SkyStoneStairBlock extends AEBaseStairBlock { + public SkyStoneStairBlock(final Block block, final Integer meta) { + super(block, meta, EnumSet.of(AEFeature.DecorativeQuartzBlocks)); + } } diff --git a/src/main/java/appeng/block/storage/BlockChest.java b/src/main/java/appeng/block/storage/BlockChest.java index 92d04ebb..092c8dc0 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 appeng.api.AEApi; import appeng.api.storage.ICellHandler; @@ -36,59 +37,56 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockChest extends AEBaseTileBlock { + public BlockChest() { + super(Material.iron); + this.setTileEntity(TileChest.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.MEChest)); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderMEChest getRenderer() { + return new RenderMEChest(); + } -public class BlockChest extends AEBaseTileBlock -{ + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final TileChest tg = this.getTileEntity(w, x, y, z); + if (tg != null && !p.isSneaking()) { + if (Platform.isClient()) { + return true; + } - public BlockChest() - { - super( Material.iron ); - this.setTileEntity( TileChest.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.MEChest ) ); - } + if (side != tg.getUp().ordinal()) { + Platform.openGUI( + p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_CHEST + ); + } else { + final ItemStack cell = tg.getStackInSlot(1); + if (cell != null) { + final ICellHandler ch + = AEApi.instance().registries().cell().getHandler(cell); - @Override - @SideOnly( Side.CLIENT ) - protected RenderMEChest getRenderer() - { - return new RenderMEChest(); - } + tg.openGui(p, ch, cell, side); + } else { + p.addChatMessage(PlayerMessages.ChestCannotReadStorageCell.get()); + } + } - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileChest tg = this.getTileEntity( w, x, y, z ); - if( tg != null && !p.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + return true; + } - if( side != tg.getUp().ordinal() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_CHEST ); - } - else - { - final ItemStack cell = tg.getStackInSlot( 1 ); - if( cell != null ) - { - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); - - tg.openGui( p, ch, cell, side ); - } - else - { - p.addChatMessage( PlayerMessages.ChestCannotReadStorageCell.get() ); - } - } - - return true; - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockDrive.java b/src/main/java/appeng/block/storage/BlockDrive.java index c2058a6c..3202d6fd 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 appeng.block.AEBaseTileBlock; import appeng.client.render.blocks.RenderDrive; @@ -32,43 +33,44 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockDrive extends AEBaseTileBlock { + public BlockDrive() { + super(Material.iron); + this.setTileEntity(TileDrive.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.MEDrive)); + } + @Override + @SideOnly(Side.CLIENT) + protected RenderDrive getRenderer() { + return new RenderDrive(); + } -public class BlockDrive extends AEBaseTileBlock -{ + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - public BlockDrive() - { - super( Material.iron ); - this.setTileEntity( TileDrive.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.MEDrive ) ); - } - - @Override - @SideOnly( Side.CLIENT ) - protected RenderDrive getRenderer() - { - return new RenderDrive(); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final TileDrive tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_DRIVE ); - } - return true; - } - return false; - } + final TileDrive tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + 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 7228e567..23c07b47 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 appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; @@ -30,46 +31,48 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class BlockIOPort extends AEBaseTileBlock { + public BlockIOPort() { + super(Material.iron); + this.setTileEntity(TileIOPort.class); + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.IOPort)); + } + @Override + public final void onNeighborBlockChange( + final World w, final int x, final int y, final int z, final Block junk + ) { + final TileIOPort te = this.getTileEntity(w, x, y, z); + if (te != null) { + te.updateRedstoneState(); + } + } -public class BlockIOPort extends AEBaseTileBlock -{ + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer p, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (p.isSneaking()) { + return false; + } - public BlockIOPort() - { - super( Material.iron ); - this.setTileEntity( TileIOPort.class ); - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.IOPort ) ); - } - - @Override - public final void onNeighborBlockChange( final World w, final int x, final int y, final int z, final Block junk ) - { - final TileIOPort te = this.getTileEntity( w, x, y, z ); - if( te != null ) - { - te.updateRedstoneState(); - } - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer p, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( p.isSneaking() ) - { - return false; - } - - final TileIOPort tg = this.getTileEntity( w, x, y, z ); - if( tg != null ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, tg, ForgeDirection.getOrientation( side ), GuiBridge.GUI_IOPORT ); - } - return true; - } - return false; - } + final TileIOPort tg = this.getTileEntity(w, x, y, z); + if (tg != null) { + if (Platform.isServer()) { + Platform.openGUI( + p, tg, ForgeDirection.getOrientation(side), GuiBridge.GUI_IOPORT + ); + } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/block/storage/BlockSkyChest.java b/src/main/java/appeng/block/storage/BlockSkyChest.java index 039aedf6..529ef562 100644 --- a/src/main/java/appeng/block/storage/BlockSkyChest.java +++ b/src/main/java/appeng/block/storage/BlockSkyChest.java @@ -18,6 +18,9 @@ package appeng.block.storage; +import java.util.Collections; +import java.util.EnumSet; +import java.util.List; import appeng.api.AEApi; import appeng.block.AEBaseTileBlock; @@ -44,133 +47,151 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.List; +public class BlockSkyChest extends AEBaseTileBlock implements ICustomCollision { + private static final double AABB_OFFSET_BOTTOM = .0625d; + private static final double AABB_OFFSET_SIDES = 0; + private static final double AABB_OFFSET_TOP = .125d; + public BlockSkyChest() { + super(Material.rock); + this.setTileEntity(TileSkyChest.class); + this.isOpaque = this.isFullSize = false; + this.hasSubtypes = true; + this.lightOpacity = 0; + this.setHardness(50); + this.blockResistance = 150.0f; + this.setFeature(EnumSet.of(AEFeature.Core, AEFeature.SkyStoneChests)); + } -public class BlockSkyChest extends AEBaseTileBlock implements ICustomCollision -{ + @Override + public int damageDropped(final int metadata) { + return metadata; + } - private static final double AABB_OFFSET_BOTTOM = .0625d; - private static final double AABB_OFFSET_SIDES = 0; - private static final double AABB_OFFSET_TOP = .125d; + @Override + public ItemStack getPickBlock( + final MovingObjectPosition target, + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player + ) { + final ItemStack is = super.getPickBlock(target, world, x, y, z, player); + is.setItemDamage(world.getBlockMetadata(x, y, z)); - public BlockSkyChest() - { - super( Material.rock ); - this.setTileEntity( TileSkyChest.class ); - this.isOpaque = this.isFullSize = false; - this.hasSubtypes = true; - this.lightOpacity = 0; - this.setHardness( 50 ); - this.blockResistance = 150.0f; - this.setFeature( EnumSet.of( AEFeature.Core, AEFeature.SkyStoneChests ) ); - } + return is; + } - @Override - public int damageDropped( final int metadata ) - { - return metadata; - } + @Override + @SideOnly(Side.CLIENT) + protected RenderBlockSkyChest getRenderer() { + return new RenderBlockSkyChest(); + } + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(final int direction, final int metadata) { + for (final Block skyStoneBlock : + AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet()) { + return skyStoneBlock.getIcon(direction, metadata); + } - @Override - public ItemStack getPickBlock( final MovingObjectPosition target, final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - final ItemStack is = super.getPickBlock( target, world, x, y, z, player ); - is.setItemDamage( world.getBlockMetadata( x, y, z ) ); + return Blocks.stone.getIcon(direction, metadata); + } - return is; - } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (Platform.isServer()) { + Platform.openGUI( + player, + this.getTileEntity(w, x, y, z), + ForgeDirection.getOrientation(side), + GuiBridge.GUI_SKYCHEST + ); + } - @Override - @SideOnly( Side.CLIENT ) - protected RenderBlockSkyChest getRenderer() - { - return new RenderBlockSkyChest(); - } + return true; + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getIcon( final int direction, final int metadata ) - { - for( final Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) - { - return skyStoneBlock.getIcon( direction, metadata ); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) {} - return Blocks.stone.getIcon( direction, metadata ); - } + @Override + @SideOnly(Side.CLIENT) + public void getCheckedSubBlocks( + final Item item, final CreativeTabs tabs, final List itemStacks + ) { + super.getCheckedSubBlocks(item, tabs, itemStacks); - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( Platform.isServer() ) - { - Platform.openGUI( player, this.getTileEntity( w, x, y, z ), ForgeDirection.getOrientation( side ), GuiBridge.GUI_SKYCHEST ); - } + itemStacks.add(new ItemStack(item, 1, 1)); + } - return true; - } + @Override + public String getUnlocalizedName(final ItemStack is) { + if (is.getItemDamage() == 1) { + return this.getUnlocalizedName() + ".Block"; + } - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - } + return this.getUnlocalizedName(); + } - @Override - @SideOnly( Side.CLIENT ) - public void getCheckedSubBlocks( final Item item, final CreativeTabs tabs, final List itemStacks ) - { - super.getCheckedSubBlocks( item, tabs, itemStacks ); + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity thePlayer, + final boolean isVisual + ) { + return Collections.singletonList(computeAABB(w, x, y, z)); + } - itemStacks.add( new ItemStack( item, 1, 1 ) ); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + out.add(computeAABB(w, x, y, z)); + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - if( is.getItemDamage() == 1 ) - { - return this.getUnlocalizedName() + ".Block"; - } + private AxisAlignedBB + computeAABB(final World w, final int x, final int y, final int z) { + final TileSkyChest sk = this.getTileEntity(w, x, y, z); + ForgeDirection o = ForgeDirection.UP; - return this.getUnlocalizedName(); - } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity thePlayer, final boolean isVisual ) - { - return Collections.singletonList( computeAABB( w, x, y, z ) ); - } + if (sk != null) + o = sk.getUp(); - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - out.add( computeAABB( w, x, y, z ) ); - } + final double offsetX = o.offsetX == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; + final double offsetY = o.offsetY == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; + final double offsetZ = o.offsetZ == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; - private AxisAlignedBB computeAABB( final World w, final int x, final int y, final int z ) - { - final TileSkyChest sk = this.getTileEntity( w, x, y, z ); - ForgeDirection o = ForgeDirection.UP; + // x/z needs to be multiplied by -1, thus we simply add not substract. + final double minX = Math.max(0.0, offsetX + o.offsetX * AABB_OFFSET_TOP); + final double minY = Math.max(0.0, offsetY - o.offsetY * AABB_OFFSET_TOP); + final double minZ = Math.max(0.0, offsetZ + o.offsetZ * AABB_OFFSET_TOP); - if( sk != null ) - o = sk.getUp(); + final double maxX = Math.min(1.0, (1.0 - offsetX) + o.offsetX * AABB_OFFSET_TOP); + final double maxY = Math.min(1.0, (1.0 - offsetY) - o.offsetY * AABB_OFFSET_TOP); + final double maxZ = Math.min(1.0, (1.0 - offsetZ) + o.offsetZ * AABB_OFFSET_TOP); - final double offsetX = o.offsetX == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; - final double offsetY = o.offsetY == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; - final double offsetZ = o.offsetZ == 0 ? AABB_OFFSET_BOTTOM : AABB_OFFSET_SIDES; - - // x/z needs to be multiplied by -1, thus we simply add not substract. - final double minX = Math.max( 0.0, offsetX + o.offsetX * AABB_OFFSET_TOP ); - final double minY = Math.max( 0.0, offsetY - o.offsetY * AABB_OFFSET_TOP ); - final double minZ = Math.max( 0.0, offsetZ + o.offsetZ * AABB_OFFSET_TOP ); - - final double maxX = Math.min( 1.0, ( 1.0 - offsetX ) + o.offsetX * AABB_OFFSET_TOP ); - final double maxY = Math.min( 1.0, ( 1.0 - offsetY ) - o.offsetY * AABB_OFFSET_TOP ); - final double maxZ = Math.min( 1.0, ( 1.0 - offsetZ ) + o.offsetZ * AABB_OFFSET_TOP ); - - return AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ); - } + return AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ); + } } diff --git a/src/main/java/appeng/client/ClientHelper.java b/src/main/java/appeng/client/ClientHelper.java index fe1f176b..187bc64f 100644 --- a/src/main/java/appeng/client/ClientHelper.java +++ b/src/main/java/appeng/client/ClientHelper.java @@ -18,6 +18,10 @@ package appeng.client; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; import appeng.api.parts.CableRenderMode; import appeng.api.util.AEColor; @@ -71,367 +75,381 @@ import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.common.MinecraftForge; import org.lwjgl.opengl.GL11; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; +public class ClientHelper extends ServerHelper { + private static final RenderItem ITEM_RENDERER = new RenderItem(); + private static final RenderBlocks BLOCK_RENDERER = new RenderBlocks(); + @SubscribeEvent + public void postPlayerRender(final RenderLivingEvent.Pre p) { + final PlayerColor player + = TickHandler.INSTANCE.getPlayerColors().get(p.entity.getEntityId()); + if (player != null) { + final AEColor col = player.myColor; -public class ClientHelper extends ServerHelper -{ + final float r = 0xff & (col.mediumVariant >> 16); + final float g = 0xff & (col.mediumVariant >> 8); + final float b = 0xff & (col.mediumVariant); + GL11.glColor3f(r / 255.0f, g / 255.0f, b / 255.0f); + } + } - private static final RenderItem ITEM_RENDERER = new RenderItem(); - private static final RenderBlocks BLOCK_RENDERER = new RenderBlocks(); + @Override + public void init() { + MinecraftForge.EVENT_BUS.register(this); + } - @SubscribeEvent - public void postPlayerRender( final RenderLivingEvent.Pre p ) - { - final PlayerColor player = TickHandler.INSTANCE.getPlayerColors().get( p.entity.getEntityId() ); - if( player != null ) - { - final AEColor col = player.myColor; + @Override + public World getWorld() { + if (Platform.isClient()) { + return Minecraft.getMinecraft().theWorld; + } else { + return super.getWorld(); + } + } - final float r = 0xff & ( col.mediumVariant >> 16 ); - final float g = 0xff & ( col.mediumVariant >> 8 ); - final float b = 0xff & ( col.mediumVariant ); - GL11.glColor3f( r / 255.0f, g / 255.0f, b / 255.0f ); - } - } + @Override + public void bindTileEntitySpecialRenderer(final Class tile, final AEBaseBlock blk) { + final BaseBlockRender bbr = blk.getRendererInstance().getRendererInstance(); + if (bbr.hasTESR() && tile != null) { + ClientRegistry.bindTileEntitySpecialRenderer(tile, new TESRWrapper(bbr)); + } + } - @Override - public void init() - { - MinecraftForge.EVENT_BUS.register( this ); - } + @Override + public List getPlayers() { + if (Platform.isClient()) { + final List o = new ArrayList(); + o.add(Minecraft.getMinecraft().thePlayer); + return o; + } else { + return super.getPlayers(); + } + } - @Override - public World getWorld() - { - if( Platform.isClient() ) - { - return Minecraft.getMinecraft().theWorld; - } - else - { - return super.getWorld(); - } - } + @Override + public void spawnEffect( + final EffectType effect, + final World worldObj, + final double posX, + final double posY, + final double posZ, + final 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: + } + } + } - @Override - public void bindTileEntitySpecialRenderer( final Class tile, final AEBaseBlock blk ) - { - final BaseBlockRender bbr = blk.getRendererInstance().getRendererInstance(); - if( bbr.hasTESR() && tile != null ) - { - ClientRegistry.bindTileEntitySpecialRenderer( tile, new TESRWrapper( bbr ) ); - } - } + private void spawnAssembler( + final World worldObj, + final double posX, + final double posY, + final double posZ, + final Object o + ) { + final PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; - @Override - public List getPlayers() - { - if( Platform.isClient() ) - { - final List o = new ArrayList(); - o.add( Minecraft.getMinecraft().thePlayer ); - return o; - } - else - { - return super.getPlayers(); - } - } + final 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); + } - @Override - public void spawnEffect( final EffectType effect, final World worldObj, final double posX, final double posY, final double posZ, final 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 + spawnVibrant(final World w, final double x, final double y, final double z) { + if (CommonHelper.proxy.shouldAddParticles(Platform.getRandom())) { + final double d0 = (Platform.getRandomFloat() - 0.5F) * 0.26D; + final double d1 = (Platform.getRandomFloat() - 0.5F) * 0.26D; + final double d2 = (Platform.getRandomFloat() - 0.5F) * 0.26D; - private void spawnAssembler( final World worldObj, final double posX, final double posY, final double posZ, final Object o ) - { - final PacketAssemblerAnimation paa = (PacketAssemblerAnimation) o; + final VibrantFX fx + = new VibrantFX(w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } - final 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 spawnCrafting( + final World w, final double posX, final double posY, final double posZ + ) { + final float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - private void spawnVibrant( final World w, final double x, final double y, final double z ) - { - if( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - final double d0 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; - final double d1 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; - final double d2 = ( Platform.getRandomFloat() - 0.5F ) * 0.26D; + final CraftingFx fx + = new CraftingFx(w, posX + x, posY + y, posZ + z, Items.diamond); - final VibrantFX fx = new VibrantFX( w, x + d0, y + d1, z + d2, 0.0D, 0.0D, 0.0D ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } + fx.motionX = -x * 0.2; + fx.motionY = -y * 0.2; + fx.motionZ = -z * 0.2; - private void spawnCrafting( final World w, final double posX, final double posY, final double posZ ) - { - final float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - final CraftingFx fx = new CraftingFx( w, posX + x, posY + y, posZ + z, Items.diamond ); + private void + spawnEnergy(final World w, final double posX, final double posY, final double posZ) { + final float x = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float y = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; + final float z = (float) (((Platform.getRandomInt() % 100) * 0.01) - 0.5) * 0.7f; - fx.motionX = -x * 0.2; - fx.motionY = -y * 0.2; - fx.motionZ = -z * 0.2; + final EnergyFx fx = new EnergyFx(w, posX + x, posY + y, posZ + z, Items.diamond); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + fx.motionX = -x * 0.1; + fx.motionY = -y * 0.1; + fx.motionZ = -z * 0.1; - private void spawnEnergy( final World w, final double posX, final double posY, final double posZ ) - { - final float x = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float y = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; - final float z = (float) ( ( ( Platform.getRandomInt() % 100 ) * 0.01 ) - 0.5 ) * 0.7f; + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - final EnergyFx fx = new EnergyFx( w, posX + x, posY + y, posZ + z, Items.diamond ); + private void spawnLightning( + final World worldObj, final double posX, final double posY, final double posZ + ) { + final LightningFX fx + = new LightningFX(worldObj, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f); + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } - fx.motionX = -x * 0.1; - fx.motionY = -y * 0.1; - fx.motionZ = -z * 0.1; + private void spawnLightningArc( + final World worldObj, + final double posX, + final double posY, + final double posZ, + final Vec3 second + ) { + final 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); + } - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + @Override + public boolean shouldAddParticles(final Random r) { + final int setting = Minecraft.getMinecraft().gameSettings.particleSetting; + if (setting == 2) { + return false; + } + if (setting == 0) { + return true; + } + return r.nextInt(2 * (setting + 1)) == 0; + } - private void spawnLightning( final World worldObj, final double posX, final double posY, final double posZ ) - { - final LightningFX fx = new LightningFX( worldObj, posX, posY + 0.3f, posZ, 0.0f, 0.0f, 0.0f ); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } + @Override + public MovingObjectPosition getMOP() { + return Minecraft.getMinecraft().objectMouseOver; + } - private void spawnLightningArc( final World worldObj, final double posX, final double posY, final double posZ, final Vec3 second ) - { - final 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 void doRenderItem(final ItemStack itemstack, final World w) { + if (itemstack != null) { + final EntityItem entityitem = new EntityItem(w, 0.0D, 0.0D, 0.0D, itemstack); + entityitem.getEntityItem().stackSize = 1; - @Override - public boolean shouldAddParticles( final Random r ) - { - final int setting = Minecraft.getMinecraft().gameSettings.particleSetting; - if( setting == 2 ) - { - return false; - } - if( setting == 0 ) - { - return true; - } - return r.nextInt( 2 * ( setting + 1 ) ) == 0; - } + // set all this stuff and then do shit? meh? + entityitem.hoverStart = 0; + entityitem.age = 0; + entityitem.rotationYaw = 0; - @Override - public MovingObjectPosition getMOP() - { - return Minecraft.getMinecraft().objectMouseOver; - } + GL11.glPushMatrix(); + GL11.glTranslatef(0, -0.04F, 0); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + // GL11.glDisable( GL11.GL_CULL_FACE ); - @Override - public void doRenderItem( final ItemStack itemstack, final World w ) - { - if( itemstack != null ) - { - final EntityItem entityitem = new EntityItem( w, 0.0D, 0.0D, 0.0D, itemstack ); - entityitem.getEntityItem().stackSize = 1; + 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); + // GL11.glTranslated( -8.0, -12.2, -10.6 ); + GL11.glScalef(1.0f, -1.0f, 0.005f); + // GL11.glScalef( 1.0f , -1.0f, 1.0f ); - // set all this stuff and then do shit? meh? - entityitem.hoverStart = 0; - entityitem.age = 0; - entityitem.rotationYaw = 0; + final Block block = Block.getBlockFromItem(itemstack.getItem()); + 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); + GL11.glRotatef(30.0f, 0.0f, 1.0f, 0.0f); + } - GL11.glPushMatrix(); - GL11.glTranslatef( 0, -0.04F, 0 ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - // GL11.glDisable( GL11.GL_CULL_FACE ); + final IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer( + itemstack, IItemRenderer.ItemRenderType.ENTITY + ); + if (customRenderer != null + && !(itemstack.getItem() instanceof ItemBlock)) { + if (customRenderer.shouldUseRenderHelper( + IItemRenderer.ItemRenderType.ENTITY, + itemstack, + IItemRenderer.ItemRendererHelper.BLOCK_3D + )) { + GL11.glTranslatef(0, -0.04F, 0); + GL11.glScalef(0.7f, 0.7f, 0.7f); + GL11.glRotatef(35, 1, 0, 0); + GL11.glRotatef(45, 0, 1, 0); + GL11.glRotatef(-90, 0, 1, 0); + } + } else if (itemstack.getItem() instanceof ItemBlock) { + GL11.glTranslatef(0, -0.04F, 0); + GL11.glScalef(1.1f, 1.1f, 1.1f); + GL11.glRotatef(-90, 0, 1, 0); + } else { + GL11.glTranslatef(0, -0.14F, 0); + GL11.glScalef(0.8f, 0.8f, 0.8f); + } - 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 ); - // GL11.glTranslated( -8.0, -12.2, -10.6 ); - GL11.glScalef( 1.0f, -1.0f, 0.005f ); - // GL11.glScalef( 1.0f , -1.0f, 1.0f ); + RenderItem.renderInFrame = true; + RenderManager.instance.renderEntityWithPosYaw( + entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F + ); + RenderItem.renderInFrame = false; + } else { + GL11.glScalef(1.0f / 42.0f, 1.0f / 42.0f, 1.0f / 42.0f); + GL11.glTranslated(-8.0, -10.2, -10.4); + GL11.glScalef(1.0f, 1.0f, 0.005f); - final Block block = Block.getBlockFromItem( itemstack.getItem() ); - 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 ); - GL11.glRotatef( 30.0f, 0.0f, 1.0f, 0.0f ); - } + RenderItem.renderInFrame = false; + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + if (!ForgeHooksClient.renderInventoryItem( + BLOCK_RENDERER, + Minecraft.getMinecraft().renderEngine, + itemstack, + true, + 0, + 0, + 0 + )) { + ITEM_RENDERER.renderItemIntoGUI( + fr, Minecraft.getMinecraft().renderEngine, itemstack, 0, 0, false + ); + } + } - final IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer( itemstack, IItemRenderer.ItemRenderType.ENTITY ); - if( customRenderer != null && !( itemstack.getItem() instanceof ItemBlock ) ) - { - if( customRenderer.shouldUseRenderHelper( IItemRenderer.ItemRenderType.ENTITY, itemstack, IItemRenderer.ItemRendererHelper.BLOCK_3D ) ) - { - GL11.glTranslatef( 0, -0.04F, 0 ); - GL11.glScalef( 0.7f, 0.7f, 0.7f ); - GL11.glRotatef( 35, 1, 0, 0 ); - GL11.glRotatef( 45, 0, 1, 0 ); - GL11.glRotatef( -90, 0, 1, 0 ); - } - } - else if( itemstack.getItem() instanceof ItemBlock ) - { - GL11.glTranslatef( 0, -0.04F, 0 ); - GL11.glScalef( 1.1f, 1.1f, 1.1f ); - GL11.glRotatef( -90, 0, 1, 0 ); - } - else - { - GL11.glTranslatef( 0, -0.14F, 0 ); - GL11.glScalef( 0.8f, 0.8f, 0.8f ); - } + GL11.glPopMatrix(); + } + } - RenderItem.renderInFrame = true; - RenderManager.instance.renderEntityWithPosYaw( entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F ); - RenderItem.renderInFrame = false; - } - else - { - GL11.glScalef( 1.0f / 42.0f, 1.0f / 42.0f, 1.0f / 42.0f ); - GL11.glTranslated( -8.0, -10.2, -10.4 ); - GL11.glScalef( 1.0f, 1.0f, 0.005f ); + @Override + public void postInit() { + RenderingRegistry.registerBlockHandler(WorldRender.INSTANCE); + RenderManager.instance.entityRenderMap.put( + EntityTinyTNTPrimed.class, new RenderTinyTNTPrimed() + ); + RenderManager.instance.entityRenderMap.put( + EntityFloatingItem.class, new RenderFloatingItem() + ); + } - RenderItem.renderInFrame = false; - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - if( !ForgeHooksClient.renderInventoryItem( BLOCK_RENDERER, Minecraft.getMinecraft().renderEngine, itemstack, true, 0, 0, 0 ) ) - { - ITEM_RENDERER.renderItemIntoGUI( fr, Minecraft.getMinecraft().renderEngine, itemstack, 0, 0, false ); - } - } + @Override + public CableRenderMode getRenderMode() { + if (Platform.isServer()) { + return super.getRenderMode(); + } - GL11.glPopMatrix(); - } - } + final Minecraft mc = Minecraft.getMinecraft(); + final EntityPlayer player = mc.thePlayer; - @Override - public void postInit() - { - RenderingRegistry.registerBlockHandler( WorldRender.INSTANCE ); - RenderManager.instance.entityRenderMap.put( EntityTinyTNTPrimed.class, new RenderTinyTNTPrimed() ); - RenderManager.instance.entityRenderMap.put( EntityFloatingItem.class, new RenderFloatingItem() ); - } + return this.renderModeForPlayer(player); + } - @Override - public CableRenderMode getRenderMode() - { - if( Platform.isServer() ) - { - return super.getRenderMode(); - } + @Override + public void triggerUpdates() { + final Minecraft mc = Minecraft.getMinecraft(); + if (mc == null || mc.thePlayer == null || mc.theWorld == null) { + return; + } - final Minecraft mc = Minecraft.getMinecraft(); - final EntityPlayer player = mc.thePlayer; + final EntityPlayer player = mc.thePlayer; - return this.renderModeForPlayer( player ); - } + final int x = (int) player.posX; + final int y = (int) player.posY; + final int z = (int) player.posZ; - @Override - public void triggerUpdates() - { - final Minecraft mc = Minecraft.getMinecraft(); - if( mc == null || mc.thePlayer == null || mc.theWorld == null ) - { - return; - } + final int range = 16 * 16; - final EntityPlayer player = mc.thePlayer; + mc.theWorld.markBlockRangeForRenderUpdate( + x - range, y - range, z - range, x + range, y + range, z + range + ); + } - final int x = (int) player.posX; - final int y = (int) player.posY; - final int z = (int) player.posZ; + @Override + public void missingCoreMod() { + throw new MissingCoreMod(); + } - final int range = 16 * 16; + @SubscribeEvent + public void wheelEvent(final MouseEvent me) { + if (me.isCanceled() || me.dwheel == 0) { + return; + } - mc.theWorld.markBlockRangeForRenderUpdate( x - range, y - range, z - range, x + range, y + range, z + range ); - } + final Minecraft mc = Minecraft.getMinecraft(); + final EntityPlayer player = mc.thePlayer; + final ItemStack is = player.getHeldItem(); - @Override - public void missingCoreMod() - { - throw new MissingCoreMod(); - } + 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 (final IOException e) { + AELog.debug(e); + } + } + } - @SubscribeEvent - public void wheelEvent( final MouseEvent me ) - { - if( me.isCanceled() || me.dwheel == 0 ) - { - return; - } + @SubscribeEvent + public void updateTextureSheet(final TextureStitchEvent.Pre ev) { + if (ev.map.getTextureType() == 1) { + for (final ExtraItemTextures et : ExtraItemTextures.values()) { + et.registerIcon(ev.map); + } + } - final Minecraft mc = Minecraft.getMinecraft(); - final EntityPlayer player = mc.thePlayer; - final ItemStack is = player.getHeldItem(); + if (ev.map.getTextureType() == 0) { + for (final ExtraBlockTextures et : ExtraBlockTextures.values()) { + et.registerIcon(ev.map); + } - 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( final IOException e ) - { - AELog.debug( e ); - } - } - } - - @SubscribeEvent - public void updateTextureSheet( final TextureStitchEvent.Pre ev ) - { - if( ev.map.getTextureType() == 1 ) - { - for( final ExtraItemTextures et : ExtraItemTextures.values() ) - { - et.registerIcon( ev.map ); - } - } - - if( ev.map.getTextureType() == 0 ) - { - for( final ExtraBlockTextures et : ExtraBlockTextures.values() ) - { - et.registerIcon( ev.map ); - } - - for( final CableBusTextures cb : CableBusTextures.values() ) - { - cb.registerIcon( ev.map ); - } - } - } + for (final 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 8929909e..37b512d5 100644 --- a/src/main/java/appeng/client/EffectType.java +++ b/src/main/java/appeng/client/EffectType.java @@ -18,8 +18,4 @@ package appeng.client; - -public enum EffectType -{ - Energy, Lightning, Vibrant, Crafting, Assembler, LightningArc -} +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 71abe2d3..9f5442d2 100644 --- a/src/main/java/appeng/client/gui/AEBaseGui.java +++ b/src/main/java/appeng/client/gui/AEBaseGui.java @@ -18,6 +18,11 @@ package appeng.client.gui; +import java.io.IOException; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.util.*; +import java.util.concurrent.TimeUnit; import appeng.api.storage.data.IAEItemStack; import appeng.client.gui.widgets.GuiScrollbar; @@ -57,892 +62,867 @@ import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.ParseException; -import java.util.*; -import java.util.concurrent.TimeUnit; - - -public abstract class AEBaseGui extends GuiContainer -{ - private static boolean switchingGuis; - private final List meSlots = new LinkedList(); - // drag y - private final Set drag_click = new HashSet(); - private final AppEngRenderItem aeRenderItem = new AppEngRenderItem(); - private GuiScrollbar scrollBar = null; - private boolean disableShiftClick = false; - private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); - private ItemStack dbl_whichItem; - private Slot bl_clicked; - private boolean subGui; - - public AEBaseGui( final Container container ) - { - super( container ); - this.subGui = switchingGuis; - switchingGuis = false; - } - - protected static String join( final Collection toolTip, final String delimiter ) - { - final Joiner joiner = Joiner.on( delimiter ); - - return joiner.join( toolTip ); - } - - protected int getQty( final GuiButton btn ) - { - try - { - final DecimalFormat df = new DecimalFormat( "+#;-#" ); - return df.parse( btn.displayString ).intValue(); - } - catch( final ParseException e ) - { - return 0; - } - } - - public boolean isSubGui() - { - return this.subGui; - } - - @Override - public void initGui() - { - super.initGui(); - - final List slots = this.getInventorySlots(); - final Iterator i = slots.iterator(); - while( i.hasNext() ) - { - if( i.next() instanceof SlotME ) - { - i.remove(); - } - } - - for( final InternalSlotME me : this.meSlots ) - { - slots.add( new SlotME( me ) ); - } - } - - @SuppressWarnings( "unchecked" ) - private List getInventorySlots() - { - return this.inventorySlots.inventorySlots; - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - super.drawScreen( mouseX, mouseY, btn ); - - for( final Object c : this.buttonList ) - { - if( c instanceof ITooltip ) - { - final ITooltip tooltip = (ITooltip) c; - final int x = tooltip.xPos(); // ((GuiImgButton) c).xPosition; - int y = tooltip.yPos(); // ((GuiImgButton) c).yPosition; - - if( x < mouseX && x + tooltip.getWidth() > mouseX && tooltip.isVisible() ) - { - if( y < mouseY && y + tooltip.getHeight() > mouseY ) - { - if( y < 15 ) - { - y = 15; - } - - final String msg = tooltip.getMessage(); - if( msg != null ) - { - this.drawTooltip( x + 11, y + 4, 0, msg ); - } - } - } - } - } - } - - public void drawTooltip( final int par2, final int par3, final int forceWidth, final String message ) - { - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - final String[] var4 = message.split( "\n" ); - - if( var4.length > 0 ) - { - int var5 = 0; - int var6; - int var7; - - for( var6 = 0; var6 < var4.length; ++var6 ) - { - var7 = this.fontRendererObj.getStringWidth( var4[var6] ); - - if( var7 > var5 ) - { - var5 = var7; - } - } - - var6 = par2 + 12; - var7 = par3 - 12; - int var9 = 8; - - if( var4.length > 1 ) - { - var9 += 2 + ( var4.length - 1 ) * 10; - } - - if( this.guiTop + var7 + var9 + 6 > this.height ) - { - var7 = this.height - var9 - this.guiTop - 6; - } - - if( forceWidth > 0 ) - { - var5 = forceWidth; - } - - this.zLevel = 300.0F; - itemRender.zLevel = 300.0F; - final int var10 = -267386864; - this.drawGradientRect( var6 - 3, var7 - 4, var6 + var5 + 3, var7 - 3, var10, var10 ); - this.drawGradientRect( var6 - 3, var7 + var9 + 3, var6 + var5 + 3, var7 + var9 + 4, var10, var10 ); - this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 + var9 + 3, var10, var10 ); - this.drawGradientRect( var6 - 4, var7 - 3, var6 - 3, var7 + var9 + 3, var10, var10 ); - this.drawGradientRect( var6 + var5 + 3, var7 - 3, var6 + var5 + 4, var7 + var9 + 3, var10, var10 ); - final int var11 = 1347420415; - final int var12 = ( var11 & 16711422 ) >> 1 | var11 & -16777216; - this.drawGradientRect( var6 - 3, var7 - 3 + 1, var6 - 3 + 1, var7 + var9 + 3 - 1, var11, var12 ); - this.drawGradientRect( var6 + var5 + 2, var7 - 3 + 1, var6 + var5 + 3, var7 + var9 + 3 - 1, var11, var12 ); - this.drawGradientRect( var6 - 3, var7 - 3, var6 + var5 + 3, var7 - 3 + 1, var11, var11 ); - this.drawGradientRect( var6 - 3, var7 + var9 + 2, var6 + var5 + 3, var7 + var9 + 3, var12, var12 ); - - for( int var13 = 0; var13 < var4.length; ++var13 ) - { - String var14 = var4[var13]; - - if( var13 == 0 ) - { - var14 = '\u00a7' + Integer.toHexString( 15 ) + var14; - } - else - { - var14 = "\u00a77" + var14; - } - - this.fontRendererObj.drawStringWithShadow( var14, var6, var7, -1 ); - - if( var13 == 0 ) - { - var7 += 2; - } - - var7 += 10; - } - - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - } - GL11.glPopAttrib(); - } - - @Override - protected final void drawGuiContainerForegroundLayer( final int x, final int y ) - { - final int ox = this.guiLeft; // (width - xSize) / 2; - final int oy = this.guiTop; // (height - ySize) / 2; - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - if( this.getScrollBar() != null ) - { - this.getScrollBar().draw( this ); - } - - this.drawFG( ox, oy, x, y ); - } - - public abstract void drawFG( int offsetX, int offsetY, int mouseX, int mouseY ); - - @Override - protected final void drawGuiContainerBackgroundLayer( final float f, final int x, final int y ) - { - final int ox = this.guiLeft; // (width - xSize) / 2; - final int oy = this.guiTop; // (height - ySize) / 2; - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - this.drawBG( ox, oy, x, y ); - - final List slots = this.getInventorySlots(); - for( final Slot slot : slots ) - { - if( slot instanceof OptionalSlotFake ) - { - final OptionalSlotFake fs = (OptionalSlotFake) slot; - if( fs.renderDisabled() ) - { - if( fs.isEnabled() ) - { - this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, - 18 ); - } - else - { - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 0.4F ); - GL11.glEnable( GL11.GL_BLEND ); - this.drawTexturedModalRect( ox + fs.xDisplayPosition - 1, oy + fs.yDisplayPosition - 1, fs.getSourceX() - 1, fs.getSourceY() - 1, 18, 18 ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glPopAttrib(); - } - } - } - } - } - - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - this.drag_click.clear(); - - if( btn == 1 ) - { - for( final Object o : this.buttonList ) - { - final GuiButton guibutton = (GuiButton) o; - if( guibutton.mousePressed( this.mc, xCoord, yCoord ) ) - { - super.mouseClicked( xCoord, yCoord, 0 ); - return; - } - } - } - - if( this.getScrollBar() != null ) - { - this.getScrollBar().click( this, xCoord - this.guiLeft, yCoord - this.guiTop ); - } - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - protected void mouseClickMove( final int x, final int y, final int c, final long d ) - { - final Slot slot = this.getSlot( x, y ); - final ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); - - if( this.getScrollBar() != null ) - { - this.getScrollBar().click( this, x - this.guiLeft, y - this.guiTop ); - } - - if( slot instanceof SlotFake && itemstack != null ) - { - this.drag_click.add( slot ); - if( this.drag_click.size() > 1 ) - { - for( final Slot dr : this.drag_click ) - { - final PacketInventoryAction p = new PacketInventoryAction( c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN : InventoryAction.PLACE_SINGLE, dr.slotNumber, 0 ); - NetworkHandler.instance.sendToServer( p ); - } - } - } - else - { - super.mouseClickMove( x, y, c, d ); - } - } - - @Override - protected void handleMouseClick( final Slot slot, final int slotIdx, final int ctrlDown, final int mouseButton ) - { - final EntityPlayer player = Minecraft.getMinecraft().thePlayer; - - if( slot instanceof SlotFake ) - { - final InventoryAction action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; - - if( this.drag_click.size() > 1 ) - { - return; - } - - final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); - NetworkHandler.instance.sendToServer( p ); - - return; - } - - if( slot instanceof SlotPatternTerm ) - { - if( mouseButton == 6 ) - { - return; // prevent weird double clicks.. - } - - try - { - NetworkHandler.instance.sendToServer( ( (SlotPatternTerm) slot ).getRequest( isShiftKeyDown() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else if( slot instanceof SlotCraftingTerm ) - { - if( mouseButton == 6 ) - { - return; // prevent weird double clicks.. - } - - InventoryAction action = null; - if( isShiftKeyDown() ) - { - action = InventoryAction.CRAFT_SHIFT; - } - else - { - // Craft stack on right-click, craft single on left-click - action = ( mouseButton == 1 ) ? InventoryAction.CRAFT_STACK : InventoryAction.CRAFT_ITEM; - } - - final PacketInventoryAction p = new PacketInventoryAction( action, slotIdx, 0 ); - NetworkHandler.instance.sendToServer( p ); - - return; - } - - if( Keyboard.isKeyDown( Keyboard.KEY_SPACE ) ) - { - if( this.enableSpaceClicking() && !( slot instanceof SlotPatternTerm ) ) - { - IAEItemStack stack = null; - if( slot instanceof SlotME ) - { - stack = ( (SlotME) slot ).getAEStack(); - } - - int slotNum = this.getInventorySlots().size(); - - if( !( slot instanceof SlotME ) && slot != null ) - { - slotNum = slot.slotNumber; - } - - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); - final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, slotNum, 0 ); - NetworkHandler.instance.sendToServer( p ); - return; - } - } - - if( slot instanceof SlotDisconnected ) - { - InventoryAction action = null; - - switch( mouseButton ) - { - case 0: // pickup / set-down. - action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; - break; - case 1: - action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; - break; - - case 3: // creative dupe: - - if( player.capabilities.isCreativeMode ) - { - action = InventoryAction.CREATIVE_DUPLICATE; - } - - break; - - default: - case 4: // drop item: - case 6: - } - - if( action != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( action, slot.getSlotIndex(), ( (SlotDisconnected) slot ).getSlot().getId() ); - NetworkHandler.instance.sendToServer( p ); - } - - return; - } - - if( slot instanceof SlotME ) - { - InventoryAction action = null; - IAEItemStack stack = null; - - switch( mouseButton ) - { - case 0: // pickup / set-down. - action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE : InventoryAction.PICKUP_OR_SET_DOWN; - stack = ( (SlotME) slot ).getAEStack(); - - if( stack != null && action == InventoryAction.PICKUP_OR_SET_DOWN && stack.getStackSize() == 0 && player.inventory.getItemStack() == null ) - { - action = InventoryAction.AUTO_CRAFT; - } - - break; - case 1: - action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE : InventoryAction.SHIFT_CLICK; - stack = ( (SlotME) slot ).getAEStack(); - break; - - case 3: // creative dupe: - - stack = ( (SlotME) slot ).getAEStack(); - if( stack != null && stack.isCraftable() ) - { - action = InventoryAction.AUTO_CRAFT; - } - else if( player.capabilities.isCreativeMode ) - { - final IAEItemStack slotItem = ( (SlotME) slot ).getAEStack(); - if( slotItem != null ) - { - action = InventoryAction.CREATIVE_DUPLICATE; - } - } - break; - - default: - case 4: // drop item: - case 6: - } - - if( action != null ) - { - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( stack ); - final PacketInventoryAction p = new PacketInventoryAction( action, this.getInventorySlots().size(), 0 ); - NetworkHandler.instance.sendToServer( p ); - } - - return; - } - - if( !this.disableShiftClick && isShiftKeyDown() ) - { - this.disableShiftClick = true; - - if( this.dbl_whichItem == null || this.bl_clicked != slot || this.dbl_clickTimer.elapsed( TimeUnit.MILLISECONDS ) > 150 ) - { - // some simple double click logic. - this.bl_clicked = slot; - this.dbl_clickTimer = Stopwatch.createStarted(); - if( slot != null ) - { - this.dbl_whichItem = slot.getHasStack() ? slot.getStack().copy() : null; - } - else - { - this.dbl_whichItem = null; - } - } - else if( this.dbl_whichItem != null ) - { - // a replica of the weird broken vanilla feature. - - final List slots = this.getInventorySlots(); - for( final Slot inventorySlot : slots ) - { - if( inventorySlot != null && inventorySlot.canTakeStack( - this.mc.thePlayer ) && inventorySlot.getHasStack() && inventorySlot.inventory == slot.inventory && Container.func_94527_a( - inventorySlot, this.dbl_whichItem, true ) ) - { - this.handleMouseClick( inventorySlot, inventorySlot.slotNumber, ctrlDown, 1 ); - } - } - } - - this.disableShiftClick = false; - } - - super.handleMouseClick( slot, slotIdx, ctrlDown, mouseButton ); - } - - @Override - protected boolean checkHotbarKeys( final int keyCode ) - { - final Slot theSlot; - - try - { - theSlot = ObfuscationReflectionHelper.getPrivateValue( GuiContainer.class, this, "theSlot", "field_147006_u", "f" ); - } - catch( final Throwable t ) - { - return false; - } - - if( this.mc.thePlayer.inventory.getItemStack() == null && theSlot != null ) - { - for( int j = 0; j < 9; ++j ) - { - if( keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode() ) - { - final List slots = this.getInventorySlots(); - for( final Slot s : slots ) - { - if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) - { - if( !s.canTakeStack( ( (AEBaseContainer) this.inventorySlots ).getPlayerInv().player ) ) - { - return false; - } - } - } - - if( theSlot.getSlotStackLimit() == 64 ) - { - this.handleMouseClick( theSlot, theSlot.slotNumber, j, 2 ); - return true; - } - else - { - for( final Slot s : slots ) - { - if( s.getSlotIndex() == j && s.inventory == ( (AEBaseContainer) this.inventorySlots ).getPlayerInv() ) - { - NetworkHandler.instance.sendToServer( new PacketSwapSlots( s.slotNumber, theSlot.slotNumber ) ); - return true; - } - } - } - } - } - } - - return false; - } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - this.subGui = true; // in case the gui is reopened later ( i'm looking at you NEI ) - } - - protected Slot getSlot( final int mouseX, final int mouseY ) - { - final List slots = this.getInventorySlots(); - for( final 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 - public void handleMouseInput() - { - super.handleMouseInput(); - - final int i = Mouse.getEventDWheel(); - if( i != 0 && isShiftKeyDown() ) - { - final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; - final int y = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; - this.mouseWheelEvent( x, y, i / Math.abs( i ) ); - } - else if( i != 0 && this.getScrollBar() != null ) - { - this.getScrollBar().wheel( i ); - } - } - - private void mouseWheelEvent( final int x, final int y, final int wheel ) - { - final Slot slot = this.getSlot( x, y ); - if( slot instanceof SlotME ) - { - final IAEItemStack item = ( (SlotME) slot ).getAEStack(); - if( item != null ) - { - ( (AEBaseContainer) this.inventorySlots ).setTargetStack( item ); - final InventoryAction direction = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; - final int times = Math.abs( wheel ); - final int inventorySize = this.getInventorySlots().size(); - for( int h = 0; h < times; h++ ) - { - final PacketInventoryAction p = new PacketInventoryAction( direction, inventorySize, 0 ); - NetworkHandler.instance.sendToServer( p ); - } - } - } - } - - protected boolean enableSpaceClicking() - { - return true; - } - - public void bindTexture( final String base, final String file ) - { - final ResourceLocation loc = new ResourceLocation( base, "textures/" + file ); - this.mc.getTextureManager().bindTexture( loc ); - } - - protected void drawItem( final int x, final int y, final ItemStack is ) - { - this.zLevel = 100.0F; - itemRender.zLevel = 100.0F; - - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - RenderHelper.enableGUIStandardItemLighting(); - itemRender.renderItemAndEffectIntoGUI( this.fontRendererObj, this.mc.renderEngine, is, x, y ); - GL11.glPopAttrib(); - - itemRender.zLevel = 0.0F; - this.zLevel = 0.0F; - } - - protected String getGuiDisplayName( final String in ) - { - return this.hasCustomInventoryName() ? this.getInventoryName() : in; - } - - private boolean hasCustomInventoryName() - { - if( this.inventorySlots instanceof AEBaseContainer ) - { - return ( (AEBaseContainer) this.inventorySlots ).getCustomName() != null; - } - return false; - } - - private String getInventoryName() - { - return ( (AEBaseContainer) this.inventorySlots ).getCustomName(); - } - - private void drawSlot( final Slot s ) - { - if( s instanceof SlotME ) - { - final RenderItem pIR = this.setItemRender( this.aeRenderItem ); - try - { - this.zLevel = 100.0F; - itemRender.zLevel = 100.0F; - - if( !this.isPowered() ) - { - GL11.glDisable( GL11.GL_LIGHTING ); - drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, 0x66111111 ); - GL11.glEnable( GL11.GL_LIGHTING ); - } - - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - - this.aeRenderItem.setAeStack( ( (SlotME) s ).getAEStack() ); - - this.safeDrawSlot( s ); - } - catch( final Exception err ) - { - AELog.warn( "[AppEng] AE prevented crash while drawing slot: " + err.toString() ); - } - this.setItemRender( pIR ); - return; - } - else - { - try - { - final ItemStack is = s.getStack(); - if( s instanceof AppEngSlot && ( ( (AppEngSlot) s ).renderIconWithItem() || is == null ) && ( ( (AppEngSlot) s ).shouldDisplay() ) ) - { - final AppEngSlot aes = (AppEngSlot) s; - if( aes.getIcon() >= 0 ) - { - this.bindTexture( "guis/states.png" ); - - GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - final Tessellator tessellator = Tessellator.instance; - try - { - final int uv_y = (int) Math.floor( aes.getIcon() / 16 ); - final int uv_x = aes.getIcon() - uv_y * 16; - - GL11.glEnable( GL11.GL_BLEND ); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - final float par1 = aes.xDisplayPosition; - final float par2 = aes.yDisplayPosition; - final float par3 = uv_x * 16; - final float par4 = uv_y * 16; - - tessellator.startDrawingQuads(); - tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() ); - final float f1 = 0.00390625F; - final float f = 0.00390625F; - final float par6 = 16; - tessellator.addVertexWithUV( par1 + 0, par2 + par6, this.zLevel, ( par3 + 0 ) * f, ( par4 + par6 ) * f1 ); - final float par5 = 16; - tessellator.addVertexWithUV( par1 + par5, par2 + par6, this.zLevel, ( par3 + par5 ) * f, ( par4 + par6 ) * f1 ); - tessellator.addVertexWithUV( par1 + par5, par2 + 0, this.zLevel, ( par3 + par5 ) * f, ( par4 + 0 ) * f1 ); - tessellator.addVertexWithUV( par1 + 0, par2 + 0, this.zLevel, ( par3 + 0 ) * f, ( par4 + 0 ) * f1 ); - tessellator.setColorRGBA_F( 1.0f, 1.0f, 1.0f, 1.0f ); - tessellator.draw(); - - } - catch( final Exception err ) - { - } - GL11.glPopAttrib(); - } - } - - if( is != null && s instanceof AppEngSlot ) - { - if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.NotAvailable ) - { - boolean isValid = s.isItemValid( - is ) || s instanceof SlotOutput || s instanceof AppEngCraftingSlot || s instanceof SlotDisabled || s instanceof SlotInaccessible || s instanceof SlotFake || s instanceof SlotRestrictedInput || s instanceof SlotDisconnected; - if( isValid && s instanceof SlotRestrictedInput ) - { - try - { - isValid = ( (SlotRestrictedInput) s ).isValid( is, this.mc.theWorld ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - } - ( (AppEngSlot) s ).setIsValid( isValid ? hasCalculatedValidness.Valid : hasCalculatedValidness.Invalid ); - } - - if( ( (AppEngSlot) s ).getIsValid() == hasCalculatedValidness.Invalid ) - { - this.zLevel = 100.0F; - itemRender.zLevel = 100.0F; - - GL11.glDisable( GL11.GL_LIGHTING ); - drawRect( s.xDisplayPosition, s.yDisplayPosition, 16 + s.xDisplayPosition, 16 + s.yDisplayPosition, 0x66ff6666 ); - GL11.glEnable( GL11.GL_LIGHTING ); - - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - } - } - - if( s instanceof AppEngSlot ) - { - ( (AppEngSlot) s ).setDisplay( true ); - this.safeDrawSlot( s ); - } - else - { - this.safeDrawSlot( s ); - } - - return; - } - catch( final Exception err ) - { - AELog.warn( "[AppEng] AE prevented crash while drawing slot: " + err.toString() ); - } - } - // do the usual for non-ME Slots. - this.safeDrawSlot( s ); - } - - private RenderItem setItemRender( final RenderItem item ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ) ) - { - return ( (INEI) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.NEI ) ).setItemRender( item ); - } - else - { - final RenderItem ri = itemRender; - itemRender = item; - return ri; - } - } - - protected boolean isPowered() - { - return true; - } - - private void safeDrawSlot( final Slot s ) - { - try - { - GuiContainer.class.getDeclaredMethod( "func_146977_a_original", Slot.class ).invoke( this, s ); - } - catch( final Exception err ) - { - } - } - - public void bindTexture( final String file ) - { - final ResourceLocation loc = new ResourceLocation( AppEng.MOD_ID, "textures/" + file ); - this.mc.getTextureManager().bindTexture( loc ); - } - - public void func_146977_a( final Slot s ) - { - this.drawSlot( s ); - } - - protected GuiScrollbar getScrollBar() - { - return this.scrollBar; - } - - protected void setScrollBar( final GuiScrollbar myScrollBar ) - { - this.scrollBar = myScrollBar; - } - - protected List getMeSlots() - { - return this.meSlots; - } - - public static final synchronized boolean isSwitchingGuis() - { - return switchingGuis; - } - - public static final synchronized void setSwitchingGuis( final boolean switchingGuis ) - { - AEBaseGui.switchingGuis = switchingGuis; - } +public abstract class AEBaseGui extends GuiContainer { + private static boolean switchingGuis; + private final List meSlots = new LinkedList(); + // drag y + private final Set drag_click = new HashSet(); + private final AppEngRenderItem aeRenderItem = new AppEngRenderItem(); + private GuiScrollbar scrollBar = null; + private boolean disableShiftClick = false; + private Stopwatch dbl_clickTimer = Stopwatch.createStarted(); + private ItemStack dbl_whichItem; + private Slot bl_clicked; + private boolean subGui; + + public AEBaseGui(final Container container) { + super(container); + this.subGui = switchingGuis; + switchingGuis = false; + } + + protected static String + join(final Collection toolTip, final String delimiter) { + final Joiner joiner = Joiner.on(delimiter); + + return joiner.join(toolTip); + } + + protected int getQty(final GuiButton btn) { + try { + final DecimalFormat df = new DecimalFormat("+#;-#"); + return df.parse(btn.displayString).intValue(); + } catch (final ParseException e) { + return 0; + } + } + + public boolean isSubGui() { + return this.subGui; + } + + @Override + public void initGui() { + super.initGui(); + + final List slots = this.getInventorySlots(); + final Iterator i = slots.iterator(); + while (i.hasNext()) { + if (i.next() instanceof SlotME) { + i.remove(); + } + } + + for (final InternalSlotME me : this.meSlots) { + slots.add(new SlotME(me)); + } + } + + @SuppressWarnings("unchecked") + private List getInventorySlots() { + return this.inventorySlots.inventorySlots; + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + super.drawScreen(mouseX, mouseY, btn); + + for (final Object c : this.buttonList) { + if (c instanceof ITooltip) { + final ITooltip tooltip = (ITooltip) c; + final int x = tooltip.xPos(); // ((GuiImgButton) c).xPosition; + int y = tooltip.yPos(); // ((GuiImgButton) c).yPosition; + + if (x < mouseX && x + tooltip.getWidth() > mouseX + && tooltip.isVisible()) { + if (y < mouseY && y + tooltip.getHeight() > mouseY) { + if (y < 15) { + y = 15; + } + + final String msg = tooltip.getMessage(); + if (msg != null) { + this.drawTooltip(x + 11, y + 4, 0, msg); + } + } + } + } + } + } + + public void drawTooltip( + final int par2, final int par3, final int forceWidth, final String message + ) { + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + final String[] var4 = message.split("\n"); + + if (var4.length > 0) { + int var5 = 0; + int var6; + int var7; + + for (var6 = 0; var6 < var4.length; ++var6) { + var7 = this.fontRendererObj.getStringWidth(var4[var6]); + + if (var7 > var5) { + var5 = var7; + } + } + + var6 = par2 + 12; + var7 = par3 - 12; + int var9 = 8; + + if (var4.length > 1) { + var9 += 2 + (var4.length - 1) * 10; + } + + if (this.guiTop + var7 + var9 + 6 > this.height) { + var7 = this.height - var9 - this.guiTop - 6; + } + + if (forceWidth > 0) { + var5 = forceWidth; + } + + this.zLevel = 300.0F; + itemRender.zLevel = 300.0F; + final int var10 = -267386864; + this.drawGradientRect( + var6 - 3, var7 - 4, var6 + var5 + 3, var7 - 3, var10, var10 + ); + this.drawGradientRect( + var6 - 3, var7 + var9 + 3, var6 + var5 + 3, var7 + var9 + 4, var10, var10 + ); + this.drawGradientRect( + var6 - 3, var7 - 3, var6 + var5 + 3, var7 + var9 + 3, var10, var10 + ); + this.drawGradientRect( + var6 - 4, var7 - 3, var6 - 3, var7 + var9 + 3, var10, var10 + ); + this.drawGradientRect( + var6 + var5 + 3, var7 - 3, var6 + var5 + 4, var7 + var9 + 3, var10, var10 + ); + final int var11 = 1347420415; + final int var12 = (var11 & 16711422) >> 1 | var11 & -16777216; + this.drawGradientRect( + var6 - 3, var7 - 3 + 1, var6 - 3 + 1, var7 + var9 + 3 - 1, var11, var12 + ); + this.drawGradientRect( + var6 + var5 + 2, + var7 - 3 + 1, + var6 + var5 + 3, + var7 + var9 + 3 - 1, + var11, + var12 + ); + this.drawGradientRect( + var6 - 3, var7 - 3, var6 + var5 + 3, var7 - 3 + 1, var11, var11 + ); + this.drawGradientRect( + var6 - 3, var7 + var9 + 2, var6 + var5 + 3, var7 + var9 + 3, var12, var12 + ); + + for (int var13 = 0; var13 < var4.length; ++var13) { + String var14 = var4[var13]; + + if (var13 == 0) { + var14 = '\u00a7' + Integer.toHexString(15) + var14; + } else { + var14 = "\u00a77" + var14; + } + + this.fontRendererObj.drawStringWithShadow(var14, var6, var7, -1); + + if (var13 == 0) { + var7 += 2; + } + + var7 += 10; + } + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + GL11.glPopAttrib(); + } + + @Override + protected final void drawGuiContainerForegroundLayer(final int x, final int y) { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + + if (this.getScrollBar() != null) { + this.getScrollBar().draw(this); + } + + this.drawFG(ox, oy, x, y); + } + + public abstract void drawFG(int offsetX, int offsetY, int mouseX, int mouseY); + + @Override + protected final void + drawGuiContainerBackgroundLayer(final float f, final int x, final int y) { + final int ox = this.guiLeft; // (width - xSize) / 2; + final int oy = this.guiTop; // (height - ySize) / 2; + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + this.drawBG(ox, oy, x, y); + + final List slots = this.getInventorySlots(); + for (final Slot slot : slots) { + if (slot instanceof OptionalSlotFake) { + final OptionalSlotFake fs = (OptionalSlotFake) slot; + if (fs.renderDisabled()) { + if (fs.isEnabled()) { + this.drawTexturedModalRect( + ox + fs.xDisplayPosition - 1, + oy + fs.yDisplayPosition - 1, + fs.getSourceX() - 1, + fs.getSourceY() - 1, + 18, + 18 + ); + } else { + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.4F); + GL11.glEnable(GL11.GL_BLEND); + this.drawTexturedModalRect( + ox + fs.xDisplayPosition - 1, + oy + fs.yDisplayPosition - 1, + fs.getSourceX() - 1, + fs.getSourceY() - 1, + 18, + 18 + ); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glPopAttrib(); + } + } + } + } + } + + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + this.drag_click.clear(); + + if (btn == 1) { + for (final Object o : this.buttonList) { + final GuiButton guibutton = (GuiButton) o; + if (guibutton.mousePressed(this.mc, xCoord, yCoord)) { + super.mouseClicked(xCoord, yCoord, 0); + return; + } + } + } + + if (this.getScrollBar() != null) { + this.getScrollBar().click(this, xCoord - this.guiLeft, yCoord - this.guiTop); + } + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + protected void mouseClickMove(final int x, final int y, final int c, final long d) { + final Slot slot = this.getSlot(x, y); + final ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); + + if (this.getScrollBar() != null) { + this.getScrollBar().click(this, x - this.guiLeft, y - this.guiTop); + } + + if (slot instanceof SlotFake && itemstack != null) { + this.drag_click.add(slot); + if (this.drag_click.size() > 1) { + for (final Slot dr : this.drag_click) { + final PacketInventoryAction p = new PacketInventoryAction( + c == 0 ? InventoryAction.PICKUP_OR_SET_DOWN + : InventoryAction.PLACE_SINGLE, + dr.slotNumber, + 0 + ); + NetworkHandler.instance.sendToServer(p); + } + } + } else { + super.mouseClickMove(x, y, c, d); + } + } + + @Override + protected void handleMouseClick( + final Slot slot, final int slotIdx, final int ctrlDown, final int mouseButton + ) { + final EntityPlayer player = Minecraft.getMinecraft().thePlayer; + + if (slot instanceof SlotFake) { + final InventoryAction action = ctrlDown == 1 + ? InventoryAction.SPLIT_OR_PLACE_SINGLE + : InventoryAction.PICKUP_OR_SET_DOWN; + + if (this.drag_click.size() > 1) { + return; + } + + final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0); + NetworkHandler.instance.sendToServer(p); + + return; + } + + if (slot instanceof SlotPatternTerm) { + if (mouseButton == 6) { + return; // prevent weird double clicks.. + } + + try { + NetworkHandler.instance.sendToServer( + ((SlotPatternTerm) slot).getRequest(isShiftKeyDown()) + ); + } catch (final IOException e) { + AELog.debug(e); + } + } else if (slot instanceof SlotCraftingTerm) { + if (mouseButton == 6) { + return; // prevent weird double clicks.. + } + + InventoryAction action = null; + if (isShiftKeyDown()) { + action = InventoryAction.CRAFT_SHIFT; + } else { + // Craft stack on right-click, craft single on left-click + action = (mouseButton == 1) ? InventoryAction.CRAFT_STACK + : InventoryAction.CRAFT_ITEM; + } + + final PacketInventoryAction p = new PacketInventoryAction(action, slotIdx, 0); + NetworkHandler.instance.sendToServer(p); + + return; + } + + if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { + if (this.enableSpaceClicking() && !(slot instanceof SlotPatternTerm)) { + IAEItemStack stack = null; + if (slot instanceof SlotME) { + stack = ((SlotME) slot).getAEStack(); + } + + int slotNum = this.getInventorySlots().size(); + + if (!(slot instanceof SlotME) && slot != null) { + slotNum = slot.slotNumber; + } + + ((AEBaseContainer) this.inventorySlots).setTargetStack(stack); + final PacketInventoryAction p + = new PacketInventoryAction(InventoryAction.MOVE_REGION, slotNum, 0); + NetworkHandler.instance.sendToServer(p); + return; + } + } + + if (slot instanceof SlotDisconnected) { + InventoryAction action = null; + + switch (mouseButton) { + case 0: // pickup / set-down. + action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE + : InventoryAction.PICKUP_OR_SET_DOWN; + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE + : InventoryAction.SHIFT_CLICK; + break; + + case 3: // creative dupe: + + if (player.capabilities.isCreativeMode) { + action = InventoryAction.CREATIVE_DUPLICATE; + } + + break; + + default: + case 4: // drop item: + case 6: + } + + if (action != null) { + final PacketInventoryAction p = new PacketInventoryAction( + action, + slot.getSlotIndex(), + ((SlotDisconnected) slot).getSlot().getId() + ); + NetworkHandler.instance.sendToServer(p); + } + + return; + } + + if (slot instanceof SlotME) { + InventoryAction action = null; + IAEItemStack stack = null; + + switch (mouseButton) { + case 0: // pickup / set-down. + action = ctrlDown == 1 ? InventoryAction.SPLIT_OR_PLACE_SINGLE + : InventoryAction.PICKUP_OR_SET_DOWN; + stack = ((SlotME) slot).getAEStack(); + + if (stack != null && action == InventoryAction.PICKUP_OR_SET_DOWN + && stack.getStackSize() == 0 + && player.inventory.getItemStack() == null) { + action = InventoryAction.AUTO_CRAFT; + } + + break; + case 1: + action = ctrlDown == 1 ? InventoryAction.PICKUP_SINGLE + : InventoryAction.SHIFT_CLICK; + stack = ((SlotME) slot).getAEStack(); + break; + + case 3: // creative dupe: + + stack = ((SlotME) slot).getAEStack(); + if (stack != null && stack.isCraftable()) { + action = InventoryAction.AUTO_CRAFT; + } else if (player.capabilities.isCreativeMode) { + final IAEItemStack slotItem = ((SlotME) slot).getAEStack(); + if (slotItem != null) { + action = InventoryAction.CREATIVE_DUPLICATE; + } + } + break; + + default: + case 4: // drop item: + case 6: + } + + if (action != null) { + ((AEBaseContainer) this.inventorySlots).setTargetStack(stack); + final PacketInventoryAction p = new PacketInventoryAction( + action, this.getInventorySlots().size(), 0 + ); + NetworkHandler.instance.sendToServer(p); + } + + return; + } + + if (!this.disableShiftClick && isShiftKeyDown()) { + this.disableShiftClick = true; + + if (this.dbl_whichItem == null || this.bl_clicked != slot + || this.dbl_clickTimer.elapsed(TimeUnit.MILLISECONDS) > 150) { + // some simple double click logic. + this.bl_clicked = slot; + this.dbl_clickTimer = Stopwatch.createStarted(); + if (slot != null) { + this.dbl_whichItem + = slot.getHasStack() ? slot.getStack().copy() : null; + } else { + this.dbl_whichItem = null; + } + } else if (this.dbl_whichItem != null) { + // a replica of the weird broken vanilla feature. + + final List slots = this.getInventorySlots(); + for (final Slot inventorySlot : slots) { + if (inventorySlot != null + && inventorySlot.canTakeStack(this.mc.thePlayer) + && inventorySlot.getHasStack() + && inventorySlot.inventory == slot.inventory + && Container.func_94527_a( + inventorySlot, this.dbl_whichItem, true + )) { + this.handleMouseClick( + inventorySlot, inventorySlot.slotNumber, ctrlDown, 1 + ); + } + } + } + + this.disableShiftClick = false; + } + + super.handleMouseClick(slot, slotIdx, ctrlDown, mouseButton); + } + + @Override + protected boolean checkHotbarKeys(final int keyCode) { + final Slot theSlot; + + try { + theSlot = ObfuscationReflectionHelper.getPrivateValue( + GuiContainer.class, this, "theSlot", "field_147006_u", "f" + ); + } catch (final Throwable t) { + return false; + } + + if (this.mc.thePlayer.inventory.getItemStack() == null && theSlot != null) { + for (int j = 0; j < 9; ++j) { + if (keyCode == this.mc.gameSettings.keyBindsHotbar[j].getKeyCode()) { + final List slots = this.getInventorySlots(); + for (final Slot s : slots) { + if (s.getSlotIndex() == j + && s.inventory + == ((AEBaseContainer) this.inventorySlots) + .getPlayerInv()) { + if (!s.canTakeStack(((AEBaseContainer) this.inventorySlots) + .getPlayerInv() + .player)) { + return false; + } + } + } + + if (theSlot.getSlotStackLimit() == 64) { + this.handleMouseClick(theSlot, theSlot.slotNumber, j, 2); + return true; + } else { + for (final Slot s : slots) { + if (s.getSlotIndex() == j + && s.inventory + == ((AEBaseContainer) this.inventorySlots) + .getPlayerInv()) { + NetworkHandler.instance.sendToServer( + new PacketSwapSlots(s.slotNumber, theSlot.slotNumber) + ); + return true; + } + } + } + } + } + } + + return false; + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + this.subGui + = true; // in case the gui is reopened later ( i'm looking at you NEI ) + } + + protected Slot getSlot(final int mouseX, final int mouseY) { + final List slots = this.getInventorySlots(); + for (final 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 + public void handleMouseInput() { + super.handleMouseInput(); + + final int i = Mouse.getEventDWheel(); + if (i != 0 && isShiftKeyDown()) { + final int x = Mouse.getEventX() * this.width / this.mc.displayWidth; + final int y = this.height + - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; + this.mouseWheelEvent(x, y, i / Math.abs(i)); + } else if (i != 0 && this.getScrollBar() != null) { + this.getScrollBar().wheel(i); + } + } + + private void mouseWheelEvent(final int x, final int y, final int wheel) { + final Slot slot = this.getSlot(x, y); + if (slot instanceof SlotME) { + final IAEItemStack item = ((SlotME) slot).getAEStack(); + if (item != null) { + ((AEBaseContainer) this.inventorySlots).setTargetStack(item); + final InventoryAction direction + = wheel > 0 ? InventoryAction.ROLL_DOWN : InventoryAction.ROLL_UP; + final int times = Math.abs(wheel); + final int inventorySize = this.getInventorySlots().size(); + for (int h = 0; h < times; h++) { + final PacketInventoryAction p + = new PacketInventoryAction(direction, inventorySize, 0); + NetworkHandler.instance.sendToServer(p); + } + } + } + } + + protected boolean enableSpaceClicking() { + return true; + } + + public void bindTexture(final String base, final String file) { + final ResourceLocation loc = new ResourceLocation(base, "textures/" + file); + this.mc.getTextureManager().bindTexture(loc); + } + + protected void drawItem(final int x, final int y, final ItemStack is) { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableGUIStandardItemLighting(); + itemRender.renderItemAndEffectIntoGUI( + this.fontRendererObj, this.mc.renderEngine, is, x, y + ); + GL11.glPopAttrib(); + + itemRender.zLevel = 0.0F; + this.zLevel = 0.0F; + } + + protected String getGuiDisplayName(final String in) { + return this.hasCustomInventoryName() ? this.getInventoryName() : in; + } + + private boolean hasCustomInventoryName() { + if (this.inventorySlots instanceof AEBaseContainer) { + return ((AEBaseContainer) this.inventorySlots).getCustomName() != null; + } + return false; + } + + private String getInventoryName() { + return ((AEBaseContainer) this.inventorySlots).getCustomName(); + } + + private void drawSlot(final Slot s) { + if (s instanceof SlotME) { + final RenderItem pIR = this.setItemRender(this.aeRenderItem); + try { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + if (!this.isPowered()) { + GL11.glDisable(GL11.GL_LIGHTING); + drawRect( + s.xDisplayPosition, + s.yDisplayPosition, + 16 + s.xDisplayPosition, + 16 + s.yDisplayPosition, + 0x66111111 + ); + GL11.glEnable(GL11.GL_LIGHTING); + } + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + + this.aeRenderItem.setAeStack(((SlotME) s).getAEStack()); + + this.safeDrawSlot(s); + } catch (final Exception err) { + AELog.warn( + "[AppEng] AE prevented crash while drawing slot: " + err.toString() + ); + } + this.setItemRender(pIR); + return; + } else { + try { + final ItemStack is = s.getStack(); + if (s instanceof AppEngSlot + && (((AppEngSlot) s).renderIconWithItem() || is == null) + && (((AppEngSlot) s).shouldDisplay())) { + final AppEngSlot aes = (AppEngSlot) s; + if (aes.getIcon() >= 0) { + this.bindTexture("guis/states.png"); + + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + final Tessellator tessellator = Tessellator.instance; + try { + final int uv_y = (int) Math.floor(aes.getIcon() / 16); + final int uv_x = aes.getIcon() - uv_y * 16; + + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glBlendFunc( + GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA + ); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + final float par1 = aes.xDisplayPosition; + final float par2 = aes.yDisplayPosition; + final float par3 = uv_x * 16; + final float par4 = uv_y * 16; + + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F( + 1.0f, 1.0f, 1.0f, aes.getOpacityOfIcon() + ); + final float f1 = 0.00390625F; + final float f = 0.00390625F; + final float par6 = 16; + tessellator.addVertexWithUV( + par1 + 0, + par2 + par6, + this.zLevel, + (par3 + 0) * f, + (par4 + par6) * f1 + ); + final float par5 = 16; + tessellator.addVertexWithUV( + par1 + par5, + par2 + par6, + this.zLevel, + (par3 + par5) * f, + (par4 + par6) * f1 + ); + tessellator.addVertexWithUV( + par1 + par5, + par2 + 0, + this.zLevel, + (par3 + par5) * f, + (par4 + 0) * f1 + ); + tessellator.addVertexWithUV( + par1 + 0, + par2 + 0, + this.zLevel, + (par3 + 0) * f, + (par4 + 0) * f1 + ); + tessellator.setColorRGBA_F(1.0f, 1.0f, 1.0f, 1.0f); + tessellator.draw(); + + } catch (final Exception err) {} + GL11.glPopAttrib(); + } + } + + if (is != null && s instanceof AppEngSlot) { + if (((AppEngSlot) s).getIsValid() + == hasCalculatedValidness.NotAvailable) { + boolean isValid = s.isItemValid(is) || s instanceof SlotOutput + || s instanceof AppEngCraftingSlot + || s instanceof SlotDisabled || s instanceof SlotInaccessible + || s instanceof SlotFake || s instanceof SlotRestrictedInput + || s instanceof SlotDisconnected; + if (isValid && s instanceof SlotRestrictedInput) { + try { + isValid = ((SlotRestrictedInput) s) + .isValid(is, this.mc.theWorld); + } catch (final Exception err) { + AELog.debug(err); + } + } + ((AppEngSlot) s) + .setIsValid( + isValid ? hasCalculatedValidness.Valid + : hasCalculatedValidness.Invalid + ); + } + + if (((AppEngSlot) s).getIsValid() == hasCalculatedValidness.Invalid) { + this.zLevel = 100.0F; + itemRender.zLevel = 100.0F; + + GL11.glDisable(GL11.GL_LIGHTING); + drawRect( + s.xDisplayPosition, + s.yDisplayPosition, + 16 + s.xDisplayPosition, + 16 + s.yDisplayPosition, + 0x66ff6666 + ); + GL11.glEnable(GL11.GL_LIGHTING); + + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } + } + + if (s instanceof AppEngSlot) { + ((AppEngSlot) s).setDisplay(true); + this.safeDrawSlot(s); + } else { + this.safeDrawSlot(s); + } + + return; + } catch (final Exception err) { + AELog.warn( + "[AppEng] AE prevented crash while drawing slot: " + err.toString() + ); + } + } + // do the usual for non-ME Slots. + this.safeDrawSlot(s); + } + + private RenderItem setItemRender(final RenderItem item) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + return ((INEI) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.NEI)) + .setItemRender(item); + } else { + final RenderItem ri = itemRender; + itemRender = item; + return ri; + } + } + + protected boolean isPowered() { + return true; + } + + private void safeDrawSlot(final Slot s) { + try { + GuiContainer.class.getDeclaredMethod("func_146977_a_original", Slot.class) + .invoke(this, s); + } catch (final Exception err) {} + } + + public void bindTexture(final String file) { + final ResourceLocation loc + = new ResourceLocation(AppEng.MOD_ID, "textures/" + file); + this.mc.getTextureManager().bindTexture(loc); + } + + public void func_146977_a(final Slot s) { + this.drawSlot(s); + } + + protected GuiScrollbar getScrollBar() { + return this.scrollBar; + } + + protected void setScrollBar(final GuiScrollbar myScrollBar) { + this.scrollBar = myScrollBar; + } + + protected List getMeSlots() { + return this.meSlots; + } + + public static final synchronized boolean isSwitchingGuis() { + return switchingGuis; + } + + public static final synchronized void setSwitchingGuis(final boolean switchingGuis) { + AEBaseGui.switchingGuis = switchingGuis; + } } diff --git a/src/main/java/appeng/client/gui/AEBaseMEGui.java b/src/main/java/appeng/client/gui/AEBaseMEGui.java index 7a110b77..a8c617b0 100644 --- a/src/main/java/appeng/client/gui/AEBaseMEGui.java +++ b/src/main/java/appeng/client/gui/AEBaseMEGui.java @@ -18,6 +18,9 @@ package appeng.client.gui; +import java.text.NumberFormat; +import java.util.List; +import java.util.Locale; import appeng.api.storage.data.IAEItemStack; import appeng.client.me.SlotME; @@ -27,118 +30,122 @@ import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import java.text.NumberFormat; -import java.util.List; -import java.util.Locale; +public abstract class AEBaseMEGui extends AEBaseGui { + public AEBaseMEGui(final Container container) { + super(container); + } + public List handleItemTooltip( + final ItemStack stack, + final int mouseX, + final int mouseY, + final List currentToolTip + ) { + if (stack != null) { + final Slot s = this.getSlot(mouseX, mouseY); + if (s instanceof SlotME) { + final int BigNumber + = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; -public abstract class AEBaseMEGui extends AEBaseGui -{ + IAEItemStack myStack = null; - public AEBaseMEGui( final Container container ) - { - super( container ); - } + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) {} - public List handleItemTooltip( final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip ) - { - if( stack != null ) - { - final Slot s = this.getSlot( mouseX, mouseY ); - if( s instanceof SlotME ) - { - final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; + if (myStack != null) { + if (myStack.getStackSize() > BigNumber + || (myStack.getStackSize() > 1 && stack.isItemDamaged())) { + final String local = ButtonToolTips.ItemsStored.getLocal(); + final String formattedAmount + = NumberFormat.getNumberInstance(Locale.US).format( + myStack.getStackSize() + ); + final String format = String.format(local, formattedAmount); - IAEItemStack myStack = null; + currentToolTip.add("\u00a77" + format); + } - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } + if (myStack.getCountRequestable() > 0) { + final String local = ButtonToolTips.ItemsRequestable.getLocal(); + final String formattedAmount + = NumberFormat.getNumberInstance(Locale.US).format( + myStack.getCountRequestable() + ); + final String format = String.format(local, formattedAmount); - if( myStack != null ) - { - if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) - { - final String local = ButtonToolTips.ItemsStored.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ); - final String format = String.format( local, formattedAmount ); + currentToolTip.add("\u00a77" + format); + } + } else if (stack.stackSize > BigNumber || (stack.stackSize > 1 && stack.isItemDamaged())) { + final String local = ButtonToolTips.ItemsStored.getLocal(); + final String formattedAmount + = NumberFormat.getNumberInstance(Locale.US).format(stack.stackSize + ); + final String format = String.format(local, formattedAmount); - currentToolTip.add( "\u00a77" + format ); - } + currentToolTip.add("\u00a77" + format); + } + } + } + return currentToolTip; + } - if( myStack.getCountRequestable() > 0 ) - { - final String local = ButtonToolTips.ItemsRequestable.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( myStack.getCountRequestable() ); - final String format = String.format( local, formattedAmount ); + // Vanilla version... + // protected void drawItemStackTooltip(ItemStack stack, int x, int y) + @Override + protected void renderToolTip(final ItemStack stack, final int x, final int y) { + final Slot s = this.getSlot(x, y); + if (s instanceof SlotME && stack != null) { + final int BigNumber + = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; - currentToolTip.add( "\u00a77" + format ); - } - } - else if( stack.stackSize > BigNumber || ( stack.stackSize > 1 && stack.isItemDamaged() ) ) - { - final String local = ButtonToolTips.ItemsStored.getLocal(); - final String formattedAmount = NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ); - final String format = String.format( local, formattedAmount ); + IAEItemStack myStack = null; - currentToolTip.add( "\u00a77" + format ); - } - } - } - return currentToolTip; - } + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) {} - // Vanilla version... - // protected void drawItemStackTooltip(ItemStack stack, int x, int y) - @Override - protected void renderToolTip( final ItemStack stack, final int x, final int y ) - { - final Slot s = this.getSlot( x, y ); - if( s instanceof SlotME && stack != null ) - { - final int BigNumber = AEConfig.instance.useTerminalUseLargeFont() ? 999 : 9999; + if (myStack != null) { + @SuppressWarnings("unchecked") + final List currentToolTip = stack.getTooltip( + this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips + ); - IAEItemStack myStack = null; + if (myStack.getStackSize() > BigNumber + || (myStack.getStackSize() > 1 && stack.isItemDamaged())) { + currentToolTip.add( + "Items Stored: " + + NumberFormat.getNumberInstance(Locale.US).format( + myStack.getStackSize() + ) + ); + } - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } + if (myStack.getCountRequestable() > 0) { + currentToolTip.add( + "Items Requestable: " + + NumberFormat.getNumberInstance(Locale.US).format( + myStack.getCountRequestable() + ) + ); + } - if( myStack != null ) - { - @SuppressWarnings( "unchecked" ) final List currentToolTip = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); - - if( myStack.getStackSize() > BigNumber || ( myStack.getStackSize() > 1 && stack.isItemDamaged() ) ) - { - currentToolTip.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( myStack.getStackSize() ) ); - } - - 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 ) - { - final List var4 = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); - var4.add( "Items Stored: " + NumberFormat.getNumberInstance( Locale.US ).format( stack.stackSize ) ); - this.drawTooltip( x, y, 0, join( var4, "\n" ) ); - return; - } - } - super.renderToolTip( stack, x, y ); - // super.drawItemStackTooltip( stack, x, y ); - } + this.drawTooltip(x, y, 0, join(currentToolTip, "\n")); + } else if (stack.stackSize > BigNumber) { + final List var4 = stack.getTooltip( + this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips + ); + var4.add( + "Items Stored: " + + NumberFormat.getNumberInstance(Locale.US).format(stack.stackSize) + ); + this.drawTooltip(x, y, 0, join(var4, "\n")); + return; + } + } + 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 e8ac394d..d712f6cb 100644 --- a/src/main/java/appeng/client/gui/GuiNull.java +++ b/src/main/java/appeng/client/gui/GuiNull.java @@ -18,26 +18,18 @@ package appeng.client.gui; - import net.minecraft.inventory.Container; +public class GuiNull extends AEBaseGui { + public GuiNull(final Container container) { + super(container); + } -public class GuiNull extends AEBaseGui -{ + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) {} - public GuiNull( final Container container ) - { - super( container ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 f395aa38..b7e42f18 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGui.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGui.java @@ -18,6 +18,8 @@ package appeng.client.gui.config; +import java.util.ArrayList; +import java.util.List; import appeng.core.AEConfig; import appeng.core.AppEng; @@ -27,45 +29,40 @@ import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.ConfigElement; -import java.util.ArrayList; -import java.util.List; +public class AEConfigGui extends GuiConfig { + public AEConfigGui(final GuiScreen parent) { + super( + parent, + getConfigElements(), + AppEng.MOD_ID, + false, + false, + GuiConfig.getAbridgedConfigPath(AEConfig.instance.getFilePath()) + ); + } + private static List getConfigElements() { + final List list = new ArrayList(); -public class AEConfigGui extends GuiConfig -{ + for (final String cat : AEConfig.instance.getCategoryNames()) { + if (cat.equals("versionchecker")) { + continue; + } - public AEConfigGui( final GuiScreen parent ) - { - super( parent, getConfigElements(), AppEng.MOD_ID, false, false, GuiConfig.getAbridgedConfigPath( AEConfig.instance.getFilePath() ) ); - } + if (cat.equals("settings")) { + continue; + } - private static List getConfigElements() - { - final List list = new ArrayList(); + final ConfigCategory cc = AEConfig.instance.getCategory(cat); - for( final String cat : AEConfig.instance.getCategoryNames() ) - { - if( cat.equals( "versionchecker" ) ) - { - continue; - } + if (cc.isChild()) { + continue; + } - if( cat.equals( "settings" ) ) - { - continue; - } + final ConfigElement ce = new ConfigElement(cc); + list.add(ce); + } - final ConfigCategory cc = AEConfig.instance.getCategory( cat ); - - if( cc.isChild() ) - { - continue; - } - - final ConfigElement ce = new ConfigElement( cc ); - list.add( ce ); - } - - return list; - } + return list; + } } diff --git a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java index 4bd50347..93f7f76b 100644 --- a/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java +++ b/src/main/java/appeng/client/gui/config/AEConfigGuiFactory.java @@ -18,38 +18,29 @@ package appeng.client.gui.config; +import java.util.Set; import cpw.mods.fml.client.IModGuiFactory; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; -import java.util.Set; +public class AEConfigGuiFactory implements IModGuiFactory { + @Override + public void initialize(final Minecraft minecraftInstance) {} + @Override + public Class mainConfigGuiClass() { + return AEConfigGui.class; + } -public class AEConfigGuiFactory implements IModGuiFactory -{ + @Override + public Set runtimeGuiCategories() { + return null; + } - @Override - public void initialize( final Minecraft minecraftInstance ) - { - - } - - @Override - public Class mainConfigGuiClass() - { - return AEConfigGui.class; - } - - @Override - public Set runtimeGuiCategories() - { - return null; - } - - @Override - public RuntimeOptionGuiHandler getHandlerFor( final RuntimeOptionCategoryElement element ) - { - return null; - } + @Override + public RuntimeOptionGuiHandler + getHandlerFor(final 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 e00bd6d0..e1f10f95 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 appeng.api.config.*; import appeng.api.implementations.items.IUpgradeModule; @@ -35,167 +36,206 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; -import java.io.IOException; +public class GuiCellWorkbench extends GuiUpgradeable { + private final ContainerCellWorkbench workbench; + private GuiImgButton clear; + private GuiImgButton partition; + private GuiToggleButton copyMode; -public class GuiCellWorkbench extends GuiUpgradeable -{ + public GuiCellWorkbench( + final InventoryPlayer inventoryPlayer, final TileCellWorkbench te + ) { + super(new ContainerCellWorkbench(inventoryPlayer, te)); + this.workbench = (ContainerCellWorkbench) this.inventorySlots; + this.ySize = 251; + } - private final ContainerCellWorkbench workbench; + @Override + protected void addButtons() { + this.clear = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE + ); + this.partition = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH + ); + this.copyMode = new GuiToggleButton( + this.guiLeft - 18, + this.guiTop + 48, + 11 * 16 + 5, + 12 * 16 + 5, + GuiText.CopyMode.getLocal(), + GuiText.CopyModeDesc.getLocal() + ); + this.fuzzyMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 68, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); - private GuiImgButton clear; - private GuiImgButton partition; - private GuiToggleButton copyMode; + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.partition); + this.buttonList.add(this.clear); + this.buttonList.add(this.copyMode); + } - public GuiCellWorkbench( final InventoryPlayer inventoryPlayer, final TileCellWorkbench te ) - { - super( new ContainerCellWorkbench( inventoryPlayer, te ) ); - this.workbench = (ContainerCellWorkbench) this.inventorySlots; - this.ySize = 251; - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.handleButtonVisibility(); - @Override - protected void addButtons() - { - this.clear = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE ); - this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ); - this.copyMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 48, 11 * 16 + 5, 12 * 16 + 5, GuiText.CopyMode.getLocal(), GuiText.CopyModeDesc.getLocal() ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); + 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 + ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.partition ); - this.buttonList.add( this.clear ); - this.buttonList.add( this.copyMode ); - } + final 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 + ); - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.handleButtonVisibility(); + 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 + ); - 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 ); + final 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 + ); + } + } - final 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 ); + @Override + protected void handleButtonVisibility() { + this.copyMode.setState(this.workbench.getCopyMode() == CopyMode.CLEAR_ON_REMOVE); - 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 ); + boolean hasFuzzy = false; + final IInventory inv = this.workbench.getCellUpgradeInventory(); + for (int x = 0; x < inv.getSizeInventory(); x++) { + final ItemStack is = inv.getStackInSlot(x); + if (is != null && is.getItem() instanceof IUpgradeModule) { + if (((IUpgradeModule) is.getItem()).getType(is) == Upgrades.FUZZY) { + hasFuzzy = true; + } + } + } + this.fuzzyMode.setVisibility(hasFuzzy); + } - final 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 String getBackground() { + return "guis/cellworkbench.png"; + } - @Override - protected void handleButtonVisibility() - { - this.copyMode.setState( this.workbench.getCopyMode() == CopyMode.CLEAR_ON_REMOVE ); + @Override + protected boolean drawUpgrades() { + return this.workbench.availableUpgrades() > 0; + } - boolean hasFuzzy = false; - final IInventory inv = this.workbench.getCellUpgradeInventory(); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - final ItemStack is = inv.getStackInSlot( x ); - if( is != null && is.getItem() instanceof IUpgradeModule ) - { - if( ( (IUpgradeModule) is.getItem() ).getType( is ) == Upgrades.FUZZY ) - { - hasFuzzy = true; - } - } - } - this.fuzzyMode.setVisibility( hasFuzzy ); - } + @Override + protected GuiText getName() { + return GuiText.CellWorkbench; + } - @Override - protected String getBackground() - { - return "guis/cellworkbench.png"; - } + @Override + protected void actionPerformed(final 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) { + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected boolean drawUpgrades() - { - return this.workbench.availableUpgrades() > 0; - } + FuzzyMode fz = (FuzzyMode) this.fuzzyMode.getCurrentValue(); + fz = Platform.rotateEnum( + fz, backwards, Settings.FUZZY_MODE.getPossibleValues() + ); - @Override - protected GuiText getName() - { - return GuiText.CellWorkbench; - } - - @Override - protected void actionPerformed( final 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 ) - { - final 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( final IOException ignored ) - { - } - } + NetworkHandler.instance.sendToServer( + new PacketValueConfig("CellWorkbench.Fuzzy", fz.name()) + ); + } else { + super.actionPerformed(btn); + } + } catch (final 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 d424a012..850cf432 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiChest.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerChest; @@ -30,48 +29,55 @@ import appeng.tile.storage.TileChest; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; +public class GuiChest extends AEBaseGui { + private GuiTabButton priority; -public class GuiChest extends AEBaseGui -{ + public GuiChest(final InventoryPlayer inventoryPlayer, final TileChest te) { + super(new ContainerChest(inventoryPlayer, te)); + this.ySize = 166; + } - private GuiTabButton priority; + @Override + protected void actionPerformed(final GuiButton par1GuiButton) { + super.actionPerformed(par1GuiButton); - public GuiChest( final InventoryPlayer inventoryPlayer, final TileChest te ) - { - super( new ContainerChest( inventoryPlayer, te ) ); - this.ySize = 166; - } + if (par1GuiButton == this.priority) { + NetworkHandler.instance.sendToServer( + new PacketSwitchGuis(GuiBridge.GUI_PRIORITY) + ); + } + } - @Override - protected void actionPerformed( final GuiButton par1GuiButton ) - { - super.actionPerformed( par1GuiButton ); + @Override + public void initGui() { + super.initGui(); - if( par1GuiButton == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + 2 + 4 * 16, + GuiText.Priority.getLocal(), + itemRender + ) + ); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); + } - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 6e372d34..fd026b55 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCondenser.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCondenser.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; @@ -33,62 +32,77 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; +public class GuiCondenser extends AEBaseGui { + private final ContainerCondenser cvc; + private GuiProgressBar pb; + private GuiImgButton mode; -public class GuiCondenser extends AEBaseGui -{ + public GuiCondenser(final InventoryPlayer inventoryPlayer, final TileCondenser te) { + super(new ContainerCondenser(inventoryPlayer, te)); + this.cvc = (ContainerCondenser) this.inventorySlots; + this.ySize = 197; + } - private final ContainerCondenser cvc; - private GuiProgressBar pb; - private GuiImgButton mode; + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - public GuiCondenser( final InventoryPlayer inventoryPlayer, final TileCondenser te ) - { - super( new ContainerCondenser( inventoryPlayer, te ) ); - this.cvc = (ContainerCondenser) this.inventorySlots; - this.ySize = 197; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (this.mode == btn) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(Settings.CONDENSER_OUTPUT, backwards) + ); + } + } - final boolean backwards = Mouse.isButtonDown( 1 ); + @Override + public void initGui() { + super.initGui(); - if( this.mode == btn ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( Settings.CONDENSER_OUTPUT, backwards ) ); - } - } + this.pb = new GuiProgressBar( + this.cvc, + "guis/condenser.png", + 120 + this.guiLeft, + 25 + this.guiTop, + 178, + 25, + 6, + 18, + Direction.VERTICAL, + GuiText.StoredEnergy.getLocal() + ); - @Override - public void initGui() - { - super.initGui(); + this.mode = new GuiImgButton( + 128 + this.guiLeft, + 52 + this.guiTop, + Settings.CONDENSER_OUTPUT, + this.cvc.getOutput() + ); - this.pb = new GuiProgressBar( this.cvc, "guis/condenser.png", 120 + this.guiLeft, 25 + this.guiTop, 178, 25, 6, 18, Direction.VERTICAL, GuiText.StoredEnergy.getLocal() ); + this.buttonList.add(this.pb); + this.buttonList.add(this.mode); + } - this.mode = new GuiImgButton( 128 + this.guiLeft, 52 + this.guiTop, Settings.CONDENSER_OUTPUT, this.cvc.getOutput() ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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.buttonList.add( this.pb ); - this.buttonList.add( this.mode ); - } + this.mode.set(this.cvc.getOutput()); + this.mode.setFillVar(String.valueOf(this.cvc.getOutput().requiredPower)); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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 ); + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/condenser.png"); - this.mode.set( this.cvc.getOutput() ); - this.mode.setFillVar( String.valueOf( this.cvc.getOutput().requiredPower ) ); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/condenser.png" ); - - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + 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 49483822..5d058498 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftAmount.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IParts; @@ -43,267 +42,272 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; +public class GuiCraftAmount extends AEBaseGui { + private GuiNumberBox amountToCraft; + private GuiTabButton originalGuiBtn; -public class GuiCraftAmount extends AEBaseGui -{ - private GuiNumberBox amountToCraft; - private GuiTabButton originalGuiBtn; + private GuiButton next; - private GuiButton next; + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; + private GuiBridge originalGui; - private GuiBridge originalGui; + @Reflected + public GuiCraftAmount(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(new ContainerCraftAmount(inventoryPlayer, te)); + } - @Reflected - public GuiCraftAmount( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftAmount( inventoryPlayer, te ) ); - } + @Override + public void initGui() { + super.initGui(); - @Override - public void initGui() - { - super.initGui(); + final int a = AEConfig.instance.craftItemsByStackAmounts(0); + final int b = AEConfig.instance.craftItemsByStackAmounts(1); + final int c = AEConfig.instance.craftItemsByStackAmounts(2); + final int d = AEConfig.instance.craftItemsByStackAmounts(3); - final int a = AEConfig.instance.craftItemsByStackAmounts( 0 ); - final int b = AEConfig.instance.craftItemsByStackAmounts( 1 ); - final int c = AEConfig.instance.craftItemsByStackAmounts( 2 ); - final int d = AEConfig.instance.craftItemsByStackAmounts( 3 ); + this.buttonList.add( + this.plus1 + = new GuiButton(0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a) + ); + this.buttonList.add( + this.plus10 + = new GuiButton(0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b) + ); + this.buttonList.add( + this.plus100 + = new GuiButton(0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c) + ); + this.buttonList.add( + this.plus1000 + = new GuiButton(0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d) + ); - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 26, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 26, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 26, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 26, 38, 20, "+" + d ) ); + this.buttonList.add( + this.minus1 + = new GuiButton(0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a) + ); + this.buttonList.add( + this.minus10 + = new GuiButton(0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b) + ); + this.buttonList.add( + this.minus100 + = new GuiButton(0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c) + ); + this.buttonList.add( + this.minus1000 + = new GuiButton(0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d) + ); - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 75, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 75, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 75, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 75, 38, 20, "-" + d ) ); + this.buttonList.add( + this.next = new GuiButton( + 0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal() + ) + ); - this.buttonList.add( this.next = new GuiButton( 0, this.guiLeft + 128, this.guiTop + 51, 38, 20, GuiText.Next.getLocal() ) ); + ItemStack myIcon = null; + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); - ItemStack myIcon = null; - final Object target = ( (AEBaseContainer) this.inventorySlots ).getTarget(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IParts parts = definitions.parts(); + if (target instanceof WirelessTerminalGuiObject) { + for (final ItemStack wirelessTerminalStack : + definitions.items().wirelessTerminal().maybeStack(1).asSet()) { + myIcon = wirelessTerminalStack; + } - if( target instanceof WirelessTerminalGuiObject ) - { - for( final ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) - { - myIcon = wirelessTerminalStack; - } + this.originalGui = GuiBridge.GUI_WIRELESS_TERM; + } - this.originalGui = GuiBridge.GUI_WIRELESS_TERM; - } + if (target instanceof PartTerminal) { + for (final ItemStack stack : parts.terminal().maybeStack(1).asSet()) { + myIcon = stack; + } + this.originalGui = GuiBridge.GUI_ME; + } - if( target instanceof PartTerminal ) - { - for( final ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) - { - myIcon = stack; - } - this.originalGui = GuiBridge.GUI_ME; - } + if (target instanceof PartCraftingTerminal) { + for (final ItemStack stack : parts.craftingTerminal().maybeStack(1).asSet()) { + myIcon = stack; + } + this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } - if( target instanceof PartCraftingTerminal ) - { - for( final ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) - { - myIcon = stack; - } - this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } + if (target instanceof PartPatternTerminal) { + for (final ItemStack stack : parts.patternTerminal().maybeStack(1).asSet()) { + myIcon = stack; + } + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } - if( target instanceof PartPatternTerminal ) - { - for( final ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) - { - myIcon = stack; - } - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } + if (this.originalGui != null && myIcon != null) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + myIcon, + myIcon.getDisplayName(), + itemRender + ) + ); + } - if( this.originalGui != null && myIcon != null ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ) ); - } + this.amountToCraft = new GuiNumberBox( + this.fontRendererObj, + this.guiLeft + 62, + this.guiTop + 57, + 59, + this.fontRendererObj.FONT_HEIGHT, + Integer.class + ); + this.amountToCraft.setEnableBackgroundDrawing(false); + this.amountToCraft.setMaxStringLength(16); + this.amountToCraft.setTextColor(0xFFFFFF); + this.amountToCraft.setVisible(true); + this.amountToCraft.setFocused(true); + this.amountToCraft.setText("1"); + } - this.amountToCraft = new GuiNumberBox( this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT, Integer.class ); - this.amountToCraft.setEnableBackgroundDrawing( false ); - this.amountToCraft.setMaxStringLength( 16 ); - this.amountToCraft.setTextColor( 0xFFFFFF ); - this.amountToCraft.setVisible( true ); - this.amountToCraft.setFocused( true ); - this.amountToCraft.setText( "1" ); - } + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString(GuiText.SelectAmount.getLocal(), 8, 6, 4210752); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( GuiText.SelectAmount.getLocal(), 8, 6, 4210752 ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.next.displayString + = isShiftKeyDown() ? GuiText.Start.getLocal() : GuiText.Next.getLocal(); - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - 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); - this.bindTexture( "guis/craftAmt.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + try { + Long.parseLong(this.amountToCraft.getText()); + this.next.enabled = this.amountToCraft.getText().length() > 0; + } catch (final NumberFormatException e) { + this.next.enabled = false; + } - try - { - Long.parseLong( this.amountToCraft.getText() ); - this.next.enabled = this.amountToCraft.getText().length() > 0; - } - catch( final NumberFormatException e ) - { - this.next.enabled = false; - } + this.amountToCraft.drawTextBox(); + } - this.amountToCraft.drawTextBox(); - } + @Override + protected void keyTyped(final char character, final 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)) { + try { + String out = this.amountToCraft.getText(); - @Override - protected void keyTyped( final char character, final 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 ) ) - { - try - { - String out = this.amountToCraft.getText(); + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + if (fixed) { + this.amountToCraft.setText(out); + } - if( fixed ) - { - this.amountToCraft.setText( out ); - } + if (out.isEmpty()) { + out = "0"; + } - if( out.isEmpty() ) - { - out = "0"; - } + final long result = Long.parseLong(out); + if (result < 0) { + this.amountToCraft.setText("1"); + } + } catch (final NumberFormatException e) { + // :P + } + } else { + super.keyTyped(character, key); + } + } + } - final long result = Long.parseLong( out ); - if( result < 0 ) - { - this.amountToCraft.setText( "1" ); - } - } - catch( final NumberFormatException e ) - { - // :P - } - } - else - { - super.keyTyped( character, key ); - } - } - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + try { + if (btn == this.originalGuiBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.originalGui + )); + } - try - { + if (btn == this.next) { + NetworkHandler.instance.sendToServer(new PacketCraftRequest( + Integer.parseInt(this.amountToCraft.getText()), isShiftKeyDown() + )); + } + } catch (final NumberFormatException e) { + // nope.. + this.amountToCraft.setText("1"); + } - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); - } + final boolean isPlus = btn == this.plus1 || btn == this.plus10 + || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 + || btn == this.minus100 || btn == this.minus1000; - if( btn == this.next ) - { - NetworkHandler.instance.sendToServer( new PacketCraftRequest( Integer.parseInt( this.amountToCraft.getText() ), isShiftKeyDown() ) ); - } - } - catch( final NumberFormatException e ) - { - // nope.. - this.amountToCraft.setText( "1" ); - } + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + private void addQty(final int i) { + try { + String out = this.amountToCraft.getText(); - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - private void addQty( final int i ) - { - try - { - String out = this.amountToCraft.getText(); + if (fixed) { + this.amountToCraft.setText(out); + } - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + if (out.isEmpty()) { + out = "0"; + } - if( fixed ) - { - this.amountToCraft.setText( out ); - } + long result = Integer.parseInt(out); - if( out.isEmpty() ) - { - out = "0"; - } + if (result == 1 && i > 1) { + result = 0; + } - long result = Integer.parseInt( out ); + result += i; + if (result < 1) { + result = 1; + } - if( result == 1 && i > 1 ) - { - result = 0; - } + out = Long.toString(result); + Integer.parseInt(out); + this.amountToCraft.setText(out); + } catch (final NumberFormatException e) { + // :P + } + } - result += i; - if( result < 1 ) - { - result = 1; - } - - out = Long.toString( result ); - Integer.parseInt( out ); - this.amountToCraft.setText( out ); - } - catch( final NumberFormatException e ) - { - // :P - } - } - - protected String getBackground() - { - return "guis/craftAmt.png"; - } + protected String getBackground() { + return "guis/craftAmt.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java index 918abe69..a99b6148 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftConfirm.java @@ -18,6 +18,12 @@ package appeng.client.gui.implementations; +import java.io.IOException; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; import appeng.api.AEApi; import appeng.api.storage.ITerminalHost; @@ -44,534 +50,516 @@ import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.io.IOException; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; - - -public class GuiCraftConfirm extends AEBaseGui -{ - - private final ContainerCraftConfirm ccc; - - private final int rows = 5; - - private final IItemList storage = AEApi.instance().storage().createItemList(); - private final IItemList pending = AEApi.instance().storage().createItemList(); - private final IItemList missing = AEApi.instance().storage().createItemList(); - - private final List visual = new ArrayList(); - - private GuiBridge OriginalGui; - private GuiButton cancel; - private GuiButton start; - private GuiButton selectCPU; - private int tooltip = -1; - - public GuiCraftConfirm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftConfirm( inventoryPlayer, te ) ); - this.xSize = 238; - this.ySize = 206; - - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - - this.ccc = (ContainerCraftConfirm) this.inventorySlots; - - if( te instanceof WirelessTerminalGuiObject ) - { - this.OriginalGui = GuiBridge.GUI_WIRELESS_TERM; - } - - if( te instanceof PartTerminal ) - { - this.OriginalGui = GuiBridge.GUI_ME; - } - - if( te instanceof PartCraftingTerminal ) - { - this.OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } - - if( te instanceof PartPatternTerminal ) - { - this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - } - - boolean isAutoStart() - { - return ( (ContainerCraftConfirm) this.inventorySlots ).isAutoStart(); - } - - @Override - public void initGui() - { - super.initGui(); - - this.start = new GuiButton( 0, this.guiLeft + 162, this.guiTop + this.ySize - 25, 50, 20, GuiText.Start.getLocal() ); - 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.enabled = false; - this.buttonList.add( this.selectCPU ); - - 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 ); - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.updateCPUButtonText(); - - this.start.enabled = !( this.ccc.hasNoCPU() || this.isSimulation() ); - this.selectCPU.enabled = !this.isSimulation(); - - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; - - this.tooltip = -1; - - final int offY = 23; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 9 + x * 67; - final int minY = gy + 22 + y * offY; - - if( minX < mouseX && minX + 67 > mouseX ) - { - if( minY < mouseY && minY + offY - 2 > mouseY ) - { - this.tooltip = z; - break; - } - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - - super.drawScreen( mouseX, mouseY, btn ); - } - - private void updateCPUButtonText() - { - String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); - if( this.ccc.getSelectedCpu() >= 0 )// && status.selectedCpu < status.cpus.size() ) - { - if( this.ccc.getName().length() > 0 ) - { - final String name = this.ccc.getName().substring( 0, Math.min( 20, this.ccc.getName().length() ) ); - btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; - } - else - { - btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu(); - } - } - - if( this.ccc.hasNoCPU() ) - { - btnTextText = GuiText.NoCraftingCPUs.getLocal(); - } - - this.selectCPU.displayString = btnTextText; - } - - private boolean isSimulation() - { - return ( (ContainerCraftConfirm) this.inventorySlots ).isSimulation(); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final long BytesUsed = this.ccc.getUsedBytes(); - final String byteUsed = NumberFormat.getInstance().format( BytesUsed ); - final 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() ) - { - dsp = GuiText.Simulation.getLocal(); - } - else - { - dsp = this.ccc.getCpuAvailableBytes() > 0 ? ( GuiText.Bytes.getLocal() + ": " + this.ccc.getCpuAvailableBytes() + " : " + GuiText.CoProcessors.getLocal() + ": " + this.ccc.getCpuCoProcessors() ) : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A"; - } - - final int offset = ( 219 - this.fontRendererObj.getStringWidth( dsp ) ) / 2; - this.fontRendererObj.drawString( dsp, offset, 165, 4210752 ); - - final int sectionLength = 67; - - int x = 0; - int y = 0; - final int xo = 9; - final int yo = 22; - final int viewStart = this.getScrollBar().getCurrentScroll() * 3; - final int viewEnd = viewStart + 3 * this.rows; - - String dspToolTip = ""; - final List lineList = new LinkedList(); - int toolPosX = 0; - int toolPosY = 0; - - final int offY = 23; - - for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) - { - final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if( refStack != null ) - { - GL11.glPushMatrix(); - GL11.glScaled( 0.5, 0.5, 0.5 ); - - final IAEItemStack stored = this.storage.findPrecise( refStack ); - final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); - final IAEItemStack missingStack = this.missing.findPrecise( refStack ); - - int lines = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - lines++; - } - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - } - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - } - - final int negY = ( ( lines - 1 ) * 5 ) / 2; - int downY = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - String str = Long.toString( stored.getStackSize() ); - if( stored.getStackSize() >= 10000 ) - { - str = Long.toString( stored.getStackSize() / 1000 ) + 'k'; - } - if( stored.getStackSize() >= 10000000 ) - { - str = Long.toString( stored.getStackSize() / 1000000 ) + 'm'; - } - - str = GuiText.FromStorage.getLocal() + ": " + str; - final 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 ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.FromStorage.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); - } - - downY += 5; - } - - boolean red = false; - if( missingStack != null && missingStack.getStackSize() > 0 ) - { - String str = Long.toString( missingStack.getStackSize() ); - if( missingStack.getStackSize() >= 10000 ) - { - str = Long.toString( missingStack.getStackSize() / 1000 ) + 'k'; - } - if( missingStack.getStackSize() >= 10000000 ) - { - str = Long.toString( missingStack.getStackSize() / 1000000 ) + 'm'; - } - - str = GuiText.Missing.getLocal() + ": " + str; - final 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 ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Missing.getLocal() + ": " + Long.toString( missingStack.getStackSize() ) ); - } - - red = true; - downY += 5; - } - - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - String str = Long.toString( pendingStack.getStackSize() ); - if( pendingStack.getStackSize() >= 10000 ) - { - str = Long.toString( pendingStack.getStackSize() / 1000 ) + 'k'; - } - if( pendingStack.getStackSize() >= 10000000 ) - { - str = Long.toString( pendingStack.getStackSize() / 1000000 ) + 'm'; - } - - str = GuiText.ToCraft.getLocal() + ": " + str; - final 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 ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.ToCraft.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); - } - } - - GL11.glPopMatrix(); - final int posX = x * ( 1 + sectionLength ) + xo + sectionLength - 19; - final int posY = y * offY + yo; - - final ItemStack is = refStack.copy().getItemStack(); - - if( this.tooltip == z - viewStart ) - { - dspToolTip = Platform.getItemDisplayName( is ); - - if( lineList.size() > 0 ) - { - dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - } - - toolPosX = x * ( 1 + sectionLength ) + xo + sectionLength - 8; - toolPosY = y * offY + yo; - } - - this.drawItem( posX, posY, is ); - - if( red ) - { - final int startX = x * ( 1 + sectionLength ) + xo; - final int startY = posY - 4; - drawRect( startX, startY, startX + sectionLength, startY + offY, 0x1AFF0000 ); - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - } - - if( this.tooltip >= 0 && dspToolTip.length() > 0 ) - { - this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.setScrollBar(); - this.bindTexture( "guis/craftingreport.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - private void setScrollBar() - { - final int size = this.visual.size(); - - this.getScrollBar().setTop( 19 ).setLeft( 218 ).setHeight( 114 ); - this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - this.rows, 1 ); - } - - public void postUpdate( final List list, final byte ref ) - { - switch( ref ) - { - case 0: - for( final IAEItemStack l : list ) - { - this.handleInput( this.storage, l ); - } - break; - - case 1: - for( final IAEItemStack l : list ) - { - this.handleInput( this.pending, l ); - } - break; - - case 2: - for( final IAEItemStack l : list ) - { - this.handleInput( this.missing, l ); - } - break; - } - - for( final IAEItemStack l : list ) - { - final long amt = this.getTotal( l ); - - if( amt <= 0 ) - { - this.deleteVisualStack( l ); - } - else - { - final IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput( final IItemList s, final 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( final IAEItemStack is ) - { - final IAEItemStack a = this.storage.findPrecise( is ); - final IAEItemStack c = this.pending.findPrecise( is ); - final 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( final IAEItemStack l ) - { - final Iterator i = this.visual.iterator(); - while( i.hasNext() ) - { - final IAEItemStack o = i.next(); - if( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - - private IAEItemStack findVisualStack( final IAEItemStack l ) - { - for( final IAEItemStack o : this.visual ) - { - if( o.equals( l ) ) - { - return o; - } - } - - final IAEItemStack stack = l.copy(); - this.visual.add( stack ); - return stack; - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( key == 28 ) - { - this.actionPerformed( this.start ); - } - super.keyTyped( character, key ); - } - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final boolean backwards = Mouse.isButtonDown( 1 ); - - if( btn == this.selectCPU ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); - } - catch( final IOException e ) - { - AELog.debug( 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( final Throwable e ) - { - AELog.debug( e ); - } - } - } +public class GuiCraftConfirm extends AEBaseGui { + private final ContainerCraftConfirm ccc; + + private final int rows = 5; + + private final IItemList storage + = AEApi.instance().storage().createItemList(); + private final IItemList pending + = AEApi.instance().storage().createItemList(); + private final IItemList missing + = AEApi.instance().storage().createItemList(); + + private final List visual = new ArrayList(); + + private GuiBridge OriginalGui; + private GuiButton cancel; + private GuiButton start; + private GuiButton selectCPU; + private int tooltip = -1; + + public GuiCraftConfirm( + final InventoryPlayer inventoryPlayer, final ITerminalHost te + ) { + super(new ContainerCraftConfirm(inventoryPlayer, te)); + this.xSize = 238; + this.ySize = 206; + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + + this.ccc = (ContainerCraftConfirm) this.inventorySlots; + + if (te instanceof WirelessTerminalGuiObject) { + this.OriginalGui = GuiBridge.GUI_WIRELESS_TERM; + } + + if (te instanceof PartTerminal) { + this.OriginalGui = GuiBridge.GUI_ME; + } + + if (te instanceof PartCraftingTerminal) { + this.OriginalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } + + if (te instanceof PartPatternTerminal) { + this.OriginalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } + } + + boolean isAutoStart() { + return ((ContainerCraftConfirm) this.inventorySlots).isAutoStart(); + } + + @Override + public void initGui() { + super.initGui(); + + this.start = new GuiButton( + 0, + this.guiLeft + 162, + this.guiTop + this.ySize - 25, + 50, + 20, + GuiText.Start.getLocal() + ); + 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.enabled = false; + this.buttonList.add(this.selectCPU); + + 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); + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.updateCPUButtonText(); + + this.start.enabled = !(this.ccc.hasNoCPU() || this.isSimulation()); + this.selectCPU.enabled = !this.isSimulation(); + + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if (minX < mouseX && minX + 67 > mouseX) { + if (minY < mouseY && minY + offY - 2 > mouseY) { + this.tooltip = z; + break; + } + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + + super.drawScreen(mouseX, mouseY, btn); + } + + private void updateCPUButtonText() { + String btnTextText + = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal(); + if (this.ccc.getSelectedCpu() + >= 0) // && status.selectedCpu < status.cpus.size() ) + { + if (this.ccc.getName().length() > 0) { + final String name = this.ccc.getName().substring( + 0, Math.min(20, this.ccc.getName().length()) + ); + btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name; + } else { + btnTextText + = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu(); + } + } + + if (this.ccc.hasNoCPU()) { + btnTextText = GuiText.NoCraftingCPUs.getLocal(); + } + + this.selectCPU.displayString = btnTextText; + } + + private boolean isSimulation() { + return ((ContainerCraftConfirm) this.inventorySlots).isSimulation(); + } + + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final long BytesUsed = this.ccc.getUsedBytes(); + final String byteUsed = NumberFormat.getInstance().format(BytesUsed); + final 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()) { + dsp = GuiText.Simulation.getLocal(); + } else { + dsp = this.ccc.getCpuAvailableBytes() > 0 + ? (GuiText.Bytes.getLocal() + ": " + this.ccc.getCpuAvailableBytes() + + " : " + GuiText.CoProcessors.getLocal() + ": " + + this.ccc.getCpuCoProcessors()) + : GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + + ": N/A"; + } + + final int offset = (219 - this.fontRendererObj.getStringWidth(dsp)) / 2; + this.fontRendererObj.drawString(dsp, offset, 165, 4210752); + + final int sectionLength = 67; + + int x = 0; + int y = 0; + final int xo = 9; + final int yo = 22; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * this.rows; + + String dspToolTip = ""; + final List lineList = new LinkedList(); + int toolPosX = 0; + int toolPosY = 0; + + final int offY = 23; + + for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) { + final IAEItemStack refStack + = this.visual.get(z); // repo.getReferenceItem( z ); + if (refStack != null) { + GL11.glPushMatrix(); + GL11.glScaled(0.5, 0.5, 0.5); + + final IAEItemStack stored = this.storage.findPrecise(refStack); + final IAEItemStack pendingStack = this.pending.findPrecise(refStack); + final IAEItemStack missingStack = this.missing.findPrecise(refStack); + + int lines = 0; + + if (stored != null && stored.getStackSize() > 0) { + lines++; + } + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + } + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + } + + final int negY = ((lines - 1) * 5) / 2; + int downY = 0; + + if (stored != null && stored.getStackSize() > 0) { + String str = Long.toString(stored.getStackSize()); + if (stored.getStackSize() >= 10000) { + str = Long.toString(stored.getStackSize() / 1000) + 'k'; + } + if (stored.getStackSize() >= 10000000) { + str = Long.toString(stored.getStackSize() / 1000000) + 'm'; + } + + str = GuiText.FromStorage.getLocal() + ": " + str; + final 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 + ); + + if (this.tooltip == z - viewStart) { + lineList.add( + GuiText.FromStorage.getLocal() + ": " + + Long.toString(stored.getStackSize()) + ); + } + + downY += 5; + } + + boolean red = false; + if (missingStack != null && missingStack.getStackSize() > 0) { + String str = Long.toString(missingStack.getStackSize()); + if (missingStack.getStackSize() >= 10000) { + str = Long.toString(missingStack.getStackSize() / 1000) + 'k'; + } + if (missingStack.getStackSize() >= 10000000) { + str = Long.toString(missingStack.getStackSize() / 1000000) + 'm'; + } + + str = GuiText.Missing.getLocal() + ": " + str; + final 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 + ); + + if (this.tooltip == z - viewStart) { + lineList.add( + GuiText.Missing.getLocal() + ": " + + Long.toString(missingStack.getStackSize()) + ); + } + + red = true; + downY += 5; + } + + if (pendingStack != null && pendingStack.getStackSize() > 0) { + String str = Long.toString(pendingStack.getStackSize()); + if (pendingStack.getStackSize() >= 10000) { + str = Long.toString(pendingStack.getStackSize() / 1000) + 'k'; + } + if (pendingStack.getStackSize() >= 10000000) { + str = Long.toString(pendingStack.getStackSize() / 1000000) + 'm'; + } + + str = GuiText.ToCraft.getLocal() + ": " + str; + final 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 + ); + + if (this.tooltip == z - viewStart) { + lineList.add( + GuiText.ToCraft.getLocal() + ": " + + Long.toString(pendingStack.getStackSize()) + ); + } + } + + GL11.glPopMatrix(); + final int posX = x * (1 + sectionLength) + xo + sectionLength - 19; + final int posY = y * offY + yo; + + final ItemStack is = refStack.copy().getItemStack(); + + if (this.tooltip == z - viewStart) { + dspToolTip = Platform.getItemDisplayName(is); + + if (lineList.size() > 0) { + dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList); + } + + toolPosX = x * (1 + sectionLength) + xo + sectionLength - 8; + toolPosY = y * offY + yo; + } + + this.drawItem(posX, posY, is); + + if (red) { + final int startX = x * (1 + sectionLength) + xo; + final int startY = posY - 4; + drawRect( + startX, startY, startX + sectionLength, startY + offY, 0x1AFF0000 + ); + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + } + + if (this.tooltip >= 0 && dspToolTip.length() > 0) { + this.drawTooltip(toolPosX, toolPosY + 10, 0, dspToolTip); + } + } + + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.setScrollBar(); + this.bindTexture("guis/craftingreport.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + private void setScrollBar() { + final int size = this.visual.size(); + + this.getScrollBar().setTop(19).setLeft(218).setHeight(114); + this.getScrollBar().setRange(0, (size + 2) / 3 - this.rows, 1); + } + + public void postUpdate(final List list, final byte ref) { + switch (ref) { + case 0: + for (final IAEItemStack l : list) { + this.handleInput(this.storage, l); + } + break; + + case 1: + for (final IAEItemStack l : list) { + this.handleInput(this.pending, l); + } + break; + + case 2: + for (final IAEItemStack l : list) { + this.handleInput(this.missing, l); + } + break; + } + + for (final IAEItemStack l : list) { + final long amt = this.getTotal(l); + + if (amt <= 0) { + this.deleteVisualStack(l); + } else { + final IAEItemStack is = this.findVisualStack(l); + is.setStackSize(amt); + } + } + + this.setScrollBar(); + } + + private void handleInput(final IItemList s, final 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(final IAEItemStack is) { + final IAEItemStack a = this.storage.findPrecise(is); + final IAEItemStack c = this.pending.findPrecise(is); + final 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(final IAEItemStack l) { + final Iterator i = this.visual.iterator(); + while (i.hasNext()) { + final IAEItemStack o = i.next(); + if (o.equals(l)) { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack(final IAEItemStack l) { + for (final IAEItemStack o : this.visual) { + if (o.equals(l)) { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add(stack); + return stack; + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if (key == 28) { + this.actionPerformed(this.start); + } + super.keyTyped(character, key); + } + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + final boolean backwards = Mouse.isButtonDown(1); + + if (btn == this.selectCPU) { + try { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("Terminal.Cpu", backwards ? "Prev" : "Next") + ); + } catch (final IOException e) { + AELog.debug(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 (final Throwable e) { + AELog.debug(e); + } + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java index c8ca39b4..b209e56c 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingCPU.java @@ -18,6 +18,12 @@ package appeng.client.gui.implementations; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; import appeng.api.AEApi; import appeng.api.config.SortDir; @@ -44,446 +50,442 @@ import net.minecraft.item.ItemStack; import org.apache.commons.lang3.time.DurationFormatUtils; import org.lwjgl.opengl.GL11; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.TimeUnit; - - -public class GuiCraftingCPU extends AEBaseGui implements ISortSource -{ - private static final int GUI_HEIGHT = 184; - private static final int GUI_WIDTH = 238; - - private static final int DISPLAYED_ROWS = 6; - - private static final int TEXT_COLOR = 0x404040; - private static final int BACKGROUND_ALPHA = 0x5A000000; - - private static final int SECTION_LENGTH = 67; - - private static final int SCROLLBAR_TOP = 19; - private static final int SCROLLBAR_LEFT = 218; - private static final int SCROLLBAR_HEIGHT = 137; - - private static final int CANCEL_LEFT_OFFSET = 163; - private static final int CANCEL_TOP_OFFSET = 25; - private static final int CANCEL_HEIGHT = 20; - private static final int CANCEL_WIDTH = 50; - - private static final int TITLE_TOP_OFFSET = 7; - private static final int TITLE_LEFT_OFFSET = 8; - - private static final int ITEMSTACK_LEFT_OFFSET = 9; - private static final int ITEMSTACK_TOP_OFFSET = 22; - - private final ContainerCraftingCPU craftingCpu; - - private IItemList storage = AEApi.instance().storage().createItemList(); - private IItemList active = AEApi.instance().storage().createItemList(); - private IItemList pending = AEApi.instance().storage().createItemList(); - - private List visual = new ArrayList(); - private GuiButton cancel; - private int tooltip = -1; - - public GuiCraftingCPU( final InventoryPlayer inventoryPlayer, final Object te ) - { - this( new ContainerCraftingCPU( inventoryPlayer, te ) ); - } - - protected GuiCraftingCPU( final ContainerCraftingCPU container ) - { - super( container ); - this.craftingCpu = container; - this.ySize = GUI_HEIGHT; - this.xSize = GUI_WIDTH; - - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - } - - public void clearItems() - { - this.storage = AEApi.instance().storage().createItemList(); - this.active = AEApi.instance().storage().createItemList(); - this.pending = AEApi.instance().storage().createItemList(); - this.visual = new ArrayList(); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - if( this.cancel == btn ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileCrafting.Cancel", "Cancel" ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - @Override - public void initGui() - { - super.initGui(); - this.setScrollBar(); - this.cancel = new GuiButton( 0, this.guiLeft + CANCEL_LEFT_OFFSET, this.guiTop + this.ySize - CANCEL_TOP_OFFSET, CANCEL_WIDTH, CANCEL_HEIGHT, GuiText.Cancel.getLocal() ); - this.buttonList.add( this.cancel ); - } - - private void setScrollBar() - { - final int size = this.visual.size(); - - this.getScrollBar().setTop( SCROLLBAR_TOP ).setLeft( SCROLLBAR_LEFT ).setHeight( SCROLLBAR_HEIGHT ); - this.getScrollBar().setRange( 0, ( size + 2 ) / 3 - DISPLAYED_ROWS, 1 ); - } - - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.cancel.enabled = !this.visual.isEmpty(); - - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; - - this.tooltip = -1; - - final int offY = 23; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 9 + x * 67; - final int minY = gy + 22 + y * offY; - - if( minX < mouseX && minX + 67 > mouseX ) - { - if( minY < mouseY && minY + offY - 2 > mouseY ) - { - this.tooltip = z; - break; - } - } - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - - super.drawScreen( mouseX, mouseY, btn ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - String title = this.getGuiDisplayName( GuiText.CraftingStatus.getLocal() ); - - if( this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty() ) - { - final long etaInMilliseconds = TimeUnit.MILLISECONDS.convert( this.craftingCpu.getEstimatedTime(), TimeUnit.NANOSECONDS ); - final String etaTimeText = DurationFormatUtils.formatDuration( etaInMilliseconds, GuiText.ETAFormat.getLocal() ); - title += " - " + etaTimeText; - } - - this.fontRendererObj.drawString( title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, TEXT_COLOR ); - - int x = 0; - int y = 0; - final int viewStart = this.getScrollBar().getCurrentScroll() * 3; - final int viewEnd = viewStart + 3 * 6; - - String dspToolTip = ""; - final List lineList = new LinkedList(); - int toolPosX = 0; - int toolPosY = 0; - - final int offY = 23; - - final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; - for( int z = viewStart; z < Math.min( viewEnd, this.visual.size() ); z++ ) - { - final IAEItemStack refStack = this.visual.get( z );// repo.getReferenceItem( z ); - if( refStack != null ) - { - GL11.glPushMatrix(); - GL11.glScaled( 0.5, 0.5, 0.5 ); - - final IAEItemStack stored = this.storage.findPrecise( refStack ); - final IAEItemStack activeStack = this.active.findPrecise( refStack ); - final IAEItemStack pendingStack = this.pending.findPrecise( refStack ); - - int lines = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - lines++; - } - boolean active = false; - if( activeStack != null && activeStack.getStackSize() > 0 ) - { - lines++; - active = true; - } - boolean scheduled = false; - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - lines++; - scheduled = true; - } - - if( AEConfig.instance.useColoredCraftingStatus && ( active || scheduled ) ) - { - final int bgColor = ( active ? AEColor.Green.blackVariant : AEColor.Yellow.blackVariant ) | BACKGROUND_ALPHA; - final int startX = ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET ) * 2; - final int startY = ( ( y * offY + ITEMSTACK_TOP_OFFSET ) - 3 ) * 2; - drawRect( startX, startY, startX + ( SECTION_LENGTH * 2 ), startY + ( offY * 2 ) - 2, bgColor ); - } - - final int negY = ( ( lines - 1 ) * 5 ) / 2; - int downY = 0; - - if( stored != null && stored.getStackSize() > 0 ) - { - final String str = GuiText.Stored.getLocal() + ": " + converter.toWideReadableForm( stored.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Stored.getLocal() + ": " + Long.toString( stored.getStackSize() ) ); - } - - downY += 5; - } - - if( activeStack != null && activeStack.getStackSize() > 0 ) - { - final String str = GuiText.Crafting.getLocal() + ": " + converter.toWideReadableForm( activeStack.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Crafting.getLocal() + ": " + Long.toString( activeStack.getStackSize() ) ); - } - - downY += 5; - } - - if( pendingStack != null && pendingStack.getStackSize() > 0 ) - { - final String str = GuiText.Scheduled.getLocal() + ": " + converter.toWideReadableForm( pendingStack.getStackSize() ); - final int w = 4 + this.fontRendererObj.getStringWidth( str ); - - this.fontRendererObj.drawString( str, (int) ( ( x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19 - ( w * 0.5 ) ) * 2 ), ( y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY ) * 2, TEXT_COLOR ); - - if( this.tooltip == z - viewStart ) - { - lineList.add( GuiText.Scheduled.getLocal() + ": " + Long.toString( pendingStack.getStackSize() ) ); - } - } - - GL11.glPopMatrix(); - final int posX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 19; - final int posY = y * offY + ITEMSTACK_TOP_OFFSET; - - final ItemStack is = refStack.copy().getItemStack(); - - if( this.tooltip == z - viewStart ) - { - dspToolTip = Platform.getItemDisplayName( is ); - - if( lineList.size() > 0 ) - { - dspToolTip = dspToolTip + '\n' + Joiner.on( "\n" ).join( lineList ); - } - - toolPosX = x * ( 1 + SECTION_LENGTH ) + ITEMSTACK_LEFT_OFFSET + SECTION_LENGTH - 8; - toolPosY = y * offY + ITEMSTACK_TOP_OFFSET; - } - - this.drawItem( posX, posY, is ); - - x++; - - if( x > 2 ) - { - y++; - x = 0; - } - } - } - - if( this.tooltip >= 0 && dspToolTip.length() > 0 ) - { - this.drawTooltip( toolPosX, toolPosY + 10, 0, dspToolTip ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/craftingcpu.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - public void postUpdate( final List list, final byte ref ) - { - switch( ref ) - { - case 0: - for( final IAEItemStack l : list ) - { - this.handleInput( this.storage, l ); - } - break; - - case 1: - for( final IAEItemStack l : list ) - { - this.handleInput( this.active, l ); - } - break; - - case 2: - for( final IAEItemStack l : list ) - { - this.handleInput( this.pending, l ); - } - break; - } - - for( final IAEItemStack l : list ) - { - final long amt = this.getTotal( l ); - - if( amt <= 0 ) - { - this.deleteVisualStack( l ); - } - else - { - final IAEItemStack is = this.findVisualStack( l ); - is.setStackSize( amt ); - } - } - - this.setScrollBar(); - } - - private void handleInput( final IItemList s, final 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( final IAEItemStack is ) - { - final IAEItemStack a = this.storage.findPrecise( is ); - final IAEItemStack b = this.active.findPrecise( is ); - final 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( final IAEItemStack l ) - { - final Iterator i = this.visual.iterator(); - - while( i.hasNext() ) - { - final IAEItemStack o = i.next(); - if( o.equals( l ) ) - { - i.remove(); - return; - } - } - } - - private IAEItemStack findVisualStack( final IAEItemStack l ) - { - for( final IAEItemStack o : this.visual ) - { - if( o.equals( l ) ) - { - return o; - } - } - - final IAEItemStack stack = l.copy(); - this.visual.add( stack ); - - return stack; - } - - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } - - @Override - public Enum getSortDir() - { - return SortDir.ASCENDING; - } - - @Override - public Enum getSortDisplay() - { - return ViewItems.ALL; - } +public class GuiCraftingCPU extends AEBaseGui implements ISortSource { + private static final int GUI_HEIGHT = 184; + private static final int GUI_WIDTH = 238; + + private static final int DISPLAYED_ROWS = 6; + + private static final int TEXT_COLOR = 0x404040; + private static final int BACKGROUND_ALPHA = 0x5A000000; + + private static final int SECTION_LENGTH = 67; + + private static final int SCROLLBAR_TOP = 19; + private static final int SCROLLBAR_LEFT = 218; + private static final int SCROLLBAR_HEIGHT = 137; + + private static final int CANCEL_LEFT_OFFSET = 163; + private static final int CANCEL_TOP_OFFSET = 25; + private static final int CANCEL_HEIGHT = 20; + private static final int CANCEL_WIDTH = 50; + + private static final int TITLE_TOP_OFFSET = 7; + private static final int TITLE_LEFT_OFFSET = 8; + + private static final int ITEMSTACK_LEFT_OFFSET = 9; + private static final int ITEMSTACK_TOP_OFFSET = 22; + + private final ContainerCraftingCPU craftingCpu; + + private IItemList storage = AEApi.instance().storage().createItemList(); + private IItemList active = AEApi.instance().storage().createItemList(); + private IItemList pending = AEApi.instance().storage().createItemList(); + + private List visual = new ArrayList(); + private GuiButton cancel; + private int tooltip = -1; + + public GuiCraftingCPU(final InventoryPlayer inventoryPlayer, final Object te) { + this(new ContainerCraftingCPU(inventoryPlayer, te)); + } + + protected GuiCraftingCPU(final ContainerCraftingCPU container) { + super(container); + this.craftingCpu = container; + this.ySize = GUI_HEIGHT; + this.xSize = GUI_WIDTH; + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + } + + public void clearItems() { + this.storage = AEApi.instance().storage().createItemList(); + this.active = AEApi.instance().storage().createItemList(); + this.pending = AEApi.instance().storage().createItemList(); + this.visual = new ArrayList(); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + if (this.cancel == btn) { + try { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("TileCrafting.Cancel", "Cancel") + ); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + @Override + public void initGui() { + super.initGui(); + this.setScrollBar(); + this.cancel = new GuiButton( + 0, + this.guiLeft + CANCEL_LEFT_OFFSET, + this.guiTop + this.ySize - CANCEL_TOP_OFFSET, + CANCEL_WIDTH, + CANCEL_HEIGHT, + GuiText.Cancel.getLocal() + ); + this.buttonList.add(this.cancel); + } + + private void setScrollBar() { + final int size = this.visual.size(); + + this.getScrollBar() + .setTop(SCROLLBAR_TOP) + .setLeft(SCROLLBAR_LEFT) + .setHeight(SCROLLBAR_HEIGHT); + this.getScrollBar().setRange(0, (size + 2) / 3 - DISPLAYED_ROWS, 1); + } + + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.cancel.enabled = !this.visual.isEmpty(); + + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; + + this.tooltip = -1; + + final int offY = 23; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 9 + x * 67; + final int minY = gy + 22 + y * offY; + + if (minX < mouseX && minX + 67 > mouseX) { + if (minY < mouseY && minY + offY - 2 > mouseY) { + this.tooltip = z; + break; + } + } + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + + super.drawScreen(mouseX, mouseY, btn); + } + + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + String title = this.getGuiDisplayName(GuiText.CraftingStatus.getLocal()); + + if (this.craftingCpu.getEstimatedTime() > 0 && !this.visual.isEmpty()) { + final long etaInMilliseconds = TimeUnit.MILLISECONDS.convert( + this.craftingCpu.getEstimatedTime(), TimeUnit.NANOSECONDS + ); + final String etaTimeText = DurationFormatUtils.formatDuration( + etaInMilliseconds, GuiText.ETAFormat.getLocal() + ); + title += " - " + etaTimeText; + } + + this.fontRendererObj.drawString( + title, TITLE_LEFT_OFFSET, TITLE_TOP_OFFSET, TEXT_COLOR + ); + + int x = 0; + int y = 0; + final int viewStart = this.getScrollBar().getCurrentScroll() * 3; + final int viewEnd = viewStart + 3 * 6; + + String dspToolTip = ""; + final List lineList = new LinkedList(); + int toolPosX = 0; + int toolPosY = 0; + + final int offY = 23; + + final ReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) { + final IAEItemStack refStack + = this.visual.get(z); // repo.getReferenceItem( z ); + if (refStack != null) { + GL11.glPushMatrix(); + GL11.glScaled(0.5, 0.5, 0.5); + + final IAEItemStack stored = this.storage.findPrecise(refStack); + final IAEItemStack activeStack = this.active.findPrecise(refStack); + final IAEItemStack pendingStack = this.pending.findPrecise(refStack); + + int lines = 0; + + if (stored != null && stored.getStackSize() > 0) { + lines++; + } + boolean active = false; + if (activeStack != null && activeStack.getStackSize() > 0) { + lines++; + active = true; + } + boolean scheduled = false; + if (pendingStack != null && pendingStack.getStackSize() > 0) { + lines++; + scheduled = true; + } + + if (AEConfig.instance.useColoredCraftingStatus && (active || scheduled)) { + final int bgColor = (active ? AEColor.Green.blackVariant + : AEColor.Yellow.blackVariant) + | BACKGROUND_ALPHA; + final int startX + = (x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET) * 2; + final int startY = ((y * offY + ITEMSTACK_TOP_OFFSET) - 3) * 2; + drawRect( + startX, + startY, + startX + (SECTION_LENGTH * 2), + startY + (offY * 2) - 2, + bgColor + ); + } + + final int negY = ((lines - 1) * 5) / 2; + int downY = 0; + + if (stored != null && stored.getStackSize() > 0) { + final String str = GuiText.Stored.getLocal() + ": " + + converter.toWideReadableForm(stored.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + this.fontRendererObj.drawString( + str, + (int + ) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + + SECTION_LENGTH - 19 - (w * 0.5)) + * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, + TEXT_COLOR + ); + + if (this.tooltip == z - viewStart) { + lineList.add( + GuiText.Stored.getLocal() + ": " + + Long.toString(stored.getStackSize()) + ); + } + + downY += 5; + } + + if (activeStack != null && activeStack.getStackSize() > 0) { + final String str = GuiText.Crafting.getLocal() + ": " + + converter.toWideReadableForm(activeStack.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + + this.fontRendererObj.drawString( + str, + (int + ) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + + SECTION_LENGTH - 19 - (w * 0.5)) + * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, + TEXT_COLOR + ); + + if (this.tooltip == z - viewStart) { + lineList.add( + GuiText.Crafting.getLocal() + ": " + + Long.toString(activeStack.getStackSize()) + ); + } + + downY += 5; + } + + if (pendingStack != null && pendingStack.getStackSize() > 0) { + final String str = GuiText.Scheduled.getLocal() + ": " + + converter.toWideReadableForm(pendingStack.getStackSize()); + final int w = 4 + this.fontRendererObj.getStringWidth(str); + + this.fontRendererObj.drawString( + str, + (int + ) ((x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + + SECTION_LENGTH - 19 - (w * 0.5)) + * 2), + (y * offY + ITEMSTACK_TOP_OFFSET + 6 - negY + downY) * 2, + TEXT_COLOR + ); + + if (this.tooltip == z - viewStart) { + lineList.add( + GuiText.Scheduled.getLocal() + ": " + + Long.toString(pendingStack.getStackSize()) + ); + } + } + + GL11.glPopMatrix(); + final int posX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + + SECTION_LENGTH - 19; + final int posY = y * offY + ITEMSTACK_TOP_OFFSET; + + final ItemStack is = refStack.copy().getItemStack(); + + if (this.tooltip == z - viewStart) { + dspToolTip = Platform.getItemDisplayName(is); + + if (lineList.size() > 0) { + dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList); + } + + toolPosX = x * (1 + SECTION_LENGTH) + ITEMSTACK_LEFT_OFFSET + + SECTION_LENGTH - 8; + toolPosY = y * offY + ITEMSTACK_TOP_OFFSET; + } + + this.drawItem(posX, posY, is); + + x++; + + if (x > 2) { + y++; + x = 0; + } + } + } + + if (this.tooltip >= 0 && dspToolTip.length() > 0) { + this.drawTooltip(toolPosX, toolPosY + 10, 0, dspToolTip); + } + } + + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/craftingcpu.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } + + public void postUpdate(final List list, final byte ref) { + switch (ref) { + case 0: + for (final IAEItemStack l : list) { + this.handleInput(this.storage, l); + } + break; + + case 1: + for (final IAEItemStack l : list) { + this.handleInput(this.active, l); + } + break; + + case 2: + for (final IAEItemStack l : list) { + this.handleInput(this.pending, l); + } + break; + } + + for (final IAEItemStack l : list) { + final long amt = this.getTotal(l); + + if (amt <= 0) { + this.deleteVisualStack(l); + } else { + final IAEItemStack is = this.findVisualStack(l); + is.setStackSize(amt); + } + } + + this.setScrollBar(); + } + + private void handleInput(final IItemList s, final 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(final IAEItemStack is) { + final IAEItemStack a = this.storage.findPrecise(is); + final IAEItemStack b = this.active.findPrecise(is); + final 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(final IAEItemStack l) { + final Iterator i = this.visual.iterator(); + + while (i.hasNext()) { + final IAEItemStack o = i.next(); + if (o.equals(l)) { + i.remove(); + return; + } + } + } + + private IAEItemStack findVisualStack(final IAEItemStack l) { + for (final IAEItemStack o : this.visual) { + if (o.equals(l)) { + return o; + } + } + + final IAEItemStack stack = l.copy(); + this.visual.add(stack); + + return stack; + } + + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } + + @Override + public Enum getSortDir() { + return SortDir.ASCENDING; + } + + @Override + public Enum getSortDisplay() { + 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 ad199ab9..46c62d16 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingStatus.java @@ -22,6 +22,7 @@ package appeng.client.gui.implementations; +import java.io.IOException; import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; @@ -44,142 +45,135 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; -import java.io.IOException; +public class GuiCraftingStatus extends GuiCraftingCPU { + private final ContainerCraftingStatus status; + private GuiButton selectCPU; + private GuiTabButton originalGuiBtn; + private GuiBridge originalGui; + private ItemStack myIcon = null; -public class GuiCraftingStatus extends GuiCraftingCPU -{ + public GuiCraftingStatus( + final InventoryPlayer inventoryPlayer, final ITerminalHost te + ) { + super(new ContainerCraftingStatus(inventoryPlayer, te)); - private final ContainerCraftingStatus status; - private GuiButton selectCPU; + this.status = (ContainerCraftingStatus) this.inventorySlots; + final Object target = this.status.getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); - private GuiTabButton originalGuiBtn; - private GuiBridge originalGui; - private ItemStack myIcon = null; + if (target instanceof WirelessTerminalGuiObject) { + for (final ItemStack wirelessTerminalStack : + definitions.items().wirelessTerminal().maybeStack(1).asSet()) { + this.myIcon = wirelessTerminalStack; + } - public GuiCraftingStatus( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( new ContainerCraftingStatus( inventoryPlayer, te ) ); + this.originalGui = GuiBridge.GUI_WIRELESS_TERM; + } - this.status = (ContainerCraftingStatus) this.inventorySlots; - final Object target = this.status.getTarget(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IParts parts = definitions.parts(); + if (target instanceof PartTerminal) { + for (final ItemStack stack : parts.terminal().maybeStack(1).asSet()) { + this.myIcon = stack; + } + this.originalGui = GuiBridge.GUI_ME; + } - if( target instanceof WirelessTerminalGuiObject ) - { - for( final ItemStack wirelessTerminalStack : definitions.items().wirelessTerminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = wirelessTerminalStack; - } + if (target instanceof PartCraftingTerminal) { + for (final ItemStack stack : parts.craftingTerminal().maybeStack(1).asSet()) { + this.myIcon = stack; + } + this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } - this.originalGui = GuiBridge.GUI_WIRELESS_TERM; - } + if (target instanceof PartPatternTerminal) { + for (final ItemStack stack : parts.patternTerminal().maybeStack(1).asSet()) { + this.myIcon = stack; + } + this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } + } - if( target instanceof PartTerminal ) - { - for( final ItemStack stack : parts.terminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = stack; - } - this.originalGui = GuiBridge.GUI_ME; - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - if( target instanceof PartCraftingTerminal ) - { - for( final ItemStack stack : parts.craftingTerminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = stack; - } - this.originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } + final boolean backwards = Mouse.isButtonDown(1); - if( target instanceof PartPatternTerminal ) - { - for( final ItemStack stack : parts.patternTerminal().maybeStack( 1 ).asSet() ) - { - this.myIcon = stack; - } - this.originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - } + if (btn == this.selectCPU) { + try { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("Terminal.Cpu", backwards ? "Prev" : "Next") + ); + } catch (final IOException e) { + AELog.debug(e); + } + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (btn == this.originalGuiBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.originalGui)); + } + } - final boolean backwards = Mouse.isButtonDown( 1 ); + @Override + public void initGui() { + super.initGui(); - if( btn == this.selectCPU ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "Terminal.Cpu", backwards ? "Prev" : "Next" ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + this.selectCPU = new GuiButton( + 0, + this.guiLeft + 8, + this.guiTop + this.ySize - 25, + 150, + 20, + GuiText.CraftingCPU.getLocal() + ": " + GuiText.NoCraftingCPUs + ); + // selectCPU.enabled = false; + this.buttonList.add(this.selectCPU); - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.originalGui ) ); - } - } + 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.setHideEdge(13); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + this.updateCPUButtonText(); + super.drawScreen(mouseX, mouseY, btn); + } - this.selectCPU = new GuiButton( 0, this.guiLeft + 8, this.guiTop + this.ySize - 25, 150, 20, GuiText.CraftingCPU.getLocal() + ": " + GuiText.NoCraftingCPUs ); - // selectCPU.enabled = false; - this.buttonList.add( this.selectCPU ); + private void updateCPUButtonText() { + String btnTextText = GuiText.NoCraftingJobs.getLocal(); - 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.setHideEdge( 13 ); - } - } + if (this.status.selectedCpu >= 0) // && status.selectedCpu < status.cpus.size() ) + { + if (this.status.myName.length() > 0) { + final String name = this.status.myName.substring( + 0, Math.min(20, this.status.myName.length()) + ); + btnTextText = GuiText.CPUs.getLocal() + ": " + name; + } else { + btnTextText = GuiText.CPUs.getLocal() + ": #" + this.status.selectedCpu; + } + } - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { - this.updateCPUButtonText(); - super.drawScreen( mouseX, mouseY, btn ); - } + if (this.status.noCPU) { + btnTextText = GuiText.NoCraftingJobs.getLocal(); + } - private void updateCPUButtonText() - { - String btnTextText = GuiText.NoCraftingJobs.getLocal(); + this.selectCPU.displayString = btnTextText; + } - if( this.status.selectedCpu >= 0 )// && status.selectedCpu < status.cpus.size() ) - { - if( this.status.myName.length() > 0 ) - { - final String name = this.status.myName.substring( 0, Math.min( 20, this.status.myName.length() ) ); - btnTextText = GuiText.CPUs.getLocal() + ": " + name; - } - else - { - btnTextText = GuiText.CPUs.getLocal() + ": #" + this.status.selectedCpu; - } - } - - if( this.status.noCPU ) - { - btnTextText = GuiText.NoCraftingJobs.getLocal(); - } - - this.selectCPU.displayString = btnTextText; - } - - @Override - protected String getGuiDisplayName( final String in ) - { - return in; // the cup name is on the button - } + @Override + protected String getGuiDisplayName(final String in) { + 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 f8ea72be..cb75b85f 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiCraftingTerm.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.ActionItems; import appeng.api.config.Settings; import appeng.api.storage.ITerminalHost; @@ -34,61 +33,66 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; +public class GuiCraftingTerm extends GuiMEMonitorable { + private GuiImgButton clearBtn; -public class GuiCraftingTerm extends GuiMEMonitorable -{ + public GuiCraftingTerm( + final InventoryPlayer inventoryPlayer, final ITerminalHost te + ) { + super(inventoryPlayer, te, new ContainerCraftingTerm(inventoryPlayer, te)); + this.setReservedSpace(73); + } - private GuiImgButton clearBtn; + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - public GuiCraftingTerm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerCraftingTerm( inventoryPlayer, te ) ); - this.setReservedSpace( 73 ); - } + if (this.clearBtn == btn) { + Slot s = null; + final Container c = this.inventorySlots; + for (final Object j : c.inventorySlots) { + if (j instanceof SlotCraftingMatrix) { + s = (Slot) j; + } + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (s != null) { + final PacketInventoryAction p = new PacketInventoryAction( + InventoryAction.MOVE_REGION, s.slotNumber, 0 + ); + NetworkHandler.instance.sendToServer(p); + } + } + } - if( this.clearBtn == btn ) - { - Slot s = null; - final Container c = this.inventorySlots; - for( final Object j : c.inventorySlots ) - { - if( j instanceof SlotCraftingMatrix ) - { - s = (Slot) j; - } - } + @Override + public void initGui() { + super.initGui(); + this.buttonList.add( + this.clearBtn = new GuiImgButton( + this.guiLeft + 92, + this.guiTop + this.ySize - 156, + Settings.ACTIONS, + ActionItems.STASH + ) + ); + this.clearBtn.setHalfSize(true); + } - if( s != null ) - { - final PacketInventoryAction p = new PacketInventoryAction( InventoryAction.MOVE_REGION, s.slotNumber, 0 ); - NetworkHandler.instance.sendToServer( p ); - } - } - } + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRendererObj.drawString( + GuiText.CraftingTerminal.getLocal(), + 8, + this.ySize - 96 + 1 - this.getReservedSpace(), + 4210752 + ); + } - @Override - public void initGui() - { - super.initGui(); - this.buttonList.add( this.clearBtn = new GuiImgButton( this.guiLeft + 92, this.guiTop + this.ySize - 156, Settings.ACTIONS, ActionItems.STASH ) ); - this.clearBtn.setHalfSize( true ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.CraftingTerminal.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), 4210752 ); - } - - @Override - protected String getBackground() - { - return "guis/crafting.png"; - } + @Override + protected String getBackground() { + return "guis/crafting.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiDrive.java b/src/main/java/appeng/client/gui/implementations/GuiDrive.java index 5d4d15a7..30a842be 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiDrive.java +++ b/src/main/java/appeng/client/gui/implementations/GuiDrive.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiTabButton; import appeng.container.implementations.ContainerDrive; @@ -30,48 +29,55 @@ import appeng.tile.storage.TileDrive; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; +public class GuiDrive extends AEBaseGui { + private GuiTabButton priority; -public class GuiDrive extends AEBaseGui -{ + public GuiDrive(final InventoryPlayer inventoryPlayer, final TileDrive te) { + super(new ContainerDrive(inventoryPlayer, te)); + this.ySize = 199; + } - private GuiTabButton priority; + @Override + protected void actionPerformed(final GuiButton par1GuiButton) { + super.actionPerformed(par1GuiButton); - public GuiDrive( final InventoryPlayer inventoryPlayer, final TileDrive te ) - { - super( new ContainerDrive( inventoryPlayer, te ) ); - this.ySize = 199; - } + if (par1GuiButton == this.priority) { + NetworkHandler.instance.sendToServer( + new PacketSwitchGuis(GuiBridge.GUI_PRIORITY) + ); + } + } - @Override - protected void actionPerformed( final GuiButton par1GuiButton ) - { - super.actionPerformed( par1GuiButton ); + @Override + public void initGui() { + super.initGui(); - if( par1GuiButton == this.priority ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_PRIORITY ) ); - } - } + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + 2 + 4 * 16, + GuiText.Priority.getLocal(), + itemRender + ) + ); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); + } - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/drive.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 dd9b8f5a..fa1cbb48 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java +++ b/src/main/java/appeng/client/gui/implementations/GuiFormationPlane.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.FuzzyMode; import appeng.api.config.Settings; import appeng.api.config.YesNo; @@ -35,68 +34,78 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; +public class GuiFormationPlane extends GuiUpgradeable { + private GuiTabButton priority; + private GuiImgButton placeMode; -public class GuiFormationPlane extends GuiUpgradeable -{ + public GuiFormationPlane( + final InventoryPlayer inventoryPlayer, final PartFormationPlane te + ) { + super(new ContainerFormationPlane(inventoryPlayer, te)); + this.ySize = 251; + } - private GuiTabButton priority; - private GuiImgButton placeMode; + @Override + protected void addButtons() { + this.placeMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 28, Settings.PLACE_BLOCK, YesNo.YES + ); + this.fuzzyMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); - public GuiFormationPlane( final InventoryPlayer inventoryPlayer, final PartFormationPlane te ) - { - super( new ContainerFormationPlane( inventoryPlayer, te ) ); - this.ySize = 251; - } + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + 2 + 4 * 16, + GuiText.Priority.getLocal(), + itemRender + ) + ); - @Override - protected void addButtons() - { - this.placeMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.PLACE_BLOCK, YesNo.YES ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); + this.buttonList.add(this.placeMode); + this.buttonList.add(this.fuzzyMode); + } - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); - this.buttonList.add( this.placeMode ); - this.buttonList.add( this.fuzzyMode ); - } + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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.placeMode != null) { + this.placeMode.set(((ContainerFormationPlane) this.cvb).getPlaceMode()); + } + } - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } - if( this.placeMode != null ) - { - this.placeMode.set( ( (ContainerFormationPlane) this.cvb ).getPlaceMode() ); - } - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final 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 (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 9c0969ec..82139766 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiGrinder.java +++ b/src/main/java/appeng/client/gui/implementations/GuiGrinder.java @@ -18,34 +18,33 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerGrinder; import appeng.core.localization.GuiText; import appeng.tile.grindstone.TileGrinder; import net.minecraft.entity.player.InventoryPlayer; +public class GuiGrinder extends AEBaseGui { + public GuiGrinder(final InventoryPlayer inventoryPlayer, final TileGrinder te) { + super(new ContainerGrinder(inventoryPlayer, te)); + this.ySize = 176; + } -public class GuiGrinder extends AEBaseGui -{ + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); + } - public GuiGrinder( final InventoryPlayer inventoryPlayer, final TileGrinder te ) - { - super( new ContainerGrinder( inventoryPlayer, te ) ); - this.ySize = 176; - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/grinder.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 aeac8cb5..b01bbcd3 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiIOPort.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.AEApi; import appeng.api.config.FullnessMode; import appeng.api.config.OperationMode; @@ -36,92 +35,100 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; +public class GuiIOPort extends GuiUpgradeable { + private GuiImgButton fullMode; + private GuiImgButton operationMode; -public class GuiIOPort extends GuiUpgradeable -{ + public GuiIOPort(final InventoryPlayer inventoryPlayer, final TileIOPort te) { + super(new ContainerIOPort(inventoryPlayer, te)); + this.ySize = 166; + } - private GuiImgButton fullMode; - private GuiImgButton operationMode; + @Override + protected void addButtons() { + this.redstoneMode = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 28, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.IGNORE + ); + this.fullMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.FULLNESS_MODE, FullnessMode.EMPTY + ); + this.operationMode = new GuiImgButton( + this.guiLeft + 80, + this.guiTop + 17, + Settings.OPERATION_MODE, + OperationMode.EMPTY + ); - public GuiIOPort( final InventoryPlayer inventoryPlayer, final TileIOPort te ) - { - super( new ContainerIOPort( inventoryPlayer, te ) ); - this.ySize = 166; - } + this.buttonList.add(this.operationMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fullMode); + } - @Override - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.fullMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.FULLNESS_MODE, FullnessMode.EMPTY ); - this.operationMode = new GuiImgButton( this.guiLeft + 80, this.guiTop + 17, Settings.OPERATION_MODE, OperationMode.EMPTY ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); - this.buttonList.add( this.operationMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fullMode ); - } + if (this.redstoneMode != null) { + this.redstoneMode.set(this.cvb.getRedStoneMode()); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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.operationMode != null) { + this.operationMode.set(((ContainerIOPort) this.cvb).getOperationMode()); + } - if( this.redstoneMode != null ) - { - this.redstoneMode.set( this.cvb.getRedStoneMode() ); - } + if (this.fullMode != null) { + this.fullMode.set(((ContainerIOPort) this.cvb).getFullMode()); + } + } - if( this.operationMode != null ) - { - this.operationMode.set( ( (ContainerIOPort) this.cvb ).getOperationMode() ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); - if( this.fullMode != null ) - { - this.fullMode.set( ( (ContainerIOPort) this.cvb ).getFullMode() ); - } - } + final IDefinitions definitions = AEApi.instance().definitions(); - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); + for (final ItemStack cell1kStack : + definitions.items().cell1k().maybeStack(1).asSet()) { + this.drawItem(offsetX + 66 - 8, offsetY + 17, cell1kStack); + } - final IDefinitions definitions = AEApi.instance().definitions(); + for (final ItemStack driveStack : + definitions.blocks().drive().maybeStack(1).asSet()) { + this.drawItem(offsetX + 94 + 8, offsetY + 17, driveStack); + } + } - for( final ItemStack cell1kStack : definitions.items().cell1k().maybeStack( 1 ).asSet() ) - { - this.drawItem( offsetX + 66 - 8, offsetY + 17, cell1kStack ); - } + @Override + protected String getBackground() { + return "guis/ioport.png"; + } - for( final ItemStack driveStack : definitions.blocks().drive().maybeStack( 1 ).asSet() ) - { - this.drawItem( offsetX + 94 + 8, offsetY + 17, driveStack ); - } - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - @Override - protected String getBackground() - { - return "guis/ioport.png"; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (btn == this.fullMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.fullMode.getSetting(), backwards) + ); + } - final 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 ) ); - } - } + 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 50a86cdd..54e63772 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInscriber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInscriber.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiProgressBar; import appeng.client.gui.widgets.GuiProgressBar.Direction; @@ -28,65 +27,68 @@ import appeng.core.localization.GuiText; import appeng.tile.misc.TileInscriber; import net.minecraft.entity.player.InventoryPlayer; +public class GuiInscriber extends AEBaseGui { + private final ContainerInscriber cvc; + private GuiProgressBar pb; -public class GuiInscriber extends AEBaseGui -{ + public GuiInscriber(final InventoryPlayer inventoryPlayer, final TileInscriber te) { + super(new ContainerInscriber(inventoryPlayer, te)); + this.cvc = (ContainerInscriber) this.inventorySlots; + this.ySize = 176; + this.xSize = this.hasToolbox() ? 246 : 211; + } - private final ContainerInscriber cvc; - private GuiProgressBar pb; + private boolean hasToolbox() { + return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); + } - public GuiInscriber( final InventoryPlayer inventoryPlayer, final TileInscriber te ) - { - super( new ContainerInscriber( inventoryPlayer, te ) ); - this.cvc = (ContainerInscriber) this.inventorySlots; - this.ySize = 176; - this.xSize = this.hasToolbox() ? 246 : 211; - } + @Override + public void initGui() { + super.initGui(); - private boolean hasToolbox() - { - return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); - } + 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 initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.setFullMsg( + this.cvc.getCurrentProgress() * 100 / this.cvc.getMaxProgress() + "%" + ); - this.pb = new GuiProgressBar( this.cvc, "guis/inscriber.png", 135, 39, 135, 177, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Inscriber.getLocal()), 8, 6, 4210752 + ); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 + ); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.setFullMsg( this.cvc.getCurrentProgress() * 100 / this.cvc.getMaxProgress() + "%" ); + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/inscriber.png"); + this.pb.xPosition = 135 + this.guiLeft; + this.pb.yPosition = 39 + this.guiTop; - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Inscriber.getLocal() ), 8, 6, 4210752 ); - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/inscriber.png" ); - this.pb.xPosition = 135 + this.guiLeft; - this.pb.yPosition = 39 + this.guiTop; + 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 + ); + } + } - 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 ); - } - } - - private boolean drawUpgrades() - { - return true; - } + private boolean drawUpgrades() { + return true; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiInterface.java b/src/main/java/appeng/client/gui/implementations/GuiInterface.java index 6be8582c..a3fa881f 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterface.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterface.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.api.config.YesNo; import appeng.client.gui.widgets.GuiImgButton; @@ -35,81 +34,102 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; +public class GuiInterface extends GuiUpgradeable { + private GuiTabButton priority; + private GuiImgButton BlockMode; + private GuiToggleButton interfaceMode; -public class GuiInterface extends GuiUpgradeable -{ + public GuiInterface(final InventoryPlayer inventoryPlayer, final IInterfaceHost te) { + super(new ContainerInterface(inventoryPlayer, te)); + this.ySize = 211; + } - private GuiTabButton priority; - private GuiImgButton BlockMode; - private GuiToggleButton interfaceMode; + @Override + protected void addButtons() { + this.priority = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + 2 + 4 * 16, + GuiText.Priority.getLocal(), + itemRender + ); + this.buttonList.add(this.priority); - public GuiInterface( final InventoryPlayer inventoryPlayer, final IInterfaceHost te ) - { - super( new ContainerInterface( inventoryPlayer, te ) ); - this.ySize = 211; - } + this.BlockMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO + ); + this.buttonList.add(this.BlockMode); - @Override - protected void addButtons() - { - this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ); - this.buttonList.add( this.priority ); + this.interfaceMode = new GuiToggleButton( + this.guiLeft - 18, + this.guiTop + 26, + 84, + 85, + GuiText.InterfaceTerminal.getLocal(), + GuiText.InterfaceTerminalHint.getLocal() + ); + this.buttonList.add(this.interfaceMode); + } - this.BlockMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO ); - this.buttonList.add( this.BlockMode ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (this.BlockMode != null) { + this.BlockMode.set(((ContainerInterface) this.cvb).getBlockingMode()); + } - this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), GuiText.InterfaceTerminalHint.getLocal() ); - this.buttonList.add( this.interfaceMode ); - } + if (this.interfaceMode != null) { + this.interfaceMode.setState( + ((ContainerInterface) this.cvb).getInterfaceTerminalMode() == YesNo.YES + ); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( this.BlockMode != null ) - { - this.BlockMode.set( ( (ContainerInterface) this.cvb ).getBlockingMode() ); - } + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.Interface.getLocal()), 8, 6, 4210752 + ); - if( this.interfaceMode != null ) - { - this.interfaceMode.setState( ( (ContainerInterface) this.cvb ).getInterfaceTerminalMode() == YesNo.YES ); - } + this.fontRendererObj.drawString( + GuiText.Config.getLocal(), 18, 6 + 11 + 7, 4210752 + ); + this.fontRendererObj.drawString( + GuiText.StoredItems.getLocal(), 18, 6 + 60 + 7, 4210752 + ); + this.fontRendererObj.drawString( + GuiText.Patterns.getLocal(), 8, 6 + 73 + 7, 4210752 + ); - this.fontRendererObj.drawString( this.getGuiDisplayName( GuiText.Interface.getLocal() ), 8, 6, 4210752 ); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 + ); + } - this.fontRendererObj.drawString( GuiText.Config.getLocal(), 18, 6 + 11 + 7, 4210752 ); - this.fontRendererObj.drawString( GuiText.StoredItems.getLocal(), 18, 6 + 60 + 7, 4210752 ); - this.fontRendererObj.drawString( GuiText.Patterns.getLocal(), 8, 6 + 73 + 7, 4210752 ); + @Override + protected String getBackground() { + return "guis/interface.png"; + } - this.fontRendererObj.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 ); - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - @Override - protected String getBackground() - { - return "guis/interface.png"; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (btn == this.priority) { + NetworkHandler.instance.sendToServer( + new PacketSwitchGuis(GuiBridge.GUI_PRIORITY) + ); + } - final boolean backwards = Mouse.isButtonDown( 1 ); + if (btn == this.interfaceMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(Settings.INTERFACE_TERMINAL, backwards) + ); + } - 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 ) ); - } - } + 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 a6420bd9..8d27ce40 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java +++ b/src/main/java/appeng/client/gui/implementations/GuiInterfaceTerminal.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; +import java.util.*; import appeng.api.AEApi; import appeng.client.gui.AEBaseGui; @@ -36,363 +37,344 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import org.lwjgl.opengl.GL11; -import java.util.*; +public class GuiInterfaceTerminal extends AEBaseGui { + private static final int LINES_ON_PAGE = 6; + // TODO: copied from GuiMEMonitorable. It looks not changed, maybe unneeded? + private final int offsetX = 9; -public class GuiInterfaceTerminal extends AEBaseGui -{ + private final HashMap byId + = new HashMap(); + private final HashMultimap byName + = HashMultimap.create(); + private final ArrayList names = new ArrayList(); + private final ArrayList lines = new ArrayList(); - private static final int LINES_ON_PAGE = 6; + private final Map> cachedSearches + = new WeakHashMap>(); - // TODO: copied from GuiMEMonitorable. It looks not changed, maybe unneeded? - private final int offsetX = 9; + private boolean refreshList = false; + private MEGuiTextField searchField; - private final HashMap byId = new HashMap(); - private final HashMultimap byName = HashMultimap.create(); - private final ArrayList names = new ArrayList(); - private final ArrayList lines = new ArrayList(); + public GuiInterfaceTerminal( + final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te + ) { + super(new ContainerInterfaceTerminal(inventoryPlayer, te)); - private final Map> cachedSearches = new WeakHashMap>(); + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + this.xSize = 195; + this.ySize = 222; + } - private boolean refreshList = false; - private MEGuiTextField searchField; + @Override + public void initGui() { + super.initGui(); - public GuiInterfaceTerminal( final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te ) - { - super( new ContainerInterfaceTerminal( inventoryPlayer, te ) ); + this.getScrollBar().setLeft(175); + this.getScrollBar().setHeight(106); + this.getScrollBar().setTop(18); - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.xSize = 195; - this.ySize = 222; - } + this.searchField = new MEGuiTextField( + this.fontRendererObj, + this.guiLeft + Math.max(104, this.offsetX), + this.guiTop + 4, + 65, + 12 + ); + this.searchField.setEnableBackgroundDrawing(false); + this.searchField.setMaxStringLength(25); + this.searchField.setTextColor(0xFFFFFF); + this.searchField.setVisible(true); + this.searchField.setFocused(true); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); - this.getScrollBar().setLeft( 175 ); - this.getScrollBar().setHeight( 106 ); - this.getScrollBar().setTop( 18 ); + final int ex = this.getScrollBar().getCurrentScroll(); - this.searchField = new MEGuiTextField( this.fontRendererObj, this.guiLeft + Math.max( 104, this.offsetX ), this.guiTop + 4, 65, 12 ); - this.searchField.setEnableBackgroundDrawing( false ); - this.searchField.setMaxStringLength( 25 ); - this.searchField.setTextColor( 0xFFFFFF ); - this.searchField.setVisible( true ); - this.searchField.setFocused( true ); - } + final Iterator o = this.inventorySlots.inventorySlots.iterator(); + while (o.hasNext()) { + if (o.next() instanceof SlotDisconnected) { + o.remove(); + } + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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; + for (int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(ex + x); + if (lineObj instanceof ClientDCInternalInv) { + final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + for (int z = 0; z < inv.getInventory().getSizeInventory(); z++) { + this.inventorySlots.inventorySlots.add( + new SlotDisconnected(inv, z, z * 18 + 8, 1 + offset) + ); + } + } else if (lineObj instanceof String) { + String name = (String) lineObj; + final int rows = this.byName.get(name).size(); + if (rows > 1) { + name = name + " (" + rows + ')'; + } - final int ex = this.getScrollBar().getCurrentScroll(); + while (name.length() > 2 + && this.fontRendererObj.getStringWidth(name) > 155) { + name = name.substring(0, name.length() - 1); + } - final Iterator o = this.inventorySlots.inventorySlots.iterator(); - while( o.hasNext() ) - { - if( o.next() instanceof SlotDisconnected ) - { - o.remove(); - } - } + this.fontRendererObj.drawString(name, 10, 6 + offset, 4210752); + } + offset += 18; + } + } - int offset = 17; - for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( ex + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - for( int z = 0; z < inv.getInventory().getSizeInventory(); z++ ) - { - this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z, z * 18 + 8, 1 + offset ) ); - } - } - else if( lineObj instanceof String ) - { - String name = (String) lineObj; - final int rows = this.byName.get( name ).size(); - if( rows > 1 ) - { - name = name + " (" + rows + ')'; - } + @Override + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + this.searchField.mouseClicked(xCoord, yCoord, btn); - while( name.length() > 2 && this.fontRendererObj.getStringWidth( name ) > 155 ) - { - name = name.substring( 0, name.length() - 1 ); - } + if (btn == 1 && this.searchField.isMouseIn(xCoord, yCoord)) { + this.searchField.setText(""); + this.refreshList(); + } - this.fontRendererObj.drawString( name, 10, 6 + offset, 4210752 ); - } - offset += 18; - } - } + super.mouseClicked(xCoord, yCoord, btn); + } - @Override - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - this.searchField.mouseClicked( xCoord, yCoord, btn ); + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/interfaceterminal.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); - if( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) - { - this.searchField.setText( "" ); - this.refreshList(); - } + int offset = 17; + final int ex = this.getScrollBar().getCurrentScroll(); - super.mouseClicked( xCoord, yCoord, btn ); - } + for (int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++) { + final Object lineObj = this.lines.get(ex + x); + if (lineObj instanceof ClientDCInternalInv) { + final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/interfaceterminal.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + GL11.glColor4f(1, 1, 1, 1); + final int width = inv.getInventory().getSizeInventory() * 18; + this.drawTexturedModalRect( + offsetX + 7, offsetY + offset, 7, 139, width, 18 + ); + } + offset += 18; + } - int offset = 17; - final int ex = this.getScrollBar().getCurrentScroll(); + if (this.searchField != null) { + this.searchField.drawTextBox(); + } + } - for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ ) - { - final Object lineObj = this.lines.get( ex + x ); - if( lineObj instanceof ClientDCInternalInv ) - { - final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj; + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if (character == ' ' && this.searchField.getText().isEmpty()) { + return; + } - GL11.glColor4f( 1, 1, 1, 1 ); - final int width = inv.getInventory().getSizeInventory() * 18; - this.drawTexturedModalRect( offsetX + 7, offsetY + offset, 7, 139, width, 18 ); - } - offset += 18; - } + if (this.searchField.textboxKeyTyped(character, key)) { + this.refreshList(); + } else { + super.keyTyped(character, key); + } + } + } - if( this.searchField != null ) - { - this.searchField.drawTextBox(); - } - } + public void postUpdate(final NBTTagCompound in) { + if (in.getBoolean("clear")) { + this.byId.clear(); + this.refreshList = true; + } - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( character == ' ' && this.searchField.getText().isEmpty() ) - { - return; - } + for (final Object oKey : in.func_150296_c()) { + final String key = (String) oKey; + if (key.startsWith("=")) { + try { + final long id = Long.parseLong(key.substring(1), Character.MAX_RADIX); + final NBTTagCompound invData = in.getCompoundTag(key); + final ClientDCInternalInv current = this.getById( + id, invData.getLong("sortBy"), invData.getString("un") + ); - if( this.searchField.textboxKeyTyped( character, key ) ) - { - this.refreshList(); - } - else - { - super.keyTyped( character, key ); - } - } - } + for (int x = 0; x < current.getInventory().getSizeInventory(); x++) { + final String which = Integer.toString(x); + if (invData.hasKey(which)) { + current.getInventory().setInventorySlotContents( + x, + ItemStack.loadItemStackFromNBT( + invData.getCompoundTag(which) + ) + ); + } + } + } catch (final NumberFormatException ignored) {} + } + } - public void postUpdate( final NBTTagCompound in ) - { - if( in.getBoolean( "clear" ) ) - { - this.byId.clear(); - this.refreshList = true; - } + if (this.refreshList) { + this.refreshList = false; + // invalid caches on refresh + this.cachedSearches.clear(); + this.refreshList(); + } + } - for( final Object oKey : in.func_150296_c() ) - { - final String key = (String) oKey; - if( key.startsWith( "=" ) ) - { - try - { - final long id = Long.parseLong( key.substring( 1 ), Character.MAX_RADIX ); - final NBTTagCompound invData = in.getCompoundTag( key ); - final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) ); + /** + * Rebuilds the list of interfaces. + *

+ * Respects a search term if present (ignores case) and adding only matching patterns. + */ + private void refreshList() { + this.byName.clear(); - for( int x = 0; x < current.getInventory().getSizeInventory(); x++ ) - { - final String which = Integer.toString( x ); - if( invData.hasKey( which ) ) - { - current.getInventory().setInventorySlotContents( x, ItemStack.loadItemStackFromNBT( invData.getCompoundTag( which ) ) ); - } - } - } - catch( final NumberFormatException ignored ) - { - } - } - } + final String searchFilterLowerCase = this.searchField.getText().toLowerCase(); - if( this.refreshList ) - { - this.refreshList = false; - // invalid caches on refresh - this.cachedSearches.clear(); - this.refreshList(); - } - } + final Set cachedSearch + = this.getCacheForSearchTerm(searchFilterLowerCase); + final boolean rebuild = cachedSearch.isEmpty(); - /** - * Rebuilds the list of interfaces. - *

- * Respects a search term if present (ignores case) and adding only matching patterns. - */ - private void refreshList() - { - this.byName.clear(); + for (final 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)) { + continue; + } - final String searchFilterLowerCase = this.searchField.getText().toLowerCase(); + // Shortcut to skip any filter if search term is ""/empty + boolean found = searchFilterLowerCase.isEmpty(); - final Set cachedSearch = this.getCacheForSearchTerm( searchFilterLowerCase ); - final boolean rebuild = cachedSearch.isEmpty(); + // Search if the current inventory holds a pattern containing the search term. + if (!found && !searchFilterLowerCase.isEmpty()) { + for (final ItemStack itemStack : entry.getInventory()) { + found = this.itemStackMatchesSearchTerm( + itemStack, searchFilterLowerCase + ); + if (found) { + break; + } + } + } - for( final 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 ) ) - { - continue; - } + // if found, filter skipped or machine name matching the search term, add it + if (found || entry.getName().toLowerCase().contains(searchFilterLowerCase)) { + this.byName.put(entry.getName(), entry); + cachedSearch.add(entry); + } else { + cachedSearch.remove(entry); + } + } - // Shortcut to skip any filter if search term is ""/empty - boolean found = searchFilterLowerCase.isEmpty(); + this.names.clear(); + this.names.addAll(this.byName.keySet()); - // Search if the current inventory holds a pattern containing the search term. - if( !found && !searchFilterLowerCase.isEmpty() ) - { - for( final ItemStack itemStack : entry.getInventory() ) - { - found = this.itemStackMatchesSearchTerm( itemStack, searchFilterLowerCase ); - if( found ) - { - break; - } - } - } + Collections.sort(this.names); - // if found, filter skipped or machine name matching the search term, add it - if( found || entry.getName().toLowerCase().contains( searchFilterLowerCase ) ) - { - this.byName.put( entry.getName(), entry ); - cachedSearch.add( entry ); - } - else - { - cachedSearch.remove( entry ); - } - } + this.lines.clear(); + this.lines.ensureCapacity(this.getMaxRows()); - this.names.clear(); - this.names.addAll( this.byName.keySet() ); + for (final String n : this.names) { + this.lines.add(n); - Collections.sort( this.names ); + final ArrayList clientInventories + = new ArrayList(); + clientInventories.addAll(this.byName.get(n)); - this.lines.clear(); - this.lines.ensureCapacity( this.getMaxRows() ); + Collections.sort(clientInventories); + this.lines.addAll(clientInventories); + } - for( final String n : this.names ) - { - this.lines.add( n ); + this.getScrollBar().setRange(0, this.lines.size() - LINES_ON_PAGE, 2); + } - final ArrayList clientInventories = new ArrayList(); - clientInventories.addAll( this.byName.get( n ) ); + private boolean + itemStackMatchesSearchTerm(final ItemStack itemStack, final String searchTerm) { + if (itemStack == null) { + return false; + } - Collections.sort( clientInventories ); - this.lines.addAll( clientInventories ); - } + final NBTTagCompound encodedValue = itemStack.getTagCompound(); - this.getScrollBar().setRange( 0, this.lines.size() - LINES_ON_PAGE, 2 ); - } + if (encodedValue == null) { + return false; + } - private boolean itemStackMatchesSearchTerm( final ItemStack itemStack, final String searchTerm ) - { - if( itemStack == null ) - { - return false; - } + // Potential later use to filter by input + // NBTTagList inTag = encodedValue.getTagList( "in", 10 ); + final NBTTagList outTag = encodedValue.getTagList("out", 10); - final NBTTagCompound encodedValue = itemStack.getTagCompound(); + for (int i = 0; i < outTag.tagCount(); i++) { + final ItemStack parsedItemStack + = ItemStack.loadItemStackFromNBT(outTag.getCompoundTagAt(i)); + if (parsedItemStack != null) { + final String displayName + = Platform + .getItemDisplayName( + AEApi.instance().storage().createItemStack(parsedItemStack) + ) + .toLowerCase(); + if (displayName.contains(searchTerm)) { + return true; + } + } + } + return false; + } - if( encodedValue == null ) - { - return false; - } + /** + * Tries to retrieve a cache for a with search term as keyword. + *

+ * 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 + * @return a Set matching a superset of the search term + */ + private Set getCacheForSearchTerm(final String searchTerm) { + if (!this.cachedSearches.containsKey(searchTerm)) { + this.cachedSearches.put(searchTerm, new HashSet()); + } - // Potential later use to filter by input - // NBTTagList inTag = encodedValue.getTagList( "in", 10 ); - final NBTTagList outTag = encodedValue.getTagList( "out", 10 ); + final Set cache = this.cachedSearches.get(searchTerm); - for( int i = 0; i < outTag.tagCount(); i++ ) - { + if (cache.isEmpty() && searchTerm.length() > 1) { + cache.addAll(this.getCacheForSearchTerm( + searchTerm.substring(0, searchTerm.length() - 1) + )); + return cache; + } - final ItemStack parsedItemStack = ItemStack.loadItemStackFromNBT( outTag.getCompoundTagAt( i ) ); - if( parsedItemStack != null ) - { - final String displayName = Platform.getItemDisplayName( AEApi.instance().storage().createItemStack( parsedItemStack ) ).toLowerCase(); - if( displayName.contains( searchTerm ) ) - { - return true; - } - } - } - return false; - } + return cache; + } - /** - * Tries to retrieve a cache for a with search term as keyword. - *

- * 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 - * @return a Set matching a superset of the search term - */ - private Set getCacheForSearchTerm( final String searchTerm ) - { - if( !this.cachedSearches.containsKey( searchTerm ) ) - { - this.cachedSearches.put( searchTerm, new HashSet() ); - } + /** + * The max amount of unique names and each inv row. Not affected by the filtering. + * + * @return max amount of unique names and each inv row + */ + private int getMaxRows() { + return this.names.size() + this.byId.size(); + } - final Set cache = this.cachedSearches.get( searchTerm ); + private ClientDCInternalInv + getById(final long id, final long sortBy, final String string) { + ClientDCInternalInv o = this.byId.get(id); - if( cache.isEmpty() && searchTerm.length() > 1 ) - { - cache.addAll( this.getCacheForSearchTerm( searchTerm.substring( 0, searchTerm.length() - 1 ) ) ); - return cache; - } + if (o == null) { + this.byId.put(id, o = new ClientDCInternalInv(9, id, sortBy, string)); + this.refreshList = true; + } - return cache; - } - - /** - * The max amount of unique names and each inv row. Not affected by the filtering. - * - * @return max amount of unique names and each inv row - */ - private int getMaxRows() - { - return this.names.size() + this.byId.size(); - } - - private ClientDCInternalInv getById( final long id, final long sortBy, final String string ) - { - ClientDCInternalInv o = this.byId.get( id ); - - if( o == null ) - { - this.byId.put( id, o = new ClientDCInternalInv( 9, id, sortBy, string ) ); - this.refreshList = true; - } - - return o; - } + return o; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java b/src/main/java/appeng/client/gui/implementations/GuiLevelEmitter.java index c5ab9a49..a4e07de9 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 appeng.api.config.*; import appeng.client.gui.widgets.GuiImgButton; @@ -34,241 +35,262 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; -import java.io.IOException; +public class GuiLevelEmitter extends GuiUpgradeable { + private GuiNumberBox level; + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; -public class GuiLevelEmitter extends GuiUpgradeable -{ + private GuiImgButton levelMode; + private GuiImgButton craftingMode; - private GuiNumberBox level; + public GuiLevelEmitter( + final InventoryPlayer inventoryPlayer, final PartLevelEmitter te + ) { + super(new ContainerLevelEmitter(inventoryPlayer, te)); + } - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; + @Override + public void initGui() { + super.initGui(); - private GuiImgButton levelMode; - private GuiImgButton craftingMode; + this.level = new GuiNumberBox( + this.fontRendererObj, + this.guiLeft + 24, + this.guiTop + 43, + 79, + this.fontRendererObj.FONT_HEIGHT, + Long.class + ); + this.level.setEnableBackgroundDrawing(false); + this.level.setMaxStringLength(16); + this.level.setTextColor(0xFFFFFF); + this.level.setVisible(true); + this.level.setFocused(true); + ((ContainerLevelEmitter) this.inventorySlots).setTextField(this.level); + } - public GuiLevelEmitter( final InventoryPlayer inventoryPlayer, final PartLevelEmitter te ) - { - super( new ContainerLevelEmitter( inventoryPlayer, te ) ); - } + @Override + protected void addButtons() { + this.levelMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL + ); + this.redstoneMode = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 28, + Settings.REDSTONE_EMITTER, + RedstoneMode.LOW_SIGNAL + ); + this.fuzzyMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); + this.craftingMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_VIA_REDSTONE, YesNo.NO + ); - @Override - public void initGui() - { - super.initGui(); + final int a = AEConfig.instance.levelByStackAmounts(0); + final int b = AEConfig.instance.levelByStackAmounts(1); + final int c = AEConfig.instance.levelByStackAmounts(2); + final int d = AEConfig.instance.levelByStackAmounts(3); - this.level = new GuiNumberBox( this.fontRendererObj, this.guiLeft + 24, this.guiTop + 43, 79, this.fontRendererObj.FONT_HEIGHT, Long.class ); - this.level.setEnableBackgroundDrawing( false ); - this.level.setMaxStringLength( 16 ); - this.level.setTextColor( 0xFFFFFF ); - this.level.setVisible( true ); - this.level.setFocused( true ); - ( (ContainerLevelEmitter) this.inventorySlots ).setTextField( this.level ); - } + this.buttonList.add( + this.plus1 + = new GuiButton(0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a) + ); + this.buttonList.add( + this.plus10 + = new GuiButton(0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b) + ); + this.buttonList.add( + this.plus100 + = new GuiButton(0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c) + ); + this.buttonList.add( + this.plus1000 + = new GuiButton(0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d) + ); - @Override - protected void addButtons() - { - this.levelMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL ); - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.craftingMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_VIA_REDSTONE, YesNo.NO ); + this.buttonList.add( + this.minus1 + = new GuiButton(0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a) + ); + this.buttonList.add( + this.minus10 + = new GuiButton(0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b) + ); + this.buttonList.add( + this.minus100 + = new GuiButton(0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c) + ); + this.buttonList.add( + this.minus1000 + = new GuiButton(0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d) + ); - final int a = AEConfig.instance.levelByStackAmounts( 0 ); - final int b = AEConfig.instance.levelByStackAmounts( 1 ); - final int c = AEConfig.instance.levelByStackAmounts( 2 ); - final int d = AEConfig.instance.levelByStackAmounts( 3 ); + this.buttonList.add(this.levelMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.craftingMode); + } - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 17, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 17, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 17, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 17, 38, 20, "+" + d ) ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final boolean notCraftingMode + = this.bc.getInstalledUpgrades(Upgrades.CRAFTING) == 0; - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 59, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 59, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 59, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 59, 38, 20, "-" + d ) ); + // configure enabled status... + this.level.setEnabled(notCraftingMode); + this.plus1.enabled = notCraftingMode; + this.plus10.enabled = notCraftingMode; + this.plus100.enabled = notCraftingMode; + this.plus1000.enabled = notCraftingMode; + this.minus1.enabled = notCraftingMode; + this.minus10.enabled = notCraftingMode; + this.minus100.enabled = notCraftingMode; + this.minus1000.enabled = notCraftingMode; + this.levelMode.enabled = notCraftingMode; + this.redstoneMode.enabled = notCraftingMode; - this.buttonList.add( this.levelMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.craftingMode ); - } + super.drawFG(offsetX, offsetY, mouseX, mouseY); - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final boolean notCraftingMode = this.bc.getInstalledUpgrades( Upgrades.CRAFTING ) == 0; + if (this.craftingMode != null) { + this.craftingMode.set(this.cvb.getCraftingMode()); + } - // configure enabled status... - this.level.setEnabled( notCraftingMode ); - this.plus1.enabled = notCraftingMode; - this.plus10.enabled = notCraftingMode; - this.plus100.enabled = notCraftingMode; - this.plus1000.enabled = notCraftingMode; - this.minus1.enabled = notCraftingMode; - this.minus10.enabled = notCraftingMode; - this.minus100.enabled = notCraftingMode; - this.minus1000.enabled = notCraftingMode; - this.levelMode.enabled = notCraftingMode; - this.redstoneMode.enabled = notCraftingMode; + if (this.levelMode != null) { + this.levelMode.set(((ContainerLevelEmitter) this.cvb).getLevelMode()); + } + } - super.drawFG( offsetX, offsetY, mouseX, mouseY ); + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawBG(offsetX, offsetY, mouseX, mouseY); + this.level.drawTextBox(); + } - if( this.craftingMode != null ) - { - this.craftingMode.set( this.cvb.getCraftingMode() ); - } + @Override + protected void handleButtonVisibility() { + this.craftingMode.setVisibility( + this.bc.getInstalledUpgrades(Upgrades.CRAFTING) > 0 + ); + this.fuzzyMode.setVisibility(this.bc.getInstalledUpgrades(Upgrades.FUZZY) > 0); + } - if( this.levelMode != null ) - { - this.levelMode.set( ( (ContainerLevelEmitter) this.cvb ).getLevelMode() ); - } - } + @Override + protected String getBackground() { + return "guis/lvlemitter.png"; + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - this.level.drawTextBox(); - } + @Override + protected GuiText getName() { + return GuiText.LevelEmitter; + } - @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 actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - @Override - protected String getBackground() - { - return "guis/lvlemitter.png"; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected GuiText getName() - { - return GuiText.LevelEmitter; - } + if (btn == this.craftingMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.craftingMode.getSetting(), backwards) + ); + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (btn == this.levelMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.levelMode.getSetting(), backwards) + ); + } - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean isPlus = btn == this.plus1 || btn == this.plus10 + || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 + || btn == this.minus100 || btn == this.minus1000; - if( btn == this.craftingMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.craftingMode.getSetting(), backwards ) ); - } + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } - if( btn == this.levelMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.levelMode.getSetting(), backwards ) ); - } + private void addQty(final long i) { + try { + String Out = this.level.getText(); - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } + if (Fixed) { + this.level.setText(Out); + } - private void addQty( final long i ) - { - try - { - String Out = this.level.getText(); + if (Out.isEmpty()) { + Out = "0"; + } - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } + long result = Long.parseLong(Out); + result += i; + if (result < 0) { + result = 0; + } - if( Fixed ) - { - this.level.setText( Out ); - } + this.level.setText(Out = Long.toString(result)); - if( Out.isEmpty() ) - { - Out = "0"; - } + NetworkHandler.instance.sendToServer( + new PacketValueConfig("LevelEmitter.Value", Out) + ); + } catch (final NumberFormatException e) { + // nope.. + this.level.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } - long result = Long.parseLong( Out ); - result += i; - if( result < 0 ) - { - result = 0; - } + @Override + protected void keyTyped(final char character, final 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(); - this.level.setText( Out = Long.toString( result ) ); + boolean Fixed = false; + while (Out.startsWith("0") && Out.length() > 1) { + Out = Out.substring(1); + Fixed = true; + } - NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch( final NumberFormatException e ) - { - // nope.. - this.level.setText( "0" ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + if (Fixed) { + this.level.setText(Out); + } - @Override - protected void keyTyped( final char character, final 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(); + if (Out.isEmpty()) { + Out = "0"; + } - boolean Fixed = false; - while( Out.startsWith( "0" ) && Out.length() > 1 ) - { - Out = Out.substring( 1 ); - Fixed = true; - } - - if( Fixed ) - { - this.level.setText( Out ); - } - - if( Out.isEmpty() ) - { - Out = "0"; - } - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "LevelEmitter.Value", Out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } + NetworkHandler.instance.sendToServer( + new PacketValueConfig("LevelEmitter.Value", Out) + ); + } catch (final IOException e) { + AELog.debug(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 2175a4c2..d6972688 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMAC.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMAC.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.RedstoneMode; import appeng.api.config.Settings; import appeng.client.gui.widgets.GuiImgButton; @@ -29,60 +28,61 @@ import appeng.core.localization.GuiText; import appeng.tile.crafting.TileMolecularAssembler; import net.minecraft.entity.player.InventoryPlayer; +public class GuiMAC extends GuiUpgradeable { + private final ContainerMAC container; + private GuiProgressBar pb; -public class GuiMAC extends GuiUpgradeable -{ + public GuiMAC( + final InventoryPlayer inventoryPlayer, final TileMolecularAssembler te + ) { + super(new ContainerMAC(inventoryPlayer, te)); + this.ySize = 197; + this.container = (ContainerMAC) this.inventorySlots; + } - private final ContainerMAC container; - private GuiProgressBar pb; + @Override + public void initGui() { + super.initGui(); - public GuiMAC( final InventoryPlayer inventoryPlayer, final TileMolecularAssembler te ) - { - super( new ContainerMAC( inventoryPlayer, te ) ); - this.ySize = 197; - this.container = (ContainerMAC) this.inventorySlots; - } + this.pb = new GuiProgressBar( + this.container, "guis/mac.png", 139, 36, 148, 201, 6, 18, Direction.VERTICAL + ); + this.buttonList.add(this.pb); + } - @Override - public void initGui() - { - super.initGui(); + @Override + protected void addButtons() { + this.redstoneMode = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 8, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.IGNORE + ); + this.buttonList.add(this.redstoneMode); + } - this.pb = new GuiProgressBar( this.container, "guis/mac.png", 139, 36, 148, 201, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.setFullMsg(this.container.getCurrentProgress() + "%"); + super.drawFG(offsetX, offsetY, mouseX, mouseY); + } - @Override - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.buttonList.add( this.redstoneMode ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.pb.xPosition = 148 + this.guiLeft; + this.pb.yPosition = 48 + this.guiTop; + super.drawBG(offsetX, offsetY, mouseX, mouseY); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.setFullMsg( this.container.getCurrentProgress() + "%" ); - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - } + @Override + protected String getBackground() { + return "guis/mac.png"; + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.pb.xPosition = 148 + this.guiLeft; - this.pb.yPosition = 48 + this.guiTop; - super.drawBG( offsetX, offsetY, mouseX, mouseY ); - } - - @Override - protected String getBackground() - { - return "guis/mac.png"; - } - - @Override - protected GuiText getName() - { - return GuiText.MolecularAssembler; - } + @Override + protected GuiText getName() { + return GuiText.MolecularAssembler; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java index d1aec869..caac5e64 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEMonitorable.java @@ -18,6 +18,8 @@ package appeng.client.gui.implementations; +import java.io.IOException; +import java.util.List; import appeng.api.config.SearchBoxMode; import appeng.api.config.Settings; @@ -59,500 +61,511 @@ import net.minecraft.item.ItemStack; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; -import java.io.IOException; -import java.util.List; - - -public class GuiMEMonitorable extends AEBaseMEGui implements ISortSource, IConfigManagerHost -{ - - public static int craftingGridOffsetX; - public static int craftingGridOffsetY; - - private static String memoryText = ""; - private final ItemRepo repo; - private final int offsetX = 9; - private final int lowerTextureOffset = 0; - private final IConfigManager configSrc; - private final boolean viewCell; - private final ItemStack[] myCurrentViewCells = new ItemStack[5]; - private final ContainerMEMonitorable monitorableContainer; - private GuiTabButton craftingStatusBtn; - private MEGuiTextField searchField; - private GuiText myName; - private int perRow = 9; - private int reservedSpace = 0; - private boolean customSortOrder = true; - private int rows = 0; - private int maxRows = Integer.MAX_VALUE; - private int standardSize; - private GuiImgButton ViewBox; - private GuiImgButton SortByBox; - private GuiImgButton SortDirBox; - private GuiImgButton searchBoxSettings; - private GuiImgButton terminalStyleBox; - - public GuiMEMonitorable( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - this( inventoryPlayer, te, new ContainerMEMonitorable( inventoryPlayer, te ) ); - } - - public GuiMEMonitorable( final InventoryPlayer inventoryPlayer, final ITerminalHost te, final ContainerMEMonitorable c ) - { - - super( c ); - - final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.repo = new ItemRepo( scrollbar, this ); - - this.xSize = 185; - this.ySize = 204; - - if( te instanceof IViewCellStorage ) - { - this.xSize += 33; - } - - this.standardSize = this.xSize; - - this.configSrc = ( (IConfigurableObject) this.inventorySlots ).getConfigManager(); - ( this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots ).setGui( this ); - - this.viewCell = te instanceof IViewCellStorage; - - if( te instanceof TileSecurity ) - { - this.myName = GuiText.Security; - } - else if( te instanceof WirelessTerminalGuiObject ) - { - this.myName = GuiText.WirelessTerminal; - } - else if( te instanceof IPortableCell ) - { - this.myName = GuiText.PortableCell; - } - else if( te instanceof IMEChest ) - { - this.myName = GuiText.Chest; - } - else if( te instanceof AbstractPartTerminal ) - { - this.myName = GuiText.Terminal; - } - else if( te instanceof TileTerminal ) { - this.myName = GuiText.Terminal; - } - } - - public void postUpdate( final List list ) - { - for( final IAEItemStack is : list ) - { - this.repo.postUpdate( is ); - } - - this.repo.updateView(); - this.setScrollBar(); - } - - private void setScrollBar() - { - this.getScrollBar().setTop( 18 ).setLeft( 175 ).setHeight( this.rows * 18 - 2 ); - this.getScrollBar().setRange( 0, ( this.repo.size() + this.perRow - 1 ) / this.perRow - this.rows, Math.max( 1, this.rows / 6 ) ); - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - if( btn == this.craftingStatusBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( GuiBridge.GUI_CRAFTING_STATUS ) ); - } - - if( btn instanceof GuiImgButton ) - { - final boolean backwards = Mouse.isButtonDown( 1 ); - - final GuiImgButton iBtn = (GuiImgButton) btn; - if( iBtn.getSetting() != Settings.ACTIONS ) - { - final Enum cv = iBtn.getCurrentValue(); - final 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( final IOException e ) - { - AELog.debug( e ); - } - } - - iBtn.set( next ); - - if( next.getClass() == SearchBoxMode.class || next.getClass() == TerminalStyle.class ) - { - this.reinitalize(); - } - } - } - } - - private void reinitalize() - { - this.buttonList.clear(); - this.initGui(); - } - - @Override - public void initGui() - { - Keyboard.enableRepeatEvents( true ); - - this.maxRows = this.getMaxRows(); - this.perRow = AEConfig.instance.getConfigManager().getSetting( Settings.TERMINAL_STYLE ) != TerminalStyle.FULL ? 9 : 9 + ( ( this.width - this.standardSize ) / 18 ); - - final boolean hasNEI = IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ); - - final int NEI = hasNEI ? 0 : 0; - int top = hasNEI ? 22 : 0; - - final int magicNumber = 114 + 1; - final int extraSpace = this.height - magicNumber - NEI - top - this.reservedSpace; - - this.rows = (int) Math.floor( extraSpace / 18 ); - if( this.rows > this.maxRows ) - { - top += ( this.rows - this.maxRows ) * 18 / 2; - this.rows = this.maxRows; - } - - if( hasNEI ) - { - this.rows--; - } - - if( this.rows < 3 ) - { - this.rows = 3; - } - - this.getMeSlots().clear(); - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.perRow; x++ ) - { - this.getMeSlots().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 ); - } - else - { - this.xSize = this.standardSize; - } - - super.initGui(); - // full size : 204 - // extra slots : 72 - // slot 18 - - this.ySize = magicNumber + this.rows * 18 + this.reservedSpace; - // this.guiTop = top; - final int unusedSpace = this.height - this.ySize; - this.guiTop = (int) Math.floor( unusedSpace / ( unusedSpace < 0 ? 3.8f : 2.0f ) ); - - int offset = this.guiTop + 8; - - 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 ) - { - this.buttonList.add( this.ViewBox = new GuiImgButton( this.guiLeft - 18, offset, Settings.VIEW_MODE, this.configSrc.getSetting( Settings.VIEW_MODE ) ) ); - offset += 20; - } - - 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 ) ) ); - offset += 20; - - 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.searchField = new MEGuiTextField( this.fontRendererObj, this.guiLeft + Math.max( 80, this.offsetX ), this.guiTop + 4, 90, 12 ); - this.searchField.setEnableBackgroundDrawing( false ); - this.searchField.setMaxStringLength( 25 ); - this.searchField.setTextColor( 0xFFFFFF ); - this.searchField.setVisible( true ); - - 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.craftingStatusBtn.setHideEdge( 13 ); - } - - // Enum setting = AEConfig.INSTANCE.getSetting( "Terminal", SearchBoxMode.class, SearchBoxMode.AUTOSEARCH ); - final Enum setting = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - this.searchField.setFocused( SearchBoxMode.AUTOSEARCH == setting || SearchBoxMode.NEI_AUTOSEARCH == setting ); - - if( this.isSubGui() ) - { - this.searchField.setText( memoryText ); - this.repo.setSearchString( memoryText ); - this.repo.updateView(); - this.setScrollBar(); - } - - craftingGridOffsetX = Integer.MAX_VALUE; - craftingGridOffsetY = Integer.MAX_VALUE; - - for( final Object s : this.inventorySlots.inventorySlots ) - { - if( s instanceof AppEngSlot ) - { - if( ( (Slot) s ).xDisplayPosition < 197 ) - { - this.repositionSlot( (AppEngSlot) s ); - } - } - - if( s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix ) - { - final Slot g = (Slot) s; - if( g.xDisplayPosition > 0 && g.yDisplayPosition > 0 ) - { - craftingGridOffsetX = Math.min( craftingGridOffsetX, g.xDisplayPosition ); - craftingGridOffsetY = Math.min( craftingGridOffsetY, g.yDisplayPosition ); - } - } - } - - craftingGridOffsetX -= 25; - craftingGridOffsetY -= 6; - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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 - protected void mouseClicked( final int xCoord, final int yCoord, final int btn ) - { - final Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - - if( searchMode != SearchBoxMode.AUTOSEARCH && searchMode != SearchBoxMode.NEI_AUTOSEARCH ) - { - this.searchField.mouseClicked( xCoord, yCoord, btn ); - } - - if( btn == 1 && this.searchField.isMouseIn( xCoord, yCoord ) ) - { - this.searchField.setText( "" ); - this.repo.setSearchString( "" ); - this.repo.updateView(); - this.setScrollBar(); - } - - super.mouseClicked( xCoord, yCoord, btn ); - } - - @Override - public void onGuiClosed() - { - super.onGuiClosed(); - Keyboard.enableRepeatEvents( false ); - memoryText = this.searchField.getText(); - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - - this.bindTexture( this.getBackground() ); - final int x_width = 197; - 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.getCellViewSlot( i ).getStack() ) - { - update = true; - this.myCurrentViewCells[i] = this.monitorableContainer.getCellViewSlot( 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( final AppEngSlot s ) - { - s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( key ) ) - { - if( character == ' ' && this.searchField.getText().isEmpty() ) - { - return; - } - - if( this.searchField.textboxKeyTyped( character, key ) ) - { - this.repo.setSearchString( this.searchField.getText() ); - this.repo.updateView(); - this.setScrollBar(); - } - else - { - super.keyTyped( character, key ); - } - } - } - - @Override - public void updateScreen() - { - this.repo.setPower( this.monitorableContainer.isPowered() ); - super.updateScreen(); - } - - @Override - public Enum getSortBy() - { - return this.configSrc.getSetting( Settings.SORT_BY ); - } - - @Override - public Enum getSortDir() - { - return this.configSrc.getSetting( Settings.SORT_DIRECTION ); - } - - @Override - public Enum getSortDisplay() - { - return this.configSrc.getSetting( Settings.VIEW_MODE ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.SortByBox != null ) - { - this.SortByBox.set( this.configSrc.getSetting( Settings.SORT_BY ) ); - } - - if( this.SortDirBox != null ) - { - this.SortDirBox.set( this.configSrc.getSetting( Settings.SORT_DIRECTION ) ); - } - - if( this.ViewBox != null ) - { - this.ViewBox.set( this.configSrc.getSetting( Settings.VIEW_MODE ) ); - } - - this.repo.updateView(); - } - - int getReservedSpace() - { - return this.reservedSpace; - } - - void setReservedSpace( final int reservedSpace ) - { - this.reservedSpace = reservedSpace; - } - - public boolean isCustomSortOrder() - { - return this.customSortOrder; - } - - void setCustomSortOrder( final boolean customSortOrder ) - { - this.customSortOrder = customSortOrder; - } - - public int getStandardSize() - { - return this.standardSize; - } - - void setStandardSize( final int standardSize ) - { - this.standardSize = standardSize; - } +public class GuiMEMonitorable + extends AEBaseMEGui implements ISortSource, IConfigManagerHost { + public static int craftingGridOffsetX; + public static int craftingGridOffsetY; + + private static String memoryText = ""; + private final ItemRepo repo; + private final int offsetX = 9; + private final int lowerTextureOffset = 0; + private final IConfigManager configSrc; + private final boolean viewCell; + private final ItemStack[] myCurrentViewCells = new ItemStack[5]; + private final ContainerMEMonitorable monitorableContainer; + private GuiTabButton craftingStatusBtn; + private MEGuiTextField searchField; + private GuiText myName; + private int perRow = 9; + private int reservedSpace = 0; + private boolean customSortOrder = true; + private int rows = 0; + private int maxRows = Integer.MAX_VALUE; + private int standardSize; + private GuiImgButton ViewBox; + private GuiImgButton SortByBox; + private GuiImgButton SortDirBox; + private GuiImgButton searchBoxSettings; + private GuiImgButton terminalStyleBox; + + public GuiMEMonitorable( + final InventoryPlayer inventoryPlayer, final ITerminalHost te + ) { + this(inventoryPlayer, te, new ContainerMEMonitorable(inventoryPlayer, te)); + } + + public GuiMEMonitorable( + final InventoryPlayer inventoryPlayer, + final ITerminalHost te, + final ContainerMEMonitorable c + ) { + super(c); + + final GuiScrollbar scrollbar = new GuiScrollbar(); + this.setScrollBar(scrollbar); + this.repo = new ItemRepo(scrollbar, this); + + this.xSize = 185; + this.ySize = 204; + + if (te instanceof IViewCellStorage) { + this.xSize += 33; + } + + this.standardSize = this.xSize; + + this.configSrc = ((IConfigurableObject) this.inventorySlots).getConfigManager(); + (this.monitorableContainer = (ContainerMEMonitorable) this.inventorySlots) + .setGui(this); + + this.viewCell = te instanceof IViewCellStorage; + + if (te instanceof TileSecurity) { + this.myName = GuiText.Security; + } else if (te instanceof WirelessTerminalGuiObject) { + this.myName = GuiText.WirelessTerminal; + } else if (te instanceof IPortableCell) { + this.myName = GuiText.PortableCell; + } else if (te instanceof IMEChest) { + this.myName = GuiText.Chest; + } else if (te instanceof AbstractPartTerminal) { + this.myName = GuiText.Terminal; + } else if (te instanceof TileTerminal) { + this.myName = GuiText.Terminal; + } + } + + public void postUpdate(final List list) { + for (final IAEItemStack is : list) { + this.repo.postUpdate(is); + } + + this.repo.updateView(); + this.setScrollBar(); + } + + private void setScrollBar() { + this.getScrollBar().setTop(18).setLeft(175).setHeight(this.rows * 18 - 2); + this.getScrollBar().setRange( + 0, + (this.repo.size() + this.perRow - 1) / this.perRow - this.rows, + Math.max(1, this.rows / 6) + ); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + if (btn == this.craftingStatusBtn) { + NetworkHandler.instance.sendToServer( + new PacketSwitchGuis(GuiBridge.GUI_CRAFTING_STATUS) + ); + } + + if (btn instanceof GuiImgButton) { + final boolean backwards = Mouse.isButtonDown(1); + + final GuiImgButton iBtn = (GuiImgButton) btn; + if (iBtn.getSetting() != Settings.ACTIONS) { + final Enum cv = iBtn.getCurrentValue(); + final 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 (final IOException e) { + AELog.debug(e); + } + } + + iBtn.set(next); + + if (next.getClass() == SearchBoxMode.class + || next.getClass() == TerminalStyle.class) { + this.reinitalize(); + } + } + } + } + + private void reinitalize() { + this.buttonList.clear(); + this.initGui(); + } + + @Override + public void initGui() { + Keyboard.enableRepeatEvents(true); + + this.maxRows = this.getMaxRows(); + this.perRow + = AEConfig.instance.getConfigManager().getSetting(Settings.TERMINAL_STYLE) + != TerminalStyle.FULL + ? 9 + : 9 + ((this.width - this.standardSize) / 18); + + final boolean hasNEI + = IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI); + + final int NEI = hasNEI ? 0 : 0; + int top = hasNEI ? 22 : 0; + + final int magicNumber = 114 + 1; + final int extraSpace = this.height - magicNumber - NEI - top - this.reservedSpace; + + this.rows = (int) Math.floor(extraSpace / 18); + if (this.rows > this.maxRows) { + top += (this.rows - this.maxRows) * 18 / 2; + this.rows = this.maxRows; + } + + if (hasNEI) { + this.rows--; + } + + if (this.rows < 3) { + this.rows = 3; + } + + this.getMeSlots().clear(); + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.perRow; x++) { + this.getMeSlots().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); + } else { + this.xSize = this.standardSize; + } + + super.initGui(); + // full size : 204 + // extra slots : 72 + // slot 18 + + this.ySize = magicNumber + this.rows * 18 + this.reservedSpace; + // this.guiTop = top; + final int unusedSpace = this.height - this.ySize; + this.guiTop = (int) Math.floor(unusedSpace / (unusedSpace < 0 ? 3.8f : 2.0f)); + + int offset = this.guiTop + 8; + + 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) { + this.buttonList.add( + this.ViewBox = new GuiImgButton( + this.guiLeft - 18, + offset, + Settings.VIEW_MODE, + this.configSrc.getSetting(Settings.VIEW_MODE) + ) + ); + offset += 20; + } + + 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) + ) + ); + offset += 20; + + 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.searchField = new MEGuiTextField( + this.fontRendererObj, + this.guiLeft + Math.max(80, this.offsetX), + this.guiTop + 4, + 90, + 12 + ); + this.searchField.setEnableBackgroundDrawing(false); + this.searchField.setMaxStringLength(25); + this.searchField.setTextColor(0xFFFFFF); + this.searchField.setVisible(true); + + 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.craftingStatusBtn.setHideEdge(13); + } + + // Enum setting = AEConfig.INSTANCE.getSetting( "Terminal", SearchBoxMode.class, + // SearchBoxMode.AUTOSEARCH ); + final Enum setting = AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + this.searchField.setFocused( + SearchBoxMode.AUTOSEARCH == setting || SearchBoxMode.NEI_AUTOSEARCH == setting + ); + + if (this.isSubGui()) { + this.searchField.setText(memoryText); + this.repo.setSearchString(memoryText); + this.repo.updateView(); + this.setScrollBar(); + } + + craftingGridOffsetX = Integer.MAX_VALUE; + craftingGridOffsetY = Integer.MAX_VALUE; + + for (final Object s : this.inventorySlots.inventorySlots) { + if (s instanceof AppEngSlot) { + if (((Slot) s).xDisplayPosition < 197) { + this.repositionSlot((AppEngSlot) s); + } + } + + if (s instanceof SlotCraftingMatrix || s instanceof SlotFakeCraftingMatrix) { + final Slot g = (Slot) s; + if (g.xDisplayPosition > 0 && g.yDisplayPosition > 0) { + craftingGridOffsetX + = Math.min(craftingGridOffsetX, g.xDisplayPosition); + craftingGridOffsetY + = Math.min(craftingGridOffsetY, g.yDisplayPosition); + } + } + } + + craftingGridOffsetX -= 25; + craftingGridOffsetY -= 6; + } + + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + protected void mouseClicked(final int xCoord, final int yCoord, final int btn) { + final Enum searchMode + = AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + + if (searchMode != SearchBoxMode.AUTOSEARCH + && searchMode != SearchBoxMode.NEI_AUTOSEARCH) { + this.searchField.mouseClicked(xCoord, yCoord, btn); + } + + if (btn == 1 && this.searchField.isMouseIn(xCoord, yCoord)) { + this.searchField.setText(""); + this.repo.setSearchString(""); + this.repo.updateView(); + this.setScrollBar(); + } + + super.mouseClicked(xCoord, yCoord, btn); + } + + @Override + public void onGuiClosed() { + super.onGuiClosed(); + Keyboard.enableRepeatEvents(false); + memoryText = this.searchField.getText(); + } + + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture(this.getBackground()); + final int x_width = 197; + 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.getCellViewSlot(i).getStack()) { + update = true; + this.myCurrentViewCells[i] + = this.monitorableContainer.getCellViewSlot(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(final AppEngSlot s) { + s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; + } + + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(key)) { + if (character == ' ' && this.searchField.getText().isEmpty()) { + return; + } + + if (this.searchField.textboxKeyTyped(character, key)) { + this.repo.setSearchString(this.searchField.getText()); + this.repo.updateView(); + this.setScrollBar(); + } else { + super.keyTyped(character, key); + } + } + } + + @Override + public void updateScreen() { + this.repo.setPower(this.monitorableContainer.isPowered()); + super.updateScreen(); + } + + @Override + public Enum getSortBy() { + return this.configSrc.getSetting(Settings.SORT_BY); + } + + @Override + public Enum getSortDir() { + return this.configSrc.getSetting(Settings.SORT_DIRECTION); + } + + @Override + public Enum getSortDisplay() { + return this.configSrc.getSetting(Settings.VIEW_MODE); + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + if (this.SortByBox != null) { + this.SortByBox.set(this.configSrc.getSetting(Settings.SORT_BY)); + } + + if (this.SortDirBox != null) { + this.SortDirBox.set(this.configSrc.getSetting(Settings.SORT_DIRECTION)); + } + + if (this.ViewBox != null) { + this.ViewBox.set(this.configSrc.getSetting(Settings.VIEW_MODE)); + } + + this.repo.updateView(); + } + + int getReservedSpace() { + return this.reservedSpace; + } + + void setReservedSpace(final int reservedSpace) { + this.reservedSpace = reservedSpace; + } + + public boolean isCustomSortOrder() { + return this.customSortOrder; + } + + void setCustomSortOrder(final boolean customSortOrder) { + this.customSortOrder = customSortOrder; + } + + public int getStandardSize() { + return this.standardSize; + } + + void setStandardSize(final int standardSize) { + this.standardSize = standardSize; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java index def2d151..9fc4914f 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java +++ b/src/main/java/appeng/client/gui/implementations/GuiMEPortableCell.java @@ -18,28 +18,23 @@ package appeng.client.gui.implementations; - import appeng.api.implementations.guiobjects.IPortableCell; import appeng.container.implementations.ContainerMEPortableCell; import net.minecraft.entity.player.InventoryPlayer; +public class GuiMEPortableCell extends GuiMEMonitorable { + public GuiMEPortableCell( + final InventoryPlayer inventoryPlayer, final IPortableCell te + ) { + super(inventoryPlayer, te, new ContainerMEPortableCell(inventoryPlayer, te)); + } -public class GuiMEPortableCell extends GuiMEMonitorable -{ + int defaultGetMaxRows() { + return super.getMaxRows(); + } - public GuiMEPortableCell( final InventoryPlayer inventoryPlayer, final IPortableCell te ) - { - super( inventoryPlayer, te, new ContainerMEPortableCell( inventoryPlayer, te ) ); - } - - int defaultGetMaxRows() - { - return super.getMaxRows(); - } - - @Override - int getMaxRows() - { - return 3; - } + @Override + int getMaxRows() { + return 3; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java index e1770fd9..a3ac8697 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java +++ b/src/main/java/appeng/client/gui/implementations/GuiNetworkStatus.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; +import java.util.List; import appeng.api.config.Settings; import appeng.api.config.SortDir; @@ -43,280 +44,289 @@ import net.minecraft.item.ItemStack; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.util.List; +public class GuiNetworkStatus extends AEBaseGui implements ISortSource { + private final ItemRepo repo; + private final int rows = 4; + private GuiImgButton units; + private int tooltip = -1; - -public class GuiNetworkStatus extends AEBaseGui implements ISortSource -{ - - private final ItemRepo repo; - private final int rows = 4; - private GuiImgButton units; - private int tooltip = -1; - - public GuiNetworkStatus( final InventoryPlayer inventoryPlayer, final INetworkTool te ) { + public GuiNetworkStatus( + final InventoryPlayer inventoryPlayer, final INetworkTool te + ) { this(inventoryPlayer, te.getGridHost()); } - public GuiNetworkStatus( final InventoryPlayer inventoryPlayer, final IGridHost te ) - { - super( new ContainerNetworkStatus( inventoryPlayer, te ) ); - final GuiScrollbar scrollbar = new GuiScrollbar(); + public GuiNetworkStatus(final InventoryPlayer inventoryPlayer, final IGridHost te) { + super(new ContainerNetworkStatus(inventoryPlayer, te)); + final GuiScrollbar scrollbar = new GuiScrollbar(); - this.setScrollBar( scrollbar ); - this.repo = new ItemRepo( scrollbar, this ); - this.ySize = 153; - this.xSize = 195; - this.repo.setRowSize( 5 ); - } + this.setScrollBar(scrollbar); + this.repo = new ItemRepo(scrollbar, this); + this.ySize = 153; + this.xSize = 195; + this.repo.setRowSize(5); + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - final boolean backwards = Mouse.isButtonDown( 1 ); + final boolean backwards = Mouse.isButtonDown(1); - if( btn == this.units ) - { - AEConfig.instance.nextPowerUnit( backwards ); - this.units.set( AEConfig.instance.selectedPowerUnit() ); - } - } + if (btn == this.units) { + AEConfig.instance.nextPowerUnit(backwards); + this.units.set(AEConfig.instance.selectedPowerUnit()); + } + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void initGui() { + super.initGui(); - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit() ); - this.buttonList.add( this.units ); - } + this.units = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 8, + Settings.POWER_UNITS, + AEConfig.instance.selectedPowerUnit() + ); + this.buttonList.add(this.units); + } - @Override - public void drawScreen( final int mouseX, final int mouseY, final float btn ) - { + @Override + public void drawScreen(final int mouseX, final int mouseY, final float btn) { + final int gx = (this.width - this.xSize) / 2; + final int gy = (this.height - this.ySize) / 2; - final int gx = ( this.width - this.xSize ) / 2; - final int gy = ( this.height - this.ySize ) / 2; + this.tooltip = -1; - this.tooltip = -1; + int y = 0; + int x = 0; + for (int z = 0; z <= 4 * 5; z++) { + final int minX = gx + 14 + x * 31; + final int minY = gy + 41 + y * 18; - int y = 0; - int x = 0; - for( int z = 0; z <= 4 * 5; z++ ) - { - final int minX = gx + 14 + x * 31; - final int minY = gy + 41 + y * 18; + if (minX < mouseX && minX + 28 > mouseX) { + if (minY < mouseY && minY + 20 > mouseY) { + this.tooltip = z; + break; + } + } - if( minX < mouseX && minX + 28 > mouseX ) - { - if( minY < mouseY && minY + 20 > mouseY ) - { - this.tooltip = z; - break; - } - } + x++; - x++; + if (x > 4) { + y++; + x = 0; + } + } - if( x > 4 ) - { - y++; - x = 0; - } - } + super.drawScreen(mouseX, mouseY, btn); + } - super.drawScreen( mouseX, mouseY, btn ); - } + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + final ContainerNetworkStatus ns = (ContainerNetworkStatus) this.inventorySlots; - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - final ContainerNetworkStatus ns = (ContainerNetworkStatus) this.inventorySlots; + this.fontRendererObj.drawString(GuiText.NetworkDetails.getLocal(), 8, 6, 4210752); - this.fontRendererObj.drawString( GuiText.NetworkDetails.getLocal(), 8, 6, 4210752 ); + this.fontRendererObj.drawString( + GuiText.StoredPower.getLocal() + ": " + + Platform.formatPowerLong(ns.getCurrentPower(), false), + 13, + 16, + 4210752 + ); + this.fontRendererObj.drawString( + GuiText.MaxPower.getLocal() + ": " + + Platform.formatPowerLong(ns.getMaxPower(), false), + 13, + 26, + 4210752 + ); - this.fontRendererObj.drawString( GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong( ns.getCurrentPower(), false ), 13, 16, 4210752 ); - this.fontRendererObj.drawString( GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong( ns.getMaxPower(), false ), 13, 26, 4210752 ); + this.fontRendererObj.drawString( + GuiText.PowerInputRate.getLocal() + ": " + + Platform.formatPowerLong(ns.getAverageAddition(), true), + 13, + 143 - 10, + 4210752 + ); + this.fontRendererObj.drawString( + GuiText.PowerUsageRate.getLocal() + ": " + + Platform.formatPowerLong(ns.getPowerUsage(), true), + 13, + 143 - 20, + 4210752 + ); - this.fontRendererObj.drawString( GuiText.PowerInputRate.getLocal() + ": " + Platform.formatPowerLong( ns.getAverageAddition(), true ), 13, 143 - 10, 4210752 ); - this.fontRendererObj.drawString( GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong( ns.getPowerUsage(), true ), 13, 143 - 20, 4210752 ); + final int sectionLength = 30; - final int sectionLength = 30; + int x = 0; + int y = 0; + final int xo = 12; + final int yo = 42; + final int viewStart = 0; // myScrollBar.getCurrentScroll() * 5; + final int viewEnd = viewStart + 5 * 4; - int x = 0; - int y = 0; - final int xo = 12; - final int yo = 42; - final int viewStart = 0;// myScrollBar.getCurrentScroll() * 5; - final int viewEnd = viewStart + 5 * 4; + String toolTip = ""; + int toolPosX = 0; + int toolPosY = 0; - String toolTip = ""; - int toolPosX = 0; - int toolPosY = 0; + for (int z = viewStart; z < Math.min(viewEnd, this.repo.size()); z++) { + final IAEItemStack refStack = this.repo.getReferenceItem(z); + if (refStack != null) { + GL11.glPushMatrix(); + GL11.glScaled(0.5, 0.5, 0.5); - for( int z = viewStart; z < Math.min( viewEnd, this.repo.size() ); z++ ) - { - final IAEItemStack refStack = this.repo.getReferenceItem( z ); - if( refStack != null ) - { - GL11.glPushMatrix(); - GL11.glScaled( 0.5, 0.5, 0.5 ); + String str = Long.toString(refStack.getStackSize()); + if (refStack.getStackSize() >= 10000) { + str = Long.toString(refStack.getStackSize() / 1000) + 'k'; + } - String str = Long.toString( refStack.getStackSize() ); - if( refStack.getStackSize() >= 10000 ) - { - str = Long.toString( refStack.getStackSize() / 1000 ) + 'k'; - } + final 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 + ); - final 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 ); + GL11.glPopMatrix(); + final int posX = x * sectionLength + xo + sectionLength - 18; + final int posY = y * 18 + yo; - GL11.glPopMatrix(); - final int posX = x * sectionLength + xo + sectionLength - 18; - final int posY = y * 18 + yo; + if (this.tooltip == z - viewStart) { + toolTip = Platform.getItemDisplayName(this.repo.getItem(z)); - if( this.tooltip == z - viewStart ) - { - toolTip = Platform.getItemDisplayName( this.repo.getItem( z ) ); + toolTip + += ('\n' + GuiText.Installed.getLocal() + ": " + + (refStack.getStackSize())); + if (refStack.getCountRequestable() > 0) { + toolTip + += ('\n' + GuiText.EnergyDrain.getLocal() + ": " + + Platform.formatPowerLong( + refStack.getCountRequestable(), true + )); + } - toolTip += ( '\n' + GuiText.Installed.getLocal() + ": " + ( refStack.getStackSize() ) ); - if( refStack.getCountRequestable() > 0 ) - { - toolTip += ( '\n' + GuiText.EnergyDrain.getLocal() + ": " + Platform.formatPowerLong( refStack.getCountRequestable(), true ) ); - } + toolPosX = x * sectionLength + xo + sectionLength - 8; + toolPosY = y * 18 + yo; + } - toolPosX = x * sectionLength + xo + sectionLength - 8; - toolPosY = y * 18 + yo; - } + this.drawItem(posX, posY, this.repo.getItem(z)); - this.drawItem( posX, posY, this.repo.getItem( z ) ); + x++; - x++; + if (x > 4) { + y++; + x = 0; + } + } + } - if( x > 4 ) - { - y++; - x = 0; - } - } - } + if (this.tooltip >= 0 && toolTip.length() > 0) { + this.drawTooltip(toolPosX, toolPosY + 10, 0, toolTip); + } + } - if( this.tooltip >= 0 && toolTip.length() > 0 ) - { - this.drawTooltip( toolPosX, toolPosY + 10, 0, toolTip ); - } - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/networkstatus.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/networkstatus.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + public void postUpdate(final List list) { + this.repo.clear(); - public void postUpdate( final List list ) - { - this.repo.clear(); + for (final IAEItemStack is : list) { + this.repo.postUpdate(is); + } - for( final IAEItemStack is : list ) - { - this.repo.postUpdate( is ); - } + this.repo.updateView(); + this.setScrollBar(); + } - this.repo.updateView(); - this.setScrollBar(); - } + private void setScrollBar() { + final int size = this.repo.size(); + this.getScrollBar().setTop(39).setLeft(175).setHeight(78); + this.getScrollBar().setRange(0, (size + 4) / 5 - this.rows, 1); + } - private void setScrollBar() - { - final int size = this.repo.size(); - this.getScrollBar().setTop( 39 ).setLeft( 175 ).setHeight( 78 ); - this.getScrollBar().setRange( 0, ( size + 4 ) / 5 - this.rows, 1 ); - } + // @Override - NEI + public List handleItemTooltip( + final ItemStack stack, + final int mouseX, + final int mouseY, + final List currentToolTip + ) { + if (stack != null) { + final Slot s = this.getSlot(mouseX, mouseY); + if (s instanceof SlotME) { + IAEItemStack myStack = null; - // @Override - NEI - public List handleItemTooltip( final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip ) - { - if( stack != null ) - { - final Slot s = this.getSlot( mouseX, mouseY ); - if( s instanceof SlotME ) - { - IAEItemStack myStack = null; + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) {} - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } + if (myStack != null) { + while (currentToolTip.size() > 1) { + currentToolTip.remove(1); + } + } + } + } + return currentToolTip; + } - if( myStack != null ) - { - while( currentToolTip.size() > 1 ) - { - currentToolTip.remove( 1 ); - } - } - } - } - return currentToolTip; - } + // Vanilla version... + protected void drawItemStackTooltip(final ItemStack stack, final int x, final int y) { + final Slot s = this.getSlot(x, y); + if (s instanceof SlotME && stack != null) { + IAEItemStack myStack = null; - // Vanilla version... - protected void drawItemStackTooltip( final ItemStack stack, final int x, final int y ) - { - final Slot s = this.getSlot( x, y ); - if( s instanceof SlotME && stack != null ) - { - IAEItemStack myStack = null; + try { + final SlotME theSlotField = (SlotME) s; + myStack = theSlotField.getAEStack(); + } catch (final Throwable ignore) {} - try - { - final SlotME theSlotField = (SlotME) s; - myStack = theSlotField.getAEStack(); - } - catch( final Throwable ignore ) - { - } + if (myStack != null) { + final List currentToolTip = stack.getTooltip( + this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips + ); - if( myStack != null ) - { - final List currentToolTip = stack.getTooltip( this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips ); + while (currentToolTip.size() > 1) { + currentToolTip.remove(1); + } - while( currentToolTip.size() > 1 ) - { - currentToolTip.remove( 1 ); - } + currentToolTip.add( + GuiText.Installed.getLocal() + ": " + (myStack.getStackSize()) + ); + currentToolTip.add( + GuiText.EnergyDrain.getLocal() + ": " + + Platform.formatPowerLong(myStack.getCountRequestable(), true) + ); - 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")); + } + } + // super.drawItemStackTooltip( stack, x, y ); + } - this.drawTooltip( x, y, 0, join( currentToolTip, "\n" ) ); - } - } - // super.drawItemStackTooltip( stack, x, y ); - } + @Override + public Enum getSortBy() { + return SortOrder.NAME; + } - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } + @Override + public Enum getSortDir() { + return SortDir.ASCENDING; + } - @Override - public Enum getSortDir() - { - return SortDir.ASCENDING; - } - - @Override - public Enum getSortDisplay() - { - return ViewItems.ALL; - } + @Override + public Enum getSortDisplay() { + return ViewItems.ALL; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java b/src/main/java/appeng/client/gui/implementations/GuiNetworkTool.java index ec505b82..89cb53c1 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 appeng.api.implementations.guiobjects.INetworkTool; import appeng.client.gui.AEBaseGui; @@ -30,64 +31,66 @@ import appeng.core.sync.packets.PacketValueConfig; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; -import java.io.IOException; +public class GuiNetworkTool extends AEBaseGui { + private GuiToggleButton tFacades; + public GuiNetworkTool(final InventoryPlayer inventoryPlayer, final INetworkTool te) { + super(new ContainerNetworkTool(inventoryPlayer, te)); + this.ySize = 166; + } -public class GuiNetworkTool extends AEBaseGui -{ + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - private GuiToggleButton tFacades; + try { + if (btn == this.tFacades) { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("NetworkTool", "Toggle") + ); + } + } catch (final IOException e) { + AELog.debug(e); + } + } - public GuiNetworkTool( final InventoryPlayer inventoryPlayer, final INetworkTool te ) - { - super( new ContainerNetworkTool( inventoryPlayer, te ) ); - this.ySize = 166; - } + @Override + public void initGui() { + super.initGui(); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + this.tFacades = new GuiToggleButton( + this.guiLeft - 18, + this.guiTop + 8, + 23, + 22, + GuiText.TransparentFacades.getLocal(), + GuiText.TransparentFacadesHint.getLocal() + ); - try - { - if( btn == this.tFacades ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "NetworkTool", "Toggle" ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + this.buttonList.add(this.tFacades); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (this.tFacades != null) { + this.tFacades.setState( + ((ContainerNetworkTool) this.inventorySlots).isFacadeMode() + ); + } - this.tFacades = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 8, 23, 22, GuiText.TransparentFacades.getLocal(), GuiText.TransparentFacadesHint.getLocal() ); + this.fontRendererObj.drawString( + this.getGuiDisplayName(GuiText.NetworkTool.getLocal()), 8, 6, 4210752 + ); + this.fontRendererObj.drawString( + GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 + ); + } - this.buttonList.add( this.tFacades ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( this.tFacades != null ) - { - this.tFacades.setState( ( (ContainerNetworkTool) this.inventorySlots ).isFacadeMode() ); - } - - 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/toolbox.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 d5afd53b..a03ded6e 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 appeng.api.config.ActionItems; import appeng.api.config.ItemSubstitution; @@ -35,144 +36,166 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; -import java.io.IOException; +public class GuiPatternTerm extends GuiMEMonitorable { + private static final String SUBSITUTION_DISABLE = "0"; + private static final String SUBSITUTION_ENABLE = "1"; + private static final String CRAFTMODE_CRFTING = "1"; + private static final String CRAFTMODE_PROCESSING = "0"; -public class GuiPatternTerm extends GuiMEMonitorable -{ + private final ContainerPatternTerm container; - private static final String SUBSITUTION_DISABLE = "0"; - private static final String SUBSITUTION_ENABLE = "1"; + private GuiTabButton tabCraftButton; + private GuiTabButton tabProcessButton; + private GuiImgButton substitutionsEnabledBtn; + private GuiImgButton substitutionsDisabledBtn; + private GuiImgButton encodeBtn; + private GuiImgButton clearBtn; - private static final String CRAFTMODE_CRFTING = "1"; - private static final String CRAFTMODE_PROCESSING = "0"; + public GuiPatternTerm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerPatternTerm(inventoryPlayer, te)); + this.container = (ContainerPatternTerm) this.inventorySlots; + this.setReservedSpace(81); + } - private final ContainerPatternTerm container; + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - private GuiTabButton tabCraftButton; - private GuiTabButton tabProcessButton; - private GuiImgButton substitutionsEnabledBtn; - private GuiImgButton substitutionsDisabledBtn; - private GuiImgButton encodeBtn; - private GuiImgButton clearBtn; + try { + if (this.tabCraftButton == btn || this.tabProcessButton == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminal.CraftMode", + this.tabProcessButton == btn ? CRAFTMODE_CRFTING + : CRAFTMODE_PROCESSING + )); + } - public GuiPatternTerm( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerPatternTerm( inventoryPlayer, te ) ); - this.container = (ContainerPatternTerm) this.inventorySlots; - this.setReservedSpace( 81 ); - } + if (this.encodeBtn == btn) { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("PatternTerminal.Encode", "1") + ); + } - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (this.clearBtn == btn) { + NetworkHandler.instance.sendToServer( + new PacketValueConfig("PatternTerminal.Clear", "1") + ); + } - try - { + if (this.substitutionsEnabledBtn == btn + || this.substitutionsDisabledBtn == btn) { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "PatternTerminal.Substitute", + this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE + : SUBSITUTION_ENABLE + )); + } + } catch (final IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - if( this.tabCraftButton == btn || this.tabProcessButton == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", this.tabProcessButton == btn ? CRAFTMODE_CRFTING : CRAFTMODE_PROCESSING ) ); - } + @Override + public void initGui() { + super.initGui(); + 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.tabCraftButton); - if( this.encodeBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Encode", "1" ) ); - } + this.tabProcessButton = new GuiTabButton( + this.guiLeft + 173, + this.guiTop + this.ySize - 177, + new ItemStack(Blocks.furnace), + GuiText.ProcessingPattern.getLocal(), + itemRender + ); + this.buttonList.add(this.tabProcessButton); - if( this.clearBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Clear", "1" ) ); - } + this.substitutionsEnabledBtn = new GuiImgButton( + this.guiLeft + 84, + this.guiTop + this.ySize - 163, + Settings.ACTIONS, + ItemSubstitution.ENABLED + ); + this.substitutionsEnabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsEnabledBtn); - if( this.substitutionsEnabledBtn == btn || this.substitutionsDisabledBtn == btn ) - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PatternTerminal.Substitute", this.substitutionsEnabledBtn == btn ? SUBSITUTION_DISABLE : SUBSITUTION_ENABLE ) ); - } - } - catch( final IOException e ) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + this.substitutionsDisabledBtn = new GuiImgButton( + this.guiLeft + 84, + this.guiTop + this.ySize - 163, + Settings.ACTIONS, + ItemSubstitution.DISABLED + ); + this.substitutionsDisabledBtn.setHalfSize(true); + this.buttonList.add(this.substitutionsDisabledBtn); - @Override - public void initGui() - { - super.initGui(); - 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.tabCraftButton ); + this.clearBtn = new GuiImgButton( + this.guiLeft + 74, + this.guiTop + this.ySize - 163, + Settings.ACTIONS, + ActionItems.CLOSE + ); + this.clearBtn.setHalfSize(true); + this.buttonList.add(this.clearBtn); - this.tabProcessButton = new GuiTabButton( this.guiLeft + 173, this.guiTop + this.ySize - 177, new ItemStack( Blocks.furnace ), GuiText.ProcessingPattern.getLocal(), itemRender ); - this.buttonList.add( this.tabProcessButton ); + this.encodeBtn = new GuiImgButton( + this.guiLeft + 147, + this.guiTop + this.ySize - 142, + Settings.ACTIONS, + ActionItems.ENCODE + ); + this.buttonList.add(this.encodeBtn); + } - this.substitutionsEnabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.ENABLED ); - this.substitutionsEnabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsEnabledBtn ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + if (!this.container.isCraftingMode()) { + this.tabCraftButton.visible = false; + this.tabProcessButton.visible = true; + } else { + this.tabCraftButton.visible = true; + this.tabProcessButton.visible = false; + } - this.substitutionsDisabledBtn = new GuiImgButton( this.guiLeft + 84, this.guiTop + this.ySize - 163, Settings.ACTIONS, ItemSubstitution.DISABLED ); - this.substitutionsDisabledBtn.setHalfSize( true ); - this.buttonList.add( this.substitutionsDisabledBtn ); + if (this.container.substitute) { + this.substitutionsEnabledBtn.visible = true; + this.substitutionsDisabledBtn.visible = false; + } else { + this.substitutionsEnabledBtn.visible = false; + this.substitutionsDisabledBtn.visible = true; + } - this.clearBtn = new GuiImgButton( this.guiLeft + 74, this.guiTop + this.ySize - 163, Settings.ACTIONS, ActionItems.CLOSE ); - this.clearBtn.setHalfSize( true ); - this.buttonList.add( this.clearBtn ); + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRendererObj.drawString( + GuiText.PatternTerminal.getLocal(), + 8, + this.ySize - 96 + 2 - this.getReservedSpace(), + 4210752 + ); + } - this.encodeBtn = new GuiImgButton( this.guiLeft + 147, this.guiTop + this.ySize - 142, Settings.ACTIONS, ActionItems.ENCODE ); - this.buttonList.add( this.encodeBtn ); - } + @Override + protected String getBackground() { + if (this.container.isCraftingMode()) { + return "guis/pattern.png"; + } + return "guis/pattern2.png"; + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - if( !this.container.isCraftingMode() ) - { - this.tabCraftButton.visible = false; - this.tabProcessButton.visible = true; - } - else - { - this.tabCraftButton.visible = true; - this.tabProcessButton.visible = false; - } - - if( this.container.substitute ) - { - this.substitutionsEnabledBtn.visible = true; - this.substitutionsDisabledBtn.visible = false; - } - else - { - this.substitutionsEnabledBtn.visible = false; - this.substitutionsDisabledBtn.visible = true; - } - - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.PatternTerminal.getLocal(), 8, this.ySize - 96 + 2 - this.getReservedSpace(), 4210752 ); - } - - @Override - protected String getBackground() - { - if( this.container.isCraftingMode() ) - { - return "guis/pattern.png"; - } - return "guis/pattern2.png"; - } - - @Override - protected void repositionSlot( final AppEngSlot s ) - { - if( s.isPlayerSide() ) - { - s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; - } - else - { - s.yDisplayPosition = s.getY() + this.ySize - 78 - 3; - } - } + @Override + protected void repositionSlot(final AppEngSlot s) { + if (s.isPlayerSide()) { + s.yDisplayPosition = s.getY() + this.ySize - 78 - 5; + } else { + s.yDisplayPosition = s.getY() + 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 1e5dd06e..bf467b9f 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 appeng.api.AEApi; import appeng.api.definitions.IBlocks; @@ -46,247 +47,252 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; -import java.io.IOException; +public class GuiPriority extends AEBaseGui { + private GuiNumberBox priority; + private GuiTabButton originalGuiBtn; + private GuiButton plus1; + private GuiButton plus10; + private GuiButton plus100; + private GuiButton plus1000; + private GuiButton minus1; + private GuiButton minus10; + private GuiButton minus100; + private GuiButton minus1000; -public class GuiPriority extends AEBaseGui -{ + private GuiBridge OriginalGui; - private GuiNumberBox priority; - private GuiTabButton originalGuiBtn; + public GuiPriority(final InventoryPlayer inventoryPlayer, final IPriorityHost te) { + super(new ContainerPriority(inventoryPlayer, te)); + } - private GuiButton plus1; - private GuiButton plus10; - private GuiButton plus100; - private GuiButton plus1000; - private GuiButton minus1; - private GuiButton minus10; - private GuiButton minus100; - private GuiButton minus1000; + @Override + public void initGui() { + super.initGui(); - private GuiBridge OriginalGui; + final int a = AEConfig.instance.priorityByStacksAmounts(0); + final int b = AEConfig.instance.priorityByStacksAmounts(1); + final int c = AEConfig.instance.priorityByStacksAmounts(2); + final int d = AEConfig.instance.priorityByStacksAmounts(3); - public GuiPriority( final InventoryPlayer inventoryPlayer, final IPriorityHost te ) - { - super( new ContainerPriority( inventoryPlayer, te ) ); - } + this.buttonList.add( + this.plus1 + = new GuiButton(0, this.guiLeft + 20, this.guiTop + 32, 22, 20, "+" + a) + ); + this.buttonList.add( + this.plus10 + = new GuiButton(0, this.guiLeft + 48, this.guiTop + 32, 28, 20, "+" + b) + ); + this.buttonList.add( + this.plus100 + = new GuiButton(0, this.guiLeft + 82, this.guiTop + 32, 32, 20, "+" + c) + ); + this.buttonList.add( + this.plus1000 + = new GuiButton(0, this.guiLeft + 120, this.guiTop + 32, 38, 20, "+" + d) + ); - @Override - public void initGui() - { - super.initGui(); + this.buttonList.add( + this.minus1 + = new GuiButton(0, this.guiLeft + 20, this.guiTop + 69, 22, 20, "-" + a) + ); + this.buttonList.add( + this.minus10 + = new GuiButton(0, this.guiLeft + 48, this.guiTop + 69, 28, 20, "-" + b) + ); + this.buttonList.add( + this.minus100 + = new GuiButton(0, this.guiLeft + 82, this.guiTop + 69, 32, 20, "-" + c) + ); + this.buttonList.add( + this.minus1000 + = new GuiButton(0, this.guiLeft + 120, this.guiTop + 69, 38, 20, "-" + d) + ); - final int a = AEConfig.instance.priorityByStacksAmounts( 0 ); - final int b = AEConfig.instance.priorityByStacksAmounts( 1 ); - final int c = AEConfig.instance.priorityByStacksAmounts( 2 ); - final int d = AEConfig.instance.priorityByStacksAmounts( 3 ); + ItemStack myIcon = null; + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + final IDefinitions definitions = AEApi.instance().definitions(); + final IParts parts = definitions.parts(); + final IBlocks blocks = definitions.blocks(); - this.buttonList.add( this.plus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 32, 22, 20, "+" + a ) ); - this.buttonList.add( this.plus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 32, 28, 20, "+" + b ) ); - this.buttonList.add( this.plus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 32, 32, 20, "+" + c ) ); - this.buttonList.add( this.plus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 32, 38, 20, "+" + d ) ); + if (target instanceof PartStorageBus) { + for (final ItemStack storageBusStack : + parts.storageBus().maybeStack(1).asSet()) { + myIcon = storageBusStack; + } + this.OriginalGui = GuiBridge.GUI_STORAGEBUS; + } - this.buttonList.add( this.minus1 = new GuiButton( 0, this.guiLeft + 20, this.guiTop + 69, 22, 20, "-" + a ) ); - this.buttonList.add( this.minus10 = new GuiButton( 0, this.guiLeft + 48, this.guiTop + 69, 28, 20, "-" + b ) ); - this.buttonList.add( this.minus100 = new GuiButton( 0, this.guiLeft + 82, this.guiTop + 69, 32, 20, "-" + c ) ); - this.buttonList.add( this.minus1000 = new GuiButton( 0, this.guiLeft + 120, this.guiTop + 69, 38, 20, "-" + d ) ); + if (target instanceof PartFormationPlane) { + for (final ItemStack formationPlaneStack : + parts.formationPlane().maybeStack(1).asSet()) { + myIcon = formationPlaneStack; + } + this.OriginalGui = GuiBridge.GUI_FORMATION_PLANE; + } - ItemStack myIcon = null; - final 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 TileDrive) { + for (final ItemStack driveStack : blocks.drive().maybeStack(1).asSet()) { + myIcon = driveStack; + } - if( target instanceof PartStorageBus ) - { - for( final ItemStack storageBusStack : parts.storageBus().maybeStack( 1 ).asSet() ) - { - myIcon = storageBusStack; - } - this.OriginalGui = GuiBridge.GUI_STORAGEBUS; - } + this.OriginalGui = GuiBridge.GUI_DRIVE; + } - if( target instanceof PartFormationPlane ) - { - for( final ItemStack formationPlaneStack : parts.formationPlane().maybeStack( 1 ).asSet() ) - { - myIcon = formationPlaneStack; - } - this.OriginalGui = GuiBridge.GUI_FORMATION_PLANE; - } + if (target instanceof TileChest) { + for (final ItemStack chestStack : blocks.chest().maybeStack(1).asSet()) { + myIcon = chestStack; + } - if( target instanceof TileDrive ) - { - for( final ItemStack driveStack : blocks.drive().maybeStack( 1 ).asSet() ) - { - myIcon = driveStack; - } + this.OriginalGui = GuiBridge.GUI_CHEST; + } - this.OriginalGui = GuiBridge.GUI_DRIVE; - } + if (target instanceof TileInterface) { + for (final ItemStack interfaceStack : blocks.iface().maybeStack(1).asSet()) { + myIcon = interfaceStack; + } - if( target instanceof TileChest ) - { - for( final ItemStack chestStack : blocks.chest().maybeStack( 1 ).asSet() ) - { - myIcon = chestStack; - } + this.OriginalGui = GuiBridge.GUI_INTERFACE; + } - this.OriginalGui = GuiBridge.GUI_CHEST; - } + if (target instanceof PartInterface) { + for (final ItemStack interfaceStack : parts.iface().maybeStack(1).asSet()) { + myIcon = interfaceStack; + } + this.OriginalGui = GuiBridge.GUI_INTERFACE; + } - if( target instanceof TileInterface ) - { - for( final ItemStack interfaceStack : blocks.iface().maybeStack( 1 ).asSet() ) - { - myIcon = interfaceStack; - } + if (this.OriginalGui != null && myIcon != null) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + myIcon, + myIcon.getDisplayName(), + itemRender + ) + ); + } - this.OriginalGui = GuiBridge.GUI_INTERFACE; - } + this.priority = new GuiNumberBox( + this.fontRendererObj, + this.guiLeft + 62, + this.guiTop + 57, + 59, + this.fontRendererObj.FONT_HEIGHT, + Long.class + ); + this.priority.setEnableBackgroundDrawing(false); + this.priority.setMaxStringLength(16); + this.priority.setTextColor(0xFFFFFF); + this.priority.setVisible(true); + this.priority.setFocused(true); + ((ContainerPriority) this.inventorySlots).setTextField(this.priority); + } - if( target instanceof PartInterface ) - { - for( final ItemStack interfaceStack : parts.iface().maybeStack( 1 ).asSet() ) - { - myIcon = interfaceStack; - } - this.OriginalGui = GuiBridge.GUI_INTERFACE; - } + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString(GuiText.Priority.getLocal(), 8, 6, 4210752); + } - if( this.OriginalGui != null && myIcon != null ) - { - this.buttonList.add( this.originalGuiBtn = new GuiTabButton( this.guiLeft + 154, this.guiTop, myIcon, myIcon.getDisplayName(), itemRender ) ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/priority.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); - this.priority = new GuiNumberBox( this.fontRendererObj, this.guiLeft + 62, this.guiTop + 57, 59, this.fontRendererObj.FONT_HEIGHT, Long.class ); - this.priority.setEnableBackgroundDrawing( false ); - this.priority.setMaxStringLength( 16 ); - this.priority.setTextColor( 0xFFFFFF ); - this.priority.setVisible( true ); - this.priority.setFocused( true ); - ( (ContainerPriority) this.inventorySlots ).setTextField( this.priority ); - } + this.priority.drawTextBox(); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( GuiText.Priority.getLocal(), 8, 6, 4210752 ); - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/priority.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); + if (btn == this.originalGuiBtn) { + NetworkHandler.instance.sendToServer(new PacketSwitchGuis(this.OriginalGui)); + } - this.priority.drawTextBox(); - } + final boolean isPlus = btn == this.plus1 || btn == this.plus10 + || btn == this.plus100 || btn == this.plus1000; + final boolean isMinus = btn == this.minus1 || btn == this.minus10 + || btn == this.minus100 || btn == this.minus1000; - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } - if( btn == this.originalGuiBtn ) - { - NetworkHandler.instance.sendToServer( new PacketSwitchGuis( this.OriginalGui ) ); - } + private void addQty(final int i) { + try { + String out = this.priority.getText(); - final boolean isPlus = btn == this.plus1 || btn == this.plus10 || btn == this.plus100 || btn == this.plus1000; - final boolean isMinus = btn == this.minus1 || btn == this.minus10 || btn == this.minus100 || btn == this.minus1000; + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - if( isPlus || isMinus ) - { - this.addQty( this.getQty( btn ) ); - } - } + if (fixed) { + this.priority.setText(out); + } - private void addQty( final int i ) - { - try - { - String out = this.priority.getText(); + if (out.isEmpty()) { + out = "0"; + } - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + long result = Long.parseLong(out); + result += i; - if( fixed ) - { - this.priority.setText( out ); - } + this.priority.setText(out = Long.toString(result)); - if( out.isEmpty() ) - { - out = "0"; - } + NetworkHandler.instance.sendToServer( + new PacketValueConfig("PriorityHost.Priority", out) + ); + } catch (final NumberFormatException e) { + // nope.. + this.priority.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } - long result = Long.parseLong( out ); - result += i; + @Override + protected void keyTyped(final char character, final int key) { + if (!this.checkHotbarKeys(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(); - this.priority.setText( out = Long.toString( result ) ); + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); - } - catch( final NumberFormatException e ) - { - // nope.. - this.priority.setText( "0" ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + if (fixed) { + this.priority.setText(out); + } - @Override - protected void keyTyped( final char character, final int key ) - { - if( !this.checkHotbarKeys( 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(); + if (out.isEmpty()) { + out = "0"; + } - boolean fixed = false; - while( out.startsWith( "0" ) && out.length() > 1 ) - { - out = out.substring( 1 ); - fixed = true; - } + NetworkHandler.instance.sendToServer( + new PacketValueConfig("PriorityHost.Priority", out) + ); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } + } - if( fixed ) - { - this.priority.setText( out ); - } - - if( out.isEmpty() ) - { - out = "0"; - } - - NetworkHandler.instance.sendToServer( new PacketValueConfig( "PriorityHost.Priority", out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } - } - - protected String getBackground() - { - return "guis/priority.png"; - } + protected String getBackground() { + return "guis/priority.png"; + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiQNB.java b/src/main/java/appeng/client/gui/implementations/GuiQNB.java index 3d4ae71e..d6a7c32b 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiQNB.java +++ b/src/main/java/appeng/client/gui/implementations/GuiQNB.java @@ -18,34 +18,33 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerQNB; import appeng.core.localization.GuiText; import appeng.tile.qnb.TileQuantumBridge; import net.minecraft.entity.player.InventoryPlayer; +public class GuiQNB extends AEBaseGui { + public GuiQNB(final InventoryPlayer inventoryPlayer, final TileQuantumBridge te) { + super(new ContainerQNB(inventoryPlayer, te)); + this.ySize = 166; + } -public class GuiQNB extends AEBaseGui -{ + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); + } - public GuiQNB( final InventoryPlayer inventoryPlayer, final TileQuantumBridge te ) - { - super( new ContainerQNB( inventoryPlayer, te ) ); - this.ySize = 166; - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/chest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 e2c6180d..d8327a98 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 appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerQuartzKnife; @@ -29,67 +30,67 @@ import appeng.items.contents.QuartzKnifeObj; import net.minecraft.client.gui.GuiTextField; import net.minecraft.entity.player.InventoryPlayer; -import java.io.IOException; +public class GuiQuartzKnife extends AEBaseGui { + private GuiTextField name; + public GuiQuartzKnife( + final InventoryPlayer inventoryPlayer, final QuartzKnifeObj te + ) { + super(new ContainerQuartzKnife(inventoryPlayer, te)); + this.ySize = 184; + } -public class GuiQuartzKnife extends AEBaseGui -{ + @Override + public void initGui() { + super.initGui(); - private GuiTextField name; + this.name = new GuiTextField( + this.fontRendererObj, + this.guiLeft + 24, + this.guiTop + 32, + 79, + this.fontRendererObj.FONT_HEIGHT + ); + this.name.setEnableBackgroundDrawing(false); + this.name.setMaxStringLength(32); + this.name.setTextColor(0xFFFFFF); + this.name.setVisible(true); + this.name.setFocused(true); + } - public GuiQuartzKnife( final InventoryPlayer inventoryPlayer, final QuartzKnifeObj te ) - { - super( new ContainerQuartzKnife( inventoryPlayer, te ) ); - this.ySize = 184; - } + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 initGui() - { - super.initGui(); + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/quartzknife.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + this.name.drawTextBox(); + } - this.name = new GuiTextField( this.fontRendererObj, this.guiLeft + 24, this.guiTop + 32, 79, this.fontRendererObj.FONT_HEIGHT ); - this.name.setEnableBackgroundDrawing( false ); - this.name.setMaxStringLength( 32 ); - this.name.setTextColor( 0xFFFFFF ); - this.name.setVisible( true ); - this.name.setFocused( true ); - } - - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/quartzknife.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - this.name.drawTextBox(); - } - - @Override - protected void keyTyped( final char character, final int key ) - { - if( this.name.textboxKeyTyped( character, key ) ) - { - try - { - final String Out = this.name.getText(); - ( (ContainerQuartzKnife) this.inventorySlots ).setName( Out ); - NetworkHandler.instance.sendToServer( new PacketValueConfig( "QuartzKnife.Name", Out ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - else - { - super.keyTyped( character, key ); - } - } + @Override + protected void keyTyped(final char character, final int key) { + if (this.name.textboxKeyTyped(character, key)) { + try { + final String Out = this.name.getText(); + ((ContainerQuartzKnife) this.inventorySlots).setName(Out); + NetworkHandler.instance.sendToServer( + new PacketValueConfig("QuartzKnife.Name", Out) + ); + } catch (final IOException e) { + AELog.debug(e); + } + } else { + super.keyTyped(character, key); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiSecurity.java b/src/main/java/appeng/client/gui/implementations/GuiSecurity.java index b287c9e2..9d88bc69 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSecurity.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSecurity.java @@ -18,6 +18,7 @@ package appeng.client.gui.implementations; +import java.io.IOException; import appeng.api.config.SecurityPermissions; import appeng.api.config.SortOrder; @@ -30,111 +31,154 @@ import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketValueConfig; import net.minecraft.entity.player.InventoryPlayer; -import java.io.IOException; +public class GuiSecurity extends GuiMEMonitorable { + private GuiToggleButton inject; + private GuiToggleButton extract; + private GuiToggleButton craft; + private GuiToggleButton build; + private GuiToggleButton security; + public GuiSecurity(final InventoryPlayer inventoryPlayer, final ITerminalHost te) { + super(inventoryPlayer, te, new ContainerSecurity(inventoryPlayer, te)); + this.setCustomSortOrder(false); + this.setReservedSpace(33); -public class GuiSecurity extends GuiMEMonitorable -{ + // increase size so that the slot is over the gui. + this.xSize += 56; + this.setStandardSize(this.xSize); + } - private GuiToggleButton inject; - private GuiToggleButton extract; - private GuiToggleButton craft; - private GuiToggleButton build; - private GuiToggleButton security; + @Override + protected void actionPerformed(final net.minecraft.client.gui.GuiButton btn) { + super.actionPerformed(btn); - public GuiSecurity( final InventoryPlayer inventoryPlayer, final ITerminalHost te ) - { - super( inventoryPlayer, te, new ContainerSecurity( inventoryPlayer, te ) ); - this.setCustomSortOrder( false ); - this.setReservedSpace( 33 ); + SecurityPermissions toggleSetting = null; - // increase size so that the slot is over the gui. - this.xSize += 56; - this.setStandardSize( this.xSize ); - } + 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; + } - @Override - protected void actionPerformed( final net.minecraft.client.gui.GuiButton btn ) - { - super.actionPerformed( btn ); + if (toggleSetting != null) { + try { + NetworkHandler.instance.sendToServer(new PacketValueConfig( + "TileSecurity.ToggleOption", toggleSetting.name() + )); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - SecurityPermissions toggleSetting = null; + @Override + public void initGui() { + super.initGui(); - 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; - } + final 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() + ) + ); - if( toggleSetting != null ) - { - try - { - NetworkHandler.instance.sendToServer( new PacketValueConfig( "TileSecurity.ToggleOption", toggleSetting.name() ) ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + this.buttonList.add( + this.extract = new GuiToggleButton( + this.guiLeft + 56 + 18, + top, + 11 * 16 + 1, + 12 * 16 + 1, + SecurityPermissions.EXTRACT.getUnlocalizedName(), + SecurityPermissions.EXTRACT.getUnlocalizedTip() + ) + ); - @Override - public void initGui() - { - super.initGui(); + 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() + ) + ); - final 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.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.extract = new GuiToggleButton( this.guiLeft + 56 + 18, top, 11 * 16 + 1, 12 * 16 + 1, SecurityPermissions.EXTRACT.getUnlocalizedName(), SecurityPermissions.EXTRACT.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.craft = new GuiToggleButton( this.guiLeft + 56 + 18 * 2, top, 11 * 16 + 2, 12 * 16 + 2, SecurityPermissions.CRAFT.getUnlocalizedName(), SecurityPermissions.CRAFT.getUnlocalizedTip() ) ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + super.drawFG(offsetX, offsetY, mouseX, mouseY); + this.fontRendererObj.drawString( + GuiText.SecurityCardEditor.getLocal(), + 8, + this.ySize - 96 + 1 - this.getReservedSpace(), + 4210752 + ); + } - 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() ) ); + @Override + protected String getBackground() { + final ContainerSecurity cs = (ContainerSecurity) this.inventorySlots; - 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.inject.setState( + (cs.getPermissionMode() & (1 << SecurityPermissions.INJECT.ordinal())) > 0 + ); + this.extract.setState( + (cs.getPermissionMode() & (1 << SecurityPermissions.EXTRACT.ordinal())) > 0 + ); + this.craft.setState( + (cs.getPermissionMode() & (1 << SecurityPermissions.CRAFT.ordinal())) > 0 + ); + this.build.setState( + (cs.getPermissionMode() & (1 << SecurityPermissions.BUILD.ordinal())) > 0 + ); + this.security.setState( + (cs.getPermissionMode() & (1 << SecurityPermissions.SECURITY.ordinal())) > 0 + ); - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - super.drawFG( offsetX, offsetY, mouseX, mouseY ); - this.fontRendererObj.drawString( GuiText.SecurityCardEditor.getLocal(), 8, this.ySize - 96 + 1 - this.getReservedSpace(), 4210752 ); - } + return "guis/security.png"; + } - @Override - protected String getBackground() - { - final ContainerSecurity cs = (ContainerSecurity) this.inventorySlots; - - this.inject.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.INJECT.ordinal() ) ) > 0 ); - this.extract.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.EXTRACT.ordinal() ) ) > 0 ); - this.craft.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.CRAFT.ordinal() ) ) > 0 ); - this.build.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.BUILD.ordinal() ) ) > 0 ); - this.security.setState( ( cs.getPermissionMode() & ( 1 << SecurityPermissions.SECURITY.ordinal() ) ) > 0 ); - - return "guis/security.png"; - } - - @Override - public Enum getSortBy() - { - return SortOrder.NAME; - } + @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 7ce0f73b..07cf1f59 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSkyChest.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.container.implementations.ContainerSkyChest; import appeng.core.localization.GuiText; @@ -27,33 +26,32 @@ import appeng.integration.IntegrationType; import appeng.tile.storage.TileSkyChest; import net.minecraft.entity.player.InventoryPlayer; +public class GuiSkyChest extends AEBaseGui { + public GuiSkyChest(final InventoryPlayer inventoryPlayer, final TileSkyChest te) { + super(new ContainerSkyChest(inventoryPlayer, te)); + this.ySize = 195; + } -public class GuiSkyChest extends AEBaseGui -{ + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); + } - public GuiSkyChest( final InventoryPlayer inventoryPlayer, final TileSkyChest te ) - { - super( new ContainerSkyChest( inventoryPlayer, te ) ); - this.ySize = 195; - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture("guis/skychest.png"); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/skychest.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } - - @Override - protected boolean enableSpaceClicking() - { - return !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.InvTweaks ); - } + @Override + protected boolean enableSpaceClicking() { + return !IntegrationRegistry.INSTANCE.isEnabled(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 daadd10e..75879b10 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java +++ b/src/main/java/appeng/client/gui/implementations/GuiSpatialIOPort.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; @@ -31,59 +30,87 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; +public class GuiSpatialIOPort extends AEBaseGui { + private final ContainerSpatialIOPort container; + private GuiImgButton units; -public class GuiSpatialIOPort extends AEBaseGui -{ + public GuiSpatialIOPort( + final InventoryPlayer inventoryPlayer, final TileSpatialIOPort te + ) { + super(new ContainerSpatialIOPort(inventoryPlayer, te)); + this.ySize = 199; + this.container = (ContainerSpatialIOPort) this.inventorySlots; + } - private final ContainerSpatialIOPort container; - private GuiImgButton units; + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - public GuiSpatialIOPort( final InventoryPlayer inventoryPlayer, final TileSpatialIOPort te ) - { - super( new ContainerSpatialIOPort( inventoryPlayer, te ) ); - this.ySize = 199; - this.container = (ContainerSpatialIOPort) this.inventorySlots; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (btn == this.units) { + AEConfig.instance.nextPowerUnit(backwards); + this.units.set(AEConfig.instance.selectedPowerUnit()); + } + } - final boolean backwards = Mouse.isButtonDown( 1 ); + @Override + public void initGui() { + super.initGui(); - if( btn == this.units ) - { - AEConfig.instance.nextPowerUnit( backwards ); - this.units.set( AEConfig.instance.selectedPowerUnit() ); - } - } + this.units = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 8, + Settings.POWER_UNITS, + AEConfig.instance.selectedPowerUnit() + ); + this.buttonList.add(this.units); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.fontRendererObj.drawString( + GuiText.StoredPower.getLocal() + ": " + + Platform.formatPowerLong(this.container.getCurrentPower(), false), + 13, + 21, + 4210752 + ); + this.fontRendererObj.drawString( + GuiText.MaxPower.getLocal() + ": " + + Platform.formatPowerLong(this.container.getMaxPower(), false), + 13, + 31, + 4210752 + ); + this.fontRendererObj.drawString( + GuiText.RequiredPower.getLocal() + ": " + + Platform.formatPowerLong(this.container.getRequiredPower(), false), + 13, + 78, + 4210752 + ); + this.fontRendererObj.drawString( + GuiText.Efficiency.getLocal() + ": " + + (((float) this.container.getEfficency()) / 100) + '%', + 13, + 88, + 4210752 + ); - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit() ); - this.buttonList.add( this.units ); - } + 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 drawFG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.fontRendererObj.drawString( GuiText.StoredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getCurrentPower(), false ), 13, 21, 4210752 ); - this.fontRendererObj.drawString( GuiText.MaxPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getMaxPower(), false ), 13, 31, 4210752 ); - this.fontRendererObj.drawString( GuiText.RequiredPower.getLocal() + ": " + Platform.formatPowerLong( this.container.getRequiredPower(), false ), 13, 78, 4210752 ); - this.fontRendererObj.drawString( GuiText.Efficiency.getLocal() + ": " + ( ( (float) this.container.getEfficency() ) / 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/spatialio.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 65e6eb3d..ba23276c 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 appeng.api.config.*; import appeng.client.gui.widgets.GuiImgButton; @@ -35,103 +36,117 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; -import java.io.IOException; +public class GuiStorageBus extends GuiUpgradeable { + private GuiImgButton rwMode; + private GuiImgButton storageFilter; + private GuiTabButton priority; + private GuiImgButton partition; + private GuiImgButton clear; + public GuiStorageBus(final InventoryPlayer inventoryPlayer, final PartStorageBus te) { + super(new ContainerStorageBus(inventoryPlayer, te)); + this.ySize = 251; + } -public class GuiStorageBus extends GuiUpgradeable -{ + @Override + protected void addButtons() { + this.clear = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE + ); + this.partition = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH + ); + this.rwMode = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 48, + Settings.ACCESS, + AccessRestriction.READ_WRITE + ); + this.storageFilter = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 68, + Settings.STORAGE_FILTER, + StorageFilter.EXTRACTABLE_ONLY + ); + this.fuzzyMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); - private GuiImgButton rwMode; - private GuiImgButton storageFilter; - private GuiTabButton priority; - private GuiImgButton partition; - private GuiImgButton clear; + this.buttonList.add( + this.priority = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + 2 + 4 * 16, + GuiText.Priority.getLocal(), + itemRender + ) + ); - public GuiStorageBus( final InventoryPlayer inventoryPlayer, final PartStorageBus te ) - { - super( new ContainerStorageBus( inventoryPlayer, te ) ); - this.ySize = 251; - } + this.buttonList.add(this.storageFilter); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.rwMode); + this.buttonList.add(this.partition); + this.buttonList.add(this.clear); + } - @Override - protected void addButtons() - { - this.clear = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.ACTIONS, ActionItems.CLOSE ); - this.partition = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.ACTIONS, ActionItems.WRENCH ); - this.rwMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.storageFilter = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 88, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); - this.buttonList.add( this.priority = new GuiTabButton( this.guiLeft + 154, this.guiTop, 2 + 4 * 16, GuiText.Priority.getLocal(), itemRender ) ); + if (this.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } - this.buttonList.add( this.storageFilter ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.rwMode ); - this.buttonList.add( this.partition ); - this.buttonList.add( this.clear ); - } + if (this.storageFilter != null) { + this.storageFilter.set(((ContainerStorageBus) this.cvb).getStorageFilter()); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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.rwMode != null) { + this.rwMode.set(((ContainerStorageBus) this.cvb).getReadWriteMode()); + } + } - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } + @Override + protected String getBackground() { + return "guis/storagebus.png"; + } - if( this.storageFilter != null ) - { - this.storageFilter.set( ( (ContainerStorageBus) this.cvb ).getStorageFilter() ); - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - if( this.rwMode != null ) - { - this.rwMode.set( ( (ContainerStorageBus) this.cvb ).getReadWriteMode() ); - } - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected String getBackground() - { - return "guis/storagebus.png"; - } - - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); - - final 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( final IOException e ) - { - AELog.debug( e ); - } - } + 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 (final IOException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java index 461c94f1..3ee84ebe 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java +++ b/src/main/java/appeng/client/gui/implementations/GuiUpgradeable.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.*; import appeng.api.implementations.IUpgradeableHost; import appeng.client.gui.AEBaseGui; @@ -33,162 +32,176 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; +public class GuiUpgradeable extends AEBaseGui { + protected final ContainerUpgradeable cvb; + protected final IUpgradeableHost bc; -public class GuiUpgradeable extends AEBaseGui -{ + protected GuiImgButton redstoneMode; + protected GuiImgButton fuzzyMode; + protected GuiImgButton craftMode; + protected GuiImgButton schedulingMode; - protected final ContainerUpgradeable cvb; - protected final IUpgradeableHost bc; + public GuiUpgradeable( + final InventoryPlayer inventoryPlayer, final IUpgradeableHost te + ) { + this(new ContainerUpgradeable(inventoryPlayer, te)); + } - protected GuiImgButton redstoneMode; - protected GuiImgButton fuzzyMode; - protected GuiImgButton craftMode; - protected GuiImgButton schedulingMode; + public GuiUpgradeable(final ContainerUpgradeable te) { + super(te); + this.cvb = te; - public GuiUpgradeable( final InventoryPlayer inventoryPlayer, final IUpgradeableHost te ) - { - this( new ContainerUpgradeable( inventoryPlayer, te ) ); - } + this.bc = (IUpgradeableHost) te.getTarget(); + this.xSize = this.hasToolbox() ? 246 : 211; + this.ySize = 184; + } - public GuiUpgradeable( final ContainerUpgradeable te ) - { - super( te ); - this.cvb = te; + protected boolean hasToolbox() { + return ((ContainerUpgradeable) this.inventorySlots).hasToolbox(); + } - this.bc = (IUpgradeableHost) te.getTarget(); - this.xSize = this.hasToolbox() ? 246 : 211; - this.ySize = 184; - } + @Override + public void initGui() { + super.initGui(); + this.addButtons(); + } - protected boolean hasToolbox() - { - return ( (ContainerUpgradeable) this.inventorySlots ).hasToolbox(); - } + protected void addButtons() { + this.redstoneMode = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 8, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.IGNORE + ); + this.fuzzyMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 28, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); + this.craftMode = new GuiImgButton( + this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_ONLY, YesNo.NO + ); + this.schedulingMode = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 68, + Settings.SCHEDULING_MODE, + SchedulingMode.DEFAULT + ); - @Override - public void initGui() - { - super.initGui(); - this.addButtons(); - } + this.buttonList.add(this.craftMode); + this.buttonList.add(this.redstoneMode); + this.buttonList.add(this.fuzzyMode); + this.buttonList.add(this.schedulingMode); + } - protected void addButtons() - { - this.redstoneMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.fuzzyMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 28, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.craftMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 48, Settings.CRAFT_ONLY, YesNo.NO ); - this.schedulingMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 68, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); - this.buttonList.add( this.craftMode ); - this.buttonList.add( this.redstoneMode ); - this.buttonList.add( this.fuzzyMode ); - this.buttonList.add( this.schedulingMode ); - } + if (this.redstoneMode != null) { + this.redstoneMode.set(this.cvb.getRedStoneMode()); + } - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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.fuzzyMode != null) { + this.fuzzyMode.set(this.cvb.getFuzzyMode()); + } - if( this.redstoneMode != null ) - { - this.redstoneMode.set( this.cvb.getRedStoneMode() ); - } + if (this.craftMode != null) { + this.craftMode.set(this.cvb.getCraftingMode()); + } - if( this.fuzzyMode != null ) - { - this.fuzzyMode.set( this.cvb.getFuzzyMode() ); - } + if (this.schedulingMode != null) { + this.schedulingMode.set(this.cvb.getSchedulingMode()); + } + } - if( this.craftMode != null ) - { - this.craftMode.set( this.cvb.getCraftingMode() ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.handleButtonVisibility(); - if( this.schedulingMode != null ) - { - this.schedulingMode.set( this.cvb.getSchedulingMode() ); - } - } + this.bindTexture(this.getBackground()); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, 211 - 34, this.ySize); + if (this.drawUpgrades()) { + this.drawTexturedModalRect( + offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvb.availableUpgrades() * 18 + ); + } + if (this.hasToolbox()) { + this.drawTexturedModalRect( + offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 + ); + } + } - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.handleButtonVisibility(); + protected void handleButtonVisibility() { + 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 + ); + } + if (this.schedulingMode != null) { + this.schedulingMode.setVisibility( + this.bc.getInstalledUpgrades(Upgrades.CAPACITY) > 0 + && this.bc instanceof PartExportBus + ); + } + } - this.bindTexture( this.getBackground() ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, 211 - 34, this.ySize ); - if( this.drawUpgrades() ) - { - this.drawTexturedModalRect( offsetX + 177, offsetY, 177, 0, 35, 14 + this.cvb.availableUpgrades() * 18 ); - } - if( this.hasToolbox() ) - { - this.drawTexturedModalRect( offsetX + 178, offsetY + this.ySize - 90, 178, this.ySize - 90, 68, 68 ); - } - } + protected String getBackground() { + return "guis/bus.png"; + } - protected void handleButtonVisibility() - { - 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 ); - } - if( this.schedulingMode != null ) - { - this.schedulingMode.setVisibility( this.bc.getInstalledUpgrades( Upgrades.CAPACITY ) > 0 && this.bc instanceof PartExportBus ); - } - } + protected boolean drawUpgrades() { + return true; + } - protected String getBackground() - { - return "guis/bus.png"; - } + protected GuiText getName() { + return this.bc instanceof PartImportBus ? GuiText.ImportBus : GuiText.ExportBus; + } - protected boolean drawUpgrades() - { - return true; - } + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - protected GuiText getName() - { - return this.bc instanceof PartImportBus ? GuiText.ImportBus : GuiText.ExportBus; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (btn == this.redstoneMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.redstoneMode.getSetting(), backwards) + ); + } - final boolean backwards = Mouse.isButtonDown( 1 ); + if (btn == this.craftMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.craftMode.getSetting(), backwards) + ); + } - if( btn == this.redstoneMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.redstoneMode.getSetting(), backwards ) ); - } + if (btn == this.fuzzyMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.fuzzyMode.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 ) ); - } - - if( btn == this.schedulingMode ) - { - NetworkHandler.instance.sendToServer( new PacketConfigButton( this.schedulingMode.getSetting(), backwards ) ); - } - } + if (btn == this.schedulingMode) { + NetworkHandler.instance.sendToServer( + new PacketConfigButton(this.schedulingMode.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 ee67b84b..c4c57c57 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java +++ b/src/main/java/appeng/client/gui/implementations/GuiVibrationChamber.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiProgressBar; import appeng.client.gui.widgets.GuiProgressBar.Direction; @@ -28,54 +27,60 @@ import appeng.tile.misc.TileVibrationChamber; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.opengl.GL11; +public class GuiVibrationChamber extends AEBaseGui { + private final ContainerVibrationChamber cvc; + private GuiProgressBar pb; -public class GuiVibrationChamber extends AEBaseGui -{ + public GuiVibrationChamber( + final InventoryPlayer inventoryPlayer, final TileVibrationChamber te + ) { + super(new ContainerVibrationChamber(inventoryPlayer, te)); + this.cvc = (ContainerVibrationChamber) this.inventorySlots; + this.ySize = 166; + } - private final ContainerVibrationChamber cvc; - private GuiProgressBar pb; + @Override + public void initGui() { + super.initGui(); - public GuiVibrationChamber( final InventoryPlayer inventoryPlayer, final TileVibrationChamber te ) - { - super( new ContainerVibrationChamber( inventoryPlayer, te ) ); - this.cvc = (ContainerVibrationChamber) this.inventorySlots; - this.ySize = 166; - } + this.pb = new GuiProgressBar( + this.cvc, "guis/vibchamber.png", 99, 36, 176, 14, 6, 18, Direction.VERTICAL + ); + this.buttonList.add(this.pb); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); - this.pb = new GuiProgressBar( this.cvc, "guis/vibchamber.png", 99, 36, 176, 14, 6, 18, Direction.VERTICAL ); - this.buttonList.add( this.pb ); - } + this.pb.setFullMsg( + this.cvc.getAePerTick() * this.cvc.getCurrentProgress() / 100 + " AE/t" + ); - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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 ); + if (this.cvc.getCurrentProgress() > 0) { + final int i1 = this.cvc.getCurrentProgress(); + this.bindTexture("guis/vibchamber.png"); + GL11.glColor3f(1, 1, 1); + final int l = -15; + final int k = 25; + this.drawTexturedModalRect( + k + 56, l + 36 + 12 - i1, 176, 12 - i1, 14, i1 + 2 + ); + } + } - this.pb.setFullMsg( this.cvc.getAePerTick() * this.cvc.getCurrentProgress() / 100 + " AE/t" ); - - if( this.cvc.getCurrentProgress() > 0 ) - { - final int i1 = this.cvc.getCurrentProgress(); - this.bindTexture( "guis/vibchamber.png" ); - GL11.glColor3f( 1, 1, 1 ); - final int l = -15; - final int k = 25; - this.drawTexturedModalRect( k + 56, l + 36 + 12 - i1, 176, 12 - i1, 14, i1 + 2 ); - } - } - - @Override - public void drawBG( final int offsetX, final int offsetY, final int mouseX, final 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 + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 a47cbda7..c9a24ad3 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWireless.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWireless.java @@ -18,7 +18,6 @@ package appeng.client.gui.implementations; - import appeng.api.config.Settings; import appeng.client.gui.AEBaseGui; import appeng.client.gui.widgets.GuiImgButton; @@ -31,65 +30,71 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.InventoryPlayer; import org.lwjgl.input.Mouse; +public class GuiWireless extends AEBaseGui { + private GuiImgButton units; -public class GuiWireless extends AEBaseGui -{ + public GuiWireless(final InventoryPlayer inventoryPlayer, final TileWireless te) { + super(new ContainerWireless(inventoryPlayer, te)); + this.ySize = 166; + } - private GuiImgButton units; + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); - public GuiWireless( final InventoryPlayer inventoryPlayer, final TileWireless te ) - { - super( new ContainerWireless( inventoryPlayer, te ) ); - this.ySize = 166; - } + final boolean backwards = Mouse.isButtonDown(1); - @Override - protected void actionPerformed( final GuiButton btn ) - { - super.actionPerformed( btn ); + if (btn == this.units) { + AEConfig.instance.nextPowerUnit(backwards); + this.units.set(AEConfig.instance.selectedPowerUnit()); + } + } - final boolean backwards = Mouse.isButtonDown( 1 ); + @Override + public void initGui() { + super.initGui(); - if( btn == this.units ) - { - AEConfig.instance.nextPowerUnit( backwards ); - this.units.set( AEConfig.instance.selectedPowerUnit() ); - } - } + this.units = new GuiImgButton( + this.guiLeft - 18, + this.guiTop + 8, + Settings.POWER_UNITS, + AEConfig.instance.selectedPowerUnit() + ); + this.buttonList.add(this.units); + } - @Override - public void initGui() - { - super.initGui(); + @Override + public void + drawFG(final int offsetX, final int offsetY, final int mouseX, final 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 + ); - this.units = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.POWER_UNITS, AEConfig.instance.selectedPowerUnit() ); - this.buttonList.add( this.units ); - } + final ContainerWireless cw = (ContainerWireless) this.inventorySlots; - @Override - public void drawFG( final int offsetX, final int offsetY, final int mouseX, final 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 ); + if (cw.getRange() > 0) { + final String firstMessage + = GuiText.Range.getLocal() + ": " + (cw.getRange() / 10.0) + " m"; + final String secondMessage = GuiText.PowerUsageRate.getLocal() + ": " + + Platform.formatPowerLong(cw.getDrain(), true); - final ContainerWireless cw = (ContainerWireless) this.inventorySlots; + final int strWidth = Math.max( + this.fontRendererObj.getStringWidth(firstMessage), + this.fontRendererObj.getStringWidth(secondMessage) + ); + final int cOffset = (this.xSize / 2) - (strWidth / 2); + this.fontRendererObj.drawString(firstMessage, cOffset, 20, 4210752); + this.fontRendererObj.drawString(secondMessage, cOffset, 20 + 12, 4210752); + } + } - if( cw.getRange() > 0 ) - { - final String firstMessage = GuiText.Range.getLocal() + ": " + ( cw.getRange() / 10.0 ) + " m"; - final String secondMessage = GuiText.PowerUsageRate.getLocal() + ": " + Platform.formatPowerLong( cw.getDrain(), true ); - - final int strWidth = Math.max( this.fontRendererObj.getStringWidth( firstMessage ), this.fontRendererObj.getStringWidth( secondMessage ) ); - final 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( final int offsetX, final int offsetY, final int mouseX, final int mouseY ) - { - this.bindTexture( "guis/wireless.png" ); - this.drawTexturedModalRect( offsetX, offsetY, 0, 0, this.xSize, this.ySize ); - } + @Override + public void + drawBG(final int offsetX, final int offsetY, final int mouseX, final 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 7eb18a9e..ad113ac8 100644 --- a/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java +++ b/src/main/java/appeng/client/gui/implementations/GuiWirelessTerm.java @@ -18,22 +18,18 @@ package appeng.client.gui.implementations; - import appeng.api.implementations.guiobjects.IPortableCell; import net.minecraft.entity.player.InventoryPlayer; +public class GuiWirelessTerm extends GuiMEPortableCell { + public GuiWirelessTerm( + final InventoryPlayer inventoryPlayer, final IPortableCell te + ) { + super(inventoryPlayer, te); + } -public class GuiWirelessTerm extends GuiMEPortableCell -{ - - public GuiWirelessTerm( final InventoryPlayer inventoryPlayer, final IPortableCell te ) - { - super( inventoryPlayer, te ); - } - - @Override - int getMaxRows() - { - return this.defaultGetMaxRows(); - } + @Override + int getMaxRows() { + return this.defaultGetMaxRows(); + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java index bee045ae..20409248 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java @@ -18,6 +18,9 @@ package appeng.client.gui.widgets; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; import appeng.api.config.*; import appeng.client.texture.ExtraBlockTextures; @@ -27,379 +30,743 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.util.StatCollector; import org.lwjgl.opengl.GL11; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; - - -public class GuiImgButton extends GuiButton implements ITooltip -{ - private static final Pattern COMPILE = Pattern.compile( "%s" ); - private static final Pattern PATTERN_NEW_LINE = Pattern.compile( "\\n", Pattern.LITERAL ); - private static Map appearances; - private final Enum buttonSetting; - private boolean halfSize = false; - private String fillVar; - private Enum currentValue; - - public GuiImgButton( final int x, final int y, final Enum idx, final Enum val ) - { - super( 0, 0, 16, "" ); - - this.buttonSetting = idx; - this.currentValue = val; - this.xPosition = x; - this.yPosition = y; - this.width = 16; - this.height = 16; - - if( appearances == null ) - { - appearances = new HashMap(); - this.registerApp( 16 * 7, Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH, ButtonToolTips.CondenserOutput, ButtonToolTips.Trash ); - this.registerApp( 16 * 7 + 1, Settings.CONDENSER_OUTPUT, CondenserOutput.MATTER_BALLS, ButtonToolTips.CondenserOutput, ButtonToolTips.MatterBalls ); - this.registerApp( 16 * 7 + 2, Settings.CONDENSER_OUTPUT, CondenserOutput.SINGULARITY, ButtonToolTips.CondenserOutput, ButtonToolTips.Singularity ); - - this.registerApp( 16 * 9 + 1, Settings.ACCESS, AccessRestriction.READ, ButtonToolTips.IOMode, ButtonToolTips.Read ); - this.registerApp( 16 * 9, Settings.ACCESS, AccessRestriction.WRITE, ButtonToolTips.IOMode, ButtonToolTips.Write ); - this.registerApp( 16 * 9 + 2, Settings.ACCESS, AccessRestriction.READ_WRITE, ButtonToolTips.IOMode, ButtonToolTips.ReadWrite ); - - this.registerApp( 16 * 10, Settings.POWER_UNITS, PowerUnits.AE, ButtonToolTips.PowerUnits, PowerUnits.AE.unlocalizedName ); - this.registerApp( 16 * 10 + 1, Settings.POWER_UNITS, PowerUnits.EU, ButtonToolTips.PowerUnits, PowerUnits.EU.unlocalizedName ); - this.registerApp( 16 * 10 + 2, Settings.POWER_UNITS, PowerUnits.MK, ButtonToolTips.PowerUnits, PowerUnits.MK.unlocalizedName ); - this.registerApp( 16 * 10 + 3, Settings.POWER_UNITS, PowerUnits.WA, ButtonToolTips.PowerUnits, PowerUnits.WA.unlocalizedName ); - this.registerApp( 16 * 10 + 4, Settings.POWER_UNITS, PowerUnits.RF, ButtonToolTips.PowerUnits, PowerUnits.RF.unlocalizedName ); - - this.registerApp( 3, Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE, ButtonToolTips.RedstoneMode, ButtonToolTips.AlwaysActive ); - this.registerApp( 0, Settings.REDSTONE_CONTROLLED, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithoutSignal ); - this.registerApp( 1, Settings.REDSTONE_CONTROLLED, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveWithSignal ); - this.registerApp( 2, Settings.REDSTONE_CONTROLLED, RedstoneMode.SIGNAL_PULSE, ButtonToolTips.RedstoneMode, ButtonToolTips.ActiveOnPulse ); - - this.registerApp( 0, Settings.REDSTONE_EMITTER, RedstoneMode.LOW_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelsBelow ); - this.registerApp( 1, Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL, ButtonToolTips.RedstoneMode, ButtonToolTips.EmitLevelAbove ); - - this.registerApp( 51, Settings.OPERATION_MODE, OperationMode.FILL, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell ); - this.registerApp( 50, Settings.OPERATION_MODE, OperationMode.EMPTY, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork ); - - this.registerApp( 51, Settings.IO_DIRECTION, RelativeDirection.LEFT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToStorageCell ); - this.registerApp( 50, Settings.IO_DIRECTION, RelativeDirection.RIGHT, ButtonToolTips.TransferDirection, ButtonToolTips.TransferToNetwork ); - - this.registerApp( 48, Settings.SORT_DIRECTION, SortDir.ASCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection ); - this.registerApp( 49, Settings.SORT_DIRECTION, SortDir.DESCENDING, ButtonToolTips.SortOrder, ButtonToolTips.ToggleSortDirection ); - - this.registerApp( 16 * 2 + 3, Settings.SEARCH_MODE, SearchBoxMode.AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Auto ); - this.registerApp( 16 * 2 + 4, Settings.SEARCH_MODE, SearchBoxMode.MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_Standard ); - this.registerApp( 16 * 2 + 5, Settings.SEARCH_MODE, SearchBoxMode.NEI_AUTOSEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_NEIAuto ); - this.registerApp( 16 * 2 + 6, Settings.SEARCH_MODE, SearchBoxMode.NEI_MANUAL_SEARCH, ButtonToolTips.SearchMode, ButtonToolTips.SearchMode_NEIStandard ); - - this.registerApp( 16 * 5 + 3, Settings.LEVEL_TYPE, LevelType.ENERGY_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Energy ); - this.registerApp( 16 * 4 + 3, Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL, ButtonToolTips.LevelType, ButtonToolTips.LevelType_Item ); - - this.registerApp( 16 * 13, Settings.TERMINAL_STYLE, TerminalStyle.TALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Tall ); - this.registerApp( 16 * 13 + 1, Settings.TERMINAL_STYLE, TerminalStyle.SMALL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Small ); - this.registerApp( 16 * 13 + 2, Settings.TERMINAL_STYLE, TerminalStyle.FULL, ButtonToolTips.TerminalStyle, ButtonToolTips.TerminalStyle_Full ); - - this.registerApp( 64, Settings.SORT_BY, SortOrder.NAME, ButtonToolTips.SortBy, ButtonToolTips.ItemName ); - this.registerApp( 65, Settings.SORT_BY, SortOrder.AMOUNT, ButtonToolTips.SortBy, ButtonToolTips.NumberOfItems ); - this.registerApp( 68, Settings.SORT_BY, SortOrder.INVTWEAKS, ButtonToolTips.SortBy, ButtonToolTips.InventoryTweaks ); - this.registerApp( 69, Settings.SORT_BY, SortOrder.MOD, ButtonToolTips.SortBy, ButtonToolTips.Mod ); - - this.registerApp( 66, Settings.ACTIONS, ActionItems.WRENCH, ButtonToolTips.PartitionStorage, ButtonToolTips.PartitionStorageHint ); - this.registerApp( 6, Settings.ACTIONS, ActionItems.CLOSE, ButtonToolTips.Clear, ButtonToolTips.ClearSettings ); - this.registerApp( 6, Settings.ACTIONS, ActionItems.STASH, ButtonToolTips.Stash, ButtonToolTips.StashDesc ); - - this.registerApp( 8, Settings.ACTIONS, ActionItems.ENCODE, ButtonToolTips.Encode, ButtonToolTips.EncodeDescription ); - this.registerApp( 4 + 3 * 16, Settings.ACTIONS, ItemSubstitution.ENABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescEnabled ); - this.registerApp( 7 + 3 * 16, Settings.ACTIONS, ItemSubstitution.DISABLED, ButtonToolTips.Substitutions, ButtonToolTips.SubstitutionsDescDisabled ); - - this.registerApp( 16, Settings.VIEW_MODE, ViewItems.STORED, ButtonToolTips.View, ButtonToolTips.StoredItems ); - this.registerApp( 18, Settings.VIEW_MODE, ViewItems.ALL, ButtonToolTips.View, ButtonToolTips.StoredCraftable ); - this.registerApp( 19, Settings.VIEW_MODE, ViewItems.CRAFTABLE, ButtonToolTips.View, ButtonToolTips.Craftable ); - - this.registerApp( 16 * 6, Settings.FUZZY_MODE, FuzzyMode.PERCENT_25, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_25 ); - this.registerApp( 16 * 6 + 1, Settings.FUZZY_MODE, FuzzyMode.PERCENT_50, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_50 ); - this.registerApp( 16 * 6 + 2, Settings.FUZZY_MODE, FuzzyMode.PERCENT_75, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_75 ); - this.registerApp( 16 * 6 + 3, Settings.FUZZY_MODE, FuzzyMode.PERCENT_99, ButtonToolTips.FuzzyMode, ButtonToolTips.FZPercent_99 ); - this.registerApp( 16 * 6 + 4, Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL, ButtonToolTips.FuzzyMode, ButtonToolTips.FZIgnoreAll ); - - this.registerApp( 80, Settings.FULLNESS_MODE, FullnessMode.EMPTY, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenEmpty ); - this.registerApp( 81, Settings.FULLNESS_MODE, FullnessMode.HALF, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenWorkIsDone ); - this.registerApp( 82, Settings.FULLNESS_MODE, FullnessMode.FULL, ButtonToolTips.OperationMode, ButtonToolTips.MoveWhenFull ); - - this.registerApp( 16 + 5, Settings.BLOCK, YesNo.YES, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.Blocking ); - this.registerApp( 16 + 4, Settings.BLOCK, YesNo.NO, ButtonToolTips.InterfaceBlockingMode, ButtonToolTips.NonBlocking ); - - this.registerApp( 16 + 3, Settings.CRAFT_ONLY, YesNo.YES, ButtonToolTips.Craft, ButtonToolTips.CraftOnly ); - this.registerApp( 16 + 2, Settings.CRAFT_ONLY, YesNo.NO, ButtonToolTips.Craft, ButtonToolTips.CraftEither ); - - this.registerApp( 16 * 11 + 2, Settings.CRAFT_VIA_REDSTONE, YesNo.YES, ButtonToolTips.EmitterMode, ButtonToolTips.CraftViaRedstone ); - this.registerApp( 16 * 11 + 1, Settings.CRAFT_VIA_REDSTONE, YesNo.NO, ButtonToolTips.EmitterMode, ButtonToolTips.EmitWhenCrafting ); - - this.registerApp( 16 * 3 + 5, Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsNo ); - this.registerApp( 16 * 3 + 6, Settings.STORAGE_FILTER, StorageFilter.NONE, ButtonToolTips.ReportInaccessibleItems, ButtonToolTips.ReportInaccessibleItemsYes ); - - this.registerApp( 16 * 14, Settings.PLACE_BLOCK, YesNo.YES, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementYes ); - this.registerApp( 16 * 14 + 1, Settings.PLACE_BLOCK, YesNo.NO, ButtonToolTips.BlockPlacement, ButtonToolTips.BlockPlacementNo ); - - this.registerApp( 16 * 15, Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeDefault ); - this.registerApp( 16 * 15 + 1, Settings.SCHEDULING_MODE, SchedulingMode.ROUNDROBIN, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRoundRobin ); - this.registerApp( 16 * 15 + 2, Settings.SCHEDULING_MODE, SchedulingMode.RANDOM, ButtonToolTips.SchedulingMode, ButtonToolTips.SchedulingModeRandom ); - } - } - - private void registerApp( final int iconIndex, final Settings setting, final Enum val, final ButtonToolTips title, final Object hint ) - { - final ButtonAppearance a = new ButtonAppearance(); - a.displayName = title.getUnlocalized(); - a.displayValue = (String) ( hint instanceof String ? hint : ( (ButtonToolTips) hint ).getUnlocalized() ); - a.index = iconIndex; - appearances.put( new EnumPair( setting, val ), a ); - } - - public void setVisibility( final boolean vis ) - { - this.visible = vis; - this.enabled = vis; - } - - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3 ) - { - if( this.visible ) - { - final int iconIndex = this.getIconIndex(); - - if( this.halfSize ) - { - this.width = 8; - this.height = 8; - - GL11.glPushMatrix(); - GL11.glTranslatef( this.xPosition, this.yPosition, 0.0F ); - GL11.glScalef( 0.5f, 0.5f, 0.5f ); - - if( this.enabled ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - else - { - GL11.glColor4f( 0.5f, 0.5f, 0.5f, 1.0f ); - } - - 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; - - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; - - this.drawTexturedModalRect( 0, 0, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( 0, 0, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - - GL11.glPopMatrix(); - } - else - { - if( this.enabled ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - else - { - GL11.glColor4f( 0.5f, 0.5f, 0.5f, 1.0f ); - } - - 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; - - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; - - this.drawTexturedModalRect( this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } - - private int getIconIndex() - { - if( this.buttonSetting != null && this.currentValue != null ) - { - final ButtonAppearance app = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if( app == null ) - { - return 256 - 1; - } - return app.index; - } - return 256 - 1; - } - - public Settings getSetting() - { - return (Settings) this.buttonSetting; - } - - public Enum getCurrentValue() - { - return this.currentValue; - } - - @Override - public String getMessage() - { - String displayName = null; - String displayValue = null; - - if( this.buttonSetting != null && this.currentValue != null ) - { - final ButtonAppearance buttonAppearance = appearances.get( new EnumPair( this.buttonSetting, this.currentValue ) ); - if( buttonAppearance == null ) - { - return "No Such Message"; - } - - displayName = buttonAppearance.displayName; - displayValue = buttonAppearance.displayValue; - } - - if( displayName != null ) - { - String name = StatCollector.translateToLocal( displayName ); - String value = StatCollector.translateToLocal( displayValue ); - - if( name == null || name.isEmpty() ) - { - name = displayName; - } - if( value == null || value.isEmpty() ) - { - value = displayValue; - } - - if( this.fillVar != null ) - { - value = COMPILE.matcher( value ).replaceFirst( this.fillVar ); - } - - value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); - final StringBuilder sb = new StringBuilder( value ); - - int i = sb.lastIndexOf( "\n" ); - if( i <= 0 ) - { - i = 0; - } - while( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) - { - sb.replace( i, i + 1, "\n" ); - } - - return name + '\n' + sb; - } - return null; - } - - @Override - public int xPos() - { - return this.xPosition; - } - - @Override - public int yPos() - { - return this.yPosition; - } - - @Override - public int getWidth() - { - return this.halfSize ? 8 : 16; - } - - @Override - public int getHeight() - { - return this.halfSize ? 8 : 16; - } - - @Override - public boolean isVisible() - { - return this.visible; - } - - public void set( final Enum e ) - { - if( this.currentValue != e ) - { - this.currentValue = e; - } - } - - public boolean isHalfSize() - { - return this.halfSize; - } - - public void setHalfSize( final boolean halfSize ) - { - this.halfSize = halfSize; - } - - public String getFillVar() - { - return this.fillVar; - } - - public void setFillVar( final String fillVar ) - { - this.fillVar = fillVar; - } - - private static final class EnumPair - { - - final Enum setting; - final Enum value; - - EnumPair( final Enum a, final Enum b ) - { - this.setting = a; - this.value = b; - } - - @Override - public int hashCode() - { - return this.setting.hashCode() ^ this.value.hashCode(); - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final EnumPair other = (EnumPair) obj; - return other.setting == this.setting && other.value == this.value; - } - } - - - private static class ButtonAppearance - { - public int index; - public String displayName; - public String displayValue; - } +public class GuiImgButton extends GuiButton implements ITooltip { + private static final Pattern COMPILE = Pattern.compile("%s"); + private static final Pattern PATTERN_NEW_LINE + = Pattern.compile("\\n", Pattern.LITERAL); + private static Map appearances; + private final Enum buttonSetting; + private boolean halfSize = false; + private String fillVar; + private Enum currentValue; + + public GuiImgButton(final int x, final int y, final Enum idx, final Enum val) { + super(0, 0, 16, ""); + + this.buttonSetting = idx; + this.currentValue = val; + this.xPosition = x; + this.yPosition = y; + this.width = 16; + this.height = 16; + + if (appearances == null) { + appearances = new HashMap(); + this.registerApp( + 16 * 7, + Settings.CONDENSER_OUTPUT, + CondenserOutput.TRASH, + ButtonToolTips.CondenserOutput, + ButtonToolTips.Trash + ); + this.registerApp( + 16 * 7 + 1, + Settings.CONDENSER_OUTPUT, + CondenserOutput.MATTER_BALLS, + ButtonToolTips.CondenserOutput, + ButtonToolTips.MatterBalls + ); + this.registerApp( + 16 * 7 + 2, + Settings.CONDENSER_OUTPUT, + CondenserOutput.SINGULARITY, + ButtonToolTips.CondenserOutput, + ButtonToolTips.Singularity + ); + + this.registerApp( + 16 * 9 + 1, + Settings.ACCESS, + AccessRestriction.READ, + ButtonToolTips.IOMode, + ButtonToolTips.Read + ); + this.registerApp( + 16 * 9, + Settings.ACCESS, + AccessRestriction.WRITE, + ButtonToolTips.IOMode, + ButtonToolTips.Write + ); + this.registerApp( + 16 * 9 + 2, + Settings.ACCESS, + AccessRestriction.READ_WRITE, + ButtonToolTips.IOMode, + ButtonToolTips.ReadWrite + ); + + this.registerApp( + 16 * 10, + Settings.POWER_UNITS, + PowerUnits.AE, + ButtonToolTips.PowerUnits, + PowerUnits.AE.unlocalizedName + ); + this.registerApp( + 16 * 10 + 1, + Settings.POWER_UNITS, + PowerUnits.EU, + ButtonToolTips.PowerUnits, + PowerUnits.EU.unlocalizedName + ); + this.registerApp( + 16 * 10 + 2, + Settings.POWER_UNITS, + PowerUnits.MK, + ButtonToolTips.PowerUnits, + PowerUnits.MK.unlocalizedName + ); + this.registerApp( + 16 * 10 + 3, + Settings.POWER_UNITS, + PowerUnits.WA, + ButtonToolTips.PowerUnits, + PowerUnits.WA.unlocalizedName + ); + this.registerApp( + 16 * 10 + 4, + Settings.POWER_UNITS, + PowerUnits.RF, + ButtonToolTips.PowerUnits, + PowerUnits.RF.unlocalizedName + ); + + this.registerApp( + 3, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.IGNORE, + ButtonToolTips.RedstoneMode, + ButtonToolTips.AlwaysActive + ); + this.registerApp( + 0, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.LOW_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.ActiveWithoutSignal + ); + this.registerApp( + 1, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.HIGH_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.ActiveWithSignal + ); + this.registerApp( + 2, + Settings.REDSTONE_CONTROLLED, + RedstoneMode.SIGNAL_PULSE, + ButtonToolTips.RedstoneMode, + ButtonToolTips.ActiveOnPulse + ); + + this.registerApp( + 0, + Settings.REDSTONE_EMITTER, + RedstoneMode.LOW_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.EmitLevelsBelow + ); + this.registerApp( + 1, + Settings.REDSTONE_EMITTER, + RedstoneMode.HIGH_SIGNAL, + ButtonToolTips.RedstoneMode, + ButtonToolTips.EmitLevelAbove + ); + + this.registerApp( + 51, + Settings.OPERATION_MODE, + OperationMode.FILL, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToStorageCell + ); + this.registerApp( + 50, + Settings.OPERATION_MODE, + OperationMode.EMPTY, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToNetwork + ); + + this.registerApp( + 51, + Settings.IO_DIRECTION, + RelativeDirection.LEFT, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToStorageCell + ); + this.registerApp( + 50, + Settings.IO_DIRECTION, + RelativeDirection.RIGHT, + ButtonToolTips.TransferDirection, + ButtonToolTips.TransferToNetwork + ); + + this.registerApp( + 48, + Settings.SORT_DIRECTION, + SortDir.ASCENDING, + ButtonToolTips.SortOrder, + ButtonToolTips.ToggleSortDirection + ); + this.registerApp( + 49, + Settings.SORT_DIRECTION, + SortDir.DESCENDING, + ButtonToolTips.SortOrder, + ButtonToolTips.ToggleSortDirection + ); + + this.registerApp( + 16 * 2 + 3, + Settings.SEARCH_MODE, + SearchBoxMode.AUTOSEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_Auto + ); + this.registerApp( + 16 * 2 + 4, + Settings.SEARCH_MODE, + SearchBoxMode.MANUAL_SEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_Standard + ); + this.registerApp( + 16 * 2 + 5, + Settings.SEARCH_MODE, + SearchBoxMode.NEI_AUTOSEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_NEIAuto + ); + this.registerApp( + 16 * 2 + 6, + Settings.SEARCH_MODE, + SearchBoxMode.NEI_MANUAL_SEARCH, + ButtonToolTips.SearchMode, + ButtonToolTips.SearchMode_NEIStandard + ); + + this.registerApp( + 16 * 5 + 3, + Settings.LEVEL_TYPE, + LevelType.ENERGY_LEVEL, + ButtonToolTips.LevelType, + ButtonToolTips.LevelType_Energy + ); + this.registerApp( + 16 * 4 + 3, + Settings.LEVEL_TYPE, + LevelType.ITEM_LEVEL, + ButtonToolTips.LevelType, + ButtonToolTips.LevelType_Item + ); + + this.registerApp( + 16 * 13, + Settings.TERMINAL_STYLE, + TerminalStyle.TALL, + ButtonToolTips.TerminalStyle, + ButtonToolTips.TerminalStyle_Tall + ); + this.registerApp( + 16 * 13 + 1, + Settings.TERMINAL_STYLE, + TerminalStyle.SMALL, + ButtonToolTips.TerminalStyle, + ButtonToolTips.TerminalStyle_Small + ); + this.registerApp( + 16 * 13 + 2, + Settings.TERMINAL_STYLE, + TerminalStyle.FULL, + ButtonToolTips.TerminalStyle, + ButtonToolTips.TerminalStyle_Full + ); + + this.registerApp( + 64, + Settings.SORT_BY, + SortOrder.NAME, + ButtonToolTips.SortBy, + ButtonToolTips.ItemName + ); + this.registerApp( + 65, + Settings.SORT_BY, + SortOrder.AMOUNT, + ButtonToolTips.SortBy, + ButtonToolTips.NumberOfItems + ); + this.registerApp( + 68, + Settings.SORT_BY, + SortOrder.INVTWEAKS, + ButtonToolTips.SortBy, + ButtonToolTips.InventoryTweaks + ); + this.registerApp( + 69, + Settings.SORT_BY, + SortOrder.MOD, + ButtonToolTips.SortBy, + ButtonToolTips.Mod + ); + + this.registerApp( + 66, + Settings.ACTIONS, + ActionItems.WRENCH, + ButtonToolTips.PartitionStorage, + ButtonToolTips.PartitionStorageHint + ); + this.registerApp( + 6, + Settings.ACTIONS, + ActionItems.CLOSE, + ButtonToolTips.Clear, + ButtonToolTips.ClearSettings + ); + this.registerApp( + 6, + Settings.ACTIONS, + ActionItems.STASH, + ButtonToolTips.Stash, + ButtonToolTips.StashDesc + ); + + this.registerApp( + 8, + Settings.ACTIONS, + ActionItems.ENCODE, + ButtonToolTips.Encode, + ButtonToolTips.EncodeDescription + ); + this.registerApp( + 4 + 3 * 16, + Settings.ACTIONS, + ItemSubstitution.ENABLED, + ButtonToolTips.Substitutions, + ButtonToolTips.SubstitutionsDescEnabled + ); + this.registerApp( + 7 + 3 * 16, + Settings.ACTIONS, + ItemSubstitution.DISABLED, + ButtonToolTips.Substitutions, + ButtonToolTips.SubstitutionsDescDisabled + ); + + this.registerApp( + 16, + Settings.VIEW_MODE, + ViewItems.STORED, + ButtonToolTips.View, + ButtonToolTips.StoredItems + ); + this.registerApp( + 18, + Settings.VIEW_MODE, + ViewItems.ALL, + ButtonToolTips.View, + ButtonToolTips.StoredCraftable + ); + this.registerApp( + 19, + Settings.VIEW_MODE, + ViewItems.CRAFTABLE, + ButtonToolTips.View, + ButtonToolTips.Craftable + ); + + this.registerApp( + 16 * 6, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_25, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_25 + ); + this.registerApp( + 16 * 6 + 1, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_50, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_50 + ); + this.registerApp( + 16 * 6 + 2, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_75, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_75 + ); + this.registerApp( + 16 * 6 + 3, + Settings.FUZZY_MODE, + FuzzyMode.PERCENT_99, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZPercent_99 + ); + this.registerApp( + 16 * 6 + 4, + Settings.FUZZY_MODE, + FuzzyMode.IGNORE_ALL, + ButtonToolTips.FuzzyMode, + ButtonToolTips.FZIgnoreAll + ); + + this.registerApp( + 80, + Settings.FULLNESS_MODE, + FullnessMode.EMPTY, + ButtonToolTips.OperationMode, + ButtonToolTips.MoveWhenEmpty + ); + this.registerApp( + 81, + Settings.FULLNESS_MODE, + FullnessMode.HALF, + ButtonToolTips.OperationMode, + ButtonToolTips.MoveWhenWorkIsDone + ); + this.registerApp( + 82, + Settings.FULLNESS_MODE, + FullnessMode.FULL, + ButtonToolTips.OperationMode, + ButtonToolTips.MoveWhenFull + ); + + this.registerApp( + 16 + 5, + Settings.BLOCK, + YesNo.YES, + ButtonToolTips.InterfaceBlockingMode, + ButtonToolTips.Blocking + ); + this.registerApp( + 16 + 4, + Settings.BLOCK, + YesNo.NO, + ButtonToolTips.InterfaceBlockingMode, + ButtonToolTips.NonBlocking + ); + + this.registerApp( + 16 + 3, + Settings.CRAFT_ONLY, + YesNo.YES, + ButtonToolTips.Craft, + ButtonToolTips.CraftOnly + ); + this.registerApp( + 16 + 2, + Settings.CRAFT_ONLY, + YesNo.NO, + ButtonToolTips.Craft, + ButtonToolTips.CraftEither + ); + + this.registerApp( + 16 * 11 + 2, + Settings.CRAFT_VIA_REDSTONE, + YesNo.YES, + ButtonToolTips.EmitterMode, + ButtonToolTips.CraftViaRedstone + ); + this.registerApp( + 16 * 11 + 1, + Settings.CRAFT_VIA_REDSTONE, + YesNo.NO, + ButtonToolTips.EmitterMode, + ButtonToolTips.EmitWhenCrafting + ); + + this.registerApp( + 16 * 3 + 5, + Settings.STORAGE_FILTER, + StorageFilter.EXTRACTABLE_ONLY, + ButtonToolTips.ReportInaccessibleItems, + ButtonToolTips.ReportInaccessibleItemsNo + ); + this.registerApp( + 16 * 3 + 6, + Settings.STORAGE_FILTER, + StorageFilter.NONE, + ButtonToolTips.ReportInaccessibleItems, + ButtonToolTips.ReportInaccessibleItemsYes + ); + + this.registerApp( + 16 * 14, + Settings.PLACE_BLOCK, + YesNo.YES, + ButtonToolTips.BlockPlacement, + ButtonToolTips.BlockPlacementYes + ); + this.registerApp( + 16 * 14 + 1, + Settings.PLACE_BLOCK, + YesNo.NO, + ButtonToolTips.BlockPlacement, + ButtonToolTips.BlockPlacementNo + ); + + this.registerApp( + 16 * 15, + Settings.SCHEDULING_MODE, + SchedulingMode.DEFAULT, + ButtonToolTips.SchedulingMode, + ButtonToolTips.SchedulingModeDefault + ); + this.registerApp( + 16 * 15 + 1, + Settings.SCHEDULING_MODE, + SchedulingMode.ROUNDROBIN, + ButtonToolTips.SchedulingMode, + ButtonToolTips.SchedulingModeRoundRobin + ); + this.registerApp( + 16 * 15 + 2, + Settings.SCHEDULING_MODE, + SchedulingMode.RANDOM, + ButtonToolTips.SchedulingMode, + ButtonToolTips.SchedulingModeRandom + ); + } + } + + private void registerApp( + final int iconIndex, + final Settings setting, + final Enum val, + final ButtonToolTips title, + final Object hint + ) { + final ButtonAppearance a = new ButtonAppearance(); + a.displayName = title.getUnlocalized(); + a.displayValue = (String + ) (hint instanceof String ? hint : ((ButtonToolTips) hint).getUnlocalized()); + a.index = iconIndex; + appearances.put(new EnumPair(setting, val), a); + } + + public void setVisibility(final boolean vis) { + this.visible = vis; + this.enabled = vis; + } + + @Override + public void + drawButton(final Minecraft par1Minecraft, final int par2, final int par3) { + if (this.visible) { + final int iconIndex = this.getIconIndex(); + + if (this.halfSize) { + this.width = 8; + this.height = 8; + + GL11.glPushMatrix(); + GL11.glTranslatef(this.xPosition, this.yPosition, 0.0F); + GL11.glScalef(0.5f, 0.5f, 0.5f); + + if (this.enabled) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } else { + GL11.glColor4f(0.5f, 0.5f, 0.5f, 1.0f); + } + + 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; + + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; + + this.drawTexturedModalRect(0, 0, 256 - 16, 256 - 16, 16, 16); + this.drawTexturedModalRect(0, 0, uv_x * 16, uv_y * 16, 16, 16); + this.mouseDragged(par1Minecraft, par2, par3); + + GL11.glPopMatrix(); + } else { + if (this.enabled) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } else { + GL11.glColor4f(0.5f, 0.5f, 0.5f, 1.0f); + } + + 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; + + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; + + this.drawTexturedModalRect( + this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 + ); + this.drawTexturedModalRect( + this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16 + ); + this.mouseDragged(par1Minecraft, par2, par3); + } + } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } + + private int getIconIndex() { + if (this.buttonSetting != null && this.currentValue != null) { + final ButtonAppearance app + = appearances.get(new EnumPair(this.buttonSetting, this.currentValue)); + if (app == null) { + return 256 - 1; + } + return app.index; + } + return 256 - 1; + } + + public Settings getSetting() { + return (Settings) this.buttonSetting; + } + + public Enum getCurrentValue() { + return this.currentValue; + } + + @Override + public String getMessage() { + String displayName = null; + String displayValue = null; + + if (this.buttonSetting != null && this.currentValue != null) { + final ButtonAppearance buttonAppearance + = appearances.get(new EnumPair(this.buttonSetting, this.currentValue)); + if (buttonAppearance == null) { + return "No Such Message"; + } + + displayName = buttonAppearance.displayName; + displayValue = buttonAppearance.displayValue; + } + + if (displayName != null) { + String name = StatCollector.translateToLocal(displayName); + String value = StatCollector.translateToLocal(displayValue); + + if (name == null || name.isEmpty()) { + name = displayName; + } + if (value == null || value.isEmpty()) { + value = displayValue; + } + + if (this.fillVar != null) { + value = COMPILE.matcher(value).replaceFirst(this.fillVar); + } + + value = PATTERN_NEW_LINE.matcher(value).replaceAll("\n"); + final StringBuilder sb = new StringBuilder(value); + + int i = sb.lastIndexOf("\n"); + if (i <= 0) { + i = 0; + } + while (i + 30 < sb.length() && (i = sb.lastIndexOf(" ", i + 30)) != -1) { + sb.replace(i, i + 1, "\n"); + } + + return name + '\n' + sb; + } + return null; + } + + @Override + public int xPos() { + return this.xPosition; + } + + @Override + public int yPos() { + return this.yPosition; + } + + @Override + public int getWidth() { + return this.halfSize ? 8 : 16; + } + + @Override + public int getHeight() { + return this.halfSize ? 8 : 16; + } + + @Override + public boolean isVisible() { + return this.visible; + } + + public void set(final Enum e) { + if (this.currentValue != e) { + this.currentValue = e; + } + } + + public boolean isHalfSize() { + return this.halfSize; + } + + public void setHalfSize(final boolean halfSize) { + this.halfSize = halfSize; + } + + public String getFillVar() { + return this.fillVar; + } + + public void setFillVar(final String fillVar) { + this.fillVar = fillVar; + } + + private static final class EnumPair { + final Enum setting; + final Enum value; + + EnumPair(final Enum a, final Enum b) { + this.setting = a; + this.value = b; + } + + @Override + public int hashCode() { + return this.setting.hashCode() ^ this.value.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final EnumPair other = (EnumPair) obj; + return other.setting == this.setting && other.value == this.value; + } + } + + private static class ButtonAppearance { + public int index; + public String displayName; + public String displayValue; + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java index 53902366..c36aeeed 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java +++ b/src/main/java/appeng/client/gui/widgets/GuiNumberBox.java @@ -18,46 +18,41 @@ package appeng.client.gui.widgets; - import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiTextField; +public class GuiNumberBox extends GuiTextField { + private final Class type; -public class GuiNumberBox extends GuiTextField -{ + public GuiNumberBox( + final FontRenderer fontRenderer, + final int x, + final int y, + final int width, + final int height, + final Class type + ) { + super(fontRenderer, x, y, width, height); + this.type = type; + } - private final Class type; + @Override + public void writeText(final String selectedText) { + final String original = this.getText(); + super.writeText(selectedText); - public GuiNumberBox( final FontRenderer fontRenderer, final int x, final int y, final int width, final int height, final Class type ) - { - super( fontRenderer, x, y, width, height ); - this.type = type; - } + try { + if (this.type == int.class || this.type == Integer.class) { + Integer.parseInt(this.getText()); - @Override - public void writeText( final String selectedText ) - { - final String original = this.getText(); - super.writeText( selectedText ); + } else if (this.type == long.class || this.type == Long.class) { + Long.parseLong(this.getText()); - try - { - if( this.type == int.class || this.type == Integer.class ) - { - Integer.parseInt( this.getText() ); - } - else if( this.type == long.class || this.type == Long.class ) - { - Long.parseLong( this.getText() ); - } - else if( this.type == double.class || this.type == Double.class ) - { - Double.parseDouble( this.getText() ); - } - } - catch( final NumberFormatException e ) - { - this.setText( original ); - } - } + } else if (this.type == double.class || this.type == Double.class) { + Double.parseDouble(this.getText()); + } + } catch (final 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 90bc58cf..44df8465 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiProgressBar.java @@ -18,117 +18,135 @@ package appeng.client.gui.widgets; - import appeng.container.interfaces.IProgressProvider; import appeng.core.localization.GuiText; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.util.ResourceLocation; +public class GuiProgressBar extends GuiButton implements ITooltip { + private final IProgressProvider source; + private final ResourceLocation texture; + private final int fill_u; + private final int fill_v; + private final Direction layout; + private final String titleName; + private String fullMsg; -public class GuiProgressBar extends GuiButton implements ITooltip -{ + public GuiProgressBar( + final IProgressProvider source, + final String texture, + final int posX, + final int posY, + final int u, + final int y, + final int width, + final int height, + final Direction dir + ) { + this(source, texture, posX, posY, u, y, width, height, dir, null); + } - private final IProgressProvider source; - private final ResourceLocation texture; - private final int fill_u; - private final int fill_v; - private final Direction layout; - private final String titleName; - private String fullMsg; + public GuiProgressBar( + final IProgressProvider source, + final String texture, + final int posX, + final int posY, + final int u, + final int y, + final int width, + final int height, + final Direction dir, + final String title + ) { + super(posX, posY, width, ""); + this.source = source; + this.xPosition = posX; + this.yPosition = posY; + this.texture = new ResourceLocation("appliedenergistics2", "textures/" + texture); + this.width = width; + this.height = height; + this.fill_u = u; + this.fill_v = y; + this.layout = dir; + this.titleName = title; + } - public GuiProgressBar( final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir ) - { - this( source, texture, posX, posY, u, y, width, height, dir, null ); - } + @Override + public void + drawButton(final Minecraft par1Minecraft, final int par2, final int par3) { + if (this.visible) { + par1Minecraft.getTextureManager().bindTexture(this.texture); + final int max = this.source.getMaxProgress(); + final int current = this.source.getCurrentProgress(); - public GuiProgressBar( final IProgressProvider source, final String texture, final int posX, final int posY, final int u, final int y, final int width, final int height, final Direction dir, final String title ) - { - super( posX, posY, width, "" ); - this.source = source; - this.xPosition = posX; - this.yPosition = posY; - this.texture = new ResourceLocation( "appliedenergistics2", "textures/" + texture ); - this.width = width; - this.height = height; - this.fill_u = u; - this.fill_v = y; - this.layout = dir; - this.titleName = title; - } + if (this.layout == Direction.VERTICAL) { + final 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 { + final 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 + ); + } - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3 ) - { - if( this.visible ) - { - par1Minecraft.getTextureManager().bindTexture( this.texture ); - final int max = this.source.getMaxProgress(); - final int current = this.source.getCurrentProgress(); + this.mouseDragged(par1Minecraft, par2, par3); + } + } - if( this.layout == Direction.VERTICAL ) - { - final 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 - { - final 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 ); - } + public void setFullMsg(final String msg) { + this.fullMsg = msg; + } - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } + @Override + public String getMessage() { + if (this.fullMsg != null) { + return this.fullMsg; + } - public void setFullMsg( final String msg ) - { - this.fullMsg = msg; - } + return (this.titleName != null ? this.titleName : "") + '\n' + + this.source.getCurrentProgress() + ' ' + GuiText.Of.getLocal() + ' ' + + this.source.getMaxProgress(); + } - @Override - public String getMessage() - { - if( this.fullMsg != null ) - { - return this.fullMsg; - } + @Override + public int xPos() { + return this.xPosition - 2; + } - return ( this.titleName != null ? this.titleName : "" ) + '\n' + this.source.getCurrentProgress() + ' ' + GuiText.Of.getLocal() + ' ' + this.source.getMaxProgress(); - } + @Override + public int yPos() { + return this.yPosition - 2; + } - @Override - public int xPos() - { - return this.xPosition - 2; - } + @Override + public int getWidth() { + return this.width + 4; + } - @Override - public int yPos() - { - return this.yPosition - 2; - } + @Override + public int getHeight() { + return this.height + 4; + } - @Override - public int getWidth() - { - return this.width + 4; - } + @Override + public boolean isVisible() { + return true; + } - @Override - public int getHeight() - { - return this.height + 4; - } - - @Override - public boolean isVisible() - { - return true; - } - - public enum Direction - { - HORIZONTAL, VERTICAL - } + 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 6171738f..a13b7bf5 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java +++ b/src/main/java/appeng/client/gui/widgets/GuiScrollbar.java @@ -18,137 +18,118 @@ package appeng.client.gui.widgets; - import appeng.client.gui.AEBaseGui; import org.lwjgl.opengl.GL11; +public class GuiScrollbar implements IScrollSource { + private int displayX = 0; + private int displayY = 0; + private int width = 12; + private int height = 16; + private int pageSize = 1; -public class GuiScrollbar implements IScrollSource -{ + private int maxScroll = 0; + private int minScroll = 0; + private int currentScroll = 0; - private int displayX = 0; - private int displayY = 0; - private int width = 12; - private int height = 16; - private int pageSize = 1; + public void draw(final AEBaseGui g) { + g.bindTexture("minecraft", "gui/container/creative_inventory/tabs.png"); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - private int maxScroll = 0; - private int minScroll = 0; - private int currentScroll = 0; + if (this.getRange() == 0) { + g.drawTexturedModalRect( + this.displayX, this.displayY, 232 + this.width, 0, this.width, 15 + ); + } else { + final int offset = (this.currentScroll - this.minScroll) * (this.height - 15) + / this.getRange(); + g.drawTexturedModalRect( + this.displayX, offset + this.displayY, 232, 0, this.width, 15 + ); + } + } - public void draw( final AEBaseGui g ) - { - g.bindTexture( "minecraft", "gui/container/creative_inventory/tabs.png" ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + private int getRange() { + return this.maxScroll - this.minScroll; + } - if( this.getRange() == 0 ) - { - g.drawTexturedModalRect( this.displayX, this.displayY, 232 + this.width, 0, this.width, 15 ); - } - else - { - final int offset = ( this.currentScroll - this.minScroll ) * ( this.height - 15 ) / this.getRange(); - g.drawTexturedModalRect( this.displayX, offset + this.displayY, 232, 0, this.width, 15 ); - } - } + public int getLeft() { + return this.displayX; + } - private int getRange() - { - return this.maxScroll - this.minScroll; - } + public GuiScrollbar setLeft(final int v) { + this.displayX = v; + return this; + } - public int getLeft() - { - return this.displayX; - } + public int getTop() { + return this.displayY; + } - public GuiScrollbar setLeft( final int v ) - { - this.displayX = v; - return this; - } + public GuiScrollbar setTop(final int v) { + this.displayY = v; + return this; + } - public int getTop() - { - return this.displayY; - } + public int getWidth() { + return this.width; + } - public GuiScrollbar setTop( final int v ) - { - this.displayY = v; - return this; - } + public GuiScrollbar setWidth(final int v) { + this.width = v; + return this; + } - public int getWidth() - { - return this.width; - } + public int getHeight() { + return this.height; + } - public GuiScrollbar setWidth( final int v ) - { - this.width = v; - return this; - } + public GuiScrollbar setHeight(final int v) { + this.height = v; + return this; + } - public int getHeight() - { - return this.height; - } + public void setRange(final int min, final int max, final int pageSize) { + this.minScroll = min; + this.maxScroll = max; + this.pageSize = pageSize; - public GuiScrollbar setHeight( final int v ) - { - this.height = v; - return this; - } + if (this.minScroll > this.maxScroll) { + this.maxScroll = this.minScroll; + } - public void setRange( final int min, final int max, final int pageSize ) - { - this.minScroll = min; - this.maxScroll = max; - this.pageSize = pageSize; + this.applyRange(); + } - if( this.minScroll > this.maxScroll ) - { - this.maxScroll = this.minScroll; - } + private void applyRange() { + this.currentScroll + = Math.max(Math.min(this.currentScroll, this.maxScroll), this.minScroll); + } - this.applyRange(); - } + @Override + public int getCurrentScroll() { + return this.currentScroll; + } - private void applyRange() - { - this.currentScroll = Math.max( Math.min( this.currentScroll, this.maxScroll ), this.minScroll ); - } + public void click(final AEBaseGui aeBaseGui, final int x, final int y) { + if (this.getRange() == 0) { + return; + } - @Override - public int getCurrentScroll() - { - return this.currentScroll; - } + if (x > this.displayX && x <= this.displayX + this.width) { + 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.applyRange(); + } + } + } - public void click( final AEBaseGui aeBaseGui, final int x, final int y ) - { - if( this.getRange() == 0 ) - { - return; - } - - if( x > this.displayX && x <= this.displayX + this.width ) - { - 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.applyRange(); - } - } - } - - public void wheel( int delta ) - { - delta = Math.max( Math.min( -delta, 1 ), -1 ); - this.currentScroll += delta * this.pageSize; - this.applyRange(); - } + 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 54c0f7ac..b2f7e2b5 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java @@ -18,7 +18,6 @@ package appeng.client.gui.widgets; - import appeng.client.texture.ExtraBlockTextures; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; @@ -29,135 +28,145 @@ import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; +public class GuiTabButton extends GuiButton implements ITooltip { + private final RenderItem itemRenderer; + private final String message; + private int hideEdge = 0; + private int myIcon = -1; + private ItemStack myItem; -public class GuiTabButton extends GuiButton implements ITooltip -{ - private final RenderItem itemRenderer; - private final String message; - private int hideEdge = 0; - private int myIcon = -1; - private ItemStack myItem; + public GuiTabButton( + final int x, final int y, final int ico, final String message, final RenderItem ir + ) { + super(0, 0, 16, ""); - public GuiTabButton( final int x, final int y, final int ico, final String message, final RenderItem ir ) - { - super( 0, 0, 16, "" ); + this.xPosition = x; + this.yPosition = y; + this.width = 22; + this.height = 22; + this.myIcon = ico; + this.message = message; + this.itemRenderer = ir; + } - this.xPosition = x; - this.yPosition = y; - this.width = 22; - this.height = 22; - this.myIcon = ico; - this.message = message; - this.itemRenderer = ir; - } + /** + * Using itemstack as an 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 + */ + public GuiTabButton( + final int x, + final int y, + final ItemStack ico, + final String message, + final RenderItem ir + ) { + super(0, 0, 16, ""); + this.xPosition = x; + this.yPosition = y; + this.width = 22; + this.height = 22; + this.myItem = ico; + this.message = message; + this.itemRenderer = ir; + } - /** - * Using itemstack as an 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 - */ - public GuiTabButton( final int x, final int y, final ItemStack ico, final String message, final RenderItem ir ) - { - super( 0, 0, 16, "" ); - this.xPosition = x; - this.yPosition = y; - this.width = 22; - this.height = 22; - this.myItem = ico; - this.message = message; - this.itemRenderer = ir; - } + @Override + public void drawButton(final Minecraft minecraft, final int x, final int y) { + if (this.visible) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + minecraft.renderEngine.bindTexture( + ExtraBlockTextures.GuiTexture("guis/states.png") + ); + this.field_146123_n = x >= this.xPosition && y >= this.yPosition + && x < this.xPosition + this.width && y < this.yPosition + this.height; - @Override - public void drawButton( final Minecraft minecraft, final int x, final int y ) - { - if( this.visible ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - minecraft.renderEngine.bindTexture( ExtraBlockTextures.GuiTexture( "guis/states.png" ) ); - this.field_146123_n = x >= this.xPosition && y >= this.yPosition && x < this.xPosition + this.width && y < this.yPosition + this.height; + int uv_x = (this.hideEdge > 0 ? 11 : 13); - int uv_x = ( this.hideEdge > 0 ? 11 : 13 ); + final int offsetX = this.hideEdge > 0 ? 1 : 0; - final int offsetX = this.hideEdge > 0 ? 1 : 0; + this.drawTexturedModalRect( + this.xPosition, this.yPosition, uv_x * 16, 0, 25, 22 + ); - this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, 0, 25, 22 ); + if (this.myIcon >= 0) { + final int uv_y = (int) Math.floor(this.myIcon / 16); + uv_x = this.myIcon - uv_y * 16; - if( this.myIcon >= 0 ) - { - final 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 + ); + } - this.drawTexturedModalRect( offsetX + this.xPosition + 3, this.yPosition + 3, uv_x * 16, uv_y * 16, 16, 16 ); - } + this.mouseDragged(minecraft, x, y); - this.mouseDragged( minecraft, x, y ); + if (this.myItem != null) { + this.zLevel = 100.0F; + this.itemRenderer.zLevel = 100.0F; - if( this.myItem != null ) - { - this.zLevel = 100.0F; - this.itemRenderer.zLevel = 100.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + RenderHelper.enableGUIStandardItemLighting(); + final FontRenderer fontrenderer = minecraft.fontRenderer; + this.itemRenderer.renderItemAndEffectIntoGUI( + fontrenderer, + minecraft.renderEngine, + this.myItem, + offsetX + this.xPosition + 3, + this.yPosition + 3 + ); + GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - RenderHelper.enableGUIStandardItemLighting(); - final FontRenderer fontrenderer = minecraft.fontRenderer; - this.itemRenderer.renderItemAndEffectIntoGUI( fontrenderer, minecraft.renderEngine, this.myItem, offsetX + this.xPosition + 3, this.yPosition + 3 ); - GL11.glDisable( GL11.GL_LIGHTING ); + this.itemRenderer.zLevel = 0.0F; + this.zLevel = 0.0F; + } + } + } - this.itemRenderer.zLevel = 0.0F; - this.zLevel = 0.0F; - } - } - } + @Override + public String getMessage() { + return this.message; + } - @Override - public String getMessage() - { - return this.message; - } + @Override + public int xPos() { + return this.xPosition; + } - @Override - public int xPos() - { - return this.xPosition; - } + @Override + public int yPos() { + return this.yPosition; + } - @Override - public int yPos() - { - return this.yPosition; - } + @Override + public int getWidth() { + return 22; + } - @Override - public int getWidth() - { - return 22; - } + @Override + public int getHeight() { + return 22; + } - @Override - public int getHeight() - { - return 22; - } + @Override + public boolean isVisible() { + return this.visible; + } - @Override - public boolean isVisible() - { - return this.visible; - } + public int getHideEdge() { + return this.hideEdge; + } - public int getHideEdge() - { - return this.hideEdge; - } - - public void setHideEdge( final int hideEdge ) - { - this.hideEdge = hideEdge; - } + public void setHideEdge(final int hideEdge) { + this.hideEdge = hideEdge; + } } diff --git a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java index 6477d2b4..d85a673e 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java @@ -18,6 +18,7 @@ package appeng.client.gui.widgets; +import java.util.regex.Pattern; import appeng.client.texture.ExtraBlockTextures; import net.minecraft.client.Minecraft; @@ -25,125 +26,122 @@ import net.minecraft.client.gui.GuiButton; import net.minecraft.util.StatCollector; import org.lwjgl.opengl.GL11; -import java.util.regex.Pattern; +public class GuiToggleButton extends GuiButton implements ITooltip { + private static final Pattern PATTERN_NEW_LINE + = Pattern.compile("\\n", Pattern.LITERAL); + private final int iconIdxOn; + private final int iconIdxOff; + private final String displayName; + private final String displayHint; -public class GuiToggleButton extends GuiButton implements ITooltip -{ - private static final Pattern PATTERN_NEW_LINE = Pattern.compile( "\\n", Pattern.LITERAL ); - private final int iconIdxOn; - private final int iconIdxOff; + private boolean isActive; - private final String displayName; - private final String displayHint; + public GuiToggleButton( + final int x, + final int y, + final int on, + final int off, + final String displayName, + final String displayHint + ) { + super(0, 0, 16, ""); + this.iconIdxOn = on; + this.iconIdxOff = off; + this.displayName = displayName; + this.displayHint = displayHint; + this.xPosition = x; + this.yPosition = y; + this.width = 16; + this.height = 16; + } - private boolean isActive; + public void setState(final boolean isOn) { + this.isActive = isOn; + } - public GuiToggleButton( final int x, final int y, final int on, final int off, final String displayName, final String displayHint ) - { - super( 0, 0, 16, "" ); - this.iconIdxOn = on; - this.iconIdxOff = off; - this.displayName = displayName; - this.displayHint = displayHint; - this.xPosition = x; - this.yPosition = y; - this.width = 16; - this.height = 16; - } + @Override + public void + drawButton(final Minecraft par1Minecraft, final int par2, final int par3) { + if (this.visible) { + final int iconIndex = this.getIconIndex(); - public void setState( final boolean isOn ) - { - this.isActive = isOn; - } + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + 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; - @Override - public void drawButton( final Minecraft par1Minecraft, final int par2, final int par3 ) - { - if( this.visible ) - { - final int iconIndex = this.getIconIndex(); + final int uv_y = (int) Math.floor(iconIndex / 16); + final int uv_x = iconIndex - uv_y * 16; - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - 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; + this.drawTexturedModalRect( + this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 + ); + this.drawTexturedModalRect( + this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16 + ); + this.mouseDragged(par1Minecraft, par2, par3); + } + } - final int uv_y = (int) Math.floor( iconIndex / 16 ); - final int uv_x = iconIndex - uv_y * 16; + private int getIconIndex() { + return this.isActive ? this.iconIdxOn : this.iconIdxOff; + } - this.drawTexturedModalRect( this.xPosition, this.yPosition, 256 - 16, 256 - 16, 16, 16 ); - this.drawTexturedModalRect( this.xPosition, this.yPosition, uv_x * 16, uv_y * 16, 16, 16 ); - this.mouseDragged( par1Minecraft, par2, par3 ); - } - } + @Override + public String getMessage() { + if (this.displayName != null) { + String name = StatCollector.translateToLocal(this.displayName); + String value = StatCollector.translateToLocal(this.displayHint); - private int getIconIndex() - { - return this.isActive ? this.iconIdxOn : this.iconIdxOff; - } + if (name == null || name.isEmpty()) { + name = this.displayName; + } + if (value == null || value.isEmpty()) { + value = this.displayHint; + } - @Override - public String getMessage() - { - if( this.displayName != null ) - { - String name = StatCollector.translateToLocal( this.displayName ); - String value = StatCollector.translateToLocal( this.displayHint ); + value = PATTERN_NEW_LINE.matcher(value).replaceAll("\n"); + final StringBuilder sb = new StringBuilder(value); - if( name == null || name.isEmpty() ) - { - name = this.displayName; - } - if( value == null || value.isEmpty() ) - { - value = this.displayHint; - } + int i = sb.lastIndexOf("\n"); + if (i <= 0) { + i = 0; + } + while (i + 30 < sb.length() && (i = sb.lastIndexOf(" ", i + 30)) != -1) { + sb.replace(i, i + 1, "\n"); + } - value = PATTERN_NEW_LINE.matcher( value ).replaceAll( "\n" ); - final StringBuilder sb = new StringBuilder( value ); + return name + '\n' + sb; + } + return null; + } - int i = sb.lastIndexOf( "\n" ); - if( i <= 0 ) - { - i = 0; - } - while( i + 30 < sb.length() && ( i = sb.lastIndexOf( " ", i + 30 ) ) != -1 ) - { - sb.replace( i, i + 1, "\n" ); - } + @Override + public int xPos() { + return this.xPosition; + } - return name + '\n' + sb; - } - return null; - } + @Override + public int yPos() { + return this.yPosition; + } - @Override - public int xPos() - { - return this.xPosition; - } + @Override + public int getWidth() { + return 16; + } - @Override - public int yPos() - { - return this.yPosition; - } + @Override + public int getHeight() { + return 16; + } - @Override - public int getWidth() - { - return 16; - } - - @Override - public int getHeight() - { - return 16; - } - - @Override - public boolean isVisible() - { - return this.visible; - } + @Override + public boolean isVisible() { + return this.visible; + } } diff --git a/src/main/java/appeng/client/gui/widgets/IScrollSource.java b/src/main/java/appeng/client/gui/widgets/IScrollSource.java index 10829091..207fe881 100644 --- a/src/main/java/appeng/client/gui/widgets/IScrollSource.java +++ b/src/main/java/appeng/client/gui/widgets/IScrollSource.java @@ -18,9 +18,6 @@ package appeng.client.gui.widgets; - -public interface IScrollSource -{ - - int getCurrentScroll(); +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 534dcb0d..057415d6 100644 --- a/src/main/java/appeng/client/gui/widgets/ISortSource.java +++ b/src/main/java/appeng/client/gui/widgets/ISortSource.java @@ -18,26 +18,22 @@ package appeng.client.gui.widgets; - import appeng.api.config.SortDir; import appeng.api.config.ViewItems; +public interface ISortSource { + /** + * @return Sor + */ + Enum getSortBy(); -public interface ISortSource -{ + /** + * @return {@link SortDir} + */ + Enum getSortDir(); - /** - * @return Sor - */ - Enum getSortBy(); - - /** - * @return {@link SortDir} - */ - Enum getSortDir(); - - /** - * @return {@link ViewItems} - */ - Enum getSortDisplay(); + /** + * @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 232992ac..f08412ba 100644 --- a/src/main/java/appeng/client/gui/widgets/ITooltip.java +++ b/src/main/java/appeng/client/gui/widgets/ITooltip.java @@ -18,50 +18,47 @@ package appeng.client.gui.widgets; - /** * AEBaseGui controlled Tooltip Interface. */ -public interface ITooltip -{ +public interface ITooltip { + /** + * returns the tooltip message. + * + * @return tooltip message + */ + String getMessage(); - /** - * returns the tooltip message. - * - * @return tooltip message - */ - String getMessage(); + /** + * x Location for the object that triggers the tooltip. + * + * @return xPosition + */ + int xPos(); - /** - * x Location for the object that triggers the tooltip. - * - * @return xPosition - */ - int xPos(); + /** + * y Location for the object that triggers the tooltip. + * + * @return yPosition + */ + int yPos(); - /** - * y Location for the object that triggers the tooltip. - * - * @return yPosition - */ - int yPos(); + /** + * Width of the object that triggers the tooltip. + * + * @return width + */ + int getWidth(); - /** - * Width of the object that triggers the tooltip. - * - * @return width - */ - int getWidth(); + /** + * Height for the object that triggers the tooltip. + * + * @return height + */ + int getHeight(); - /** - * Height for the object that triggers the tooltip. - * - * @return height - */ - int getHeight(); - - /** - * @return true if button being drawn - */ - boolean isVisible(); + /** + * @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 b3e1823c..f22a5169 100644 --- a/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java +++ b/src/main/java/appeng/client/gui/widgets/MEGuiTextField.java @@ -18,11 +18,9 @@ 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. @@ -31,57 +29,67 @@ import net.minecraft.client.gui.GuiTextField; *

* The rendering does pay attention to the size of the '_' caret. */ -public class MEGuiTextField extends GuiTextField -{ - private static final int PADDING = 2; +public class MEGuiTextField extends GuiTextField { + private static final int PADDING = 2; - private final int _xPos; - private final int _yPos; - private final int _width; - private final int _height; + private final int _xPos; + private final int _yPos; + private final int _width; + private final int _height; - /** - * Uses the values to instantiate a padded version of a text field. - * 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 - */ - public MEGuiTextField( final FontRenderer fontRenderer, final int xPos, final int yPos, final int width, final int height ) - { - super( fontRenderer, xPos + PADDING, yPos + PADDING, width - 2 * PADDING - fontRenderer.getCharWidth( '_' ), height - 2 * PADDING ); + /** + * Uses the values to instantiate a padded version of a text field. + * 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 + */ + public MEGuiTextField( + final FontRenderer fontRenderer, + final int xPos, + final int yPos, + final int width, + final int height + ) { + super( + fontRenderer, + xPos + PADDING, + yPos + PADDING, + width - 2 * PADDING - fontRenderer.getCharWidth('_'), + height - 2 * PADDING + ); - this._xPos = xPos; - this._yPos = yPos; - this._width = width; - this._height = height; - } + this._xPos = xPos; + this._yPos = yPos; + this._width = width; + this._height = height; + } - @Override - public void mouseClicked( final int xPos, final int yPos, final int button ) - { - super.mouseClicked( xPos, yPos, button ); + @Override + public void mouseClicked(final int xPos, final int yPos, final int button) { + super.mouseClicked(xPos, yPos, button); - final boolean requiresFocus = this.isMouseIn( xPos, yPos ); + final boolean requiresFocus = this.isMouseIn(xPos, yPos); - this.setFocused( requiresFocus ); - } + this.setFocused(requiresFocus); + } - /** - * Checks if the mouse is within the element - * - * @param xCoord current x coord of the mouse - * @param yCoord current y coord of the mouse - * @return true if mouse position is within the text field area - */ - public boolean isMouseIn( final int xCoord, final int yCoord ) - { - final boolean withinXRange = this._xPos <= xCoord && xCoord < this._xPos + this._width; - final boolean withinYRange = this._yPos <= yCoord && yCoord < this._yPos + this._height; + /** + * Checks if the mouse is within the element + * + * @param xCoord current x coord of the mouse + * @param yCoord current y coord of the mouse + * @return true if mouse position is within the text field area + */ + public boolean isMouseIn(final int xCoord, final int yCoord) { + final boolean withinXRange + = this._xPos <= xCoord && xCoord < this._xPos + this._width; + final boolean withinYRange + = this._yPos <= yCoord && yCoord < this._yPos + this._height; - return withinXRange && withinYRange; - } + return withinXRange && withinYRange; + } } diff --git a/src/main/java/appeng/client/me/ClientDCInternalInv.java b/src/main/java/appeng/client/me/ClientDCInternalInv.java index 3b19e920..04962aae 100644 --- a/src/main/java/appeng/client/me/ClientDCInternalInv.java +++ b/src/main/java/appeng/client/me/ClientDCInternalInv.java @@ -18,54 +18,46 @@ package appeng.client.me; +import javax.annotation.Nonnull; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.ItemSorters; import net.minecraft.util.StatCollector; -import javax.annotation.Nonnull; +public class ClientDCInternalInv implements Comparable { + private final String unlocalizedName; + private final AppEngInternalInventory inventory; + private final long id; + private final long sortBy; -public class ClientDCInternalInv implements Comparable -{ + public ClientDCInternalInv( + final int size, final long id, final long sortBy, final String unlocalizedName + ) { + this.inventory = new AppEngInternalInventory(null, size); + this.unlocalizedName = unlocalizedName; + this.id = id; + this.sortBy = sortBy; + } - private final String unlocalizedName; - private final AppEngInternalInventory inventory; + public String getName() { + final String s = StatCollector.translateToLocal(this.unlocalizedName + ".name"); + if (s.equals(this.unlocalizedName + ".name")) { + return StatCollector.translateToLocal(this.unlocalizedName); + } + return s; + } - private final long id; - private final long sortBy; + @Override + public int compareTo(@Nonnull final ClientDCInternalInv o) { + return ItemSorters.compareLong(this.sortBy, o.sortBy); + } - public ClientDCInternalInv( final int size, final long id, final long sortBy, final String unlocalizedName ) - { - this.inventory = new AppEngInternalInventory( null, size ); - this.unlocalizedName = unlocalizedName; - this.id = id; - this.sortBy = sortBy; - } + public AppEngInternalInventory getInventory() { + return this.inventory; + } - public String getName() - { - final String s = StatCollector.translateToLocal( this.unlocalizedName + ".name" ); - if( s.equals( this.unlocalizedName + ".name" ) ) - { - return StatCollector.translateToLocal( this.unlocalizedName ); - } - return s; - } - - @Override - public int compareTo( @Nonnull final ClientDCInternalInv o ) - { - return ItemSorters.compareLong( this.sortBy, o.sortBy ); - } - - public AppEngInternalInventory getInventory() - { - return this.inventory; - } - - public long getId() - { - return this.id; - } + public long getId() { + return this.id; + } } \ 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 3128932f..63a28045 100644 --- a/src/main/java/appeng/client/me/InternalSlotME.java +++ b/src/main/java/appeng/client/me/InternalSlotME.java @@ -18,49 +18,41 @@ package appeng.client.me; - import appeng.api.storage.data.IAEItemStack; import net.minecraft.item.ItemStack; +public class InternalSlotME { + private final int offset; + private final int xPos; + private final int yPos; + private final ItemRepo repo; -public class InternalSlotME -{ + public InternalSlotME( + final ItemRepo def, final int offset, final int displayX, final int displayY + ) { + this.repo = def; + this.offset = offset; + this.xPos = displayX; + this.yPos = displayY; + } - private final int offset; - private final int xPos; - private final int yPos; - private final ItemRepo repo; + ItemStack getStack() { + return this.repo.getItem(this.offset); + } - public InternalSlotME( final ItemRepo def, final int offset, final int displayX, final int displayY ) - { - this.repo = def; - this.offset = offset; - this.xPos = displayX; - this.yPos = displayY; - } + IAEItemStack getAEStack() { + return this.repo.getReferenceItem(this.offset); + } - ItemStack getStack() - { - return this.repo.getItem( this.offset ); - } + boolean hasPower() { + return this.repo.hasPower(); + } - IAEItemStack getAEStack() - { - return this.repo.getReferenceItem( this.offset ); - } + int getxPosition() { + return this.xPos; + } - boolean hasPower() - { - return this.repo.hasPower(); - } - - int getxPosition() - { - return this.xPos; - } - - int getyPosition() - { - return this.yPos; - } + int getyPosition() { + return this.yPos; + } } diff --git a/src/main/java/appeng/client/me/ItemRepo.java b/src/main/java/appeng/client/me/ItemRepo.java index 394e8ae6..fcf3de55 100644 --- a/src/main/java/appeng/client/me/ItemRepo.java +++ b/src/main/java/appeng/client/me/ItemRepo.java @@ -18,6 +18,12 @@ package appeng.client.me; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.regex.Pattern; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.config.*; @@ -33,273 +39,223 @@ import appeng.util.prioitylist.IPartitionList; import cpw.mods.fml.relauncher.ReflectionHelper; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.regex.Pattern; +public class ItemRepo { + private final IItemList list + = AEApi.instance().storage().createItemList(); + private final ArrayList view = new ArrayList(); + private final ArrayList dsp = new ArrayList(); + private final IScrollSource src; + private final ISortSource sortSrc; + private int rowSize = 9; -public class ItemRepo -{ + private String searchString = ""; + private IPartitionList myPartitionList; + private String innerSearch = ""; + private String NEIWord = null; + private boolean hasPower; - private final IItemList list = AEApi.instance().storage().createItemList(); - private final ArrayList view = new ArrayList(); - private final ArrayList dsp = new ArrayList(); - private final IScrollSource src; - private final ISortSource sortSrc; + public ItemRepo(final IScrollSource src, final ISortSource sortSrc) { + this.src = src; + this.sortSrc = sortSrc; + } - private int rowSize = 9; + public IAEItemStack getReferenceItem(int idx) { + idx += this.src.getCurrentScroll() * this.rowSize; - private String searchString = ""; - private IPartitionList myPartitionList; - private String innerSearch = ""; - private String NEIWord = null; - private boolean hasPower; + if (idx >= this.view.size()) { + return null; + } + return this.view.get(idx); + } - public ItemRepo( final IScrollSource src, final ISortSource sortSrc ) - { - this.src = src; - this.sortSrc = sortSrc; - } + public ItemStack getItem(int idx) { + idx += this.src.getCurrentScroll() * this.rowSize; - public IAEItemStack getReferenceItem( int idx ) - { - idx += this.src.getCurrentScroll() * this.rowSize; + if (idx >= this.dsp.size()) { + return null; + } + return this.dsp.get(idx); + } - if( idx >= this.view.size() ) - { - return null; - } - return this.view.get( idx ); - } + void setSearch(final String search) { + this.searchString = search == null ? "" : search; + } - public ItemStack getItem( int idx ) - { - idx += this.src.getCurrentScroll() * this.rowSize; + public void postUpdate(final IAEItemStack is) { + final IAEItemStack st = this.list.findPrecise(is); - if( idx >= this.dsp.size() ) - { - return null; - } - return this.dsp.get( idx ); - } + if (st != null) { + st.reset(); + st.add(is); + } else { + this.list.add(is); + } + } - void setSearch( final String search ) - { - this.searchString = search == null ? "" : search; - } + public void setViewCell(final ItemStack[] list) { + this.myPartitionList = ItemViewCell.createFilter(list); + this.updateView(); + } - public void postUpdate( final IAEItemStack is ) - { - final IAEItemStack st = this.list.findPrecise( is ); + public void updateView() { + this.view.clear(); + this.dsp.clear(); - if( st != null ) - { - st.reset(); - st.add( is ); - } - else - { - this.list.add( is ); - } - } + this.view.ensureCapacity(this.list.size()); + this.dsp.ensureCapacity(this.list.size()); - public void setViewCell( final ItemStack[] list ) - { - this.myPartitionList = ItemViewCell.createFilter( list ); - this.updateView(); - } + final Enum viewMode = this.sortSrc.getSortDisplay(); + final Enum searchMode + = AEConfig.instance.settings.getSetting(Settings.SEARCH_MODE); + if (searchMode == SearchBoxMode.NEI_AUTOSEARCH + || searchMode == SearchBoxMode.NEI_MANUAL_SEARCH) { + this.updateNEI(this.searchString); + } - public void updateView() - { - this.view.clear(); - this.dsp.clear(); + this.innerSearch = this.searchString; + final boolean terminalSearchToolTips + = AEConfig.instance.settings.getSetting(Settings.SEARCH_TOOLTIPS) != YesNo.NO; + // boolean terminalSearchMods = Configuration.INSTANCE.settings.getSetting( + // Settings.SEARCH_MODS ) != YesNo.NO; - this.view.ensureCapacity( this.list.size() ); - this.dsp.ensureCapacity( this.list.size() ); + boolean searchMod = false; + if (this.innerSearch.startsWith("@")) { + searchMod = true; + this.innerSearch = this.innerSearch.substring(1); + } - final Enum viewMode = this.sortSrc.getSortDisplay(); - final Enum searchMode = AEConfig.instance.settings.getSetting( Settings.SEARCH_MODE ); - if( searchMode == SearchBoxMode.NEI_AUTOSEARCH || searchMode == SearchBoxMode.NEI_MANUAL_SEARCH ) - { - this.updateNEI( this.searchString ); - } + Pattern m = null; + try { + m = Pattern.compile(this.innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE); + } catch (final Throwable ignore) { + try { + m = Pattern.compile( + Pattern.quote(this.innerSearch.toLowerCase()), + Pattern.CASE_INSENSITIVE + ); + } catch (final Throwable __) { + return; + } + } - this.innerSearch = this.searchString; - final boolean terminalSearchToolTips = AEConfig.instance.settings.getSetting( Settings.SEARCH_TOOLTIPS ) != YesNo.NO; - // boolean terminalSearchMods = Configuration.INSTANCE.settings.getSetting( Settings.SEARCH_MODS ) != YesNo.NO; + boolean notDone = false; + for (IAEItemStack is : this.list) { + if (this.myPartitionList != null) { + if (!this.myPartitionList.isListed(is)) { + continue; + } + } - boolean searchMod = false; - if( this.innerSearch.startsWith( "@" ) ) - { - searchMod = true; - this.innerSearch = this.innerSearch.substring( 1 ); - } + if (viewMode == ViewItems.CRAFTABLE && !is.isCraftable()) { + continue; + } - Pattern m = null; - try - { - m = Pattern.compile( this.innerSearch.toLowerCase(), Pattern.CASE_INSENSITIVE ); - } - catch( final Throwable ignore ) - { - try - { - m = Pattern.compile( Pattern.quote( this.innerSearch.toLowerCase() ), Pattern.CASE_INSENSITIVE ); - } - catch( final Throwable __ ) - { - return; - } - } + if (viewMode == ViewItems.CRAFTABLE) { + is = is.copy(); + is.setStackSize(0); + } - boolean notDone = false; - for( IAEItemStack is : this.list ) - { - if( this.myPartitionList != null ) - { - if( !this.myPartitionList.isListed( is ) ) - { - continue; - } - } + if (viewMode == ViewItems.STORED && is.getStackSize() == 0) { + continue; + } - if( viewMode == ViewItems.CRAFTABLE && !is.isCraftable() ) - { - continue; - } + final String dspName + = searchMod ? Platform.getModId(is) : Platform.getItemDisplayName(is); + notDone = true; - if( viewMode == ViewItems.CRAFTABLE ) - { - is = is.copy(); - is.setStackSize( 0 ); - } + if (m.matcher(dspName.toLowerCase()).find()) { + this.view.add(is); + notDone = false; + } - if( viewMode == ViewItems.STORED && is.getStackSize() == 0 ) - { - continue; - } + if (terminalSearchToolTips && notDone) { + for (final Object lp : Platform.getTooltip(is)) { + if (lp instanceof String && m.matcher((CharSequence) lp).find()) { + this.view.add(is); + notDone = false; + break; + } + } + } - final String dspName = searchMod ? Platform.getModId( is ) : Platform.getItemDisplayName( is ); - notDone = true; + /* + * if ( terminalSearchMods && notDone ) { if ( m.matcher( Platform.getMod( + * is.getItemStack() ) ).find() ) { view.add( is ); notDone = false; } } + */ + } - if( m.matcher( dspName.toLowerCase() ).find() ) - { - this.view.add( is ); - notDone = false; - } + final Enum SortBy = this.sortSrc.getSortBy(); + final Enum SortDir = this.sortSrc.getSortDir(); - if( terminalSearchToolTips && notDone ) - { - for( final Object lp : Platform.getTooltip( is ) ) - { - if( lp instanceof String && m.matcher( (CharSequence) lp ).find() ) - { - this.view.add( is ); - notDone = false; - break; - } - } - } + ItemSorters.setDirection((appeng.api.config.SortDir) SortDir); + ItemSorters.init(); - /* - * if ( terminalSearchMods && notDone ) { if ( m.matcher( Platform.getMod( is.getItemStack() ) ).find() ) { - * view.add( is ); notDone = false; } } - */ - } + if (SortBy == SortOrder.MOD) { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD); + } else if (SortBy == SortOrder.AMOUNT) { + Collections.sort(this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE); + } 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); + } - final Enum SortBy = this.sortSrc.getSortBy(); - final Enum SortDir = this.sortSrc.getSortDir(); + for (final IAEItemStack is : this.view) { + this.dsp.add(is.getItemStack()); + } + } - ItemSorters.setDirection( (appeng.api.config.SortDir) SortDir ); - ItemSorters.init(); + private void updateNEI(final String filter) { + try { + if (this.NEIWord == null || !this.NEIWord.equals(filter)) { + final Class c = ReflectionHelper.getClass( + this.getClass().getClassLoader(), "codechicken.nei.LayoutManager" + ); + final Field fldSearchField = c.getField("searchField"); + final Object searchField = fldSearchField.get(c); - if( SortBy == SortOrder.MOD ) - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_MOD ); - } - else if( SortBy == SortOrder.AMOUNT ) - { - Collections.sort( this.view, ItemSorters.CONFIG_BASED_SORT_BY_SIZE ); - } - 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 ); - } + final Method a + = searchField.getClass().getMethod("setText", String.class); + final Method b + = searchField.getClass().getMethod("onTextChange", String.class); - for( final IAEItemStack is : this.view ) - { - this.dsp.add( is.getItemStack() ); - } - } + this.NEIWord = filter; + a.invoke(searchField, filter); + b.invoke(searchField, ""); + } + } catch (final Throwable ignore) {} + } - private void updateNEI( final String filter ) - { - try - { - if( this.NEIWord == null || !this.NEIWord.equals( filter ) ) - { - final Class c = ReflectionHelper.getClass( this.getClass().getClassLoader(), "codechicken.nei.LayoutManager" ); - final Field fldSearchField = c.getField( "searchField" ); - final Object searchField = fldSearchField.get( c ); + public int size() { + return this.view.size(); + } - final Method a = searchField.getClass().getMethod( "setText", String.class ); - final Method b = searchField.getClass().getMethod( "onTextChange", String.class ); + public void clear() { + this.list.resetStatus(); + } - this.NEIWord = filter; - a.invoke( searchField, filter ); - b.invoke( searchField, "" ); - } - } - catch( final Throwable ignore ) - { + public boolean hasPower() { + return this.hasPower; + } - } - } + public void setPower(final boolean hasPower) { + this.hasPower = hasPower; + } - public int size() - { - return this.view.size(); - } + public int getRowSize() { + return this.rowSize; + } - public void clear() - { - this.list.resetStatus(); - } + public void setRowSize(final int rowSize) { + this.rowSize = rowSize; + } - public boolean hasPower() - { - return this.hasPower; - } + public String getSearchString() { + return this.searchString; + } - public void setPower( final boolean hasPower ) - { - this.hasPower = hasPower; - } - - public int getRowSize() - { - return this.rowSize; - } - - public void setRowSize( final int rowSize ) - { - this.rowSize = rowSize; - } - - public String getSearchString() - { - return this.searchString; - } - - public void setSearchString( @Nonnull final String searchString ) - { - this.searchString = searchString; - } + public void setSearchString(@Nonnull final String searchString) { + this.searchString = searchString; + } } diff --git a/src/main/java/appeng/client/me/SlotDisconnected.java b/src/main/java/appeng/client/me/SlotDisconnected.java index e105d958..99c4f399 100644 --- a/src/main/java/appeng/client/me/SlotDisconnected.java +++ b/src/main/java/appeng/client/me/SlotDisconnected.java @@ -18,7 +18,6 @@ package appeng.client.me; - import appeng.container.slot.AppEngSlot; import appeng.items.misc.ItemEncodedPattern; import appeng.util.Platform; @@ -26,86 +25,70 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotDisconnected extends AppEngSlot { + private final ClientDCInternalInv mySlot; -public class SlotDisconnected extends AppEngSlot -{ + public SlotDisconnected( + final ClientDCInternalInv me, final int which, final int x, final int y + ) { + super(me.getInventory(), which, x, y); + this.mySlot = me; + } - private final ClientDCInternalInv mySlot; + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - public SlotDisconnected( final ClientDCInternalInv me, final int which, final int x, final int y ) - { - super( me.getInventory(), which, x, y ); - this.mySlot = me; - } + @Override + public void putStack(final ItemStack par1ItemStack) {} - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { + @Override + public ItemStack getDisplayStack() { + if (Platform.isClient()) { + final ItemStack is = super.getStack(); + if (is != null && is.getItem() instanceof ItemEncodedPattern) { + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ItemStack out = iep.getOutput(is); + if (out != null) { + return out; + } + } + } + return super.getStack(); + } - } + @Override + public void + onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean getHasStack() { + return this.getStack() != null; + } - @Override - public ItemStack getDisplayStack() - { - if( Platform.isClient() ) - { - final ItemStack is = super.getStack(); - if( is != null && is.getItem() instanceof ItemEncodedPattern ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ItemStack out = iep.getOutput( is ); - if( out != null ) - { - return out; - } - } - } - return super.getStack(); - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - } + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } - @Override - public boolean getHasStack() - { - return this.getStack() != null; - } + @Override + public boolean isSlotInInventory(final IInventory par1iInventory, final int par2) { + return false; + } - @Override - public int getSlotStackLimit() - { - return 0; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } - - @Override - public boolean isSlotInInventory( final IInventory par1iInventory, final int par2 ) - { - return false; - } - - public ClientDCInternalInv getSlot() - { - return this.mySlot; - } + public ClientDCInternalInv getSlot() { + return this.mySlot; + } } diff --git a/src/main/java/appeng/client/me/SlotME.java b/src/main/java/appeng/client/me/SlotME.java index b9640919..f4db614f 100644 --- a/src/main/java/appeng/client/me/SlotME.java +++ b/src/main/java/appeng/client/me/SlotME.java @@ -18,92 +18,73 @@ package appeng.client.me; - import appeng.api.storage.data.IAEItemStack; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +public class SlotME extends Slot { + private final InternalSlotME mySlot; -public class SlotME extends Slot -{ + public SlotME(final InternalSlotME me) { + super(null, 0, me.getxPosition(), me.getyPosition()); + this.mySlot = me; + } - private final InternalSlotME mySlot; + public IAEItemStack getAEStack() { + if (this.mySlot.hasPower()) { + return this.mySlot.getAEStack(); + } + return null; + } - public SlotME( final InternalSlotME me ) - { - super( null, 0, me.getxPosition(), me.getyPosition() ); - this.mySlot = me; - } + @Override + public void + onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { + } - public IAEItemStack getAEStack() - { - if( this.mySlot.hasPower() ) - { - return this.mySlot.getAEStack(); - } - return null; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - } + @Override + public ItemStack getStack() { + if (this.mySlot.hasPower()) { + return this.mySlot.getStack(); + } + return null; + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean getHasStack() { + if (this.mySlot.hasPower()) { + return this.getStack() != null; + } + return false; + } - @Override - public ItemStack getStack() - { - if( this.mySlot.hasPower() ) - { - return this.mySlot.getStack(); - } - return null; - } + @Override + public void putStack(final ItemStack par1ItemStack) {} - @Override - public boolean getHasStack() - { - if( this.mySlot.hasPower() ) - { - return this.getStack() != null; - } - return false; - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } - } + @Override + public boolean isSlotInInventory(final IInventory par1iInventory, final int par2) { + return false; + } - @Override - public int getSlotStackLimit() - { - return 0; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } - - @Override - public boolean isSlotInInventory( final IInventory par1iInventory, final int par2 ) - { - return false; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final 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 3209fe31..e33e7f8e 100644 --- a/src/main/java/appeng/client/render/AppEngRenderItem.java +++ b/src/main/java/appeng/client/render/AppEngRenderItem.java @@ -18,6 +18,7 @@ package appeng.client.render; +import javax.annotation.Nonnull; import appeng.api.storage.data.IAEItemStack; import appeng.core.AEConfig; @@ -32,133 +33,147 @@ import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; -import javax.annotation.Nonnull; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class AppEngRenderItem extends RenderItem -{ - private static final ISlimReadableNumberConverter SLIM_CONVERTER = ReadableNumberConverter.INSTANCE; - private static final IWideReadableNumberConverter WIDE_CONVERTER = ReadableNumberConverter.INSTANCE; +public class AppEngRenderItem extends RenderItem { + private static final ISlimReadableNumberConverter SLIM_CONVERTER + = ReadableNumberConverter.INSTANCE; + private static final IWideReadableNumberConverter WIDE_CONVERTER + = ReadableNumberConverter.INSTANCE; - private IAEItemStack aeStack = null; + private IAEItemStack aeStack = null; - @Override - public void renderItemOverlayIntoGUI( final FontRenderer fontRenderer, final TextureManager textureManager, final ItemStack is, final int par4, final int par5, final String par6Str ) - { - if( is != null ) - { - final float scaleFactor = AEConfig.instance.useTerminalUseLargeFont() ? 0.85f : 0.5f; - final float inverseScaleFactor = 1.0f / scaleFactor; - final int offset = AEConfig.instance.useTerminalUseLargeFont() ? 0 : -1; + @Override + public void renderItemOverlayIntoGUI( + final FontRenderer fontRenderer, + final TextureManager textureManager, + final ItemStack is, + final int par4, + final int par5, + final String par6Str + ) { + if (is != null) { + final float scaleFactor + = AEConfig.instance.useTerminalUseLargeFont() ? 0.85f : 0.5f; + final float inverseScaleFactor = 1.0f / scaleFactor; + final int offset = AEConfig.instance.useTerminalUseLargeFont() ? 0 : -1; - final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); - fontRenderer.setUnicodeFlag( false ); + final boolean unicodeFlag = fontRenderer.getUnicodeFlag(); + fontRenderer.setUnicodeFlag(false); - if( is.getItem().showDurabilityBar( is ) ) - { - final double health = is.getItem().getDurabilityForDisplay( is ); - final int j1 = (int) Math.round( 13.0D - health * 13.0D ); - final int k = (int) Math.round( 255.0D - health * 255.0D ); + if (is.getItem().showDurabilityBar(is)) { + final double health = is.getItem().getDurabilityForDisplay(is); + final int j1 = (int) Math.round(13.0D - health * 13.0D); + final int k = (int) Math.round(255.0D - health * 255.0D); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glDisable( GL11.GL_TEXTURE_2D ); - GL11.glDisable( GL11.GL_ALPHA_TEST ); - GL11.glDisable( GL11.GL_BLEND ); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_BLEND); - final Tessellator tessellator = Tessellator.instance; - final int l = 255 - k << 16 | k << 8; - final int i1 = ( 255 - k ) / 4 << 16 | 16128; + final Tessellator tessellator = Tessellator.instance; + final int l = 255 - k << 16 | k << 8; + final int i1 = (255 - k) / 4 << 16 | 16128; - this.renderQuad( tessellator, par4 + 2, par5 + 13, 13, 2, 0 ); - this.renderQuad( tessellator, par4 + 2, par5 + 13, 12, 1, i1 ); - this.renderQuad( tessellator, par4 + 2, par5 + 13, j1, 1, l ); + this.renderQuad(tessellator, par4 + 2, par5 + 13, 13, 2, 0); + this.renderQuad(tessellator, par4 + 2, par5 + 13, 12, 1, i1); + this.renderQuad(tessellator, par4 + 2, par5 + 13, j1, 1, l); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } - if( is.stackSize == 0 ) - { - final String craftLabelText = AEConfig.instance.useTerminalUseLargeFont() ? GuiText.LargeFontCraft.getLocal() : GuiText.SmallFontCraft.getLocal(); + if (is.stackSize == 0) { + final String craftLabelText = AEConfig.instance.useTerminalUseLargeFont() + ? GuiText.LargeFontCraft.getLocal() + : GuiText.SmallFontCraft.getLocal(); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glPushMatrix(); - GL11.glScaled( scaleFactor, scaleFactor, scaleFactor ); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glPushMatrix(); + GL11.glScaled(scaleFactor, scaleFactor, scaleFactor); - final int X = (int) ( ( (float) par4 + offset + 16.0f - fontRenderer.getStringWidth( craftLabelText ) * scaleFactor ) * inverseScaleFactor ); - final int Y = (int) ( ( (float) par5 + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); - fontRenderer.drawStringWithShadow( craftLabelText, X, Y, 16777215 ); + final int X = (int + ) (((float) par4 + offset + 16.0f + - fontRenderer.getStringWidth(craftLabelText) * scaleFactor) + * inverseScaleFactor); + final int Y = (int + ) (((float) par5 + offset + 16.0f - 7.0f * scaleFactor) + * inverseScaleFactor); + fontRenderer.drawStringWithShadow(craftLabelText, X, Y, 16777215); - GL11.glPopMatrix(); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - } + GL11.glPopMatrix(); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } - final long amount = this.aeStack != null ? this.aeStack.getStackSize() : is.stackSize; + final long amount + = this.aeStack != null ? this.aeStack.getStackSize() : is.stackSize; - if( amount != 0 ) - { - final String stackSize = this.getToBeRenderedStackSize( amount ); + if (amount != 0) { + final String stackSize = this.getToBeRenderedStackSize(amount); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL11.GL_DEPTH_TEST ); - GL11.glPushMatrix(); - GL11.glScaled( scaleFactor, scaleFactor, scaleFactor ); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glPushMatrix(); + GL11.glScaled(scaleFactor, scaleFactor, scaleFactor); - final int X = (int) ( ( (float) par4 + offset + 16.0f - fontRenderer.getStringWidth( stackSize ) * scaleFactor ) * inverseScaleFactor ); - final int Y = (int) ( ( (float) par5 + offset + 16.0f - 7.0f * scaleFactor ) * inverseScaleFactor ); - fontRenderer.drawStringWithShadow( stackSize, X, Y, 16777215 ); + final int X = (int + ) (((float) par4 + offset + 16.0f + - fontRenderer.getStringWidth(stackSize) * scaleFactor) + * inverseScaleFactor); + final int Y = (int + ) (((float) par5 + offset + 16.0f - 7.0f * scaleFactor) + * inverseScaleFactor); + fontRenderer.drawStringWithShadow(stackSize, X, Y, 16777215); - GL11.glPopMatrix(); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - } + GL11.glPopMatrix(); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } - fontRenderer.setUnicodeFlag( unicodeFlag ); - } - } + fontRenderer.setUnicodeFlag(unicodeFlag); + } + } - private void renderQuad( final Tessellator par1Tessellator, final int par2, final int par3, final int par4, final int par5, final 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 void renderQuad( + final Tessellator par1Tessellator, + final int par2, + final int par3, + final int par4, + final int par5, + final 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( final long originalSize ) - { - if( AEConfig.instance.useTerminalUseLargeFont() ) - { - return SLIM_CONVERTER.toSlimReadableForm( originalSize ); - } - else - { - return WIDE_CONVERTER.toWideReadableForm( originalSize ); - } - } + private String getToBeRenderedStackSize(final long originalSize) { + if (AEConfig.instance.useTerminalUseLargeFont()) { + return SLIM_CONVERTER.toSlimReadableForm(originalSize); + } else { + return WIDE_CONVERTER.toWideReadableForm(originalSize); + } + } - public IAEItemStack getAeStack() - { - return this.aeStack; - } + public IAEItemStack getAeStack() { + return this.aeStack; + } - public void setAeStack( @Nonnull final IAEItemStack aeStack ) - { - this.aeStack = aeStack; - } + public void setAeStack(@Nonnull final IAEItemStack aeStack) { + this.aeStack = aeStack; + } } diff --git a/src/main/java/appeng/client/render/BaseBlockRender.java b/src/main/java/appeng/client/render/BaseBlockRender.java index 97990abc..34295478 100644 --- a/src/main/java/appeng/client/render/BaseBlockRender.java +++ b/src/main/java/appeng/client/render/BaseBlockRender.java @@ -18,6 +18,9 @@ package appeng.client.render; +import java.nio.FloatBuffer; +import java.util.EnumSet; +import javax.annotation.Nullable; import appeng.api.util.IOrientable; import appeng.block.AEBaseBlock; @@ -43,741 +46,1015 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; -import javax.annotation.Nullable; -import java.nio.FloatBuffer; -import java.util.EnumSet; - - -@SideOnly( Side.CLIENT ) -public class BaseBlockRender -{ - private static final int ORIENTATION_BITS = 7; - private static final int FLIP_H_BIT = 8; - private static final int FLIP_V_BIT = 16; - private static final byte[][][] ORIENTATION_MAP = new byte[6][6][6]; - - private final boolean hasTESR; - private final double renderDistance; - private final FloatBuffer rotMat = BufferUtils.createFloatBuffer( 16 ); - - public BaseBlockRender() - { - this( false, 20 ); - } - - public BaseBlockRender( final boolean enableTESR, final double renderDistance ) - { - this.hasTESR = enableTESR; - this.renderDistance = renderDistance; - setOriMap(); - } - - private static void setOriMap() - { - // pointed up... - ORIENTATION_MAP[0][3][1] = 0; - ORIENTATION_MAP[1][3][1] = 0; - ORIENTATION_MAP[2][3][1] = 0; - ORIENTATION_MAP[3][3][1] = 0; - ORIENTATION_MAP[4][3][1] = 0; - ORIENTATION_MAP[5][3][1] = 0; - - ORIENTATION_MAP[0][5][1] = 1; - ORIENTATION_MAP[1][5][1] = 2; - ORIENTATION_MAP[2][5][1] = 0; - ORIENTATION_MAP[3][5][1] = 0; - ORIENTATION_MAP[4][5][1] = 0; - ORIENTATION_MAP[5][5][1] = 0; - - ORIENTATION_MAP[0][2][1] = 3; - ORIENTATION_MAP[1][2][1] = 3; - ORIENTATION_MAP[2][2][1] = 0; - ORIENTATION_MAP[3][2][1] = 0; - ORIENTATION_MAP[4][2][1] = 0; - ORIENTATION_MAP[5][2][1] = 0; - - ORIENTATION_MAP[0][4][1] = 2; - ORIENTATION_MAP[1][4][1] = 1; - ORIENTATION_MAP[2][4][1] = 0; - ORIENTATION_MAP[3][4][1] = 0; - ORIENTATION_MAP[4][4][1] = 0; - ORIENTATION_MAP[5][4][1] = 0; - - // upside down - ORIENTATION_MAP[0][3][0] = FLIP_H_BIT; - ORIENTATION_MAP[1][3][0] = FLIP_H_BIT; - ORIENTATION_MAP[2][3][0] = 3; - ORIENTATION_MAP[3][3][0] = 3; - ORIENTATION_MAP[4][3][0] = 3; - ORIENTATION_MAP[5][3][0] = 3; - - ORIENTATION_MAP[0][4][0] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[1][4][0] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[2][4][0] = 3; - ORIENTATION_MAP[3][4][0] = 3; - ORIENTATION_MAP[4][4][0] = 3; - ORIENTATION_MAP[5][4][0] = 3; - - ORIENTATION_MAP[0][5][0] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][5][0] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[2][5][0] = 3; - ORIENTATION_MAP[3][5][0] = 3; - ORIENTATION_MAP[4][5][0] = 3; - ORIENTATION_MAP[5][5][0] = 3; - - ORIENTATION_MAP[0][2][0] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[1][2][0] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[2][2][0] = 3; - ORIENTATION_MAP[3][2][0] = 3; - ORIENTATION_MAP[4][2][0] = 3; - ORIENTATION_MAP[5][2][0] = 3; - - // side 1 - ORIENTATION_MAP[0][3][5] = 1 | FLIP_V_BIT; - ORIENTATION_MAP[1][3][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[2][3][5] = 1; - ORIENTATION_MAP[3][3][5] = 1; - ORIENTATION_MAP[4][3][5] = 1; - ORIENTATION_MAP[5][3][5] = 1 | FLIP_V_BIT; - - ORIENTATION_MAP[0][1][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][1][5] = 1; - ORIENTATION_MAP[2][1][5] = 3 | FLIP_V_BIT; - ORIENTATION_MAP[3][1][5] = 3; - ORIENTATION_MAP[4][1][5] = 1 | FLIP_V_BIT; - ORIENTATION_MAP[5][1][5] = 1; - - ORIENTATION_MAP[0][2][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][2][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[2][2][5] = 1; - ORIENTATION_MAP[3][2][5] = 2 | FLIP_V_BIT; - ORIENTATION_MAP[4][2][5] = 1 | FLIP_V_BIT; - ORIENTATION_MAP[5][2][5] = 1; - - ORIENTATION_MAP[0][0][5] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][0][5] = 1; - ORIENTATION_MAP[2][0][5] = 0; - ORIENTATION_MAP[3][0][5] = FLIP_V_BIT; - ORIENTATION_MAP[4][0][5] = 1; - ORIENTATION_MAP[5][0][5] = 1 | FLIP_V_BIT; - - // side 2 - ORIENTATION_MAP[0][1][2] = FLIP_H_BIT; - ORIENTATION_MAP[1][1][2] = 0; - ORIENTATION_MAP[2][1][2] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[3][1][2] = 1; - ORIENTATION_MAP[4][1][2] = 3; - ORIENTATION_MAP[5][1][2] = 3 | FLIP_H_BIT; - - ORIENTATION_MAP[0][4][2] = FLIP_H_BIT; - ORIENTATION_MAP[1][4][2] = FLIP_H_BIT; - ORIENTATION_MAP[2][4][2] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[3][4][2] = 1; - ORIENTATION_MAP[4][4][2] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[5][4][2] = 2; - - ORIENTATION_MAP[0][0][2] = FLIP_V_BIT; - ORIENTATION_MAP[1][0][2] = 0; - ORIENTATION_MAP[2][0][2] = 2; - ORIENTATION_MAP[3][0][2] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[4][0][2] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[5][0][2] = 0; - - ORIENTATION_MAP[0][5][2] = FLIP_H_BIT; - ORIENTATION_MAP[1][5][2] = FLIP_H_BIT; - ORIENTATION_MAP[2][5][2] = 2; - ORIENTATION_MAP[3][5][2] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[4][5][2] = 2; - ORIENTATION_MAP[5][5][2] = 1 | FLIP_H_BIT; - - // side 3 - ORIENTATION_MAP[0][0][3] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[1][0][3] = 3; - ORIENTATION_MAP[2][0][3] = 1; - ORIENTATION_MAP[3][0][3] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[4][0][3] = 0; - ORIENTATION_MAP[5][0][3] = FLIP_H_BIT; - - ORIENTATION_MAP[0][4][3] = 3; - ORIENTATION_MAP[1][4][3] = 3; - ORIENTATION_MAP[2][4][3] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[3][4][3] = 2; - ORIENTATION_MAP[4][4][3] = 1; - ORIENTATION_MAP[5][4][3] = 2 | FLIP_H_BIT; - - ORIENTATION_MAP[0][1][3] = 3 | FLIP_V_BIT; - ORIENTATION_MAP[1][1][3] = 3; - ORIENTATION_MAP[2][1][3] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[3][1][3] = 2; - ORIENTATION_MAP[4][1][3] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[5][1][3] = 0; - - ORIENTATION_MAP[0][5][3] = 3; - ORIENTATION_MAP[1][5][3] = 3; - ORIENTATION_MAP[2][5][3] = 1; - ORIENTATION_MAP[3][5][3] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[4][5][3] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[5][5][3] = 1; - - // side 4 - ORIENTATION_MAP[0][3][4] = 1; - ORIENTATION_MAP[1][3][4] = 2; - ORIENTATION_MAP[2][3][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[3][3][4] = 1; - ORIENTATION_MAP[4][3][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[5][3][4] = 1; - - ORIENTATION_MAP[0][0][4] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][0][4] = 2; - ORIENTATION_MAP[2][0][4] = 0; - ORIENTATION_MAP[3][0][4] = FLIP_H_BIT; - ORIENTATION_MAP[4][0][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[5][0][4] = 1; - - ORIENTATION_MAP[0][1][4] = 1 | FLIP_H_BIT; - ORIENTATION_MAP[1][1][4] = 2; - ORIENTATION_MAP[2][1][4] = 3 | FLIP_H_BIT; - ORIENTATION_MAP[3][1][4] = 3; - ORIENTATION_MAP[4][1][4] = 2; - ORIENTATION_MAP[5][1][4] = 1 | FLIP_H_BIT; - - ORIENTATION_MAP[0][2][4] = 1; - ORIENTATION_MAP[1][2][4] = 2; - ORIENTATION_MAP[2][2][4] = 1; - ORIENTATION_MAP[3][2][4] = 2 | FLIP_H_BIT; - ORIENTATION_MAP[4][2][4] = 2; - ORIENTATION_MAP[5][2][4] = 1 | FLIP_H_BIT; - } - - public boolean hasTESR() - { - return this.hasTESR; - } - - protected int adjustBrightness( final int v, final double d ) - { - int r = 0xff & ( v >> 16 ); - int g = 0xff & ( v >> 8 ); - int b = 0xff & ( v ); - - r *= d; - g *= d; - b *= d; - - r = Math.min( 255, Math.max( 0, r ) ); - g = Math.min( 255, Math.max( 0, g ) ); - b = Math.min( 255, Math.max( 0, b ) ); - - return ( r << 16 ) | ( g << 8 ) | b; - } - - double getTesrRenderDistance() - { - return this.renderDistance; - } - - public void renderInventory( final B block, final ItemStack item, final RenderBlocks renderer, final ItemRenderType type, final Object[] data ) - { - final Tessellator tess = Tessellator.instance; - final BlockRenderInfo info = block.getRendererInstance(); - - if( info.isValid() ) - { - if( block.hasSubtypes() ) - { - block.setRenderStateByMeta( item.getItemDamage() ); - } - - renderer.uvRotateBottom = info.getTexture( ForgeDirection.DOWN ).setFlip( getOrientation( ForgeDirection.DOWN, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - renderer.uvRotateTop = info.getTexture( ForgeDirection.UP ).setFlip( getOrientation( ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - - renderer.uvRotateEast = info.getTexture( ForgeDirection.EAST ).setFlip( getOrientation( ForgeDirection.EAST, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - renderer.uvRotateWest = info.getTexture( ForgeDirection.WEST ).setFlip( getOrientation( ForgeDirection.WEST, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - - renderer.uvRotateNorth = info.getTexture( ForgeDirection.NORTH ).setFlip( getOrientation( ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - renderer.uvRotateSouth = info.getTexture( ForgeDirection.SOUTH ).setFlip( getOrientation( ForgeDirection.SOUTH, ForgeDirection.SOUTH, ForgeDirection.UP ) ); - } - - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), block, item, tess, 0xffffff, renderer ); - - if( block.hasSubtypes() ) - { - info.setTemporaryRenderIcon( null ); - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - - static int getOrientation( final ForgeDirection in, final ForgeDirection forward, final ForgeDirection up ) - { - if( in == null || in == ForgeDirection.UNKNOWN // 1 - || forward == null || forward == ForgeDirection.UNKNOWN // 2 - || up == null || up == ForgeDirection.UNKNOWN ) - { - return 0; - } - - final int a = in.ordinal(); - final int b = forward.ordinal(); - final int c = up.ordinal(); - - return ORIENTATION_MAP[a][b][c]; - } - - public void renderInvBlock( final EnumSet sides, final B block, final ItemStack item, final Tessellator tess, final int color, final RenderBlocks renderer ) - { - if( block == null ) - { - return; - } - - int meta = 0; - - if( block.hasSubtypes() && item != null ) - { - meta = item.getItemDamage(); - } - - if( sides.contains( ForgeDirection.DOWN ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, -1.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceYNeg( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.DOWN ), block.getIcon( ForgeDirection.DOWN.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.UP ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, 1.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceYPos( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.UP ), block.getIcon( ForgeDirection.UP.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.NORTH ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, 0.0F, -1.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceZNeg( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.NORTH ), block.getIcon( ForgeDirection.NORTH.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.SOUTH ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 0.0F, 0.0F, 1.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceZPos( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.SOUTH ), block.getIcon( ForgeDirection.SOUTH.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.WEST ) ) - { - tess.startDrawingQuads(); - tess.setNormal( -1.0F, 0.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceXNeg( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.WEST ), block.getIcon( ForgeDirection.WEST.ordinal(), meta ) ) ); - tess.draw(); - } - - if( sides.contains( ForgeDirection.EAST ) ) - { - tess.startDrawingQuads(); - tess.setNormal( 1.0F, 0.0F, 0.0F ); - tess.setColorOpaque_I( color ); - renderer.renderFaceXPos( block, 0.0D, 0.0D, 0.0D, this.firstNotNull( renderer.overrideBlockTexture, block.getRendererInstance().getTexture( ForgeDirection.EAST ), block.getIcon( ForgeDirection.EAST.ordinal(), meta ) ) ); - tess.draw(); - } - } - - private IIcon firstNotNull( final IIcon... s ) - { - for( final IIcon o : s ) - { - if( o != null ) - { - return o; - } - } - - return ExtraBlockTextures.getMissing(); - } - - public boolean renderInWorld( final B block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - this.preRenderInWorld( block, world, x, y, z, renderer ); - - final boolean o = renderer.renderStandardBlock( block, x, y, z ); - - this.postRenderInWorld( renderer ); - - return o; - } - - public void preRenderInWorld( final B block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - - final BlockRenderInfo info = block.getRendererInstance(); - final IOrientable te = this.getOrientable( block, world, x, y, z ); - - if( te != null ) - { - final ForgeDirection forward = te.getForward(); - final ForgeDirection up = te.getUp(); - - renderer.uvRotateBottom = info.getTexture( ForgeDirection.DOWN ).setFlip( getOrientation( ForgeDirection.DOWN, forward, up ) ); - renderer.uvRotateTop = info.getTexture( ForgeDirection.UP ).setFlip( getOrientation( ForgeDirection.UP, forward, up ) ); - - renderer.uvRotateEast = info.getTexture( ForgeDirection.EAST ).setFlip( getOrientation( ForgeDirection.EAST, forward, up ) ); - renderer.uvRotateWest = info.getTexture( ForgeDirection.WEST ).setFlip( getOrientation( ForgeDirection.WEST, forward, up ) ); - - renderer.uvRotateNorth = info.getTexture( ForgeDirection.NORTH ).setFlip( getOrientation( ForgeDirection.NORTH, forward, up ) ); - renderer.uvRotateSouth = info.getTexture( ForgeDirection.SOUTH ).setFlip( getOrientation( ForgeDirection.SOUTH, forward, up ) ); - } - } - - public void postRenderInWorld( final RenderBlocks renderer ) - { - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - - @Nullable - public IOrientable getOrientable( final B block, final IBlockAccess w, final int x, final int y, final int z ) - { - return block.getOrientable( w, x, y, z ); - } - - protected void setInvRenderBounds( final RenderBlocks renderer, final int i, final int j, final int k, final int l, final int m, final int n ) - { - renderer.setRenderBounds( i / 16.0, j / 16.0, k / 16.0, l / 16.0, m / 16.0, n / 16.0 ); - } - - protected void renderBlockBounds( final RenderBlocks renderer, double minX, double minY, double minZ, double maxX, double maxY, double maxZ, final ForgeDirection x, final ForgeDirection y, final ForgeDirection z ) - { - minX /= 16.0; - minY /= 16.0; - minZ /= 16.0; - maxX /= 16.0; - maxY /= 16.0; - maxZ /= 16.0; - - double aX = minX * x.offsetX + minY * y.offsetX + minZ * z.offsetX; - double aY = minX * x.offsetY + minY * y.offsetY + minZ * z.offsetY; - double aZ = minX * x.offsetZ + minY * y.offsetZ + minZ * z.offsetZ; - - double bX = maxX * x.offsetX + maxY * y.offsetX + maxZ * z.offsetX; - 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 ) - { - aX += 1; - bX += 1; - } - - if( x.offsetY + y.offsetY + z.offsetY < 0 ) - { - aY += 1; - bY += 1; - } - - if( x.offsetZ + y.offsetZ + z.offsetZ < 0 ) - { - aZ += 1; - bZ += 1; - } - - renderer.renderMinX = Math.min( aX, bX ); - renderer.renderMinY = Math.min( aY, bY ); - renderer.renderMinZ = Math.min( aZ, bZ ); - renderer.renderMaxX = Math.max( aX, bX ); - renderer.renderMaxY = Math.max( aY, bY ); - renderer.renderMaxZ = Math.max( aZ, bZ ); - } - - @SideOnly( Side.CLIENT ) - protected void renderCutoutFace( final B block, final IIcon ico, final int x, final int y, final int z, final RenderBlocks renderer, final ForgeDirection orientation, final float edgeThickness ) - { - final Tessellator tess = Tessellator.instance; - - double offsetX = 0.0; - double offsetY = 0.0; - double offsetZ = 0.0; - double layerAX = 0.0; - double layerAZ = 0.0; - double layerBY = 0.0; - double layerBZ = 0.0; - - boolean flip = false; - switch( orientation ) - { - case NORTH: - - layerAX = 1.0; - layerBY = 1.0; - flip = true; - - break; - case SOUTH: - - layerAX = 1.0; - layerBY = 1.0; - offsetZ = 1.0; - - break; - case EAST: - - flip = true; - layerAZ = 1.0; - layerBY = 1.0; - offsetX = 1.0; - - break; - case WEST: - - layerAZ = 1.0; - layerBY = 1.0; - - break; - case UP: - - flip = true; - layerAX = 1.0; - layerBZ = 1.0; - offsetY = 1.0; - - break; - case DOWN: - - layerAX = 1.0; - layerBZ = 1.0; - - break; - default: - break; - } - - offsetX += x; - offsetY += y; - offsetZ += z; - - final double layerBX = 0.0; - final double layerAY = 0.0; - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 0, 1.0, - // v -> v - 0, edgeThickness, ico, flip ); - - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 0.0, edgeThickness, - // v -> v - edgeThickness, 1.0 - edgeThickness, ico, flip ); - - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 1.0 - edgeThickness, 1.0, - // v -> v - edgeThickness, 1.0 - edgeThickness, ico, flip ); - - this.renderFace( tess, offsetX, offsetY, offsetZ, layerAX, layerAY, layerAZ, layerBX, layerBY, layerBZ, - // u -> u - 0, 1.0, - // v -> v - 1.0 - edgeThickness, 1.0, ico, flip ); - } - - @SideOnly( Side.CLIENT ) - private void renderFace( final Tessellator tess, final double offsetX, final double offsetY, final double offsetZ, final double ax, final double ay, final double az, final double bx, final double by, final double bz, final double ua, final double ub, final double va, final double vb, final IIcon ico, final boolean 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 ) ); - tess.addVertexWithUV( offsetX + ax * ub + bx * vb, offsetY + ay * ub + by * vb, offsetZ + az * ub + bz * vb, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( vb * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ub + bx * va, offsetY + ay * ub + by * va, offsetZ + az * ub + bz * va, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( va * 16.0 ) ); - } - else - { - 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 * ub + bx * va, offsetY + ay * ub + by * va, offsetZ + az * ub + bz * va, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( va * 16.0 ) ); - tess.addVertexWithUV( offsetX + ax * ub + bx * vb, offsetY + ay * ub + by * vb, offsetZ + az * ub + bz * vb, ico.getInterpolatedU( ub * 16.0 ), ico.getInterpolatedV( vb * 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 ) ); - } - } - - @SideOnly( Side.CLIENT ) - protected void renderFace( final int x, final int y, final int z, final B block, final IIcon ico, final RenderBlocks renderer, final ForgeDirection orientation ) - { - switch( orientation ) - { - case NORTH: - renderer.renderFaceZNeg( block, x, y, z, ico ); - break; - case SOUTH: - renderer.renderFaceZPos( block, x, y, z, ico ); - break; - case EAST: - renderer.renderFaceXPos( block, x, y, z, ico ); - break; - case WEST: - renderer.renderFaceXNeg( block, x, y, z, ico ); - break; - case UP: - renderer.renderFaceYPos( block, x, y, z, ico ); - break; - case DOWN: - renderer.renderFaceYNeg( block, x, y, z, ico ); - break; - default: - break; - } - } - - public void selectFace( final RenderBlocks renderer, final ForgeDirection west, final ForgeDirection up, final ForgeDirection forward, final int u1, final int u2, int v1, int v2 ) - { - v1 = 16 - v1; - v2 = 16 - v2; - - final double minX = ( forward.offsetX > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetX, u1 ) + this.mapFaceUV( up.offsetX, v1 ); - final double minY = ( forward.offsetY > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetY, u1 ) + this.mapFaceUV( up.offsetY, v1 ); - final double minZ = ( forward.offsetZ > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetZ, u1 ) + this.mapFaceUV( up.offsetZ, v1 ); - - final double maxX = ( forward.offsetX > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetX, u2 ) + this.mapFaceUV( up.offsetX, v2 ); - final double maxY = ( forward.offsetY > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetY, u2 ) + this.mapFaceUV( up.offsetY, v2 ); - final double maxZ = ( forward.offsetZ > 0 ? 1 : 0 ) + this.mapFaceUV( west.offsetZ, u2 ) + this.mapFaceUV( up.offsetZ, v2 ); - - renderer.renderMinX = Math.max( 0.0, Math.min( minX, maxX ) - ( forward.offsetX != 0 ? 0 : 0.001 ) ); - renderer.renderMaxX = Math.min( 1.0, Math.max( minX, maxX ) + ( forward.offsetX != 0 ? 0 : 0.001 ) ); - - renderer.renderMinY = Math.max( 0.0, Math.min( minY, maxY ) - ( forward.offsetY != 0 ? 0 : 0.001 ) ); - renderer.renderMaxY = Math.min( 1.0, Math.max( minY, maxY ) + ( forward.offsetY != 0 ? 0 : 0.001 ) ); - - renderer.renderMinZ = Math.max( 0.0, Math.min( minZ, maxZ ) - ( forward.offsetZ != 0 ? 0 : 0.001 ) ); - renderer.renderMaxZ = Math.min( 1.0, Math.max( minZ, maxZ ) + ( forward.offsetZ != 0 ? 0 : 0.001 ) ); - } - - private double mapFaceUV( final int offset, final int uv ) - { - if( offset == 0 ) - { - return 0; - } - - if( offset > 0 ) - { - return uv / 16.0; - } - - return ( 16.0 - uv ) / 16.0; - } - - public void renderTile( final B block, final T tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - renderer.uvRotateBottom = renderer.uvRotateTop = renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; - - final ForgeDirection up = ForgeDirection.UP; - final ForgeDirection forward = ForgeDirection.SOUTH; - this.applyTESRRotation( x, y, z, forward, up ); - - Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.locationBlocksTexture ); - RenderHelper.disableStandardItemLighting(); - - if( Minecraft.isAmbientOcclusionEnabled() ) - { - GL11.glShadeModel( GL11.GL_SMOOTH ); - } - else - { - GL11.glShadeModel( GL11.GL_FLAT ); - } - - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - - tess.setTranslation( -tile.xCoord, -tile.yCoord, -tile.zCoord ); - tess.startDrawingQuads(); - - // note that this is a terrible approach... - renderer.setRenderBoundsFromBlock( block ); - renderer.renderStandardBlock( block, tile.xCoord, tile.yCoord, tile.zCoord ); - - tess.draw(); - tess.setTranslation( 0, 0, 0 ); - RenderHelper.enableStandardItemLighting(); - - renderer.uvRotateBottom = renderer.uvRotateTop = renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; - } - - protected void applyTESRRotation( final double x, final double y, final double z, ForgeDirection forward, ForgeDirection up ) - { - if( forward != null && up != null ) - { - if( forward == ForgeDirection.UNKNOWN ) - { - forward = ForgeDirection.SOUTH; - } - - if( up == ForgeDirection.UNKNOWN ) - { - up = ForgeDirection.UP; - } - - final ForgeDirection west = Platform.crossProduct( forward, up ); - - this.rotMat.put( 0, west.offsetX ); - this.rotMat.put( 1, west.offsetY ); - this.rotMat.put( 2, west.offsetZ ); - this.rotMat.put( 3, 0 ); - - this.rotMat.put( 4, up.offsetX ); - this.rotMat.put( 5, up.offsetY ); - this.rotMat.put( 6, up.offsetZ ); - this.rotMat.put( 7, 0 ); - - this.rotMat.put( 8, forward.offsetX ); - this.rotMat.put( 9, forward.offsetY ); - this.rotMat.put( 10, forward.offsetZ ); - this.rotMat.put( 11, 0 ); - - this.rotMat.put( 12, 0 ); - this.rotMat.put( 13, 0 ); - this.rotMat.put( 14, 0 ); - this.rotMat.put( 15, 1 ); - GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); - GL11.glMultMatrix( this.rotMat ); - GL11.glTranslated( -0.5, -0.5, -0.5 ); - } - else - { - GL11.glTranslated( x, y, z ); - } - } - - public void doRenderItem( final ItemStack itemstack, final TileEntity par1EntityItemFrame ) - { - if( itemstack != null ) - { - final EntityItem entityitem = new EntityItem( par1EntityItemFrame.getWorldObj(), 0.0D, 0.0D, 0.0D, itemstack ); - - entityitem.getEntityItem().stackSize = 1; - - // set all this stuff and then do shit? meh? - entityitem.hoverStart = 0; - entityitem.age = 0; - entityitem.rotationYaw = 0; - - GL11.glPushMatrix(); - GL11.glTranslatef( 0, -0.14F, 0 ); - - RenderItem.renderInFrame = true; - RenderManager.instance.renderEntityWithPosYaw( entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F ); - RenderItem.renderInFrame = false; - - GL11.glPopMatrix(); - } - } +@SideOnly(Side.CLIENT) +public class BaseBlockRender { + private static final int ORIENTATION_BITS = 7; + private static final int FLIP_H_BIT = 8; + private static final int FLIP_V_BIT = 16; + private static final byte[][][] ORIENTATION_MAP = new byte[6][6][6]; + + private final boolean hasTESR; + private final double renderDistance; + private final FloatBuffer rotMat = BufferUtils.createFloatBuffer(16); + + public BaseBlockRender() { + this(false, 20); + } + + public BaseBlockRender(final boolean enableTESR, final double renderDistance) { + this.hasTESR = enableTESR; + this.renderDistance = renderDistance; + setOriMap(); + } + + private static void setOriMap() { + // pointed up... + ORIENTATION_MAP[0][3][1] = 0; + ORIENTATION_MAP[1][3][1] = 0; + ORIENTATION_MAP[2][3][1] = 0; + ORIENTATION_MAP[3][3][1] = 0; + ORIENTATION_MAP[4][3][1] = 0; + ORIENTATION_MAP[5][3][1] = 0; + + ORIENTATION_MAP[0][5][1] = 1; + ORIENTATION_MAP[1][5][1] = 2; + ORIENTATION_MAP[2][5][1] = 0; + ORIENTATION_MAP[3][5][1] = 0; + ORIENTATION_MAP[4][5][1] = 0; + ORIENTATION_MAP[5][5][1] = 0; + + ORIENTATION_MAP[0][2][1] = 3; + ORIENTATION_MAP[1][2][1] = 3; + ORIENTATION_MAP[2][2][1] = 0; + ORIENTATION_MAP[3][2][1] = 0; + ORIENTATION_MAP[4][2][1] = 0; + ORIENTATION_MAP[5][2][1] = 0; + + ORIENTATION_MAP[0][4][1] = 2; + ORIENTATION_MAP[1][4][1] = 1; + ORIENTATION_MAP[2][4][1] = 0; + ORIENTATION_MAP[3][4][1] = 0; + ORIENTATION_MAP[4][4][1] = 0; + ORIENTATION_MAP[5][4][1] = 0; + + // upside down + ORIENTATION_MAP[0][3][0] = FLIP_H_BIT; + ORIENTATION_MAP[1][3][0] = FLIP_H_BIT; + ORIENTATION_MAP[2][3][0] = 3; + ORIENTATION_MAP[3][3][0] = 3; + ORIENTATION_MAP[4][3][0] = 3; + ORIENTATION_MAP[5][3][0] = 3; + + ORIENTATION_MAP[0][4][0] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[1][4][0] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[2][4][0] = 3; + ORIENTATION_MAP[3][4][0] = 3; + ORIENTATION_MAP[4][4][0] = 3; + ORIENTATION_MAP[5][4][0] = 3; + + ORIENTATION_MAP[0][5][0] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][5][0] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[2][5][0] = 3; + ORIENTATION_MAP[3][5][0] = 3; + ORIENTATION_MAP[4][5][0] = 3; + ORIENTATION_MAP[5][5][0] = 3; + + ORIENTATION_MAP[0][2][0] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[1][2][0] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[2][2][0] = 3; + ORIENTATION_MAP[3][2][0] = 3; + ORIENTATION_MAP[4][2][0] = 3; + ORIENTATION_MAP[5][2][0] = 3; + + // side 1 + ORIENTATION_MAP[0][3][5] = 1 | FLIP_V_BIT; + ORIENTATION_MAP[1][3][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[2][3][5] = 1; + ORIENTATION_MAP[3][3][5] = 1; + ORIENTATION_MAP[4][3][5] = 1; + ORIENTATION_MAP[5][3][5] = 1 | FLIP_V_BIT; + + ORIENTATION_MAP[0][1][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][1][5] = 1; + ORIENTATION_MAP[2][1][5] = 3 | FLIP_V_BIT; + ORIENTATION_MAP[3][1][5] = 3; + ORIENTATION_MAP[4][1][5] = 1 | FLIP_V_BIT; + ORIENTATION_MAP[5][1][5] = 1; + + ORIENTATION_MAP[0][2][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][2][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[2][2][5] = 1; + ORIENTATION_MAP[3][2][5] = 2 | FLIP_V_BIT; + ORIENTATION_MAP[4][2][5] = 1 | FLIP_V_BIT; + ORIENTATION_MAP[5][2][5] = 1; + + ORIENTATION_MAP[0][0][5] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][0][5] = 1; + ORIENTATION_MAP[2][0][5] = 0; + ORIENTATION_MAP[3][0][5] = FLIP_V_BIT; + ORIENTATION_MAP[4][0][5] = 1; + ORIENTATION_MAP[5][0][5] = 1 | FLIP_V_BIT; + + // side 2 + ORIENTATION_MAP[0][1][2] = FLIP_H_BIT; + ORIENTATION_MAP[1][1][2] = 0; + ORIENTATION_MAP[2][1][2] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[3][1][2] = 1; + ORIENTATION_MAP[4][1][2] = 3; + ORIENTATION_MAP[5][1][2] = 3 | FLIP_H_BIT; + + ORIENTATION_MAP[0][4][2] = FLIP_H_BIT; + ORIENTATION_MAP[1][4][2] = FLIP_H_BIT; + ORIENTATION_MAP[2][4][2] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[3][4][2] = 1; + ORIENTATION_MAP[4][4][2] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[5][4][2] = 2; + + ORIENTATION_MAP[0][0][2] = FLIP_V_BIT; + ORIENTATION_MAP[1][0][2] = 0; + ORIENTATION_MAP[2][0][2] = 2; + ORIENTATION_MAP[3][0][2] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[4][0][2] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[5][0][2] = 0; + + ORIENTATION_MAP[0][5][2] = FLIP_H_BIT; + ORIENTATION_MAP[1][5][2] = FLIP_H_BIT; + ORIENTATION_MAP[2][5][2] = 2; + ORIENTATION_MAP[3][5][2] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[4][5][2] = 2; + ORIENTATION_MAP[5][5][2] = 1 | FLIP_H_BIT; + + // side 3 + ORIENTATION_MAP[0][0][3] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[1][0][3] = 3; + ORIENTATION_MAP[2][0][3] = 1; + ORIENTATION_MAP[3][0][3] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[4][0][3] = 0; + ORIENTATION_MAP[5][0][3] = FLIP_H_BIT; + + ORIENTATION_MAP[0][4][3] = 3; + ORIENTATION_MAP[1][4][3] = 3; + ORIENTATION_MAP[2][4][3] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[3][4][3] = 2; + ORIENTATION_MAP[4][4][3] = 1; + ORIENTATION_MAP[5][4][3] = 2 | FLIP_H_BIT; + + ORIENTATION_MAP[0][1][3] = 3 | FLIP_V_BIT; + ORIENTATION_MAP[1][1][3] = 3; + ORIENTATION_MAP[2][1][3] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[3][1][3] = 2; + ORIENTATION_MAP[4][1][3] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[5][1][3] = 0; + + ORIENTATION_MAP[0][5][3] = 3; + ORIENTATION_MAP[1][5][3] = 3; + ORIENTATION_MAP[2][5][3] = 1; + ORIENTATION_MAP[3][5][3] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[4][5][3] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[5][5][3] = 1; + + // side 4 + ORIENTATION_MAP[0][3][4] = 1; + ORIENTATION_MAP[1][3][4] = 2; + ORIENTATION_MAP[2][3][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[3][3][4] = 1; + ORIENTATION_MAP[4][3][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[5][3][4] = 1; + + ORIENTATION_MAP[0][0][4] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][0][4] = 2; + ORIENTATION_MAP[2][0][4] = 0; + ORIENTATION_MAP[3][0][4] = FLIP_H_BIT; + ORIENTATION_MAP[4][0][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[5][0][4] = 1; + + ORIENTATION_MAP[0][1][4] = 1 | FLIP_H_BIT; + ORIENTATION_MAP[1][1][4] = 2; + ORIENTATION_MAP[2][1][4] = 3 | FLIP_H_BIT; + ORIENTATION_MAP[3][1][4] = 3; + ORIENTATION_MAP[4][1][4] = 2; + ORIENTATION_MAP[5][1][4] = 1 | FLIP_H_BIT; + + ORIENTATION_MAP[0][2][4] = 1; + ORIENTATION_MAP[1][2][4] = 2; + ORIENTATION_MAP[2][2][4] = 1; + ORIENTATION_MAP[3][2][4] = 2 | FLIP_H_BIT; + ORIENTATION_MAP[4][2][4] = 2; + ORIENTATION_MAP[5][2][4] = 1 | FLIP_H_BIT; + } + + public boolean hasTESR() { + return this.hasTESR; + } + + protected int adjustBrightness(final int v, final double d) { + int r = 0xff & (v >> 16); + int g = 0xff & (v >> 8); + int b = 0xff & (v); + + r *= d; + g *= d; + b *= d; + + r = Math.min(255, Math.max(0, r)); + g = Math.min(255, Math.max(0, g)); + b = Math.min(255, Math.max(0, b)); + + return (r << 16) | (g << 8) | b; + } + + double getTesrRenderDistance() { + return this.renderDistance; + } + + public void renderInventory( + final B block, + final ItemStack item, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] data + ) { + final Tessellator tess = Tessellator.instance; + final BlockRenderInfo info = block.getRendererInstance(); + + if (info.isValid()) { + if (block.hasSubtypes()) { + block.setRenderStateByMeta(item.getItemDamage()); + } + + renderer.uvRotateBottom + = info.getTexture(ForgeDirection.DOWN) + .setFlip(getOrientation( + ForgeDirection.DOWN, ForgeDirection.SOUTH, ForgeDirection.UP + )); + renderer.uvRotateTop + = info.getTexture(ForgeDirection.UP) + .setFlip(getOrientation( + ForgeDirection.UP, ForgeDirection.SOUTH, ForgeDirection.UP + )); + + renderer.uvRotateEast + = info.getTexture(ForgeDirection.EAST) + .setFlip(getOrientation( + ForgeDirection.EAST, ForgeDirection.SOUTH, ForgeDirection.UP + )); + renderer.uvRotateWest + = info.getTexture(ForgeDirection.WEST) + .setFlip(getOrientation( + ForgeDirection.WEST, ForgeDirection.SOUTH, ForgeDirection.UP + )); + + renderer.uvRotateNorth + = info.getTexture(ForgeDirection.NORTH) + .setFlip(getOrientation( + ForgeDirection.NORTH, ForgeDirection.SOUTH, ForgeDirection.UP + )); + renderer.uvRotateSouth + = info.getTexture(ForgeDirection.SOUTH) + .setFlip(getOrientation( + ForgeDirection.SOUTH, ForgeDirection.SOUTH, ForgeDirection.UP + )); + } + + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), block, item, tess, 0xffffff, renderer + ); + + if (block.hasSubtypes()) { + info.setTemporaryRenderIcon(null); + } + + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + } + + static int getOrientation( + final ForgeDirection in, final ForgeDirection forward, final ForgeDirection up + ) { + if (in == null || in == ForgeDirection.UNKNOWN // 1 + || forward == null || forward == ForgeDirection.UNKNOWN // 2 + || up == null || up == ForgeDirection.UNKNOWN) { + return 0; + } + + final int a = in.ordinal(); + final int b = forward.ordinal(); + final int c = up.ordinal(); + + return ORIENTATION_MAP[a][b][c]; + } + + public void renderInvBlock( + final EnumSet sides, + final B block, + final ItemStack item, + final Tessellator tess, + final int color, + final RenderBlocks renderer + ) { + if (block == null) { + return; + } + + int meta = 0; + + if (block.hasSubtypes() && item != null) { + meta = item.getItemDamage(); + } + + if (sides.contains(ForgeDirection.DOWN)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, -1.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceYNeg( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.DOWN), + block.getIcon(ForgeDirection.DOWN.ordinal(), meta) + ) + ); + tess.draw(); + } + + if (sides.contains(ForgeDirection.UP)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, 1.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceYPos( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.UP), + block.getIcon(ForgeDirection.UP.ordinal(), meta) + ) + ); + tess.draw(); + } + + if (sides.contains(ForgeDirection.NORTH)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, 0.0F, -1.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceZNeg( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.NORTH), + block.getIcon(ForgeDirection.NORTH.ordinal(), meta) + ) + ); + tess.draw(); + } + + if (sides.contains(ForgeDirection.SOUTH)) { + tess.startDrawingQuads(); + tess.setNormal(0.0F, 0.0F, 1.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceZPos( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.SOUTH), + block.getIcon(ForgeDirection.SOUTH.ordinal(), meta) + ) + ); + tess.draw(); + } + + if (sides.contains(ForgeDirection.WEST)) { + tess.startDrawingQuads(); + tess.setNormal(-1.0F, 0.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceXNeg( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.WEST), + block.getIcon(ForgeDirection.WEST.ordinal(), meta) + ) + ); + tess.draw(); + } + + if (sides.contains(ForgeDirection.EAST)) { + tess.startDrawingQuads(); + tess.setNormal(1.0F, 0.0F, 0.0F); + tess.setColorOpaque_I(color); + renderer.renderFaceXPos( + block, + 0.0D, + 0.0D, + 0.0D, + this.firstNotNull( + renderer.overrideBlockTexture, + block.getRendererInstance().getTexture(ForgeDirection.EAST), + block.getIcon(ForgeDirection.EAST.ordinal(), meta) + ) + ); + tess.draw(); + } + } + + private IIcon firstNotNull(final IIcon... s) { + for (final IIcon o : s) { + if (o != null) { + return o; + } + } + + return ExtraBlockTextures.getMissing(); + } + + public boolean renderInWorld( + final B block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + this.preRenderInWorld(block, world, x, y, z, renderer); + + final boolean o = renderer.renderStandardBlock(block, x, y, z); + + this.postRenderInWorld(renderer); + + return o; + } + + public void preRenderInWorld( + final B block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final BlockRenderInfo info = block.getRendererInstance(); + final IOrientable te = this.getOrientable(block, world, x, y, z); + + if (te != null) { + final ForgeDirection forward = te.getForward(); + final ForgeDirection up = te.getUp(); + + renderer.uvRotateBottom + = info.getTexture(ForgeDirection.DOWN) + .setFlip(getOrientation(ForgeDirection.DOWN, forward, up)); + renderer.uvRotateTop + = info.getTexture(ForgeDirection.UP) + .setFlip(getOrientation(ForgeDirection.UP, forward, up)); + + renderer.uvRotateEast + = info.getTexture(ForgeDirection.EAST) + .setFlip(getOrientation(ForgeDirection.EAST, forward, up)); + renderer.uvRotateWest + = info.getTexture(ForgeDirection.WEST) + .setFlip(getOrientation(ForgeDirection.WEST, forward, up)); + + renderer.uvRotateNorth + = info.getTexture(ForgeDirection.NORTH) + .setFlip(getOrientation(ForgeDirection.NORTH, forward, up)); + renderer.uvRotateSouth + = info.getTexture(ForgeDirection.SOUTH) + .setFlip(getOrientation(ForgeDirection.SOUTH, forward, up)); + } + } + + public void postRenderInWorld(final RenderBlocks renderer) { + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + } + + @Nullable + public IOrientable getOrientable( + final B block, final IBlockAccess w, final int x, final int y, final int z + ) { + return block.getOrientable(w, x, y, z); + } + + protected void setInvRenderBounds( + final RenderBlocks renderer, + final int i, + final int j, + final int k, + final int l, + final int m, + final int n + ) { + renderer.setRenderBounds( + i / 16.0, j / 16.0, k / 16.0, l / 16.0, m / 16.0, n / 16.0 + ); + } + + protected void renderBlockBounds( + final RenderBlocks renderer, + double minX, + double minY, + double minZ, + double maxX, + double maxY, + double maxZ, + final ForgeDirection x, + final ForgeDirection y, + final ForgeDirection z + ) { + minX /= 16.0; + minY /= 16.0; + minZ /= 16.0; + maxX /= 16.0; + maxY /= 16.0; + maxZ /= 16.0; + + double aX = minX * x.offsetX + minY * y.offsetX + minZ * z.offsetX; + double aY = minX * x.offsetY + minY * y.offsetY + minZ * z.offsetY; + double aZ = minX * x.offsetZ + minY * y.offsetZ + minZ * z.offsetZ; + + double bX = maxX * x.offsetX + maxY * y.offsetX + maxZ * z.offsetX; + 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) { + aX += 1; + bX += 1; + } + + if (x.offsetY + y.offsetY + z.offsetY < 0) { + aY += 1; + bY += 1; + } + + if (x.offsetZ + y.offsetZ + z.offsetZ < 0) { + aZ += 1; + bZ += 1; + } + + renderer.renderMinX = Math.min(aX, bX); + renderer.renderMinY = Math.min(aY, bY); + renderer.renderMinZ = Math.min(aZ, bZ); + renderer.renderMaxX = Math.max(aX, bX); + renderer.renderMaxY = Math.max(aY, bY); + renderer.renderMaxZ = Math.max(aZ, bZ); + } + + @SideOnly(Side.CLIENT) + protected void renderCutoutFace( + final B block, + final IIcon ico, + final int x, + final int y, + final int z, + final RenderBlocks renderer, + final ForgeDirection orientation, + final float edgeThickness + ) { + final Tessellator tess = Tessellator.instance; + + double offsetX = 0.0; + double offsetY = 0.0; + double offsetZ = 0.0; + double layerAX = 0.0; + double layerAZ = 0.0; + double layerBY = 0.0; + double layerBZ = 0.0; + + boolean flip = false; + switch (orientation) { + case NORTH: + + layerAX = 1.0; + layerBY = 1.0; + flip = true; + + break; + case SOUTH: + + layerAX = 1.0; + layerBY = 1.0; + offsetZ = 1.0; + + break; + case EAST: + + flip = true; + layerAZ = 1.0; + layerBY = 1.0; + offsetX = 1.0; + + break; + case WEST: + + layerAZ = 1.0; + layerBY = 1.0; + + break; + case UP: + + flip = true; + layerAX = 1.0; + layerBZ = 1.0; + offsetY = 1.0; + + break; + case DOWN: + + layerAX = 1.0; + layerBZ = 1.0; + + break; + default: + break; + } + + offsetX += x; + offsetY += y; + offsetZ += z; + + final double layerBX = 0.0; + final double layerAY = 0.0; + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 0, + 1.0, + // v -> v + 0, + edgeThickness, + ico, + flip + ); + + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 0.0, + edgeThickness, + // v -> v + edgeThickness, + 1.0 - edgeThickness, + ico, + flip + ); + + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 1.0 - edgeThickness, + 1.0, + // v -> v + edgeThickness, + 1.0 - edgeThickness, + ico, + flip + ); + + this.renderFace( + tess, + offsetX, + offsetY, + offsetZ, + layerAX, + layerAY, + layerAZ, + layerBX, + layerBY, + layerBZ, + // u -> u + 0, + 1.0, + // v -> v + 1.0 - edgeThickness, + 1.0, + ico, + flip + ); + } + + @SideOnly(Side.CLIENT) + private void renderFace( + final Tessellator tess, + final double offsetX, + final double offsetY, + final double offsetZ, + final double ax, + final double ay, + final double az, + final double bx, + final double by, + final double bz, + final double ua, + final double ub, + final double va, + final double vb, + final IIcon ico, + final boolean 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) + ); + tess.addVertexWithUV( + offsetX + ax * ub + bx * vb, + offsetY + ay * ub + by * vb, + offsetZ + az * ub + bz * vb, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(vb * 16.0) + ); + tess.addVertexWithUV( + offsetX + ax * ub + bx * va, + offsetY + ay * ub + by * va, + offsetZ + az * ub + bz * va, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(va * 16.0) + ); + } else { + 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 * ub + bx * va, + offsetY + ay * ub + by * va, + offsetZ + az * ub + bz * va, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(va * 16.0) + ); + tess.addVertexWithUV( + offsetX + ax * ub + bx * vb, + offsetY + ay * ub + by * vb, + offsetZ + az * ub + bz * vb, + ico.getInterpolatedU(ub * 16.0), + ico.getInterpolatedV(vb * 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) + ); + } + } + + @SideOnly(Side.CLIENT) + protected void renderFace( + final int x, + final int y, + final int z, + final B block, + final IIcon ico, + final RenderBlocks renderer, + final ForgeDirection orientation + ) { + switch (orientation) { + case NORTH: + renderer.renderFaceZNeg(block, x, y, z, ico); + break; + case SOUTH: + renderer.renderFaceZPos(block, x, y, z, ico); + break; + case EAST: + renderer.renderFaceXPos(block, x, y, z, ico); + break; + case WEST: + renderer.renderFaceXNeg(block, x, y, z, ico); + break; + case UP: + renderer.renderFaceYPos(block, x, y, z, ico); + break; + case DOWN: + renderer.renderFaceYNeg(block, x, y, z, ico); + break; + default: + break; + } + } + + public void selectFace( + final RenderBlocks renderer, + final ForgeDirection west, + final ForgeDirection up, + final ForgeDirection forward, + final int u1, + final int u2, + int v1, + int v2 + ) { + v1 = 16 - v1; + v2 = 16 - v2; + + final double minX = (forward.offsetX > 0 ? 1 : 0) + + this.mapFaceUV(west.offsetX, u1) + this.mapFaceUV(up.offsetX, v1); + final double minY = (forward.offsetY > 0 ? 1 : 0) + + this.mapFaceUV(west.offsetY, u1) + this.mapFaceUV(up.offsetY, v1); + final double minZ = (forward.offsetZ > 0 ? 1 : 0) + + this.mapFaceUV(west.offsetZ, u1) + this.mapFaceUV(up.offsetZ, v1); + + final double maxX = (forward.offsetX > 0 ? 1 : 0) + + this.mapFaceUV(west.offsetX, u2) + this.mapFaceUV(up.offsetX, v2); + final double maxY = (forward.offsetY > 0 ? 1 : 0) + + this.mapFaceUV(west.offsetY, u2) + this.mapFaceUV(up.offsetY, v2); + final double maxZ = (forward.offsetZ > 0 ? 1 : 0) + + this.mapFaceUV(west.offsetZ, u2) + this.mapFaceUV(up.offsetZ, v2); + + renderer.renderMinX + = Math.max(0.0, Math.min(minX, maxX) - (forward.offsetX != 0 ? 0 : 0.001)); + renderer.renderMaxX + = Math.min(1.0, Math.max(minX, maxX) + (forward.offsetX != 0 ? 0 : 0.001)); + + renderer.renderMinY + = Math.max(0.0, Math.min(minY, maxY) - (forward.offsetY != 0 ? 0 : 0.001)); + renderer.renderMaxY + = Math.min(1.0, Math.max(minY, maxY) + (forward.offsetY != 0 ? 0 : 0.001)); + + renderer.renderMinZ + = Math.max(0.0, Math.min(minZ, maxZ) - (forward.offsetZ != 0 ? 0 : 0.001)); + renderer.renderMaxZ + = Math.min(1.0, Math.max(minZ, maxZ) + (forward.offsetZ != 0 ? 0 : 0.001)); + } + + private double mapFaceUV(final int offset, final int uv) { + if (offset == 0) { + return 0; + } + + if (offset > 0) { + return uv / 16.0; + } + + return (16.0 - uv) / 16.0; + } + + public void renderTile( + final B block, + final T tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer + ) { + renderer.uvRotateBottom = renderer.uvRotateTop = renderer.uvRotateEast + = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; + + final ForgeDirection up = ForgeDirection.UP; + final ForgeDirection forward = ForgeDirection.SOUTH; + this.applyTESRRotation(x, y, z, forward, up); + + Minecraft.getMinecraft().getTextureManager().bindTexture( + TextureMap.locationBlocksTexture + ); + RenderHelper.disableStandardItemLighting(); + + if (Minecraft.isAmbientOcclusionEnabled()) { + GL11.glShadeModel(GL11.GL_SMOOTH); + } else { + GL11.glShadeModel(GL11.GL_FLAT); + } + + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + + tess.setTranslation(-tile.xCoord, -tile.yCoord, -tile.zCoord); + tess.startDrawingQuads(); + + // note that this is a terrible approach... + renderer.setRenderBoundsFromBlock(block); + renderer.renderStandardBlock(block, tile.xCoord, tile.yCoord, tile.zCoord); + + tess.draw(); + tess.setTranslation(0, 0, 0); + RenderHelper.enableStandardItemLighting(); + + renderer.uvRotateBottom = renderer.uvRotateTop = renderer.uvRotateEast + = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = 0; + } + + protected void applyTESRRotation( + final double x, + final double y, + final double z, + ForgeDirection forward, + ForgeDirection up + ) { + if (forward != null && up != null) { + if (forward == ForgeDirection.UNKNOWN) { + forward = ForgeDirection.SOUTH; + } + + if (up == ForgeDirection.UNKNOWN) { + up = ForgeDirection.UP; + } + + final ForgeDirection west = Platform.crossProduct(forward, up); + + this.rotMat.put(0, west.offsetX); + this.rotMat.put(1, west.offsetY); + this.rotMat.put(2, west.offsetZ); + this.rotMat.put(3, 0); + + this.rotMat.put(4, up.offsetX); + this.rotMat.put(5, up.offsetY); + this.rotMat.put(6, up.offsetZ); + this.rotMat.put(7, 0); + + this.rotMat.put(8, forward.offsetX); + this.rotMat.put(9, forward.offsetY); + this.rotMat.put(10, forward.offsetZ); + this.rotMat.put(11, 0); + + this.rotMat.put(12, 0); + this.rotMat.put(13, 0); + this.rotMat.put(14, 0); + this.rotMat.put(15, 1); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); + GL11.glMultMatrix(this.rotMat); + GL11.glTranslated(-0.5, -0.5, -0.5); + } else { + GL11.glTranslated(x, y, z); + } + } + + public void + doRenderItem(final ItemStack itemstack, final TileEntity par1EntityItemFrame) { + if (itemstack != null) { + final EntityItem entityitem = new EntityItem( + par1EntityItemFrame.getWorldObj(), 0.0D, 0.0D, 0.0D, itemstack + ); + + entityitem.getEntityItem().stackSize = 1; + + // set all this stuff and then do shit? meh? + entityitem.hoverStart = 0; + entityitem.age = 0; + entityitem.rotationYaw = 0; + + GL11.glPushMatrix(); + GL11.glTranslatef(0, -0.14F, 0); + + RenderItem.renderInFrame = true; + RenderManager.instance.renderEntityWithPosYaw( + entityitem, 0.0D, 0.0D, 0.0D, 0.0F, 0.0F + ); + RenderItem.renderInFrame = false; + + GL11.glPopMatrix(); + } + } } diff --git a/src/main/java/appeng/client/render/BlockRenderInfo.java b/src/main/java/appeng/client/render/BlockRenderInfo.java index 928a5d6e..8f9464f5 100644 --- a/src/main/java/appeng/client/render/BlockRenderInfo.java +++ b/src/main/java/appeng/client/render/BlockRenderInfo.java @@ -18,7 +18,6 @@ package appeng.client.render; - import appeng.block.AEBaseBlock; import appeng.client.texture.FlippableIcon; import appeng.client.texture.TmpFlippableIcon; @@ -26,120 +25,134 @@ import appeng.tile.AEBaseTile; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; +public class BlockRenderInfo { + private final BaseBlockRender + rendererInstance; + 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; + private FlippableIcon northIcon = null; + private FlippableIcon eastIcon = null; + private FlippableIcon westIcon = null; -public class BlockRenderInfo -{ + public BlockRenderInfo( + final BaseBlockRender inst + ) { + this.rendererInstance = inst; + } - private final BaseBlockRender rendererInstance; - 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; - private FlippableIcon northIcon = null; - private FlippableIcon eastIcon = null; - private FlippableIcon westIcon = null; + public void updateIcons( + final FlippableIcon bottom, + final FlippableIcon top, + final FlippableIcon north, + final FlippableIcon south, + final FlippableIcon east, + final FlippableIcon west + ) { + this.topIcon = top; + this.bottomIcon = bottom; + this.southIcon = south; + this.northIcon = north; + this.eastIcon = east; + this.westIcon = west; + } - public BlockRenderInfo( final BaseBlockRender inst ) - { - this.rendererInstance = inst; - } + public void setTemporaryRenderIcon(final IIcon icon) { + if (icon == null) { + this.useTmp = false; + } else { + this.useTmp = true; + this.tmpTopIcon.setOriginal(icon); + this.tmpBottomIcon.setOriginal(icon); + this.tmpSouthIcon.setOriginal(icon); + this.tmpNorthIcon.setOriginal(icon); + this.tmpEastIcon.setOriginal(icon); + this.tmpWestIcon.setOriginal(icon); + } + } - public void updateIcons( final FlippableIcon bottom, final FlippableIcon top, final FlippableIcon north, final FlippableIcon south, final FlippableIcon east, final FlippableIcon west ) - { - this.topIcon = top; - this.bottomIcon = bottom; - this.southIcon = south; - this.northIcon = north; - this.eastIcon = east; - this.westIcon = west; - } + public void setTemporaryRenderIcons( + final IIcon nTopIcon, + final IIcon nBottomIcon, + final IIcon nSouthIcon, + final IIcon nNorthIcon, + final IIcon nEastIcon, + final IIcon nWestIcon + ) { + this.tmpTopIcon.setOriginal( + nTopIcon == null ? this.getTexture(ForgeDirection.UP) : nTopIcon + ); + this.tmpBottomIcon.setOriginal( + nBottomIcon == null ? this.getTexture(ForgeDirection.DOWN) : nBottomIcon + ); + this.tmpSouthIcon.setOriginal( + nSouthIcon == null ? this.getTexture(ForgeDirection.SOUTH) : nSouthIcon + ); + this.tmpNorthIcon.setOriginal( + nNorthIcon == null ? this.getTexture(ForgeDirection.NORTH) : nNorthIcon + ); + this.tmpEastIcon.setOriginal( + nEastIcon == null ? this.getTexture(ForgeDirection.EAST) : nEastIcon + ); + this.tmpWestIcon.setOriginal( + nWestIcon == null ? this.getTexture(ForgeDirection.WEST) : nWestIcon + ); + this.useTmp = true; + } - public void setTemporaryRenderIcon( final IIcon icon ) - { - if( icon == null ) - { - this.useTmp = false; - } - else - { - this.useTmp = true; - this.tmpTopIcon.setOriginal( icon ); - this.tmpBottomIcon.setOriginal( icon ); - this.tmpSouthIcon.setOriginal( icon ); - this.tmpNorthIcon.setOriginal( icon ); - this.tmpEastIcon.setOriginal( icon ); - this.tmpWestIcon.setOriginal( icon ); - } - } + public FlippableIcon getTexture(final ForgeDirection dir) { + if (this.useTmp) { + 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; + } + } - public void setTemporaryRenderIcons( final IIcon nTopIcon, final IIcon nBottomIcon, final IIcon nSouthIcon, final IIcon nNorthIcon, final IIcon nEastIcon, final IIcon nWestIcon ) - { - this.tmpTopIcon.setOriginal( nTopIcon == null ? this.getTexture( ForgeDirection.UP ) : nTopIcon ); - this.tmpBottomIcon.setOriginal( nBottomIcon == null ? this.getTexture( ForgeDirection.DOWN ) : nBottomIcon ); - this.tmpSouthIcon.setOriginal( nSouthIcon == null ? this.getTexture( ForgeDirection.SOUTH ) : nSouthIcon ); - this.tmpNorthIcon.setOriginal( nNorthIcon == null ? this.getTexture( ForgeDirection.NORTH ) : nNorthIcon ); - this.tmpEastIcon.setOriginal( nEastIcon == null ? this.getTexture( ForgeDirection.EAST ) : nEastIcon ); - this.tmpWestIcon.setOriginal( nWestIcon == null ? this.getTexture( ForgeDirection.WEST ) : nWestIcon ); - this.useTmp = true; - } + 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; + } - public FlippableIcon getTexture( final ForgeDirection dir ) - { - if( this.useTmp ) - { - 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; - } - } + return this.topIcon; + } - 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; - } + boolean isValid() { + return this.topIcon != null && this.bottomIcon != null && this.southIcon != null + && this.northIcon != null && this.eastIcon != null && this.westIcon != null; + } - return this.topIcon; - } - - boolean isValid() - { - return this.topIcon != null && this.bottomIcon != null && this.southIcon != null && this.northIcon != null && this.eastIcon != null && this.westIcon != null; - } - - public BaseBlockRender getRendererInstance() - { - return this.rendererInstance; - } + public BaseBlockRender getRendererInstance() { + return this.rendererInstance; + } } diff --git a/src/main/java/appeng/client/render/BusRenderHelper.java b/src/main/java/appeng/client/render/BusRenderHelper.java index a60d6865..0018cd66 100644 --- a/src/main/java/appeng/client/render/BusRenderHelper.java +++ b/src/main/java/appeng/client/render/BusRenderHelper.java @@ -18,6 +18,8 @@ package appeng.client.render; +import java.util.EnumSet; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; @@ -40,594 +42,662 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; -import java.util.EnumSet; - - -@SideOnly( Side.CLIENT ) -public final class BusRenderHelper implements IPartRenderHelper -{ - public static final BusRenderHelper INSTANCE = new BusRenderHelper(); - private static final int HEX_WHITE = 0xffffff; - - private final BoundBoxCalculator bbc; - private final boolean noAlphaPass; - private final BaseBlockRender bbr; - private final Optional maybeBlock; - private final Optional maybeBaseBlock; - private int renderingForPass; - private int currentPass; - private int itemsRendered; - private double minX; - private double minY; - private double minZ; - private double maxX; - private double maxY; - private double maxZ; - private ForgeDirection ax; - private ForgeDirection ay; - private ForgeDirection az; - private int color; - - public BusRenderHelper() - { - this.bbc = new BoundBoxCalculator( this ); - this.noAlphaPass = !AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ); - this.bbr = new BaseBlockRender(); - this.renderingForPass = 0; - this.currentPass = 0; - this.itemsRendered = 0; - this.minX = 0; - this.minY = 0; - this.minZ = 0; - this.maxX = 16; - this.maxY = 16; - this.maxZ = 16; - this.ax = ForgeDirection.EAST; - this.az = ForgeDirection.SOUTH; - this.ay = ForgeDirection.UP; - this.color = HEX_WHITE; - this.maybeBlock = AEApi.instance().definitions().blocks().multiPart().maybeBlock(); - this.maybeBaseBlock = this.maybeBlock.transform( new BaseBlockTransformFunction() ); - } - - public int getItemsRendered() - { - return this.itemsRendered; - } - - public void setPass( final int pass ) - { - this.renderingForPass = 0; - this.currentPass = pass; - this.itemsRendered = 0; - } - - public double getBound( final ForgeDirection side ) - { - switch( side ) - { - default: - case UNKNOWN: - return 0.5; - case DOWN: - return this.minY; - case EAST: - return this.maxX; - case NORTH: - return this.minZ; - case SOUTH: - return this.maxZ; - case UP: - return this.maxY; - case WEST: - return this.minX; - } - } - - public void setRenderColor( final int color ) - { - for( final Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) - { - final BlockCableBus cableBus = (BlockCableBus) block; - cableBus.setRenderColor( color ); - } - } - - public void setOrientation( final ForgeDirection dx, final ForgeDirection dy, final ForgeDirection dz ) - { - this.ax = dx == null ? ForgeDirection.EAST : dx; - this.ay = dy == null ? ForgeDirection.UP : dy; - this.az = dz == null ? ForgeDirection.SOUTH : dz; - } - - public double[] getBounds() - { - return new double[] { this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ }; - } - - public void setBounds( final double[] bounds ) - { - if( bounds == null || bounds.length != 6 ) - { - return; - } - - this.minX = bounds[0]; - this.minY = bounds[1]; - this.minZ = bounds[2]; - this.maxX = bounds[3]; - this.maxY = bounds[4]; - this.maxZ = bounds[5]; - } - - private static class BoundBoxCalculator implements IPartCollisionHelper - { - private final BusRenderHelper helper; - private boolean started = false; - - private float minX; - private float minY; - private float minZ; - - private float maxX; - private float maxY; - private float maxZ; - - public BoundBoxCalculator( final BusRenderHelper helper ) - { - this.helper = helper; - } - - @Override - public void addBox( final double minX, final double minY, final double minZ, final double maxX, final double maxY, final double maxZ ) - { - if( this.started ) - { - this.minX = Math.min( this.minX, (float) minX ); - this.minY = Math.min( this.minY, (float) minY ); - this.minZ = Math.min( this.minZ, (float) minZ ); - this.maxX = Math.max( this.maxX, (float) maxX ); - this.maxY = Math.max( this.maxY, (float) maxY ); - this.maxZ = Math.max( this.maxZ, (float) maxZ ); - } - else - { - this.started = true; - this.minX = (float) minX; - this.minY = (float) minY; - this.minZ = (float) minZ; - this.maxX = (float) maxX; - this.maxY = (float) maxY; - this.maxZ = (float) maxZ; - } - } - - @Override - public ForgeDirection getWorldX() - { - return this.helper.ax; - } - - @Override - public ForgeDirection getWorldY() - { - return this.helper.ay; - } - - @Override - public ForgeDirection getWorldZ() - { - return this.helper.az; - } - - @Override - public boolean isBBCollision() - { - return false; - } - } - - - private static final class BaseBlockTransformFunction implements Function - { - @Nullable - @Override - public AEBaseBlock apply( final Block input ) - { - if( input instanceof AEBaseBlock ) - { - return ( (AEBaseBlock) input ); - } - - return null; - } - } - - @Override - public void renderForPass( final int pass ) - { - this.renderingForPass = pass; - } - - private boolean renderThis() - { - if( this.renderingForPass == this.currentPass || this.noAlphaPass ) - { - this.itemsRendered++; - return true; - } - return false; - } - - @Override - public void normalRendering() - { - final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); - rbw.setCalculations( true ); - rbw.setUseTextures( true ); - rbw.enableAO = false; - } - - @Override - public ISimplifiedBundle useSimplifiedRendering( final int x, final int y, final int z, final IBoxProvider p, final ISimplifiedBundle sim ) - { - final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); - - if( sim != null && this.maybeBlock.isPresent() && rbw.similarLighting( this.maybeBlock.get(), rbw.blockAccess, x, y, z, sim ) ) - { - rbw.populate( sim ); - rbw.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - rbw.setCalculations( false ); - rbw.setUseTextures( false ); - - return sim; - } - else - { - final boolean allFaces = rbw.renderAllFaces; - rbw.renderAllFaces = true; - rbw.setCalculations( true ); - rbw.getFaces().clear(); - - this.bbc.started = false; - if( p == null ) - { - this.bbc.minX = this.bbc.minY = this.bbc.minZ = 0; - this.bbc.maxX = this.bbc.maxY = this.bbc.maxZ = 16; - } - else - { - p.getBoxes( this.bbc ); - - if( this.bbc.minX < 1 ) - { - this.bbc.minX = 1; - } - if( this.bbc.minY < 1 ) - { - this.bbc.minY = 1; - } - if( this.bbc.minZ < 1 ) - { - this.bbc.minZ = 1; - } - - if( this.bbc.maxX > 15 ) - { - this.bbc.maxX = 15; - } - if( this.bbc.maxY > 15 ) - { - this.bbc.maxY = 15; - } - if( this.bbc.maxZ > 15 ) - { - this.bbc.maxZ = 15; - } - } - - this.setBounds( this.bbc.minX, this.bbc.minY, this.bbc.minZ, this.bbc.maxX, this.bbc.maxY, this.bbc.maxZ ); - - this.bbr.renderBlockBounds( rbw, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az ); - - for( final Block block : this.maybeBlock.asSet() ) - { - rbw.renderStandardBlock( block, x, y, z ); - } - - rbw.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - rbw.renderAllFaces = allFaces; - rbw.setCalculations( false ); - rbw.setUseTextures( false ); - - return rbw.getLightingCache(); - } - } - - @Override - public void setBounds( final float minX, final float minY, final float minZ, final float maxX, final float maxY, final float maxZ ) - { - this.minX = minX; - this.minY = minY; - this.minZ = minZ; - this.maxX = maxX; - this.maxY = maxY; - this.maxZ = maxZ; - } - - @Override - public void setInvColor( final int newColor ) - { - this.color = newColor; - } - - @Override - public void setTexture( final IIcon ico ) - { - for( final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) - { - baseBlock.getRendererInstance().setTemporaryRenderIcon( ico ); - } - } - - @Override - public void setTexture( final IIcon down, final IIcon up, final IIcon north, final IIcon south, final IIcon west, final IIcon east ) - { - final IIcon[] list = new IIcon[6]; - - list[0] = down; - list[1] = up; - list[2] = north; - list[3] = south; - list[4] = west; - list[5] = east; - - for( final 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()] ); - } - } - - private ForgeDirection mapRotation( final ForgeDirection dir ) - { - final ForgeDirection forward = this.az; - final ForgeDirection up = this.ay; - - if( forward == null || up == null ) - { - return dir; - } - - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - - ForgeDirection west = ForgeDirection.UNKNOWN; - for( final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS ) - { - if( dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z ) - { - west = dx; - } - } - - if( dir == forward ) - { - return ForgeDirection.SOUTH; - } - if( dir == forward.getOpposite() ) - { - return ForgeDirection.NORTH; - } - - if( dir == up ) - { - return ForgeDirection.UP; - } - if( dir == up.getOpposite() ) - { - return ForgeDirection.DOWN; - } - - if( dir == west ) - { - return ForgeDirection.WEST; - } - if( dir == west.getOpposite() ) - { - return ForgeDirection.EAST; - } - - return ForgeDirection.UNKNOWN; - } - - @Override - public void renderInventoryBox( final RenderBlocks renderer ) - { - 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( final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), baseBlock, null, Tessellator.instance, this.color, renderer ); - } - } - - @Override - public void renderInventoryFace( final IIcon icon, final ForgeDirection face, final RenderBlocks renderer ) - { - 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( icon ); - - for( final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderInvBlock( EnumSet.of( face ), baseBlock, null, Tessellator.instance, this.color, renderer ); - } - } - - @Override - public void renderBlock( final int x, final int y, final int z, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - for( final Block multiPart : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) - { - final AEBaseBlock block = (AEBaseBlock) multiPart; - - final BlockRenderInfo info = block.getRendererInstance(); - final ForgeDirection forward = BusRenderHelper.INSTANCE.az; - final ForgeDirection up = BusRenderHelper.INSTANCE.ay; - - renderer.uvRotateBottom = info.getTexture( ForgeDirection.DOWN ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.DOWN, forward, up ) ); - renderer.uvRotateTop = info.getTexture( ForgeDirection.UP ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.UP, forward, up ) ); - - renderer.uvRotateEast = info.getTexture( ForgeDirection.EAST ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.EAST, forward, up ) ); - renderer.uvRotateWest = info.getTexture( ForgeDirection.WEST ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.WEST, forward, up ) ); - - renderer.uvRotateNorth = info.getTexture( ForgeDirection.NORTH ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.NORTH, forward, up ) ); - renderer.uvRotateSouth = info.getTexture( ForgeDirection.SOUTH ).setFlip( BaseBlockRender.getOrientation( ForgeDirection.SOUTH, forward, up ) ); - - this.bbr.renderBlockBounds( renderer, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az ); - - renderer.renderStandardBlock( block, x, y, z ); - } - } - - @Override - public Block getBlock() - { - for( final Block block : AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet() ) - { - return block; - } - - throw new MissingDefinition( "Tried to access the multi part block without it being defined." ); - } - - public void prepareBounds( final RenderBlocks renderer ) - { - this.bbr.renderBlockBounds( renderer, this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ, this.ax, this.ay, this.az ); - } - - @Override - public void setFacesToRender( final EnumSet faces ) - { - BusRenderer.INSTANCE.getRenderer().setRenderFaces( faces ); - } - - @Override - public void renderBlockCurrentBounds( final int x, final int y, final int z, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - for( final Block block : this.maybeBlock.asSet() ) - { - renderer.renderStandardBlock( block, x, y, z ); - } - } - - @Override - public void renderFaceCutout( final int x, final int y, final int z, final IIcon ico, ForgeDirection face, final float edgeThickness, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - switch( face ) - { - case DOWN: - face = this.ay.getOpposite(); - break; - case EAST: - face = this.ax; - break; - case NORTH: - face = this.az.getOpposite(); - break; - case SOUTH: - face = this.az; - break; - case UP: - face = this.ay; - break; - case WEST: - face = this.ax.getOpposite(); - break; - case UNKNOWN: - break; - default: - break; - } - - for( final AEBaseBlock block : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderCutoutFace( block, ico, x, y, z, renderer, face, edgeThickness ); - } - } - - @Override - public void renderFace( final int x, final int y, final int z, final IIcon ico, ForgeDirection face, final RenderBlocks renderer ) - { - if( !this.renderThis() ) - { - return; - } - - this.prepareBounds( renderer ); - switch( face ) - { - case DOWN: - face = this.ay.getOpposite(); - break; - case EAST: - face = this.ax; - break; - case NORTH: - face = this.az.getOpposite(); - break; - case SOUTH: - face = this.az; - break; - case UP: - face = this.ay; - break; - case WEST: - face = this.ax.getOpposite(); - break; - case UNKNOWN: - break; - default: - break; - } - - for( final AEBaseBlock block : this.maybeBaseBlock.asSet() ) - { - this.bbr.renderFace( x, y, z, block, ico, renderer, face ); - } - } - - @Override - public ForgeDirection getWorldX() - { - return this.ax; - } - - @Override - public ForgeDirection getWorldY() - { - return this.ay; - } - - @Override - public ForgeDirection getWorldZ() - { - return this.az; - } +@SideOnly(Side.CLIENT) +public final class BusRenderHelper implements IPartRenderHelper { + public static final BusRenderHelper INSTANCE = new BusRenderHelper(); + private static final int HEX_WHITE = 0xffffff; + + private final BoundBoxCalculator bbc; + private final boolean noAlphaPass; + private final BaseBlockRender bbr; + private final Optional maybeBlock; + private final Optional maybeBaseBlock; + private int renderingForPass; + private int currentPass; + private int itemsRendered; + private double minX; + private double minY; + private double minZ; + private double maxX; + private double maxY; + private double maxZ; + private ForgeDirection ax; + private ForgeDirection ay; + private ForgeDirection az; + private int color; + + public BusRenderHelper() { + this.bbc = new BoundBoxCalculator(this); + this.noAlphaPass = !AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass); + this.bbr = new BaseBlockRender(); + this.renderingForPass = 0; + this.currentPass = 0; + this.itemsRendered = 0; + this.minX = 0; + this.minY = 0; + this.minZ = 0; + this.maxX = 16; + this.maxY = 16; + this.maxZ = 16; + this.ax = ForgeDirection.EAST; + this.az = ForgeDirection.SOUTH; + this.ay = ForgeDirection.UP; + this.color = HEX_WHITE; + this.maybeBlock + = AEApi.instance().definitions().blocks().multiPart().maybeBlock(); + this.maybeBaseBlock = this.maybeBlock.transform(new BaseBlockTransformFunction()); + } + + public int getItemsRendered() { + return this.itemsRendered; + } + + public void setPass(final int pass) { + this.renderingForPass = 0; + this.currentPass = pass; + this.itemsRendered = 0; + } + + public double getBound(final ForgeDirection side) { + switch (side) { + default: + case UNKNOWN: + return 0.5; + case DOWN: + return this.minY; + case EAST: + return this.maxX; + case NORTH: + return this.minZ; + case SOUTH: + return this.maxZ; + case UP: + return this.maxY; + case WEST: + return this.minX; + } + } + + public void setRenderColor(final int color) { + for (final Block block : + AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet()) { + final BlockCableBus cableBus = (BlockCableBus) block; + cableBus.setRenderColor(color); + } + } + + public void setOrientation( + final ForgeDirection dx, final ForgeDirection dy, final ForgeDirection dz + ) { + this.ax = dx == null ? ForgeDirection.EAST : dx; + this.ay = dy == null ? ForgeDirection.UP : dy; + this.az = dz == null ? ForgeDirection.SOUTH : dz; + } + + public double[] getBounds() { + return new double[] { this.minX, this.minY, this.minZ, + this.maxX, this.maxY, this.maxZ }; + } + + public void setBounds(final double[] bounds) { + if (bounds == null || bounds.length != 6) { + return; + } + + this.minX = bounds[0]; + this.minY = bounds[1]; + this.minZ = bounds[2]; + this.maxX = bounds[3]; + this.maxY = bounds[4]; + this.maxZ = bounds[5]; + } + + private static class BoundBoxCalculator implements IPartCollisionHelper { + private final BusRenderHelper helper; + private boolean started = false; + + private float minX; + private float minY; + private float minZ; + + private float maxX; + private float maxY; + private float maxZ; + + public BoundBoxCalculator(final BusRenderHelper helper) { + this.helper = helper; + } + + @Override + public void addBox( + final double minX, + final double minY, + final double minZ, + final double maxX, + final double maxY, + final double maxZ + ) { + if (this.started) { + this.minX = Math.min(this.minX, (float) minX); + this.minY = Math.min(this.minY, (float) minY); + this.minZ = Math.min(this.minZ, (float) minZ); + this.maxX = Math.max(this.maxX, (float) maxX); + this.maxY = Math.max(this.maxY, (float) maxY); + this.maxZ = Math.max(this.maxZ, (float) maxZ); + } else { + this.started = true; + this.minX = (float) minX; + this.minY = (float) minY; + this.minZ = (float) minZ; + this.maxX = (float) maxX; + this.maxY = (float) maxY; + this.maxZ = (float) maxZ; + } + } + + @Override + public ForgeDirection getWorldX() { + return this.helper.ax; + } + + @Override + public ForgeDirection getWorldY() { + return this.helper.ay; + } + + @Override + public ForgeDirection getWorldZ() { + return this.helper.az; + } + + @Override + public boolean isBBCollision() { + return false; + } + } + + private static final class BaseBlockTransformFunction + implements Function { + @Nullable + @Override + public AEBaseBlock apply(final Block input) { + if (input instanceof AEBaseBlock) { + return ((AEBaseBlock) input); + } + + return null; + } + } + + @Override + public void renderForPass(final int pass) { + this.renderingForPass = pass; + } + + private boolean renderThis() { + if (this.renderingForPass == this.currentPass || this.noAlphaPass) { + this.itemsRendered++; + return true; + } + return false; + } + + @Override + public void normalRendering() { + final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); + rbw.setCalculations(true); + rbw.setUseTextures(true); + rbw.enableAO = false; + } + + @Override + public ISimplifiedBundle useSimplifiedRendering( + final int x, + final int y, + final int z, + final IBoxProvider p, + final ISimplifiedBundle sim + ) { + final RenderBlocksWorkaround rbw = BusRenderer.INSTANCE.getRenderer(); + + if (sim != null && this.maybeBlock.isPresent() + && rbw.similarLighting( + this.maybeBlock.get(), rbw.blockAccess, x, y, z, sim + )) { + rbw.populate(sim); + rbw.setFaces(EnumSet.allOf(ForgeDirection.class)); + rbw.setCalculations(false); + rbw.setUseTextures(false); + + return sim; + } else { + final boolean allFaces = rbw.renderAllFaces; + rbw.renderAllFaces = true; + rbw.setCalculations(true); + rbw.getFaces().clear(); + + this.bbc.started = false; + if (p == null) { + this.bbc.minX = this.bbc.minY = this.bbc.minZ = 0; + this.bbc.maxX = this.bbc.maxY = this.bbc.maxZ = 16; + } else { + p.getBoxes(this.bbc); + + if (this.bbc.minX < 1) { + this.bbc.minX = 1; + } + if (this.bbc.minY < 1) { + this.bbc.minY = 1; + } + if (this.bbc.minZ < 1) { + this.bbc.minZ = 1; + } + + if (this.bbc.maxX > 15) { + this.bbc.maxX = 15; + } + if (this.bbc.maxY > 15) { + this.bbc.maxY = 15; + } + if (this.bbc.maxZ > 15) { + this.bbc.maxZ = 15; + } + } + + this.setBounds( + this.bbc.minX, + this.bbc.minY, + this.bbc.minZ, + this.bbc.maxX, + this.bbc.maxY, + this.bbc.maxZ + ); + + this.bbr.renderBlockBounds( + rbw, + this.minX, + this.minY, + this.minZ, + this.maxX, + this.maxY, + this.maxZ, + this.ax, + this.ay, + this.az + ); + + for (final Block block : this.maybeBlock.asSet()) { + rbw.renderStandardBlock(block, x, y, z); + } + + rbw.setFaces(EnumSet.allOf(ForgeDirection.class)); + rbw.renderAllFaces = allFaces; + rbw.setCalculations(false); + rbw.setUseTextures(false); + + return rbw.getLightingCache(); + } + } + + @Override + public void setBounds( + final float minX, + final float minY, + final float minZ, + final float maxX, + final float maxY, + final float maxZ + ) { + this.minX = minX; + this.minY = minY; + this.minZ = minZ; + this.maxX = maxX; + this.maxY = maxY; + this.maxZ = maxZ; + } + + @Override + public void setInvColor(final int newColor) { + this.color = newColor; + } + + @Override + public void setTexture(final IIcon ico) { + for (final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet()) { + baseBlock.getRendererInstance().setTemporaryRenderIcon(ico); + } + } + + @Override + public void setTexture( + final IIcon down, + final IIcon up, + final IIcon north, + final IIcon south, + final IIcon west, + final IIcon east + ) { + final IIcon[] list = new IIcon[6]; + + list[0] = down; + list[1] = up; + list[2] = north; + list[3] = south; + list[4] = west; + list[5] = east; + + for (final 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()] + ); + } + } + + private ForgeDirection mapRotation(final ForgeDirection dir) { + final ForgeDirection forward = this.az; + final ForgeDirection up = this.ay; + + if (forward == null || up == null) { + return dir; + } + + final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + + ForgeDirection west = ForgeDirection.UNKNOWN; + for (final ForgeDirection dx : ForgeDirection.VALID_DIRECTIONS) { + if (dx.offsetX == west_x && dx.offsetY == west_y && dx.offsetZ == west_z) { + west = dx; + } + } + + if (dir == forward) { + return ForgeDirection.SOUTH; + } + if (dir == forward.getOpposite()) { + return ForgeDirection.NORTH; + } + + if (dir == up) { + return ForgeDirection.UP; + } + if (dir == up.getOpposite()) { + return ForgeDirection.DOWN; + } + + if (dir == west) { + return ForgeDirection.WEST; + } + if (dir == west.getOpposite()) { + return ForgeDirection.EAST; + } + + return ForgeDirection.UNKNOWN; + } + + @Override + public void renderInventoryBox(final RenderBlocks renderer) { + 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 (final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet()) { + this.bbr.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + baseBlock, + null, + Tessellator.instance, + this.color, + renderer + ); + } + } + + @Override + public void renderInventoryFace( + final IIcon icon, final ForgeDirection face, final RenderBlocks renderer + ) { + 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(icon); + + for (final AEBaseBlock baseBlock : this.maybeBaseBlock.asSet()) { + this.bbr.renderInvBlock( + EnumSet.of(face), + baseBlock, + null, + Tessellator.instance, + this.color, + renderer + ); + } + } + + @Override + public void + renderBlock(final int x, final int y, final int z, final RenderBlocks renderer) { + if (!this.renderThis()) { + return; + } + + for (final Block multiPart : + AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet()) { + final AEBaseBlock block = (AEBaseBlock) multiPart; + + final BlockRenderInfo info = block.getRendererInstance(); + final ForgeDirection forward = BusRenderHelper.INSTANCE.az; + final ForgeDirection up = BusRenderHelper.INSTANCE.ay; + + renderer.uvRotateBottom + = info.getTexture(ForgeDirection.DOWN) + .setFlip( + BaseBlockRender.getOrientation(ForgeDirection.DOWN, forward, up) + ); + renderer.uvRotateTop + = info.getTexture(ForgeDirection.UP) + .setFlip( + BaseBlockRender.getOrientation(ForgeDirection.UP, forward, up) + ); + + renderer.uvRotateEast + = info.getTexture(ForgeDirection.EAST) + .setFlip( + BaseBlockRender.getOrientation(ForgeDirection.EAST, forward, up) + ); + renderer.uvRotateWest + = info.getTexture(ForgeDirection.WEST) + .setFlip( + BaseBlockRender.getOrientation(ForgeDirection.WEST, forward, up) + ); + + renderer.uvRotateNorth = info.getTexture(ForgeDirection.NORTH) + .setFlip(BaseBlockRender.getOrientation( + ForgeDirection.NORTH, forward, up + )); + renderer.uvRotateSouth = info.getTexture(ForgeDirection.SOUTH) + .setFlip(BaseBlockRender.getOrientation( + ForgeDirection.SOUTH, forward, up + )); + + this.bbr.renderBlockBounds( + renderer, + this.minX, + this.minY, + this.minZ, + this.maxX, + this.maxY, + this.maxZ, + this.ax, + this.ay, + this.az + ); + + renderer.renderStandardBlock(block, x, y, z); + } + } + + @Override + public Block getBlock() { + for (final Block block : + AEApi.instance().definitions().blocks().multiPart().maybeBlock().asSet()) { + return block; + } + + throw new MissingDefinition( + "Tried to access the multi part block without it being defined." + ); + } + + public void prepareBounds(final RenderBlocks renderer) { + this.bbr.renderBlockBounds( + renderer, + this.minX, + this.minY, + this.minZ, + this.maxX, + this.maxY, + this.maxZ, + this.ax, + this.ay, + this.az + ); + } + + @Override + public void setFacesToRender(final EnumSet faces) { + BusRenderer.INSTANCE.getRenderer().setRenderFaces(faces); + } + + @Override + public void renderBlockCurrentBounds( + final int x, final int y, final int z, final RenderBlocks renderer + ) { + if (!this.renderThis()) { + return; + } + + for (final Block block : this.maybeBlock.asSet()) { + renderer.renderStandardBlock(block, x, y, z); + } + } + + @Override + public void renderFaceCutout( + final int x, + final int y, + final int z, + final IIcon ico, + ForgeDirection face, + final float edgeThickness, + final RenderBlocks renderer + ) { + if (!this.renderThis()) { + return; + } + + switch (face) { + case DOWN: + face = this.ay.getOpposite(); + break; + case EAST: + face = this.ax; + break; + case NORTH: + face = this.az.getOpposite(); + break; + case SOUTH: + face = this.az; + break; + case UP: + face = this.ay; + break; + case WEST: + face = this.ax.getOpposite(); + break; + case UNKNOWN: + break; + default: + break; + } + + for (final AEBaseBlock block : this.maybeBaseBlock.asSet()) { + this.bbr.renderCutoutFace(block, ico, x, y, z, renderer, face, edgeThickness); + } + } + + @Override + public void renderFace( + final int x, + final int y, + final int z, + final IIcon ico, + ForgeDirection face, + final RenderBlocks renderer + ) { + if (!this.renderThis()) { + return; + } + + this.prepareBounds(renderer); + switch (face) { + case DOWN: + face = this.ay.getOpposite(); + break; + case EAST: + face = this.ax; + break; + case NORTH: + face = this.az.getOpposite(); + break; + case SOUTH: + face = this.az; + break; + case UP: + face = this.ay; + break; + case WEST: + face = this.ax.getOpposite(); + break; + case UNKNOWN: + break; + default: + break; + } + + for (final AEBaseBlock block : this.maybeBaseBlock.asSet()) { + this.bbr.renderFace(x, y, z, block, ico, renderer, face); + } + } + + @Override + public ForgeDirection getWorldX() { + return this.ax; + } + + @Override + public ForgeDirection getWorldY() { + return this.ay; + } + + @Override + public ForgeDirection getWorldZ() { + return this.az; + } } diff --git a/src/main/java/appeng/client/render/BusRenderer.java b/src/main/java/appeng/client/render/BusRenderer.java index 0660bf57..39919a2d 100644 --- a/src/main/java/appeng/client/render/BusRenderer.java +++ b/src/main/java/appeng/client/render/BusRenderer.java @@ -18,6 +18,9 @@ package appeng.client.render; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; import appeng.api.parts.IAlphaPassItem; import appeng.api.parts.IFacadePart; @@ -37,153 +40,137 @@ import net.minecraftforge.client.IItemRenderer; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; +@SideOnly(Side.CLIENT) +public class BusRenderer implements IItemRenderer { + public static final BusRenderer INSTANCE = new BusRenderer(); + private static final Map RENDER_PART = new HashMap(); + private final RenderBlocksWorkaround renderer = new RenderBlocksWorkaround(); + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } -@SideOnly( Side.CLIENT ) -public class BusRenderer implements IItemRenderer -{ + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper + ) { + return true; + } - public static final BusRenderer INSTANCE = new BusRenderer(); - private static final Map RENDER_PART = new HashMap(); - private final RenderBlocksWorkaround renderer = new RenderBlocksWorkaround(); + @Override + public void + renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + if (item == null) { + return; + } - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_LIGHTING); - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return true; - } + 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); + GL11.glDisable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); + } else { + GL11.glAlphaFunc(GL11.GL_GREATER, 0.4f); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glDisable(GL11.GL_BLEND); + } - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - if( item == null ) - { - return; - } + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(-0.2f, -0.1f, -0.3f); + } - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glEnable( GL11.GL_LIGHTING ); + 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( 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 ); - GL11.glDisable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_BLEND ); - } - else - { - GL11.glAlphaFunc( GL11.GL_GREATER, 0.4f ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glDisable( GL11.GL_BLEND ); - } + if (type == ItemRenderType.INVENTORY) { + GL11.glTranslatef(0.0f, -0.1f, 0.0f); + } - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glTranslatef( -0.2f, -0.1f, -0.3f ); - } + GL11.glTranslated(0.2, 0.3, 0.1); + GL11.glScaled(1.2, 1.2, 1.); - 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 ); - } + GL11.glColor4f(1, 1, 1, 1); + Tessellator.instance.setColorOpaque_F(1, 1, 1); + Tessellator.instance.setBrightness(14 << 20 | 14 << 4); - if( type == ItemRenderType.INVENTORY ) - { - GL11.glTranslatef( 0.0f, -0.1f, 0.0f ); - } + BusRenderHelper.INSTANCE.setBounds(0, 0, 0, 1, 1, 1); + BusRenderHelper.INSTANCE.setTexture(null); + BusRenderHelper.INSTANCE.setInvColor(0xffffff); + this.getRenderer().blockAccess = ClientHelper.proxy.getWorld(); - GL11.glTranslated( 0.2, 0.3, 0.1 ); - GL11.glScaled( 1.2, 1.2, 1. ); + BusRenderHelper.INSTANCE.setOrientation( + ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH + ); - GL11.glColor4f( 1, 1, 1, 1 ); - Tessellator.instance.setColorOpaque_F( 1, 1, 1 ); - Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); + this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast + = this.getRenderer().uvRotateNorth = this.getRenderer().uvRotateSouth + = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; + this.getRenderer().useInventoryTint = false; + this.getRenderer().overrideBlockTexture = null; - BusRenderHelper.INSTANCE.setBounds( 0, 0, 0, 1, 1, 1 ); - BusRenderHelper.INSTANCE.setTexture( null ); - BusRenderHelper.INSTANCE.setInvColor( 0xffffff ); - this.getRenderer().blockAccess = ClientHelper.proxy.getWorld(); + if (item.getItem() instanceof IFacadeItem) { + final IFacadeItem fi = (IFacadeItem) item.getItem(); + final IFacadePart fp = fi.createPartFromItemStack(item, ForgeDirection.SOUTH); - BusRenderHelper.INSTANCE.setOrientation( ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glRotatef(160.0f, 0.0f, 1.0f, 0.0f); + GL11.glTranslated(-0.4, 0.1, -1.6); + } - this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast = this.getRenderer().uvRotateNorth = this.getRenderer().uvRotateSouth = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; - this.getRenderer().useInventoryTint = false; - this.getRenderer().overrideBlockTexture = null; + if (fp != null) { + fp.renderInventory(BusRenderHelper.INSTANCE, this.getRenderer()); + } + } else { + final IPart ip = this.getRenderer(item, (IPartItem) item.getItem()); - if( item.getItem() instanceof IFacadeItem ) - { - final IFacadeItem fi = (IFacadeItem) item.getItem(); - final IFacadePart fp = fi.createPartFromItemStack( item, ForgeDirection.SOUTH ); + if (ip != null) { + if (type == ItemRenderType.ENTITY) { + final int depth = ip.cableConnectionRenderTo(); + GL11.glTranslatef(0.0f, 0.0f, -0.04f * (8 - depth) - 0.06f); + } - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glRotatef( 160.0f, 0.0f, 1.0f, 0.0f ); - GL11.glTranslated( -0.4, 0.1, -1.6 ); - } + ip.renderInventory(BusRenderHelper.INSTANCE, this.getRenderer()); + } + } - if( fp != null ) - { - fp.renderInventory( BusRenderHelper.INSTANCE, this.getRenderer() ); - } - } - else - { - final IPart ip = this.getRenderer( item, (IPartItem) item.getItem() ); + this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast + = this.getRenderer().uvRotateNorth = this.getRenderer().uvRotateSouth + = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; - if( ip != null ) - { - if( type == ItemRenderType.ENTITY ) - { - final int depth = ip.cableConnectionRenderTo(); - GL11.glTranslatef( 0.0f, 0.0f, -0.04f * ( 8 - depth ) - 0.06f ); - } + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } - ip.renderInventory( BusRenderHelper.INSTANCE, this.getRenderer() ); - } - } + @Nullable + private IPart getRenderer(final ItemStack is, final IPartItem c) { + final int id = (Item.getIdFromItem(is.getItem()) << Platform.DEF_OFFSET) + | is.getItemDamage(); - this.getRenderer().uvRotateBottom = this.getRenderer().uvRotateEast = this.getRenderer().uvRotateNorth = this.getRenderer().uvRotateSouth = this.getRenderer().uvRotateTop = this.getRenderer().uvRotateWest = 0; + IPart part = RENDER_PART.get(id); - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } + if (part == null) { + part = c.createPartFromItemStack(is); + if (part != null) { + RENDER_PART.put(id, part); + } + } - @Nullable - private IPart getRenderer( final ItemStack is, final IPartItem c ) - { - final int id = ( Item.getIdFromItem( is.getItem() ) << Platform.DEF_OFFSET ) | is.getItemDamage(); + return part; + } - IPart part = RENDER_PART.get( id ); - - if( part == null ) - { - part = c.createPartFromItemStack( is ); - if( part != null ) - { - RENDER_PART.put( id, part ); - } - } - - return part; - } - - public RenderBlocksWorkaround getRenderer() - { - return this.renderer; - } + public RenderBlocksWorkaround getRenderer() { + return this.renderer; + } } diff --git a/src/main/java/appeng/client/render/CableRenderHelper.java b/src/main/java/appeng/client/render/CableRenderHelper.java index 68e237d4..d9043dba 100644 --- a/src/main/java/appeng/client/render/CableRenderHelper.java +++ b/src/main/java/appeng/client/render/CableRenderHelper.java @@ -18,6 +18,9 @@ package appeng.client.render; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import appeng.api.parts.IFacadeContainer; import appeng.api.parts.IFacadePart; @@ -29,242 +32,242 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; +public class CableRenderHelper { + private static final CableRenderHelper INSTANCE = new CableRenderHelper(); + public static CableRenderHelper getInstance() { + return INSTANCE; + } -public class CableRenderHelper -{ + public void renderStatic( + final CableBusContainer cableBusContainer, final IFacadeContainer iFacadeContainer + ) { + final TileEntity te = cableBusContainer.getTile(); + final RenderBlocksWorkaround renderer = BusRenderer.INSTANCE.getRenderer(); - private static final CableRenderHelper INSTANCE = new CableRenderHelper(); + if (renderer.overrideBlockTexture != null) { + BusRenderHelper.INSTANCE.setPass(0); + } - public static CableRenderHelper getInstance() - { - return INSTANCE; - } + if (renderer.blockAccess == null) { + renderer.blockAccess = Minecraft.getMinecraft().theWorld; + } - public void renderStatic( final CableBusContainer cableBusContainer, final IFacadeContainer iFacadeContainer ) - { - final TileEntity te = cableBusContainer.getTile(); - final RenderBlocksWorkaround renderer = BusRenderer.INSTANCE.getRenderer(); + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = cableBusContainer.getPart(s); + if (part != null) { + this.setSide(s); + renderer.renderAllFaces = true; - if( renderer.overrideBlockTexture != null ) - { - BusRenderHelper.INSTANCE.setPass( 0 ); - } + renderer.flipTexture = false; + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop + = renderer.uvRotateWest = 0; - if( renderer.blockAccess == null ) - { - renderer.blockAccess = Minecraft.getMinecraft().theWorld; - } + part.renderStatic( + te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer + ); - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = cableBusContainer.getPart( s ); - if( part != null ) - { - this.setSide( s ); - renderer.renderAllFaces = true; + renderer.setFaces(EnumSet.allOf(ForgeDirection.class)); + renderer.setCalculations(true); + renderer.setUseTextures(true); + } + } - renderer.flipTexture = false; - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + if (!iFacadeContainer.isEmpty()) { + /** + * snag list of boxes... + */ + final List boxes = new ArrayList(); - part.renderStatic( te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer ); + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = cableBusContainer.getPart(s); + if (part != null) { + this.setSide(s); + final BusRenderHelper brh = BusRenderHelper.INSTANCE; + final BusCollisionHelper bch = new BusCollisionHelper( + boxes, + brh.getWorldX(), + brh.getWorldY(), + brh.getWorldZ(), + null, + true + ); + part.getBoxes(bch); + } + } - renderer.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - renderer.setCalculations( true ); - renderer.setUseTextures( true ); - } - } + boolean useThinFacades = false; + final double min = 2.0 / 16.0; + final double max = 14.0 / 16.0; - if( !iFacadeContainer.isEmpty() ) - { - /** - * snag list of boxes... - */ - final List boxes = new ArrayList(); + for (final AxisAlignedBB bb : boxes) { + int o = 0; + o += bb.maxX > max ? 1 : 0; + o += bb.maxY > max ? 1 : 0; + o += bb.maxZ > max ? 1 : 0; + o += bb.minX < min ? 1 : 0; + o += bb.minY < min ? 1 : 0; + o += bb.minZ < min ? 1 : 0; - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = cableBusContainer.getPart( s ); - if( part != null ) - { - this.setSide( s ); - final BusRenderHelper brh = BusRenderHelper.INSTANCE; - final BusCollisionHelper bch = new BusCollisionHelper( boxes, brh.getWorldX(), brh.getWorldY(), brh.getWorldZ(), null, true ); - part.getBoxes( bch ); - } - } + if (o >= 2) { + useThinFacades = true; + } + } - boolean useThinFacades = false; - final double min = 2.0 / 16.0; - final double max = 14.0 / 16.0; + for (final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) { + final IFacadePart fPart = iFacadeContainer.getFacade(s); - for( final AxisAlignedBB bb : boxes ) - { - int o = 0; - o += bb.maxX > max ? 1 : 0; - o += bb.maxY > max ? 1 : 0; - o += bb.maxZ > max ? 1 : 0; - o += bb.minX < min ? 1 : 0; - o += bb.minY < min ? 1 : 0; - o += bb.minZ < min ? 1 : 0; + if (fPart != null) { + fPart.setThinFacades(useThinFacades); + final AxisAlignedBB pb = fPart.getPrimaryBox(); + AxisAlignedBB b = null; + for (final AxisAlignedBB bb : boxes) { + if (bb.intersectsWith(pb)) { + if (b == null) { + b = bb; + } else { + b.maxX = Math.max(b.maxX, bb.maxX); + b.maxY = Math.max(b.maxY, bb.maxY); + b.maxZ = Math.max(b.maxZ, bb.maxZ); + b.minX = Math.min(b.minX, bb.minX); + b.minY = Math.min(b.minY, bb.minY); + b.minZ = Math.min(b.minZ, bb.minZ); + } + } + } - if( o >= 2 ) - { - useThinFacades = true; - } - } + renderer.flipTexture = false; + renderer.uvRotateBottom = renderer.uvRotateEast + = renderer.uvRotateNorth = renderer.uvRotateSouth + = renderer.uvRotateTop = renderer.uvRotateWest = 0; - for( final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) - { - final IFacadePart fPart = iFacadeContainer.getFacade( s ); + this.setSide(s); + fPart.renderStatic( + te.xCoord, + te.yCoord, + te.zCoord, + BusRenderHelper.INSTANCE, + renderer, + iFacadeContainer, + b, + cableBusContainer.getPart(s) == null + ); + } + } - if( fPart != null ) - { - fPart.setThinFacades( useThinFacades ); - final AxisAlignedBB pb = fPart.getPrimaryBox(); - AxisAlignedBB b = null; - for( final AxisAlignedBB bb : boxes ) - { - if( bb.intersectsWith( pb ) ) - { - if( b == null ) - { - b = bb; - } - else - { - b.maxX = Math.max( b.maxX, bb.maxX ); - b.maxY = Math.max( b.maxY, bb.maxY ); - b.maxZ = Math.max( b.maxZ, bb.maxZ ); - b.minX = Math.min( b.minX, bb.minX ); - b.minY = Math.min( b.minY, bb.minY ); - b.minZ = Math.min( b.minZ, bb.minZ ); - } - } - } + renderer.setFacade(false); + renderer.enableAO = false; + renderer.setTexture(null); + renderer.setCalculations(true); + } + } - renderer.flipTexture = false; - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + private void setSide(final ForgeDirection s) { + final ForgeDirection ax; + final ForgeDirection ay; + final ForgeDirection az; - this.setSide( s ); - fPart.renderStatic( te.xCoord, te.yCoord, te.zCoord, BusRenderHelper.INSTANCE, renderer, iFacadeContainer, b, cableBusContainer.getPart( s ) == null ); - } - } + 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; + } - renderer.setFacade( false ); - renderer.enableAO = false; - renderer.setTexture( null ); - renderer.setCalculations( true ); - } - } + BusRenderHelper.INSTANCE.setOrientation(ax, ay, az); + } - private void setSide( final ForgeDirection s ) - { - final ForgeDirection ax; - final ForgeDirection ay; - final ForgeDirection az; + public void renderDynamic( + final CableBusContainer cableBusContainer, + final double x, + final double y, + final double z + ) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = cableBusContainer.getPart(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; - } + if (part != null) { + final ForgeDirection ax; + final ForgeDirection ay; + final ForgeDirection az; - BusRenderHelper.INSTANCE.setOrientation( ax, ay, 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; + } - public void renderDynamic( final CableBusContainer cableBusContainer, final double x, final double y, final double z ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = cableBusContainer.getPart( s ); - - if( part != null ) - { - final ForgeDirection ax; - final ForgeDirection ay; - final 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 ); - part.renderDynamic( x, y, z, BusRenderHelper.INSTANCE, BusRenderer.INSTANCE.getRenderer() ); - } - } - } + BusRenderHelper.INSTANCE.setOrientation(ax, ay, az); + part.renderDynamic( + x, y, z, BusRenderHelper.INSTANCE, BusRenderer.INSTANCE.getRenderer() + ); + } + } + } } diff --git a/src/main/java/appeng/client/render/ItemRenderer.java b/src/main/java/appeng/client/render/ItemRenderer.java index c51c3c33..cf4100ae 100644 --- a/src/main/java/appeng/client/render/ItemRenderer.java +++ b/src/main/java/appeng/client/render/ItemRenderer.java @@ -18,52 +18,46 @@ package appeng.client.render; - import net.minecraft.item.ItemStack; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; +public class ItemRenderer implements IItemRenderer { + public static final ItemRenderer INSTANCE = new ItemRenderer(); -public class ItemRenderer implements IItemRenderer -{ + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } - public static final ItemRenderer INSTANCE = new ItemRenderer(); + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper + ) { + return true; + } - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } + @Override + public void + renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_DEPTH_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return true; - } + if (type == ItemRenderType.ENTITY) { + GL11.glTranslatef(-0.5f, -0.5f, -0.5f); + } + if (type == ItemRenderType.INVENTORY) { + GL11.glTranslatef(0.0f, -0.1f, 0.0f); + } - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_DEPTH_TEST ); - GL11.glEnable( GL11.GL_BLEND ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + WorldRender.INSTANCE.renderItemBlock(item, type, data); - if( type == ItemRenderType.ENTITY ) - { - GL11.glTranslatef( -0.5f, -0.5f, -0.5f ); - } - if( type == ItemRenderType.INVENTORY ) - { - GL11.glTranslatef( 0.0f, -0.1f, 0.0f ); - } - - WorldRender.INSTANCE.renderItemBlock( item, type, data ); - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } + 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 d4277dc8..85f09245 100644 --- a/src/main/java/appeng/client/render/RenderBlocksWorkaround.java +++ b/src/main/java/appeng/client/render/RenderBlocksWorkaround.java @@ -18,6 +18,10 @@ package appeng.client.render; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.Set; import appeng.api.parts.ISimplifiedBundle; import appeng.core.AELog; @@ -30,758 +34,772 @@ import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.Set; - - -@SideOnly( Side.CLIENT ) -public class RenderBlocksWorkaround extends RenderBlocks -{ - - private final int[] lightHashTmp = new int[27]; - private boolean calculations = true; - private EnumSet renderFaces = EnumSet.allOf( ForgeDirection.class ); - private EnumSet faces = EnumSet.allOf( ForgeDirection.class ); - private boolean isFacade = false; - private boolean useTextures = true; - private float opacity = 1.0f; - private Field fBrightness = null; - private Field fColor = null; - private LightingCache lightState = new LightingCache(); - - private int getCurrentColor() - { - try - { - if( this.fColor == null ) - { - try - { - this.fColor = Tessellator.class.getDeclaredField( "color" ); - } - catch( final Throwable t ) - { - this.fColor = Tessellator.class.getDeclaredField( "field_78402_m" ); - } - this.fColor.setAccessible( true ); - } - return (Integer) this.fColor.get( Tessellator.instance ); - } - catch( final Throwable t ) - { - return 0; - } - } - - private int getCurrentBrightness() - { - try - { - if( this.fBrightness == null ) - { - try - { - this.fBrightness = Tessellator.class.getDeclaredField( "brightness" ); - } - catch( final Throwable t ) - { - this.fBrightness = Tessellator.class.getDeclaredField( "field_78401_l" ); - } - this.fBrightness.setAccessible( true ); - } - return (Integer) this.fBrightness.get( Tessellator.instance ); - } - catch( final Throwable t ) - { - return 0; - } - } - - void setTexture( final IIcon ico ) - { - this.lightState.rXPos = this.lightState.rXNeg = this.lightState.rYPos = this.lightState.rYNeg = this.lightState.rZPos = this.lightState.rZNeg = ico; - } - - public void setTexture( final IIcon rYNeg, final IIcon rYPos, final IIcon rZNeg, final IIcon rZPos, final IIcon rXNeg, final 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; - } - - private boolean renderStandardBlockNoCalculations( final Block b, final int x, final int y, final int z ) - { - Tessellator.instance.setBrightness( this.lightState.bXPos ); - this.restoreAO( this.lightState.aoXPos, this.lightState.foXPos ); - this.renderFaceXPos( b, x, y, z, this.isUseTextures() ? 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.isUseTextures() ? 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.isUseTextures() ? 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.isUseTextures() ? 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.isUseTextures() ? 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.isUseTextures() ? this.lightState.rZNeg : this.getBlockIcon( b, this.blockAccess, x, y, z, ForgeDirection.NORTH.ordinal() ) ); - - return true; - } - - private void restoreAO( final int[] z, final 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.getOpacity() * 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( final int[] z, final 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( final Block blk, final int x, final int y, final int z ) - { - try - { - if( this.isCalculations() ) - { - this.lightState.lightHash = this.getLightingHash( blk, this.blockAccess, x, y, z ); - return super.renderStandardBlock( blk, x, y, z ); - } - else - { - this.enableAO = this.lightState.isAO; - final boolean out = this.renderStandardBlockNoCalculations( blk, x, y, z ); - this.enableAO = false; - return out; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - // meh - } - return false; - } - - @Override - public void renderFaceYNeg( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.DOWN ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.DOWN ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMinY; - final double d14 = par6 + this.renderMinZ; - final 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( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.UP ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.UP ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( this.renderMinZ * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( this.renderMaxZ * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMaxY; - final double d14 = par6 + this.renderMinZ; - final 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( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.NORTH ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.NORTH ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMinY; - final double d14 = par4 + this.renderMaxY; - final 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( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.SOUTH ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.SOUTH ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinX * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxX * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par2 + this.renderMaxX; - final double d13 = par4 + this.renderMinY; - final double d14 = par4 + this.renderMaxY; - final 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( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.WEST ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.WEST ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( this.renderMinZ * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( this.renderMaxZ * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMinX; - final double d12 = par4 + this.renderMinY; - final double d13 = par4 + this.renderMaxY; - final double d14 = par6 + this.renderMinZ; - final 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( final Block par1Block, final double par2, final double par4, final double par6, final IIcon par8Icon ) - { - if( this.getFaces().contains( ForgeDirection.EAST ) ) - { - if( !this.getRenderFaces().contains( ForgeDirection.EAST ) ) - { - return; - } - - if( this.isFacade() ) - { - final Tessellator tessellator = Tessellator.instance; - - final double d3 = par8Icon.getInterpolatedU( 16.0D - this.renderMinZ * 16.0D ); - final double d4 = par8Icon.getInterpolatedU( 16.0D - this.renderMaxZ * 16.0D ); - final double d5 = par8Icon.getInterpolatedV( 16.0D - this.renderMaxY * 16.0D ); - final double d6 = par8Icon.getInterpolatedV( 16.0D - this.renderMinY * 16.0D ); - - final double d11 = par2 + this.renderMaxX; - final double d12 = par4 + this.renderMinY; - final double d13 = par4 + this.renderMaxY; - final double d14 = par6 + this.renderMinZ; - final 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( final double u, final double v ) - { - final double rA = this.colorRedTopLeft * u + ( 1.0 - u ) * this.colorRedTopRight; - final double rB = this.colorRedBottomLeft * u + ( 1.0 - u ) * this.colorRedBottomRight; - final float r = (float) ( rA * v + rB * ( 1.0 - v ) ); - - final double gA = this.colorGreenTopLeft * u + ( 1.0 - u ) * this.colorGreenTopRight; - final double gB = this.colorGreenBottomLeft * u + ( 1.0 - u ) * this.colorGreenBottomRight; - final float g = (float) ( gA * v + gB * ( 1.0 - v ) ); - - final double bA = this.colorBlueTopLeft * u + ( 1.0 - u ) * this.colorBlueTopRight; - final double bB = this.colorBlueBottomLeft * u + ( 1.0 - u ) * this.colorBlueBottomRight; - final float b = (float) ( bA * v + bB * ( 1.0 - v ) ); - - final double highA = ( this.brightnessTopLeft >> 16 & 255 ) * u + ( 1.0 - u ) * ( this.brightnessTopRight >> 16 & 255 ); - final double highB = ( this.brightnessBottomLeft >> 16 & 255 ) * u + ( 1.0 - u ) * ( this.brightnessBottomRight >> 16 & 255 ); - final int high = ( (int) ( highA * v + highB * ( 1.0 - v ) ) ) & 255; - - final double lowA = ( ( this.brightnessTopLeft & 255 ) ) * u + ( 1.0 - u ) * ( ( this.brightnessTopRight & 255 ) ); - final double lowB = ( ( this.brightnessBottomLeft & 255 ) ) * u + ( 1.0 - u ) * ( ( this.brightnessBottomRight & 255 ) ); - final int low = ( (int) ( lowA * v + lowB * ( 1.0 - v ) ) ) & 255; - - final int out = ( high << 16 ) | low; - - Tessellator.instance.setColorRGBA_F( r, g, b, this.getOpacity() ); - Tessellator.instance.setBrightness( out ); - } - - public boolean similarLighting( final Block blk, final IBlockAccess w, final int x, final int y, final int z, final ISimplifiedBundle sim ) - { - final int lh = this.getLightingHash( blk, w, x, y, z ); - return ( (LightingCache) sim ).lightHash == lh; - } - - private int getLightingHash( final Block blk, final IBlockAccess w, final int x, final int y, final 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( final ISimplifiedBundle sim ) - { - this.lightState = new LightingCache( (LightingCache) sim ); - } - - public ISimplifiedBundle getLightingCache() - { - return new LightingCache( this.lightState ); - } - - Set getFaces() - { - return this.faces; - } - - public void setFaces( final EnumSet faces ) - { - this.faces = faces; - } - - private boolean isCalculations() - { - return this.calculations; - } - - public void setCalculations( final boolean calculations ) - { - this.calculations = calculations; - } - - private boolean isUseTextures() - { - return this.useTextures; - } - - void setUseTextures( final boolean useTextures ) - { - this.useTextures = useTextures; - } - - private boolean isFacade() - { - return this.isFacade; - } - - public void setFacade( final boolean isFacade ) - { - this.isFacade = isFacade; - } - - private float getOpacity() - { - return this.opacity; - } - - public void setOpacity( final float opacity ) - { - this.opacity = opacity; - } - - private EnumSet getRenderFaces() - { - return this.renderFaces; - } - - void setRenderFaces( final EnumSet renderFaces ) - { - this.renderFaces = renderFaces; - } - - private static class LightingCache implements ISimplifiedBundle - { - 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( final LightingCache secondCSrc ) - { - this.rXPos = secondCSrc.rXPos; - this.rXNeg = secondCSrc.rXNeg; - this.rYPos = secondCSrc.rYPos; - this.rYNeg = secondCSrc.rYNeg; - this.rZPos = secondCSrc.rZPos; - this.rZNeg = secondCSrc.rZNeg; - - this.isAO = secondCSrc.isAO; - - this.bXPos = secondCSrc.bXPos; - this.bXNeg = secondCSrc.bXNeg; - this.bYPos = secondCSrc.bYPos; - this.bYNeg = secondCSrc.bYNeg; - this.bZPos = secondCSrc.bZPos; - this.bZNeg = secondCSrc.bZNeg; - - this.aoXPos = secondCSrc.aoXPos.clone(); - this.aoXNeg = secondCSrc.aoXNeg.clone(); - this.aoYPos = secondCSrc.aoYPos.clone(); - this.aoYNeg = secondCSrc.aoYNeg.clone(); - this.aoZPos = secondCSrc.aoZPos.clone(); - this.aoZNeg = secondCSrc.aoZNeg.clone(); - - this.foXPos = secondCSrc.foXPos.clone(); - this.foXNeg = secondCSrc.foXNeg.clone(); - this.foYPos = secondCSrc.foYPos.clone(); - this.foYNeg = secondCSrc.foYNeg.clone(); - this.foZPos = secondCSrc.foZPos.clone(); - this.foZNeg = secondCSrc.foZNeg.clone(); - - this.lightHash = secondCSrc.lightHash; - } - - public LightingCache() - { - this.rXPos = null; - this.rXNeg = null; - this.rYPos = null; - this.rYNeg = null; - this.rZPos = null; - this.rZNeg = null; - - this.isAO = false; - - this.bXPos = 0; - this.bXNeg = 0; - this.bYPos = 0; - this.bYNeg = 0; - this.bZPos = 0; - this.bZNeg = 0; - - this.aoXPos = new int[5]; - this.aoXNeg = new int[5]; - this.aoYPos = new int[5]; - this.aoYNeg = new int[5]; - this.aoZPos = new int[5]; - this.aoZNeg = new int[5]; - - this.foXPos = new float[12]; - this.foXNeg = new float[12]; - this.foYPos = new float[12]; - this.foYNeg = new float[12]; - this.foZPos = new float[12]; - this.foZNeg = new float[12]; - - this.lightHash = 0; - } - } +@SideOnly(Side.CLIENT) +public class RenderBlocksWorkaround extends RenderBlocks { + private final int[] lightHashTmp = new int[27]; + private boolean calculations = true; + private EnumSet renderFaces = EnumSet.allOf(ForgeDirection.class); + private EnumSet faces = EnumSet.allOf(ForgeDirection.class); + private boolean isFacade = false; + private boolean useTextures = true; + private float opacity = 1.0f; + private Field fBrightness = null; + private Field fColor = null; + private LightingCache lightState = new LightingCache(); + + private int getCurrentColor() { + try { + if (this.fColor == null) { + try { + this.fColor = Tessellator.class.getDeclaredField("color"); + } catch (final Throwable t) { + this.fColor = Tessellator.class.getDeclaredField("field_78402_m"); + } + this.fColor.setAccessible(true); + } + return (Integer) this.fColor.get(Tessellator.instance); + } catch (final Throwable t) { + return 0; + } + } + + private int getCurrentBrightness() { + try { + if (this.fBrightness == null) { + try { + this.fBrightness = Tessellator.class.getDeclaredField("brightness"); + } catch (final Throwable t) { + this.fBrightness + = Tessellator.class.getDeclaredField("field_78401_l"); + } + this.fBrightness.setAccessible(true); + } + return (Integer) this.fBrightness.get(Tessellator.instance); + } catch (final Throwable t) { + return 0; + } + } + + void setTexture(final IIcon ico) { + this.lightState.rXPos = this.lightState.rXNeg = this.lightState.rYPos + = this.lightState.rYNeg = this.lightState.rZPos = this.lightState.rZNeg = ico; + } + + public void setTexture( + final IIcon rYNeg, + final IIcon rYPos, + final IIcon rZNeg, + final IIcon rZPos, + final IIcon rXNeg, + final 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; + } + + private boolean renderStandardBlockNoCalculations( + final Block b, final int x, final int y, final int z + ) { + Tessellator.instance.setBrightness(this.lightState.bXPos); + this.restoreAO(this.lightState.aoXPos, this.lightState.foXPos); + this.renderFaceXPos( + b, + x, + y, + z, + this.isUseTextures() + ? 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.isUseTextures() + ? 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.isUseTextures() + ? 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.isUseTextures() + ? 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.isUseTextures() + ? 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.isUseTextures() + ? this.lightState.rZNeg + : this.getBlockIcon( + b, this.blockAccess, x, y, z, ForgeDirection.NORTH.ordinal() + ) + ); + + return true; + } + + private void restoreAO(final int[] z, final 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.getOpacity() * 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(final int[] z, final 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(final Block blk, final int x, final int y, final int z) { + try { + if (this.isCalculations()) { + this.lightState.lightHash + = this.getLightingHash(blk, this.blockAccess, x, y, z); + return super.renderStandardBlock(blk, x, y, z); + } else { + this.enableAO = this.lightState.isAO; + final boolean out = this.renderStandardBlockNoCalculations(blk, x, y, z); + this.enableAO = false; + return out; + } + } catch (final Throwable t) { + AELog.debug(t); + // meh + } + return false; + } + + @Override + public void renderFaceYNeg( + final Block par1Block, + final double par2, + final double par4, + final double par6, + final IIcon par8Icon + ) { + if (this.getFaces().contains(ForgeDirection.DOWN)) { + if (!this.getRenderFaces().contains(ForgeDirection.DOWN)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + final double d5 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); + final double d6 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMinY; + final double d14 = par6 + this.renderMinZ; + final 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( + final Block par1Block, + final double par2, + final double par4, + final double par6, + final IIcon par8Icon + ) { + if (this.getFaces().contains(ForgeDirection.UP)) { + if (!this.getRenderFaces().contains(ForgeDirection.UP)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + final double d5 = par8Icon.getInterpolatedV(this.renderMinZ * 16.0D); + final double d6 = par8Icon.getInterpolatedV(this.renderMaxZ * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMaxY; + final double d14 = par6 + this.renderMinZ; + final 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( + final Block par1Block, + final double par2, + final double par4, + final double par6, + final IIcon par8Icon + ) { + if (this.getFaces().contains(ForgeDirection.NORTH)) { + if (!this.getRenderFaces().contains(ForgeDirection.NORTH)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 + = par8Icon.getInterpolatedU(16.0D - this.renderMinX * 16.0D); + final double d4 + = par8Icon.getInterpolatedU(16.0D - this.renderMaxX * 16.0D); + final double d5 + = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 + = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMinY; + final double d14 = par4 + this.renderMaxY; + final 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( + final Block par1Block, + final double par2, + final double par4, + final double par6, + final IIcon par8Icon + ) { + if (this.getFaces().contains(ForgeDirection.SOUTH)) { + if (!this.getRenderFaces().contains(ForgeDirection.SOUTH)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinX * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxX * 16.0D); + final double d5 + = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 + = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par2 + this.renderMaxX; + final double d13 = par4 + this.renderMinY; + final double d14 = par4 + this.renderMaxY; + final 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( + final Block par1Block, + final double par2, + final double par4, + final double par6, + final IIcon par8Icon + ) { + if (this.getFaces().contains(ForgeDirection.WEST)) { + if (!this.getRenderFaces().contains(ForgeDirection.WEST)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 = par8Icon.getInterpolatedU(this.renderMinZ * 16.0D); + final double d4 = par8Icon.getInterpolatedU(this.renderMaxZ * 16.0D); + final double d5 + = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 + = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMinX; + final double d12 = par4 + this.renderMinY; + final double d13 = par4 + this.renderMaxY; + final double d14 = par6 + this.renderMinZ; + final 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( + final Block par1Block, + final double par2, + final double par4, + final double par6, + final IIcon par8Icon + ) { + if (this.getFaces().contains(ForgeDirection.EAST)) { + if (!this.getRenderFaces().contains(ForgeDirection.EAST)) { + return; + } + + if (this.isFacade()) { + final Tessellator tessellator = Tessellator.instance; + + final double d3 + = par8Icon.getInterpolatedU(16.0D - this.renderMinZ * 16.0D); + final double d4 + = par8Icon.getInterpolatedU(16.0D - this.renderMaxZ * 16.0D); + final double d5 + = par8Icon.getInterpolatedV(16.0D - this.renderMaxY * 16.0D); + final double d6 + = par8Icon.getInterpolatedV(16.0D - this.renderMinY * 16.0D); + + final double d11 = par2 + this.renderMaxX; + final double d12 = par4 + this.renderMinY; + final double d13 = par4 + this.renderMaxY; + final double d14 = par6 + this.renderMinZ; + final 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(final double u, final double v) { + final double rA = this.colorRedTopLeft * u + (1.0 - u) * this.colorRedTopRight; + final double rB + = this.colorRedBottomLeft * u + (1.0 - u) * this.colorRedBottomRight; + final float r = (float) (rA * v + rB * (1.0 - v)); + + final double gA + = this.colorGreenTopLeft * u + (1.0 - u) * this.colorGreenTopRight; + final double gB + = this.colorGreenBottomLeft * u + (1.0 - u) * this.colorGreenBottomRight; + final float g = (float) (gA * v + gB * (1.0 - v)); + + final double bA = this.colorBlueTopLeft * u + (1.0 - u) * this.colorBlueTopRight; + final double bB + = this.colorBlueBottomLeft * u + (1.0 - u) * this.colorBlueBottomRight; + final float b = (float) (bA * v + bB * (1.0 - v)); + + final double highA = (this.brightnessTopLeft >> 16 & 255) * u + + (1.0 - u) * (this.brightnessTopRight >> 16 & 255); + final double highB = (this.brightnessBottomLeft >> 16 & 255) * u + + (1.0 - u) * (this.brightnessBottomRight >> 16 & 255); + final int high = ((int) (highA * v + highB * (1.0 - v))) & 255; + + final double lowA = ((this.brightnessTopLeft & 255)) * u + + (1.0 - u) * ((this.brightnessTopRight & 255)); + final double lowB = ((this.brightnessBottomLeft & 255)) * u + + (1.0 - u) * ((this.brightnessBottomRight & 255)); + final int low = ((int) (lowA * v + lowB * (1.0 - v))) & 255; + + final int out = (high << 16) | low; + + Tessellator.instance.setColorRGBA_F(r, g, b, this.getOpacity()); + Tessellator.instance.setBrightness(out); + } + + public boolean similarLighting( + final Block blk, + final IBlockAccess w, + final int x, + final int y, + final int z, + final ISimplifiedBundle sim + ) { + final int lh = this.getLightingHash(blk, w, x, y, z); + return ((LightingCache) sim).lightHash == lh; + } + + private int getLightingHash( + final Block blk, final IBlockAccess w, final int x, final int y, final 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(final ISimplifiedBundle sim) { + this.lightState = new LightingCache((LightingCache) sim); + } + + public ISimplifiedBundle getLightingCache() { + return new LightingCache(this.lightState); + } + + Set getFaces() { + return this.faces; + } + + public void setFaces(final EnumSet faces) { + this.faces = faces; + } + + private boolean isCalculations() { + return this.calculations; + } + + public void setCalculations(final boolean calculations) { + this.calculations = calculations; + } + + private boolean isUseTextures() { + return this.useTextures; + } + + void setUseTextures(final boolean useTextures) { + this.useTextures = useTextures; + } + + private boolean isFacade() { + return this.isFacade; + } + + public void setFacade(final boolean isFacade) { + this.isFacade = isFacade; + } + + private float getOpacity() { + return this.opacity; + } + + public void setOpacity(final float opacity) { + this.opacity = opacity; + } + + private EnumSet getRenderFaces() { + return this.renderFaces; + } + + void setRenderFaces(final EnumSet renderFaces) { + this.renderFaces = renderFaces; + } + + private static class LightingCache implements ISimplifiedBundle { + 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(final LightingCache secondCSrc) { + this.rXPos = secondCSrc.rXPos; + this.rXNeg = secondCSrc.rXNeg; + this.rYPos = secondCSrc.rYPos; + this.rYNeg = secondCSrc.rYNeg; + this.rZPos = secondCSrc.rZPos; + this.rZNeg = secondCSrc.rZNeg; + + this.isAO = secondCSrc.isAO; + + this.bXPos = secondCSrc.bXPos; + this.bXNeg = secondCSrc.bXNeg; + this.bYPos = secondCSrc.bYPos; + this.bYNeg = secondCSrc.bYNeg; + this.bZPos = secondCSrc.bZPos; + this.bZNeg = secondCSrc.bZNeg; + + this.aoXPos = secondCSrc.aoXPos.clone(); + this.aoXNeg = secondCSrc.aoXNeg.clone(); + this.aoYPos = secondCSrc.aoYPos.clone(); + this.aoYNeg = secondCSrc.aoYNeg.clone(); + this.aoZPos = secondCSrc.aoZPos.clone(); + this.aoZNeg = secondCSrc.aoZNeg.clone(); + + this.foXPos = secondCSrc.foXPos.clone(); + this.foXNeg = secondCSrc.foXNeg.clone(); + this.foYPos = secondCSrc.foYPos.clone(); + this.foYNeg = secondCSrc.foYNeg.clone(); + this.foZPos = secondCSrc.foZPos.clone(); + this.foZNeg = secondCSrc.foZNeg.clone(); + + this.lightHash = secondCSrc.lightHash; + } + + public LightingCache() { + this.rXPos = null; + this.rXNeg = null; + this.rYPos = null; + this.rYNeg = null; + this.rZPos = null; + this.rZNeg = null; + + this.isAO = false; + + this.bXPos = 0; + this.bXNeg = 0; + this.bYPos = 0; + this.bYNeg = 0; + this.bZPos = 0; + this.bZNeg = 0; + + this.aoXPos = new int[5]; + this.aoXNeg = new int[5]; + this.aoYPos = new int[5]; + this.aoYNeg = new int[5]; + this.aoZPos = new int[5]; + this.aoZNeg = new int[5]; + + this.foXPos = new float[12]; + this.foXNeg = new float[12]; + this.foYPos = new float[12]; + this.foYNeg = new float[12]; + this.foZPos = new float[12]; + this.foZNeg = new float[12]; + + this.lightHash = 0; + } + } } diff --git a/src/main/java/appeng/client/render/SpatialSkyRender.java b/src/main/java/appeng/client/render/SpatialSkyRender.java index 66e04cba..5533f02b 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 net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; @@ -28,162 +29,147 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraftforge.client.IRenderHandler; import org.lwjgl.opengl.GL11; -import java.util.Random; +public class SpatialSkyRender extends IRenderHandler { + private static final SpatialSkyRender INSTANCE = new SpatialSkyRender(); + private final Random random = new Random(); + private final int dspList; + private long cycle = 0; -public class SpatialSkyRender extends IRenderHandler -{ + public SpatialSkyRender() { + this.dspList = GLAllocation.generateDisplayLists(1); + } - private static final SpatialSkyRender INSTANCE = new SpatialSkyRender(); + public static IRenderHandler getInstance() { + return INSTANCE; + } - private final Random random = new Random(); - private final int dspList; - private long cycle = 0; + @Override + public void + render(final float partialTicks, final WorldClient world, final Minecraft mc) { + final long now = System.currentTimeMillis(); - public SpatialSkyRender() - { - this.dspList = GLAllocation.generateDisplayLists( 1 ); - } + if (now - this.cycle > 2000) { + this.cycle = now; + GL11.glNewList(this.dspList, GL11.GL_COMPILE); + this.renderTwinkles(); + GL11.glEndList(); + } - public static IRenderHandler getInstance() - { - return INSTANCE; - } + float fade = now - this.cycle; + fade /= 1000; + fade = 0.15f * (1.0f - Math.abs((fade - 1.0f) * (fade - 1.0f))); - @Override - public void render( final float partialTicks, final WorldClient world, final Minecraft mc ) - { - final long now = System.currentTimeMillis(); + 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); - if( now - this.cycle > 2000 ) - { - this.cycle = now; - GL11.glNewList( this.dspList, GL11.GL_COMPILE ); - this.renderTwinkles(); - GL11.glEndList(); - } + final Tessellator tessellator = Tessellator.instance; - float fade = now - this.cycle; - fade /= 1000; - fade = 0.15f * ( 1.0f - Math.abs( ( fade - 1.0f ) * ( fade - 1.0f ) ) ); + for (int i = 0; i < 6; ++i) { + GL11.glPushMatrix(); - 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 ); + switch (i) { + case 1: + GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F); + break; + case 2: + GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F); + break; + case 3: + GL11.glRotatef(180.0F, 1.0F, 0.0F, 0.0F); + break; + case 4: + GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F); + break; + case 5: + GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F); + break; + default: + break; + } - final Tessellator tessellator = Tessellator.instance; + 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(); - for( int i = 0; i < 6; ++i ) - { - GL11.glPushMatrix(); + GL11.glPopMatrix(); + } - switch( i ) - { - case 1: - GL11.glRotatef( 90.0F, 1.0F, 0.0F, 0.0F ); - break; - case 2: - GL11.glRotatef( -90.0F, 1.0F, 0.0F, 0.0F ); - break; - case 3: - GL11.glRotatef( 180.0F, 1.0F, 0.0F, 0.0F ); - break; - case 4: - GL11.glRotatef( 90.0F, 0.0F, 0.0F, 1.0F ); - break; - case 5: - GL11.glRotatef( -90.0F, 0.0F, 0.0F, 1.0F ); - break; - default: - break; - } + if (fade > 0.0f) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_TEXTURE_2D); - 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(); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + RenderHelper.disableStandardItemLighting(); - GL11.glPopMatrix(); - } + GL11.glEnable(GL11.GL_TEXTURE_2D); + GL11.glColor4f(fade, fade, fade, 1.0f); + GL11.glCallList(this.dspList); - if( fade > 0.0f ) - { - GL11.glEnable( GL11.GL_BLEND ); - GL11.glDisable( GL11.GL_TEXTURE_2D ); + RenderHelper.enableStandardItemLighting(); + } - OpenGlHelper.glBlendFunc( 770, 771, 1, 0 ); - RenderHelper.disableStandardItemLighting(); + GL11.glEnable(GL11.GL_FOG); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_BLEND); + GL11.glDepthMask(true); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - GL11.glColor4f( fade, fade, fade, 1.0f ); - GL11.glCallList( this.dspList ); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); + } - RenderHelper.enableStandardItemLighting(); - } + private void renderTwinkles() { + final Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); - GL11.glEnable( GL11.GL_FOG ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); - GL11.glEnable( GL11.GL_BLEND ); - GL11.glDepthMask( true ); + 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; + double iZ = this.random.nextFloat() * 2.0F - 1.0F; + final double d3 = 0.05F + this.random.nextFloat() * 0.1F; + double dist = iX * iX + iY * iY + iZ * iZ; - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); - } + if (dist < 1.0D && dist > 0.01D) { + dist = 1.0D / Math.sqrt(dist); + iX *= dist; + iY *= dist; + iZ *= dist; - private void renderTwinkles() - { - final Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); + final double x = iX * 100.0D; + final double y = iY * 100.0D; + final double z = iZ * 100.0D; + final double d8 = Math.atan2(iX, iZ); + final double d9 = Math.sin(d8); + final double d10 = Math.cos(d8); + final double d11 = Math.atan2(Math.sqrt(iX * iX + iZ * iZ), iY); + final double d12 = Math.sin(d11); + final double d13 = Math.cos(d11); + final double d14 = this.random.nextDouble() * Math.PI * 2.0D; + final double d15 = Math.sin(d14); + final double d16 = Math.cos(d14); - 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; - double iZ = this.random.nextFloat() * 2.0F - 1.0F; - final double d3 = 0.05F + this.random.nextFloat() * 0.1F; - double dist = iX * iX + iY * iY + iZ * iZ; + for (int j = 0; j < 4; ++j) { + final double d17 = 0.0D; + final double d18 = ((j & 2) - 1) * d3; + final double d19 = ((j + 1 & 2) - 1) * d3; + final double d20 = d18 * d16 - d19 * d15; + final double d21 = d19 * d16 + d18 * d15; + final double d22 = d20 * d12 + d17 * d13; + final double d23 = d17 * d12 - d20 * d13; + final double d24 = d23 * d9 - d21 * d10; + final double d25 = d21 * d9 + d23 * d10; - if( dist < 1.0D && dist > 0.01D ) - { - dist = 1.0D / Math.sqrt( dist ); - iX *= dist; - iY *= dist; - iZ *= dist; + tessellator.addVertex(x + d24, y + d22, z + d25); + } + } + } - final double x = iX * 100.0D; - final double y = iY * 100.0D; - final double z = iZ * 100.0D; - final double d8 = Math.atan2( iX, iZ ); - final double d9 = Math.sin( d8 ); - final double d10 = Math.cos( d8 ); - final double d11 = Math.atan2( Math.sqrt( iX * iX + iZ * iZ ), iY ); - final double d12 = Math.sin( d11 ); - final double d13 = Math.cos( d11 ); - final double d14 = this.random.nextDouble() * Math.PI * 2.0D; - final double d15 = Math.sin( d14 ); - final double d16 = Math.cos( d14 ); - - for( int j = 0; j < 4; ++j ) - { - final double d17 = 0.0D; - final double d18 = ( ( j & 2 ) - 1 ) * d3; - final double d19 = ( ( j + 1 & 2 ) - 1 ) * d3; - final double d20 = d18 * d16 - d19 * d15; - final double d21 = d19 * d16 + d18 * d15; - final double d22 = d20 * d12 + d17 * d13; - final double d23 = d17 * d12 - d20 * d13; - final double d24 = d23 * d9 - d21 * d10; - final double d25 = d21 * d9 + d23 * d10; - - tessellator.addVertex( x + d24, y + d22, z + d25 ); - } - } - } - - tessellator.draw(); - } + tessellator.draw(); + } } diff --git a/src/main/java/appeng/client/render/TESRWrapper.java b/src/main/java/appeng/client/render/TESRWrapper.java index 57347f9b..6e70822c 100644 --- a/src/main/java/appeng/client/render/TESRWrapper.java +++ b/src/main/java/appeng/client/render/TESRWrapper.java @@ -18,7 +18,6 @@ package appeng.client.render; - import appeng.block.AEBaseBlock; import appeng.core.AELog; import appeng.tile.AEBaseTile; @@ -31,55 +30,58 @@ import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; +@SideOnly(Side.CLIENT) +public class TESRWrapper extends TileEntitySpecialRenderer { + private final RenderBlocks renderBlocksInstance = new RenderBlocks(); -@SideOnly( Side.CLIENT ) -public class TESRWrapper extends TileEntitySpecialRenderer -{ + private final BaseBlockRender blkRender; + private final double maxDistance; - private final RenderBlocks renderBlocksInstance = new RenderBlocks(); + public TESRWrapper(final BaseBlockRender render) { + this.blkRender = render; + this.maxDistance = this.blkRender.getTesrRenderDistance(); + } - private final BaseBlockRender blkRender; - private final double maxDistance; + @Override + public final void renderTileEntityAt( + final TileEntity te, final double x, final double y, final double z, final float f + ) { + if (te instanceof AEBaseTile) { + final Block b = te.getBlockType(); - public TESRWrapper( final BaseBlockRender render ) - { - this.blkRender = render; - this.maxDistance = this.blkRender.getTesrRenderDistance(); - } + if (b instanceof AEBaseBlock && ((AEBaseTile) te).requiresTESR()) { + if (Math.abs(x) > this.maxDistance || Math.abs(y) > this.maxDistance + || Math.abs(z) > this.maxDistance) { + return; + } - @Override - public final void renderTileEntityAt( final TileEntity te, final double x, final double y, final double z, final float f ) - { - if( te instanceof AEBaseTile ) - { - final Block b = te.getBlockType(); + final Tessellator tess = Tessellator.instance; - if( b instanceof AEBaseBlock && ( (AEBaseTile) te ).requiresTESR() ) - { - if( Math.abs( x ) > this.maxDistance || Math.abs( y ) > this.maxDistance || Math.abs( z ) > this.maxDistance ) - { - return; - } + try { + GL11.glPushMatrix(); - final Tessellator tess = Tessellator.instance; + this.renderBlocksInstance.blockAccess = te.getWorldObj(); + this.blkRender.renderTile( + (AEBaseBlock) b, + (AEBaseTile) te, + tess, + x, + y, + z, + f, + this.renderBlocksInstance + ); - try - { - GL11.glPushMatrix(); - - this.renderBlocksInstance.blockAccess = te.getWorldObj(); - this.blkRender.renderTile( (AEBaseBlock) b, (AEBaseTile) te, tess, x, y, z, f, this.renderBlocksInstance ); - - GL11.glPopMatrix(); - } - catch( final Throwable t ) - { - AELog.error( "Hi, Looks like there was a crash while rendering something..." ); - t.printStackTrace(); - AELog.error( "MC will now crash ( probably )!" ); - throw new IllegalStateException( t ); - } - } - } - } + GL11.glPopMatrix(); + } catch (final Throwable t) { + AELog.error( + "Hi, Looks like there was a crash while rendering something..." + ); + t.printStackTrace(); + AELog.error("MC will now crash ( probably )!"); + throw new IllegalStateException(t); + } + } + } + } } diff --git a/src/main/java/appeng/client/render/WorldRender.java b/src/main/java/appeng/client/render/WorldRender.java index d93cf0a0..e9210b97 100644 --- a/src/main/java/appeng/client/render/WorldRender.java +++ b/src/main/java/appeng/client/render/WorldRender.java @@ -18,6 +18,8 @@ package appeng.client.render; +import java.util.HashMap; +import java.util.Map; import appeng.block.AEBaseBlock; import appeng.core.AELog; @@ -31,81 +33,82 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; -import java.util.HashMap; -import java.util.Map; +@SideOnly(Side.CLIENT) +public final class WorldRender implements ISimpleBlockRenderingHandler { + public static final WorldRender INSTANCE = new WorldRender(); + private final Map blockRenders + = new HashMap(); + private final int renderID = RenderingRegistry.getNextAvailableRenderId(); + private final RenderBlocks renderer = new RenderBlocks(); + private boolean hasError = false; + private WorldRender() {} -@SideOnly( Side.CLIENT ) -public final class WorldRender implements ISimpleBlockRenderingHandler -{ + void setRender(final AEBaseBlock in, final BaseBlockRender r) { + this.blockRenders.put(in, r); + } - public static final WorldRender INSTANCE = new WorldRender(); - private final Map blockRenders = new HashMap(); - private final int renderID = RenderingRegistry.getNextAvailableRenderId(); - private final RenderBlocks renderer = new RenderBlocks(); - private boolean hasError = false; + @Override + public void renderInventoryBlock( + final Block block, + final int metadata, + final int modelID, + final RenderBlocks renderer + ) { + // wtf is this for? + } - private WorldRender() - { - } + @Override + public boolean renderWorldBlock( + final IBlockAccess world, + final int x, + final int y, + final int z, + final Block block, + final int modelId, + final RenderBlocks renderer + ) { + final AEBaseBlock blk = (AEBaseBlock) block; + renderer.setRenderBoundsFromBlock(block); + return this.getRender(blk).renderInWorld(blk, world, x, y, z, renderer); + } - void setRender( final AEBaseBlock in, final BaseBlockRender r ) - { - this.blockRenders.put( in, r ); - } + @Override + public boolean shouldRender3DInInventory(final int modelId) { + return true; + } - @Override - public void renderInventoryBlock( final Block block, final int metadata, final int modelID, final RenderBlocks renderer ) - { - // wtf is this for? - } + @Override + public int getRenderId() { + return this.renderID; + } - @Override - public boolean renderWorldBlock( final IBlockAccess world, final int x, final int y, final int z, final Block block, final int modelId, final RenderBlocks renderer ) - { - final AEBaseBlock blk = (AEBaseBlock) block; - renderer.setRenderBoundsFromBlock( block ); - return this.getRender( blk ).renderInWorld( blk, world, x, y, z, renderer ); - } + private BaseBlockRender getRender(final AEBaseBlock block) { + return block.getRendererInstance().getRendererInstance(); + } - @Override - public boolean shouldRender3DInInventory( final int modelId ) - { - return true; - } + void renderItemBlock( + final ItemStack item, final ItemRenderType type, final Object[] data + ) { + final Block blk = Block.getBlockFromItem(item.getItem()); + if (blk instanceof AEBaseBlock) { + final AEBaseBlock block = (AEBaseBlock) blk; + this.renderer.setRenderBoundsFromBlock(block); - @Override - public int getRenderId() - { - return this.renderID; - } - - private BaseBlockRender getRender( final AEBaseBlock block ) - { - return block.getRendererInstance().getRendererInstance(); - } - - void renderItemBlock( final ItemStack item, final ItemRenderType type, final Object[] data ) - { - final Block blk = Block.getBlockFromItem( item.getItem() ); - if( blk instanceof AEBaseBlock ) - { - final AEBaseBlock block = (AEBaseBlock) blk; - this.renderer.setRenderBoundsFromBlock( block ); - - this.renderer.uvRotateBottom = this.renderer.uvRotateEast = this.renderer.uvRotateNorth = this.renderer.uvRotateSouth = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; - this.getRender( block ).renderInventory( block, item, this.renderer, type, data ); - this.renderer.uvRotateBottom = this.renderer.uvRotateEast = this.renderer.uvRotateNorth = this.renderer.uvRotateSouth = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; - } - else - { - if( !this.hasError ) - { - this.hasError = true; - AELog.error( "Invalid render - item/block mismatch" ); - AELog.error( " item: " + item.getUnlocalizedName() ); - AELog.error( " block: " + blk.getUnlocalizedName() ); - } - } - } + this.renderer.uvRotateBottom = this.renderer.uvRotateEast + = this.renderer.uvRotateNorth = this.renderer.uvRotateSouth + = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; + this.getRender(block).renderInventory(block, item, this.renderer, type, data); + this.renderer.uvRotateBottom = this.renderer.uvRotateEast + = this.renderer.uvRotateNorth = this.renderer.uvRotateSouth + = this.renderer.uvRotateTop = this.renderer.uvRotateWest = 0; + } else { + if (!this.hasError) { + this.hasError = true; + AELog.error("Invalid render - item/block mismatch"); + AELog.error(" item: " + item.getUnlocalizedName()); + AELog.error(" block: " + blk.getUnlocalizedName()); + } + } + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java b/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java index a08e060e..83979aa3 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockAssembler.java @@ -18,6 +18,7 @@ package appeng.client.render.blocks; +import java.util.EnumSet; import appeng.api.networking.IGridHost; import appeng.api.parts.IBoxProvider; @@ -43,250 +44,407 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RenderBlockAssembler + extends BaseBlockRender + implements IBoxProvider { + public RenderBlockAssembler() { + super(false, 20); + } + @Override + public void renderInventory( + final BlockMolecularAssembler blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.setOverrideBlockTexture(blk.getIcon(0, 0)); -public class RenderBlockAssembler extends BaseBlockRender implements IBoxProvider -{ + this.setInvRenderBounds(renderer, 2, 14, 0, 14, 16, 2); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - public RenderBlockAssembler() - { - super( false, 20 ); - } + this.setInvRenderBounds(renderer, 0, 14, 2, 2, 16, 14); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - @Override - public void renderInventory( final BlockMolecularAssembler blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.setOverrideBlockTexture( blk.getIcon( 0, 0 ) ); + this.setInvRenderBounds(renderer, 2, 0, 14, 14, 2, 16); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 2, 14, 0, 14, 16, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 14, 0, 2, 16, 2, 14); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 0, 14, 2, 2, 16, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 0, 0, 0, 16, 2, 2); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 2, 0, 14, 14, 2, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 0, 2, 0, 2, 16, 2); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 14, 0, 2, 16, 2, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 0, 0, 2, 2, 2, 16); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 0, 0, 0, 16, 2, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 0, 14, 14, 16, 16, 16); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 0, 2, 0, 2, 16, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 14, 0, 14, 16, 14, 16); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 0, 0, 2, 2, 2, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 14, 14, 0, 16, 16, 14); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 0, 14, 14, 16, 16, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 14, 2, 0, 16, 14, 2); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 14, 0, 14, 16, 14, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 0, 2, 14, 2, 14, 16); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 14, 14, 0, 16, 16, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 1, 1, 1, 15, 15, 15); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), + blk, + is, + Tessellator.instance, + 0xffffff, + renderer + ); - this.setInvRenderBounds( renderer, 14, 2, 0, 16, 14, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + renderer.setOverrideBlockTexture(null); + } - this.setInvRenderBounds( renderer, 0, 2, 14, 2, 14, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + @Override + public boolean renderInWorld( + final BlockMolecularAssembler maBlock, + final IBlockAccess world, + final int x, + final int y, + final int z, + RenderBlocks renderer + ) { + final TileMolecularAssembler tma = maBlock.getTileEntity(world, x, y, z); - this.setInvRenderBounds( renderer, 1, 1, 1, 15, 15, 15 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, Tessellator.instance, 0xffffff, renderer ); + if (BlockMolecularAssembler.isBooleanAlphaPass()) { + if (tma.isPowered()) { + this.renderBlockBounds( + renderer, + 1, + 1, + 1, + 15, + 15, + 15, + ForgeDirection.WEST, + ForgeDirection.UP, + ForgeDirection.SOUTH + ); + final TaughtIcon lights = new TaughtIcon( + ExtraBlockTextures.BlockMolecularAssemblerLights.getIcon(), -2.0f + ); + Tessellator.instance.setColorRGBA_F(1, 1, 1, 0.3f); + Tessellator.instance.setBrightness(14 << 20 | 14 << 4); + renderer.renderFaceXNeg(maBlock, x, y, z, lights); + renderer.renderFaceXPos(maBlock, x, y, z, lights); + renderer.renderFaceYNeg(maBlock, x, y, z, lights); + renderer.renderFaceYPos(maBlock, x, y, z, lights); + renderer.renderFaceZNeg(maBlock, x, y, z, lights); + renderer.renderFaceZPos(maBlock, x, y, z, lights); + return true; + } + return false; + } - renderer.setOverrideBlockTexture( null ); - } + BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; + renderer = BusRenderer.INSTANCE.getRenderer(); - @Override - public boolean renderInWorld( final BlockMolecularAssembler maBlock, final IBlockAccess world, final int x, final int y, final int z, RenderBlocks renderer ) - { - final TileMolecularAssembler tma = maBlock.getTileEntity( world, x, y, z ); + this.preRenderInWorld(maBlock, world, x, y, z, renderer); - if( BlockMolecularAssembler.isBooleanAlphaPass() ) - { - if( tma.isPowered() ) - { - this.renderBlockBounds( renderer, 1, 1, 1, 15, 15, 15, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.SOUTH ); - final TaughtIcon lights = new TaughtIcon( ExtraBlockTextures.BlockMolecularAssemblerLights.getIcon(), -2.0f ); - Tessellator.instance.setColorRGBA_F( 1, 1, 1, 0.3f ); - Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); - renderer.renderFaceXNeg( maBlock, x, y, z, lights ); - renderer.renderFaceXPos( maBlock, x, y, z, lights ); - renderer.renderFaceYNeg( maBlock, x, y, z, lights ); - renderer.renderFaceYPos( maBlock, x, y, z, lights ); - renderer.renderFaceZNeg( maBlock, x, y, z, lights ); - renderer.renderFaceZPos( maBlock, x, y, z, lights ); - return true; - } - return false; - } + tma.setLightCache(BusRenderHelper.INSTANCE.useSimplifiedRendering( + x, y, z, this, tma.getLightCache() + )); - BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; - renderer = BusRenderer.INSTANCE.getRenderer(); + BusRenderer.INSTANCE.getRenderer().setFacade(true); + final IOrientable te = this.getOrientable(maBlock, world, x, y, z); - this.preRenderInWorld( maBlock, world, x, y, z, renderer ); + final ForgeDirection fdy = te.getUp(); + final ForgeDirection fdz = te.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); - tma.setLightCache( BusRenderHelper.INSTANCE.useSimplifiedRendering( x, y, z, this, tma.getLightCache() ) ); + renderer.renderAllFaces = true; - BusRenderer.INSTANCE.getRenderer().setFacade( true ); - final IOrientable te = this.getOrientable( maBlock, world, x, y, z ); + this.renderCableAt(0.11D, world, x, y, z, maBlock, renderer, 0.141D, false); + this.renderCableAt(0.188D, world, x, y, z, maBlock, renderer, 0.1875D, true); - final ForgeDirection fdy = te.getUp(); - final ForgeDirection fdz = te.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); + maBlock.getRendererInstance().setTemporaryRenderIcon(maBlock.getIcon(0, 0)); - renderer.renderAllFaces = true; + this.renderBlockBounds(renderer, 2, 14, 0, 14, 16, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderCableAt( 0.11D, world, x, y, z, maBlock, renderer, 0.141D, false ); - this.renderCableAt( 0.188D, world, x, y, z, maBlock, renderer, 0.1875D, true ); + this.renderBlockBounds(renderer, 0, 14, 2, 2, 16, 14, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - maBlock.getRendererInstance().setTemporaryRenderIcon( maBlock.getIcon( 0, 0 ) ); + this.renderBlockBounds(renderer, 2, 0, 14, 14, 2, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 2, 14, 0, 14, 16, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 14, 0, 2, 16, 2, 14, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 0, 14, 2, 2, 16, 14, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + // sides... + this.renderBlockBounds(renderer, 0, 0, 0, 16, 2, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 2, 0, 14, 14, 2, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 0, 2, 0, 2, 16, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 14, 0, 2, 16, 2, 14, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 0, 0, 2, 2, 2, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - // sides... - this.renderBlockBounds( renderer, 0, 0, 0, 16, 2, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 0, 14, 14, 16, 16, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 0, 2, 0, 2, 16, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 14, 0, 14, 16, 14, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 0, 0, 2, 2, 2, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 14, 14, 0, 16, 16, 14, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 0, 14, 14, 16, 16, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 14, 2, 0, 16, 14, 2, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 14, 0, 14, 16, 14, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 0, 2, 14, 2, 14, 16, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 14, 14, 0, 16, 16, 14, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + this.renderBlockBounds(renderer, 1, 1, 1, 15, 15, 15, fdx, fdy, fdz); + renderer.renderStandardBlock(maBlock, x, y, z); - this.renderBlockBounds( renderer, 14, 2, 0, 16, 14, 2, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + BusRenderHelper.INSTANCE.normalRendering(); - this.renderBlockBounds( renderer, 0, 2, 14, 2, 14, 16, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + maBlock.getRendererInstance().setTemporaryRenderIcon(null); - this.renderBlockBounds( renderer, 1, 1, 1, 15, 15, 15, fdx, fdy, fdz ); - renderer.renderStandardBlock( maBlock, x, y, z ); + renderer.renderAllFaces = false; + BusRenderer.INSTANCE.getRenderer().setFacade(false); - BusRenderHelper.INSTANCE.normalRendering(); + this.postRenderInWorld(renderer); - maBlock.getRendererInstance().setTemporaryRenderIcon( null ); + return true; + } - renderer.renderAllFaces = false; - BusRenderer.INSTANCE.getRenderer().setFacade( false ); + private void renderCableAt( + final double thickness, + final IBlockAccess world, + final int x, + final int y, + final int z, + final BlockMolecularAssembler block, + final RenderBlocks renderer, + final double pull, + final boolean covered + ) { + IIcon texture = null; - this.postRenderInWorld( renderer ); + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.WEST, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + 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); + } - return true; - } + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.EAST, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + 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); + } - private void renderCableAt( final double thickness, final IBlockAccess world, final int x, final int y, final int z, final BlockMolecularAssembler block, final RenderBlocks renderer, final double pull, final boolean covered ) - { - IIcon texture = null; + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.NORTH, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + 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); + } - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.WEST, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - 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 ); - } + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.SOUTH, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + 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); + } - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.EAST, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - 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 ); - } + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.DOWN, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + 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); + } - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.NORTH, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - 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 ); - } + texture = this.getConnectedCable(world, x, y, z, ForgeDirection.UP, covered); + block.getRendererInstance().setTemporaryRenderIcon(texture); + 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); + } - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.SOUTH, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - 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(null); + } - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.DOWN, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - 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 ); - } + private IIcon getConnectedCable( + final IBlockAccess world, + final int x, + final int y, + final int z, + final ForgeDirection side, + final boolean covered + ) { + final int tileYPos = y + side.offsetY; - texture = this.getConnectedCable( world, x, y, z, ForgeDirection.UP, covered ); - block.getRendererInstance().setTemporaryRenderIcon( texture ); - 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 ); - } + if (-1 < tileYPos && tileYPos < 256) { + final TileEntity ne + = world.getTileEntity(x + side.offsetX, tileYPos, z + side.offsetZ); + if (ne instanceof IGridHost && ne instanceof IPartHost) { + final IPartHost ph = (IPartHost) ne; + final IPart pcx = ph.getPart(ForgeDirection.UNKNOWN); - block.getRendererInstance().setTemporaryRenderIcon( null ); - } + if (pcx instanceof PartCable) { + final PartCable pc = (PartCable) pcx; - private IIcon getConnectedCable( final IBlockAccess world, final int x, final int y, final int z, final ForgeDirection side, final boolean covered ) - { - final int tileYPos = y + side.offsetY; + if (pc.isConnected(side.getOpposite())) { + if (covered) { + return pc.getCoveredTexture(pc.getCableColor()); + } + return pc.getGlassTexture(pc.getCableColor()); + } + } + } + } - if( -1 < tileYPos && tileYPos < 256 ) - { - final TileEntity ne = world.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); - if( ne instanceof IGridHost && ne instanceof IPartHost ) - { - final IPartHost ph = (IPartHost) ne; - final IPart pcx = ph.getPart( ForgeDirection.UNKNOWN ); + return null; + } - if( pcx instanceof PartCable ) - { - final 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( final IPartCollisionHelper bch ) - { - bch.addBox( 0, 0, 0, 16, 16, 16 ); - } + @Override + public void getBoxes(final 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 9cc1a5ae..cf4cdb2d 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 appeng.api.util.IOrientable; import appeng.block.misc.BlockCharger; @@ -37,144 +38,172 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.EnumSet; +public class RenderBlockCharger extends BaseBlockRender { + public RenderBlockCharger() { + super(true, 30); + } + @Override + public void renderInventory( + final BlockCharger blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + final Tessellator tess = Tessellator.instance; -public class RenderBlockCharger extends BaseBlockRender -{ + renderer.renderAllFaces = true; + this.setInvRenderBounds(renderer, 6, 1, 0, 10, 15, 2); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - public RenderBlockCharger() - { - super( true, 30 ); - } + blk.getRendererInstance().setTemporaryRenderIcons( + ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null + ); - @Override - public void renderInventory( final BlockCharger blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final Tessellator tess = Tessellator.instance; + this.setInvRenderBounds(renderer, 2, 0, 2, 14, 3, 14); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - renderer.renderAllFaces = true; - this.setInvRenderBounds( renderer, 6, 1, 0, 10, 15, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 3, 3, 3, 13, 4, 13); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - blk.getRendererInstance().setTemporaryRenderIcons( ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null ); + blk.getRendererInstance().setTemporaryRenderIcon(null); - this.setInvRenderBounds( renderer, 2, 0, 2, 14, 3, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + blk.getRendererInstance().setTemporaryRenderIcons( + null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null + ); - this.setInvRenderBounds( renderer, 3, 3, 3, 13, 4, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 2, 13, 2, 14, 16, 14); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - blk.getRendererInstance().setTemporaryRenderIcon( null ); + this.setInvRenderBounds(renderer, 3, 12, 3, 13, 13, 13); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - blk.getRendererInstance().setTemporaryRenderIcons( null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null ); + renderer.renderAllFaces = false; + blk.getRendererInstance().setTemporaryRenderIcon(null); + } - this.setInvRenderBounds( renderer, 2, 13, 2, 14, 16, 14 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + @Override + public boolean renderInWorld( + final BlockCharger block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + this.preRenderInWorld(block, world, x, y, z, renderer); - this.setInvRenderBounds( renderer, 3, 12, 3, 13, 13, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + final IOrientable te = this.getOrientable(block, world, x, y, z); - renderer.renderAllFaces = false; - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } + final ForgeDirection fdy = te.getUp(); + final ForgeDirection fdz = te.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); - @Override - public boolean renderInWorld( final BlockCharger block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - this.preRenderInWorld( block, world, x, y, z, renderer ); + renderer.renderAllFaces = true; + this.renderBlockBounds(renderer, 6, 1, 0, 10, 15, 2, fdx, fdy, fdz); + boolean out = renderer.renderStandardBlock(block, x, y, z); - final IOrientable te = this.getOrientable( block, world, x, y, z ); + block.getRendererInstance().setTemporaryRenderIcons( + ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null + ); - final ForgeDirection fdy = te.getUp(); - final ForgeDirection fdz = te.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); + this.renderBlockBounds(renderer, 2, 0, 2, 14, 3, 14, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - renderer.renderAllFaces = true; - this.renderBlockBounds( renderer, 6, 1, 0, 10, 15, 2, fdx, fdy, fdz ); - boolean out = renderer.renderStandardBlock( block, x, y, z ); + this.renderBlockBounds(renderer, 3, 3, 3, 13, 4, 13, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - block.getRendererInstance().setTemporaryRenderIcons( ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null, null ); + block.getRendererInstance().setTemporaryRenderIcon(null); - this.renderBlockBounds( renderer, 2, 0, 2, 14, 3, 14, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + block.getRendererInstance().setTemporaryRenderIcons( + null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null + ); - this.renderBlockBounds( renderer, 3, 3, 3, 13, 4, 13, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + this.renderBlockBounds(renderer, 2, 13, 2, 14, 16, 14, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - block.getRendererInstance().setTemporaryRenderIcon( null ); + this.renderBlockBounds(renderer, 3, 12, 3, 13, 13, 13, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - block.getRendererInstance().setTemporaryRenderIcons( null, ExtraBlockTextures.BlockChargerInside.getIcon(), null, null, null, null ); + renderer.renderAllFaces = false; + block.getRendererInstance().setTemporaryRenderIcon(null); - this.renderBlockBounds( renderer, 2, 13, 2, 14, 16, 14, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + this.postRenderInWorld(renderer); + return out; + } - this.renderBlockBounds( renderer, 3, 12, 3, 13, 13, 13, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + @Override + public void renderTile( + final BlockCharger block, + final TileCharger tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer + ) { + if (tile == null) { + return; + } - renderer.renderAllFaces = false; - block.getRendererInstance().setTemporaryRenderIcon( null ); + final ItemStack sis = tile.getStackInSlot(0); - this.postRenderInWorld( renderer ); - return out; - } + if (sis == null) { + return; + } - @Override - public void renderTile( final BlockCharger block, final TileCharger tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( tile == null ) - { - return; - } + GL11.glPushMatrix(); + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); - final ItemStack sis = tile.getStackInSlot( 0 ); + try { + GL11.glTranslatef(0.5f, 0.45f, 0.5f); + GL11.glScalef(1.0f / 1.1f, 1.0f / 1.1f, 1.0f / 1.1f); + GL11.glScalef(1.0f, 1.0f, 1.0f); - if( sis == null ) - { - return; - } + final Block blk = Block.getBlockFromItem(sis.getItem()); - GL11.glPushMatrix(); - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); + 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); + GL11.glRotatef(30.0f, 0.0f, 1.0f, 0.0f); + } + final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( + tile.xCoord, tile.yCoord, tile.zCoord, 0 + ); + final int var11 = br % 65536; + final int var12 = br / 65536; - try - { - GL11.glTranslatef( 0.5f, 0.45f, 0.5f ); - GL11.glScalef( 1.0f / 1.1f, 1.0f / 1.1f, 1.0f / 1.1f ); - GL11.glScalef( 1.0f, 1.0f, 1.0f ); + OpenGlHelper.setLightmapTextureCoords( + OpenGlHelper.lightmapTexUnit, var11, var12 + ); - final Block blk = Block.getBlockFromItem( sis.getItem() ); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - 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 ); - GL11.glRotatef( 30.0f, 0.0f, 1.0f, 0.0f ); - } - final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( tile.xCoord, tile.yCoord, tile.zCoord, 0 ); - final int var11 = br % 65536; - final int var12 = br / 65536; + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11, var12 ); + this.doRenderItem(sis, tile); + } catch (final Exception err) { + AELog.debug(err); + } finally { + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_LIGHTING); + } - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - - this.doRenderItem( sis, tile ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - finally - { - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glEnable( GL11.GL_LIGHTING ); - } - - GL11.glPopMatrix(); - } + 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 cec1c5ae..cd644e67 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockController.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockController.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.networking.BlockController; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; @@ -28,159 +27,150 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; +public class RenderBlockController + extends BaseBlockRender { + public RenderBlockController() { + super(false, 20); + } -public class RenderBlockController extends BaseBlockRender -{ + @Override + public boolean renderInWorld( + final BlockController blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final boolean xx + = this.getTileEntity(world, x - 1, y, z) instanceof TileController + && this.getTileEntity(world, x + 1, y, z) instanceof TileController; + final boolean yy + = this.getTileEntity(world, x, y - 1, z) instanceof TileController + && this.getTileEntity(world, x, y + 1, z) instanceof TileController; + final boolean zz + = this.getTileEntity(world, x, y, z - 1) instanceof TileController + && this.getTileEntity(world, x, y, z + 1) instanceof TileController; - public RenderBlockController() - { - super( false, 20 ); - } + final int meta = world.getBlockMetadata(x, y, z); + final boolean hasPower = meta > 0; + final boolean isConflict = meta == 2; - @Override - public boolean renderInWorld( final BlockController blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { + ExtraBlockTextures lights = null; - final boolean xx = this.getTileEntity( world, x - 1, y, z ) instanceof TileController && this.getTileEntity( world, x + 1, y, z ) instanceof TileController; - final boolean yy = this.getTileEntity( world, x, y - 1, z ) instanceof TileController && this.getTileEntity( world, x, y + 1, z ) instanceof TileController; - final boolean zz = this.getTileEntity( world, x, y, z - 1 ) instanceof TileController && this.getTileEntity( world, x, y, z + 1 ) instanceof TileController; + if (xx && !yy && !zz) { + if (hasPower) { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerColumnPowered.getIcon() + ); + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerColumnConflict; + } else { + lights = ExtraBlockTextures.BlockControllerColumnLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerColumn.getIcon() + ); + } - final int meta = world.getBlockMetadata( x, y, z ); - final boolean hasPower = meta > 0; - final boolean isConflict = meta == 2; + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + } else if (!xx && yy && !zz) { + if (hasPower) { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerColumnPowered.getIcon() + ); + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerColumnConflict; + } else { + lights = ExtraBlockTextures.BlockControllerColumnLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerColumn.getIcon() + ); + } - ExtraBlockTextures lights = null; + renderer.uvRotateEast = 0; + renderer.uvRotateNorth = 0; + } else if (!xx && !yy && zz) { + if (hasPower) { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerColumnPowered.getIcon() + ); + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerColumnConflict; + } else { + lights = ExtraBlockTextures.BlockControllerColumnLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerColumn.getIcon() + ); + } - if( xx && !yy && !zz ) - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerColumnConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerColumnLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); - } + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 1; + renderer.uvRotateTop = 0; + } else if ((xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) >= 2) { + final int v = (Math.abs(x) + Math.abs(y) + Math.abs(z)) % 2; - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - } - else if( !xx && yy && !zz ) - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerColumnConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerColumnLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); - } + renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest + = 0; - renderer.uvRotateEast = 0; - renderer.uvRotateNorth = 0; - } - else if( !xx && !yy && zz ) - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumnPowered.getIcon() ); - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerColumnConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerColumnLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerColumn.getIcon() ); - } + if (v == 0) { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerInsideA.getIcon() + ); + } else { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerInsideB.getIcon() + ); + } + } else { + if (hasPower) { + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockControllerPowered.getIcon() + ); - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 1; - renderer.uvRotateTop = 0; - } - else if( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) >= 2 ) - { - final int v = ( Math.abs( x ) + Math.abs( y ) + Math.abs( z ) ) % 2; + if (isConflict) { + lights = ExtraBlockTextures.BlockControllerConflict; + } else { + lights = ExtraBlockTextures.BlockControllerLights; + } + } else { + blk.getRendererInstance().setTemporaryRenderIcon(null); + } + } - renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + final boolean out = renderer.renderStandardBlock(blk, x, y, z); - if( v == 0 ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideA.getIcon() ); - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerInsideB.getIcon() ); - } - } - else - { - if( hasPower ) - { - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockControllerPowered.getIcon() ); + if (lights != null) { + Tessellator.instance.setColorOpaque_F(1.0f, 1.0f, 1.0f); + Tessellator.instance.setBrightness(14 << 20 | 14 << 4); + renderer.renderFaceXNeg(blk, x, y, z, lights.getIcon()); + renderer.renderFaceXPos(blk, x, y, z, lights.getIcon()); + renderer.renderFaceYNeg(blk, x, y, z, lights.getIcon()); + renderer.renderFaceYPos(blk, x, y, z, lights.getIcon()); + renderer.renderFaceZNeg(blk, x, y, z, lights.getIcon()); + renderer.renderFaceZPos(blk, x, y, z, lights.getIcon()); + } - if( isConflict ) - { - lights = ExtraBlockTextures.BlockControllerConflict; - } - else - { - lights = ExtraBlockTextures.BlockControllerLights; - } - } - else - { - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } - } + blk.getRendererInstance().setTemporaryRenderIcon(null); + renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + return out; + } - final boolean out = renderer.renderStandardBlock( blk, x, y, z ); - - if( lights != null ) - { - Tessellator.instance.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - Tessellator.instance.setBrightness( 14 << 20 | 14 << 4 ); - renderer.renderFaceXNeg( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceXPos( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceYNeg( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceYPos( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceZNeg( blk, x, y, z, lights.getIcon() ); - renderer.renderFaceZPos( blk, x, y, z, lights.getIcon() ); - } - - blk.getRendererInstance().setTemporaryRenderIcon( null ); - renderer.uvRotateEast = renderer.uvRotateBottom = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - return out; - } - - private TileEntity getTileEntity( final IBlockAccess world, final int x, final int y, final int z ) - { - if( y >= 0 ) - { - return world.getTileEntity( x, y, z ); - } - return null; - } + private TileEntity + getTileEntity(final IBlockAccess world, final int x, final int y, final int z) { + 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 221e55e0..9813ffd3 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 appeng.api.AEApi; import appeng.api.util.AEColor; @@ -37,324 +38,467 @@ import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RenderBlockCraftingCPU + extends BaseBlockRender { + protected RenderBlockCraftingCPU(final boolean useTESR, final int range) { + super(useTESR, range); + } + public RenderBlockCraftingCPU() { + super(false, 20); + } -public class RenderBlockCraftingCPU extends BaseBlockRender -{ + @Override + public boolean renderInWorld( + final B blk, + final IBlockAccess w, + final int x, + final int y, + final int z, + RenderBlocks renderer + ) { + final TileCraftingTile craftingTile = blk.getTileEntity(w, x, y, z); - protected RenderBlockCraftingCPU( final boolean useTESR, final int range ) - { - super( useTESR, range ); - } + if (craftingTile == null) { + return false; + } - public RenderBlockCraftingCPU() - { - super( false, 20 ); - } + final boolean formed = craftingTile.isFormed(); + final boolean emitsLight = craftingTile.isPowered(); + final int meta = w.getBlockMetadata(x, y, z) & 3; + final boolean isMonitor = blk.getClass() == BlockCraftingMonitor.class; + final IIcon theIcon + = blk.getIcon(ForgeDirection.SOUTH.ordinal(), meta | (formed ? 8 : 0)); + IIcon nonForward = theIcon; - @Override - public boolean renderInWorld( final B blk, final IBlockAccess w, final int x, final int y, final int z, RenderBlocks renderer ) - { - final TileCraftingTile craftingTile = blk.getTileEntity( w, x, y, z ); + if (isMonitor) { + for (final Block craftingBlock : AEApi.instance() + .definitions() + .blocks() + .craftingUnit() + .maybeBlock() + .asSet()) { + nonForward = craftingBlock.getIcon(0, meta | (formed ? 8 : 0)); + } + } - if( craftingTile == null ) - { - return false; - } + if (formed && renderer.overrideBlockTexture == null) { + renderer = BusRenderer.INSTANCE.getRenderer(); + final BusRenderHelper i = BusRenderHelper.INSTANCE; + BusRenderer.INSTANCE.getRenderer().setFacade(true); - final boolean formed = craftingTile.isFormed(); - final boolean emitsLight = craftingTile.isPowered(); - final int meta = w.getBlockMetadata( x, y, z ) & 3; - final boolean isMonitor = blk.getClass() == BlockCraftingMonitor.class; - final IIcon theIcon = blk.getIcon( ForgeDirection.SOUTH.ordinal(), meta | ( formed ? 8 : 0 ) ); - IIcon nonForward = theIcon; + renderer.blockAccess = w; + i.setPass(0); + i.setOrientation( + ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH + ); - if( isMonitor ) - { - for( final Block craftingBlock : AEApi.instance().definitions().blocks().craftingUnit().maybeBlock().asSet() ) - { - nonForward = craftingBlock.getIcon( 0, meta | ( formed ? 8 : 0 ) ); - } - } + try { + craftingTile.setLightCache( + i.useSimplifiedRendering(x, y, z, null, craftingTile.getLightCache()) + ); + } catch (final Throwable ignored) {} - if( formed && renderer.overrideBlockTexture == null ) - { - renderer = BusRenderer.INSTANCE.getRenderer(); - final BusRenderHelper i = BusRenderHelper.INSTANCE; - BusRenderer.INSTANCE.getRenderer().setFacade( true ); + final float highX + = this.isConnected(w, x, y, z, ForgeDirection.EAST) ? 16 : 13.01f; + final float lowX + = this.isConnected(w, x, y, z, ForgeDirection.WEST) ? 0 : 2.99f; - renderer.blockAccess = w; - i.setPass( 0 ); - i.setOrientation( ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); + final float highY + = this.isConnected(w, x, y, z, ForgeDirection.UP) ? 16 : 13.01f; + final float lowY + = this.isConnected(w, x, y, z, ForgeDirection.DOWN) ? 0 : 2.99f; - try - { - craftingTile.setLightCache( i.useSimplifiedRendering( x, y, z, null, craftingTile.getLightCache() ) ); - } - catch( final Throwable ignored ) - { + final float highZ + = this.isConnected(w, x, y, z, ForgeDirection.SOUTH) ? 16 : 13.01f; + final float lowZ + = this.isConnected(w, x, y, z, ForgeDirection.NORTH) ? 0 : 2.99f; - } + this.renderCorner( + i, + renderer, + w, + x, + y, + z, + ForgeDirection.UP, + ForgeDirection.EAST, + ForgeDirection.NORTH + ); + this.renderCorner( + i, + renderer, + w, + x, + y, + z, + ForgeDirection.UP, + ForgeDirection.EAST, + ForgeDirection.SOUTH + ); + this.renderCorner( + i, + renderer, + w, + x, + y, + z, + ForgeDirection.UP, + ForgeDirection.WEST, + ForgeDirection.NORTH + ); + this.renderCorner( + i, + renderer, + w, + x, + y, + z, + ForgeDirection.UP, + ForgeDirection.WEST, + ForgeDirection.SOUTH + ); + this.renderCorner( + i, + renderer, + w, + x, + y, + z, + ForgeDirection.DOWN, + ForgeDirection.EAST, + ForgeDirection.NORTH + ); + this.renderCorner( + i, + renderer, + w, + x, + y, + z, + ForgeDirection.DOWN, + ForgeDirection.EAST, + ForgeDirection.SOUTH + ); + 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 + ); - final float highX = this.isConnected( w, x, y, z, ForgeDirection.EAST ) ? 16 : 13.01f; - final float lowX = this.isConnected( w, x, y, z, ForgeDirection.WEST ) ? 0 : 2.99f; + for (final 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.prepareBounds(renderer); - final float highY = this.isConnected( w, x, y, z, ForgeDirection.UP ) ? 16 : 13.01f; - final float lowY = this.isConnected( w, x, y, z, ForgeDirection.DOWN ) ? 0 : 2.99f; + boolean localEmit = emitsLight; - final float highZ = this.isConnected( w, x, y, z, ForgeDirection.SOUTH ) ? 16 : 13.01f; - final float lowZ = this.isConnected( w, x, y, z, ForgeDirection.NORTH ) ? 0 : 2.99f; + if (blk instanceof BlockCraftingMonitor + && craftingTile.getForward() != side) { + localEmit = false; + } - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.EAST, ForgeDirection.NORTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.EAST, ForgeDirection.SOUTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.WEST, ForgeDirection.NORTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.UP, ForgeDirection.WEST, ForgeDirection.SOUTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.NORTH ); - this.renderCorner( i, renderer, w, x, y, z, ForgeDirection.DOWN, ForgeDirection.EAST, ForgeDirection.SOUTH ); - 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 ); + this.handleSide( + blk, + meta, + x, + y, + z, + i, + renderer, + craftingTile.getForward() == side ? theIcon : nonForward, + localEmit, + isMonitor, + side, + w + ); + } - for( final 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.prepareBounds( renderer ); + BusRenderer.INSTANCE.getRenderer().setFacade(false); + i.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + i.normalRendering(); - boolean localEmit = emitsLight; + return true; + } else { + final double a = 0.0 / 16.0; + final double o = 16.0 / 16.0; + renderer.setRenderBounds(a, a, a, o, o, o); - if( blk instanceof BlockCraftingMonitor && craftingTile.getForward() != side ) - { - localEmit = false; - } + return renderer.renderStandardBlock(blk, x, y, z); + } + } - this.handleSide( blk, meta, x, y, z, i, renderer, craftingTile.getForward() == side ? theIcon : nonForward, localEmit, isMonitor, side, w ); - } + private boolean isConnected( + final IBlockAccess w, + final int x, + final int y, + final int z, + final ForgeDirection side + ) { + final int tileYPos = y + side.offsetY; - BusRenderer.INSTANCE.getRenderer().setFacade( false ); - i.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - i.normalRendering(); + if (0 <= tileYPos && tileYPos <= 255) { + final TileEntity tile + = w.getTileEntity(x + side.offsetX, tileYPos, z + side.offsetZ); - return true; - } - else - { - final double a = 0.0 / 16.0; - final double o = 16.0 / 16.0; - renderer.setRenderBounds( a, a, a, o, o, o ); + return tile instanceof TileCraftingTile; + } else { + return false; + } + } - return renderer.renderStandardBlock( blk, x, y, z ); - } - } + private void renderCorner( + final BusRenderHelper i, + final RenderBlocks renderer, + final IBlockAccess w, + final int x, + final int y, + final int z, + final ForgeDirection up, + final ForgeDirection east, + final ForgeDirection south + ) { + if (this.isConnected(w, x, y, z, up) || this.isConnected(w, x, y, z, east) + || this.isConnected(w, x, y, z, south)) { + return; + } - private boolean isConnected( final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection side ) - { - final int tileYPos = y + side.offsetY; + 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); + } - if( 0 <= tileYPos && tileYPos <= 255 ) - { - final TileEntity tile = w.getTileEntity( x + side.offsetX, tileYPos, z + side.offsetZ ); + private float + fso(final ForgeDirection side, final float def, final ForgeDirection target) { + if (side == target) { + if (side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0) { + return 16; + } + return 0; + } + return def; + } - return tile instanceof TileCraftingTile; - } - else - { - return false; - } - } + private void handleSide( + final B blk, + final int meta, + final int x, + final int y, + final int z, + final BusRenderHelper i, + final RenderBlocks renderer, + final IIcon color, + final boolean emitsLight, + final boolean isMonitor, + final ForgeDirection side, + final IBlockAccess w + ) { + if (this.isConnected(w, x, y, z, side)) { + return; + } - private void renderCorner( final BusRenderHelper i, final RenderBlocks renderer, final IBlockAccess w, final int x, final int y, final int z, final ForgeDirection up, final ForgeDirection east, final ForgeDirection south ) - { - if( this.isConnected( w, x, y, z, up ) || this.isConnected( w, x, y, z, east ) || this.isConnected( w, x, y, z, south ) ) - { - return; - } + i.setFacesToRender(EnumSet.of(side)); - 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 ); - } + 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()) { + i.setTexture(ExtraBlockTextures.BlockCraftingMonitorOuter.getIcon()); + } else { + i.setTexture(ExtraBlockTextures.BlockCraftingFitSolid.getIcon()); + } - private float fso( final ForgeDirection side, final float def, final ForgeDirection target ) - { - if( side == target ) - { - if( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) - { - return 16; - } - return 0; - } - return def; - } + i.renderBlockCurrentBounds(x, y, z, renderer); - private void handleSide( final B blk, final int meta, final int x, final int y, final int z, final BusRenderHelper i, final RenderBlocks renderer, final IIcon color, final boolean emitsLight, final boolean isMonitor, final ForgeDirection side, final IBlockAccess w ) - { - if( this.isConnected( w, x, y, z, side ) ) - { - return; - } + if (color != null) { + i.setTexture(color); - i.setFacesToRender( EnumSet.of( side ) ); + if (!emitsLight) { + if (color + == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon()) { + final int b = w.getLightBrightnessForSkyBlocks( + x + side.offsetX, y + side.offsetY, z + side.offsetZ, 0 + ); - 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() ) - { - i.setTexture( ExtraBlockTextures.BlockCraftingMonitorOuter.getIcon() ); - } - else - { - i.setTexture( ExtraBlockTextures.BlockCraftingFitSolid.getIcon() ); - } + final TileCraftingMonitorTile sr = blk.getTileEntity(w, x, y, z); + final AEColor col = sr.getColor(); - i.renderBlockCurrentBounds( x, y, z, renderer ); + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(col.whiteVariant); + i.renderFace(x, y, z, color, side, renderer); - if( color != null ) - { - i.setTexture( color ); + Tessellator.instance.setColorOpaque_I(col.mediumVariant); + i.renderFace( + x, + y, + z, + ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), + side, + renderer + ); - if( !emitsLight ) - { - if( color == ExtraBlockTextures.BlockCraftingMonitorFit_Light.getIcon() ) - { - final int b = w.getLightBrightnessForSkyBlocks( x + side.offsetX, y + side.offsetY, z + side.offsetZ, 0 ); + Tessellator.instance.setColorOpaque_I(col.blackVariant); + i.renderFace( + x, + y, + z, + ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), + side, + renderer + ); + } else { + i.renderBlockCurrentBounds(x, y, z, renderer); + } + } else { + if (isMonitor) { + final TileCraftingMonitorTile sr = blk.getTileEntity(w, x, y, z); + final AEColor col = sr.getColor(); - final TileCraftingMonitorTile sr = blk.getTileEntity( w, x, y, z ); - final AEColor col = sr.getColor(); + Tessellator.instance.setColorOpaque_I(col.whiteVariant); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace(x, y, z, color, side, renderer); - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( col.whiteVariant ); - i.renderFace( x, y, z, color, side, renderer ); + Tessellator.instance.setColorOpaque_I(col.mediumVariant); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace( + x, + y, + z, + ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), + side, + renderer + ); - Tessellator.instance.setColorOpaque_I( col.mediumVariant ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), side, renderer ); + Tessellator.instance.setColorOpaque_I(col.blackVariant); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace( + x, + y, + z, + ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), + side, + renderer + ); + } else { + Tessellator.instance.setColorOpaque_F(1.0f, 1.0f, 1.0f); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + i.renderFace(x, y, z, color, side, renderer); + } + } + } + } - Tessellator.instance.setColorOpaque_I( col.blackVariant ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), side, renderer ); - } - else - { - i.renderBlockCurrentBounds( x, y, z, renderer ); - } - } - else - { - if( isMonitor ) - { - final TileCraftingMonitorTile sr = blk.getTileEntity( w, x, y, z ); - final AEColor col = sr.getColor(); + for (final ForgeDirection a : ForgeDirection.VALID_DIRECTIONS) { + if (a == side || a == side.getOpposite()) { + continue; + } - Tessellator.instance.setColorOpaque_I( col.whiteVariant ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, color, side, renderer ); - - Tessellator.instance.setColorOpaque_I( col.mediumVariant ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Medium.getIcon(), side, renderer ); - - Tessellator.instance.setColorOpaque_I( col.blackVariant ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, ExtraBlockTextures.BlockCraftingMonitorFit_Dark.getIcon(), side, renderer ); - } - else - { - Tessellator.instance.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); - Tessellator.instance.setBrightness( 13 << 20 | 13 << 4 ); - i.renderFace( x, y, z, color, side, renderer ); - } - } - } - } - - for( final ForgeDirection a : ForgeDirection.VALID_DIRECTIONS ) - { - 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 ) ) - { - i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon() ); - } + 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 ) ) { - i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon() ); - } - else - { - i.setTexture( ExtraBlockTextures.BlockCraftingUnitRingLong.getIcon() ); - } + i.setTexture(ExtraBlockTextures.BlockCraftingUnitRingLongRotated.getIcon() + ); + } else { + i.setTexture(ExtraBlockTextures.BlockCraftingUnitRingLong.getIcon()); + } - if( !( i.getBound( a ) < 0.001 || i.getBound( a ) > 15.999 ) ) - { - final double width = 3.0 / 16.0; + if (!(i.getBound(a) < 0.001 || i.getBound(a) > 15.999)) { + final double width = 3.0 / 16.0; - 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: - } + 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: + } - i.renderBlockCurrentBounds( x, y, z, renderer ); - i.prepareBounds( renderer ); - } - } - } + i.renderBlockCurrentBounds(x, y, z, renderer); + i.prepareBounds(renderer); + } + } + } - private float gso( final ForgeDirection side, final float def, final ForgeDirection target ) - { - if( side != target ) - { - if( side.offsetX > 0 || side.offsetY > 0 || side.offsetZ > 0 ) - { - return 16; - } - return 0; - } - return def; - } + private float + gso(final ForgeDirection side, final float def, final ForgeDirection target) { + if (side != target) { + 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 2fa0eb70..65681f36 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCraftingCPUMonitor.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.storage.data.IAEItemStack; import appeng.block.crafting.BlockCraftingMonitor; import appeng.client.ClientHelper; @@ -38,149 +37,146 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv1 */ -public class RenderBlockCraftingCPUMonitor extends RenderBlockCraftingCPU -{ - private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; +public class RenderBlockCraftingCPUMonitor + extends RenderBlockCraftingCPU { + private static final IWideReadableNumberConverter NUMBER_CONVERTER + = ReadableNumberConverter.INSTANCE; - public RenderBlockCraftingCPUMonitor() - { - super( true, 20 ); - } + public RenderBlockCraftingCPUMonitor() { + super(true, 20); + } - @Override - public void renderTile( final BlockCraftingMonitor block, final TileCraftingMonitorTile tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( tile != null ) - { - final IAEItemStack ais = tile.getJobProgress(); + @Override + public void renderTile( + final BlockCraftingMonitor block, + final TileCraftingMonitorTile tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer + ) { + if (tile != null) { + final IAEItemStack ais = tile.getJobProgress(); - if( tile.getDisplayList() == null ) - { - tile.setUpdateList( true ); - tile.setDisplayList( GLAllocation.generateDisplayLists( 1 ) ); - } - else - { - GL11.glPushMatrix(); - GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); + if (tile.getDisplayList() == null) { + tile.setUpdateList(true); + tile.setDisplayList(GLAllocation.generateDisplayLists(1)); + } else { + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); - if( tile.isUpdateList() ) - { - tile.setUpdateList( false ); - GL11.glNewList( tile.getDisplayList(), GL11.GL_COMPILE_AND_EXECUTE ); - this.tesrRenderScreen( tess, tile, ais ); - GL11.glEndList(); - } - else - { - GL11.glCallList( tile.getDisplayList() ); - } + if (tile.isUpdateList()) { + tile.setUpdateList(false); + GL11.glNewList(tile.getDisplayList(), GL11.GL_COMPILE_AND_EXECUTE); + this.tesrRenderScreen(tess, tile, ais); + GL11.glEndList(); + } else { + GL11.glCallList(tile.getDisplayList()); + } - GL11.glPopMatrix(); - } - } - } + GL11.glPopMatrix(); + } + } + } - private void tesrRenderScreen( final Tessellator tess, final TileCraftingMonitorTile cmt, final IAEItemStack ais ) - { - final ForgeDirection side = cmt.getForward(); + private void tesrRenderScreen( + final Tessellator tess, final TileCraftingMonitorTile cmt, final IAEItemStack ais + ) { + final ForgeDirection side = cmt.getForward(); - ForgeDirection walrus = side.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP; - int spin = 0; - int max = 5; + ForgeDirection walrus + = side.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP; + int spin = 0; + int max = 5; - while( walrus != cmt.getUp() && max > 0 ) - { - max--; - spin++; - walrus = Platform.rotateAround( walrus, side ); - } - max--; + while (walrus != cmt.getUp() && max > 0) { + max--; + spin++; + walrus = Platform.rotateAround(walrus, side); + } + max--; - GL11.glTranslated( side.offsetX * 0.69, side.offsetY * 0.69, side.offsetZ * 0.69 ); + GL11.glTranslated(side.offsetX * 0.69, side.offsetY * 0.69, side.offsetZ * 0.69); - final float scale = 0.7f; - GL11.glScalef( scale, scale, scale ); + final float scale = 0.7f; + GL11.glScalef(scale, scale, scale); - switch( side ) - { - case 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 ); - break; - case 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 ); - break; - case EAST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( -90.0f, 0.0f, 1.0f, 0.0f ); - break; - case WEST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); - break; - case NORTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - break; - case SOUTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 180.0f, 0.0f, 1.0f, 0.0f ); - break; + switch (side) { + case 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); + break; + case 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); + break; + case EAST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); + break; + case WEST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); + break; + case NORTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + break; + case SOUTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(180.0f, 0.0f, 1.0f, 0.0f); + break; - default: - break; - } + default: + break; + } - try - { - final ItemStack sis = ais.getItemStack(); - sis.stackSize = 1; + try { + final ItemStack sis = ais.getItemStack(); + sis.stackSize = 1; - final int br = 16 << 20 | 16 << 4; - final int var11 = br % 65536; - final int var12 = br / 65536; + final int br = 16 << 20 | 16 << 4; + final int var11 = br % 65536; + final int var12 = br / 65536; - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F ); + OpenGlHelper.setLightmapTextureCoords( + OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F + ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - // RenderHelper.enableGUIStandardItemLighting(); - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + // RenderHelper.enableGUIStandardItemLighting(); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); - ClientHelper.proxy.doRenderItem( sis, cmt.getWorldObj() ); - } - catch( final Exception e ) - { - AELog.debug( e ); - } - finally - { - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glEnable( GL11.GL_LIGHTING ); - } + ClientHelper.proxy.doRenderItem(sis, cmt.getWorldObj()); + } catch (final Exception e) { + AELog.debug(e); + } finally { + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glEnable(GL11.GL_LIGHTING); + } - GL11.glTranslatef( 0.0f, 0.14f, -0.24f ); - GL11.glScalef( 1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f ); + GL11.glTranslatef(0.0f, 0.14f, -0.24f); + GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); - final long stackSize = ais.getStackSize(); - final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ); + final long stackSize = ais.getStackSize(); + final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm(stackSize); - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( renderedStackSize ); + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(renderedStackSize); - GL11.glTranslatef( -0.5f * width, 0.0f, -1.0f ); - fr.drawString( renderedStackSize, 0, 0, 0 ); - } + GL11.glTranslatef(-0.5f * width, 0.0f, -1.0f); + fr.drawString(renderedStackSize, 0, 0, 0); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java b/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java index 6a893536..1a744309 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockCrank.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.grindstone.BlockCrank; import appeng.client.render.BaseBlockRender; import appeng.tile.grindstone.TileCrank; @@ -33,81 +32,112 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; +public class RenderBlockCrank extends BaseBlockRender { + public RenderBlockCrank() { + super(true, 60); + } -public class RenderBlockCrank extends BaseBlockRender -{ + @Override + public void renderInventory( + final BlockCrank blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.renderAllFaces = true; - public RenderBlockCrank() - { - super( true, 60 ); - } + renderer.setRenderBounds( + 0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.3, 0.5D + 0.05 + ); + super.renderInventory(blk, is, renderer, type, obj); - @Override - public void renderInventory( final BlockCrank blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.renderAllFaces = true; + renderer.setRenderBounds( + 0.70D - 0.15, + 0.75D - 0.05, + 0.5D - 0.05, + 0.70D + 0.28, + 0.75D + 0.05, + 0.5D + 0.05 + ); + super.renderInventory(blk, is, renderer, type, obj); - renderer.setRenderBounds( 0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.3, 0.5D + 0.05 ); - super.renderInventory( blk, is, renderer, type, obj ); + renderer.renderAllFaces = false; + } - renderer.setRenderBounds( 0.70D - 0.15, 0.75D - 0.05, 0.5D - 0.05, 0.70D + 0.28, 0.75D + 0.05, 0.5D + 0.05 ); - super.renderInventory( blk, is, renderer, type, obj ); + @Override + public boolean renderInWorld( + final BlockCrank imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + return true; + } - renderer.renderAllFaces = false; - } + @Override + public void renderTile( + final BlockCrank blk, + final TileCrank tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderBlocks + ) { + if (tile.getUp() == null || tile.getUp() == ForgeDirection.UNKNOWN) { + return; + } + Minecraft.getMinecraft().getTextureManager().bindTexture( + TextureMap.locationBlocksTexture + ); + RenderHelper.disableStandardItemLighting(); - @Override - public boolean renderInWorld( final BlockCrank imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } + if (Minecraft.isAmbientOcclusionEnabled()) { + GL11.glShadeModel(GL11.GL_SMOOTH); + } else { + GL11.glShadeModel(GL11.GL_FLAT); + } - @Override - public void renderTile( final BlockCrank blk, final TileCrank tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderBlocks ) - { - if( tile.getUp() == null || tile.getUp() == ForgeDirection.UNKNOWN ) - { - return; - } - Minecraft.getMinecraft().getTextureManager().bindTexture( TextureMap.locationBlocksTexture ); - RenderHelper.disableStandardItemLighting(); + GL11.glCullFace(GL11.GL_FRONT); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); - if( Minecraft.isAmbientOcclusionEnabled() ) - { - GL11.glShadeModel( GL11.GL_SMOOTH ); - } - else - { - GL11.glShadeModel( GL11.GL_FLAT ); - } + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); - GL11.glCullFace( GL11.GL_FRONT ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); + GL11.glTranslated(0.5, 0, 0.5); + GL11.glRotatef(tile.getVisibleRotation(), 0, 1, 0); + GL11.glTranslated(-0.5, 0, -0.5); - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); + tess.setTranslation(-tile.xCoord, -tile.yCoord, -tile.zCoord); + tess.startDrawingQuads(); + renderBlocks.renderAllFaces = true; + renderBlocks.blockAccess = tile.getWorldObj(); - GL11.glTranslated( 0.5, 0, 0.5 ); - GL11.glRotatef( tile.getVisibleRotation(), 0, 1, 0 ); - GL11.glTranslated( -0.5, 0, -0.5 ); + renderBlocks.setRenderBounds( + 0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.1, 0.5D + 0.05 + ); - tess.setTranslation( -tile.xCoord, -tile.yCoord, -tile.zCoord ); - tess.startDrawingQuads(); - renderBlocks.renderAllFaces = true; - renderBlocks.blockAccess = tile.getWorldObj(); + renderBlocks.renderStandardBlock(blk, tile.xCoord, tile.yCoord, tile.zCoord); - renderBlocks.setRenderBounds( 0.5D - 0.05, 0.5D - 0.5, 0.5D - 0.05, 0.5D + 0.05, 0.5D + 0.1, 0.5D + 0.05 ); + renderBlocks.setRenderBounds( + 0.70D - 0.15, + 0.55D - 0.05, + 0.5D - 0.05, + 0.70D + 0.15, + 0.55D + 0.05, + 0.5D + 0.05 + ); - renderBlocks.renderStandardBlock( blk, tile.xCoord, tile.yCoord, tile.zCoord ); + renderBlocks.renderStandardBlock(blk, tile.xCoord, tile.yCoord, tile.zCoord); - renderBlocks.setRenderBounds( 0.70D - 0.15, 0.55D - 0.05, 0.5D - 0.05, 0.70D + 0.15, 0.55D + 0.05, 0.5D + 0.05 ); + tess.draw(); + tess.setTranslation(0, 0, 0); - renderBlocks.renderStandardBlock( blk, tile.xCoord, tile.yCoord, tile.zCoord ); + GL11.glCullFace(GL11.GL_BACK); - tess.draw(); - tess.setTranslation( 0, 0, 0 ); - - GL11.glCullFace( GL11.GL_BACK ); - - RenderHelper.enableStandardItemLighting(); - } + 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 5219ff2b..a34e273f 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockEnergyCube.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.api.implementations.items.IAEItemPowerStorage; import appeng.block.networking.BlockEnergyCell; import appeng.client.render.BaseBlockRender; @@ -28,48 +27,54 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RenderBlockEnergyCube + extends BaseBlockRender { + public RenderBlockEnergyCube() { + super(false, 20); + } -public class RenderBlockEnergyCube extends BaseBlockRender -{ + @Override + public void renderInventory( + final BlockEnergyCell blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + final IAEItemPowerStorage myItem = (IAEItemPowerStorage) is.getItem(); + final double internalCurrentPower = myItem.getAECurrentPower(is); + final double internalMaxPower = myItem.getAEMaxPower(is); - public RenderBlockEnergyCube() - { - super( false, 20 ); - } + int meta = (int) (8.0 * (internalCurrentPower / internalMaxPower)); - @Override - public void renderInventory( final BlockEnergyCell blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final IAEItemPowerStorage myItem = (IAEItemPowerStorage) is.getItem(); - final double internalCurrentPower = myItem.getAECurrentPower( is ); - final double internalMaxPower = myItem.getAEMaxPower( is ); + if (meta > 7) { + meta = 7; + } + if (meta < 0) { + meta = 0; + } - int meta = (int) ( 8.0 * ( internalCurrentPower / internalMaxPower ) ); + renderer.setOverrideBlockTexture(blk.getIcon(0, meta)); + super.renderInventory(blk, is, renderer, type, obj); + renderer.setOverrideBlockTexture(null); + } - if( meta > 7 ) - { - meta = 7; - } - if( meta < 0 ) - { - meta = 0; - } + @Override + public boolean renderInWorld( + final BlockEnergyCell blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final int meta = world.getBlockMetadata(x, y, z); - renderer.setOverrideBlockTexture( blk.getIcon( 0, meta ) ); - super.renderInventory( blk, is, renderer, type, obj ); - renderer.setOverrideBlockTexture( null ); - } + renderer.overrideBlockTexture = blk.getIcon(0, meta); - @Override - public boolean renderInWorld( final BlockEnergyCell blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final int meta = world.getBlockMetadata( x, y, z ); + final boolean out = renderer.renderStandardBlock(blk, x, y, z); + renderer.overrideBlockTexture = null; - renderer.overrideBlockTexture = blk.getIcon( 0, meta ); - - final boolean out = renderer.renderStandardBlock( blk, x, y, z ); - renderer.overrideBlockTexture = null; - - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java b/src/main/java/appeng/client/render/blocks/RenderBlockInscriber.java index 8ea64317..aa1e3588 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 appeng.api.features.IInscriberRecipe; import appeng.api.util.IOrientable; @@ -43,283 +44,406 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.EnumSet; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class RenderBlockInscriber extends BaseBlockRender -{ - private static final float ITEM_RENDER_SCALE = 1.0f / 1.1f; +public class RenderBlockInscriber extends BaseBlockRender { + private static final float ITEM_RENDER_SCALE = 1.0f / 1.1f; - public RenderBlockInscriber() - { - super( true, 30 ); - } + public RenderBlockInscriber() { + super(true, 30); + } - @Override - public void renderInventory( final BlockInscriber blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final Tessellator tess = Tessellator.instance; + @Override + public void renderInventory( + final BlockInscriber blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + final Tessellator tess = Tessellator.instance; - renderer.renderAllFaces = true; - this.setInvRenderBounds( renderer, 6, 1, 0, 10, 15, 2 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + renderer.renderAllFaces = true; + this.setInvRenderBounds(renderer, 6, 1, 0, 10, 15, 2); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - // sides... - this.setInvRenderBounds( renderer, 3, 1, 0, 13, 15, 3 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + // sides... + this.setInvRenderBounds(renderer, 3, 1, 0, 13, 15, 3); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - this.setInvRenderBounds( renderer, 0, 1, 0, 3, 15, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 0, 1, 0, 3, 15, 16); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - this.setInvRenderBounds( renderer, 13, 1, 0, 16, 15, 16 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 13, 1, 0, 16, 15, 16); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - this.setInvRenderBounds( renderer, 1, 0, 1, 15, 2, 15 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 1, 0, 1, 15, 2, 15); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - this.setInvRenderBounds( renderer, 1, 14, 1, 15, 16, 15 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 1, 14, 1, 15, 16, 15); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.BlockInscriberInside.getIcon() ); + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.BlockInscriberInside.getIcon() + ); - // press - this.setInvRenderBounds( renderer, 3, 2, 3, 13, 3, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + // press + this.setInvRenderBounds(renderer, 3, 2, 3, 13, 3, 13); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - this.setInvRenderBounds( renderer, 3, 13, 3, 13, 15, 13 ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.setInvRenderBounds(renderer, 3, 13, 3, 13, 15, 13); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - blk.getRendererInstance().setTemporaryRenderIcon( null ); + blk.getRendererInstance().setTemporaryRenderIcon(null); - renderer.renderAllFaces = false; - // blk.getRendererInstance().setTemporaryRenderIcon( null ); + renderer.renderAllFaces = false; + // blk.getRendererInstance().setTemporaryRenderIcon( null ); + } - } + @Override + public boolean renderInWorld( + final BlockInscriber block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final IOrientable te = this.getOrientable(block, world, x, y, z); - @Override - public boolean renderInWorld( final BlockInscriber block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final IOrientable te = this.getOrientable( block, world, x, y, z ); + if (te == null) { + return false; + } - if( te == null ) - { - return false; - } + this.preRenderInWorld(block, world, x, y, z, renderer); - this.preRenderInWorld( block, world, x, y, z, renderer ); + final ForgeDirection fdy = te.getUp(); + final ForgeDirection fdz = te.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); - final ForgeDirection fdy = te.getUp(); - final ForgeDirection fdz = te.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); + renderer.renderAllFaces = true; - renderer.renderAllFaces = true; + // sides... + this.renderBlockBounds(renderer, 3, 1, 0, 13, 15, 3, fdx, fdy, fdz); + boolean out = renderer.renderStandardBlock(block, x, y, z); - // sides... - this.renderBlockBounds( renderer, 3, 1, 0, 13, 15, 3, fdx, fdy, fdz ); - boolean out = renderer.renderStandardBlock( block, x, y, z ); + this.renderBlockBounds(renderer, 0, 1, 0, 3, 15, 16, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - this.renderBlockBounds( renderer, 0, 1, 0, 3, 15, 16, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + this.renderBlockBounds(renderer, 13, 1, 0, 16, 15, 16, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - this.renderBlockBounds( renderer, 13, 1, 0, 16, 15, 16, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + // top bottom.. + this.renderBlockBounds(renderer, 1, 0, 1, 15, 4, 15, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - // top bottom.. - this.renderBlockBounds( renderer, 1, 0, 1, 15, 4, 15, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + this.renderBlockBounds(renderer, 1, 12, 1, 15, 16, 15, fdx, fdy, fdz); + out = renderer.renderStandardBlock(block, x, y, z); - this.renderBlockBounds( renderer, 1, 12, 1, 15, 16, 15, fdx, fdy, fdz ); - out = renderer.renderStandardBlock( block, x, y, z ); + block.getRendererInstance().setTemporaryRenderIcon(null); - block.getRendererInstance().setTemporaryRenderIcon( null ); + renderer.renderAllFaces = false; + block.getRendererInstance().setTemporaryRenderIcon(null); - renderer.renderAllFaces = false; - block.getRendererInstance().setTemporaryRenderIcon( null ); + this.postRenderInWorld(renderer); + return out; + } - this.postRenderInWorld( renderer ); - return out; - } + @Override + public void renderTile( + final BlockInscriber block, + final TileInscriber tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer + ) { + // render inscriber - @Override - public void renderTile( final BlockInscriber block, final TileInscriber tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - // render inscriber + GL11.glPushMatrix(); + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); - GL11.glPushMatrix(); - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); + // render sides of stamps + GL11.glCullFace(GL11.GL_FRONT); - // render sides of stamps - GL11.glCullFace( GL11.GL_FRONT ); + final Minecraft mc = Minecraft.getMinecraft(); + mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture); - final Minecraft mc = Minecraft.getMinecraft(); - mc.renderEngine.bindTexture( TextureMap.locationBlocksTexture ); + // << 20 | light << 4; + final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( + tile.xCoord, tile.yCoord, tile.zCoord, 0 + ); + final int var11 = br % 65536; + final int var12 = br / 65536; - // << 20 | light << 4; - final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( tile.xCoord, tile.yCoord, tile.zCoord, 0 ); - final int var11 = br % 65536; - final int var12 = br / 65536; + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, var11, var12); - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11, var12 ); + long absoluteProgress = 0; - long absoluteProgress = 0; + if (tile.isSmash()) { + final long currentTime = System.currentTimeMillis(); + absoluteProgress = currentTime - tile.getClientStart(); + if (absoluteProgress > 800) { + tile.setSmash(false); + } + } - if( tile.isSmash() ) - { - final long currentTime = System.currentTimeMillis(); - absoluteProgress = currentTime - tile.getClientStart(); - if( absoluteProgress > 800 ) - { - tile.setSmash( false ); - } - } + final float relativeProgress = absoluteProgress % 800 / 400.0f; + float progress = relativeProgress; - final float relativeProgress = absoluteProgress % 800 / 400.0f; - float progress = relativeProgress; + if (progress > 1.0f) { + progress = 1.0f - (progress - 1.0f); + } + float press = 0.2f; + press -= progress / 5.0f; - if( progress > 1.0f ) - { - progress = 1.0f - ( progress - 1.0f ); - } - float press = 0.2f; - press -= progress / 5.0f; + final IIcon ic = ExtraBlockTextures.BlockInscriberInside.getIcon(); + tess.startDrawingQuads(); - final IIcon ic = ExtraBlockTextures.BlockInscriberInside.getIcon(); - tess.startDrawingQuads(); + float middle = 0.5f; + middle += 0.02f; + final float TwoPx = 2.0f / 16.0f; + tess.addVertexWithUV( + TwoPx, middle + press, TwoPx, ic.getInterpolatedU(2), ic.getInterpolatedV(2) + ); + tess.addVertexWithUV( + 1.0 - TwoPx, + middle + press, + TwoPx, + ic.getInterpolatedU(14), + ic.getInterpolatedV(2) + ); + tess.addVertexWithUV( + 1.0 - TwoPx, + middle + press, + 1.0 - TwoPx, + ic.getInterpolatedU(14), + ic.getInterpolatedV(13) + ); + tess.addVertexWithUV( + TwoPx, + middle + press, + 1.0 - TwoPx, + ic.getInterpolatedU(2), + ic.getInterpolatedV(13) + ); - float middle = 0.5f; - middle += 0.02f; - final float TwoPx = 2.0f / 16.0f; - tess.addVertexWithUV( TwoPx, middle + press, TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + press, TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 13 ) ); - tess.addVertexWithUV( TwoPx, middle + press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 13 ) ); + 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) + ); + final float base = 0.4f; + 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( 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 ) ); - final float base = 0.4f; - 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) + ); + tess.addVertexWithUV( + TwoPx, middle - press, TwoPx, ic.getInterpolatedU(14), ic.getInterpolatedV(2) + ); + tess.addVertexWithUV( + TwoPx, + middle - press, + 1.0 - TwoPx, + ic.getInterpolatedU(14), + ic.getInterpolatedV(13) + ); + tess.addVertexWithUV( + 1.0 - TwoPx, + middle - press, + 1.0 - TwoPx, + ic.getInterpolatedU(2), + ic.getInterpolatedV(13) + ); - middle -= 2.0f * 0.02f; - tess.addVertexWithUV( 1.0 - TwoPx, middle - press, TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( TwoPx, middle - press, TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 2 ) ); - tess.addVertexWithUV( TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 14 ), ic.getInterpolatedV( 13 ) ); - tess.addVertexWithUV( 1.0 - TwoPx, middle - press, 1.0 - TwoPx, ic.getInterpolatedU( 2 ), ic.getInterpolatedV( 13 ) ); + 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( 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.draw(); - tess.draw(); + GL11.glPopMatrix(); - GL11.glPopMatrix(); + // render items. + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - // render items. - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + int items = 0; + if (tile.getStackInSlot(0) != null) { + items++; + } + if (tile.getStackInSlot(1) != null) { + items++; + } + if (tile.getStackInSlot(2) != null) { + items++; + } - int items = 0; - if( tile.getStackInSlot( 0 ) != null ) - { - items++; - } - if( tile.getStackInSlot( 1 ) != null ) - { - items++; - } - if( tile.getStackInSlot( 2 ) != null ) - { - items++; - } + if (relativeProgress > 1.0f || items == 0) { + ItemStack is = tile.getStackInSlot(3); - if( relativeProgress > 1.0f || items == 0 ) - { - ItemStack is = tile.getStackInSlot( 3 ); + if (is == null) { + final IInscriberRecipe ir = tile.getTask(); + if (ir != null) { + is = ir.getOutput().copy(); + } + } - if( is == null ) - { - final IInscriberRecipe ir = tile.getTask(); - if( ir != null ) - { - is = ir.getOutput().copy(); - } - } + this.renderItem(is, 0.0f, block, tile, tess, x, y, z, f, renderer); + } else { + this.renderItem( + tile.getStackInSlot(0), press, block, tile, tess, x, y, z, f, renderer + ); + this.renderItem( + tile.getStackInSlot(1), -press, block, tile, tess, x, y, z, f, renderer + ); + this.renderItem( + tile.getStackInSlot(2), 0.0f, block, tile, tess, x, y, z, f, renderer + ); + } - this.renderItem( is, 0.0f, block, tile, tess, x, y, z, f, renderer ); - } - else - { - this.renderItem( tile.getStackInSlot( 0 ), press, block, tile, tess, x, y, z, f, renderer ); - this.renderItem( tile.getStackInSlot( 1 ), -press, block, tile, tess, x, y, z, f, renderer ); - this.renderItem( tile.getStackInSlot( 2 ), 0.0f, block, tile, tess, x, y, z, f, renderer ); - } + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glCullFace(GL11.GL_BACK); + } - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glCullFace( GL11.GL_BACK ); - } + private void renderItem( + ItemStack sis, + final float o, + final AEBaseBlock block, + final AEBaseTile tile, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer + ) { + if (sis != null) { + sis = sis.copy(); - private void renderItem( ItemStack sis, final float o, final AEBaseBlock block, final AEBaseTile tile, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( sis != null ) - { - sis = sis.copy(); + GL11.glPushMatrix(); + // fix to inscriber + this.applyTESRRotation(x, y, z, tile.getForward(), tile.getUp()); - GL11.glPushMatrix(); - // fix to inscriber - this.applyTESRRotation( x, y, z, tile.getForward(), tile.getUp() ); + try { + // move to center + GL11.glTranslatef(0.5f, 0.5f + o, 0.5f); - try - { - // move to center - GL11.glTranslatef( 0.5f, 0.5f + o, 0.5f ); + // set scale + GL11.glScalef(ITEM_RENDER_SCALE, ITEM_RENDER_SCALE, ITEM_RENDER_SCALE); - // set scale - GL11.glScalef( ITEM_RENDER_SCALE, ITEM_RENDER_SCALE, ITEM_RENDER_SCALE ); + final Block blk = Block.getBlockFromItem(sis.getItem()); - final Block blk = Block.getBlockFromItem( sis.getItem() ); + // is a block + if (sis.getItemSpriteNumber() == 0 && block != null + && RenderBlocks.renderItemIn3d(blk.getRenderType())) { + // rotate block in angle to make it more plastic + GL11.glRotatef(22.5f, 1f, 0f, 0f); + GL11.glRotatef(-33.75f, 0f, 1f, 0f); + } else { + // rotate item to match the inventory icon orientation. + GL11.glRotatef(-90.0f, 1f, 0f, 0f); + GL11.glRotatef(180.0f, 0f, 1f, 0f); + } - // is a block - if( sis.getItemSpriteNumber() == 0 && block != null && RenderBlocks.renderItemIn3d( blk.getRenderType() ) ) - { - // rotate block in angle to make it more plastic - GL11.glRotatef( 22.5f, 1f, 0f, 0f ); - GL11.glRotatef( -33.75f, 0f, 1f, 0f ); - } - else - { - // rotate item to match the inventory icon orientation. - GL11.glRotatef( -90.0f, 1f, 0f, 0f ); - GL11.glRotatef( 180.0f, 0f, 1f, 0f ); - } + // << 20 | light << 4; + final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( + tile.xCoord, tile.yCoord, tile.zCoord, 0 + ); + final int var11 = br % 65536; + final int var12 = br / 65536; - // << 20 | light << 4; - final int br = tile.getWorldObj().getLightBrightnessForSkyBlocks( tile.xCoord, tile.yCoord, tile.zCoord, 0 ); - final int var11 = br % 65536; - final int var12 = br / 65536; + OpenGlHelper.setLightmapTextureCoords( + OpenGlHelper.lightmapTexUnit, var11, var12 + ); - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11, var12 ); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); + this.doRenderItem(sis, tile); + } catch (final Exception err) { + AELog.debug(err); + } - this.doRenderItem( sis, tile ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } - - GL11.glPopMatrix(); - } - } + 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 ecd8527f..114280dc 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockInterface.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockInterface; import appeng.client.render.BaseBlockRender; import appeng.client.render.BlockRenderInfo; @@ -29,31 +28,39 @@ import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; +public class RenderBlockInterface extends BaseBlockRender { + public RenderBlockInterface() { + super(false, 20); + } -public class RenderBlockInterface extends BaseBlockRender -{ + @Override + public boolean renderInWorld( + final BlockInterface block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TileInterface ti = block.getTileEntity(world, x, y, z); + final BlockRenderInfo info = block.getRendererInstance(); - public RenderBlockInterface() - { - super( false, 20 ); - } + if (ti != null && ti.getForward() != ForgeDirection.UNKNOWN) { + final IIcon side = ExtraBlockTextures.BlockInterfaceAlternateArrow.getIcon(); + info.setTemporaryRenderIcons( + ExtraBlockTextures.BlockInterfaceAlternate.getIcon(), + block.getIcon(0, 0), + side, + side, + side, + side + ); + } - @Override - public boolean renderInWorld( final BlockInterface block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileInterface ti = block.getTileEntity( world, x, y, z ); - final BlockRenderInfo info = block.getRendererInstance(); + final boolean fz = super.renderInWorld(block, world, x, y, z, renderer); - if( ti != null && ti.getForward() != ForgeDirection.UNKNOWN ) - { - final IIcon side = ExtraBlockTextures.BlockInterfaceAlternateArrow.getIcon(); - info.setTemporaryRenderIcons( ExtraBlockTextures.BlockInterfaceAlternate.getIcon(), block.getIcon( 0, 0 ), side, side, side, side ); - } + info.setTemporaryRenderIcon(null); - final boolean fz = super.renderInWorld( block, world, x, y, z, renderer ); - - info.setTemporaryRenderIcon( null ); - - return fz; - } + return fz; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java b/src/main/java/appeng/client/render/blocks/RenderBlockPaint.java index 3d375525..0e7ed365 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 appeng.block.misc.BlockPaint; import appeng.client.render.BaseBlockRender; @@ -32,154 +33,293 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RenderBlockPaint extends BaseBlockRender { + public RenderBlockPaint() { + super(false, 0); + } + @Override + public void renderInventory( + final BlockPaint block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) {} -public class RenderBlockPaint extends BaseBlockRender -{ + @Override + public boolean renderInWorld( + final BlockPaint imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TilePaint tp = imb.getTileEntity(world, x, y, z); + boolean out = false; - public RenderBlockPaint() - { - super( false, 0 ); - } + if (tp != null) { + // super.renderInWorld( imb, world, x, y, z, renderer ); - @Override - public void renderInventory( final BlockPaint block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { + final IIcon[] icoSet = { imb.getIcon(0, 0), + ExtraBlockTextures.BlockPaint2.getIcon(), + ExtraBlockTextures.BlockPaint3.getIcon() }; - } + final Tessellator tess = Tessellator.instance; - @Override - public boolean renderInWorld( final BlockPaint imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TilePaint tp = imb.getTileEntity( world, x, y, z ); - boolean out = false; + final int brightness = imb.getMixedBrightnessForBlock(world, x, y, z); - if( tp != null ) - { - // super.renderInWorld( imb, world, x, y, z, renderer ); + final EnumSet validSides + = EnumSet.noneOf(ForgeDirection.class); - final IIcon[] icoSet = { imb.getIcon( 0, 0 ), ExtraBlockTextures.BlockPaint2.getIcon(), ExtraBlockTextures.BlockPaint3.getIcon() }; + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (tp.isSideValid(side)) { + validSides.add(side); + } + } - final Tessellator tess = Tessellator.instance; + double offsetConstant = 0.001; + final int lumen = 14 << 20 | 14 << 4; + for (final Splotch s : tp.getDots()) { + if (!validSides.contains(s.getSide())) { + continue; + } - final int brightness = imb.getMixedBrightnessForBlock( world, x, y, z ); + if (s.isLumen()) { + tess.setColorOpaque_I(s.getColor().whiteVariant); + tess.setBrightness(lumen); + } else { + tess.setColorOpaque_I(s.getColor().mediumVariant); + tess.setBrightness(brightness); + } - final EnumSet validSides = EnumSet.noneOf( ForgeDirection.class ); + double offset = offsetConstant; + offsetConstant += 0.001; - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( tp.isSideValid( side ) ) - { - validSides.add( side ); - } - } + final double buffer = 0.1; - double offsetConstant = 0.001; - final int lumen = 14 << 20 | 14 << 4; - for( final Splotch s : tp.getDots() ) - { - if( !validSides.contains( s.getSide() ) ) - { - continue; - } + double pos_x = s.x(); + double pos_y = s.y(); - if( s.isLumen() ) - { - tess.setColorOpaque_I( s.getColor().whiteVariant ); - tess.setBrightness( lumen ); - } - else - { - tess.setColorOpaque_I( s.getColor().mediumVariant ); - tess.setBrightness( brightness ); - } + pos_x = Math.max(buffer, Math.min(1.0 - buffer, pos_x)); + pos_y = Math.max(buffer, Math.min(1.0 - buffer, pos_y)); - double offset = offsetConstant; - offsetConstant += 0.001; + if (s.getSide() == ForgeDirection.SOUTH + || s.getSide() == ForgeDirection.NORTH) { + pos_x += x; + pos_y += y; + } - final double buffer = 0.1; + else if (s.getSide() == ForgeDirection.UP || s.getSide() == ForgeDirection.DOWN) { + pos_x += x; + pos_y += z; + } - double pos_x = s.x(); - double pos_y = s.y(); + else { + pos_x += y; + pos_y += z; + } - pos_x = Math.max( buffer, Math.min( 1.0 - buffer, pos_x ) ); - pos_y = Math.max( buffer, Math.min( 1.0 - buffer, pos_y ) ); + final IIcon ico = icoSet[s.getSeed() % icoSet.length]; - if( s.getSide() == ForgeDirection.SOUTH || s.getSide() == ForgeDirection.NORTH ) - { - pos_x += x; - pos_y += y; - } + switch (s.getSide()) { + case UP: + offset = 1.0 - offset; + tess.addVertexWithUV( + pos_x - buffer, + y + offset, + pos_y - buffer, + ico.getMinU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x + buffer, + y + offset, + pos_y - buffer, + ico.getMaxU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x + buffer, + y + offset, + pos_y + buffer, + ico.getMaxU(), + ico.getMaxV() + ); + tess.addVertexWithUV( + pos_x - buffer, + y + offset, + pos_y + buffer, + ico.getMinU(), + ico.getMaxV() + ); + break; - else if( s.getSide() == ForgeDirection.UP || s.getSide() == ForgeDirection.DOWN ) - { - pos_x += x; - pos_y += z; - } + case DOWN: + tess.addVertexWithUV( + pos_x + buffer, + y + offset, + pos_y - buffer, + ico.getMinU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x - buffer, + y + offset, + pos_y - buffer, + ico.getMaxU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x - buffer, + y + offset, + pos_y + buffer, + ico.getMaxU(), + ico.getMaxV() + ); + tess.addVertexWithUV( + pos_x + buffer, + y + offset, + pos_y + buffer, + ico.getMinU(), + ico.getMaxV() + ); + break; - else - { - pos_x += y; - pos_y += z; - } + case EAST: + offset = 1.0 - offset; + tess.addVertexWithUV( + x + offset, + pos_x + buffer, + pos_y - buffer, + ico.getMinU(), + ico.getMinV() + ); + tess.addVertexWithUV( + x + offset, + pos_x - buffer, + pos_y - buffer, + ico.getMaxU(), + ico.getMinV() + ); + tess.addVertexWithUV( + x + offset, + pos_x - buffer, + pos_y + buffer, + ico.getMaxU(), + ico.getMaxV() + ); + tess.addVertexWithUV( + x + offset, + pos_x + buffer, + pos_y + buffer, + ico.getMinU(), + ico.getMaxV() + ); + break; - final IIcon ico = icoSet[s.getSeed() % icoSet.length]; + case WEST: + tess.addVertexWithUV( + x + offset, + pos_x - buffer, + pos_y - buffer, + ico.getMinU(), + ico.getMinV() + ); + tess.addVertexWithUV( + x + offset, + pos_x + buffer, + pos_y - buffer, + ico.getMaxU(), + ico.getMinV() + ); + tess.addVertexWithUV( + x + offset, + pos_x + buffer, + pos_y + buffer, + ico.getMaxU(), + ico.getMaxV() + ); + tess.addVertexWithUV( + x + offset, + pos_x - buffer, + pos_y + buffer, + ico.getMinU(), + ico.getMaxV() + ); + break; - switch( s.getSide() ) - { - case UP: - offset = 1.0 - offset; - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; + case SOUTH: + offset = 1.0 - offset; + tess.addVertexWithUV( + pos_x + buffer, + pos_y - buffer, + z + offset, + ico.getMinU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x - buffer, + pos_y - buffer, + z + offset, + ico.getMaxU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x - buffer, + pos_y + buffer, + z + offset, + ico.getMaxU(), + ico.getMaxV() + ); + tess.addVertexWithUV( + pos_x + buffer, + pos_y + buffer, + z + offset, + ico.getMinU(), + ico.getMaxV() + ); + break; - case DOWN: - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, y + offset, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x + buffer, y + offset, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; + case NORTH: + tess.addVertexWithUV( + pos_x - buffer, + pos_y - buffer, + z + offset, + ico.getMinU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x + buffer, + pos_y - buffer, + z + offset, + ico.getMaxU(), + ico.getMinV() + ); + tess.addVertexWithUV( + pos_x + buffer, + pos_y + buffer, + z + offset, + ico.getMaxU(), + ico.getMaxV() + ); + tess.addVertexWithUV( + pos_x - buffer, + pos_y + buffer, + z + offset, + ico.getMinU(), + ico.getMaxV() + ); + break; - case EAST: - offset = 1.0 - offset; - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; + default: + } + } - case WEST: - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y - buffer, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y - buffer, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( x + offset, pos_x + buffer, pos_y + buffer, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( x + offset, pos_x - buffer, pos_y + buffer, ico.getMinU(), ico.getMaxV() ); - break; + out = true; + } - case SOUTH: - offset = 1.0 - offset; - tess.addVertexWithUV( pos_x + buffer, pos_y - buffer, z + offset, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, pos_y - buffer, z + offset, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x - buffer, pos_y + buffer, z + offset, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x + buffer, pos_y + buffer, z + offset, ico.getMinU(), ico.getMaxV() ); - break; - - case NORTH: - tess.addVertexWithUV( pos_x - buffer, pos_y - buffer, z + offset, ico.getMinU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, pos_y - buffer, z + offset, ico.getMaxU(), ico.getMinV() ); - tess.addVertexWithUV( pos_x + buffer, pos_y + buffer, z + offset, ico.getMaxU(), ico.getMaxV() ); - tess.addVertexWithUV( pos_x - buffer, pos_y + buffer, z + offset, ico.getMinU(), ico.getMaxV() ); - break; - - default: - } - } - - out = true; - } - - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java b/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java index 9d830eb9..34b8f426 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockQuartzAccelerator.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockQuartzGrowthAccelerator; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; @@ -28,37 +27,42 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.IBlockAccess; +public class RenderBlockQuartzAccelerator + extends BaseBlockRender { + public RenderBlockQuartzAccelerator() { + super(false, 20); + } -public class RenderBlockQuartzAccelerator extends BaseBlockRender -{ + @Override + public boolean renderInWorld( + final BlockQuartzGrowthAccelerator blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TileEntity te = world.getTileEntity(x, y, z); - public RenderBlockQuartzAccelerator() - { - super( false, 20 ); - } + if (te instanceof TileQuartzGrowthAccelerator) { + final TileQuartzGrowthAccelerator tileCGA = (TileQuartzGrowthAccelerator) te; - @Override - public boolean renderInWorld( final BlockQuartzGrowthAccelerator blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileEntity te = world.getTileEntity( x, y, z ); + if (tileCGA.isPowered()) { + final IIcon top_Bottom + = ExtraBlockTextures.BlockQuartzGrowthAcceleratorOn.getIcon(); + final IIcon side + = ExtraBlockTextures.BlockQuartzGrowthAcceleratorSideOn.getIcon(); - if( te instanceof TileQuartzGrowthAccelerator ) - { - final TileQuartzGrowthAccelerator tileCGA = (TileQuartzGrowthAccelerator) te; + blk.getRendererInstance().setTemporaryRenderIcons( + top_Bottom, top_Bottom, side, side, side, side + ); + } + } - if( tileCGA.isPowered() ) - { - final IIcon top_Bottom = ExtraBlockTextures.BlockQuartzGrowthAcceleratorOn.getIcon(); - final IIcon side = ExtraBlockTextures.BlockQuartzGrowthAcceleratorSideOn.getIcon(); + final boolean out = super.renderInWorld(blk, world, x, y, z, renderer); - blk.getRendererInstance().setTemporaryRenderIcons( top_Bottom, top_Bottom, side, side, side, side ); - } - } + blk.getRendererInstance().setTemporaryRenderIcon(null); - final boolean out = super.renderInWorld( blk, world, x, y, z, renderer ); - - blk.getRendererInstance().setTemporaryRenderIcon( null ); - - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java b/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java index c2917dbd..d863af49 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockSkyChest.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.storage.BlockSkyChest; import appeng.client.render.BaseBlockRender; import appeng.tile.storage.TileSkyChest; @@ -33,109 +32,121 @@ import net.minecraftforge.client.IItemRenderer.ItemRenderType; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; +public class RenderBlockSkyChest extends BaseBlockRender { + private static final ResourceLocation SKY_STONE_CHEST + = new ResourceLocation("appliedenergistics2", "textures/models/skychest.png"); + private static final ResourceLocation SKY_BLOCK_CHEST = new ResourceLocation( + "appliedenergistics2", "textures/models/skyblockchest.png" + ); + private static final ResourceLocation[] METADATA_TO_TEXTURE + = { SKY_STONE_CHEST, SKY_BLOCK_CHEST }; -public class RenderBlockSkyChest extends BaseBlockRender -{ + private final ModelChest model = new ModelChest(); - private static final ResourceLocation SKY_STONE_CHEST = new ResourceLocation( "appliedenergistics2", "textures/models/skychest.png" ); - private static final ResourceLocation SKY_BLOCK_CHEST = new ResourceLocation( "appliedenergistics2", "textures/models/skyblockchest.png" ); - private static final ResourceLocation[] METADATA_TO_TEXTURE = { - SKY_STONE_CHEST, - SKY_BLOCK_CHEST - }; + public RenderBlockSkyChest() { + super(true, 80); + } - private final ModelChest model = new ModelChest(); + @Override + public void renderInventory( + final BlockSkyChest blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - public RenderBlockSkyChest() - { - super( true, 80 ); - } + final int metaData = is.getItemDamage(); + final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; - @Override - public void renderInventory( final BlockSkyChest blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + Minecraft.getMinecraft().getTextureManager().bindTexture(loc); - final int metaData = is.getItemDamage(); - final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; + GL11.glScalef(1.0F, -1F, -1F); + GL11.glTranslatef(-0.0F, -1.0F, -1.0F); - Minecraft.getMinecraft().getTextureManager().bindTexture( loc ); + this.model.chestLid.offsetY = -(0.9f / 16.0f); + final float lidAngle = 0.0f; + this.model.chestLid.rotateAngleX = -((lidAngle * 3.141593F) / 2.0F); + this.model.renderAll(); - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glTranslatef( -0.0F, -1.0F, -1.0F ); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } - this.model.chestLid.offsetY = -( 0.9f / 16.0f ); - final float lidAngle = 0.0f; - this.model.chestLid.rotateAngleX = -( ( lidAngle * 3.141593F ) / 2.0F ); - this.model.renderAll(); + @Override + public boolean renderInWorld( + final BlockSkyChest blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + return true; + } - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } + @Override + public void renderTile( + final BlockSkyChest block, + final TileSkyChest skyChest, + final Tessellator tess, + final double x, + final double y, + final double z, + final float partialTick, + final RenderBlocks renderer + ) { + if (skyChest == null || !skyChest.hasWorldObj()) { + return; + } - @Override - public boolean renderInWorld( final BlockSkyChest blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - @Override - public void renderTile( final BlockSkyChest block, final TileSkyChest skyChest, final Tessellator tess, final double x, final double y, final double z, final float partialTick, final RenderBlocks renderer ) - { - if( skyChest == null || !skyChest.hasWorldObj() ) - { - return; - } + final int metaData = skyChest.getWorldObj().getBlockMetadata( + skyChest.xCoord, skyChest.yCoord, skyChest.zCoord + ); + final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + Minecraft.getMinecraft().getTextureManager().bindTexture(loc); - final int metaData = skyChest.getWorldObj().getBlockMetadata( skyChest.xCoord, skyChest.yCoord, skyChest.zCoord ); - final ResourceLocation loc = METADATA_TO_TEXTURE[metaData]; + this.applyTESRRotation(x, y, z, skyChest.getForward(), skyChest.getUp()); - Minecraft.getMinecraft().getTextureManager().bindTexture( loc ); + GL11.glScalef(1.0F, -1F, -1F); + GL11.glTranslatef(-0.0F, -1.0F, -1.0F); - this.applyTESRRotation( x, y, z, skyChest.getForward(), skyChest.getUp() ); + final long now = System.currentTimeMillis(); + final long distance = now - skyChest.getLastEvent(); - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glTranslatef( -0.0F, -1.0F, -1.0F ); + if (skyChest.getPlayerOpen() > 0) { + skyChest.setLidAngle(skyChest.getLidAngle() + distance * 0.0001f); + } else { + skyChest.setLidAngle(skyChest.getLidAngle() - distance * 0.0001f); + } - final long now = System.currentTimeMillis(); - final long distance = now - skyChest.getLastEvent(); + if (skyChest.getLidAngle() > 0.5f) { + skyChest.setLidAngle(0.5f); + } - if( skyChest.getPlayerOpen() > 0 ) - { - skyChest.setLidAngle( skyChest.getLidAngle() + distance * 0.0001f ); - } - else - { - skyChest.setLidAngle( skyChest.getLidAngle() - distance * 0.0001f ); - } + if (skyChest.getLidAngle() < 0.0f) { + skyChest.setLidAngle(0.0f); + } - if( skyChest.getLidAngle() > 0.5f ) - { - skyChest.setLidAngle( 0.5f ); - } + float lidAngle = skyChest.getLidAngle(); + lidAngle = 1.0F - lidAngle; + lidAngle = 1.0F - lidAngle * lidAngle * lidAngle; - if( skyChest.getLidAngle() < 0.0f ) - { - skyChest.setLidAngle( 0.0f ); - } + this.model.chestLid.offsetY = -(1.01f / 16.0f); + this.model.chestLid.rotateAngleX = -((lidAngle * 3.141593F) / 2.0F); - float lidAngle = skyChest.getLidAngle(); - lidAngle = 1.0F - lidAngle; - lidAngle = 1.0F - lidAngle * lidAngle * lidAngle; + // The vanilla chests wants culling reversed... + GL11.glCullFace(GL11.GL_FRONT); + this.model.renderAll(); + GL11.glCullFace(GL11.GL_BACK); - this.model.chestLid.offsetY = -( 1.01f / 16.0f ); - this.model.chestLid.rotateAngleX = -( ( lidAngle * 3.141593F ) / 2.0F ); - - // The vanilla chests wants culling reversed... - GL11.glCullFace( GL11.GL_FRONT ); - this.model.renderAll(); - GL11.glCullFace( GL11.GL_BACK ); - - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + 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 e438f530..6ff2a0d0 100644 --- a/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java +++ b/src/main/java/appeng/client/render/blocks/RenderBlockSkyCompass.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockSkyCompass; import appeng.client.render.BaseBlockRender; import appeng.client.render.model.ModelCompass; @@ -38,208 +37,200 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; +public class RenderBlockSkyCompass + extends BaseBlockRender { + private static final ResourceLocation TEXTURE_SKY_COMPASS + = new ResourceLocation("appliedenergistics2", "textures/models/compass.png"); -public class RenderBlockSkyCompass extends BaseBlockRender -{ - private static final ResourceLocation TEXTURE_SKY_COMPASS = new ResourceLocation( "appliedenergistics2", "textures/models/compass.png" ); + private final ModelCompass model = new ModelCompass(); - private final ModelCompass model = new ModelCompass(); + public RenderBlockSkyCompass() { + super(true, 80); + } - public RenderBlockSkyCompass() - { - super( true, 80 ); - } + @Override + public void renderInventory( + final BlockSkyCompass blk, + final ItemStack is, + final RenderBlocks renderer, + ItemRenderType type, + final Object[] obj + ) { + if (type == ItemRenderType.INVENTORY) { + boolean isGood = false; + final IInventory inv = Minecraft.getMinecraft().thePlayer.inventory; - @Override - public void renderInventory( final BlockSkyCompass blk, final ItemStack is, final RenderBlocks renderer, ItemRenderType type, final Object[] obj ) - { - if( type == ItemRenderType.INVENTORY ) - { - boolean isGood = false; - final IInventory inv = Minecraft.getMinecraft().thePlayer.inventory; + for (int x = 0; x < inv.getSizeInventory(); x++) { + if (inv.getStackInSlot(x) == is) { + isGood = true; + } + } - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - if( inv.getStackInSlot( x ) == is ) - { - isGood = true; - } - } + if (!isGood) { + type = ItemRenderType.FIRST_PERSON_MAP; + } + } - if( !isGood ) - { - type = ItemRenderType.FIRST_PERSON_MAP; - } - } + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + Minecraft.getMinecraft().getTextureManager().bindTexture(TEXTURE_SKY_COMPASS); - Minecraft.getMinecraft().getTextureManager().bindTexture( TEXTURE_SKY_COMPASS ); + if (type == ItemRenderType.ENTITY) { + GL11.glRotatef(-90.0f, 0.0f, 0.0f, 1.0f); + GL11.glScalef(1.0F, -1F, -1F); + GL11.glScalef(2.5f, 2.5f, 2.5f); + GL11.glTranslatef(-0.25F, -1.65F, -0.19F); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glRotatef(15.3f, 0.0f, 0.0f, 1.0f); + } - if( type == ItemRenderType.ENTITY ) - { - GL11.glRotatef( -90.0f, 0.0f, 0.0f, 1.0f ); - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glScalef( 2.5f, 2.5f, 2.5f ); - GL11.glTranslatef( -0.25F, -1.65F, -0.19F ); - } - else - { - 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); - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glScalef( 2.5f, 2.5f, 2.5f ); + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(0.3F, -1.65F, -0.19F); + } else { + GL11.glTranslatef(0.2F, -1.65F, -0.19F); + } + } - 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(); - long now = System.currentTimeMillis(); + 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_FIRST_PERSON || type == ItemRenderType.INVENTORY || type == ItemRenderType.EQUIPPED ) - { - EntityPlayer p = Minecraft.getMinecraft().thePlayer; - float rYaw = p.rotationYaw; + if (type == ItemRenderType.EQUIPPED) { + p = (EntityPlayer) obj[1]; + rYaw = p.renderYawOffset; + } - if( type == ItemRenderType.EQUIPPED ) - { - p = (EntityPlayer) obj[1]; - rYaw = p.renderYawOffset; - } + final int x = (int) p.posX; + final int y = (int) p.posY; + final int z = (int) p.posZ; + final CompassResult cr + = CompassManager.INSTANCE.getCompassDirection(0, x, y, z); - final int x = (int) p.posX; - final int y = (int) p.posY; - final int z = (int) p.posZ; - final CompassResult cr = CompassManager.INSTANCE.getCompassDirection( 0, x, y, z ); + 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 + ); + } + } - 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.isValidResult()) { + if (cr.isSpin()) { + now %= 100000; + this.model.renderAll((now / 50000.0f) * (float) Math.PI * 500.0f); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + final float offRads = rYaw / 180.0f * (float) Math.PI; + final float adjustment = (float) Math.PI * 0.74f; - if( cr.isValidResult() ) - { - if( cr.isSpin() ) - { - now %= 100000; - this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); - } - else - { - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - final float offRads = rYaw / 180.0f * (float) Math.PI; - final float adjustment = (float) Math.PI * 0.74f; + this.model.renderAll((float + ) this.flipidiy(cr.getRad() + offRads + adjustment)); + } else { + final float offRads = rYaw / 180.0f * (float) Math.PI; + final float adjustment = (float) Math.PI * -0.74f; - this.model.renderAll( (float) this.flipidiy( cr.getRad() + offRads + adjustment ) ); - } - else - { - final float offRads = rYaw / 180.0f * (float) Math.PI; - final float adjustment = (float) Math.PI * -0.74f; + this.model.renderAll((float + ) this.flipidiy(cr.getRad() + offRads + adjustment)); + } + } + } else { + now %= 1000000; + 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( (float) this.flipidiy( cr.getRad() + offRads + adjustment ) ); - } - } - } - else - { - now %= 1000000; - 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 ); - } + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } + @Override + public boolean renderInWorld( + final BlockSkyCompass blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + return true; + } - @Override - public boolean renderInWorld( final BlockSkyCompass blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } + @Override + public void renderTile( + final BlockSkyCompass block, + final TileSkyCompass skyCompass, + final Tessellator tess, + final double x, + final double y, + final double z, + final float partialTick, + final RenderBlocks renderer + ) { + if (skyCompass == null) { + return; + } - @Override - public void renderTile( final BlockSkyCompass block, final TileSkyCompass skyCompass, final Tessellator tess, final double x, final double y, final double z, final float partialTick, final RenderBlocks renderer ) - { - if( skyCompass == null ) - { - return; - } + if (!skyCompass.hasWorldObj()) { + return; + } - if( !skyCompass.hasWorldObj() ) - { - return; - } + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glCullFace(GL11.GL_FRONT); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glCullFace( GL11.GL_FRONT ); + Minecraft.getMinecraft().getTextureManager().bindTexture(TEXTURE_SKY_COMPASS); - Minecraft.getMinecraft().getTextureManager().bindTexture( TEXTURE_SKY_COMPASS ); + this.applyTESRRotation(x, y, z, skyCompass.getUp(), skyCompass.getForward()); - this.applyTESRRotation( x, y, z, skyCompass.getUp(), skyCompass.getForward() ); + GL11.glScalef(1.0F, -1F, -1F); + GL11.glTranslatef(0.5F, -1.5F, -0.5F); - GL11.glScalef( 1.0F, -1F, -1F ); - GL11.glTranslatef( 0.5F, -1.5F, -0.5F ); + long now = System.currentTimeMillis(); + CompassResult cr = null; - long now = System.currentTimeMillis(); - CompassResult cr = null; + if (skyCompass.getForward() == ForgeDirection.UP + || skyCompass.getForward() == ForgeDirection.DOWN) { + cr = CompassManager.INSTANCE.getCompassDirection( + 0, skyCompass.xCoord, skyCompass.yCoord, skyCompass.zCoord + ); + } else { + cr = new CompassResult(false, true, 0); + } - if( skyCompass.getForward() == ForgeDirection.UP || skyCompass.getForward() == ForgeDirection.DOWN ) - { - cr = CompassManager.INSTANCE.getCompassDirection( 0, skyCompass.xCoord, skyCompass.yCoord, skyCompass.zCoord ); - } - else - { - cr = new CompassResult( false, true, 0 ); - } + if (cr.isValidResult()) { + if (cr.isSpin()) { + now %= 100000; + this.model.renderAll((now / 50000.0f) * (float) Math.PI * 500.0f); + } else { + this.model.renderAll((float + ) (skyCompass.getForward() == ForgeDirection.DOWN + ? this.flipidiy(cr.getRad()) + : cr.getRad())); + } + } else { + now %= 1000000; + this.model.renderAll((now / 500000.0f) * (float) Math.PI * 500.0f); + } - if( cr.isValidResult() ) - { - if( cr.isSpin() ) - { - now %= 100000; - this.model.renderAll( ( now / 50000.0f ) * (float) Math.PI * 500.0f ); - } - else - { - this.model.renderAll( (float) ( skyCompass.getForward() == ForgeDirection.DOWN ? this.flipidiy( cr.getRad() ) : cr.getRad() ) ); - } - } - else - { - now %= 1000000; - this.model.renderAll( ( now / 500000.0f ) * (float) Math.PI * 500.0f ); - } + GL11.glCullFace(GL11.GL_BACK); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + } - GL11.glCullFace( GL11.GL_BACK ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - } - - private double flipidiy( final double rad ) - { - final double x = Math.cos( rad ); - final double y = Math.sin( rad ); - return Math.atan2( -y, x ); - } + private double flipidiy(final double rad) { + final double x = Math.cos(rad); + final double y = Math.sin(rad); + return Math.atan2(-y, x); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java b/src/main/java/appeng/client/render/blocks/RenderBlockWireless.java index de105aaf..0a3cdcf1 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 appeng.api.util.AEColor; import appeng.block.networking.BlockWireless; @@ -36,238 +37,382 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RenderBlockWireless extends BaseBlockRender { + private int centerX = 0; + private int centerY = 0; + private int centerZ = 0; + private BlockWireless blk; + private boolean hasChan = false; + private boolean hasPower = false; + public RenderBlockWireless() { + super(false, 20); + } -public class RenderBlockWireless extends BaseBlockRender -{ + @Override + public void renderInventory( + final BlockWireless blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + this.blk = blk; + this.centerX = 0; + this.centerY = 0; + this.centerZ = 0; + this.hasChan = false; + this.hasPower = false; - private int centerX = 0; - private int centerY = 0; - private int centerZ = 0; - private BlockWireless blk; - private boolean hasChan = false; - private boolean hasPower = false; + final BlockRenderInfo ri = blk.getRendererInstance(); + final Tessellator tess = Tessellator.instance; - public RenderBlockWireless() - { - super( false, 20 ); - } + renderer.renderAllFaces = true; - @Override - public void renderInventory( final BlockWireless blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - this.blk = blk; - this.centerX = 0; - this.centerY = 0; - this.centerZ = 0; - this.hasChan = false; - this.hasPower = false; + IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); + ri.setTemporaryRenderIcons( + r, + r, + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + r, + r + ); + this.renderBlockBounds( + renderer, + 5, + 5, + 0, + 11, + 11, + 1, + ForgeDirection.EAST, + ForgeDirection.UP, + ForgeDirection.SOUTH + ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - final BlockRenderInfo ri = blk.getRendererInstance(); - final Tessellator tess = Tessellator.instance; + r = CableBusTextures.PartWirelessSides.getIcon(); + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r + ); + this.renderBlockBounds( + renderer, + 5, + 5, + 1, + 11, + 11, + 2, + ForgeDirection.EAST, + ForgeDirection.UP, + ForgeDirection.SOUTH + ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - renderer.renderAllFaces = true; + tess.startDrawingQuads(); + ri.setTemporaryRenderIcon(null); + this.renderTorchAtAngle( + renderer, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH + ); + super.postRenderInWorld(renderer); + tess.draw(); - IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); - ri.setTemporaryRenderIcons( r, r, CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 0, 11, 11, 1, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r + ); - r = CableBusTextures.PartWirelessSides.getIcon(); - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 1, 11, 11, 2, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + final ForgeDirection[] sides = { ForgeDirection.EAST, + ForgeDirection.WEST, + ForgeDirection.UP, + ForgeDirection.DOWN }; - tess.startDrawingQuads(); - ri.setTemporaryRenderIcon( null ); - this.renderTorchAtAngle( renderer, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH ); - super.postRenderInWorld( renderer ); - tess.draw(); + int s = 1; - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); + for (final 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.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); + } - final ForgeDirection[] sides = { ForgeDirection.EAST, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.DOWN }; + s = 3; + for (final 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 + ); - int s = 1; + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); + } + } - for( final 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.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - } + @Override + public boolean renderInWorld( + final BlockWireless blk, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TileWireless tw = blk.getTileEntity(world, x, y, z); + this.blk = blk; - s = 3; - for( final 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 ); + if (tw != null) { + this.hasChan = (tw.getClientFlags() + & (TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG)) + == (TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG); + this.hasPower = (tw.getClientFlags() & TileWireless.POWERED_FLAG) + == TileWireless.POWERED_FLAG; - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - } - } + final BlockRenderInfo ri = blk.getRendererInstance(); - @Override - public boolean renderInWorld( final BlockWireless blk, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileWireless tw = blk.getTileEntity( world, x, y, z ); - this.blk = blk; + final ForgeDirection fdy = tw.getUp(); + final ForgeDirection fdz = tw.getForward(); + final ForgeDirection fdx = Platform.crossProduct(fdz, fdy).getOpposite(); - if( tw != null ) - { - this.hasChan = ( tw.getClientFlags() & ( TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG ) ) == ( TileWireless.POWERED_FLAG | TileWireless.CHANNEL_FLAG ); - this.hasPower = ( tw.getClientFlags() & TileWireless.POWERED_FLAG ) == TileWireless.POWERED_FLAG; + renderer.renderAllFaces = true; - final BlockRenderInfo ri = blk.getRendererInstance(); + IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); + ri.setTemporaryRenderIcons( + r, + r, + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + r, + r + ); + this.renderBlockBounds(renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz); + super.renderInWorld(blk, world, x, y, z, renderer); - final ForgeDirection fdy = tw.getUp(); - final ForgeDirection fdz = tw.getForward(); - final ForgeDirection fdx = Platform.crossProduct( fdz, fdy ).getOpposite(); + r = CableBusTextures.PartWirelessSides.getIcon(); + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r + ); + this.renderBlockBounds(renderer, 5, 5, 1, 11, 11, 2, fdx, fdy, fdz); + super.renderInWorld(blk, world, x, y, z, renderer); - renderer.renderAllFaces = true; + this.centerX = x; + this.centerY = y; + this.centerZ = z; + ri.setTemporaryRenderIcon(null); - IIcon r = CableBusTextures.PartMonitorSidesStatus.getIcon(); - ri.setTemporaryRenderIcons( r, r, CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz ); - super.renderInWorld( blk, world, x, y, z, renderer ); + this.renderTorchAtAngle(renderer, fdx, fdy, fdz); + super.postRenderInWorld(renderer); - r = CableBusTextures.PartWirelessSides.getIcon(); - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 1, 11, 11, 2, fdx, fdy, fdz ); - super.renderInWorld( blk, world, x, y, z, renderer ); + ri.setTemporaryRenderIcons( + r, + r, + ExtraBlockTextures.BlockWirelessInside.getIcon(), + ExtraBlockTextures.BlockWirelessInside.getIcon(), + r, + r + ); - this.centerX = x; - this.centerY = y; - this.centerZ = z; - ri.setTemporaryRenderIcon( null ); + final ForgeDirection[] sides = { ForgeDirection.EAST, + ForgeDirection.WEST, + ForgeDirection.UP, + ForgeDirection.DOWN }; - this.renderTorchAtAngle( renderer, fdx, fdy, fdz ); - super.postRenderInWorld( renderer ); + int s = 1; - ri.setTemporaryRenderIcons( r, r, ExtraBlockTextures.BlockWirelessInside.getIcon(), ExtraBlockTextures.BlockWirelessInside.getIcon(), r, r ); + for (final 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 + ); + super.renderInWorld(blk, world, x, y, z, renderer); + } - final ForgeDirection[] sides = { ForgeDirection.EAST, ForgeDirection.WEST, ForgeDirection.UP, ForgeDirection.DOWN }; + s = 3; + for (final 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 + ); + super.renderInWorld(blk, world, x, y, z, renderer); + } - int s = 1; + r = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); + // ri.setTemporaryRenderIcons( r, r, + // ExtraTextures.BlockChargerInside.getIcon(), + // ExtraTextures.BlockChargerInside.getIcon(), r, r ); + this.renderBlockBounds(renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz); - for( final 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 ); - super.renderInWorld( blk, world, x, y, z, renderer ); - } + if (this.hasChan) { + final int l = 14; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(AEColor.Transparent.blackVariant); + } else if (this.hasPower) { + final int l = 9; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(AEColor.Transparent.whiteVariant); + } else { + Tessellator.instance.setBrightness(0); + Tessellator.instance.setColorOpaque_I(0x000000); + } - s = 3; - for( final 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 ); - super.renderInWorld( blk, world, x, y, z, renderer ); - } + if (ForgeDirection.UP != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.UP); + } + if (ForgeDirection.DOWN != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.DOWN); + } + if (ForgeDirection.EAST != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.EAST); + } + if (ForgeDirection.WEST != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.WEST); + } + if (ForgeDirection.SOUTH != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.SOUTH); + } + if (ForgeDirection.NORTH != fdz.getOpposite()) { + super.renderFace(x, y, z, blk, r, renderer, ForgeDirection.NORTH); + } - r = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); - // ri.setTemporaryRenderIcons( r, r, ExtraTextures.BlockChargerInside.getIcon(), - // ExtraTextures.BlockChargerInside.getIcon(), r, r ); - this.renderBlockBounds( renderer, 5, 5, 0, 11, 11, 1, fdx, fdy, fdz ); + ri.setTemporaryRenderIcon(null); + renderer.renderAllFaces = false; + } - if( this.hasChan ) - { - final int l = 14; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( AEColor.Transparent.blackVariant ); - } - else if( this.hasPower ) - { - final int l = 9; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( AEColor.Transparent.whiteVariant ); - } - else - { - Tessellator.instance.setBrightness( 0 ); - Tessellator.instance.setColorOpaque_I( 0x000000 ); - } + return true; + } - if( ForgeDirection.UP != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.UP ); - } - if( ForgeDirection.DOWN != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.DOWN ); - } - if( ForgeDirection.EAST != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.EAST ); - } - if( ForgeDirection.WEST != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.WEST ); - } - if( ForgeDirection.SOUTH != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.SOUTH ); - } - if( ForgeDirection.NORTH != fdz.getOpposite() ) - { - super.renderFace( x, y, z, blk, r, renderer, ForgeDirection.NORTH ); - } + private void renderTorchAtAngle( + final RenderBlocks renderer, + final ForgeDirection x, + final ForgeDirection y, + final ForgeDirection z + ) { + final IIcon r + = (this.hasChan ? CableBusTextures.BlockWirelessOn.getIcon() + : this.blk.getIcon(0, 0)); + final IIcon sides = new OffsetIcon(r, 0.0f, -2.0f); - ri.setTemporaryRenderIcon( null ); - renderer.renderAllFaces = false; - } + 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; + } - return true; - } + Tessellator.instance.setColorOpaque_I(0xffffff); + this.renderBlockBounds(renderer, 0, 7, 1, 16, 9, 16, x, y, z); + this.renderFace( + this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, y + ); + this.renderFace( + this.centerX, + this.centerY, + this.centerZ, + this.blk, + sides, + renderer, + y.getOpposite() + ); - private void renderTorchAtAngle( final RenderBlocks renderer, final ForgeDirection x, final ForgeDirection y, final ForgeDirection z ) - { - final IIcon r = ( this.hasChan ? CableBusTextures.BlockWirelessOn.getIcon() : this.blk.getIcon( 0, 0 ) ); - final IIcon sides = new OffsetIcon( r, 0.0f, -2.0f ); + this.renderBlockBounds(renderer, 7, 0, 1, 9, 16, 16, x, y, z); + this.renderFace( + this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, x + ); + this.renderFace( + this.centerX, + this.centerY, + this.centerZ, + this.blk, + sides, + renderer, + x.getOpposite() + ); - 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; - } - - Tessellator.instance.setColorOpaque_I( 0xffffff ); - this.renderBlockBounds( renderer, 0, 7, 1, 16, 9, 16, x, y, z ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, y ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, y.getOpposite() ); - - this.renderBlockBounds( renderer, 7, 0, 1, 9, 16, 16, x, y, z ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, x ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, sides, renderer, x.getOpposite() ); - - this.renderBlockBounds( renderer, 7, 7, 1, 9, 9, 10.6, x, y, z ); - this.renderFace( this.centerX, this.centerY, this.centerZ, this.blk, r, renderer, z ); - } + this.renderBlockBounds(renderer, 7, 7, 1, 9, 9, 10.6, x, y, z); + this.renderFace( + this.centerX, this.centerY, this.centerZ, this.blk, r, renderer, z + ); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderDrive.java b/src/main/java/appeng/client/render/blocks/RenderDrive.java index 21400119..ecf71e9a 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 appeng.block.storage.BlockDrive; import appeng.client.render.BaseBlockRender; @@ -32,314 +33,622 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RenderDrive extends BaseBlockRender { + public RenderDrive() { + super(false, 0); + } + @Override + public void renderInventory( + final BlockDrive block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); + this.renderInvBlock( + EnumSet.of(ForgeDirection.SOUTH), + block, + is, + Tessellator.instance, + 0x000000, + renderer + ); -public class RenderDrive extends BaseBlockRender -{ + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } - public RenderDrive() - { - super( false, 0 ); - } + @Override + public boolean renderInWorld( + final BlockDrive imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TileDrive sp = imb.getTileEntity(world, x, y, z); + final ForgeDirection up = sp.getUp(); + final ForgeDirection forward = sp.getForward(); + final ForgeDirection west = Platform.crossProduct(forward, up); - @Override - public void renderInventory( final BlockDrive block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); - this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } + final boolean result = super.renderInWorld(imb, world, x, y, z, renderer); - @Override - public boolean renderInWorld( final BlockDrive imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileDrive sp = imb.getTileEntity( world, x, y, z ); - final ForgeDirection up = sp.getUp(); - final ForgeDirection forward = sp.getForward(); - final ForgeDirection west = Platform.crossProduct( forward, up ); + final Tessellator tess = Tessellator.instance; + final IIcon ico = ExtraBlockTextures.MEStorageCellTextures.getIcon(); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + final int b = world.getLightBrightnessForSkyBlocks( + x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 + ); - final boolean result = super.renderInWorld( imb, world, x, y, z, renderer ); + for (int yy = 0; yy < 5; yy++) { + for (int xx = 0; xx < 2; xx++) { + final int stat = sp.getCellStatus(yy * 2 + (1 - xx)); - final Tessellator tess = Tessellator.instance; - final IIcon ico = ExtraBlockTextures.MEStorageCellTextures.getIcon(); + this.selectFace( + renderer, + west, + up, + forward, + 2 + xx * 7, + 7 + xx * 7, + 1 + yy * 3, + 3 + yy * 3 + ); - final int b = world.getLightBrightnessForSkyBlocks( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 ); + int spin = 0; - for( int yy = 0; yy < 5; yy++ ) - { - for( int xx = 0; xx < 2; xx++ ) - { - final int stat = sp.getCellStatus( yy * 2 + ( 1 - xx ) ); + switch (forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 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 -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 -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; + } - this.selectFace( renderer, west, up, forward, 2 + xx * 7, 7 + xx * 7, 1 + yy * 3, 3 + yy * 3 ); + 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 spin = 0; + int m = 1; + int mx = 3; + if (stat == 0) { + m = 4; + mx = 5; + } - switch( forward.offsetX + forward.offsetY * 2 + forward.offsetZ * 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 -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 -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 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 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 ); + tess.setBrightness(b); + tess.setColorOpaque_I(0xffffff); + 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; + } - int m = 1; - int mx = 3; - if( stat == 0 ) - { - m = 4; - mx = 5; - } + 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 + ); + } - 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 ); + if (stat != 0) { + final 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); - tess.setBrightness( b ); - tess.setColorOpaque_I( 0xffffff ); - 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; - } + 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( ( 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 (sp.isPowered()) { + tess.setBrightness(15 << 20 | 15 << 4); + } else { + tess.setBrightness(0); + } - if( stat != 0 ) - { - final 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 ); + if (stat == 1) { + Tessellator.instance.setColorOpaque_I(0x00ff00); + } + if (stat == 2) { + Tessellator.instance.setColorOpaque_I(0xffaa00); + } + if (stat == 3) { + Tessellator.instance.setColorOpaque_I(0xff0000); + } - 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 ); + 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( 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; - } - } - } - } - - renderer.overrideBlockTexture = null; - return result; - } + renderer.overrideBlockTexture = null; + return result; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderMEChest.java b/src/main/java/appeng/client/render/blocks/RenderMEChest.java index 7eda2f28..b97fbb47 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 appeng.api.AEApi; import appeng.api.storage.ICellHandler; @@ -37,146 +38,181 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RenderMEChest extends BaseBlockRender { + public RenderMEChest() { + super(false, 0); + } + @Override + public void renderInventory( + final BlockChest block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + Tessellator.instance.setBrightness(0); -public class RenderMEChest extends BaseBlockRender -{ + renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); + this.renderInvBlock( + EnumSet.of(ForgeDirection.SOUTH), + block, + is, + Tessellator.instance, + 0x000000, + renderer + ); - public RenderMEChest() - { - super( false, 0 ); - } + renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); + this.renderInvBlock( + EnumSet.of(ForgeDirection.UP), + block, + is, + Tessellator.instance, + this.adjustBrightness(AEColor.Transparent.whiteVariant, 0.7), + renderer + ); - @Override - public void renderInventory( final BlockChest block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - Tessellator.instance.setBrightness( 0 ); + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } - renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); - this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); + @Override + public boolean renderInWorld( + final BlockChest imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TileChest sp = imb.getTileEntity(world, x, y, z); - renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); - this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), renderer ); + if (sp == null) { + return false; + } - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - @Override - public boolean renderInWorld( final BlockChest imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileChest sp = imb.getTileEntity( world, x, y, z ); + final ForgeDirection up = sp.getUp(); + final ForgeDirection forward = sp.getForward(); + final ForgeDirection west = Platform.crossProduct(forward, up); - if( sp == null ) - { - return false; - } + this.preRenderInWorld(imb, world, x, y, z, renderer); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + final int stat = sp.getCellStatus(0); + final boolean result = renderer.renderStandardBlock(imb, x, y, z); - final ForgeDirection up = sp.getUp(); - final ForgeDirection forward = sp.getForward(); - final ForgeDirection west = Platform.crossProduct( forward, up ); + this.selectFace(renderer, west, up, forward, 5, 16 - 5, 9, 12); - this.preRenderInWorld( imb, world, x, y, z, renderer ); + int offsetV = 8; + if (stat == 0) { + offsetV = 3; + } - final int stat = sp.getCellStatus( 0 ); - final boolean result = renderer.renderStandardBlock( imb, x, y, z ); + int b = world.getLightBrightnessForSkyBlocks( + x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 + ); + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(0xffffff); - this.selectFace( renderer, west, up, forward, 5, 16 - 5, 9, 12 ); + final int offsetU = -4; + final FlippableIcon flippableIcon = new FlippableIcon(new OffsetIcon( + ExtraBlockTextures.MEStorageCellTextures.getIcon(), offsetU, offsetV + )); - int offsetV = 8; - if( stat == 0 ) - { - offsetV = 3; - } + if (forward == ForgeDirection.EAST + && (up == ForgeDirection.NORTH || up == ForgeDirection.SOUTH)) { + flippableIcon.setFlip(true, false); + } else if (forward == ForgeDirection.NORTH && up == ForgeDirection.EAST) { + flippableIcon.setFlip(false, true); + } else if (forward == ForgeDirection.NORTH && up == ForgeDirection.WEST) { + flippableIcon.setFlip(true, false); + } else if (forward == ForgeDirection.DOWN && up == ForgeDirection.EAST) { + flippableIcon.setFlip(false, true); + } else if (forward == ForgeDirection.DOWN) { + flippableIcon.setFlip(true, false); + } - int b = world.getLightBrightnessForSkyBlocks( x + forward.offsetX, y + forward.offsetY, z + forward.offsetZ, 0 ); - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); + this.renderFace(x, y, z, imb, flippableIcon, renderer, forward); - final int offsetU = -4; - final FlippableIcon flippableIcon = new FlippableIcon( new OffsetIcon( ExtraBlockTextures.MEStorageCellTextures.getIcon(), offsetU, offsetV ) ); + if (stat != 0) { + b = 0; + if (sp.isPowered()) { + b = 15 << 20 | 15 << 4; + } - if( forward == ForgeDirection.EAST && ( up == ForgeDirection.NORTH || up == ForgeDirection.SOUTH ) ) - { - flippableIcon.setFlip( true, false ); - } - else if( forward == ForgeDirection.NORTH && up == ForgeDirection.EAST ) - { - flippableIcon.setFlip( false, true ); - } - else if( forward == ForgeDirection.NORTH && up == ForgeDirection.WEST ) - { - flippableIcon.setFlip( true, false ); - } - else if( forward == ForgeDirection.DOWN && up == ForgeDirection.EAST ) - { - flippableIcon.setFlip( false, true ); - } - else if( forward == ForgeDirection.DOWN ) - { - flippableIcon.setFlip( true, false ); - } + Tessellator.instance.setBrightness(b); + if (stat == 1) { + Tessellator.instance.setColorOpaque_I(0x00ff00); + } + if (stat == 2) { + Tessellator.instance.setColorOpaque_I(0xffaa00); + } + 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 + ); + } - this.renderFace( x, y, z, imb, flippableIcon, renderer, forward ); + b = world.getLightBrightnessForSkyBlocks( + x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 + ); + if (sp.isPowered()) { + b = 15 << 20 | 15 << 4; + } - if( stat != 0 ) - { - b = 0; - if( sp.isPowered() ) - { - b = 15 << 20 | 15 << 4; - } + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(0xffffff); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - Tessellator.instance.setBrightness( b ); - if( stat == 1 ) - { - Tessellator.instance.setColorOpaque_I( 0x00ff00 ); - } - if( stat == 2 ) - { - Tessellator.instance.setColorOpaque_I( 0xffaa00 ); - } - 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 ); - } + final ICellHandler ch + = AEApi.instance().registries().cell().getHandler(sp.getStorageType()); - b = world.getLightBrightnessForSkyBlocks( x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 ); - if( sp.isPowered() ) - { - b = 15 << 20 | 15 << 4; - } + Tessellator.instance.setColorOpaque_I(sp.getColor().whiteVariant); + IIcon ico = ch == null ? null : ch.getTopTexture_Light(); + this.renderFace( + x, + y, + z, + imb, + ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, + renderer, + up + ); - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + if (ico != null) { + Tessellator.instance.setColorOpaque_I(sp.getColor().mediumVariant); + ico = ch == null ? null : ch.getTopTexture_Medium(); + this.renderFace( + x, + y, + z, + imb, + ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, + renderer, + up + ); - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( sp.getStorageType() ); + Tessellator.instance.setColorOpaque_I(sp.getColor().blackVariant); + ico = ch == null ? null : ch.getTopTexture_Dark(); + this.renderFace( + x, + y, + z, + imb, + ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, + renderer, + up + ); + } - Tessellator.instance.setColorOpaque_I( sp.getColor().whiteVariant ); - IIcon ico = ch == null ? null : ch.getTopTexture_Light(); - this.renderFace( x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up ); + renderer.overrideBlockTexture = null; + this.postRenderInWorld(renderer); - if( ico != null ) - { - Tessellator.instance.setColorOpaque_I( sp.getColor().mediumVariant ); - ico = ch == null ? null : ch.getTopTexture_Medium(); - this.renderFace( x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up ); - - Tessellator.instance.setColorOpaque_I( sp.getColor().blackVariant ); - ico = ch == null ? null : ch.getTopTexture_Dark(); - this.renderFace( x, y, z, imb, ico == null ? ExtraBlockTextures.MEChest.getIcon() : ico, renderer, up ); - } - - renderer.overrideBlockTexture = null; - this.postRenderInWorld( renderer ); - - return result; - } + return result; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderNull.java b/src/main/java/appeng/client/render/blocks/RenderNull.java index 78bfc587..e78b6d9f 100644 --- a/src/main/java/appeng/client/render/blocks/RenderNull.java +++ b/src/main/java/appeng/client/render/blocks/RenderNull.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.AEBaseBlock; import appeng.client.render.BaseBlockRender; import appeng.tile.AEBaseTile; @@ -27,24 +26,29 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RenderNull extends BaseBlockRender { + public RenderNull() { + super(false, 20); + } -public class RenderNull extends BaseBlockRender -{ + @Override + public void renderInventory( + final AEBaseBlock block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) {} - public RenderNull() - { - super( false, 20 ); - } - - @Override - public void renderInventory( final AEBaseBlock block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - - } - - @Override - public boolean renderInWorld( final AEBaseBlock block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - return true; - } + @Override + public boolean renderInWorld( + final AEBaseBlock block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final 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 32c3c51e..b56d89af 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQNB.java +++ b/src/main/java/appeng/client/render/blocks/RenderQNB.java @@ -18,6 +18,8 @@ package appeng.client.render.blocks; +import java.util.Collection; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.definitions.IBlocks; @@ -38,168 +40,334 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collection; -import java.util.EnumSet; +public class RenderQNB extends BaseBlockRender { + private static final float DEFAULT_RENDER_MIN = 2.0f / 16.0f; + private static final float DEFAULT_RENDER_MAX = 14.0f / 16.0f; + private static final float CORNER_POWERED_RENDER_MIN = 3.9f / 16.0f; + private static final float CORNER_POWERED_RENDER_MAX = 12.1f / 16.0f; -public class RenderQNB extends BaseBlockRender -{ - private static final float DEFAULT_RENDER_MIN = 2.0f / 16.0f; - private static final float DEFAULT_RENDER_MAX = 14.0f / 16.0f; + private static final float CENTER_POWERED_RENDER_MIN = -0.01f / 16.0f; + private static final float CENTER_POWERED_RENDER_MAX = 16.01f / 16.0f; - private static final float CORNER_POWERED_RENDER_MIN = 3.9f / 16.0f; - private static final float CORNER_POWERED_RENDER_MAX = 12.1f / 16.0f; + @Override + public void renderInventory( + final BlockQuantumBase block, + final ItemStack item, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX + ); + super.renderInventory(block, item, renderer, type, obj); + } - private static final float CENTER_POWERED_RENDER_MIN = -0.01f / 16.0f; - private static final float CENTER_POWERED_RENDER_MAX = 16.01f / 16.0f; + @Override + public boolean renderInWorld( + final BlockQuantumBase block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TileQuantumBridge tqb = block.getTileEntity(world, x, y, z); - @Override - public void renderInventory( final BlockQuantumBase block, final ItemStack item, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - super.renderInventory( block, item, renderer, type, obj ); - } + if (tqb == null) { + return false; + } - @Override - public boolean renderInWorld( final BlockQuantumBase block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileQuantumBridge tqb = block.getTileEntity( world, x, y, z ); + renderer.renderAllFaces = true; - if( tqb == null ) - { - return false; - } + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IParts parts = definitions.parts(); - renderer.renderAllFaces = true; + for (final Block linkBlock : blocks.quantumLink().maybeBlock().asSet()) { + if (tqb.getBlockType() == linkBlock) { + if (tqb.isFormed()) { + final EnumSet sides = tqb.getConnections(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IParts parts = definitions.parts(); + final Item transGlassCable + = parts.cableGlass().item(AEColor.Transparent); + this.renderCableAt( + 0.11D, + world, + x, + y, + z, + block, + renderer, + transGlassCable.getIconIndex( + parts.cableGlass().stack(AEColor.Transparent, 1) + ), + 0.141D, + sides + ); - for( final Block linkBlock : blocks.quantumLink().maybeBlock().asSet() ) - { - if( tqb.getBlockType() == linkBlock ) - { - if( tqb.isFormed() ) - { - final EnumSet sides = tqb.getConnections(); + final 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.1875D, + sides + ); + } - final Item transGlassCable = parts.cableGlass().item( AEColor.Transparent ); - this.renderCableAt( 0.11D, world, x, y, z, block, renderer, transGlassCable.getIconIndex( parts.cableGlass().stack( AEColor.Transparent, 1 ) ), 0.141D, sides ); + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX + ); + renderer.renderStandardBlock(block, x, y, z); + } else { + if (!tqb.isFormed()) { + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX + ); + renderer.renderStandardBlock(block, x, y, z); + } else if (tqb.isCorner()) { + final Item transCoveredCable + = parts.cableCovered().item(AEColor.Transparent); - final 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.1875D, sides ); - } + this.renderCableAt( + 0.188D, + world, + x, + y, + z, + block, + renderer, + transCoveredCable.getIconIndex( + parts.cableCovered().stack(AEColor.Transparent, 1) + ), + 0.05D, + tqb.getConnections() + ); - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); - } - else - { - if( !tqb.isFormed() ) - { - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); - } - else if( tqb.isCorner() ) - { - final Item transCoveredCable = parts.cableCovered().item( AEColor.Transparent ); + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX + ); + renderer.renderStandardBlock(block, x, y, z); - this.renderCableAt( 0.188D, world, x, y, z, block, renderer, transCoveredCable.getIconIndex( parts.cableCovered().stack( AEColor.Transparent, 1 ) ), 0.05D, tqb.getConnections() ); + if (tqb.isPowered()) { + renderer.setRenderBounds( + CORNER_POWERED_RENDER_MIN, + CORNER_POWERED_RENDER_MIN, + CORNER_POWERED_RENDER_MIN, + CORNER_POWERED_RENDER_MAX, + CORNER_POWERED_RENDER_MAX, + CORNER_POWERED_RENDER_MAX + ); - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); + Tessellator.instance.setColorOpaque_F(1.0F, 1.0F, 1.0F); + final int bn = 15; + Tessellator.instance.setBrightness(bn << 20 | bn << 4); + for (final ForgeDirection side : + ForgeDirection.VALID_DIRECTIONS) { + this.renderFace( + x, + y, + z, + block, + ExtraBlockTextures.BlockQRingCornerLight.getIcon(), + renderer, + side + ); + } + } + } else { + renderer.setRenderBounds( + 0, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + 1, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX + ); + renderer.renderStandardBlock(block, x, y, z); - if( tqb.isPowered() ) - { - renderer.setRenderBounds( CORNER_POWERED_RENDER_MIN, CORNER_POWERED_RENDER_MIN, CORNER_POWERED_RENDER_MIN, CORNER_POWERED_RENDER_MAX, CORNER_POWERED_RENDER_MAX, CORNER_POWERED_RENDER_MAX ); + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + 0, + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MAX, + 1, + DEFAULT_RENDER_MAX + ); + renderer.renderStandardBlock(block, x, y, z); - Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - final int bn = 15; - Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - this.renderFace( x, y, z, block, ExtraBlockTextures.BlockQRingCornerLight.getIcon(), renderer, side ); - } - } - } - else - { - renderer.setRenderBounds( 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 1, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); + renderer.setRenderBounds( + DEFAULT_RENDER_MIN, + DEFAULT_RENDER_MIN, + 0, + DEFAULT_RENDER_MAX, + DEFAULT_RENDER_MAX, + 1 + ); + renderer.renderStandardBlock(block, x, y, z); - renderer.setRenderBounds( DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MIN, DEFAULT_RENDER_MAX, 1, DEFAULT_RENDER_MAX ); - renderer.renderStandardBlock( block, x, y, z ); + if (tqb.isPowered()) { + renderer.setRenderBounds( + CENTER_POWERED_RENDER_MIN, + CENTER_POWERED_RENDER_MIN, + CENTER_POWERED_RENDER_MIN, + CENTER_POWERED_RENDER_MAX, + CENTER_POWERED_RENDER_MAX, + CENTER_POWERED_RENDER_MAX + ); - renderer.setRenderBounds( DEFAULT_RENDER_MIN, DEFAULT_RENDER_MIN, 0, DEFAULT_RENDER_MAX, DEFAULT_RENDER_MAX, 1 ); - renderer.renderStandardBlock( block, x, y, z ); + Tessellator.instance.setColorOpaque_F(1.0F, 1.0F, 1.0F); + final int bn = 15; + Tessellator.instance.setBrightness(bn << 20 | bn << 4); + for (final ForgeDirection side : + ForgeDirection.VALID_DIRECTIONS) { + this.renderFace( + x, + y, + z, + block, + ExtraBlockTextures.BlockQRingEdgeLight.getIcon(), + renderer, + side + ); + } + } + } + } + } - if( tqb.isPowered() ) - { - renderer.setRenderBounds( CENTER_POWERED_RENDER_MIN, CENTER_POWERED_RENDER_MIN, CENTER_POWERED_RENDER_MIN, CENTER_POWERED_RENDER_MAX, CENTER_POWERED_RENDER_MAX, CENTER_POWERED_RENDER_MAX ); + renderer.renderAllFaces = false; + return true; + } - Tessellator.instance.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - final int bn = 15; - Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - this.renderFace( x, y, z, block, ExtraBlockTextures.BlockQRingEdgeLight.getIcon(), renderer, side ); - } - } - } - } - } + private void renderCableAt( + final double thickness, + final IBlockAccess world, + final int x, + final int y, + final int z, + final BlockQuantumBase block, + final RenderBlocks renderer, + final IIcon texture, + final double pull, + final Collection connections + ) { + block.getRendererInstance().setTemporaryRenderIcon(texture); - renderer.renderAllFaces = false; - return true; - } + 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); + } - private void renderCableAt( final double thickness, final IBlockAccess world, final int x, final int y, final int z, final BlockQuantumBase block, final RenderBlocks renderer, final IIcon texture, final double pull, final Collection connections ) - { - block.getRendererInstance().setTemporaryRenderIcon( texture ); + 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.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.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.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.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.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.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.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.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.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.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); + } - 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 ); - } + 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 f9fec893..6e3bacac 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 appeng.api.AEApi; import appeng.block.solids.BlockQuartzGlass; @@ -31,210 +32,297 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Random; +public class RenderQuartzGlass extends BaseBlockRender { + private static final byte[][][] OFFSETS = generateOffsets(); + public RenderQuartzGlass() { + super(false, 0); + } -public class RenderQuartzGlass extends BaseBlockRender -{ + private static byte[][][] generateOffsets() { + final Random r = new Random(924); + final byte[][][] offset = new byte[10][10][10]; - private static final byte[][][] OFFSETS = generateOffsets(); + for (int x = 0; x < 10; x++) { + for (int y = 0; y < 10; y++) { + r.nextBytes(offset[x][y]); + } + } - public RenderQuartzGlass() - { - super( false, 0 ); + return offset; + } - } + @Override + public void renderInventory( + final BlockQuartzGlass block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.overrideBlockTexture = ExtraBlockTextures.GlassFrame.getIcon(); + super.renderInventory(block, is, renderer, type, obj); + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } - private static byte[][][] generateOffsets() - { - final Random r = new Random( 924 ); - final byte[][][] offset = new byte[10][10][10]; + @Override + public boolean renderInWorld( + final BlockQuartzGlass imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - for( int x = 0; x < 10; x++ ) - { - for( int y = 0; y < 10; y++ ) - { - r.nextBytes( offset[x][y] ); - } - } + final int cx = Math.abs(x % 10); + final int cy = Math.abs(y % 10); + final int cz = Math.abs(z % 10); - return offset; - } + final int u = OFFSETS[cx][cy][cz] % 4; + final int v = OFFSETS[9 - cx][9 - cy][9 - cz] % 4; - @Override - public void renderInventory( final BlockQuartzGlass block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.GlassFrame.getIcon(); - super.renderInventory( block, is, renderer, type, obj ); - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } + 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; + } - @Override - public boolean renderInWorld( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + final boolean result = renderer.renderStandardBlock(imb, x, y, z); - final int cx = Math.abs( x % 10 ); - final int cy = Math.abs( y % 10 ); - final int cz = Math.abs( z % 10 ); + renderer.overrideBlockTexture = null; + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.EAST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.WEST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.NORTH + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.SOUTH + ); - final int u = OFFSETS[cx][cy][cz] % 4; - final int v = OFFSETS[9 - cx][9 - cy][9 - cz] % 4; + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.EAST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.WEST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.NORTH + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.SOUTH + ); - 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; - } + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.UP + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.DOWN + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.NORTH + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.SOUTH + ); - final boolean result = renderer.renderStandardBlock( imb, x, y, z ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.UP + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.DOWN + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.NORTH + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.SOUTH + ); - renderer.overrideBlockTexture = null; - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.UP, ForgeDirection.SOUTH ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.EAST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.WEST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.UP + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.DOWN + ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.DOWN, ForgeDirection.SOUTH ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.EAST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.WEST + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.UP + ); + this.renderEdge( + imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.DOWN + ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.DOWN ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.EAST, ForgeDirection.SOUTH ); + return result; + } - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.DOWN ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.NORTH ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.WEST, ForgeDirection.SOUTH ); + private void renderEdge( + final BlockQuartzGlass imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer, + final ForgeDirection side, + final 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; - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.NORTH, ForgeDirection.DOWN ); + 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; + } - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.EAST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.WEST ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.UP ); - this.renderEdge( imb, world, x, y, z, renderer, ForgeDirection.SOUTH, ForgeDirection.DOWN ); + 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; + } - return result; - } + 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; + } - private void renderEdge( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer, final ForgeDirection side, final 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; + renderer.setRenderBounds(minX, minY, minZ, maxX, maxY, maxZ); - 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; - } + 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; + } + } + } + } - 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; - } + private boolean isFlush( + final BlockQuartzGlass imb, + final IBlockAccess world, + final int x, + final int y, + final int z + ) { + return this.isGlass(imb, world, x, y, z); + } - 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; - } + private boolean isGlass( + final BlockQuartzGlass imb, + final IBlockAccess world, + final int x, + final int y, + final int z + ) { + return this.isQuartzGlass(world, x, y, z) + || this.isVibrantQuartzGlass(world, x, y, z); + } - renderer.setRenderBounds( minX, minY, minZ, maxX, maxY, maxZ ); + private boolean + isQuartzGlass(final IBlockAccess world, final int x, final int y, final int z) { + return AEApi.instance().definitions().blocks().quartzGlass().isSameAs( + world, x, y, z + ); + } - 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; - } - } - } - } - - private boolean isFlush( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isGlass( imb, world, x, y, z ); - } - - private boolean isGlass( final BlockQuartzGlass imb, final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isQuartzGlass( world, x, y, z ) || this.isVibrantQuartzGlass( world, x, y, z ); - } - - private boolean isQuartzGlass( final IBlockAccess world, final int x, final int y, final int z ) - { - return AEApi.instance().definitions().blocks().quartzGlass().isSameAs( world, x, y, z ); - } - - private boolean isVibrantQuartzGlass( final IBlockAccess world, final int x, final int y, final int z ) - { - return AEApi.instance().definitions().blocks().quartzVibrantGlass().isSameAs( world, x, y, z ); - } + private boolean isVibrantQuartzGlass( + final IBlockAccess world, final int x, final int y, final 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 50504c10..40064357 100644 --- a/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java +++ b/src/main/java/appeng/client/render/blocks/RenderQuartzOre.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.solids.OreQuartz; import appeng.client.render.BaseBlockRender; import appeng.client.texture.ExtraBlockTextures; @@ -28,35 +27,46 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RenderQuartzOre extends BaseBlockRender { + public RenderQuartzOre() { + super(false, 20); + } -public class RenderQuartzOre extends BaseBlockRender -{ + @Override + public void renderInventory( + final OreQuartz blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + super.renderInventory(blk, is, renderer, type, obj); + blk.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.OreQuartzStone.getIcon() + ); + super.renderInventory(blk, is, renderer, type, obj); + blk.getRendererInstance().setTemporaryRenderIcon(null); + } - public RenderQuartzOre() - { - super( false, 20 ); - } + @Override + public boolean renderInWorld( + final OreQuartz quartz, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + quartz.setEnhanceBrightness(true); + super.renderInWorld(quartz, world, x, y, z, renderer); + quartz.setEnhanceBrightness(false); - @Override - public void renderInventory( final OreQuartz blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - super.renderInventory( blk, is, renderer, type, obj ); - blk.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.OreQuartzStone.getIcon() ); - super.renderInventory( blk, is, renderer, type, obj ); - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } + quartz.getRendererInstance().setTemporaryRenderIcon( + ExtraBlockTextures.OreQuartzStone.getIcon() + ); + final boolean out = super.renderInWorld(quartz, world, x, y, z, renderer); + quartz.getRendererInstance().setTemporaryRenderIcon(null); - @Override - public boolean renderInWorld( final OreQuartz quartz, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - quartz.setEnhanceBrightness( true ); - super.renderInWorld( quartz, world, x, y, z, renderer ); - quartz.setEnhanceBrightness( false ); - - quartz.getRendererInstance().setTemporaryRenderIcon( ExtraBlockTextures.OreQuartzStone.getIcon() ); - final boolean out = super.renderInWorld( quartz, world, x, y, z, renderer ); - quartz.getRendererInstance().setTemporaryRenderIcon( null ); - - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java b/src/main/java/appeng/client/render/blocks/RenderQuartzTorch.java index 5688e67c..7ffe62d1 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 appeng.api.util.IOrientable; import appeng.block.AEBaseBlock; @@ -31,178 +32,347 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RenderQuartzTorch extends BaseBlockRender { + public RenderQuartzTorch() { + super(false, 20); + } + @Override + public void renderInventory( + final AEBaseBlock blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + final Tessellator tess = Tessellator.instance; -public class RenderQuartzTorch extends BaseBlockRender -{ + final float Point3 = 7.0f / 16.0f; + final float Point12 = 9.0f / 16.0f; - public RenderQuartzTorch() - { - super( false, 20 ); - } + final float renderBottom = 5.0f / 16.0f; + final float renderTop = 10.0f / 16.0f; - @Override - public void renderInventory( final AEBaseBlock blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - final Tessellator tess = Tessellator.instance; + final float xOff = 0.0f; + final float yOff = 0.0f; + final float zOff = 0.0f; - final float Point3 = 7.0f / 16.0f; - final float Point12 = 9.0f / 16.0f; + renderer.setRenderBounds( + Point3 + xOff, + renderBottom + yOff, + Point3 + zOff, + Point12 + xOff, + renderTop + yOff, + Point12 + zOff + ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - final float renderBottom = 5.0f / 16.0f; - final float renderTop = 10.0f / 16.0f; + final float singlePixel = 1.0f / 16.0f; + renderer.setRenderBounds( + Point3 + xOff, + renderTop + yOff, + Point3 + zOff, + Point3 + singlePixel + xOff, + renderTop + singlePixel + yOff, + Point3 + singlePixel + zOff + ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - final float xOff = 0.0f; - final float yOff = 0.0f; - final float zOff = 0.0f; + renderer.setRenderBounds( + Point12 - singlePixel + xOff, + renderBottom - singlePixel + yOff, + Point12 - singlePixel + zOff, + Point12 + xOff, + renderBottom + yOff, + Point12 + zOff + ); - renderer.setRenderBounds( Point3 + xOff, renderBottom + yOff, Point3 + zOff, Point12 + xOff, renderTop + yOff, Point12 + zOff ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - final float singlePixel = 1.0f / 16.0f; - renderer.setRenderBounds( Point3 + xOff, renderTop + yOff, Point3 + zOff, Point3 + singlePixel + xOff, renderTop + singlePixel + yOff, Point3 + singlePixel + zOff ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + blk.getRendererInstance().setTemporaryRenderIcon(Blocks.hopper.getIcon(0, 0)); + renderer.renderAllFaces = true; - renderer.setRenderBounds( Point12 - singlePixel + xOff, renderBottom - singlePixel + yOff, Point12 - singlePixel + zOff, Point12 + xOff, renderBottom + yOff, Point12 + zOff ); + final float top = 8.0f / 16.0f; + final float bottom = 7.0f / 16.0f; + final float Point13 = 10.0f / 16.0f; + final float Point2 = 6.0f / 16.0f; + renderer.setRenderBounds( + Point2 + xOff, + bottom + yOff, + Point2 + zOff, + Point13 + xOff, + top + yOff, + Point3 + zOff + ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); + renderer.setRenderBounds( + Point2 + xOff, + bottom + yOff, + Point12 + zOff, + Point13 + xOff, + top + yOff, + Point13 + zOff + ); - blk.getRendererInstance().setTemporaryRenderIcon( Blocks.hopper.getIcon( 0, 0 ) ); - renderer.renderAllFaces = true; + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); + renderer.setRenderBounds( + Point2 + xOff, + bottom + yOff, + Point3 + zOff, + Point3 + xOff, + top + yOff, + Point12 + zOff + ); - final float top = 8.0f / 16.0f; - final float bottom = 7.0f / 16.0f; - final float Point13 = 10.0f / 16.0f; - final float Point2 = 6.0f / 16.0f; - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point2 + zOff, Point13 + xOff, top + yOff, Point3 + zOff ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); + renderer.setRenderBounds( + Point12 + xOff, + bottom + yOff, + Point3 + zOff, + Point13 + xOff, + top + yOff, + Point12 + zOff + ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point12 + zOff, Point13 + xOff, top + yOff, Point13 + zOff ); + this.renderInvBlock( + EnumSet.allOf(ForgeDirection.class), blk, is, tess, 0xffffff, renderer + ); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point3 + zOff, Point3 + xOff, top + yOff, Point12 + zOff ); + renderer.renderAllFaces = false; + blk.getRendererInstance().setTemporaryRenderIcon(null); + } - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); - renderer.setRenderBounds( Point12 + xOff, bottom + yOff, Point3 + zOff, Point13 + xOff, top + yOff, Point12 + zOff ); + @Override + public boolean renderInWorld( + final AEBaseBlock block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final IOrientable te = block.getOrientable(world, x, y, z); - this.renderInvBlock( EnumSet.allOf( ForgeDirection.class ), blk, is, tess, 0xffffff, renderer ); + float xOff = 0.0f; + float yOff = 0.0f; + float zOff = 0.0f; - renderer.renderAllFaces = false; - blk.getRendererInstance().setTemporaryRenderIcon( null ); - } + renderer.renderAllFaces = true; - @Override - public boolean renderInWorld( final AEBaseBlock block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final IOrientable te = block.getOrientable( world, x, y, z ); + if (te != null) { + final 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); + } - float xOff = 0.0f; - float yOff = 0.0f; - float zOff = 0.0f; + final float renderTop = 10.0f / 16.0f; + final float renderBottom = 5.0f / 16.0f; + final float Point12 = 9.0f / 16.0f; + final float Point3 = 7.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); - renderer.renderAllFaces = true; + final int r = (x + y + z) % 2; + final float singlePixel = 1.0f / 16.0f; + 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); - if( te != null ) - { - final 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 ); - } + renderer.setRenderBounds( + Point12 - singlePixel + xOff, + renderBottom - singlePixel + yOff, + Point12 - singlePixel + zOff, + Point12 + xOff, + renderBottom + yOff, + Point12 + zOff + ); + super.renderInWorld(block, world, x, y, z, renderer); + } else { + renderer.setRenderBounds( + Point3 + xOff, + renderBottom - singlePixel + yOff, + Point3 + zOff, + Point3 + singlePixel + xOff, + renderBottom + yOff, + Point3 + singlePixel + zOff + ); + super.renderInWorld(block, world, x, y, z, renderer); - final float renderTop = 10.0f / 16.0f; - final float renderBottom = 5.0f / 16.0f; - final float Point12 = 9.0f / 16.0f; - final float Point3 = 7.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 ); + renderer.setRenderBounds( + Point12 - singlePixel + xOff, + renderTop + yOff, + Point12 - singlePixel + zOff, + Point12 + xOff, + renderTop + singlePixel + yOff, + Point12 + zOff + ); + super.renderInWorld(block, world, x, y, z, renderer); + } - final int r = ( x + y + z ) % 2; - final float singlePixel = 1.0f / 16.0f; - 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 ); + block.getRendererInstance().setTemporaryRenderIcon(Blocks.hopper.getIcon(0, 0)); - renderer.setRenderBounds( Point12 - singlePixel + xOff, renderBottom - singlePixel + yOff, Point12 - singlePixel + zOff, Point12 + xOff, renderBottom + yOff, Point12 + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); - } - else - { - renderer.setRenderBounds( Point3 + xOff, renderBottom - singlePixel + yOff, Point3 + zOff, Point3 + singlePixel + xOff, renderBottom + yOff, Point3 + singlePixel + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); + final float top = 8.0f / 16.0f; + final float bottom = 7.0f / 16.0f; + final float Point13 = 10.0f / 16.0f; + final float Point2 = 6.0f / 16.0f; + renderer.setRenderBounds( + Point2 + xOff, + bottom + yOff, + Point2 + zOff, + Point13 + xOff, + top + yOff, + Point3 + zOff + ); + final boolean out = renderer.renderStandardBlock(block, x, y, z); - renderer.setRenderBounds( Point12 - singlePixel + xOff, renderTop + yOff, Point12 - singlePixel + zOff, Point12 + xOff, renderTop + singlePixel + yOff, Point12 + zOff ); - super.renderInWorld( block, world, x, y, z, renderer ); - } + renderer.setRenderBounds( + Point2 + xOff, + bottom + yOff, + Point12 + zOff, + Point13 + xOff, + top + yOff, + Point13 + zOff + ); + renderer.renderStandardBlock(block, x, y, z); - block.getRendererInstance().setTemporaryRenderIcon( Blocks.hopper.getIcon( 0, 0 ) ); + renderer.setRenderBounds( + Point2 + xOff, + bottom + yOff, + Point3 + zOff, + Point3 + xOff, + top + yOff, + Point12 + zOff + ); + renderer.renderStandardBlock(block, x, y, z); - final float top = 8.0f / 16.0f; - final float bottom = 7.0f / 16.0f; - final float Point13 = 10.0f / 16.0f; - final float Point2 = 6.0f / 16.0f; - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point2 + zOff, Point13 + xOff, top + yOff, Point3 + zOff ); - final boolean out = renderer.renderStandardBlock( block, x, y, z ); + renderer.setRenderBounds( + Point12 + xOff, + bottom + yOff, + Point3 + zOff, + Point13 + xOff, + top + yOff, + Point12 + zOff + ); + renderer.renderStandardBlock(block, x, y, z); - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point12 + zOff, Point13 + xOff, top + yOff, Point13 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); + if (te != null) { + final ForgeDirection forward = te.getUp(); + switch (forward) { + case EAST: + renderer.setRenderBounds( + 0, + bottom + yOff, + bottom + zOff, + Point2 + xOff, + top + yOff, + top + zOff + ); + renderer.renderStandardBlock(block, x, y, z); + break; + case WEST: + renderer.setRenderBounds( + Point13 + xOff, + bottom + yOff, + bottom + zOff, + 1.0, + top + yOff, + top + zOff + ); + renderer.renderStandardBlock(block, x, y, z); + break; + case NORTH: + renderer.setRenderBounds( + bottom + xOff, + bottom + yOff, + Point13 + zOff, + top + xOff, + top + yOff, + 1.0 + ); + renderer.renderStandardBlock(block, x, y, z); + break; + case SOUTH: + renderer.setRenderBounds( + bottom + xOff, + bottom + yOff, + 0, + top + xOff, + top + yOff, + Point2 + zOff + ); + renderer.renderStandardBlock(block, x, y, z); + break; + case UP: + renderer.setRenderBounds( + Point2, 0, Point2, Point3, bottom + yOff, Point3 + ); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds( + Point2, 0, Point12, Point3, bottom + yOff, Point13 + ); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds( + Point12, 0, Point2, Point13, bottom + yOff, Point3 + ); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds( + Point12, 0, Point12, Point13, bottom + yOff, Point13 + ); + renderer.renderStandardBlock(block, x, y, z); + break; + case DOWN: + renderer.setRenderBounds( + Point2, top + yOff, Point2, Point3, 1.0, Point3 + ); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds( + Point2, top + yOff, Point12, Point3, 1.0, Point13 + ); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds( + Point12, top + yOff, Point2, Point13, 1.0, Point3 + ); + renderer.renderStandardBlock(block, x, y, z); + renderer.setRenderBounds( + Point12, top + yOff, Point12, Point13, 1.0, Point13 + ); + renderer.renderStandardBlock(block, x, y, z); + break; + default: + } + } - renderer.setRenderBounds( Point2 + xOff, bottom + yOff, Point3 + zOff, Point3 + xOff, top + yOff, Point12 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); + renderer.renderAllFaces = false; + block.getRendererInstance().setTemporaryRenderIcon(null); - renderer.setRenderBounds( Point12 + xOff, bottom + yOff, Point3 + zOff, Point13 + xOff, top + yOff, Point12 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - - if( te != null ) - { - final ForgeDirection forward = te.getUp(); - switch( forward ) - { - case EAST: - renderer.setRenderBounds( 0, bottom + yOff, bottom + zOff, Point2 + xOff, top + yOff, top + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case WEST: - renderer.setRenderBounds( Point13 + xOff, bottom + yOff, bottom + zOff, 1.0, top + yOff, top + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case NORTH: - renderer.setRenderBounds( bottom + xOff, bottom + yOff, Point13 + zOff, top + xOff, top + yOff, 1.0 ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case SOUTH: - renderer.setRenderBounds( bottom + xOff, bottom + yOff, 0, top + xOff, top + yOff, Point2 + zOff ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case UP: - renderer.setRenderBounds( Point2, 0, Point2, Point3, bottom + yOff, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point2, 0, Point12, Point3, bottom + yOff, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, 0, Point2, Point13, bottom + yOff, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, 0, Point12, Point13, bottom + yOff, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - break; - case DOWN: - renderer.setRenderBounds( Point2, top + yOff, Point2, Point3, 1.0, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point2, top + yOff, Point12, Point3, 1.0, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, top + yOff, Point2, Point13, 1.0, Point3 ); - renderer.renderStandardBlock( block, x, y, z ); - renderer.setRenderBounds( Point12, top + yOff, Point12, Point13, 1.0, Point13 ); - renderer.renderStandardBlock( block, x, y, z ); - break; - default: - } - } - - renderer.renderAllFaces = false; - block.getRendererInstance().setTemporaryRenderIcon( null ); - - return out; - } + return out; + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java b/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java index 1386580b..dab74b4f 100644 --- a/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java +++ b/src/main/java/appeng/client/render/blocks/RenderSpatialPylon.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.spatial.BlockSpatialPylon; import appeng.client.render.BaseBlockRender; import appeng.client.render.BlockRenderInfo; @@ -32,184 +31,236 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; +public class RenderSpatialPylon + extends BaseBlockRender { + public RenderSpatialPylon() { + super(false, 0); + } -public class RenderSpatialPylon extends BaseBlockRender -{ + @Override + public void renderInventory( + final BlockSpatialPylon block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.overrideBlockTexture + = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); + super.renderInventory(block, is, renderer, type, obj); + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } - public RenderSpatialPylon() - { - super( false, 0 ); - } + @Override + public boolean renderInWorld( + final BlockSpatialPylon imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - @Override - public void renderInventory( final BlockSpatialPylon block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); - super.renderInventory( block, is, renderer, type, obj ); - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } + final TileSpatialPylon sp = imb.getTileEntity(world, x, y, z); - @Override - public boolean renderInWorld( final BlockSpatialPylon imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + final int displayBits = (sp == null) ? 0 : sp.getDisplayBits(); - final TileSpatialPylon sp = imb.getTileEntity( world, x, y, z ); + if (displayBits != 0) { + ForgeDirection ori = ForgeDirection.UNKNOWN; + if ((displayBits & TileSpatialPylon.DISPLAY_Z) + == TileSpatialPylon.DISPLAY_X) { + ori = ForgeDirection.EAST; - final int displayBits = ( sp == null ) ? 0 : sp.getDisplayBits(); - - if( displayBits != 0 ) - { - ForgeDirection ori = ForgeDirection.UNKNOWN; - if( ( displayBits & TileSpatialPylon.DISPLAY_Z ) == TileSpatialPylon.DISPLAY_X ) - { - ori = ForgeDirection.EAST; - - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 2; - renderer.uvRotateTop = 2; - renderer.uvRotateBottom = 1; - } + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) + == TileSpatialPylon.DISPLAY_END_MAX) { + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 2; + renderer.uvRotateTop = 2; + renderer.uvRotateBottom = 1; + } else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) { - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 2; - } - else - { - renderer.uvRotateEast = 1; - renderer.uvRotateWest = 1; - renderer.uvRotateTop = 1; - renderer.uvRotateBottom = 1; - } - } + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 2; + } else { + renderer.uvRotateEast = 1; + renderer.uvRotateWest = 1; + renderer.uvRotateTop = 1; + renderer.uvRotateBottom = 1; + } + } - else if( ( displayBits & TileSpatialPylon.DISPLAY_Z ) == TileSpatialPylon.DISPLAY_Y ) - { - ori = ForgeDirection.UP; - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - renderer.uvRotateNorth = 3; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - renderer.uvRotateWest = 3; - } - } + else if ((displayBits & TileSpatialPylon.DISPLAY_Z) == TileSpatialPylon.DISPLAY_Y) { + ori = ForgeDirection.UP; + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) + == TileSpatialPylon.DISPLAY_END_MAX) { + renderer.uvRotateNorth = 3; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + renderer.uvRotateWest = 3; + } + } - else if( ( displayBits & TileSpatialPylon.DISPLAY_Z ) == TileSpatialPylon.DISPLAY_Z ) - { - ori = ForgeDirection.NORTH; - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - renderer.uvRotateSouth = 1; - renderer.uvRotateNorth = 2; - } + else if ((displayBits & TileSpatialPylon.DISPLAY_Z) == TileSpatialPylon.DISPLAY_Z) { + ori = ForgeDirection.NORTH; + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) + == TileSpatialPylon.DISPLAY_END_MAX) { + renderer.uvRotateSouth = 1; + renderer.uvRotateNorth = 2; + } else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) { - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - } - else - { - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - } - } + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + } else { + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + } + } - final BlockRenderInfo bri = imb.getRendererInstance(); - bri.setTemporaryRenderIcon( null ); - bri.setTemporaryRenderIcons( this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.UP ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.DOWN ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.SOUTH ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.NORTH ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.EAST ), this.getBlockTextureFromSideOutside( imb, sp, displayBits, ori, ForgeDirection.WEST ) ); + final BlockRenderInfo bri = imb.getRendererInstance(); + bri.setTemporaryRenderIcon(null); + bri.setTemporaryRenderIcons( + this.getBlockTextureFromSideOutside( + imb, sp, displayBits, ori, ForgeDirection.UP + ), + this.getBlockTextureFromSideOutside( + imb, sp, displayBits, ori, ForgeDirection.DOWN + ), + this.getBlockTextureFromSideOutside( + imb, sp, displayBits, ori, ForgeDirection.SOUTH + ), + this.getBlockTextureFromSideOutside( + imb, sp, displayBits, ori, ForgeDirection.NORTH + ), + this.getBlockTextureFromSideOutside( + imb, sp, displayBits, ori, ForgeDirection.EAST + ), + this.getBlockTextureFromSideOutside( + imb, sp, displayBits, ori, ForgeDirection.WEST + ) + ); - final boolean r = renderer.renderStandardBlock( imb, x, y, z ); + final boolean r = renderer.renderStandardBlock(imb, x, y, z); - if( ( displayBits & TileSpatialPylon.DISPLAY_POWERED_ENABLED ) == TileSpatialPylon.DISPLAY_POWERED_ENABLED ) - { - final int bn = 15; - Tessellator.instance.setBrightness( bn << 20 | bn << 4 ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); + if ((displayBits & TileSpatialPylon.DISPLAY_POWERED_ENABLED) + == TileSpatialPylon.DISPLAY_POWERED_ENABLED) { + final int bn = 15; + Tessellator.instance.setBrightness(bn << 20 | bn << 4); + Tessellator.instance.setColorOpaque_I(0xffffff); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.renderFace( x, y, z, imb, this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, d ), renderer, d ); - } - } - else - { - bri.setTemporaryRenderIcon( null ); - bri.setTemporaryRenderIcons( this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.UP ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.DOWN ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.SOUTH ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.NORTH ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.EAST ), this.getBlockTextureFromSideInside( imb, sp, displayBits, ori, ForgeDirection.WEST ) ); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.renderFace( + x, + y, + z, + imb, + this.getBlockTextureFromSideInside(imb, sp, displayBits, ori, d), + renderer, + d + ); + } + } else { + bri.setTemporaryRenderIcon(null); + bri.setTemporaryRenderIcons( + this.getBlockTextureFromSideInside( + imb, sp, displayBits, ori, ForgeDirection.UP + ), + this.getBlockTextureFromSideInside( + imb, sp, displayBits, ori, ForgeDirection.DOWN + ), + this.getBlockTextureFromSideInside( + imb, sp, displayBits, ori, ForgeDirection.SOUTH + ), + this.getBlockTextureFromSideInside( + imb, sp, displayBits, ori, ForgeDirection.NORTH + ), + this.getBlockTextureFromSideInside( + imb, sp, displayBits, ori, ForgeDirection.EAST + ), + this.getBlockTextureFromSideInside( + imb, sp, displayBits, ori, ForgeDirection.WEST + ) + ); - renderer.renderStandardBlock( imb, x, y, z ); - } + renderer.renderStandardBlock(imb, x, y, z); + } - bri.setTemporaryRenderIcon( null ); - renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateBottom = 0; + bri.setTemporaryRenderIcon(null); + renderer.uvRotateEast = renderer.uvRotateWest = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateBottom + = 0; - return r; - } + return r; + } - renderer.overrideBlockTexture = imb.getIcon( 0, 0 ); - boolean result = renderer.renderStandardBlock( imb, x, y, z ); + renderer.overrideBlockTexture = imb.getIcon(0, 0); + boolean result = renderer.renderStandardBlock(imb, x, y, z); - renderer.overrideBlockTexture = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); - result = renderer.renderStandardBlock( imb, x, y, z ); + renderer.overrideBlockTexture + = ExtraBlockTextures.BlockSpatialPylon_dim.getIcon(); + result = renderer.renderStandardBlock(imb, x, y, z); - renderer.overrideBlockTexture = null; - return result; - } + renderer.overrideBlockTexture = null; + return result; + } - private IIcon getBlockTextureFromSideOutside( final BlockSpatialPylon blk, final TileSpatialPylon sp, final int displayBits, final ForgeDirection ori, final ForgeDirection dir ) - { + private IIcon getBlockTextureFromSideOutside( + final BlockSpatialPylon blk, + final TileSpatialPylon sp, + final int displayBits, + final ForgeDirection ori, + final ForgeDirection dir + ) { + if (ori == dir || ori.getOpposite() == dir) { + return blk.getRendererInstance().getTexture(dir); + } - if( ori == dir || ori.getOpposite() == dir ) - { - return blk.getRendererInstance().getTexture( dir ); - } + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) + == TileSpatialPylon.DISPLAY_MIDDLE) { + return ExtraBlockTextures.BlockSpatialPylonC.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); + } - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_MIDDLE ) - { - return ExtraBlockTextures.BlockSpatialPylonC.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - return ExtraBlockTextures.BlockSpatialPylonE.getIcon(); - } + return blk.getIcon(0, 0); + } - return blk.getIcon( 0, 0 ); - } + private IIcon getBlockTextureFromSideInside( + final BlockSpatialPylon blk, + final TileSpatialPylon sp, + final int displayBits, + final ForgeDirection ori, + final ForgeDirection dir + ) { + final boolean good = (displayBits & TileSpatialPylon.DISPLAY_ENABLED) + == TileSpatialPylon.DISPLAY_ENABLED; - private IIcon getBlockTextureFromSideInside( final BlockSpatialPylon blk, final TileSpatialPylon sp, final int displayBits, final ForgeDirection ori, final ForgeDirection dir ) - { - final boolean good = ( displayBits & TileSpatialPylon.DISPLAY_ENABLED ) == TileSpatialPylon.DISPLAY_ENABLED; + if (ori == dir || ori.getOpposite() == dir) { + return good ? ExtraBlockTextures.BlockSpatialPylon_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylon_red.getIcon(); + } - if( ori == dir || ori.getOpposite() == dir ) - { - return good ? ExtraBlockTextures.BlockSpatialPylon_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylon_red.getIcon(); - } + if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) + == TileSpatialPylon.DISPLAY_MIDDLE) { + return good ? ExtraBlockTextures.BlockSpatialPylonC_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylonC_red.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MIN) { + return good ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); + } else if ((displayBits & TileSpatialPylon.DISPLAY_MIDDLE) == TileSpatialPylon.DISPLAY_END_MAX) { + return good ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() + : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); + } - if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_MIDDLE ) - { - return good ? ExtraBlockTextures.BlockSpatialPylonC_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylonC_red.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MIN ) - { - return good ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); - } - else if( ( displayBits & TileSpatialPylon.DISPLAY_MIDDLE ) == TileSpatialPylon.DISPLAY_END_MAX ) - { - return good ? ExtraBlockTextures.BlockSpatialPylonE_dim.getIcon() : ExtraBlockTextures.BlockSpatialPylonE_red.getIcon(); - } - - return blk.getIcon( 0, 0 ); - } + return blk.getIcon(0, 0); + } } diff --git a/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java b/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java index c7b2e1f6..66b790ce 100644 --- a/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java +++ b/src/main/java/appeng/client/render/blocks/RenderTinyTNT.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.misc.BlockTinyTNT; import appeng.client.render.BaseBlockRender; import appeng.tile.AEBaseTile; @@ -27,29 +26,36 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RenderTinyTNT extends BaseBlockRender { + public RenderTinyTNT() { + super(false, 0); + } -public class RenderTinyTNT extends BaseBlockRender -{ + @Override + public void renderInventory( + final BlockTinyTNT block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.setRenderBounds(0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f); + super.renderInventory(block, is, renderer, type, obj); + } - public RenderTinyTNT() - { - super( false, 0 ); - } - - @Override - public void renderInventory( final BlockTinyTNT block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final 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( final BlockTinyTNT imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - renderer.renderAllFaces = true; - renderer.setRenderBounds( 0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f ); - final boolean out = super.renderInWorld( imb, world, x, y, z, renderer ); - renderer.renderAllFaces = false; - return out; - } + @Override + public boolean renderInWorld( + final BlockTinyTNT imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + renderer.renderAllFaces = true; + renderer.setRenderBounds(0.25f, 0.0f, 0.25f, 0.75f, 0.5f, 0.75f); + final boolean out = super.renderInWorld(imb, world, x, y, z, renderer); + 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 21b3e245..ae1d49c8 100644 --- a/src/main/java/appeng/client/render/blocks/RendererCableBus.java +++ b/src/main/java/appeng/client/render/blocks/RendererCableBus.java @@ -18,7 +18,6 @@ package appeng.client.render.blocks; - import appeng.block.networking.BlockCableBus; import appeng.client.render.BaseBlockRender; import appeng.client.render.BusRenderHelper; @@ -31,45 +30,59 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; +public class RendererCableBus extends BaseBlockRender { + public RendererCableBus() { + super(true, 30); + } -public class RendererCableBus extends BaseBlockRender -{ + @Override + public void renderInventory( + final BlockCableBus blk, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + // nothing. + } - public RendererCableBus() - { - super( true, 30 ); - } + @Override + public boolean renderInWorld( + final BlockCableBus block, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final AEBaseTile t = block.getTileEntity(world, x, y, z); - @Override - public void renderInventory( final BlockCableBus blk, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - // nothing. - } + if (t instanceof TileCableBus) { + BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; + BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; + BusRenderer.INSTANCE.getRenderer().overrideBlockTexture + = renderer.overrideBlockTexture; + ((TileCableBus) t).getCableBus().renderStatic(x, y, z); + BusRenderer.INSTANCE.getRenderer().renderAllFaces = false; + } - @Override - public boolean renderInWorld( final BlockCableBus block, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final AEBaseTile t = block.getTileEntity( world, x, y, z ); + return BusRenderHelper.INSTANCE.getItemsRendered() > 0; + } - if( t instanceof TileCableBus ) - { - BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; - BusRenderer.INSTANCE.getRenderer().blockAccess = renderer.blockAccess; - BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = renderer.overrideBlockTexture; - ( (TileCableBus) t ).getCableBus().renderStatic( x, y, z ); - BusRenderer.INSTANCE.getRenderer().renderAllFaces = false; - } - - return BusRenderHelper.INSTANCE.getItemsRendered() > 0; - } - - @Override - public void renderTile( final BlockCableBus block, final TileCableBus cableBus, final Tessellator tess, final double x, final double y, final double z, final float f, final RenderBlocks renderer ) - { - if( cableBus != null ) - { - BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; - cableBus.getCableBus().renderDynamic( x, y, z ); - } - } + @Override + public void renderTile( + final BlockCableBus block, + final TileCableBus cableBus, + final Tessellator tess, + final double x, + final double y, + final double z, + final float f, + final RenderBlocks renderer + ) { + if (cableBus != null) { + BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; + cableBus.getCableBus().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 8a7988c3..f0138011 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 appeng.api.util.AEColor; import appeng.block.misc.BlockSecurity; @@ -32,71 +33,93 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.client.IItemRenderer.ItemRenderType; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class RendererSecurity extends BaseBlockRender { + public RendererSecurity() { + super(false, 0); + } + @Override + public void renderInventory( + final BlockSecurity block, + final ItemStack is, + final RenderBlocks renderer, + final ItemRenderType type, + final Object[] obj + ) { + renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); + this.renderInvBlock( + EnumSet.of(ForgeDirection.SOUTH), + block, + is, + Tessellator.instance, + 0x000000, + renderer + ); -public class RendererSecurity extends BaseBlockRender -{ + renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); + this.renderInvBlock( + EnumSet.of(ForgeDirection.UP), + block, + is, + Tessellator.instance, + this.adjustBrightness(AEColor.Transparent.whiteVariant, 0.7), + renderer + ); - public RendererSecurity() - { - super( false, 0 ); - } + renderer.overrideBlockTexture = null; + super.renderInventory(block, is, renderer, type, obj); + } - @Override - public void renderInventory( final BlockSecurity block, final ItemStack is, final RenderBlocks renderer, final ItemRenderType type, final Object[] obj ) - { - renderer.overrideBlockTexture = ExtraBlockTextures.getMissing(); - this.renderInvBlock( EnumSet.of( ForgeDirection.SOUTH ), block, is, Tessellator.instance, 0x000000, renderer ); + @Override + public boolean renderInWorld( + final BlockSecurity imb, + final IBlockAccess world, + final int x, + final int y, + final int z, + final RenderBlocks renderer + ) { + final TileSecurity sp = imb.getTileEntity(world, x, y, z); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - renderer.overrideBlockTexture = ExtraBlockTextures.MEChest.getIcon(); - this.renderInvBlock( EnumSet.of( ForgeDirection.UP ), block, is, Tessellator.instance, this.adjustBrightness( AEColor.Transparent.whiteVariant, 0.7 ), renderer ); + final ForgeDirection up = sp.getUp(); - renderer.overrideBlockTexture = null; - super.renderInventory( block, is, renderer, type, obj ); - } + this.preRenderInWorld(imb, world, x, y, z, renderer); - @Override - public boolean renderInWorld( final BlockSecurity imb, final IBlockAccess world, final int x, final int y, final int z, final RenderBlocks renderer ) - { - final TileSecurity sp = imb.getTileEntity( world, x, y, z ); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + final boolean result = renderer.renderStandardBlock(imb, x, y, z); - final ForgeDirection up = sp.getUp(); + int b = world.getLightBrightnessForSkyBlocks( + x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 + ); - this.preRenderInWorld( imb, world, x, y, z, renderer ); + if (sp.isActive()) { + b = 15 << 20 | 15 << 4; + } - final boolean result = renderer.renderStandardBlock( imb, x, y, z ); + Tessellator.instance.setBrightness(b); + Tessellator.instance.setColorOpaque_I(0xffffff); + renderer.setRenderBounds(0, 0, 0, 1, 1, 1); - int b = world.getLightBrightnessForSkyBlocks( x + up.offsetX, y + up.offsetY, z + up.offsetZ, 0 ); + 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() ) - { - b = 15 << 20 | 15 << 4; - } + if (sp.isActive()) { + Tessellator.instance.setColorOpaque_I(sp.getColor().mediumVariant); + ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Medium.getIcon() + : ExtraBlockTextures.MEChest.getIcon(); + this.renderFace(x, y, z, imb, ico, renderer, up); - Tessellator.instance.setBrightness( b ); - Tessellator.instance.setColorOpaque_I( 0xffffff ); - renderer.setRenderBounds( 0, 0, 0, 1, 1, 1 ); + Tessellator.instance.setColorOpaque_I(sp.getColor().blackVariant); + ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Dark.getIcon() + : ExtraBlockTextures.MEChest.getIcon(); + this.renderFace(x, y, z, imb, ico, renderer, up); + } - 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 ); + renderer.overrideBlockTexture = null; + this.postRenderInWorld(renderer); - if( sp.isActive() ) - { - Tessellator.instance.setColorOpaque_I( sp.getColor().mediumVariant ); - ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Medium.getIcon() : ExtraBlockTextures.MEChest.getIcon(); - this.renderFace( x, y, z, imb, ico, renderer, up ); - - Tessellator.instance.setColorOpaque_I( sp.getColor().blackVariant ); - ico = sp.isActive() ? ExtraBlockTextures.BlockMESecurityOn_Dark.getIcon() : ExtraBlockTextures.MEChest.getIcon(); - this.renderFace( x, y, z, imb, ico, renderer, up ); - } - - renderer.overrideBlockTexture = null; - this.postRenderInWorld( renderer ); - - return result; - } + return result; + } } diff --git a/src/main/java/appeng/client/render/effects/AssemblerFX.java b/src/main/java/appeng/client/render/effects/AssemblerFX.java index 0c670b3d..1791056f 100644 --- a/src/main/java/appeng/client/render/effects/AssemblerFX.java +++ b/src/main/java/appeng/client/render/effects/AssemblerFX.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.api.storage.data.IAEItemStack; import appeng.client.EffectType; import appeng.core.CommonHelper; @@ -27,63 +26,76 @@ import net.minecraft.client.particle.EntityFX; import net.minecraft.client.renderer.Tessellator; import net.minecraft.world.World; +public class AssemblerFX extends EntityFX { + private final EntityFloatingItem fi; + private final float speed; + private float time = 0; -public class AssemblerFX extends EntityFX -{ + public AssemblerFX( + final World w, + final double x, + final double y, + final double z, + final double r, + final double g, + final double b, + final float speed, + final IAEItemStack is + ) { + super(w, x, y, z, r, g, b); + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + 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.noClip = true; + } - private final EntityFloatingItem fi; - private final float speed; - private float time = 0; + @Override + public int getBrightnessForRender(final float par1) { + final int j1 = 13; + return j1 << 20 | j1 << 4; + } - public AssemblerFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b, final float speed, final IAEItemStack is ) - { - super( w, x, y, z, r, g, b ); - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - 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.noClip = true; - } + @Override + public void onUpdate() { + super.onUpdate(); - @Override - public int getBrightnessForRender( final float par1 ) - { - final int j1 = 13; - return j1 << 20 | j1 << 4; - } + if (this.isDead) { + this.fi.setDead(); + } else { + final float lifeSpan = (float) this.particleAge / (float) this.particleMaxAge; + this.fi.setProgress(lifeSpan); + } + } - @Override - public void onUpdate() - { - super.onUpdate(); + @Override + public void renderParticle( + final Tessellator tess, + final float l, + final float rX, + final float rY, + final float rZ, + final float rYZ, + final float rXY + ) { + this.time += l; - if( this.isDead ) - { - this.fi.setDead(); - } - else - { - final float lifeSpan = (float) this.particleAge / (float) this.particleMaxAge; - this.fi.setProgress( lifeSpan ); - } - } - - @Override - public void renderParticle( final Tessellator tess, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY ) - { - this.time += l; - - 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++ ) - { - CommonHelper.proxy.spawnEffect( EffectType.Crafting, this.worldObj, this.posX, this.posY, this.posZ, null ); - } - } - } + 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++) { + 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 bb60cdd7..8d30b012 100644 --- a/src/main/java/appeng/client/render/effects/ChargedOreFX.java +++ b/src/main/java/appeng/client/render/effects/ChargedOreFX.java @@ -18,31 +18,32 @@ package appeng.client.render.effects; - import net.minecraft.client.particle.EntityReddustFX; import net.minecraft.world.World; +public class ChargedOreFX extends EntityReddustFX { + public ChargedOreFX( + final World w, + final double x, + final double y, + final double z, + final float r, + final float g, + final float b + ) { + super(w, x, y, z, 0.21f, 0.61f, 1.0f); + } -public class ChargedOreFX extends EntityReddustFX -{ + @Override + public int getBrightnessForRender(final float par1) { + int j1 = super.getBrightnessForRender(par1); + j1 = Math.max(j1 >> 20, j1 >> 4); + j1 += 3; - public ChargedOreFX( final World w, final double x, final double y, final double z, final float r, final float g, final float b ) - { - super( w, x, y, z, 0.21f, 0.61f, 1.0f ); - } + if (j1 > 15) { + j1 = 15; + } - @Override - public int getBrightnessForRender( final float par1 ) - { - int j1 = super.getBrightnessForRender( par1 ); - j1 = Math.max( j1 >> 20, j1 >> 4 ); - j1 += 3; - - if( j1 > 15 ) - { - j1 = 15; - } - - return j1 << 20 | j1 << 4; - } + 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 f77739fe..3f3e2245 100644 --- a/src/main/java/appeng/client/render/effects/CraftingFx.java +++ b/src/main/java/appeng/client/render/effects/CraftingFx.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.client.texture.ExtraBlockTextures; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -30,93 +29,126 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +@SideOnly(Side.CLIENT) +public class CraftingFx extends EntityBreakingFX { + private final IIcon particleTextureIndex; -@SideOnly( Side.CLIENT ) -public class CraftingFx extends EntityBreakingFX -{ + private final int startBlkX; + private final int startBlkY; + private final int startBlkZ; - private final IIcon particleTextureIndex; + public CraftingFx( + final World par1World, + final double par2, + final double par4, + final double par6, + final Item par8Item + ) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 1; + this.particleGreen = 0.9f; + this.particleRed = 1; + this.particleAlpha = 1.3f; + this.particleScale = 1.5f; + this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); + this.particleMaxAge /= 1.2; - private final int startBlkX; - private final int startBlkY; - private final int startBlkZ; + this.startBlkX = MathHelper.floor_double(this.posX); + this.startBlkY = MathHelper.floor_double(this.posY); + this.startBlkZ = MathHelper.floor_double(this.posZ); - public CraftingFx( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 1; - this.particleGreen = 0.9f; - this.particleRed = 1; - this.particleAlpha = 1.3f; - this.particleScale = 1.5f; - this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); - this.particleMaxAge /= 1.2; + this.noClip = true; + } - this.startBlkX = MathHelper.floor_double( this.posX ); - this.startBlkY = MathHelper.floor_double( this.posY ); - this.startBlkZ = MathHelper.floor_double( this.posZ ); + @Override + public int getFXLayer() { + return 1; + } - this.noClip = true; - } + @Override + public void renderParticle( + final Tessellator par1Tessellator, + final float partialTick, + final float x, + final float y, + final float z, + final float rx, + final float rz + ) { + if (partialTick < 0 || partialTick > 1) { + return; + } - @Override - public int getFXLayer() - { - return 1; - } + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float scale = 0.1F * this.particleScale; - @Override - public void renderParticle( final Tessellator par1Tessellator, final float partialTick, final float x, final float y, final float z, final float rx, final float rz ) - { - if( partialTick < 0 || partialTick > 1 ) - { - return; - } + 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); - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float scale = 0.1F * this.particleScale; + final int blkX = MathHelper.floor_double(offX); + final int blkY = MathHelper.floor_double(offY); + final int blkZ = MathHelper.floor_double(offZ); - 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 ); + if (blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ) { + offX -= interpPosX; + offY -= interpPosY; + offZ -= interpPosZ; - final int blkX = MathHelper.floor_double( offX ); - final int blkY = MathHelper.floor_double( offY ); - final int blkZ = MathHelper.floor_double( offZ ); + // AELog.info( "" + partialTick ); + final float f14 = 1.0F; + 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 + ); + } + } - if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - offX -= interpPosX; - offY -= interpPosY; - offZ -= interpPosZ; + public void fromItem(final ForgeDirection d) { + this.posX += 0.2 * d.offsetX; + this.posY += 0.2 * d.offsetY; + this.posZ += 0.2 * d.offsetZ; + this.particleScale *= 0.8f; + } - // AELog.info( "" + partialTick ); - final float f14 = 1.0F; - 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( final ForgeDirection d ) - { - this.posX += 0.2 * d.offsetX; - this.posY += 0.2 * d.offsetY; - this.posZ += 0.2 * d.offsetZ; - this.particleScale *= 0.8f; - } - - @Override - public void onUpdate() - { - super.onUpdate(); - this.particleScale *= 0.51f; - this.particleAlpha *= 0.51f; - } + @Override + public void onUpdate() { + super.onUpdate(); + this.particleScale *= 0.51f; + this.particleAlpha *= 0.51f; + } } diff --git a/src/main/java/appeng/client/render/effects/EnergyFx.java b/src/main/java/appeng/client/render/effects/EnergyFx.java index 1b533d72..8078139e 100644 --- a/src/main/java/appeng/client/render/effects/EnergyFx.java +++ b/src/main/java/appeng/client/render/effects/EnergyFx.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.client.texture.ExtraBlockTextures; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -30,82 +29,119 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +@SideOnly(Side.CLIENT) +public class EnergyFx extends EntityBreakingFX { + private final IIcon particleTextureIndex; -@SideOnly( Side.CLIENT ) -public class EnergyFx extends EntityBreakingFX -{ + private final int startBlkX; + private final int startBlkY; + private final int startBlkZ; - private final IIcon particleTextureIndex; + public EnergyFx( + final World par1World, + final double par2, + final double par4, + final double par6, + final Item par8Item + ) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 255; + this.particleGreen = 255; + this.particleRed = 255; + this.particleAlpha = 1.4f; + this.particleScale = 3.5f; + this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); - private final int startBlkX; - private final int startBlkY; - private final int startBlkZ; + this.startBlkX = MathHelper.floor_double(this.posX); + this.startBlkY = MathHelper.floor_double(this.posY); + this.startBlkZ = MathHelper.floor_double(this.posZ); - public EnergyFx( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 255; - this.particleGreen = 255; - this.particleRed = 255; - this.particleAlpha = 1.4f; - this.particleScale = 3.5f; - this.particleTextureIndex = ExtraBlockTextures.BlockEnergyParticle.getIcon(); + this.noClip = true; + } - this.startBlkX = MathHelper.floor_double( this.posX ); - this.startBlkY = MathHelper.floor_double( this.posY ); - this.startBlkZ = MathHelper.floor_double( this.posZ ); + @Override + public int getFXLayer() { + return 1; + } - this.noClip = true; - } + @Override + public void renderParticle( + final Tessellator par1Tessellator, + final float par2, + final float par3, + final float par4, + final float par5, + final float par6, + final float par7 + ) { + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float f10 = 0.1F * this.particleScale; - @Override - public int getFXLayer() - { - return 1; - } + final float f11 + = (float) (this.prevPosX + (this.posX - this.prevPosX) * par2 - interpPosX); + final float f12 + = (float) (this.prevPosY + (this.posY - this.prevPosY) * par2 - interpPosY); + final float f13 + = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * par2 - interpPosZ); - @Override - public void renderParticle( final Tessellator par1Tessellator, final float par2, final float par3, final float par4, final float par5, final float par6, final float par7 ) - { - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float f10 = 0.1F * this.particleScale; + final int blkX = MathHelper.floor_double(this.posX); + final int blkY = MathHelper.floor_double(this.posY); + final int blkZ = MathHelper.floor_double(this.posZ); - final float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); - final float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); - final float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); + if (blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ) { + final 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 + ); + } + } - final int blkX = MathHelper.floor_double( this.posX ); - final int blkY = MathHelper.floor_double( this.posY ); - final int blkZ = MathHelper.floor_double( this.posZ ); + public void fromItem(final ForgeDirection d) { + this.posX += 0.2 * d.offsetX; + this.posY += 0.2 * d.offsetY; + this.posZ += 0.2 * d.offsetZ; + this.particleScale *= 0.8f; + } - if( blkX == this.startBlkX && blkY == this.startBlkY && blkZ == this.startBlkZ ) - { - final 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 ); - } - } - - public void fromItem( final ForgeDirection d ) - { - this.posX += 0.2 * d.offsetX; - this.posY += 0.2 * d.offsetY; - this.posZ += 0.2 * d.offsetZ; - this.particleScale *= 0.8f; - } - - @Override - public void onUpdate() - { - super.onUpdate(); - this.particleScale *= 0.89f; - this.particleAlpha *= 0.89f; - } + @Override + public void onUpdate() { + super.onUpdate(); + this.particleScale *= 0.89f; + this.particleAlpha *= 0.89f; + } } diff --git a/src/main/java/appeng/client/render/effects/LightningArcFX.java b/src/main/java/appeng/client/render/effects/LightningArcFX.java index bfbe92e2..e2e22366 100644 --- a/src/main/java/appeng/client/render/effects/LightningArcFX.java +++ b/src/main/java/appeng/client/render/effects/LightningArcFX.java @@ -18,48 +18,62 @@ package appeng.client.render.effects; +import java.util.Random; import net.minecraft.world.World; -import java.util.Random; +public class LightningArcFX extends LightningFX { + private static final Random RANDOM_GENERATOR = new Random(); + private final double rx; + private final double ry; + private final double rz; -public class LightningArcFX extends LightningFX -{ - private static final Random RANDOM_GENERATOR = new Random(); + public LightningArcFX( + final World w, + final double x, + final double y, + final double z, + final double ex, + final double ey, + final double ez, + final double r, + final double g, + final double b + ) { + super(w, x, y, z, r, g, b, 6); + this.noClip = true; - private final double rx; - private final double ry; - private final double rz; + this.rx = ex - x; + this.ry = ey - y; + this.rz = ez - z; - public LightningArcFX( final World w, final double x, final double y, final double z, final double ex, final double ey, final double ez, final double r, final double g, final double b ) - { - super( w, x, y, z, r, g, b, 6 ); - this.noClip = true; + this.regen(); + } - this.rx = ex - x; - this.ry = ey - y; - this.rz = ez - z; + @Override + protected void regen() { + final double i = 1.0 / (this.getSteps() - 1); + final double lastDirectionX = this.rx * i; + final double lastDirectionY = this.ry * i; + final double lastDirectionZ = this.rz * i; + final double len = Math.sqrt( + lastDirectionX * lastDirectionX + lastDirectionY * lastDirectionY + + lastDirectionZ * lastDirectionZ + ); - this.regen(); - } + for (int s = 0; s < this.getSteps(); s++) { + final double[][] localSteps = this.getPrecomputedSteps(); - @Override - protected void regen() - { - final double i = 1.0 / ( this.getSteps() - 1 ); - final double lastDirectionX = this.rx * i; - final double lastDirectionY = this.ry * i; - final double lastDirectionZ = this.rz * i; - final double len = Math.sqrt( lastDirectionX * lastDirectionX + lastDirectionY * lastDirectionY + lastDirectionZ * lastDirectionZ ); - - for( int s = 0; s < this.getSteps(); s++ ) - { - final double[][] localSteps = this.getPrecomputedSteps(); - - localSteps[s][0] = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - localSteps[s][1] = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - localSteps[s][2] = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * len * 1.2 ) / 2.0; - } - } + localSteps[s][0] + = (lastDirectionX + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) + / 2.0; + localSteps[s][1] + = (lastDirectionY + (RANDOM_GENERATOR.nextDouble() - 0.5) * len * 1.2) + / 2.0; + localSteps[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 ba55b128..d1ab0d8e 100644 --- a/src/main/java/appeng/client/render/effects/LightningFX.java +++ b/src/main/java/appeng/client/render/effects/LightningFX.java @@ -18,6 +18,7 @@ package appeng.client.render.effects; +import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.particle.EntityFX; @@ -26,200 +27,237 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -import java.util.Random; +public class LightningFX extends EntityFX { + private static final Random RANDOM_GENERATOR = new Random(); + private static final int STEPS = 5; + private final double[][] precomputedSteps; + private final double[] vertices = new double[3]; + private final double[] verticesWithUV = new double[3]; + private boolean hasData = false; -public class LightningFX extends EntityFX -{ - private static final Random RANDOM_GENERATOR = new Random(); - private static final int STEPS = 5; + public LightningFX( + final World w, + final double x, + final double y, + final double z, + final double r, + final double g, + final double b + ) { + this(w, x, y, z, r, g, b, 6); + this.regen(); + } - private final double[][] precomputedSteps; - private final double[] vertices = new double[3]; - private final double[] verticesWithUV = new double[3]; - private boolean hasData = false; + protected LightningFX( + final World w, + final double x, + final double y, + final double z, + final double r, + final double g, + final double b, + final int maxAge + ) { + super(w, x, y, z, r, g, b); + this.precomputedSteps = new double[LightningFX.STEPS][3]; + this.motionX = 0; + this.motionY = 0; + this.motionZ = 0; + this.particleMaxAge = maxAge; + this.noClip = true; + } - public LightningFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b ) - { - this( w, x, y, z, r, g, b, 6 ); - this.regen(); - } + 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; - protected LightningFX( final World w, final double x, final double y, final double z, final double r, final double g, final double b, final int maxAge ) - { - super( w, x, y, z, r, g, b ); - this.precomputedSteps = new double[LightningFX.STEPS][3]; - this.motionX = 0; - this.motionY = 0; - this.motionZ = 0; - this.particleMaxAge = maxAge; - this.noClip = true; - } + for (int s = 0; s < LightningFX.STEPS; s++) { + this.precomputedSteps[s][0] = lastDirectionX + = (lastDirectionX + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + this.precomputedSteps[s][1] = lastDirectionY + = (lastDirectionY + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + this.precomputedSteps[s][2] = lastDirectionZ + = (lastDirectionZ + (RANDOM_GENERATOR.nextDouble() - 0.5) * 0.9) / 2.0; + } + } - 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; + protected int getSteps() { + return LightningFX.STEPS; + } - for( int s = 0; s < LightningFX.STEPS; s++ ) - { - this.precomputedSteps[s][0] = lastDirectionX = ( lastDirectionX + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.precomputedSteps[s][1] = lastDirectionY = ( lastDirectionY + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - this.precomputedSteps[s][2] = lastDirectionZ = ( lastDirectionZ + ( RANDOM_GENERATOR.nextDouble() - 0.5 ) * 0.9 ) / 2.0; - } - } + @Override + public int getBrightnessForRender(final float par1) { + final int j1 = 13; + return j1 << 20 | j1 << 4; + } - protected int getSteps() - { - return LightningFX.STEPS; - } + @Override + public void renderParticle( + final Tessellator tess, + final float l, + final float rX, + final float rY, + final float rZ, + final float rYZ, + final float rXY + ) { + final float j = 1.0f; - @Override - public int getBrightnessForRender( final float par1 ) - { - final int j1 = 13; - return j1 << 20 | j1 << 4; - } + tess.setColorRGBA_F( + this.particleRed * j * 0.9f, + this.particleGreen * j * 0.95f, + this.particleBlue * j, + this.particleAlpha + ); - @Override - public void renderParticle( final Tessellator tess, final float l, final float rX, final float rY, final float rZ, final float rYZ, final float rXY ) - { - final float j = 1.0f; + if (this.particleAge == 3) { + this.regen(); + } + double f6 = this.particleTextureIndexX / 16.0; + final double f7 = f6 + 0.0324375F; + double f8 = this.particleTextureIndexY / 16.0; + final double f9 = f8 + 0.0324375F; - tess.setColorRGBA_F( this.particleRed * j * 0.9f, this.particleGreen * j * 0.95f, this.particleBlue * j, this.particleAlpha ); + f6 = f7; + f8 = f9; - if( this.particleAge == 3 ) - { - this.regen(); - } - double f6 = this.particleTextureIndexX / 16.0; - final double f7 = f6 + 0.0324375F; - double f8 = this.particleTextureIndexY / 16.0; - final double f9 = f8 + 0.0324375F; + double scale = 0.02; // 0.02F * this.particleScale; - f6 = f7; - f8 = f9; + final double[] a = new double[3]; + final double[] b = new double[3]; - double scale = 0.02;// 0.02F * this.particleScale; + double ox = 0; + double oy = 0; + double oz = 0; - final double[] a = new double[3]; - final double[] b = new double[3]; + final EntityPlayer p = Minecraft.getMinecraft().thePlayer; + double offX = -rZ; + double offY + = MathHelper.cos((float) (Math.PI / 2.0f + p.rotationPitch * 0.017453292F)); + double offZ = rX; - double ox = 0; - double oy = 0; - double oz = 0; + for (int layer = 0; layer < 2; layer++) { + if (layer == 0) { + scale = 0.04; + offX *= 0.001; + offY *= 0.001; + offZ *= 0.001; + tess.setColorRGBA_F( + this.particleRed * j * 0.4f, + this.particleGreen * j * 0.25f, + this.particleBlue * j * 0.45f, + this.particleAlpha + ); + } else { + offX = 0; + offY = 0; + offZ = 0; + scale = 0.02; + tess.setColorRGBA_F( + this.particleRed * j * 0.9f, + this.particleGreen * j * 0.65f, + this.particleBlue * j * 0.85f, + this.particleAlpha + ); + } - final EntityPlayer p = Minecraft.getMinecraft().thePlayer; - double offX = -rZ; - double offY = MathHelper.cos( (float) ( Math.PI / 2.0f + p.rotationPitch * 0.017453292F ) ); - double offZ = rX; + for (int cycle = 0; cycle < 3; cycle++) { + this.clear(); - for( int layer = 0; layer < 2; layer++ ) - { - if( layer == 0 ) - { - scale = 0.04; - offX *= 0.001; - offY *= 0.001; - offZ *= 0.001; - tess.setColorRGBA_F( this.particleRed * j * 0.4f, this.particleGreen * j * 0.25f, this.particleBlue * j * 0.45f, this.particleAlpha ); - } - else - { - offX = 0; - offY = 0; - offZ = 0; - scale = 0.02; - tess.setColorRGBA_F( this.particleRed * j * 0.9f, this.particleGreen * j * 0.65f, this.particleBlue * j * 0.85f, this.particleAlpha ); - } + double x = (this.prevPosX + (this.posX - this.prevPosX) * l - interpPosX) + - offX; + double y = (this.prevPosY + (this.posY - this.prevPosY) * l - interpPosY) + - offY; + double z = (this.prevPosZ + (this.posZ - this.prevPosZ) * l - interpPosZ) + - offZ; - for( int cycle = 0; cycle < 3; cycle++ ) - { - this.clear(); + for (int s = 0; s < LightningFX.STEPS; s++) { + final double xN = x + this.precomputedSteps[s][0]; + final double yN = y + this.precomputedSteps[s][1]; + final double zN = z + this.precomputedSteps[s][2]; - double x = ( this.prevPosX + ( this.posX - this.prevPosX ) * l - interpPosX ) - offX; - double y = ( this.prevPosY + ( this.posY - this.prevPosY ) * l - interpPosY ) - offY; - double z = ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * l - interpPosZ ) - offZ; + final double xD = xN - x; + final double yD = yN - y; + final double zD = zN - z; - for( int s = 0; s < LightningFX.STEPS; s++ ) - { - final double xN = x + this.precomputedSteps[s][0]; - final double yN = y + this.precomputedSteps[s][1]; - final double zN = z + this.precomputedSteps[s][2]; + if (cycle == 0) { + ox = (yD * 0) - (1 * zD); + oy = (zD * 0) - (0 * xD); + oz = (xD * 1) - (0 * yD); + } + if (cycle == 1) { + ox = (yD * 1) - (0 * zD); + oy = (zD * 0) - (1 * xD); + oz = (xD * 0) - (0 * yD); + } + if (cycle == 2) { + ox = (yD * 0) - (0 * zD); + oy = (zD * 1) - (0 * xD); + oz = (xD * 0) - (1 * yD); + } - final double xD = xN - x; - final double yD = yN - y; - final double zD = zN - z; + final double ss = Math.sqrt(ox * ox + oy * oy + oz * oz) + / ((((double) LightningFX.STEPS - (double) s) / LightningFX.STEPS) + * scale); + ox /= ss; + oy /= ss; + oz /= ss; - if( cycle == 0 ) - { - ox = ( yD * 0 ) - ( 1 * zD ); - oy = ( zD * 0 ) - ( 0 * xD ); - oz = ( xD * 1 ) - ( 0 * yD ); - } - if( cycle == 1 ) - { - ox = ( yD * 1 ) - ( 0 * zD ); - oy = ( zD * 0 ) - ( 1 * xD ); - oz = ( xD * 0 ) - ( 0 * yD ); - } - if( cycle == 2 ) - { - ox = ( yD * 0 ) - ( 0 * zD ); - oy = ( zD * 1 ) - ( 0 * xD ); - oz = ( xD * 0 ) - ( 1 * yD ); - } + a[0] = x + ox; + a[1] = y + oy; + a[2] = z + oz; - final double ss = Math.sqrt( ox * ox + oy * oy + oz * oz ) / ( ( ( (double) LightningFX.STEPS - (double) s ) / LightningFX.STEPS ) * scale ); - ox /= ss; - oy /= ss; - oz /= ss; + b[0] = x; + b[1] = y; + b[2] = z; - a[0] = x + ox; - a[1] = y + oy; - a[2] = z + oz; + this.draw(tess, a, b, f6, f8); - b[0] = x; - b[1] = y; - b[2] = z; + x = xN; + y = yN; + z = zN; + } + } + } + } - this.draw( tess, a, b, f6, f8 ); + private void clear() { + this.hasData = false; + } - x = xN; - y = yN; - z = zN; - } - } - } - } + private void draw( + final Tessellator tess, + final double[] a, + final double[] b, + final double f6, + final double f8 + ) { + if (this.hasData) { + tess.addVertexWithUV(a[0], a[1], a[2], f6, f8); + tess.addVertexWithUV( + this.vertices[0], this.vertices[1], this.vertices[2], f6, f8 + ); + tess.addVertexWithUV( + this.verticesWithUV[0], + this.verticesWithUV[1], + this.verticesWithUV[2], + f6, + f8 + ); + tess.addVertexWithUV(b[0], b[1], b[2], f6, f8); + } - private void clear() - { - this.hasData = false; - } + this.hasData = true; - private void draw( final Tessellator tess, final double[] a, final double[] b, final double f6, final double f8 ) - { - if( this.hasData ) - { - tess.addVertexWithUV( a[0], a[1], a[2], f6, f8 ); - tess.addVertexWithUV( this.vertices[0], this.vertices[1], this.vertices[2], f6, f8 ); - tess.addVertexWithUV( this.verticesWithUV[0], this.verticesWithUV[1], this.verticesWithUV[2], f6, f8 ); - tess.addVertexWithUV( b[0], b[1], b[2], f6, f8 ); - } + for (int x = 0; x < 3; x++) { + this.vertices[x] = a[x]; + this.verticesWithUV[x] = b[x]; + } + } - this.hasData = true; - - for( int x = 0; x < 3; x++ ) - { - this.vertices[x] = a[x]; - this.verticesWithUV[x] = b[x]; - } - } - - protected double[][] getPrecomputedSteps() - { - return this.precomputedSteps; - } + protected double[][] getPrecomputedSteps() { + return this.precomputedSteps; + } } diff --git a/src/main/java/appeng/client/render/effects/MatterCannonFX.java b/src/main/java/appeng/client/render/effects/MatterCannonFX.java index b1045eb9..54ebf875 100644 --- a/src/main/java/appeng/client/render/effects/MatterCannonFX.java +++ b/src/main/java/appeng/client/render/effects/MatterCannonFX.java @@ -18,7 +18,6 @@ package appeng.client.render.effects; - import appeng.client.texture.ExtraBlockTextures; import net.minecraft.client.particle.EntityBreakingFX; import net.minecraft.client.renderer.Tessellator; @@ -27,65 +26,104 @@ import net.minecraft.util.IIcon; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class MatterCannonFX extends EntityBreakingFX { + private final IIcon particleTextureIndex; -public class MatterCannonFX extends EntityBreakingFX -{ + public MatterCannonFX( + final World par1World, + final double par2, + final double par4, + final double par6, + final Item par8Item + ) { + super(par1World, par2, par4, par6, par8Item); + this.particleGravity = 0; + this.particleBlue = 255; + this.particleGreen = 255; + this.particleRed = 255; + this.particleAlpha = 1.4f; + this.particleScale = 1.1f; + this.motionX = 0.0f; + this.motionY = 0.0f; + this.motionZ = 0.0f; + this.particleTextureIndex + = ExtraBlockTextures.BlockMatterCannonParticle.getIcon(); + this.noClip = true; + } - private final IIcon particleTextureIndex; + public void fromItem(final ForgeDirection d) { + this.particleScale *= 1.2f; + } - public MatterCannonFX( final World par1World, final double par2, final double par4, final double par6, final Item par8Item ) - { - super( par1World, par2, par4, par6, par8Item ); - this.particleGravity = 0; - this.particleBlue = 255; - this.particleGreen = 255; - this.particleRed = 255; - this.particleAlpha = 1.4f; - this.particleScale = 1.1f; - this.motionX = 0.0f; - this.motionY = 0.0f; - this.motionZ = 0.0f; - this.particleTextureIndex = ExtraBlockTextures.BlockMatterCannonParticle.getIcon(); - this.noClip = true; - } + @Override + public void onUpdate() { + super.onUpdate(); + this.particleScale *= 1.19f; + this.particleAlpha *= 0.59f; + } - public void fromItem( final ForgeDirection d ) - { - this.particleScale *= 1.2f; - } + @Override + public int getFXLayer() { + return 1; + } - @Override - public void onUpdate() - { - super.onUpdate(); - this.particleScale *= 1.19f; - this.particleAlpha *= 0.59f; - } + @Override + public void renderParticle( + final Tessellator par1Tessellator, + final float par2, + final float par3, + final float par4, + final float par5, + final float par6, + final float par7 + ) { + final float f6 = this.particleTextureIndex.getMinU(); + final float f7 = this.particleTextureIndex.getMaxU(); + final float f8 = this.particleTextureIndex.getMinV(); + final float f9 = this.particleTextureIndex.getMaxV(); + final float f10 = 0.05F * this.particleScale; - @Override - public int getFXLayer() - { - return 1; - } + final float f11 + = (float) (this.prevPosX + (this.posX - this.prevPosX) * par2 - interpPosX); + final float f12 + = (float) (this.prevPosY + (this.posY - this.prevPosY) * par2 - interpPosY); + final float f13 + = (float) (this.prevPosZ + (this.posZ - this.prevPosZ) * par2 - interpPosZ); + final float f14 = 1.0F; - @Override - public void renderParticle( final Tessellator par1Tessellator, final float par2, final float par3, final float par4, final float par5, final float par6, final float par7 ) - { - final float f6 = this.particleTextureIndex.getMinU(); - final float f7 = this.particleTextureIndex.getMaxU(); - final float f8 = this.particleTextureIndex.getMinV(); - final float f9 = this.particleTextureIndex.getMaxV(); - final float f10 = 0.05F * this.particleScale; - - final float f11 = (float) ( this.prevPosX + ( this.posX - this.prevPosX ) * par2 - interpPosX ); - final float f12 = (float) ( this.prevPosY + ( this.posY - this.prevPosY ) * par2 - interpPosY ); - final float f13 = (float) ( this.prevPosZ + ( this.posZ - this.prevPosZ ) * par2 - interpPosZ ); - final 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.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/VibrantFX.java b/src/main/java/appeng/client/render/effects/VibrantFX.java index 57b413f6..82c21424 100644 --- a/src/main/java/appeng/client/render/effects/VibrantFX.java +++ b/src/main/java/appeng/client/render/effects/VibrantFX.java @@ -18,59 +18,59 @@ package appeng.client.render.effects; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.particle.EntityFX; import net.minecraft.world.World; +@SideOnly(Side.CLIENT) +public class VibrantFX extends EntityFX { + public VibrantFX( + final World par1World, + final double x, + final double y, + final double z, + final double par8, + final double par10, + final double par12 + ) { + super(par1World, x, y, z, par8, par10, par12); + final float f = this.rand.nextFloat() * 0.1F + 0.8F; + this.particleRed = f * 0.7f; + this.particleGreen = f * 0.89f; + this.particleBlue = f * 0.9f; + this.setParticleTextureIndex(0); + this.setSize(0.04F, 0.04F); + this.particleScale *= this.rand.nextFloat() * 0.6F + 1.9F; + this.motionX = 0.0D; + this.motionY = 0.0D; + this.motionZ = 0.0D; + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.particleMaxAge = (int) (20.0D / (Math.random() * 0.8D + 0.1D)); + this.noClip = true; + } -@SideOnly( Side.CLIENT ) -public class VibrantFX extends EntityFX -{ + @Override + public float getBrightness(final float par1) { + return 1.0f; + } - public VibrantFX( final World par1World, final double x, final double y, final double z, final double par8, final double par10, final double par12 ) - { - super( par1World, x, y, z, par8, par10, par12 ); - final float f = this.rand.nextFloat() * 0.1F + 0.8F; - this.particleRed = f * 0.7f; - this.particleGreen = f * 0.89f; - this.particleBlue = f * 0.9f; - this.setParticleTextureIndex( 0 ); - this.setSize( 0.04F, 0.04F ); - this.particleScale *= this.rand.nextFloat() * 0.6F + 1.9F; - this.motionX = 0.0D; - this.motionY = 0.0D; - this.motionZ = 0.0D; - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.particleMaxAge = (int) ( 20.0D / ( Math.random() * 0.8D + 0.1D ) ); - this.noClip = true; - } + /** + * Called to update the entity's position/logic. + */ + @Override + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + // this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.particleScale *= 0.95; - @Override - public float getBrightness( final float par1 ) - { - return 1.0f; - } - - /** - * Called to update the entity's position/logic. - */ - @Override - public void onUpdate() - { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - // this.moveEntity(this.motionX, this.motionY, this.motionZ); - this.particleScale *= 0.95; - - if( this.particleMaxAge <= 0 || this.particleScale < 0.1 ) - { - this.setDead(); - } - this.particleMaxAge--; - } + if (this.particleMaxAge <= 0 || this.particleScale < 0.1) { + this.setDead(); + } + this.particleMaxAge--; + } } diff --git a/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java b/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java index 7c268b6c..abbf9e31 100644 --- a/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java +++ b/src/main/java/appeng/client/render/items/ItemEncodedPatternRenderer.java @@ -18,7 +18,6 @@ package appeng.client.render.items; - import appeng.items.misc.ItemEncodedPattern; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderHelper; @@ -28,52 +27,51 @@ import net.minecraftforge.client.IItemRenderer; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.GL11; +public class ItemEncodedPatternRenderer implements IItemRenderer { + private final RenderItem ri = new RenderItem(); + private boolean recursive = false; -public class ItemEncodedPatternRenderer implements IItemRenderer -{ + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + final boolean isShiftHeld = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) + || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT); - private final RenderItem ri = new RenderItem(); - private boolean recursive = false; + if (!this.recursive && type == IItemRenderer.ItemRenderType.INVENTORY + && isShiftHeld) { + final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - final boolean isShiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); + if (iep.getOutput(item) != null) { + return true; + } + } - if( !this.recursive && type == IItemRenderer.ItemRenderType.INVENTORY && isShiftHeld ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); + return false; + } - if( iep.getOutput( item ) != null ) - { - return true; - } - } + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper + ) { + return false; + } - return false; - } + @Override + public void + renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + this.recursive = true; - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return false; - } + final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); + final ItemStack is = iep.getOutput(item); + final Minecraft mc = Minecraft.getMinecraft(); - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - this.recursive = true; + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); + RenderHelper.enableGUIStandardItemLighting(); + this.ri.renderItemAndEffectIntoGUI( + mc.fontRenderer, mc.getTextureManager(), is, 0, 0 + ); + RenderHelper.disableStandardItemLighting(); + GL11.glPopAttrib(); - final ItemEncodedPattern iep = (ItemEncodedPattern) item.getItem(); - final ItemStack is = iep.getOutput( item ); - final Minecraft mc = Minecraft.getMinecraft(); - - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); - RenderHelper.enableGUIStandardItemLighting(); - this.ri.renderItemAndEffectIntoGUI( mc.fontRenderer, mc.getTextureManager(), is, 0, 0 ); - RenderHelper.disableStandardItemLighting(); - GL11.glPopAttrib(); - - this.recursive = false; - } + this.recursive = false; + } } diff --git a/src/main/java/appeng/client/render/items/PaintBallRender.java b/src/main/java/appeng/client/render/items/PaintBallRender.java index eb2cc616..c1d5b399 100644 --- a/src/main/java/appeng/client/render/items/PaintBallRender.java +++ b/src/main/java/appeng/client/render/items/PaintBallRender.java @@ -18,7 +18,6 @@ package appeng.client.render.items; - import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; import appeng.items.misc.ItemPaintBall; @@ -29,111 +28,109 @@ import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; +public class PaintBallRender implements IItemRenderer { + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } -public class PaintBallRender implements IItemRenderer -{ + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper + ) { + return helper == ItemRendererHelper.ENTITY_BOBBING + || helper == ItemRendererHelper.ENTITY_ROTATION; + } - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } + @Override + public void + renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + final IIcon par2Icon; - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; - } + if (item.getItemDamage() < 20) { + par2Icon = item.getIconIndex(); + } else { + par2Icon = ExtraItemTextures.ItemPaintBallShimmer.getIcon(); + } - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - final IIcon par2Icon; + final float f4 = par2Icon.getMinU(); + final float f5 = par2Icon.getMaxU(); + final float f6 = par2Icon.getMinV(); + final float f7 = par2Icon.getMaxV(); - if( item.getItemDamage() < 20 ) - { - par2Icon = item.getIconIndex(); - } - else - { - par2Icon = ExtraItemTextures.ItemPaintBallShimmer.getIcon(); - } + final ItemPaintBall ipb = (ItemPaintBall) item.getItem(); - final float f4 = par2Icon.getMinU(); - final float f5 = par2Icon.getMaxU(); - final float f6 = par2Icon.getMinV(); - final float f7 = par2Icon.getMaxV(); + final Tessellator tessellator = Tessellator.instance; - final ItemPaintBall ipb = (ItemPaintBall) item.getItem(); + GL11.glPushMatrix(); - final Tessellator tessellator = Tessellator.instance; + final AEColor col = ipb.getColor(item); - GL11.glPushMatrix(); + final int colorValue + = item.getItemDamage() >= 20 ? col.mediumVariant : col.mediumVariant; + final int r = (colorValue >> 16) & 0xff; + final int g = (colorValue >> 8) & 0xff; + final int b = (colorValue) &0xff; - final AEColor col = ipb.getColor( item ); + if (item.getItemDamage() >= 20) { + final float fail = 0.7f; + final int full = (int) (255 * 0.3); + 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); + } - final int colorValue = item.getItemDamage() >= 20 ? col.mediumVariant : col.mediumVariant; - final int r = ( colorValue >> 16 ) & 0xff; - final int g = ( colorValue >> 8 ) & 0xff; - final int b = ( colorValue ) & 0xff; + if (type == ItemRenderType.INVENTORY) { + GL11.glScalef(16F, 16F, 10F); + GL11.glTranslatef(0.0F, 1.0F, 0.0F); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + GL11.glEnable(GL11.GL_ALPHA_TEST); - if( item.getItemDamage() >= 20 ) - { - final float fail = 0.7f; - final int full = (int) ( 255 * 0.3 ); - 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 ); - } + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(1, 0, 0, f5, f7); + tessellator.addVertexWithUV(1, 1, 0, f5, f6); + tessellator.addVertexWithUV(0, 1, 0, f4, f6); + tessellator.draw(); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(0.0F, 0.0F, 0.0F); + } else { + GL11.glTranslatef(-0.5F, -0.3F, 0.01F); + } + final float f12 = 0.0625F; + ItemRenderer.renderItemIn2D( + tessellator, + f5, + f6, + f4, + f7, + par2Icon.getIconWidth(), + par2Icon.getIconHeight(), + f12 + ); - if( type == ItemRenderType.INVENTORY ) - { - GL11.glScalef( 16F, 16F, 10F ); - GL11.glTranslatef( 0.0F, 1.0F, 0.0F ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(1F, 1.1F, 1F); + GL11.glTranslatef(0.0F, 1.07F, f12 / -2.0f); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + } - tessellator.startDrawingQuads(); - tessellator.setNormal( 0.0F, 1.0F, 0.0F ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 1, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 1, 1, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 1, 0, f4, f6 ); - tessellator.draw(); - } - else - { - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); - } - else - { - GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); - } - final float f12 = 0.0625F; - ItemRenderer.renderItemIn2D( tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12 ); + GL11.glColor4f(1, 1, 1, 1.0F); - GL11.glDisable( GL11.GL_CULL_FACE ); - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 1F, 1.1F, 1F ); - GL11.glTranslatef( 0.0F, 1.07F, f12 / -2.0f ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - } + if (type == ItemRenderType.INVENTORY) { + GL11.glDisable(GL11.GL_ALPHA_TEST); + } else { + GL11.glEnable(GL11.GL_CULL_FACE); + } - GL11.glColor4f( 1, 1, 1, 1.0F ); - - if( type == ItemRenderType.INVENTORY ) - { - GL11.glDisable( GL11.GL_ALPHA_TEST ); - } - else - { - GL11.glEnable( GL11.GL_CULL_FACE ); - } - - GL11.glPopMatrix(); - } + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java b/src/main/java/appeng/client/render/items/ToolBiometricCardRender.java index 2cb81840..b181a47e 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 appeng.api.implementations.items.IBiometricCard; import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; @@ -30,130 +29,129 @@ import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; +public class ToolBiometricCardRender implements IItemRenderer { + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } -public class ToolBiometricCardRender implements IItemRenderer -{ + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper + ) { + return helper == ItemRendererHelper.ENTITY_BOBBING + || helper == ItemRendererHelper.ENTITY_ROTATION; + } - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } + @Override + public void + renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + final IIcon par2Icon = item.getIconIndex(); - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; - } + final float f4 = par2Icon.getMinU(); + final float f5 = par2Icon.getMaxU(); + final float f6 = par2Icon.getMinV(); + final float f7 = par2Icon.getMaxV(); - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - final IIcon par2Icon = item.getIconIndex(); + final Tessellator tessellator = Tessellator.instance; - final float f4 = par2Icon.getMinU(); - final float f5 = par2Icon.getMaxU(); - final float f6 = par2Icon.getMinV(); - final float f7 = par2Icon.getMaxV(); + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); - final Tessellator tessellator = Tessellator.instance; + if (type == ItemRenderType.INVENTORY) { + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(16F, 16F, 10F); + GL11.glTranslatef(0.0F, 1.0F, 0.0F); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(1, 0, 0, f5, f7); + tessellator.addVertexWithUV(1, 1, 0, f5, f6); + tessellator.addVertexWithUV(0, 1, 0, f4, f6); + tessellator.draw(); + } else { + GL11.glTranslatef(-0.5F, -0.3F, 0.01F); + final float f12 = 0.0625F; + ItemRenderer.renderItemIn2D( + tessellator, + f5, + f6, + f4, + f7, + par2Icon.getIconWidth(), + par2Icon.getIconHeight(), + f12 + ); - if( type == ItemRenderType.INVENTORY ) - { - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 16F, 16F, 10F ); - GL11.glTranslatef( 0.0F, 1.0F, 0.0F ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(1F, 1.1F, 1F); + GL11.glTranslatef(0.0F, 1.07F, f12 / -2.0f); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + } - tessellator.startDrawingQuads(); - tessellator.setNormal( 0.0F, 1.0F, 0.0F ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 1, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 1, 1, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 1, 0, f4, f6 ); - tessellator.draw(); - } - else - { - GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); - final float f12 = 0.0625F; - ItemRenderer.renderItemIn2D( tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12 ); + final float u = ExtraItemTextures.White.getIcon().getInterpolatedU(8.1); + final float v = ExtraItemTextures.White.getIcon().getInterpolatedV(8.1); - GL11.glDisable( GL11.GL_CULL_FACE ); - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 1F, 1.1F, 1F ); - GL11.glTranslatef( 0.0F, 1.07F, f12 / -2.0f ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - } + String username = ""; - final float u = ExtraItemTextures.White.getIcon().getInterpolatedU( 8.1 ); - final float v = ExtraItemTextures.White.getIcon().getInterpolatedV( 8.1 ); + if (item.getItem() instanceof IBiometricCard) { + final GameProfile gp = ((IBiometricCard) item.getItem()).getProfile(item); + if (gp != null) { + username = gp.getName(); + } + } + final int hash = username.length() > 0 ? username.hashCode() : 0; - String username = ""; + GL11.glScalef(1F / 16F, 1F / 16F, 1F); + GL11.glTranslatef(4, 6, 0); + GL11.glDisable(GL11.GL_LIGHTING); - if( item.getItem() instanceof IBiometricCard ) - { - final GameProfile gp = ( (IBiometricCard) item.getItem() ).getProfile( item ); - if( gp != null ) - { - username = gp.getName(); - } - } - final int hash = username.length() > 0 ? username.hashCode() : 0; + tessellator.startDrawingQuads(); - GL11.glScalef( 1F / 16F, 1F / 16F, 1F ); - GL11.glTranslatef( 4, 6, 0 ); - GL11.glDisable( GL11.GL_LIGHTING ); + AEColor col = AEColor.values()[Math.abs(3 + hash) % AEColor.values().length]; + if (hash == 0) { + col = AEColor.Black; + } - tessellator.startDrawingQuads(); + final float z = 0; - AEColor col = AEColor.values()[Math.abs( 3 + hash ) % AEColor.values().length]; - if( hash == 0 ) - { - col = AEColor.Black; - } + for (int x = 0; x < 8; x++) // 8 + { + for (int y = 0; y < 6; y++) // 6 + { + boolean isLit = false; - final float z = 0; + if (x == 0 || y == 0 || x == 7 || y == 5) { + isLit = false; + } else { + isLit = (hash & (1 << x)) != 0 || (hash & (1 << y)) != 0; + } - for( int x = 0; x < 8; x++ )// 8 - { - for( int y = 0; y < 6; y++ )// 6 - { - boolean isLit = false; + if (isLit) { + tessellator.setColorOpaque_I(col.mediumVariant); + } else { + final float scale = 0.3f / 255.0f; + tessellator.setColorOpaque_F( + ((col.blackVariant >> 16) & 0xff) * scale, + ((col.blackVariant >> 8) & 0xff) * scale, + (col.blackVariant & 0xff) * scale + ); + } - if( x == 0 || y == 0 || x == 7 || y == 5 ) - { - isLit = false; - } - else - { - isLit = ( hash & ( 1 << x ) ) != 0 || ( hash & ( 1 << y ) ) != 0; - } + tessellator.addVertexWithUV(x, y, z, u, v); + tessellator.addVertexWithUV(x + 1, y, z, u, v); + tessellator.addVertexWithUV(x + 1, y + 1, z, u, v); + tessellator.addVertexWithUV(x, y + 1, z, u, v); + } + } - if( isLit ) - { - tessellator.setColorOpaque_I( col.mediumVariant ); - } - else - { - final float scale = 0.3f / 255.0f; - tessellator.setColorOpaque_F( ( ( col.blackVariant >> 16 ) & 0xff ) * scale, ( ( col.blackVariant >> 8 ) & 0xff ) * scale, ( col.blackVariant & 0xff ) * scale ); - } + tessellator.draw(); - tessellator.addVertexWithUV( x, y, z, u, v ); - tessellator.addVertexWithUV( x + 1, y, z, u, v ); - tessellator.addVertexWithUV( x + 1, y + 1, z, u, v ); - tessellator.addVertexWithUV( x, y + 1, z, u, v ); - } - } - - tessellator.draw(); - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java b/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java index 4b845ccc..8bc719cd 100644 --- a/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java +++ b/src/main/java/appeng/client/render/items/ToolColorApplicatorRender.java @@ -18,7 +18,6 @@ package appeng.client.render.items; - import appeng.api.util.AEColor; import appeng.client.texture.ExtraItemTextures; import appeng.items.tools.powered.ToolColorApplicator; @@ -29,133 +28,130 @@ import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; import org.lwjgl.opengl.GL11; +public class ToolColorApplicatorRender implements IItemRenderer { + @Override + public boolean handleRenderType(final ItemStack item, final ItemRenderType type) { + return true; + } -public class ToolColorApplicatorRender implements IItemRenderer -{ + @Override + public boolean shouldUseRenderHelper( + final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper + ) { + return helper == ItemRendererHelper.ENTITY_BOBBING + || helper == ItemRendererHelper.ENTITY_ROTATION; + } - @Override - public boolean handleRenderType( final ItemStack item, final ItemRenderType type ) - { - return true; - } + @Override + public void + renderItem(final ItemRenderType type, final ItemStack item, final Object... data) { + final IIcon par2Icon = item.getIconIndex(); - @Override - public boolean shouldUseRenderHelper( final ItemRenderType type, final ItemStack item, final ItemRendererHelper helper ) - { - return helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION; - } + float f4 = par2Icon.getMinU(); + float f5 = par2Icon.getMaxU(); + float f6 = par2Icon.getMinV(); + float f7 = par2Icon.getMaxV(); - @Override - public void renderItem( final ItemRenderType type, final ItemStack item, final Object... data ) - { - final IIcon par2Icon = item.getIconIndex(); + final Tessellator tessellator = Tessellator.instance; - float f4 = par2Icon.getMinU(); - float f5 = par2Icon.getMaxU(); - float f6 = par2Icon.getMinV(); - float f7 = par2Icon.getMaxV(); + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT); - final Tessellator tessellator = Tessellator.instance; + if (type == ItemRenderType.INVENTORY) { + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(16F, 16F, 10F); + GL11.glTranslatef(0.0F, 1.0F, 0.0F); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glPushMatrix(); - GL11.glPushAttrib( GL11.GL_ENABLE_BIT | GL11.GL_COLOR_BUFFER_BIT ); + tessellator.startDrawingQuads(); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(1, 0, 0, f5, f7); + tessellator.addVertexWithUV(1, 1, 0, f5, f6); + tessellator.addVertexWithUV(0, 1, 0, f4, f6); + tessellator.draw(); + } else { + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) { + GL11.glTranslatef(0.0F, 0.0F, 0.0F); + } else if (type == ItemRenderType.EQUIPPED) { + GL11.glTranslatef(0.0F, 0.0F, 0.0F); + } else { + GL11.glTranslatef(-0.5F, -0.3F, 0.01F); + } + final float f12 = 0.0625F; + ItemRenderer.renderItemIn2D( + tessellator, + f5, + f6, + f4, + f7, + par2Icon.getIconWidth(), + par2Icon.getIconHeight(), + f12 + ); - if( type == ItemRenderType.INVENTORY ) - { - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( 16F, 16F, 10F ); - GL11.glTranslatef( 0.0F, 1.0F, 0.0F ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - GL11.glEnable( GL11.GL_ALPHA_TEST ); + GL11.glDisable(GL11.GL_CULL_FACE); + GL11.glColor4f(1, 1, 1, 1.0F); + GL11.glScalef(-1F, -1F, 1F); + GL11.glTranslatef(-1.125F, 0.0f, f12 / -2.0f); + GL11.glRotatef(180F, 1.0F, 0.0F, 0.0F); + } - tessellator.startDrawingQuads(); - tessellator.setNormal( 0.0F, 1.0F, 0.0F ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 1, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 1, 1, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 1, 0, f4, f6 ); - tessellator.draw(); - } - else - { - if( type == ItemRenderType.EQUIPPED_FIRST_PERSON ) - { - GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); - } - else if( type == ItemRenderType.EQUIPPED ) - { - GL11.glTranslatef( 0.0F, 0.0F, 0.0F ); - } - else - { - GL11.glTranslatef( -0.5F, -0.3F, 0.01F ); - } - final float f12 = 0.0625F; - ItemRenderer.renderItemIn2D( tessellator, f5, f6, f4, f7, par2Icon.getIconWidth(), par2Icon.getIconHeight(), f12 ); + final IIcon dark = ExtraItemTextures.ToolColorApplicatorTip_Dark.getIcon(); + final IIcon med = ExtraItemTextures.ToolColorApplicatorTip_Medium.getIcon(); + final IIcon light = ExtraItemTextures.ToolColorApplicatorTip_Light.getIcon(); - GL11.glDisable( GL11.GL_CULL_FACE ); - GL11.glColor4f( 1, 1, 1, 1.0F ); - GL11.glScalef( -1F, -1F, 1F ); - GL11.glTranslatef( -1.125F, 0.0f, f12 / -2.0f ); - GL11.glRotatef( 180F, 1.0F, 0.0F, 0.0F ); - } + GL11.glScalef(1F / 16F, 1F / 16F, 1F); - final IIcon dark = ExtraItemTextures.ToolColorApplicatorTip_Dark.getIcon(); - final IIcon med = ExtraItemTextures.ToolColorApplicatorTip_Medium.getIcon(); - final IIcon light = ExtraItemTextures.ToolColorApplicatorTip_Light.getIcon(); + if (type != ItemRenderType.INVENTORY) { + GL11.glTranslatef(2, 0, 0); + } - GL11.glScalef( 1F / 16F, 1F / 16F, 1F ); + GL11.glDisable(GL11.GL_LIGHTING); - if( type != ItemRenderType.INVENTORY ) - { - GL11.glTranslatef( 2, 0, 0 ); - } + final AEColor col = ((ToolColorApplicator) item.getItem()).getActiveColor(item); - GL11.glDisable( GL11.GL_LIGHTING ); + if (col != null) { + tessellator.startDrawingQuads(); - final AEColor col = ( (ToolColorApplicator) item.getItem() ).getActiveColor( item ); + f4 = dark.getMinU(); + f5 = dark.getMaxU(); + f6 = dark.getMinV(); + f7 = dark.getMaxV(); - if( col != null ) - { - tessellator.startDrawingQuads(); + tessellator.setColorOpaque_I(col.blackVariant); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(16, 0, 0, f5, f7); + tessellator.addVertexWithUV(16, 16, 0, f5, f6); + tessellator.addVertexWithUV(0, 16, 0, f4, f6); - f4 = dark.getMinU(); - f5 = dark.getMaxU(); - f6 = dark.getMinV(); - f7 = dark.getMaxV(); + f4 = light.getMinU(); + f5 = light.getMaxU(); + f6 = light.getMinV(); + f7 = light.getMaxV(); - tessellator.setColorOpaque_I( col.blackVariant ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 16, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 16, 16, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 16, 0, f4, f6 ); + tessellator.setColorOpaque_I(col.whiteVariant); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(16, 0, 0, f5, f7); + tessellator.addVertexWithUV(16, 16, 0, f5, f6); + tessellator.addVertexWithUV(0, 16, 0, f4, f6); - f4 = light.getMinU(); - f5 = light.getMaxU(); - f6 = light.getMinV(); - f7 = light.getMaxV(); + f4 = med.getMinU(); + f5 = med.getMaxU(); + f6 = med.getMinV(); + f7 = med.getMaxV(); - tessellator.setColorOpaque_I( col.whiteVariant ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 16, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 16, 16, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 16, 0, f4, f6 ); + tessellator.setColorOpaque_I(col.mediumVariant); + tessellator.addVertexWithUV(0, 0, 0, f4, f7); + tessellator.addVertexWithUV(16, 0, 0, f5, f7); + tessellator.addVertexWithUV(16, 16, 0, f5, f6); + tessellator.addVertexWithUV(0, 16, 0, f4, f6); - f4 = med.getMinU(); - f5 = med.getMaxU(); - f6 = med.getMinV(); - f7 = med.getMaxV(); + tessellator.draw(); + } - tessellator.setColorOpaque_I( col.mediumVariant ); - tessellator.addVertexWithUV( 0, 0, 0, f4, f7 ); - tessellator.addVertexWithUV( 16, 0, 0, f5, f7 ); - tessellator.addVertexWithUV( 16, 16, 0, f5, f6 ); - tessellator.addVertexWithUV( 0, 16, 0, f4, f6 ); - - tessellator.draw(); - } - - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } } diff --git a/src/main/java/appeng/client/render/model/ModelCompass.java b/src/main/java/appeng/client/render/model/ModelCompass.java index 4c03c9d8..d9ee7ed8 100644 --- a/src/main/java/appeng/client/render/model/ModelCompass.java +++ b/src/main/java/appeng/client/render/model/ModelCompass.java @@ -18,102 +18,96 @@ package appeng.client.render.model; - import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; +public class ModelCompass extends ModelBase { + private final ModelRenderer Ring1; + private final ModelRenderer Ring2; + private final ModelRenderer Ring3; + private final ModelRenderer Ring4; + private final ModelRenderer Middle; + private final ModelRenderer Base; -public class ModelCompass extends ModelBase -{ + private final ModelRenderer Pointer; - private final ModelRenderer Ring1; - private final ModelRenderer Ring2; - private final ModelRenderer Ring3; - private final ModelRenderer Ring4; - private final ModelRenderer Middle; - private final ModelRenderer Base; + public ModelCompass() { + this.textureWidth = 16; + this.textureHeight = 8; - private final ModelRenderer Pointer; + this.Ring1 = new ModelRenderer(this, 0, 0); + this.Ring1.addBox(0F, 0F, 0F, 4, 1, 1); + this.Ring1.setRotationPoint(-2F, 22F, 2F); + this.Ring1.setTextureSize(16, 8); + this.Ring1.mirror = true; + this.setRotation(this.Ring1, 0F, 0F, 0F); - public ModelCompass() - { - this.textureWidth = 16; - this.textureHeight = 8; + this.Ring2 = new ModelRenderer(this, 0, 0); + this.Ring2.addBox(0F, 0F, 0F, 1, 1, 4); + this.Ring2.setRotationPoint(-3F, 22F, -2F); + this.Ring2.setTextureSize(16, 8); + this.Ring2.mirror = true; + this.setRotation(this.Ring2, 0F, 0F, 0F); - this.Ring1 = new ModelRenderer( this, 0, 0 ); - this.Ring1.addBox( 0F, 0F, 0F, 4, 1, 1 ); - this.Ring1.setRotationPoint( -2F, 22F, 2F ); - this.Ring1.setTextureSize( 16, 8 ); - this.Ring1.mirror = true; - this.setRotation( this.Ring1, 0F, 0F, 0F ); + this.Ring3 = new ModelRenderer(this, 0, 0); + this.Ring3.addBox(0F, 0F, 0F, 4, 1, 1); + this.Ring3.setRotationPoint(-2F, 22F, -3F); + this.Ring3.setTextureSize(16, 8); + this.Ring3.mirror = true; + this.setRotation(this.Ring3, 0F, 0F, 0F); - this.Ring2 = new ModelRenderer( this, 0, 0 ); - this.Ring2.addBox( 0F, 0F, 0F, 1, 1, 4 ); - this.Ring2.setRotationPoint( -3F, 22F, -2F ); - this.Ring2.setTextureSize( 16, 8 ); - this.Ring2.mirror = true; - this.setRotation( this.Ring2, 0F, 0F, 0F ); + this.Ring4 = new ModelRenderer(this, 0, 0); + this.Ring4.addBox(0F, 0F, 0F, 1, 1, 4); + this.Ring4.setRotationPoint(2F, 22F, -2F); + this.Ring4.setTextureSize(16, 8); + this.Ring4.mirror = true; + this.setRotation(this.Ring4, 0F, 0F, 0F); - this.Ring3 = new ModelRenderer( this, 0, 0 ); - this.Ring3.addBox( 0F, 0F, 0F, 4, 1, 1 ); - this.Ring3.setRotationPoint( -2F, 22F, -3F ); - this.Ring3.setTextureSize( 16, 8 ); - this.Ring3.mirror = true; - this.setRotation( this.Ring3, 0F, 0F, 0F ); + this.Middle = new ModelRenderer(this, 0, 0); + this.Middle.addBox(0F, 0F, 0F, 1, 1, 1); + this.Middle.setRotationPoint(-0.5333334F, 22F, -0.5333334F); + this.Middle.setTextureSize(16, 8); + this.Middle.mirror = true; + this.setRotation(this.Middle, 0F, 0F, 0F); - this.Ring4 = new ModelRenderer( this, 0, 0 ); - this.Ring4.addBox( 0F, 0F, 0F, 1, 1, 4 ); - this.Ring4.setRotationPoint( 2F, 22F, -2F ); - this.Ring4.setTextureSize( 16, 8 ); - this.Ring4.mirror = true; - this.setRotation( this.Ring4, 0F, 0F, 0F ); + this.Pointer = new ModelRenderer(this, 0, 0); + this.Pointer.setTextureOffset(0, 5); + this.Pointer.addBox(-0.5F, 0F, 0F, 1, 1, 2); + this.Pointer.setRotationPoint(0.5F, 22.5F, 0.5F); + this.Pointer.setTextureSize(16, 8); + this.Pointer.mirror = true; + this.Pointer.offsetZ = -0.034f; + this.Pointer.offsetX = -0.034f; + this.setRotation(this.Pointer, 0F, 0F, 0F); - this.Middle = new ModelRenderer( this, 0, 0 ); - this.Middle.addBox( 0F, 0F, 0F, 1, 1, 1 ); - this.Middle.setRotationPoint( -0.5333334F, 22F, -0.5333334F ); - this.Middle.setTextureSize( 16, 8 ); - this.Middle.mirror = true; - this.setRotation( this.Middle, 0F, 0F, 0F ); + this.Base = new ModelRenderer(this, 0, 0); + this.Base.addBox(0F, 0F, 0F, 4, 1, 4); + this.Base.setRotationPoint(-2F, 23F, -2F); + this.Base.setTextureSize(16, 8); + this.Base.mirror = true; + this.setRotation(this.Base, 0F, 0F, 0F); + } - this.Pointer = new ModelRenderer( this, 0, 0 ); - this.Pointer.setTextureOffset( 0, 5 ); - this.Pointer.addBox( -0.5F, 0F, 0F, 1, 1, 2 ); - this.Pointer.setRotationPoint( 0.5F, 22.5F, 0.5F ); - this.Pointer.setTextureSize( 16, 8 ); - this.Pointer.mirror = true; - this.Pointer.offsetZ = -0.034f; - this.Pointer.offsetX = -0.034f; - this.setRotation( this.Pointer, 0F, 0F, 0F ); + private void + setRotation(final ModelRenderer model, final float x, final float y, final float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } - this.Base = new ModelRenderer( this, 0, 0 ); - this.Base.addBox( 0F, 0F, 0F, 4, 1, 4 ); - this.Base.setRotationPoint( -2F, 23F, -2F ); - this.Base.setTextureSize( 16, 8 ); - this.Base.mirror = true; - this.setRotation( this.Base, 0F, 0F, 0F ); - } + public void renderAll(final float rad) { + this.setRotation(this.Pointer, 0F, 0F, 0F); - private void setRotation( final ModelRenderer model, final float x, final float y, final float z ) - { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } + this.Pointer.rotateAngleY = rad; - public void renderAll( final float rad ) - { - this.setRotation( this.Pointer, 0F, 0F, 0F ); + this.Base.render(0.0625F); + this.Middle.render(0.0625F); - this.Pointer.rotateAngleY = rad; + this.Pointer.render(0.0625F); - this.Base.render( 0.0625F ); - this.Middle.render( 0.0625F ); - - this.Pointer.render( 0.0625F ); - - this.Ring1.render( 0.0625F ); - this.Ring2.render( 0.0625F ); - this.Ring3.render( 0.0625F ); - this.Ring4.render( 0.0625F ); - } + this.Ring1.render(0.0625F); + this.Ring2.render(0.0625F); + this.Ring3.render(0.0625F); + this.Ring4.render(0.0625F); + } } diff --git a/src/main/java/appeng/client/texture/CableBusTextures.java b/src/main/java/appeng/client/texture/CableBusTextures.java index d7c359b0..1566bcd0 100644 --- a/src/main/java/appeng/client/texture/CableBusTextures.java +++ b/src/main/java/appeng/client/texture/CableBusTextures.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; @@ -26,87 +25,176 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; +public enum CableBusTextures { + Channels00("MECableSmart00"), + Channels01("MECableSmart01"), + Channels02("MECableSmart02"), + Channels03("MECableSmart03"), + Channels10("MECableSmart10"), + Channels11("MECableSmart11"), + Channels12("MECableSmart12"), + Channels13("MECableSmart13"), + Channels14("MECableSmart14"), + Channels04("MECableSmart04"), -public enum CableBusTextures -{ + LevelEmitterTorchOn("ItemPart.LevelEmitterOn"), + BlockWirelessOn("BlockWirelessOn"), - Channels00( "MECableSmart00" ), Channels01( "MECableSmart01" ), Channels02( "MECableSmart02" ), Channels03( "MECableSmart03" ), Channels10( "MECableSmart10" ), Channels11( "MECableSmart11" ), Channels12( "MECableSmart12" ), Channels13( "MECableSmart13" ), Channels14( "MECableSmart14" ), Channels04( "MECableSmart04" ), + BlockP2PTunnel2("ItemPart.P2PTunnel2"), + BlockP2PTunnel3("ItemPart.P2PTunnel3"), - LevelEmitterTorchOn( "ItemPart.LevelEmitterOn" ), BlockWirelessOn( "BlockWirelessOn" ), + // MEWaiting("MEWaiting"), - BlockP2PTunnel2( "ItemPart.P2PTunnel2" ), BlockP2PTunnel3( "ItemPart.P2PTunnel3" ), + PartMonitorSides("PartMonitorSides"), + PartMonitorBack("PartMonitorBack"), - // MEWaiting("MEWaiting"), + Transparent("Transparent"), + PartMonitorSidesStatus("PartMonitorSidesStatus"), + PartMonitorSidesStatusLights("PartMonitorSidesStatusLights"), - PartMonitorSides( "PartMonitorSides" ), PartMonitorBack( "PartMonitorBack" ), + PartMonitor_Colored("PartMonitor_Colored"), + PartMonitor_Bright("PartMonitor_Bright"), - Transparent( "Transparent" ), PartMonitorSidesStatus( "PartMonitorSidesStatus" ), PartMonitorSidesStatusLights( "PartMonitorSidesStatusLights" ), + PartPatternTerm_Bright("PartPatternTerm_Bright"), + PartPatternTerm_Colored("PartPatternTerm_Colored"), + PartPatternTerm_Dark("PartPatternTerm_Dark"), - PartMonitor_Colored( "PartMonitor_Colored" ), PartMonitor_Bright( "PartMonitor_Bright" ), + PartConversionMonitor_Bright("PartConversionMonitor_Bright"), + PartConversionMonitor_Colored("PartConversionMonitor_Colored"), + PartConversionMonitor_Dark("PartConversionMonitor_Dark"), + PartConversionMonitor_Dark_Locked("PartConversionMonitor_Dark_Locked"), - PartPatternTerm_Bright( "PartPatternTerm_Bright" ), PartPatternTerm_Colored( "PartPatternTerm_Colored" ), PartPatternTerm_Dark( "PartPatternTerm_Dark" ), + PartInterfaceTerm_Bright("PartInterfaceTerm_Bright"), + PartInterfaceTerm_Colored("PartInterfaceTerm_Colored"), + PartInterfaceTerm_Dark("PartInterfaceTerm_Dark"), - PartConversionMonitor_Bright( "PartConversionMonitor_Bright" ), PartConversionMonitor_Colored( "PartConversionMonitor_Colored" ), PartConversionMonitor_Dark( "PartConversionMonitor_Dark" ), PartConversionMonitor_Dark_Locked( "PartConversionMonitor_Dark_Locked" ), + PartCraftingTerm_Bright("PartCraftingTerm_Bright"), + PartCraftingTerm_Colored("PartCraftingTerm_Colored"), + PartCraftingTerm_Dark("PartCraftingTerm_Dark"), // - PartInterfaceTerm_Bright( "PartInterfaceTerm_Bright" ), PartInterfaceTerm_Colored( "PartInterfaceTerm_Colored" ), PartInterfaceTerm_Dark( "PartInterfaceTerm_Dark" ), + PartStorageMonitor_Bright("PartStorageMonitor_Bright"), + PartStorageMonitor_Colored("PartStorageMonitor_Colored"), + PartStorageMonitor_Dark("PartStorageMonitor_Dark"), + PartStorageMonitor_Colored_Locked("PartStorageMonitor_Colored_Locked"), - PartCraftingTerm_Bright( "PartCraftingTerm_Bright" ), PartCraftingTerm_Colored( "PartCraftingTerm_Colored" ), PartCraftingTerm_Dark( "PartCraftingTerm_Dark" ), // + PartTerminal_Bright("PartTerminal_Bright"), + PartTerminal_Colored("PartTerminal_Colored"), + PartTerminal_Dark("PartTerminal_Dark"), - PartStorageMonitor_Bright( "PartStorageMonitor_Bright" ), PartStorageMonitor_Colored( "PartStorageMonitor_Colored" ), PartStorageMonitor_Dark( "PartStorageMonitor_Dark" ), PartStorageMonitor_Colored_Locked( "PartStorageMonitor_Colored_Locked" ), + 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"), - PartTerminal_Bright( "PartTerminal_Bright" ), PartTerminal_Colored( "PartTerminal_Colored" ), PartTerminal_Dark( "PartTerminal_Dark" ), + 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"), - 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" ), + 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"), - 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" ), + 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"), - 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" ), + BlockAnnihilationPlaneOn("BlockAnnihilationPlaneOn"), - 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" ), + BlockFormPlaneOn("BlockFormPlaneOn"), - BlockAnnihilationPlaneOn( "BlockAnnihilationPlaneOn" ), + BlockIdentityAnnihilationPlaneOn("BlockIdentityAnnihilationPlaneOn"), - BlockFormPlaneOn( "BlockFormPlaneOn" ), + ItemPartLevelEmitterOn("ItemPart.LevelEmitterOn"), + PartTransitionPlaneBack("PartTransitionPlaneBack"), - BlockIdentityAnnihilationPlaneOn( "BlockIdentityAnnihilationPlaneOn" ), + PartTunnelSides("PartTunnelSides"), + PartPlaneSides("PartPlaneSides"), + PartExportSides("PartExportSides"), + PartImportSides("PartImportSides"), - ItemPartLevelEmitterOn( "ItemPart.LevelEmitterOn" ), PartTransitionPlaneBack( "PartTransitionPlaneBack" ), + PartWirelessSides("PartWirelessSides"), + PartStorageSides("PartStorageSides"), + PartStorageBack("PartStorageBack"); - PartTunnelSides( "PartTunnelSides" ), PartPlaneSides( "PartPlaneSides" ), PartExportSides( "PartExportSides" ), PartImportSides( "PartImportSides" ), + private final String name; + public IIcon IIcon; - PartWirelessSides( "PartWirelessSides" ), PartStorageSides( "PartStorageSides" ), PartStorageBack( "PartStorageBack" ); + CableBusTextures(final String name) { + this.name = name; + } - private final String name; - public IIcon IIcon; + public static ResourceLocation GuiTexture(final String string) { + return null; + } - CableBusTextures( final String name ) - { - this.name = name; - } + @SideOnly(Side.CLIENT) + public static IIcon getMissing() { + return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( + TextureMap.locationBlocksTexture + )) + .getAtlasSprite("missingno"); + } - public static ResourceLocation GuiTexture( final String string ) - { - return null; - } + public String getName() { + return this.name; + } - @SideOnly( Side.CLIENT ) - public static IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture ) ).getAtlasSprite( "missingno" ); - } + public IIcon getIcon() { + return this.IIcon; + } - public String getName() - { - return this.name; - } - - public IIcon getIcon() - { - return this.IIcon; - } - - public void registerIcon( final TextureMap map ) - { - this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); - } + public void registerIcon(final TextureMap map) { + this.IIcon = map.registerIcon("appliedenergistics2:" + this.name); + } } diff --git a/src/main/java/appeng/client/texture/ExtraBlockTextures.java b/src/main/java/appeng/client/texture/ExtraBlockTextures.java index 83463abb..ef00a137 100644 --- a/src/main/java/appeng/client/texture/ExtraBlockTextures.java +++ b/src/main/java/appeng/client/texture/ExtraBlockTextures.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import jdk.nashorn.internal.ir.Block; @@ -27,100 +26,154 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; +public enum ExtraBlockTextures { + BlockVibrationChamberFrontOn("BlockVibrationChamberFrontOn"), -public enum ExtraBlockTextures -{ - 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" ), + Controller0("Controller0"), + Controller1("Controller1"), + Controller2("Controller2"), + Controller3("Controller3"), + Controller4("Controller4"), + Controller5("BlockLegacyControllerFront"), + ControllerLinked("ControllerLinked"); - Controller0("Controller0"), Controller1("Controller1"), Controller2("Controller2"), Controller3("Controller3"), Controller4("Controller4"), Controller5("BlockLegacyControllerFront"), ControllerLinked("ControllerLinked"); + private final String name; + private IIcon IIcon; - private final String name; - private IIcon IIcon; + ExtraBlockTextures(final String name) { + this.name = name; + } - ExtraBlockTextures( final String name ) - { - this.name = name; - } + public static ResourceLocation GuiTexture(final String string) { + return new ResourceLocation("appliedenergistics2", "textures/" + string); + } - public static ResourceLocation GuiTexture( final 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"); + } - @SideOnly( Side.CLIENT ) - public static IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationBlocksTexture ) ).getAtlasSprite( "missingno" ); - } + public String getName() { + return this.name; + } - public String getName() - { - return this.name; - } + public IIcon getIcon() { + return this.IIcon; + } - public IIcon getIcon() - { - return this.IIcon; - } - - public void registerIcon( final TextureMap map ) - { - this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); - } + public void registerIcon(final TextureMap map) { + this.IIcon = map.registerIcon("appliedenergistics2:" + this.name); + } } diff --git a/src/main/java/appeng/client/texture/ExtraItemTextures.java b/src/main/java/appeng/client/texture/ExtraItemTextures.java index 0940d125..d9d9dc3e 100644 --- a/src/main/java/appeng/client/texture/ExtraItemTextures.java +++ b/src/main/java/appeng/client/texture/ExtraItemTextures.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.Minecraft; @@ -26,48 +25,44 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; +public enum ExtraItemTextures { + White("White"), + ItemPaintBallShimmer("ItemPaintBallShimmer"), -public enum ExtraItemTextures -{ - 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" ); + private final String name; + private IIcon IIcon; - private final String name; - private IIcon IIcon; + ExtraItemTextures(final String name) { + this.name = name; + } - ExtraItemTextures( final String name ) - { - this.name = name; - } + public static ResourceLocation GuiTexture(final String string) { + return new ResourceLocation("appliedenergistics2", "textures/" + string); + } - public static ResourceLocation GuiTexture( final 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"); + } - @SideOnly( Side.CLIENT ) - public static IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( TextureMap.locationItemsTexture ) ).getAtlasSprite( "missingno" ); - } + public String getName() { + return this.name; + } - public String getName() - { - return this.name; - } + public IIcon getIcon() { + return this.IIcon; + } - public IIcon getIcon() - { - return this.IIcon; - } - - public void registerIcon( final TextureMap map ) - { - this.IIcon = map.registerIcon( "appliedenergistics2:" + this.name ); - } + public void registerIcon(final TextureMap map) { + this.IIcon = map.registerIcon("appliedenergistics2:" + this.name); + } } diff --git a/src/main/java/appeng/client/texture/FlippableIcon.java b/src/main/java/appeng/client/texture/FlippableIcon.java index 836bf8fa..50b2abdd 100644 --- a/src/main/java/appeng/client/texture/FlippableIcon.java +++ b/src/main/java/appeng/client/texture/FlippableIcon.java @@ -18,149 +18,122 @@ package appeng.client.texture; +import javax.annotation.Nonnull; import net.minecraft.util.IIcon; -import javax.annotation.Nonnull; +public class FlippableIcon implements IIcon { + private IIcon original; + private boolean flip_u; + private boolean flip_v; + public FlippableIcon(final IIcon o) { + if (o == null) { + throw new IllegalArgumentException( + "Cannot create a wrapper icon with a null icon." + ); + } -public class FlippableIcon implements IIcon -{ + this.setOriginal(o); + this.setFlipU(false); + this.setFlipV(false); + } - private IIcon original; - private boolean flip_u; - private boolean flip_v; + @Override + public int getIconWidth() { + return this.getOriginal().getIconWidth(); + } - public FlippableIcon( final IIcon o ) - { - if( o == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } + @Override + public int getIconHeight() { + return this.getOriginal().getIconHeight(); + } - this.setOriginal( o ); - this.setFlipU( false ); - this.setFlipV( false ); - } + @Override + public float getMinU() { + if (this.isFlipU()) { + return this.getOriginal().getMaxU(); + } + return this.getOriginal().getMinU(); + } - @Override - public int getIconWidth() - { - return this.getOriginal().getIconWidth(); - } + @Override + public float getMaxU() { + if (this.isFlipU()) { + return this.getOriginal().getMinU(); + } + return this.getOriginal().getMaxU(); + } - @Override - public int getIconHeight() - { - return this.getOriginal().getIconHeight(); - } + @Override + public float getInterpolatedU(final double px) { + if (this.isFlipU()) { + return this.getOriginal().getInterpolatedU(16 - px); + } + return this.getOriginal().getInterpolatedU(px); + } - @Override - public float getMinU() - { - if( this.isFlipU() ) - { - return this.getOriginal().getMaxU(); - } - return this.getOriginal().getMinU(); - } + @Override + public float getMinV() { + if (this.isFlipV()) { + return this.getOriginal().getMaxV(); + } + return this.getOriginal().getMinV(); + } - @Override - public float getMaxU() - { - if( this.isFlipU() ) - { - return this.getOriginal().getMinU(); - } - return this.getOriginal().getMaxU(); - } + @Override + public float getMaxV() { + if (this.isFlipV()) { + return this.getOriginal().getMinV(); + } + return this.getOriginal().getMaxV(); + } - @Override - public float getInterpolatedU( final double px ) - { - if( this.isFlipU() ) - { - return this.getOriginal().getInterpolatedU( 16 - px ); - } - return this.getOriginal().getInterpolatedU( px ); - } + @Override + public float getInterpolatedV(final double px) { + if (this.isFlipV()) { + return this.getOriginal().getInterpolatedV(16 - px); + } + return this.getOriginal().getInterpolatedV(px); + } - @Override - public float getMinV() - { - if( this.isFlipV() ) - { - return this.getOriginal().getMaxV(); - } - return this.getOriginal().getMinV(); - } + @Override + public String getIconName() { + return this.getOriginal().getIconName(); + } - @Override - public float getMaxV() - { - if( this.isFlipV() ) - { - return this.getOriginal().getMinV(); - } - return this.getOriginal().getMaxV(); - } + public IIcon getOriginal() { + return this.original; + } - @Override - public float getInterpolatedV( final double px ) - { - if( this.isFlipV() ) - { - return this.getOriginal().getInterpolatedV( 16 - px ); - } - return this.getOriginal().getInterpolatedV( px ); - } + public void setFlip(final boolean u, final boolean v) { + this.setFlipU(u); + this.setFlipV(v); + } - @Override - public String getIconName() - { - return this.getOriginal().getIconName(); - } + public int setFlip(final int orientation) { + this.setFlipU((orientation & 8) == 8); + this.setFlipV((orientation & 16) == 16); + return orientation & 7; + } - public IIcon getOriginal() - { - return this.original; - } + boolean isFlipU() { + return this.flip_u; + } - public void setFlip( final boolean u, final boolean v ) - { - this.setFlipU( u ); - this.setFlipV( v ); - } + void setFlipU(final boolean flipU) { + this.flip_u = flipU; + } - public int setFlip( final int orientation ) - { - this.setFlipU( ( orientation & 8 ) == 8 ); - this.setFlipV( ( orientation & 16 ) == 16 ); - return orientation & 7; - } + boolean isFlipV() { + return this.flip_v; + } - boolean isFlipU() - { - return this.flip_u; - } + void setFlipV(final boolean flipV) { + this.flip_v = flipV; + } - void setFlipU( final boolean flipU ) - { - this.flip_u = flipU; - } - - boolean isFlipV() - { - return this.flip_v; - } - - void setFlipV( final boolean flipV ) - { - this.flip_v = flipV; - } - - public void setOriginal( @Nonnull final IIcon original ) - { - this.original = original; - } + public void setOriginal(@Nonnull final IIcon original) { + this.original = original; + } } diff --git a/src/main/java/appeng/client/texture/FullIcon.java b/src/main/java/appeng/client/texture/FullIcon.java index 2cd2267a..63eed39d 100644 --- a/src/main/java/appeng/client/texture/FullIcon.java +++ b/src/main/java/appeng/client/texture/FullIcon.java @@ -18,93 +18,78 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; +public class FullIcon implements IIcon { + private final IIcon p; -public class FullIcon implements IIcon -{ + public FullIcon(final IIcon o) { + if (o == null) { + throw new IllegalArgumentException( + "Cannot create a wrapper icon with a null icon." + ); + } - private final IIcon p; + this.p = o; + } - public FullIcon( final IIcon o ) - { - if( o == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } + @Override + public int getIconWidth() { + return this.p.getIconWidth(); + } - this.p = o; - } + @Override + public int getIconHeight() { + return this.p.getIconHeight(); + } - @Override - public int getIconWidth() - { - return this.p.getIconWidth(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMinU() { + return this.p.getMinU(); + } - @Override - public int getIconHeight() - { - return this.p.getIconHeight(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMaxU() { + return this.p.getMaxU(); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMinU() - { - return this.p.getMinU(); - } + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedU(final double d0) { + if (d0 > 8.0) { + return this.p.getMaxU(); + } + return this.p.getMinU(); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMaxU() - { - return this.p.getMaxU(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMinV() { + return this.p.getMinV(); + } - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedU( final double d0 ) - { - if( d0 > 8.0 ) - { - return this.p.getMaxU(); - } - return this.p.getMinU(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMaxV() { + return this.p.getMaxV(); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMinV() - { - return this.p.getMinV(); - } + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedV(final double d0) { + if (d0 > 8.0) { + return this.p.getMaxV(); + } + return this.p.getMinV(); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMaxV() - { - return this.p.getMaxV(); - } - - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedV( final 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 + @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 68f5eeb1..3ab1355d 100644 --- a/src/main/java/appeng/client/texture/MissingIcon.java +++ b/src/main/java/appeng/client/texture/MissingIcon.java @@ -18,7 +18,6 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; @@ -26,74 +25,64 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; +public class MissingIcon implements IIcon { + private final boolean isBlock; -public class MissingIcon implements IIcon -{ + public MissingIcon(final Object forWhat) { + this.isBlock = forWhat instanceof Block; + } - private final boolean isBlock; + @Override + public int getIconWidth() { + return this.getMissing().getIconWidth(); + } - public MissingIcon( final Object forWhat ) - { - this.isBlock = forWhat instanceof Block; - } + @SideOnly(Side.CLIENT) + private IIcon getMissing() { + return ((TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( + this.isBlock ? TextureMap.locationBlocksTexture + : TextureMap.locationItemsTexture + )) + .getAtlasSprite("missingno"); + } - @Override - public int getIconWidth() - { - return this.getMissing().getIconWidth(); - } + @Override + public int getIconHeight() { + return this.getMissing().getIconHeight(); + } - @SideOnly( Side.CLIENT ) - private IIcon getMissing() - { - return ( (TextureMap) Minecraft.getMinecraft().getTextureManager().getTexture( this.isBlock ? TextureMap.locationBlocksTexture : TextureMap.locationItemsTexture ) ).getAtlasSprite( "missingno" ); - } + @Override + public float getMinU() { + return this.getMissing().getMinU(); + } - @Override - public int getIconHeight() - { - return this.getMissing().getIconHeight(); - } + @Override + public float getMaxU() { + return this.getMissing().getMaxU(); + } - @Override - public float getMinU() - { - return this.getMissing().getMinU(); - } + @Override + public float getInterpolatedU(final double var1) { + return this.getMissing().getInterpolatedU(var1); + } - @Override - public float getMaxU() - { - return this.getMissing().getMaxU(); - } + @Override + public float getMinV() { + return this.getMissing().getMinV(); + } - @Override - public float getInterpolatedU( final double var1 ) - { - return this.getMissing().getInterpolatedU( var1 ); - } + @Override + public float getMaxV() { + return this.getMissing().getMaxV(); + } - @Override - public float getMinV() - { - return this.getMissing().getMinV(); - } + @Override + public float getInterpolatedV(final double var1) { + return this.getMissing().getInterpolatedV(var1); + } - @Override - public float getMaxV() - { - return this.getMissing().getMaxV(); - } - - @Override - public float getInterpolatedV( final double var1 ) - { - return this.getMissing().getInterpolatedV( var1 ); - } - - @Override - public String getIconName() - { - return this.getMissing().getIconName(); - } + @Override + public String getIconName() { + 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 1f0fcd2a..ab6ebc81 100644 --- a/src/main/java/appeng/client/texture/OffsetIcon.java +++ b/src/main/java/appeng/client/texture/OffsetIcon.java @@ -18,100 +18,85 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; +public class OffsetIcon implements IIcon { + private final float offsetX; + private final float offsetY; -public class OffsetIcon implements IIcon -{ + private final IIcon p; - private final float offsetX; - private final float offsetY; + public OffsetIcon(final IIcon o, final float x, final float y) { + if (o == null) { + throw new IllegalArgumentException( + "Cannot create a wrapper icon with a null icon." + ); + } - private final IIcon p; + this.p = o; + this.offsetX = x; + this.offsetY = y; + } - public OffsetIcon( final IIcon o, final float x, final float y ) - { - if( o == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } + @Override + public int getIconWidth() { + return this.p.getIconWidth(); + } - this.p = o; - this.offsetX = x; - this.offsetY = y; - } + @Override + public int getIconHeight() { + return this.p.getIconHeight(); + } - @Override - public int getIconWidth() - { - return this.p.getIconWidth(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMinU() { + return this.u(0 - this.offsetX); + } - @Override - public int getIconHeight() - { - return this.p.getIconHeight(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMaxU() { + return this.u(16 - this.offsetX); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMinU() - { - return this.u( 0 - this.offsetX ); - } + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedU(final double d0) { + return this.u(d0 - this.offsetX); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMaxU() - { - return this.u( 16 - this.offsetX ); - } + @Override + @SideOnly(Side.CLIENT) + public float getMinV() { + return this.v(0 - this.offsetY); + } - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedU( final double d0 ) - { - return this.u( d0 - this.offsetX ); - } + @Override + @SideOnly(Side.CLIENT) + public float getMaxV() { + return this.v(16 - this.offsetY); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMinV() - { - return this.v( 0 - this.offsetY ); - } + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedV(final double d0) { + return this.v(d0 - this.offsetY); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMaxV() - { - return this.v( 16 - this.offsetY ); - } + @Override + @SideOnly(Side.CLIENT) + public String getIconName() { + return this.p.getIconName(); + } - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedV( final double d0 ) - { - return this.v( d0 - this.offsetY ); - } + private float v(final double d) { + return this.p.getInterpolatedV(Math.min(16.0, Math.max(0.0, d))); + } - @Override - @SideOnly( Side.CLIENT ) - public String getIconName() - { - return this.p.getIconName(); - } - - private float v( final double d ) - { - return this.p.getInterpolatedV( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } - - private float u( final double d ) - { - return this.p.getInterpolatedU( Math.min( 16.0, Math.max( 0.0, d ) ) ); - } + private float u(final 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 f9d0c8e1..23af41ee 100644 --- a/src/main/java/appeng/client/texture/TaughtIcon.java +++ b/src/main/java/appeng/client/texture/TaughtIcon.java @@ -18,114 +18,95 @@ package appeng.client.texture; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.util.IIcon; +public class TaughtIcon implements IIcon { + private final float tightness; -public class TaughtIcon implements IIcon -{ + private final IIcon icon; - private final float tightness; + public TaughtIcon(final IIcon icon, final float tightness) { + if (icon == null) { + throw new IllegalArgumentException( + "Cannot create a wrapper icon with a null icon." + ); + } - private final IIcon icon; + this.icon = icon; + this.tightness = tightness * 0.4f; + } - public TaughtIcon( final IIcon icon, final float tightness ) - { - if( icon == null ) - { - throw new IllegalArgumentException( "Cannot create a wrapper icon with a null icon." ); - } + @Override + public int getIconWidth() { + return this.icon.getIconWidth(); + } - this.icon = icon; - this.tightness = tightness * 0.4f; - } + @Override + public int getIconHeight() { + return this.icon.getIconHeight(); + } - @Override - public int getIconWidth() - { - return this.icon.getIconWidth(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMinU() { + return this.u(0); + } - @Override - public int getIconHeight() - { - return this.icon.getIconHeight(); - } + @Override + @SideOnly(Side.CLIENT) + public float getMaxU() { + return this.u(16); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMinU() - { - return this.u( 0 ); - } + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedU(final double d0) { + return this.u(d0); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMaxU() - { - return this.u( 16 ); - } + @Override + @SideOnly(Side.CLIENT) + public float getMinV() { + return this.v(0); + } - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedU( final double d0 ) - { - return this.u( d0 ); - } + @Override + @SideOnly(Side.CLIENT) + public float getMaxV() { + return this.v(16); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMinV() - { - return this.v( 0 ); - } + @Override + @SideOnly(Side.CLIENT) + public float getInterpolatedV(final double d0) { + return this.v(d0); + } - @Override - @SideOnly( Side.CLIENT ) - public float getMaxV() - { - return this.v( 16 ); - } + @Override + @SideOnly(Side.CLIENT) + public String getIconName() { + return this.icon.getIconName(); + } - @Override - @SideOnly( Side.CLIENT ) - public float getInterpolatedV( final 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.icon.getInterpolatedV(Math.min(16.0, Math.max(0.0, d))); + } - @Override - @SideOnly( Side.CLIENT ) - public String getIconName() - { - return this.icon.getIconName(); - } - - private float v( double d ) - { - if( d < 8 ) - { - d -= this.tightness; - } - if( d > 8 ) - { - d += this.tightness; - } - return this.icon.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.icon.getInterpolatedU( 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.icon.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 07789ffa..741c1378 100644 --- a/src/main/java/appeng/client/texture/TmpFlippableIcon.java +++ b/src/main/java/appeng/client/texture/TmpFlippableIcon.java @@ -18,49 +18,37 @@ 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 class TmpFlippableIcon extends FlippableIcon -{ + public TmpFlippableIcon() { + super(NULL_ICON); + } - private static final IIcon NULL_ICON = new MissingIcon( Blocks.diamond_block ); + @Override + public void setOriginal(IIcon i) { + this.setFlip(false, false); - public TmpFlippableIcon() - { - super( NULL_ICON ); - } + while (i instanceof FlippableIcon) { + final FlippableIcon fi = (FlippableIcon) i; + if (fi.isFlipU()) { + this.setFlipU(!this.isFlipU()); + } - @Override - public void setOriginal( IIcon i ) - { - this.setFlip( false, false ); + if (fi.isFlipV()) { + this.setFlipV(!this.isFlipV()); + } - while( i instanceof FlippableIcon ) - { - final FlippableIcon fi = (FlippableIcon) i; - if( fi.isFlipU() ) - { - this.setFlipU( !this.isFlipU() ); - } + i = fi.getOriginal(); + } - if( fi.isFlipV() ) - { - this.setFlipV( !this.isFlipV() ); - } - - i = fi.getOriginal(); - } - - if( i == null ) - { - super.setOriginal( NULL_ICON ); - } - else - { - super.setOriginal( i ); - } - } + if (i == null) { + super.setOriginal(NULL_ICON); + } else { + super.setOriginal(i); + } + } } diff --git a/src/main/java/appeng/container/AEBaseContainer.java b/src/main/java/appeng/container/AEBaseContainer.java index b7a39710..13d7d31b 100644 --- a/src/main/java/appeng/container/AEBaseContainer.java +++ b/src/main/java/appeng/container/AEBaseContainer.java @@ -18,6 +18,11 @@ package appeng.container; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.*; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -63,1268 +68,1132 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.*; - - -public abstract class AEBaseContainer extends Container -{ - - private final InventoryPlayer invPlayer; - private final BaseActionSource mySrc; - private final HashSet locked = new HashSet(); - private final TileEntity tileEntity; - private final IPart part; - private final IGuiItemObject obj; - private final List dataChunks = new LinkedList(); - private final HashMap syncData = new HashMap(); - private boolean isContainerValid = true; - private String customName; - private ContainerOpenContext openContext; - private IMEInventoryHandler cellInv; - private IEnergySource powerSrc; - private boolean sentCustomName; - private int ticksSinceCheck = 900; - private IAEItemStack clientRequestedTargetItem = null; - - public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart ) - { - this( ip, myTile, myPart, null ); - } - - public AEBaseContainer( final InventoryPlayer ip, final TileEntity myTile, final IPart myPart, final 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( final Field f : this.getClass().getFields() ) - { - if( f.isAnnotationPresent( GuiSync.class ) ) - { - final GuiSync annotation = f.getAnnotation( GuiSync.class ); - if( this.syncData.containsKey( annotation.value() ) ) - { - AELog.warn( "Channel already in use: " + annotation.value() + " for " + f.getName() ); - } - else - { - this.syncData.put( annotation.value(), new SyncData( this, f, annotation ) ); - } - } - } - } - - public AEBaseContainer( final InventoryPlayer ip, final 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 IllegalArgumentException( "Must have a valid anchor, instead " + anchor + " in " + ip ); - } - - this.mySrc = new PlayerSource( ip.player, this.getActionHost() ); - - this.prepareSync(); - } - - public void postPartial( final PacketPartialItem packetPartialItem ) - { - this.dataChunks.add( packetPartialItem ); - if( packetPartialItem.getPageCount() == this.dataChunks.size() ) - { - this.parsePartials(); - } - } - - private void parsePartials() - { - int total = 0; - for( final PacketPartialItem ppi : this.dataChunks ) - { - total += ppi.getSize(); - } - - final byte[] buffer = new byte[total]; - int cursor = 0; - - for( final PacketPartialItem ppi : this.dataChunks ) - { - cursor = ppi.write( buffer, cursor ); - } - - try - { - final NBTTagCompound data = CompressedStreamTools.readCompressed( new ByteArrayInputStream( buffer ) ); - if( data != null ) - { - this.setTargetStack( AEApi.instance().storage().createItemStack( ItemStack.loadItemStackFromNBT( data ) ) ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - - this.dataChunks.clear(); - } - - public IAEItemStack getTargetStack() - { - return this.clientRequestedTargetItem; - } - - public void setTargetStack( final IAEItemStack stack ) - { - // client doesn't need to re-send, makes for lower overhead rapid packets. - if( Platform.isClient() ) - { - final ItemStack a = stack == null ? null : stack.getItemStack(); - final ItemStack b = this.clientRequestedTargetItem == null ? null : this.clientRequestedTargetItem.getItemStack(); - - if( Platform.isSameItemPrecise( a, b ) ) - { - return; - } - - final ByteArrayOutputStream stream = new ByteArrayOutputStream(); - final NBTTagCompound item = new NBTTagCompound(); - - if( stack != null ) - { - stack.writeToNBT( item ); - } - - try - { - CompressedStreamTools.writeCompressed( item, stream ); - - final int maxChunkSize = 30000; - final List miniPackets = new LinkedList(); - - final byte[] data = stream.toByteArray(); - - final ByteArrayInputStream bis = new ByteArrayInputStream( data, 0, stream.size() ); - while( bis.available() > 0 ) - { - final int nextBLock = bis.available() > maxChunkSize ? maxChunkSize : bis.available(); - final byte[] nextSegment = new byte[nextBLock]; - bis.read( nextSegment ); - miniPackets.add( nextSegment ); - } - bis.close(); - stream.close(); - - int page = 0; - for( final byte[] packet : miniPackets ) - { - final PacketPartialItem ppi = new PacketPartialItem( page, miniPackets.size(), packet ); - page++; - NetworkHandler.instance.sendToServer( ppi ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - return; - } - } - - this.clientRequestedTargetItem = stack == null ? null : stack.copy(); - } - - public BaseActionSource getActionSource() - { - return this.mySrc; - } - - public void verifyPermissions( final SecurityPermissions security, final boolean requirePower ) - { - if( Platform.isClient() ) - { - return; - } - - this.ticksSinceCheck++; - if( this.ticksSinceCheck < 20 ) - { - return; - } - - this.ticksSinceCheck = 0; - this.setValidContainer( this.isValidContainer() && this.hasAccess( security, requirePower ) ); - } - - protected boolean hasAccess( final SecurityPermissions perm, final boolean requirePower ) - { - final IActionHost host = this.getActionHost(); - - if( host != null ) - { - final IGridNode gn = host.getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( this.getInventoryPlayer().player, perm ) ) - { - return true; - } - } - } - } - - return false; - } - - public void lockPlayerInventorySlot( final int idx ) - { - this.locked.add( idx ); - } - - public Object getTarget() - { - if( this.tileEntity != null ) - { - return this.tileEntity; - } - if( this.part != null ) - { - return this.part; - } - if( this.obj != null ) - { - return this.obj; - } - return null; - } - - public InventoryPlayer getPlayerInv() - { - return this.getInventoryPlayer(); - } - - public TileEntity getTileEntity() - { - return this.tileEntity; - } - - public final void updateFullProgressBar( final int idx, final long value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( value ); - return; - } - - this.updateProgressBar( idx, (int) value ); - } - - public void stringSync( final int idx, final String value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( value ); - } - } - - protected void bindPlayerInventory( final InventoryPlayer inventoryPlayer, final int offsetX, final int offsetY ) - { - // bind player inventory - 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 + offsetX, offsetY + i * 18 ) ); - } - else - { - this.addSlotToContainer( new SlotPlayerInv( inventoryPlayer, j + i * 9 + 9, 8 + j * 18 + offsetX, offsetY + i * 18 ) ); - } - } - } - - // bind player hotbar - for( int i = 0; i < 9; i++ ) - { - if( this.locked.contains( i ) ) - { - this.addSlotToContainer( new SlotDisabled( inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); - } - else - { - this.addSlotToContainer( new SlotPlayerHotBar( inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY ) ); - } - } - } - - @Override - protected Slot addSlotToContainer( final Slot newSlot ) - { - if( newSlot instanceof AppEngSlot ) - { - final AppEngSlot s = (AppEngSlot) newSlot; - s.setContainer( this ); - return super.addSlotToContainer( newSlot ); - } - else - { - throw new IllegalArgumentException( "Invalid Slot [" + newSlot + "]for AE Container instead of AppEngSlot." ); - } - } - - @Override - public void detectAndSendChanges() - { - this.sendCustomName(); - - if( Platform.isServer() ) - { - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; - - for( final SyncData sd : this.syncData.values() ) - { - sd.tick( icrafting ); - } - } - } - - super.detectAndSendChanges(); - } - - @Override - public ItemStack transferStackInSlot( final EntityPlayer p, final int idx ) - { - if( Platform.isClient() ) - { - return null; - } - - boolean hasMETiles = false; - for( final Object is : this.inventorySlots ) - { - if( is instanceof InternalSlotME ) - { - hasMETiles = true; - break; - } - } - - if( hasMETiles && Platform.isClient() ) - { - return null; - } - - final AppEngSlot clickSlot = (AppEngSlot) this.inventorySlots.get( idx ); // require AE SLots! - - if( clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible ) - { - return null; - } - if( clickSlot != null && clickSlot.getHasStack() ) - { - ItemStack tis = clickSlot.getStack(); - - if( tis == null ) - { - return null; - } - - final List selectedSlots = new ArrayList(); - - /** - * Gather a list of valid destinations. - */ - if( clickSlot.isPlayerSide() ) - { - tis = this.shiftStoreItem( tis ); - - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - - if( !( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) - { - if( cs.isItemValid( tis ) ) - { - selectedSlots.add( cs ); - } - } - } - } - else - { - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - - if( ( cs.isPlayerSide() ) && !( cs instanceof SlotFake ) && !( cs instanceof SlotCraftingMatrix ) ) - { - if( cs.isItemValid( tis ) ) - { - selectedSlots.add( cs ); - } - } - } - } - - /** - * Handle Fake Slot Shift clicking. - */ - if( selectedSlots.isEmpty() && clickSlot.isPlayerSide() ) - { - if( tis != null ) - { - // target slots in the container... - for( final Object inventorySlot : this.inventorySlots ) - { - final AppEngSlot cs = (AppEngSlot) inventorySlot; - final ItemStack destination = cs.getStack(); - - if( !( cs.isPlayerSide() ) && cs instanceof SlotFake ) - { - if( Platform.isSameItemPrecise( destination, tis ) ) - { - break; - } - else if( destination == null ) - { - cs.putStack( tis.copy() ); - cs.onSlotChanged(); - this.updateSlot( cs ); - break; - } - } - } - } - } - - if( tis != null ) - { - // find partials.. - for( final Slot d : selectedSlots ) - { - if( d instanceof SlotDisabled || d instanceof SlotME ) - { - continue; - } - - if( d.isItemValid( tis ) ) - { - if( d.getHasStack() ) - { - final ItemStack t = d.getStack(); - - if( Platform.isSameItemPrecise( tis, t ) ) // t.isItemEqual(tis)) - { - int maxSize = t.getMaxStackSize(); - if( maxSize > d.getSlotStackLimit() ) - { - maxSize = d.getSlotStackLimit(); - } - - int placeAble = maxSize - t.stackSize; - - if( tis.stackSize < placeAble ) - { - placeAble = tis.stackSize; - } - - t.stackSize += placeAble; - tis.stackSize -= placeAble; - - if( tis.stackSize <= 0 ) - { - clickSlot.putStack( null ); - d.onSlotChanged(); - - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return null; - } - else - { - this.updateSlot( d ); - } - } - } - } - } - - // any match.. - for( final Slot d : selectedSlots ) - { - if( d instanceof SlotDisabled || d instanceof SlotME ) - { - continue; - } - - if( d.isItemValid( tis ) ) - { - if( d.getHasStack() ) - { - final ItemStack t = d.getStack(); - - if( Platform.isSameItemPrecise( t, tis ) ) - { - int maxSize = t.getMaxStackSize(); - if( d.getSlotStackLimit() < maxSize ) - { - maxSize = d.getSlotStackLimit(); - } - - int placeAble = maxSize - t.stackSize; - - if( tis.stackSize < placeAble ) - { - placeAble = tis.stackSize; - } - - t.stackSize += placeAble; - tis.stackSize -= placeAble; - - if( tis.stackSize <= 0 ) - { - clickSlot.putStack( null ); - d.onSlotChanged(); - - // if ( worldEntity != null ) - // worldEntity.markDirty(); - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return null; - } - else - { - this.updateSlot( d ); - } - } - } - else - { - int maxSize = tis.getMaxStackSize(); - if( maxSize > d.getSlotStackLimit() ) - { - maxSize = d.getSlotStackLimit(); - } - - final ItemStack tmp = tis.copy(); - if( tmp.stackSize > maxSize ) - { - tmp.stackSize = maxSize; - } - - tis.stackSize -= tmp.stackSize; - d.putStack( tmp ); - - if( tis.stackSize <= 0 ) - { - clickSlot.putStack( null ); - d.onSlotChanged(); - - // if ( worldEntity != null ) - // worldEntity.markDirty(); - // if ( hasMETiles ) updateClient(); - - this.updateSlot( clickSlot ); - this.updateSlot( d ); - return null; - } - else - { - this.updateSlot( d ); - } - } - } - } - } - - clickSlot.putStack( tis != null ? tis.copy() : null ); - } - - this.updateSlot( clickSlot ); - return null; - } - - @Override - public final void updateProgressBar( final int idx, final int value ) - { - if( this.syncData.containsKey( idx ) ) - { - this.syncData.get( idx ).update( (long) value ); - } - } - - @Override - public boolean canInteractWith( final EntityPlayer entityplayer ) - { - if( this.isValidContainer() ) - { - if( this.tileEntity instanceof IInventory ) - { - return ( (IInventory) this.tileEntity ).isUseableByPlayer( entityplayer ); - } - return true; - } - return false; - } - - @Override - public boolean canDragIntoSlot( final Slot s ) - { - return ( (AppEngSlot) s ).isDraggable(); - } - - public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) - { - if( slot >= 0 && slot < this.inventorySlots.size() ) - { - final Slot s = this.getSlot( slot ); - - if( s instanceof SlotCraftingTerm ) - { - switch( action ) - { - case CRAFT_SHIFT: - case CRAFT_ITEM: - case CRAFT_STACK: - ( (SlotCraftingTerm) s ).doClick( action, player ); - this.updateHeld( player ); - default: - } - } - - if( s instanceof SlotFake ) - { - final ItemStack hand = player.inventory.getItemStack(); - - switch( action ) - { - case PICKUP_OR_SET_DOWN: - - if( hand == null ) - { - s.putStack( null ); - } - else - { - s.putStack( hand.copy() ); - } - - break; - case PLACE_SINGLE: - - if( hand != null ) - { - final 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 ); - } - - break; - case CREATIVE_DUPLICATE: - case MOVE_REGION: - case SHIFT_CLICK: - default: - break; - } - } - - if( action == InventoryAction.MOVE_REGION ) - { - if( s instanceof SlotPatternTerm ) - return; - //SlotPatternTerm should't transfer its ItemStack to the Player - - final List from = new LinkedList(); - - for( final Object j : this.inventorySlots ) - { - if( j instanceof Slot && j.getClass() == s.getClass() ) - { - from.add( (Slot) j ); - } - } - - for( final Slot fr : from ) - { - this.transferStackInSlot( player, fr.slotNumber ); - } - } - - return; - } - - // get target item. - final IAEItemStack slotItem = this.clientRequestedTargetItem; - - switch( action ) - { - case SHIFT_CLICK: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ItemStack myItem = ais.getItemStack(); - - ais.setStackSize( myItem.getMaxStackSize() ); - - final 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.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - adp.addItems( ais.getItemStack() ); - } - } - break; - case ROLL_DOWN: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - final int releaseQty = 1; - final ItemStack isg = player.inventory.getItemStack(); - - if( isg != null && releaseQty > 0 ) - { - IAEItemStack ais = AEApi.instance().storage().createItemStack( isg ); - ais.setStackSize( 1 ); - final IAEItemStack extracted = ais.copy(); - - ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais == null ) - { - final InventoryAdaptor ia = new AdaptorPlayerHand( player ); - - final ItemStack fail = ia.removeItems( 1, extracted.getItemStack(), null ); - if( fail == null ) - { - this.getCellInventory().extractItems( extracted, Actionable.MODULATE, this.getActionSource() ); - } - - this.updateHeld( player ); - } - } - - break; - case ROLL_UP: - case PICKUP_SINGLE: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - int liftQty = 1; - final 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.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - final InventoryAdaptor ia = new AdaptorPlayerHand( player ); - - final ItemStack fail = ia.addItems( ais.getItemStack() ); - if( fail != null ) - { - this.getCellInventory().injectItems( ais, Actionable.MODULATE, this.getActionSource() ); - } - - this.updateHeld( player ); - } - } - } - break; - case PICKUP_OR_SET_DOWN: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( player.inventory.getItemStack() == null ) - { - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - ais.setStackSize( ais.getItemStack().getMaxStackSize() ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - 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.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - player.inventory.setItemStack( ais.getItemStack() ); - } - else - { - player.inventory.setItemStack( null ); - } - this.updateHeld( player ); - } - - break; - case SPLIT_OR_PLACE_SINGLE: - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( player.inventory.getItemStack() == null ) - { - if( slotItem != null ) - { - IAEItemStack ais = slotItem.copy(); - final long maxSize = ais.getItemStack().getMaxStackSize(); - ais.setStackSize( maxSize ); - ais = this.getCellInventory().extractItems( ais, Actionable.SIMULATE, this.getActionSource() ); - - if( ais != null ) - { - final long stackSize = Math.min( maxSize, ais.getStackSize() ); - ais.setStackSize( ( stackSize + 1 ) >> 1 ); - ais = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - } - - 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.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais == null ) - { - final 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 ) - { - final ItemStack is = slotItem.getItemStack(); - is.stackSize = is.getMaxStackSize(); - player.inventory.setItemStack( is ); - this.updateHeld( player ); - } - break; - case MOVE_REGION: - - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return; - } - - if( slotItem != null ) - { - final int playerInv = 9 * 4; - for( int slotNum = 0; slotNum < playerInv; slotNum++ ) - { - IAEItemStack ais = slotItem.copy(); - ItemStack myItem = ais.getItemStack(); - - ais.setStackSize( myItem.getMaxStackSize() ); - - final 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.getPowerSource(), this.getCellInventory(), ais, this.getActionSource() ); - if( ais != null ) - { - adp.addItems( ais.getItemStack() ); - } - else - { - return; - } - } - } - - break; - default: - break; - } - } - - protected void updateHeld( final EntityPlayerMP p ) - { - if( Platform.isServer() ) - { - try - { - NetworkHandler.instance.sendTo( new PacketInventoryAction( InventoryAction.UPDATE_HAND, 0, AEItemStack.create( p.inventory.getItemStack() ) ), p ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - - private ItemStack shiftStoreItem( final ItemStack input ) - { - if( this.getPowerSource() == null || this.getCellInventory() == null ) - { - return input; - } - final IAEItemStack ais = Platform.poweredInsert( this.getPowerSource(), this.getCellInventory(), AEApi.instance().storage().createItemStack( input ), this.getActionSource() ); - if( ais == null ) - { - return null; - } - return ais.getItemStack(); - } - - private void updateSlot( final Slot clickSlot ) - { - // ??? - this.detectAndSendChanges(); - } - - private 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.setCustomName( name.getCustomName() ); - } - - if( this.getCustomName() != null ) - { - try - { - NetworkHandler.instance.sendTo( new PacketValueConfig( "CustomName", this.getCustomName() ), (EntityPlayerMP) this.getInventoryPlayer().player ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - } - } - - public void swapSlotContents( final int slotA, final int slotB ) - { - final Slot a = this.getSlot( slotA ); - final Slot b = this.getSlot( slotB ); - - // NPE protection... - if( a == null || b == null ) - { - return; - } - - final ItemStack isA = a.getStack(); - final ItemStack isB = b.getStack(); - - // something to do? - if( isA == null && isB == null ) - { - return; - } - - // can take? - - if( isA != null && !a.canTakeStack( this.getInventoryPlayer().player ) ) - { - return; - } - - if( isB != null && !b.canTakeStack( this.getInventoryPlayer().player ) ) - { - return; - } - - // swap valid? - - if( isB != null && !a.isItemValid( isB ) ) - { - return; - } - - 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( testB != null ) - { - return; - } - - final int totalA = testA.stackSize; - testA.stackSize = a.getSlotStackLimit(); - testB = testA.copy(); - - testB.stackSize = totalA - testA.stackSize; - } - - if( testB != null && testB.stackSize > b.getSlotStackLimit() ) - { - if( testA != null ) - { - return; - } - - final int totalB = testB.stackSize; - testB.stackSize = b.getSlotStackLimit(); - testA = testB.copy(); - - testA.stackSize = totalB - testA.stackSize; - } - - a.putStack( testA ); - b.putStack( testB ); - } - - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - - } - - public void onSlotChange( final Slot s ) - { - - } - - public boolean isValidForSlot( final Slot s, final ItemStack i ) - { - return true; - } - - public IMEInventoryHandler getCellInventory() - { - return this.cellInv; - } - - public void setCellInventory( final IMEInventoryHandler cellInv ) - { - this.cellInv = cellInv; - } - - public String getCustomName() - { - return this.customName; - } - - public void setCustomName( final String customName ) - { - this.customName = customName; - } - - public InventoryPlayer getInventoryPlayer() - { - return this.invPlayer; - } - - public boolean isValidContainer() - { - return this.isContainerValid; - } - - public void setValidContainer( final boolean isContainerValid ) - { - this.isContainerValid = isContainerValid; - } - - public ContainerOpenContext getOpenContext() - { - return this.openContext; - } - - public void setOpenContext( final ContainerOpenContext openContext ) - { - this.openContext = openContext; - } - - public IEnergySource getPowerSource() - { - return this.powerSrc; - } - - public void setPowerSource( final IEnergySource powerSrc ) - { - this.powerSrc = powerSrc; - } +public abstract class AEBaseContainer extends Container { + private final InventoryPlayer invPlayer; + private final BaseActionSource mySrc; + private final HashSet locked = new HashSet(); + private final TileEntity tileEntity; + private final IPart part; + private final IGuiItemObject obj; + private final List dataChunks + = new LinkedList(); + private final HashMap syncData = new HashMap(); + private boolean isContainerValid = true; + private String customName; + private ContainerOpenContext openContext; + private IMEInventoryHandler cellInv; + private IEnergySource powerSrc; + private boolean sentCustomName; + private int ticksSinceCheck = 900; + private IAEItemStack clientRequestedTargetItem = null; + + public AEBaseContainer( + final InventoryPlayer ip, final TileEntity myTile, final IPart myPart + ) { + this(ip, myTile, myPart, null); + } + + public AEBaseContainer( + final InventoryPlayer ip, + final TileEntity myTile, + final IPart myPart, + final 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 (final Field f : this.getClass().getFields()) { + if (f.isAnnotationPresent(GuiSync.class)) { + final GuiSync annotation = f.getAnnotation(GuiSync.class); + if (this.syncData.containsKey(annotation.value())) { + AELog.warn( + "Channel already in use: " + annotation.value() + " for " + + f.getName() + ); + } else { + this.syncData.put( + annotation.value(), new SyncData(this, f, annotation) + ); + } + } + } + } + + public AEBaseContainer(final InventoryPlayer ip, final 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 IllegalArgumentException( + "Must have a valid anchor, instead " + anchor + " in " + ip + ); + } + + this.mySrc = new PlayerSource(ip.player, this.getActionHost()); + + this.prepareSync(); + } + + public void postPartial(final PacketPartialItem packetPartialItem) { + this.dataChunks.add(packetPartialItem); + if (packetPartialItem.getPageCount() == this.dataChunks.size()) { + this.parsePartials(); + } + } + + private void parsePartials() { + int total = 0; + for (final PacketPartialItem ppi : this.dataChunks) { + total += ppi.getSize(); + } + + final byte[] buffer = new byte[total]; + int cursor = 0; + + for (final PacketPartialItem ppi : this.dataChunks) { + cursor = ppi.write(buffer, cursor); + } + + try { + final NBTTagCompound data + = CompressedStreamTools.readCompressed(new ByteArrayInputStream(buffer)); + if (data != null) { + this.setTargetStack(AEApi.instance().storage().createItemStack( + ItemStack.loadItemStackFromNBT(data) + )); + } + } catch (final IOException e) { + AELog.debug(e); + } + + this.dataChunks.clear(); + } + + public IAEItemStack getTargetStack() { + return this.clientRequestedTargetItem; + } + + public void setTargetStack(final IAEItemStack stack) { + // client doesn't need to re-send, makes for lower overhead rapid packets. + if (Platform.isClient()) { + final ItemStack a = stack == null ? null : stack.getItemStack(); + final ItemStack b = this.clientRequestedTargetItem == null + ? null + : this.clientRequestedTargetItem.getItemStack(); + + if (Platform.isSameItemPrecise(a, b)) { + return; + } + + final ByteArrayOutputStream stream = new ByteArrayOutputStream(); + final NBTTagCompound item = new NBTTagCompound(); + + if (stack != null) { + stack.writeToNBT(item); + } + + try { + CompressedStreamTools.writeCompressed(item, stream); + + final int maxChunkSize = 30000; + final List miniPackets = new LinkedList(); + + final byte[] data = stream.toByteArray(); + + final ByteArrayInputStream bis + = new ByteArrayInputStream(data, 0, stream.size()); + while (bis.available() > 0) { + final int nextBLock + = bis.available() > maxChunkSize ? maxChunkSize : bis.available(); + final byte[] nextSegment = new byte[nextBLock]; + bis.read(nextSegment); + miniPackets.add(nextSegment); + } + bis.close(); + stream.close(); + + int page = 0; + for (final byte[] packet : miniPackets) { + final PacketPartialItem ppi + = new PacketPartialItem(page, miniPackets.size(), packet); + page++; + NetworkHandler.instance.sendToServer(ppi); + } + } catch (final IOException e) { + AELog.debug(e); + return; + } + } + + this.clientRequestedTargetItem = stack == null ? null : stack.copy(); + } + + public BaseActionSource getActionSource() { + return this.mySrc; + } + + public void + verifyPermissions(final SecurityPermissions security, final boolean requirePower) { + if (Platform.isClient()) { + return; + } + + this.ticksSinceCheck++; + if (this.ticksSinceCheck < 20) { + return; + } + + this.ticksSinceCheck = 0; + this.setValidContainer( + this.isValidContainer() && this.hasAccess(security, requirePower) + ); + } + + protected boolean + hasAccess(final SecurityPermissions perm, final boolean requirePower) { + final IActionHost host = this.getActionHost(); + + if (host != null) { + final IGridNode gn = host.getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(this.getInventoryPlayer().player, perm)) { + return true; + } + } + } + } + + return false; + } + + public void lockPlayerInventorySlot(final int idx) { + this.locked.add(idx); + } + + public Object getTarget() { + if (this.tileEntity != null) { + return this.tileEntity; + } + if (this.part != null) { + return this.part; + } + if (this.obj != null) { + return this.obj; + } + return null; + } + + public InventoryPlayer getPlayerInv() { + return this.getInventoryPlayer(); + } + + public TileEntity getTileEntity() { + return this.tileEntity; + } + + public final void updateFullProgressBar(final int idx, final long value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update(value); + return; + } + + this.updateProgressBar(idx, (int) value); + } + + public void stringSync(final int idx, final String value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update(value); + } + } + + protected void bindPlayerInventory( + final InventoryPlayer inventoryPlayer, final int offsetX, final int offsetY + ) { + // bind player inventory + 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 + offsetX, + offsetY + i * 18 + )); + } else { + this.addSlotToContainer(new SlotPlayerInv( + inventoryPlayer, + j + i * 9 + 9, + 8 + j * 18 + offsetX, + offsetY + i * 18 + )); + } + } + } + + // bind player hotbar + for (int i = 0; i < 9; i++) { + if (this.locked.contains(i)) { + this.addSlotToContainer(new SlotDisabled( + inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY + )); + } else { + this.addSlotToContainer(new SlotPlayerHotBar( + inventoryPlayer, i, 8 + i * 18 + offsetX, 58 + offsetY + )); + } + } + } + + @Override + protected Slot addSlotToContainer(final Slot newSlot) { + if (newSlot instanceof AppEngSlot) { + final AppEngSlot s = (AppEngSlot) newSlot; + s.setContainer(this); + return super.addSlotToContainer(newSlot); + } else { + throw new IllegalArgumentException( + "Invalid Slot [" + newSlot + "]for AE Container instead of AppEngSlot." + ); + } + } + + @Override + public void detectAndSendChanges() { + this.sendCustomName(); + + if (Platform.isServer()) { + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + + for (final SyncData sd : this.syncData.values()) { + sd.tick(icrafting); + } + } + } + + super.detectAndSendChanges(); + } + + @Override + public ItemStack transferStackInSlot(final EntityPlayer p, final int idx) { + if (Platform.isClient()) { + return null; + } + + boolean hasMETiles = false; + for (final Object is : this.inventorySlots) { + if (is instanceof InternalSlotME) { + hasMETiles = true; + break; + } + } + + if (hasMETiles && Platform.isClient()) { + return null; + } + + final AppEngSlot clickSlot + = (AppEngSlot) this.inventorySlots.get(idx); // require AE SLots! + + if (clickSlot instanceof SlotDisabled || clickSlot instanceof SlotInaccessible) { + return null; + } + if (clickSlot != null && clickSlot.getHasStack()) { + ItemStack tis = clickSlot.getStack(); + + if (tis == null) { + return null; + } + + final List selectedSlots = new ArrayList(); + + /** + * Gather a list of valid destinations. + */ + if (clickSlot.isPlayerSide()) { + tis = this.shiftStoreItem(tis); + + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if (!(cs.isPlayerSide()) && !(cs instanceof SlotFake) + && !(cs instanceof SlotCraftingMatrix)) { + if (cs.isItemValid(tis)) { + selectedSlots.add(cs); + } + } + } + } else { + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + + if ((cs.isPlayerSide()) && !(cs instanceof SlotFake) + && !(cs instanceof SlotCraftingMatrix)) { + if (cs.isItemValid(tis)) { + selectedSlots.add(cs); + } + } + } + } + + /** + * Handle Fake Slot Shift clicking. + */ + if (selectedSlots.isEmpty() && clickSlot.isPlayerSide()) { + if (tis != null) { + // target slots in the container... + for (final Object inventorySlot : this.inventorySlots) { + final AppEngSlot cs = (AppEngSlot) inventorySlot; + final ItemStack destination = cs.getStack(); + + if (!(cs.isPlayerSide()) && cs instanceof SlotFake) { + if (Platform.isSameItemPrecise(destination, tis)) { + break; + } else if (destination == null) { + cs.putStack(tis.copy()); + cs.onSlotChanged(); + this.updateSlot(cs); + break; + } + } + } + } + } + + if (tis != null) { + // find partials.. + for (final Slot d : selectedSlots) { + if (d instanceof SlotDisabled || d instanceof SlotME) { + continue; + } + + if (d.isItemValid(tis)) { + if (d.getHasStack()) { + final ItemStack t = d.getStack(); + + if (Platform.isSameItemPrecise(tis, t)) // t.isItemEqual(tis)) + { + int maxSize = t.getMaxStackSize(); + if (maxSize > d.getSlotStackLimit()) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if (tis.stackSize < placeAble) { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if (tis.stackSize <= 0) { + clickSlot.putStack(null); + d.onSlotChanged(); + + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return null; + } else { + this.updateSlot(d); + } + } + } + } + } + + // any match.. + for (final Slot d : selectedSlots) { + if (d instanceof SlotDisabled || d instanceof SlotME) { + continue; + } + + if (d.isItemValid(tis)) { + if (d.getHasStack()) { + final ItemStack t = d.getStack(); + + if (Platform.isSameItemPrecise(t, tis)) { + int maxSize = t.getMaxStackSize(); + if (d.getSlotStackLimit() < maxSize) { + maxSize = d.getSlotStackLimit(); + } + + int placeAble = maxSize - t.stackSize; + + if (tis.stackSize < placeAble) { + placeAble = tis.stackSize; + } + + t.stackSize += placeAble; + tis.stackSize -= placeAble; + + if (tis.stackSize <= 0) { + clickSlot.putStack(null); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return null; + } else { + this.updateSlot(d); + } + } + } else { + int maxSize = tis.getMaxStackSize(); + if (maxSize > d.getSlotStackLimit()) { + maxSize = d.getSlotStackLimit(); + } + + final ItemStack tmp = tis.copy(); + if (tmp.stackSize > maxSize) { + tmp.stackSize = maxSize; + } + + tis.stackSize -= tmp.stackSize; + d.putStack(tmp); + + if (tis.stackSize <= 0) { + clickSlot.putStack(null); + d.onSlotChanged(); + + // if ( worldEntity != null ) + // worldEntity.markDirty(); + // if ( hasMETiles ) updateClient(); + + this.updateSlot(clickSlot); + this.updateSlot(d); + return null; + } else { + this.updateSlot(d); + } + } + } + } + } + + clickSlot.putStack(tis != null ? tis.copy() : null); + } + + this.updateSlot(clickSlot); + return null; + } + + @Override + public final void updateProgressBar(final int idx, final int value) { + if (this.syncData.containsKey(idx)) { + this.syncData.get(idx).update((long) value); + } + } + + @Override + public boolean canInteractWith(final EntityPlayer entityplayer) { + if (this.isValidContainer()) { + if (this.tileEntity instanceof IInventory) { + return ((IInventory) this.tileEntity).isUseableByPlayer(entityplayer); + } + return true; + } + return false; + } + + @Override + public boolean canDragIntoSlot(final Slot s) { + return ((AppEngSlot) s).isDraggable(); + } + + public void doAction( + final EntityPlayerMP player, + final InventoryAction action, + final int slot, + final long id + ) { + if (slot >= 0 && slot < this.inventorySlots.size()) { + final Slot s = this.getSlot(slot); + + if (s instanceof SlotCraftingTerm) { + switch (action) { + case CRAFT_SHIFT: + case CRAFT_ITEM: + case CRAFT_STACK: + ((SlotCraftingTerm) s).doClick(action, player); + this.updateHeld(player); + default: + } + } + + if (s instanceof SlotFake) { + final ItemStack hand = player.inventory.getItemStack(); + + switch (action) { + case PICKUP_OR_SET_DOWN: + + if (hand == null) { + s.putStack(null); + } else { + s.putStack(hand.copy()); + } + + break; + case PLACE_SINGLE: + + if (hand != null) { + final 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); + } + + break; + case CREATIVE_DUPLICATE: + case MOVE_REGION: + case SHIFT_CLICK: + default: + break; + } + } + + if (action == InventoryAction.MOVE_REGION) { + if (s instanceof SlotPatternTerm) + return; + //SlotPatternTerm should't transfer its ItemStack to the Player + + final List from = new LinkedList(); + + for (final Object j : this.inventorySlots) { + if (j instanceof Slot && j.getClass() == s.getClass()) { + from.add((Slot) j); + } + } + + for (final Slot fr : from) { + this.transferStackInSlot(player, fr.slotNumber); + } + } + + return; + } + + // get target item. + final IAEItemStack slotItem = this.clientRequestedTargetItem; + + switch (action) { + case SHIFT_CLICK: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize(myItem.getMaxStackSize()); + + final 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.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + if (ais != null) { + adp.addItems(ais.getItemStack()); + } + } + break; + case ROLL_DOWN: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + final int releaseQty = 1; + final ItemStack isg = player.inventory.getItemStack(); + + if (isg != null && releaseQty > 0) { + IAEItemStack ais = AEApi.instance().storage().createItemStack(isg); + ais.setStackSize(1); + final IAEItemStack extracted = ais.copy(); + + ais = Platform.poweredInsert( + this.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + if (ais == null) { + final InventoryAdaptor ia = new AdaptorPlayerHand(player); + + final ItemStack fail + = ia.removeItems(1, extracted.getItemStack(), null); + if (fail == null) { + this.getCellInventory().extractItems( + extracted, Actionable.MODULATE, this.getActionSource() + ); + } + + this.updateHeld(player); + } + } + + break; + case ROLL_UP: + case PICKUP_SINGLE: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + int liftQty = 1; + final 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.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + if (ais != null) { + final InventoryAdaptor ia = new AdaptorPlayerHand(player); + + final ItemStack fail = ia.addItems(ais.getItemStack()); + if (fail != null) { + this.getCellInventory().injectItems( + ais, Actionable.MODULATE, this.getActionSource() + ); + } + + this.updateHeld(player); + } + } + } + break; + case PICKUP_OR_SET_DOWN: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (player.inventory.getItemStack() == null) { + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + ais.setStackSize(ais.getItemStack().getMaxStackSize()); + ais = Platform.poweredExtraction( + this.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + 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.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + if (ais != null) { + player.inventory.setItemStack(ais.getItemStack()); + } else { + player.inventory.setItemStack(null); + } + this.updateHeld(player); + } + + break; + case SPLIT_OR_PLACE_SINGLE: + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (player.inventory.getItemStack() == null) { + if (slotItem != null) { + IAEItemStack ais = slotItem.copy(); + final long maxSize = ais.getItemStack().getMaxStackSize(); + ais.setStackSize(maxSize); + ais = this.getCellInventory().extractItems( + ais, Actionable.SIMULATE, this.getActionSource() + ); + + if (ais != null) { + final long stackSize = Math.min(maxSize, ais.getStackSize()); + ais.setStackSize((stackSize + 1) >> 1); + ais = Platform.poweredExtraction( + this.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + } + + 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.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + if (ais == null) { + final 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) { + final ItemStack is = slotItem.getItemStack(); + is.stackSize = is.getMaxStackSize(); + player.inventory.setItemStack(is); + this.updateHeld(player); + } + break; + case MOVE_REGION: + + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return; + } + + if (slotItem != null) { + final int playerInv = 9 * 4; + for (int slotNum = 0; slotNum < playerInv; slotNum++) { + IAEItemStack ais = slotItem.copy(); + ItemStack myItem = ais.getItemStack(); + + ais.setStackSize(myItem.getMaxStackSize()); + + final 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.getPowerSource(), + this.getCellInventory(), + ais, + this.getActionSource() + ); + if (ais != null) { + adp.addItems(ais.getItemStack()); + } else { + return; + } + } + } + + break; + default: + break; + } + } + + protected void updateHeld(final EntityPlayerMP p) { + if (Platform.isServer()) { + try { + NetworkHandler.instance.sendTo( + new PacketInventoryAction( + InventoryAction.UPDATE_HAND, + 0, + AEItemStack.create(p.inventory.getItemStack()) + ), + p + ); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + + private ItemStack shiftStoreItem(final ItemStack input) { + if (this.getPowerSource() == null || this.getCellInventory() == null) { + return input; + } + final IAEItemStack ais = Platform.poweredInsert( + this.getPowerSource(), + this.getCellInventory(), + AEApi.instance().storage().createItemStack(input), + this.getActionSource() + ); + if (ais == null) { + return null; + } + return ais.getItemStack(); + } + + private void updateSlot(final Slot clickSlot) { + // ??? + this.detectAndSendChanges(); + } + + private 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.setCustomName(name.getCustomName()); + } + + if (this.getCustomName() != null) { + try { + NetworkHandler.instance.sendTo( + new PacketValueConfig("CustomName", this.getCustomName()), + (EntityPlayerMP) this.getInventoryPlayer().player + ); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } + } + } + + public void swapSlotContents(final int slotA, final int slotB) { + final Slot a = this.getSlot(slotA); + final Slot b = this.getSlot(slotB); + + // NPE protection... + if (a == null || b == null) { + return; + } + + final ItemStack isA = a.getStack(); + final ItemStack isB = b.getStack(); + + // something to do? + if (isA == null && isB == null) { + return; + } + + // can take? + + if (isA != null && !a.canTakeStack(this.getInventoryPlayer().player)) { + return; + } + + if (isB != null && !b.canTakeStack(this.getInventoryPlayer().player)) { + return; + } + + // swap valid? + + if (isB != null && !a.isItemValid(isB)) { + return; + } + + 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 (testB != null) { + return; + } + + final int totalA = testA.stackSize; + testA.stackSize = a.getSlotStackLimit(); + testB = testA.copy(); + + testB.stackSize = totalA - testA.stackSize; + } + + if (testB != null && testB.stackSize > b.getSlotStackLimit()) { + if (testA != null) { + return; + } + + final int totalB = testB.stackSize; + testB.stackSize = b.getSlotStackLimit(); + testA = testB.copy(); + + testA.stackSize = totalB - testA.stackSize; + } + + a.putStack(testA); + b.putStack(testB); + } + + public void + onUpdate(final String field, final Object oldValue, final Object newValue) {} + + public void onSlotChange(final Slot s) {} + + public boolean isValidForSlot(final Slot s, final ItemStack i) { + return true; + } + + public IMEInventoryHandler getCellInventory() { + return this.cellInv; + } + + public void setCellInventory(final IMEInventoryHandler cellInv) { + this.cellInv = cellInv; + } + + public String getCustomName() { + return this.customName; + } + + public void setCustomName(final String customName) { + this.customName = customName; + } + + public InventoryPlayer getInventoryPlayer() { + return this.invPlayer; + } + + public boolean isValidContainer() { + return this.isContainerValid; + } + + public void setValidContainer(final boolean isContainerValid) { + this.isContainerValid = isContainerValid; + } + + public ContainerOpenContext getOpenContext() { + return this.openContext; + } + + public void setOpenContext(final ContainerOpenContext openContext) { + this.openContext = openContext; + } + + public IEnergySource getPowerSource() { + return this.powerSrc; + } + + public void setPowerSource(final IEnergySource powerSrc) { + this.powerSrc = powerSrc; + } } diff --git a/src/main/java/appeng/container/ContainerNull.java b/src/main/java/appeng/container/ContainerNull.java index 8e94d3ca..ccb5ac4b 100644 --- a/src/main/java/appeng/container/ContainerNull.java +++ b/src/main/java/appeng/container/ContainerNull.java @@ -18,20 +18,15 @@ package appeng.container; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; - /* * Totally useless container that does nothing. */ -public class ContainerNull extends Container -{ - - @Override - public boolean canInteractWith( final EntityPlayer entityplayer ) - { - return false; - } +public class ContainerNull extends Container { + @Override + public boolean canInteractWith(final EntityPlayer entityplayer) { + return false; + } } diff --git a/src/main/java/appeng/container/ContainerOpenContext.java b/src/main/java/appeng/container/ContainerOpenContext.java index fb401761..a5fb753c 100644 --- a/src/main/java/appeng/container/ContainerOpenContext.java +++ b/src/main/java/appeng/container/ContainerOpenContext.java @@ -18,85 +18,68 @@ package appeng.container; - import appeng.api.parts.IPart; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class ContainerOpenContext { + private final boolean isItem; + private World w; + private int x; + private int y; + private int z; + private ForgeDirection side; -public class ContainerOpenContext -{ + public ContainerOpenContext(final Object myItem) { + final boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; + this.isItem = !isWorld; + } - private final boolean isItem; - private World w; - private int x; - private int y; - private int z; - private ForgeDirection side; + public TileEntity getTile() { + if (this.isItem) { + return null; + } + return this.getWorld().getTileEntity(this.getX(), this.getY(), this.getZ()); + } - public ContainerOpenContext( final Object myItem ) - { - final boolean isWorld = myItem instanceof IPart || myItem instanceof TileEntity; - this.isItem = !isWorld; - } + public ForgeDirection getSide() { + return this.side; + } - public TileEntity getTile() - { - if( this.isItem ) - { - return null; - } - return this.getWorld().getTileEntity( this.getX(), this.getY(), this.getZ() ); - } + public void setSide(final ForgeDirection side) { + this.side = side; + } - public ForgeDirection getSide() - { - return this.side; - } + private int getZ() { + return this.z; + } - public void setSide( final ForgeDirection side ) - { - this.side = side; - } + public void setZ(final int z) { + this.z = z; + } - private int getZ() - { - return this.z; - } + private int getY() { + return this.y; + } - public void setZ( final int z ) - { - this.z = z; - } + public void setY(final int y) { + this.y = y; + } - private int getY() - { - return this.y; - } + private int getX() { + return this.x; + } - public void setY( final int y ) - { - this.y = y; - } + public void setX(final int x) { + this.x = x; + } - private int getX() - { - return this.x; - } + private World getWorld() { + return this.w; + } - public void setX( final int x ) - { - this.x = x; - } - - private World getWorld() - { - return this.w; - } - - public void setWorld( final World w ) - { - this.w = w; - } + public void setWorld(final World w) { + this.w = w; + } } diff --git a/src/main/java/appeng/container/guisync/GuiSync.java b/src/main/java/appeng/container/guisync/GuiSync.java index 14d6e922..5f9d1fe4 100644 --- a/src/main/java/appeng/container/guisync/GuiSync.java +++ b/src/main/java/appeng/container/guisync/GuiSync.java @@ -18,21 +18,17 @@ package appeng.container.guisync; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Annotates that this field should be synchronized between the server and client. * Requires the field to be public. */ -@Retention( RetentionPolicy.RUNTIME ) -@Target( ElementType.FIELD ) -public @interface GuiSync -{ - - int value(); +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +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 d29ccb98..54eb32cc 100644 --- a/src/main/java/appeng/container/guisync/SyncData.java +++ b/src/main/java/appeng/container/guisync/SyncData.java @@ -18,6 +18,9 @@ package appeng.container.guisync; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.EnumSet; import appeng.container.AEBaseContainer; import appeng.core.AELog; @@ -27,182 +30,126 @@ import appeng.core.sync.packets.PacketValueConfig; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.ICrafting; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.EnumSet; +public class SyncData { + private final AEBaseContainer source; + private final Field field; + private final int channel; + private Object clientVersion; + public SyncData( + final AEBaseContainer container, final Field field, final GuiSync annotation + ) { + this.clientVersion = null; + this.source = container; + this.field = field; + this.channel = annotation.value(); + } -public class SyncData -{ + public int getChannel() { + return this.channel; + } - private final AEBaseContainer source; - private final Field field; - private final int channel; - private Object clientVersion; + public void tick(final ICrafting c) { + try { + final Object val = this.field.get(this.source); + if (val != null && this.clientVersion == null) { + this.send(c, val); + } else if (!val.equals(this.clientVersion)) { + this.send(c, val); + } + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IOException e) { + AELog.debug(e); + } + } - public SyncData( final AEBaseContainer container, final Field field, final GuiSync annotation ) - { - this.clientVersion = null; - this.source = container; - this.field = field; - this.channel = annotation.value(); - } + private void send(final ICrafting o, final Object val) throws IOException { + if (val instanceof String) { + if (o instanceof EntityPlayerMP) { + NetworkHandler.instance.sendTo( + new PacketValueConfig("SyncDat." + this.channel, (String) val), + (EntityPlayerMP) o + ); + } + } else if (this.field.getType().isEnum()) { + o.sendProgressBarUpdate(this.source, this.channel, ((Enum) val).ordinal()); - public int getChannel() - { - return this.channel; - } + } else if (val instanceof Long || val.getClass() == long.class) { + NetworkHandler.instance.sendTo( + new PacketProgressBar(this.channel, (Long) val), (EntityPlayerMP) o + ); - public void tick( final ICrafting c ) - { - try - { - final Object val = this.field.get( this.source ); - if( val != null && this.clientVersion == null ) - { - this.send( c, val ); - } - else if( !val.equals( this.clientVersion ) ) - { - this.send( c, val ); - } - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + } else if (val instanceof Boolean || val.getClass() == boolean.class) { + o.sendProgressBarUpdate(this.source, this.channel, ((Boolean) val) ? 1 : 0); + } else { + o.sendProgressBarUpdate(this.source, this.channel, (Integer) val); + } - private void send( final ICrafting o, final Object val ) throws IOException - { - if( val instanceof String ) - { - if( o instanceof EntityPlayerMP ) - { - NetworkHandler.instance.sendTo( new PacketValueConfig( "SyncDat." + this.channel, (String) val ), (EntityPlayerMP) o ); - } - } - else if( this.field.getType().isEnum() ) - { - o.sendProgressBarUpdate( this.source, this.channel, ( (Enum) val ).ordinal() ); - } - 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 ) - { - o.sendProgressBarUpdate( this.source, this.channel, ( (Boolean) val ) ? 1 : 0 ); - } - else - { - o.sendProgressBarUpdate( this.source, this.channel, (Integer) val ); - } + this.clientVersion = val; + } - this.clientVersion = val; - } + public void update(final Object val) { + try { + final Object oldValue = this.field.get(this.source); + if (val instanceof String) { + this.updateString(oldValue, (String) val); + } else { + this.updateValue(oldValue, (Long) val); + } + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } + } - public void update( final Object val ) - { - try - { - final Object oldValue = this.field.get( this.source ); - if( val instanceof String ) - { - this.updateString( oldValue, (String) val ); - } - else - { - this.updateValue( oldValue, (Long) val ); - } - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - } + private void updateString(final Object oldValue, final String val) { + try { + this.field.set(this.source, val); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } + } - private void updateString( final Object oldValue, final String val ) - { - try - { - this.field.set( this.source, val ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - } + private void updateValue(final Object oldValue, final long val) { + try { + if (this.field.getType().isEnum()) { + final EnumSet valList + = EnumSet.allOf((Class) this.field.getType()); + for (final 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); + } + } - private void updateValue( final Object oldValue, final long val ) - { - try - { - if( this.field.getType().isEnum() ) - { - final EnumSet valList = EnumSet.allOf( (Class) this.field.getType() ); - for( final 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( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - } + this.source.onUpdate( + this.field.getName(), oldValue, this.field.get(this.source) + ); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java b/src/main/java/appeng/container/implementations/ContainerCellWorkbench.java index 8d99d6bd..a61739e0 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 appeng.api.AEApi; import appeng.api.config.CopyMode; @@ -43,308 +44,293 @@ import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public class ContainerCellWorkbench extends ContainerUpgradeable { + private final TileCellWorkbench workBench; + private final AppEngNullInventory nullInventory = new AppEngNullInventory(); + @GuiSync(2) + public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; + private ItemStack prevStack = null; + private int lastUpgrades = 0; + public ContainerCellWorkbench(final InventoryPlayer ip, final TileCellWorkbench te) { + super(ip, te); + this.workBench = te; + } -public class ContainerCellWorkbench extends ContainerUpgradeable -{ - private final TileCellWorkbench workBench; - private final AppEngNullInventory nullInventory = new AppEngNullInventory(); - @GuiSync( 2 ) - public CopyMode copyMode = CopyMode.CLEAR_ON_REMOVE; - private ItemStack prevStack = null; - private int lastUpgrades = 0; + public void setFuzzy(final FuzzyMode valueOf) { + final ICellWorkbenchItem cwi = this.workBench.getCell(); + if (cwi != null) { + cwi.setFuzzyMode( + this.workBench.getInventoryByName("cell").getStackInSlot(0), valueOf + ); + } + } - public ContainerCellWorkbench( final InventoryPlayer ip, final TileCellWorkbench te ) - { - super( ip, te ); - this.workBench = te; - } + public void nextWorkBenchCopyMode() { + this.workBench.getConfigManager().putSetting( + Settings.COPY_MODE, Platform.nextEnum(this.getWorkBenchCopyMode()) + ); + } - public void setFuzzy( final FuzzyMode valueOf ) - { - final ICellWorkbenchItem cwi = this.workBench.getCell(); - if( cwi != null ) - { - cwi.setFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ), valueOf ); - } - } + private CopyMode getWorkBenchCopyMode() { + return (CopyMode) this.workBench.getConfigManager().getSetting(Settings.COPY_MODE + ); + } - public void nextWorkBenchCopyMode() - { - this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, Platform.nextEnum( this.getWorkBenchCopyMode() ) ); - } + @Override + protected int getHeight() { + return 251; + } - private CopyMode getWorkBenchCopyMode() - { - return (CopyMode) this.workBench.getConfigManager().getSetting( Settings.COPY_MODE ); - } + @Override + protected void setupConfig() { + final IInventory cell = this.getUpgradeable().getInventoryByName("cell"); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, + cell, + 0, + 152, + 8, + this.getInventoryPlayer() + )); - @Override - protected int getHeight() - { - return 251; - } + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + final IInventory upgradeInventory = new Upgrades(); + // null, 3 * 8 ); - @Override - protected void setupConfig() - { - final IInventory cell = this.getUpgradeable().getInventoryByName( "cell" ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.WORKBENCH_CELL, cell, 0, 152, 8, this.getInventoryPlayer() ) ); + int offset = 0; + final int x = 8; + final int y = 29; + 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++; + } + } - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - final IInventory upgradeInventory = new Upgrades(); - // null, 3 * 8 ); + for (int zz = 0; zz < 3; zz++) { + for (int z = 0; z < 8; z++) { + final int iSLot = zz * 8 + z; + this.addSlotToContainer(new OptionalSlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgradeInventory, + this, + iSLot, + 187 + zz * 18, + 8 + 18 * z, + iSLot, + this.getInventoryPlayer() + )); + } + } + /* + * 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 ) ); } + */ + } - int offset = 0; - final int x = 8; - final int y = 29; - 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++; - } - } + @Override + public int availableUpgrades() { + final ItemStack is = this.workBench.getInventoryByName("cell").getStackInSlot(0); + if (this.prevStack != is) { + this.prevStack = is; + this.lastUpgrades = this.getCellUpgradeInventory().getSizeInventory(); + } + return this.lastUpgrades; + } - for( int zz = 0; zz < 3; zz++ ) - { - for( int z = 0; z < 8; z++ ) - { - final int iSLot = zz * 8 + z; - this.addSlotToContainer( new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgradeInventory, this, iSLot, 187 + zz * 18, 8 + 18 * z, iSLot, this.getInventoryPlayer() ) ); - } - } - /* - * 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 void detectAndSendChanges() { + final ItemStack is = this.workBench.getInventoryByName("cell").getStackInSlot(0); + if (Platform.isServer()) { + if (this.workBench.getWorldObj().getTileEntity( + this.workBench.xCoord, this.workBench.yCoord, this.workBench.zCoord + ) + != this.workBench) { + this.setValidContainer(false); + } - @Override - public int availableUpgrades() - { - final ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if( this.prevStack != is ) - { - this.prevStack = is; - this.lastUpgrades = this.getCellUpgradeInventory().getSizeInventory(); - } - return this.lastUpgrades; - } + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; - @Override - public void detectAndSendChanges() - { - final ItemStack is = this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ); - if( Platform.isServer() ) - { - if( this.workBench.getWorldObj().getTileEntity( this.workBench.xCoord, this.workBench.yCoord, this.workBench.zCoord ) != this.workBench ) - { - this.setValidContainer( false ); - } + if (this.prevStack != is) { + // if the bars changed an item was probably made, so just send shit! + for (final Object s : this.inventorySlots) { + if (s instanceof OptionalSlotRestrictedInput) { + final OptionalSlotRestrictedInput sri + = (OptionalSlotRestrictedInput) s; + icrafting.sendSlotContents( + this, sri.slotNumber, sri.getStack() + ); + } + } + ((EntityPlayerMP) icrafting).isChangingQuantityOnly = false; + } + } - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; + this.setCopyMode(this.getWorkBenchCopyMode()); + this.setFuzzyMode(this.getWorkBenchFuzzyMode()); + } - if( this.prevStack != is ) - { - // if the bars changed an item was probably made, so just send shit! - for( final Object s : this.inventorySlots ) - { - if( s instanceof OptionalSlotRestrictedInput ) - { - final OptionalSlotRestrictedInput sri = (OptionalSlotRestrictedInput) s; - icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); - } - } - ( (EntityPlayerMP) icrafting ).isChangingQuantityOnly = false; - } - } + this.prevStack = is; + this.standardDetectAndSendChanges(); + } - this.setCopyMode( this.getWorkBenchCopyMode() ); - this.setFuzzyMode( this.getWorkBenchFuzzyMode() ); - } + @Override + public boolean isSlotEnabled(final int idx) { + return idx < this.availableUpgrades(); + } - this.prevStack = is; - this.standardDetectAndSendChanges(); - } + public IInventory getCellUpgradeInventory() { + final IInventory upgradeInventory = this.workBench.getCellUpgradeInventory(); - @Override - public boolean isSlotEnabled( final int idx ) - { - return idx < this.availableUpgrades(); - } + return upgradeInventory == null ? this.nullInventory : upgradeInventory; + } - public IInventory getCellUpgradeInventory() - { - final IInventory upgradeInventory = this.workBench.getCellUpgradeInventory(); + @Override + public void + onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("copyMode")) { + this.workBench.getConfigManager().putSetting( + Settings.COPY_MODE, this.getCopyMode() + ); + } - return upgradeInventory == null ? this.nullInventory : upgradeInventory; - } + super.onUpdate(field, oldValue, newValue); + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "copyMode" ) ) - { - this.workBench.getConfigManager().putSetting( Settings.COPY_MODE, this.getCopyMode() ); - } + public void clear() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + for (int x = 0; x < inv.getSizeInventory(); x++) { + inv.setInventorySlotContents(x, null); + } + this.detectAndSendChanges(); + } - super.onUpdate( field, oldValue, newValue ); - } + private FuzzyMode getWorkBenchFuzzyMode() { + final ICellWorkbenchItem cwi = this.workBench.getCell(); + if (cwi != null) { + return cwi.getFuzzyMode( + this.workBench.getInventoryByName("cell").getStackInSlot(0) + ); + } + return FuzzyMode.IGNORE_ALL; + } - public void clear() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - inv.setInventorySlotContents( x, null ); - } - this.detectAndSendChanges(); - } + public void partition() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); - private FuzzyMode getWorkBenchFuzzyMode() - { - final ICellWorkbenchItem cwi = this.workBench.getCell(); - if( cwi != null ) - { - return cwi.getFuzzyMode( this.workBench.getInventoryByName( "cell" ).getStackInSlot( 0 ) ); - } - return FuzzyMode.IGNORE_ALL; - } + final IMEInventory cellInv + = AEApi.instance().registries().cell().getCellInventory( + this.getUpgradeable().getInventoryByName("cell").getStackInSlot(0), + null, + StorageChannel.ITEMS + ); - public void partition() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); + Iterator i = new NullIterator(); + if (cellInv != null) { + final IItemList list + = cellInv.getAvailableItems(AEApi.instance().storage().createItemList()); + i = list.iterator(); + } - final IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory( this.getUpgradeable().getInventoryByName( "cell" ).getStackInSlot( 0 ), null, StorageChannel.ITEMS ); + for (int x = 0; x < inv.getSizeInventory(); x++) { + if (i.hasNext()) { + final ItemStack g = i.next().getItemStack(); + g.stackSize = 1; + inv.setInventorySlotContents(x, g); + } else { + inv.setInventorySlotContents(x, null); + } + } - Iterator i = new NullIterator(); - if( cellInv != null ) - { - final IItemList list = cellInv.getAvailableItems( AEApi.instance().storage().createItemList() ); - i = list.iterator(); - } + this.detectAndSendChanges(); + } - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - if( i.hasNext() ) - { - final ItemStack g = i.next().getItemStack(); - g.stackSize = 1; - inv.setInventorySlotContents( x, g ); - } - else - { - inv.setInventorySlotContents( x, null ); - } - } + public CopyMode getCopyMode() { + return this.copyMode; + } - this.detectAndSendChanges(); - } + private void setCopyMode(final CopyMode copyMode) { + this.copyMode = copyMode; + } - public CopyMode getCopyMode() - { - return this.copyMode; - } + private class Upgrades implements IInventory { + @Override + public int getSizeInventory() { + return ContainerCellWorkbench.this.getCellUpgradeInventory().getSizeInventory( + ); + } - private void setCopyMode( final CopyMode copyMode ) - { - this.copyMode = copyMode; - } + @Override + public ItemStack getStackInSlot(final int i) { + return ContainerCellWorkbench.this.getCellUpgradeInventory().getStackInSlot(i + ); + } - private class Upgrades implements IInventory - { + @Override + public ItemStack decrStackSize(final int i, final int j) { + final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); + final ItemStack is = inv.decrStackSize(i, j); + inv.markDirty(); + return is; + } - @Override - public int getSizeInventory() - { - return ContainerCellWorkbench.this.getCellUpgradeInventory().getSizeInventory(); - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); + final ItemStack is = inv.getStackInSlotOnClosing(i); + inv.markDirty(); + return is; + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return ContainerCellWorkbench.this.getCellUpgradeInventory().getStackInSlot( i ); - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); + inv.setInventorySlotContents(i, itemstack); + inv.markDirty(); + } - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); - final ItemStack is = inv.decrStackSize( i, j ); - inv.markDirty(); - return is; - } + @Override + public String getInventoryName() { + return "Upgrades"; + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); - final ItemStack is = inv.getStackInSlotOnClosing( i ); - inv.markDirty(); - return is; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - final IInventory inv = ContainerCellWorkbench.this.getCellUpgradeInventory(); - inv.setInventorySlotContents( i, itemstack ); - inv.markDirty(); - } + @Override + public int getInventoryStackLimit() { + return 1; + } - @Override - public String getInventoryName() - { - return "Upgrades"; - } + @Override + public void markDirty() {} - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } - @Override - public int getInventoryStackLimit() - { - return 1; - } + @Override + public void openInventory() {} - @Override - public void markDirty() - { + @Override + public void closeInventory() {} - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return ContainerCellWorkbench.this.getCellUpgradeInventory().isItemValidForSlot( i, itemstack ); - } - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return ContainerCellWorkbench.this.getCellUpgradeInventory() + .isItemValidForSlot(i, itemstack); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerChest.java b/src/main/java/appeng/container/implementations/ContainerChest.java index b168f2f4..982d02d1 100644 --- a/src/main/java/appeng/container/implementations/ContainerChest.java +++ b/src/main/java/appeng/container/implementations/ContainerChest.java @@ -18,25 +18,27 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileChest; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerChest extends AEBaseContainer { + private final TileChest chest; -public class ContainerChest extends AEBaseContainer -{ + public ContainerChest(final InventoryPlayer ip, final TileChest chest) { + super(ip, chest, null); + this.chest = chest; - private final TileChest chest; + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, + this.chest, + 1, + 80, + 37, + this.getInventoryPlayer() + )); - public ContainerChest( final InventoryPlayer ip, final TileChest chest ) - { - super( ip, chest, null ); - this.chest = chest; - - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.STORAGE_CELLS, this.chest, 1, 80, 37, this.getInventoryPlayer() ) ); - - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + 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 9602710a..093e6304 100644 --- a/src/main/java/appeng/container/implementations/ContainerCondenser.java +++ b/src/main/java/appeng/container/implementations/ContainerCondenser.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.CondenserOutput; import appeng.api.config.Settings; import appeng.container.AEBaseContainer; @@ -30,65 +29,71 @@ import appeng.tile.misc.TileCondenser; import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerCondenser extends AEBaseContainer implements IProgressProvider { + private final TileCondenser condenser; + @GuiSync(0) + public long requiredEnergy = 0; + @GuiSync(1) + public long storedPower = 0; + @GuiSync(2) + public CondenserOutput output = CondenserOutput.TRASH; -public class ContainerCondenser extends AEBaseContainer implements IProgressProvider -{ + public ContainerCondenser(final InventoryPlayer ip, final TileCondenser condenser) { + super(ip, condenser, null); + this.condenser = condenser; - private final TileCondenser condenser; - @GuiSync( 0 ) - public long requiredEnergy = 0; - @GuiSync( 1 ) - public long storedPower = 0; - @GuiSync( 2 ) - public CondenserOutput output = CondenserOutput.TRASH; + 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) + ); - public ContainerCondenser( final InventoryPlayer ip, final TileCondenser condenser ) - { - super( ip, condenser, null ); - this.condenser = condenser; + this.bindPlayerInventory(ip, 0, 197 - /* height of player inventory */ 82); + } - 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 ) ); + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + final double maxStorage = this.condenser.getStorage(); + final double requiredEnergy = this.condenser.getRequiredPower(); - this.bindPlayerInventory( ip, 0, 197 - /* height of player inventory */82 ); - } + this.requiredEnergy = requiredEnergy == 0 + ? (int) maxStorage + : (int) Math.min(requiredEnergy, maxStorage); + this.storedPower = (int) this.condenser.getStoredPower(); + this.setOutput((CondenserOutput) this.condenser.getConfigManager().getSetting( + Settings.CONDENSER_OUTPUT + )); + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - final double maxStorage = this.condenser.getStorage(); - final double requiredEnergy = this.condenser.getRequiredPower(); + super.detectAndSendChanges(); + } - this.requiredEnergy = requiredEnergy == 0 ? (int) maxStorage : (int) Math.min( requiredEnergy, maxStorage ); - this.storedPower = (int) this.condenser.getStoredPower(); - this.setOutput( (CondenserOutput) this.condenser.getConfigManager().getSetting( Settings.CONDENSER_OUTPUT ) ); - } + @Override + public int getCurrentProgress() { + return (int) this.storedPower; + } - super.detectAndSendChanges(); - } + @Override + public int getMaxProgress() { + return (int) this.requiredEnergy; + } - @Override - public int getCurrentProgress() - { - return (int) this.storedPower; - } + public CondenserOutput getOutput() { + return this.output; + } - @Override - public int getMaxProgress() - { - return (int) this.requiredEnergy; - } - - public CondenserOutput getOutput() - { - return this.output; - } - - private void setOutput( final CondenserOutput output ) - { - this.output = output; - } + private void setOutput(final CondenserOutput output) { + this.output = output; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftAmount.java b/src/main/java/appeng/container/implementations/ContainerCraftAmount.java index c7fc0e2d..a6863e6f 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 javax.annotation.Nonnull; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; @@ -33,58 +34,48 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.world.World; -import javax.annotation.Nonnull; +public class ContainerCraftAmount extends AEBaseContainer { + private final Slot craftingItem; + private IAEItemStack itemToCreate; + public ContainerCraftAmount(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); -public class ContainerCraftAmount extends AEBaseContainer -{ + this.craftingItem + = new SlotInaccessible(new AppEngInternalInventory(null, 1), 0, 34, 53); + this.addSlotToContainer(this.getCraftingItem()); + } - private final Slot craftingItem; - private IAEItemStack itemToCreate; + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + this.verifyPermissions(SecurityPermissions.CRAFT, false); + } - public ContainerCraftAmount( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); + public IGrid getGrid() { + final IActionHost h = ((IActionHost) this.getTarget()); + return h.getActionableNode().getGrid(); + } - this.craftingItem = new SlotInaccessible( new AppEngInternalInventory( null, 1 ), 0, 34, 53 ); - this.addSlotToContainer( this.getCraftingItem() ); - } + public World getWorld() { + return this.getPlayerInv().player.worldObj; + } - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - this.verifyPermissions( SecurityPermissions.CRAFT, false ); - } + public BaseActionSource getActionSrc() { + return new PlayerSource( + this.getPlayerInv().player, (IActionHost) this.getTarget() + ); + } - public IGrid getGrid() - { - final IActionHost h = ( (IActionHost) this.getTarget() ); - return h.getActionableNode().getGrid(); - } + public Slot getCraftingItem() { + return this.craftingItem; + } - public World getWorld() - { - return this.getPlayerInv().player.worldObj; - } + public IAEItemStack getItemToCraft() { + return this.itemToCreate; + } - public BaseActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); - } - - public Slot getCraftingItem() - { - return this.craftingItem; - } - - public IAEItemStack getItemToCraft() - { - return this.itemToCreate; - } - - public void setItemToCraft( @Nonnull final IAEItemStack itemToCreate ) - { - this.itemToCreate = itemToCreate; - } + public void setItemToCraft(@Nonnull final IAEItemStack itemToCreate) { + this.itemToCreate = itemToCreate; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java index a069ad3d..d8675d31 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftConfirm.java @@ -18,6 +18,11 @@ package appeng.container.implementations; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.concurrent.Future; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -56,426 +61,368 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.concurrent.Future; - - -public class ContainerCraftConfirm extends AEBaseContainer -{ - - private final ArrayList cpus = new ArrayList(); - private Future job; - private ICraftingJob result; - @GuiSync( 0 ) - public long bytesUsed; - @GuiSync( 1 ) - public long cpuBytesAvail; - @GuiSync( 2 ) - public int cpuCoProcessors; - @GuiSync( 3 ) - public boolean autoStart = false; - @GuiSync( 4 ) - public boolean simulation = true; - @GuiSync( 5 ) - public int selectedCpu = -1; - @GuiSync( 6 ) - public boolean noCPU = true; - @GuiSync( 7 ) - public String myName = ""; - - public ContainerCraftConfirm( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - } - - public void cycleCpu( final boolean next ) - { - if( next ) - { - this.setSelectedCpu( this.getSelectedCpu() + 1 ); - } - else - { - this.setSelectedCpu( this.getSelectedCpu() - 1 ); - } - - if( this.getSelectedCpu() < -1 ) - { - this.setSelectedCpu( this.cpus.size() - 1 ); - } - else if( this.getSelectedCpu() >= this.cpus.size() ) - { - this.setSelectedCpu( -1 ); - } - - if( this.getSelectedCpu() == -1 ) - { - this.setCpuAvailableBytes( 0 ); - this.setCpuCoProcessors( 0 ); - this.setName( "" ); - } - else - { - this.setName( this.cpus.get( this.getSelectedCpu() ).getName() ); - this.setCpuAvailableBytes( this.cpus.get( this.getSelectedCpu() ).getSize() ); - this.setCpuCoProcessors( this.cpus.get( this.getSelectedCpu() ).getProcessors() ); - } - } - - @Override - public void detectAndSendChanges() - { - if( Platform.isClient() ) - { - return; - } - - final ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); - final ImmutableSet cpuSet = cc.getCpus(); - - int matches = 0; - boolean changed = false; - for( final ICraftingCPU c : cpuSet ) - { - boolean found = false; - for( final CraftingCPURecord ccr : this.cpus ) - { - if( ccr.getCpu() == c ) - { - found = true; - } - } - - final boolean matched = this.cpuMatches( c ); - - if( matched ) - { - matches++; - } - - if( found == !matched ) - { - changed = true; - } - } - - if( changed || this.cpus.size() != matches ) - { - this.cpus.clear(); - for( final ICraftingCPU c : cpuSet ) - { - if( this.cpuMatches( c ) ) - { - this.cpus.add( new CraftingCPURecord( c.getAvailableStorage(), c.getCoProcessors(), c ) ); - } - } - - this.sendCPUs(); - } - - this.setNoCPU( this.cpus.isEmpty() ); - - super.detectAndSendChanges(); - - if( this.getJob() != null && this.getJob().isDone() ) - { - try - { - this.result = this.getJob().get(); - - if( !this.result.isSimulation() ) - { - this.setSimulation( false ); - if( this.isAutoStart() ) - { - this.startJob(); - return; - } - } - else - { - this.setSimulation( true ); - } - - try - { - final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); - final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); - final PacketMEInventoryUpdate c = this.result.isSimulation() ? new PacketMEInventoryUpdate( (byte) 2 ) : null; - - final IItemList plan = AEApi.instance().storage().createItemList(); - this.result.populatePlan( plan ); - - this.setUsedBytes( this.result.getByteTotal() ); - - for( final IAEItemStack out : plan ) - { - - IAEItemStack o = out.copy(); - o.reset(); - o.setStackSize( out.getStackSize() ); - - final IAEItemStack p = out.copy(); - p.reset(); - p.setStackSize( out.getCountRequestable() ); - - final IStorageGrid sg = this.getGrid().getCache( IStorageGrid.class ); - final IMEInventory items = sg.getItemInventory(); - - IAEItemStack m = null; - if( c != null && this.result.isSimulation() ) - { - m = o.copy(); - o = items.extractItems( o, Actionable.SIMULATE, this.getActionSource() ); - - if( o == null ) - { - o = m.copy(); - o.setStackSize( 0 ); - } - - m.setStackSize( m.getStackSize() - o.getStackSize() ); - } - - if( o.getStackSize() > 0 ) - { - a.appendItem( o ); - } - - if( p.getStackSize() > 0 ) - { - b.appendItem( p ); - } - - if( c != null && m != null && m.getStackSize() > 0 ) - { - c.appendItem( m ); - } - } - - for( final Object g : this.crafters ) - { - if( g instanceof EntityPlayer ) - { - NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); - NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); - if( c != null ) - { - NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); - } - } - } - } - catch( final IOException e ) - { - // :P - } - } - catch( final Throwable e ) - { - this.getPlayerInv().player.addChatMessage( new ChatComponentText( "Error: " + e.toString() ) ); - AELog.debug( e ); - this.setValidContainer( false ); - this.result = null; - } - - this.setJob( null ); - } - this.verifyPermissions( SecurityPermissions.CRAFT, false ); - } - - private IGrid getGrid() - { - final IActionHost h = ( (IActionHost) this.getTarget() ); - return h.getActionableNode().getGrid(); - } - - private boolean cpuMatches( final ICraftingCPU c ) - { - return c.getAvailableStorage() >= this.getUsedBytes() && !c.isBusy(); - } - - private void sendCPUs() - { - Collections.sort( this.cpus ); - - if( this.getSelectedCpu() >= this.cpus.size() ) - { - this.setSelectedCpu( -1 ); - this.setCpuAvailableBytes( 0 ); - this.setCpuCoProcessors( 0 ); - this.setName( "" ); - } - else if( this.getSelectedCpu() != -1 ) - { - this.setName( this.cpus.get( this.getSelectedCpu() ).getName() ); - this.setCpuAvailableBytes( this.cpus.get( this.getSelectedCpu() ).getSize() ); - this.setCpuCoProcessors( this.cpus.get( this.getSelectedCpu() ).getProcessors() ); - } - } - - public void startJob() - { - GuiBridge originalGui = null; - - final IActionHost ah = this.getActionHost(); - if( ah instanceof WirelessTerminalGuiObject ) - { - originalGui = GuiBridge.GUI_WIRELESS_TERM; - } - - if( ah instanceof PartTerminal ) - { - originalGui = GuiBridge.GUI_ME; - } - - if( ah instanceof PartCraftingTerminal ) - { - originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; - } - - if( ah instanceof PartPatternTerminal ) - { - originalGui = GuiBridge.GUI_PATTERN_TERMINAL; - } - - if( this.result != null && !this.isSimulation() ) - { - final ICraftingGrid cc = this.getGrid().getCache( ICraftingGrid.class ); - final ICraftingLink g = cc.submitJob( this.result, null, this.getSelectedCpu() == -1 ? null : this.cpus.get( this.getSelectedCpu() ).getCpu(), true, this.getActionSrc() ); - this.setAutoStart( false ); - if( g != null && originalGui != null && this.getOpenContext() != null ) - { - NetworkHandler.instance.sendTo( new PacketSwitchGuis( originalGui ), (EntityPlayerMP) this.getInventoryPlayer().player ); - - final TileEntity te = this.getOpenContext().getTile(); - Platform.openGUI( this.getInventoryPlayer().player, te, this.getOpenContext().getSide(), originalGui ); - } - } - } - - private BaseActionSource getActionSrc() - { - return new PlayerSource( this.getPlayerInv().player, (IActionHost) this.getTarget() ); - } - - @Override - public void removeCraftingFromCrafters( final ICrafting c ) - { - super.removeCraftingFromCrafters( c ); - if( this.getJob() != null ) - { - this.getJob().cancel( true ); - this.setJob( null ); - } - } - - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - super.onContainerClosed( par1EntityPlayer ); - if( this.getJob() != null ) - { - this.getJob().cancel( true ); - this.setJob( null ); - } - } - - public World getWorld() - { - return this.getPlayerInv().player.worldObj; - } - - public boolean isAutoStart() - { - return this.autoStart; - } - - public void setAutoStart( final boolean autoStart ) - { - this.autoStart = autoStart; - } - - public long getUsedBytes() - { - return this.bytesUsed; - } - - private void setUsedBytes( final long bytesUsed ) - { - this.bytesUsed = bytesUsed; - } - - public long getCpuAvailableBytes() - { - return this.cpuBytesAvail; - } - - private void setCpuAvailableBytes( final long cpuBytesAvail ) - { - this.cpuBytesAvail = cpuBytesAvail; - } - - public int getCpuCoProcessors() - { - return this.cpuCoProcessors; - } - - private void setCpuCoProcessors( final int cpuCoProcessors ) - { - this.cpuCoProcessors = cpuCoProcessors; - } - - public int getSelectedCpu() - { - return this.selectedCpu; - } - - private void setSelectedCpu( final int selectedCpu ) - { - this.selectedCpu = selectedCpu; - } - - public String getName() - { - return this.myName; - } - - private void setName( @Nonnull final String myName ) - { - this.myName = myName; - } - - public boolean hasNoCPU() - { - return this.noCPU; - } - - private void setNoCPU( final boolean noCPU ) - { - this.noCPU = noCPU; - } - - public boolean isSimulation() - { - return this.simulation; - } - - private void setSimulation( final boolean simulation ) - { - this.simulation = simulation; - } - - private Future getJob() - { - return this.job; - } - - public void setJob( final Future job ) - { - this.job = job; - } +public class ContainerCraftConfirm extends AEBaseContainer { + private final ArrayList cpus = new ArrayList(); + private Future job; + private ICraftingJob result; + @GuiSync(0) + public long bytesUsed; + @GuiSync(1) + public long cpuBytesAvail; + @GuiSync(2) + public int cpuCoProcessors; + @GuiSync(3) + public boolean autoStart = false; + @GuiSync(4) + public boolean simulation = true; + @GuiSync(5) + public int selectedCpu = -1; + @GuiSync(6) + public boolean noCPU = true; + @GuiSync(7) + public String myName = ""; + + public ContainerCraftConfirm(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); + } + + public void cycleCpu(final boolean next) { + if (next) { + this.setSelectedCpu(this.getSelectedCpu() + 1); + } else { + this.setSelectedCpu(this.getSelectedCpu() - 1); + } + + if (this.getSelectedCpu() < -1) { + this.setSelectedCpu(this.cpus.size() - 1); + } else if (this.getSelectedCpu() >= this.cpus.size()) { + this.setSelectedCpu(-1); + } + + if (this.getSelectedCpu() == -1) { + this.setCpuAvailableBytes(0); + this.setCpuCoProcessors(0); + this.setName(""); + } else { + this.setName(this.cpus.get(this.getSelectedCpu()).getName()); + this.setCpuAvailableBytes(this.cpus.get(this.getSelectedCpu()).getSize()); + this.setCpuCoProcessors(this.cpus.get(this.getSelectedCpu()).getProcessors()); + } + } + + @Override + public void detectAndSendChanges() { + if (Platform.isClient()) { + return; + } + + final ICraftingGrid cc = this.getGrid().getCache(ICraftingGrid.class); + final ImmutableSet cpuSet = cc.getCpus(); + + int matches = 0; + boolean changed = false; + for (final ICraftingCPU c : cpuSet) { + boolean found = false; + for (final CraftingCPURecord ccr : this.cpus) { + if (ccr.getCpu() == c) { + found = true; + } + } + + final boolean matched = this.cpuMatches(c); + + if (matched) { + matches++; + } + + if (found == !matched) { + changed = true; + } + } + + if (changed || this.cpus.size() != matches) { + this.cpus.clear(); + for (final ICraftingCPU c : cpuSet) { + if (this.cpuMatches(c)) { + this.cpus.add(new CraftingCPURecord( + c.getAvailableStorage(), c.getCoProcessors(), c + )); + } + } + + this.sendCPUs(); + } + + this.setNoCPU(this.cpus.isEmpty()); + + super.detectAndSendChanges(); + + if (this.getJob() != null && this.getJob().isDone()) { + try { + this.result = this.getJob().get(); + + if (!this.result.isSimulation()) { + this.setSimulation(false); + if (this.isAutoStart()) { + this.startJob(); + return; + } + } else { + this.setSimulation(true); + } + + try { + final PacketMEInventoryUpdate a + = new PacketMEInventoryUpdate((byte) 0); + final PacketMEInventoryUpdate b + = new PacketMEInventoryUpdate((byte) 1); + final PacketMEInventoryUpdate c = this.result.isSimulation() + ? new PacketMEInventoryUpdate((byte) 2) + : null; + + final IItemList plan + = AEApi.instance().storage().createItemList(); + this.result.populatePlan(plan); + + this.setUsedBytes(this.result.getByteTotal()); + + for (final IAEItemStack out : plan) { + IAEItemStack o = out.copy(); + o.reset(); + o.setStackSize(out.getStackSize()); + + final IAEItemStack p = out.copy(); + p.reset(); + p.setStackSize(out.getCountRequestable()); + + final IStorageGrid sg + = this.getGrid().getCache(IStorageGrid.class); + final IMEInventory items = sg.getItemInventory(); + + IAEItemStack m = null; + if (c != null && this.result.isSimulation()) { + m = o.copy(); + o = items.extractItems( + o, Actionable.SIMULATE, this.getActionSource() + ); + + if (o == null) { + o = m.copy(); + o.setStackSize(0); + } + + m.setStackSize(m.getStackSize() - o.getStackSize()); + } + + if (o.getStackSize() > 0) { + a.appendItem(o); + } + + if (p.getStackSize() > 0) { + b.appendItem(p); + } + + if (c != null && m != null && m.getStackSize() > 0) { + c.appendItem(m); + } + } + + for (final Object g : this.crafters) { + if (g instanceof EntityPlayer) { + NetworkHandler.instance.sendTo(a, (EntityPlayerMP) g); + NetworkHandler.instance.sendTo(b, (EntityPlayerMP) g); + if (c != null) { + NetworkHandler.instance.sendTo(c, (EntityPlayerMP) g); + } + } + } + } catch (final IOException e) { + // :P + } + } catch (final Throwable e) { + this.getPlayerInv().player.addChatMessage( + new ChatComponentText("Error: " + e.toString()) + ); + AELog.debug(e); + this.setValidContainer(false); + this.result = null; + } + + this.setJob(null); + } + this.verifyPermissions(SecurityPermissions.CRAFT, false); + } + + private IGrid getGrid() { + final IActionHost h = ((IActionHost) this.getTarget()); + return h.getActionableNode().getGrid(); + } + + private boolean cpuMatches(final ICraftingCPU c) { + return c.getAvailableStorage() >= this.getUsedBytes() && !c.isBusy(); + } + + private void sendCPUs() { + Collections.sort(this.cpus); + + if (this.getSelectedCpu() >= this.cpus.size()) { + this.setSelectedCpu(-1); + this.setCpuAvailableBytes(0); + this.setCpuCoProcessors(0); + this.setName(""); + } else if (this.getSelectedCpu() != -1) { + this.setName(this.cpus.get(this.getSelectedCpu()).getName()); + this.setCpuAvailableBytes(this.cpus.get(this.getSelectedCpu()).getSize()); + this.setCpuCoProcessors(this.cpus.get(this.getSelectedCpu()).getProcessors()); + } + } + + public void startJob() { + GuiBridge originalGui = null; + + final IActionHost ah = this.getActionHost(); + if (ah instanceof WirelessTerminalGuiObject) { + originalGui = GuiBridge.GUI_WIRELESS_TERM; + } + + if (ah instanceof PartTerminal) { + originalGui = GuiBridge.GUI_ME; + } + + if (ah instanceof PartCraftingTerminal) { + originalGui = GuiBridge.GUI_CRAFTING_TERMINAL; + } + + if (ah instanceof PartPatternTerminal) { + originalGui = GuiBridge.GUI_PATTERN_TERMINAL; + } + + if (this.result != null && !this.isSimulation()) { + final ICraftingGrid cc = this.getGrid().getCache(ICraftingGrid.class); + final ICraftingLink g = cc.submitJob( + this.result, + null, + this.getSelectedCpu() == -1 + ? null + : this.cpus.get(this.getSelectedCpu()).getCpu(), + true, + this.getActionSrc() + ); + this.setAutoStart(false); + if (g != null && originalGui != null && this.getOpenContext() != null) { + NetworkHandler.instance.sendTo( + new PacketSwitchGuis(originalGui), + (EntityPlayerMP) this.getInventoryPlayer().player + ); + + final TileEntity te = this.getOpenContext().getTile(); + Platform.openGUI( + this.getInventoryPlayer().player, + te, + this.getOpenContext().getSide(), + originalGui + ); + } + } + } + + private BaseActionSource getActionSrc() { + return new PlayerSource( + this.getPlayerInv().player, (IActionHost) this.getTarget() + ); + } + + @Override + public void removeCraftingFromCrafters(final ICrafting c) { + super.removeCraftingFromCrafters(c); + if (this.getJob() != null) { + this.getJob().cancel(true); + this.setJob(null); + } + } + + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + super.onContainerClosed(par1EntityPlayer); + if (this.getJob() != null) { + this.getJob().cancel(true); + this.setJob(null); + } + } + + public World getWorld() { + return this.getPlayerInv().player.worldObj; + } + + public boolean isAutoStart() { + return this.autoStart; + } + + public void setAutoStart(final boolean autoStart) { + this.autoStart = autoStart; + } + + public long getUsedBytes() { + return this.bytesUsed; + } + + private void setUsedBytes(final long bytesUsed) { + this.bytesUsed = bytesUsed; + } + + public long getCpuAvailableBytes() { + return this.cpuBytesAvail; + } + + private void setCpuAvailableBytes(final long cpuBytesAvail) { + this.cpuBytesAvail = cpuBytesAvail; + } + + public int getCpuCoProcessors() { + return this.cpuCoProcessors; + } + + private void setCpuCoProcessors(final int cpuCoProcessors) { + this.cpuCoProcessors = cpuCoProcessors; + } + + public int getSelectedCpu() { + return this.selectedCpu; + } + + private void setSelectedCpu(final int selectedCpu) { + this.selectedCpu = selectedCpu; + } + + public String getName() { + return this.myName; + } + + private void setName(@Nonnull final String myName) { + this.myName = myName; + } + + public boolean hasNoCPU() { + return this.noCPU; + } + + private void setNoCPU(final boolean noCPU) { + this.noCPU = noCPU; + } + + public boolean isSimulation() { + return this.simulation; + } + + private void setSimulation(final boolean simulation) { + this.simulation = simulation; + } + + private Future getJob() { + return this.job; + } + + public void setJob(final Future job) { + this.job = job; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java b/src/main/java/appeng/container/implementations/ContainerCraftingCPU.java index e9de1f98..4183a5ac 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 appeng.api.AEApi; import appeng.api.networking.IGrid; @@ -47,251 +48,213 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; +public class ContainerCraftingCPU extends AEBaseContainer + implements IMEMonitorHandlerReceiver, ICustomNameObject { + private final IItemList list + = AEApi.instance().storage().createItemList(); + private IGrid network; + private CraftingCPUCluster monitor = null; + private String cpuName = null; + @GuiSync(0) + public long eta = -1; -public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorHandlerReceiver, ICustomNameObject -{ + public ContainerCraftingCPU(final InventoryPlayer ip, final Object te) { + super(ip, te); + final IGridHost host = (IGridHost) (te instanceof IGridHost ? te : null); - private final IItemList list = AEApi.instance().storage().createItemList(); - private IGrid network; - private CraftingCPUCluster monitor = null; - private String cpuName = null; + if (host != null) { + this.findNode(host, ForgeDirection.UNKNOWN); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.findNode(host, d); + } + } - @GuiSync( 0 ) - public long eta = -1; + if (te instanceof TileCraftingTile) { + this.setCPU((ICraftingCPU) ((IAEMultiBlock) te).getCluster()); + } - public ContainerCraftingCPU( final InventoryPlayer ip, final Object te ) - { - super( ip, te ); - final IGridHost host = (IGridHost) ( te instanceof IGridHost ? te : null ); + if (this.getNetwork() == null && Platform.isServer()) { + this.setValidContainer(false); + } + } - if( host != null ) - { - this.findNode( host, ForgeDirection.UNKNOWN ); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.findNode( host, d ); - } - } + private void findNode(final IGridHost host, final ForgeDirection d) { + if (this.getNetwork() == null) { + final IGridNode node = host.getGridNode(d); + if (node != null) { + this.setNetwork(node.getGrid()); + } + } + } - if( te instanceof TileCraftingTile ) - { - this.setCPU( (ICraftingCPU) ( (IAEMultiBlock) te ).getCluster() ); - } + protected void setCPU(final ICraftingCPU c) { + if (c == this.getMonitor()) { + return; + } - if( this.getNetwork() == null && Platform.isServer() ) - { - this.setValidContainer( false ); - } - } + if (this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } - private void findNode( final IGridHost host, final ForgeDirection d ) - { - if( this.getNetwork() == null ) - { - final IGridNode node = host.getGridNode( d ); - if( node != null ) - { - this.setNetwork( node.getGrid() ); - } - } - } + for (final Object g : this.crafters) { + if (g instanceof EntityPlayer) { + try { + NetworkHandler.instance.sendTo( + new PacketValueConfig("CraftingStatus", "Clear"), + (EntityPlayerMP) g + ); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - protected void setCPU( final ICraftingCPU c ) - { - if( c == this.getMonitor() ) - { - return; - } + if (c instanceof CraftingCPUCluster) { + this.cpuName = c.getName(); + this.setMonitor((CraftingCPUCluster) c); + this.list.resetStatus(); + this.getMonitor().getListOfItem(this.list, CraftingItemList.ALL); + this.getMonitor().addListener(this, null); + this.setEstimatedTime(0); + } else { + this.setMonitor(null); + this.cpuName = ""; + this.setEstimatedTime(-1); + } + } - if( this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } + public void cancelCrafting() { + if (this.getMonitor() != null) { + this.getMonitor().cancel(); + } + this.setEstimatedTime(-1); + } - for( final Object g : this.crafters ) - { - if( g instanceof EntityPlayer ) - { - try - { - NetworkHandler.instance.sendTo( new PacketValueConfig( "CraftingStatus", "Clear" ), (EntityPlayerMP) g ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + @Override + public void removeCraftingFromCrafters(final ICrafting c) { + super.removeCraftingFromCrafters(c); - if( c instanceof CraftingCPUCluster ) - { - this.cpuName = c.getName(); - this.setMonitor( (CraftingCPUCluster) c ); - this.list.resetStatus(); - this.getMonitor().getListOfItem( this.list, CraftingItemList.ALL ); - this.getMonitor().addListener( this, null ); - this.setEstimatedTime( 0 ); - } - else - { - this.setMonitor( null ); - this.cpuName = ""; - this.setEstimatedTime( -1 ); - } - } + if (this.crafters.isEmpty() && this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } + } - public void cancelCrafting() - { - if( this.getMonitor() != null ) - { - this.getMonitor().cancel(); - } - this.setEstimatedTime( -1 ); - } + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.getMonitor() != null) { + this.getMonitor().removeListener(this); + } + } - @Override - public void removeCraftingFromCrafters( final ICrafting c ) - { - super.removeCraftingFromCrafters( c ); + @Override + public void detectAndSendChanges() { + if (Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty()) { + try { + if (this.getEstimatedTime() >= 0) { + final long elapsedTime = this.getMonitor().getElapsedTime(); + final double remainingItems + = this.getMonitor().getRemainingItemCount(); + final double startItems = this.getMonitor().getStartItemCount(); + final long eta = (long + ) (elapsedTime / Math.max(1d, (startItems - remainingItems)) + * remainingItems); + this.setEstimatedTime(eta); + } - if( this.crafters.isEmpty() && this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } - } + final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate((byte) 0); + final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate((byte) 1); + final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate((byte) 2); - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - if( this.getMonitor() != null ) - { - this.getMonitor().removeListener( this ); - } - } + for (final IAEItemStack out : this.list) { + a.appendItem( + this.getMonitor().getItemStack(out, CraftingItemList.STORAGE) + ); + b.appendItem( + this.getMonitor().getItemStack(out, CraftingItemList.ACTIVE) + ); + c.appendItem( + this.getMonitor().getItemStack(out, CraftingItemList.PENDING) + ); + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty() ) - { - try - { - if( this.getEstimatedTime() >= 0 ) - { - final long elapsedTime = this.getMonitor().getElapsedTime(); - final double remainingItems = this.getMonitor().getRemainingItemCount(); - final double startItems = this.getMonitor().getStartItemCount(); - final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems ); - this.setEstimatedTime( eta ); - } + this.list.resetStatus(); - final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); - final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); - final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 ); + for (final Object g : this.crafters) { + if (g instanceof EntityPlayer) { + if (!a.isEmpty()) { + NetworkHandler.instance.sendTo(a, (EntityPlayerMP) g); + } - for( final IAEItemStack out : this.list ) - { - a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) ); - b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) ); - c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) ); - } + if (!b.isEmpty()) { + NetworkHandler.instance.sendTo(b, (EntityPlayerMP) g); + } - this.list.resetStatus(); + if (!c.isEmpty()) { + NetworkHandler.instance.sendTo(c, (EntityPlayerMP) g); + } + } + } + } catch (final IOException e) { + // :P + } + } + super.detectAndSendChanges(); + } - for( final Object g : this.crafters ) - { - if( g instanceof EntityPlayer ) - { - if( !a.isEmpty() ) - { - NetworkHandler.instance.sendTo( a, (EntityPlayerMP) g ); - } + @Override + public boolean isValid(final Object verificationToken) { + return true; + } - if( !b.isEmpty() ) - { - NetworkHandler.instance.sendTo( b, (EntityPlayerMP) g ); - } + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource actionSource + ) { + for (IAEItemStack is : change) { + is = is.copy(); + is.setStackSize(1); + this.list.add(is); + } + } - if( !c.isEmpty() ) - { - NetworkHandler.instance.sendTo( c, (EntityPlayerMP) g ); - } - } - } - } - catch( final IOException e ) - { - // :P - } - } - super.detectAndSendChanges(); - } + @Override + public void onListUpdate() {} - @Override - public boolean isValid( final Object verificationToken ) - { - return true; - } + @Override + public String getCustomName() { + return this.cpuName; + } - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource actionSource ) - { - for( IAEItemStack is : change ) - { - is = is.copy(); - is.setStackSize( 1 ); - this.list.add( is ); - } - } + @Override + public boolean hasCustomName() { + return this.cpuName != null && this.cpuName.length() > 0; + } - @Override - public void onListUpdate() - { + public long getEstimatedTime() { + return this.eta; + } - } + private void setEstimatedTime(final long eta) { + this.eta = eta; + } - @Override - public String getCustomName() - { - return this.cpuName; - } + CraftingCPUCluster getMonitor() { + return this.monitor; + } - @Override - public boolean hasCustomName() - { - return this.cpuName != null && this.cpuName.length() > 0; - } + private void setMonitor(final CraftingCPUCluster monitor) { + this.monitor = monitor; + } - public long getEstimatedTime() - { - return this.eta; - } + IGrid getNetwork() { + return this.network; + } - private void setEstimatedTime( final long eta ) - { - this.eta = eta; - } - - CraftingCPUCluster getMonitor() - { - return this.monitor; - } - - private void setMonitor( final CraftingCPUCluster monitor ) - { - this.monitor = monitor; - } - - IGrid getNetwork() - { - return this.network; - } - - private void setNetwork( final IGrid network ) - { - this.network = network; - } + private void setNetwork(final IGrid network) { + this.network = network; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java index 12d266e5..f7b7de9f 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingStatus.java @@ -18,6 +18,9 @@ package appeng.container.implementations; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import appeng.api.networking.crafting.ICraftingCPU; import appeng.api.networking.crafting.ICraftingGrid; @@ -27,152 +30,115 @@ import appeng.util.Platform; import com.google.common.collect.ImmutableSet; import net.minecraft.entity.player.InventoryPlayer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +public class ContainerCraftingStatus extends ContainerCraftingCPU { + private final List cpus = new ArrayList(); + @GuiSync(5) + public int selectedCpu = -1; + @GuiSync(6) + public boolean noCPU = true; + @GuiSync(7) + public String myName = ""; + public ContainerCraftingStatus(final InventoryPlayer ip, final ITerminalHost te) { + super(ip, te); + } -public class ContainerCraftingStatus extends ContainerCraftingCPU -{ + @Override + public void detectAndSendChanges() { + if (Platform.isServer() && this.getNetwork() != null) { + final ICraftingGrid cc = this.getNetwork().getCache(ICraftingGrid.class); + final ImmutableSet cpuSet = cc.getCpus(); - private final List cpus = new ArrayList(); - @GuiSync( 5 ) - public int selectedCpu = -1; - @GuiSync( 6 ) - public boolean noCPU = true; - @GuiSync( 7 ) - public String myName = ""; + int matches = 0; + boolean changed = false; + for (final ICraftingCPU c : cpuSet) { + boolean found = false; + for (final CraftingCPURecord ccr : this.cpus) { + if (ccr.getCpu() == c) { + found = true; + } + } - public ContainerCraftingStatus( final InventoryPlayer ip, final ITerminalHost te ) - { - super( ip, te ); - } + final boolean matched = this.cpuMatches(c); - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() && this.getNetwork() != null ) - { - final ICraftingGrid cc = this.getNetwork().getCache( ICraftingGrid.class ); - final ImmutableSet cpuSet = cc.getCpus(); + if (matched) { + matches++; + } - int matches = 0; - boolean changed = false; - for( final ICraftingCPU c : cpuSet ) - { - boolean found = false; - for( final CraftingCPURecord ccr : this.cpus ) - { - if( ccr.getCpu() == c ) - { - found = true; - } - } + if (found == !matched) { + changed = true; + } + } - final boolean matched = this.cpuMatches( c ); + if (changed || this.cpus.size() != matches) { + this.cpus.clear(); + for (final ICraftingCPU c : cpuSet) { + if (this.cpuMatches(c)) { + this.cpus.add(new CraftingCPURecord( + c.getAvailableStorage(), c.getCoProcessors(), c + )); + } + } - if( matched ) - { - matches++; - } + this.sendCPUs(); + } - if( found == !matched ) - { - changed = true; - } - } + this.noCPU = this.cpus.isEmpty(); + } - if( changed || this.cpus.size() != matches ) - { - this.cpus.clear(); - for( final ICraftingCPU c : cpuSet ) - { - if( this.cpuMatches( c ) ) - { - this.cpus.add( new CraftingCPURecord( c.getAvailableStorage(), c.getCoProcessors(), c ) ); - } - } + super.detectAndSendChanges(); + } - this.sendCPUs(); - } + private boolean cpuMatches(final ICraftingCPU c) { + return c.isBusy(); + } - this.noCPU = this.cpus.isEmpty(); - } + private void sendCPUs() { + Collections.sort(this.cpus); - super.detectAndSendChanges(); - } + if (this.selectedCpu >= this.cpus.size()) { + this.selectedCpu = -1; + this.myName = ""; + } else if (this.selectedCpu != -1) { + this.myName = this.cpus.get(this.selectedCpu).getName(); + } - private boolean cpuMatches( final ICraftingCPU c ) - { - return c.isBusy(); - } + if (this.selectedCpu == -1 && this.cpus.size() > 0) { + this.selectedCpu = 0; + } - private void sendCPUs() - { - Collections.sort( this.cpus ); + if (this.selectedCpu != -1) { + if (this.cpus.get(this.selectedCpu).getCpu() != this.getMonitor()) { + this.setCPU(this.cpus.get(this.selectedCpu).getCpu()); + } + } else { + this.setCPU(null); + } + } - if( this.selectedCpu >= this.cpus.size() ) - { - this.selectedCpu = -1; - this.myName = ""; - } - else if( this.selectedCpu != -1 ) - { - this.myName = this.cpus.get( this.selectedCpu ).getName(); - } + public void cycleCpu(final boolean next) { + if (next) { + this.selectedCpu++; + } else { + this.selectedCpu--; + } - if( this.selectedCpu == -1 && this.cpus.size() > 0 ) - { - this.selectedCpu = 0; - } + if (this.selectedCpu < -1) { + this.selectedCpu = this.cpus.size() - 1; + } else if (this.selectedCpu >= this.cpus.size()) { + this.selectedCpu = -1; + } - if( this.selectedCpu != -1 ) - { - if( this.cpus.get( this.selectedCpu ).getCpu() != this.getMonitor() ) - { - this.setCPU( this.cpus.get( this.selectedCpu ).getCpu() ); - } - } - else - { - this.setCPU( null ); - } - } + if (this.selectedCpu == -1 && this.cpus.size() > 0) { + this.selectedCpu = 0; + } - public void cycleCpu( final boolean next ) - { - if( next ) - { - this.selectedCpu++; - } - else - { - this.selectedCpu--; - } - - if( this.selectedCpu < -1 ) - { - this.selectedCpu = this.cpus.size() - 1; - } - else if( this.selectedCpu >= this.cpus.size() ) - { - this.selectedCpu = -1; - } - - if( this.selectedCpu == -1 && this.cpus.size() > 0 ) - { - this.selectedCpu = 0; - } - - if( this.selectedCpu == -1 ) - { - this.myName = ""; - this.setCPU( null ); - } - else - { - this.myName = this.cpus.get( this.selectedCpu ).getName(); - this.setCPU( this.cpus.get( this.selectedCpu ).getCpu() ); - } - } + if (this.selectedCpu == -1) { + this.myName = ""; + this.setCPU(null); + } else { + this.myName = this.cpus.get(this.selectedCpu).getName(); + this.setCPU(this.cpus.get(this.selectedCpu).getCpu()); + } + } } diff --git a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java index 3584f7d1..ed098016 100644 --- a/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerCraftingTerm.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.storage.ITerminalHost; import appeng.container.ContainerNull; import appeng.container.slot.SlotCraftingMatrix; @@ -34,79 +33,90 @@ import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; +public class ContainerCraftingTerm extends ContainerMEMonitorable + implements IAEAppEngInventory, IContainerCraftingPacket { + private final ICraftingTerminal ct; + private final AppEngInternalInventory output = new AppEngInternalInventory(this, 1); + private final SlotCraftingMatrix[] craftingSlots = new SlotCraftingMatrix[9]; + private final SlotCraftingTerm outputSlot; -public class ContainerCraftingTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IContainerCraftingPacket -{ + public ContainerCraftingTerm( + final InventoryPlayer ip, final ITerminalHost monitorable + ) { + super(ip, monitorable, false); + this.ct = (ICraftingTerminal) monitorable; - private final ICraftingTerminal ct; - private final AppEngInternalInventory output = new AppEngInternalInventory( this, 1 ); - private final SlotCraftingMatrix[] craftingSlots = new SlotCraftingMatrix[9]; - private final SlotCraftingTerm outputSlot; + final IInventory crafting = this.ct.getInventoryByName("crafting"); - public ContainerCraftingTerm( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); - this.ct = (ICraftingTerminal) monitorable; + 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 + ) + ); + } + } - final IInventory crafting = this.ct.getInventoryByName( "crafting" ); + this.addSlotToContainer( + this.outputSlot = new SlotCraftingTerm( + this.getPlayerInv().player, + this.getActionSource(), + this.getPowerSource(), + monitorable, + crafting, + crafting, + this.output, + 131, + -72 + 18, + this + ) + ); - 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.bindPlayerInventory(ip, 0, 0); - this.addSlotToContainer( this.outputSlot = new SlotCraftingTerm( this.getPlayerInv().player, this.getActionSource(), this.getPowerSource(), monitorable, crafting, crafting, this.output, 131, -72 + 18, this ) ); + this.onCraftMatrixChanged(crafting); + } - this.bindPlayerInventory( ip, 0, 0 ); + /** + * Callback for when the crafting matrix is changed. + */ + @Override + public void onCraftMatrixChanged(final IInventory par1IInventory) { + final ContainerNull cn = new ContainerNull(); + final InventoryCrafting ic = new InventoryCrafting(cn, 3, 3); - this.onCraftMatrixChanged( crafting ); - } + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents(x, this.craftingSlots[x].getStack()); + } - /** - * Callback for when the crafting matrix is changed. - */ - @Override - public void onCraftMatrixChanged( final IInventory par1IInventory ) - { - final ContainerNull cn = new ContainerNull(); - final InventoryCrafting ic = new InventoryCrafting( cn, 3, 3 ); + this.outputSlot.putStack(CraftingManager.getInstance().findMatchingRecipe( + ic, this.getPlayerInv().player.worldObj + )); + } - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, this.craftingSlots[x].getStack() ); - } + @Override + public void saveChanges() {} - this.outputSlot.putStack( CraftingManager.getInstance().findMatchingRecipe( ic, this.getPlayerInv().player.worldObj ) ); - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) {} - @Override - public void saveChanges() - { + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("player")) { + return this.getInventoryPlayer(); + } + return this.ct.getInventoryByName(name); + } - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { - return this.getInventoryPlayer(); - } - return this.ct.getInventoryByName( name ); - } - - @Override - public boolean useRealItems() - { - return true; - } + @Override + public boolean useRealItems() { + return true; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerDrive.java b/src/main/java/appeng/container/implementations/ContainerDrive.java index 9e74837e..ad70e14f 100644 --- a/src/main/java/appeng/container/implementations/ContainerDrive.java +++ b/src/main/java/appeng/container/implementations/ContainerDrive.java @@ -18,28 +18,28 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.storage.TileDrive; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerDrive extends AEBaseContainer { + public ContainerDrive(final InventoryPlayer ip, final TileDrive drive) { + super(ip, drive, null); -public class ContainerDrive extends AEBaseContainer -{ + 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.getInventoryPlayer() + )); + } + } - public ContainerDrive( final InventoryPlayer ip, final TileDrive drive ) - { - super( ip, drive, null ); - - 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.getInventoryPlayer() ) ); - } - } - - this.bindPlayerInventory( ip, 0, 199 - /* height of player inventory */82 ); - } + 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 8a2dd14b..e11c44b8 100644 --- a/src/main/java/appeng/container/implementations/ContainerFormationPlane.java +++ b/src/main/java/appeng/container/implementations/ContainerFormationPlane.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.OptionalSlotFakeTypeOnly; @@ -29,95 +28,130 @@ import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; +public class ContainerFormationPlane extends ContainerUpgradeable { + @GuiSync(6) + public YesNo placeMode; -public class ContainerFormationPlane extends ContainerUpgradeable -{ + public ContainerFormationPlane( + final InventoryPlayer ip, final PartFormationPlane te + ) { + super(ip, te); + } - @GuiSync( 6 ) - public YesNo placeMode; + @Override + protected int getHeight() { + return 251; + } - public ContainerFormationPlane( final InventoryPlayer ip, final PartFormationPlane te ) - { - super( ip, te ); - } + @Override + protected void setupConfig() { + final int xo = 8; + final int yo = 23 + 6; - @Override - protected int getHeight() - { - return 251; - } + final IInventory config = this.getUpgradeable().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 + )); + } + } + } - @Override - protected void setupConfig() - { - final int xo = 8; - final int yo = 23 + 6; + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 4, + 187, + 8 + 18 * 4, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } - final IInventory config = this.getUpgradeable().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 ) ); - } - } - } + @Override + protected boolean supportCapacity() { + return true; + } - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ).setNotDraggable() ); - } + @Override + public int availableUpgrades() { + return 5; + } - @Override - protected boolean supportCapacity() - { - return true; - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - public int availableUpgrades() - { - return 5; - } + if (Platform.isServer()) { + this.setFuzzyMode( + (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.FUZZY_MODE + ) + ); + this.setPlaceMode((YesNo) this.getUpgradeable().getConfigManager().getSetting( + Settings.PLACE_BLOCK + )); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + this.standardDetectAndSendChanges(); + } - if( Platform.isServer() ) - { - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setPlaceMode( (YesNo) this.getUpgradeable().getConfigManager().getSetting( Settings.PLACE_BLOCK ) ); - } + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades + = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - this.standardDetectAndSendChanges(); - } + return upgrades > idx; + } - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + public YesNo getPlaceMode() { + return this.placeMode; + } - return upgrades > idx; - } - - public YesNo getPlaceMode() - { - return this.placeMode; - } - - private void setPlaceMode( final YesNo placeMode ) - { - this.placeMode = placeMode; - } + private void setPlaceMode(final YesNo placeMode) { + this.placeMode = placeMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerGrinder.java b/src/main/java/appeng/container/implementations/ContainerGrinder.java index e6963430..8c7cfdae 100644 --- a/src/main/java/appeng/container/implementations/ContainerGrinder.java +++ b/src/main/java/appeng/container/implementations/ContainerGrinder.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotInaccessible; import appeng.container.slot.SlotOutput; @@ -26,24 +25,41 @@ import appeng.container.slot.SlotRestrictedInput; import appeng.tile.grindstone.TileGrinder; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerGrinder extends AEBaseContainer { + public ContainerGrinder(final InventoryPlayer ip, final TileGrinder grinder) { + super(ip, grinder, null); -public class ContainerGrinder extends AEBaseContainer -{ + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ORE, + grinder, + 0, + 12, + 17, + this.getInventoryPlayer() + )); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ORE, + grinder, + 1, + 12 + 18, + 17, + this.getInventoryPlayer() + )); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ORE, + grinder, + 2, + 12 + 36, + 17, + this.getInventoryPlayer() + )); - public ContainerGrinder( final InventoryPlayer ip, final TileGrinder grinder ) - { - super( ip, grinder, null ); + this.addSlotToContainer(new SlotInaccessible(grinder, 6, 80, 40)); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, grinder, 0, 12, 17, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, grinder, 1, 12 + 18, 17, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ORE, grinder, 2, 12 + 36, 17, this.getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotOutput(grinder, 3, 112, 63, 2 * 16 + 15)); + this.addSlotToContainer(new SlotOutput(grinder, 4, 112 + 18, 63, 2 * 16 + 15)); + this.addSlotToContainer(new SlotOutput(grinder, 5, 112 + 36, 63, 2 * 16 + 15)); - this.addSlotToContainer( new SlotInaccessible( grinder, 6, 80, 40 ) ); - - this.addSlotToContainer( new SlotOutput( grinder, 3, 112, 63, 2 * 16 + 15 ) ); - this.addSlotToContainer( new SlotOutput( grinder, 4, 112 + 18, 63, 2 * 16 + 15 ) ); - this.addSlotToContainer( new SlotOutput( grinder, 5, 112 + 36, 63, 2 * 16 + 15 ) ); - - this.bindPlayerInventory( ip, 0, 176 - /* height of player inventory */82 ); - } + 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 3ad1e627..39b5294f 100644 --- a/src/main/java/appeng/container/implementations/ContainerIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerIOPort.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotOutput; @@ -28,102 +27,133 @@ import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; +public class ContainerIOPort extends ContainerUpgradeable { + @GuiSync(2) + public FullnessMode fMode = FullnessMode.EMPTY; + @GuiSync(3) + public OperationMode opMode = OperationMode.EMPTY; -public class ContainerIOPort extends ContainerUpgradeable -{ + public ContainerIOPort(final InventoryPlayer ip, final TileIOPort te) { + super(ip, te); + } - @GuiSync( 2 ) - public FullnessMode fMode = FullnessMode.EMPTY; - @GuiSync( 3 ) - public OperationMode opMode = OperationMode.EMPTY; + @Override + protected int getHeight() { + return 166; + } - public ContainerIOPort( final InventoryPlayer ip, final TileIOPort te ) - { - super( ip, te ); - } + @Override + protected void setupConfig() { + int offX = 19; + int offY = 17; - @Override - protected int getHeight() - { - return 166; - } + final IInventory cells = this.getUpgradeable().getInventoryByName("cells"); - @Override - protected void setupConfig() - { - int offX = 19; - int offY = 17; + 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.getInventoryPlayer() + )); + } + } - final IInventory cells = this.getUpgradeable().getInventoryByName( "cells" ); + offX = 122; + offY = 17; + 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 + )); + } + } - 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.getInventoryPlayer() ) ); - } - } + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } - offX = 122; - offY = 17; - 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 ) ); - } - } + @Override + protected boolean supportCapacity() { + return false; + } - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - } + @Override + public int availableUpgrades() { + return 3; + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - public int availableUpgrades() - { - return 3; - } + if (Platform.isServer()) { + this.setOperationMode( + (OperationMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.OPERATION_MODE + ) + ); + this.setFullMode( + (FullnessMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.FULLNESS_MODE + ) + ); + this.setRedStoneMode( + (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.REDSTONE_CONTROLLED + ) + ); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + this.standardDetectAndSendChanges(); + } - if( Platform.isServer() ) - { - this.setOperationMode( (OperationMode) this.getUpgradeable().getConfigManager().getSetting( Settings.OPERATION_MODE ) ); - this.setFullMode( (FullnessMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FULLNESS_MODE ) ); - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ) ); - } + public FullnessMode getFullMode() { + return this.fMode; + } - this.standardDetectAndSendChanges(); - } + private void setFullMode(final FullnessMode fMode) { + this.fMode = fMode; + } - public FullnessMode getFullMode() - { - return this.fMode; - } + public OperationMode getOperationMode() { + return this.opMode; + } - private void setFullMode( final FullnessMode fMode ) - { - this.fMode = fMode; - } - - public OperationMode getOperationMode() - { - return this.opMode; - } - - private void setOperationMode( final OperationMode opMode ) - { - this.opMode = opMode; - } + private void setOperationMode(final OperationMode opMode) { + this.opMode = opMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInscriber.java b/src/main/java/appeng/container/implementations/ContainerInscriber.java index 613fcb5d..4f81ff45 100644 --- a/src/main/java/appeng/container/implementations/ContainerInscriber.java +++ b/src/main/java/appeng/container/implementations/ContainerInscriber.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IItemDefinition; import appeng.api.features.IInscriberRecipe; @@ -32,180 +31,201 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class ContainerInscriber extends ContainerUpgradeable implements IProgressProvider -{ +public class ContainerInscriber + extends ContainerUpgradeable implements IProgressProvider { + private final TileInscriber ti; - private final TileInscriber ti; + private final Slot top; + private final Slot middle; + private final Slot bottom; - private final Slot top; - private final Slot middle; - private final Slot bottom; + @GuiSync(2) + public int maxProcessingTime = -1; - @GuiSync( 2 ) - public int maxProcessingTime = -1; + @GuiSync(3) + public int processingTime = -1; - @GuiSync( 3 ) - public int processingTime = -1; + public ContainerInscriber(final InventoryPlayer ip, final TileInscriber te) { + super(ip, te); + this.ti = te; - public ContainerInscriber( final InventoryPlayer ip, final TileInscriber te ) - { - super( ip, te ); - this.ti = te; + this.addSlotToContainer( + this.top = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, + this.ti, + 0, + 45, + 16, + this.getInventoryPlayer() + ) + ); + this.addSlotToContainer( + this.bottom = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, + this.ti, + 1, + 45, + 62, + this.getInventoryPlayer() + ) + ); + this.addSlotToContainer( + this.middle = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.INSCRIBER_INPUT, + this.ti, + 2, + 63, + 39, + this.getInventoryPlayer() + ) + ); - this.addSlotToContainer( this.top = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, this.ti, 0, 45, 16, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.bottom = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_PLATE, this.ti, 1, 45, 62, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.middle = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.INSCRIBER_INPUT, this.ti, 2, 63, 39, this.getInventoryPlayer() ) ); + this.addSlotToContainer(new SlotOutput(this.ti, 3, 113, 40, -1)); + } - this.addSlotToContainer( new SlotOutput( this.ti, 3, 113, 40, -1 ) ); - } + @Override + protected int getHeight() { + return 176; + } - @Override - protected int getHeight() - { - return 176; - } + @Override + /** + * Overridden super.setupConfig to prevent setting up the fake slots + */ + protected void setupConfig() { + this.setupUpgrades(); + } - @Override - /** - * Overridden super.setupConfig to prevent setting up the fake slots - */ protected void setupConfig() - { - this.setupUpgrades(); - } + @Override + protected boolean supportCapacity() { + return false; + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + public int availableUpgrades() { + return 3; + } - @Override - public int availableUpgrades() - { - return 3; - } + @Override + public void detectAndSendChanges() { + this.standardDetectAndSendChanges(); - @Override - public void detectAndSendChanges() - { - this.standardDetectAndSendChanges(); + if (Platform.isServer()) { + this.maxProcessingTime = this.ti.getMaxProcessingTime(); + this.processingTime = this.ti.getProcessingTime(); + } + } - if( Platform.isServer() ) - { - this.maxProcessingTime = this.ti.getMaxProcessingTime(); - this.processingTime = this.ti.getProcessingTime(); - } - } + @Override + public boolean isValidForSlot(final Slot s, final ItemStack is) { + final ItemStack top = this.ti.getStackInSlot(0); + final ItemStack bot = this.ti.getStackInSlot(1); - @Override - public boolean isValidForSlot( final Slot s, final ItemStack is ) - { - final ItemStack top = this.ti.getStackInSlot( 0 ); - final ItemStack bot = this.ti.getStackInSlot( 1 ); + if (s == this.middle) { + for (final ItemStack optional : + AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.isSameItemPrecise(optional, is)) { + return false; + } + } - if( s == this.middle ) - { - for( final ItemStack optional : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.isSameItemPrecise( optional, is ) ) - { - return false; - } - } + boolean matches = false; + boolean found = false; - boolean matches = false; - boolean found = false; + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + final boolean matchA + = (top == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise(top, recipe.getTopOptional().orNull())) + && // and... + (bot == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + bot, recipe.getBottomOptional().orNull() + )); - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - final boolean matchA = ( top == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( top, recipe.getTopOptional().orNull() ) ) && // and... - ( bot == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( bot, recipe.getBottomOptional().orNull() ) ); + final boolean matchB + = (bot == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise(bot, recipe.getTopOptional().orNull())) + && // and... + (top == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + top, recipe.getBottomOptional().orNull() + )); - final boolean matchB = ( bot == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( bot, recipe.getTopOptional().orNull() ) ) && // and... - ( top == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( top, recipe.getBottomOptional().orNull() ) ); + if (matchA || matchB) { + matches = true; + for (final ItemStack option : recipe.getInputs()) { + if (Platform.isSameItemPrecise(is, option)) { + found = true; + } + } + } + } - if( matchA || matchB ) - { - matches = true; - for( final ItemStack option : recipe.getInputs() ) - { - if( Platform.isSameItemPrecise( is, option ) ) - { - found = true; - } - } - } - } + if (matches && !found) { + return false; + } + } - if( matches && !found ) - { - return false; - } - } + if ((s == this.top && bot != null) || (s == this.bottom && top != null)) { + ItemStack otherSlot = null; + if (s == this.top) { + otherSlot = this.bottom.getStack(); + } else { + otherSlot = this.top.getStack(); + } - if( ( s == this.top && bot != null ) || ( s == this.bottom && top != null ) ) - { - 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); + } - // name presses - final IItemDefinition namePress = AEApi.instance().definitions().materials().namePress(); - if( namePress.isSameAs( otherSlot ) ) - { - return namePress.isSameAs( is ); - } + // everything else + boolean isValid = false; + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + if (Platform.isSameItemPrecise( + recipe.getTopOptional().orNull(), otherSlot + )) { + isValid = Platform.isSameItemPrecise( + is, recipe.getBottomOptional().orNull() + ); + } else if (Platform.isSameItemPrecise( + recipe.getBottomOptional().orNull(), otherSlot + )) { + isValid = Platform.isSameItemPrecise( + is, recipe.getTopOptional().orNull() + ); + } - // everything else - boolean isValid = false; - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - if( Platform.isSameItemPrecise( recipe.getTopOptional().orNull(), otherSlot ) ) - { - isValid = Platform.isSameItemPrecise( is, recipe.getBottomOptional().orNull() ); - } - else if( Platform.isSameItemPrecise( recipe.getBottomOptional().orNull(), otherSlot ) ) - { - isValid = Platform.isSameItemPrecise( is, recipe.getTopOptional().orNull() ); - } + if (isValid) { + break; + } + } - if( isValid ) - { - break; - } - } + if (!isValid) { + return false; + } + } - if( !isValid ) - { - return false; - } - } + return true; + } - return true; - } + @Override + public int getCurrentProgress() { + return this.processingTime; + } - @Override - public int getCurrentProgress() - { - return this.processingTime; - } - - @Override - public int getMaxProgress() - { - return this.maxProcessingTime; - } + @Override + public int getMaxProgress() { + return this.maxProcessingTime; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterface.java b/src/main/java/appeng/container/implementations/ContainerInterface.java index 51678629..be05b4f8 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterface.java +++ b/src/main/java/appeng/container/implementations/ContainerInterface.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.SecurityPermissions; import appeng.api.config.Settings; import appeng.api.config.YesNo; @@ -31,89 +30,84 @@ import appeng.helpers.DualityInterface; import appeng.helpers.IInterfaceHost; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerInterface extends ContainerUpgradeable { + private final DualityInterface myDuality; -public class ContainerInterface extends ContainerUpgradeable -{ + @GuiSync(3) + public YesNo bMode = YesNo.NO; - private final DualityInterface myDuality; + @GuiSync(4) + public YesNo iTermMode = YesNo.YES; - @GuiSync( 3 ) - public YesNo bMode = YesNo.NO; + public ContainerInterface(final InventoryPlayer ip, final IInterfaceHost te) { + super(ip, te.getInterfaceDuality().getHost()); - @GuiSync( 4 ) - public YesNo iTermMode = YesNo.YES; + this.myDuality = te.getInterfaceDuality(); - public ContainerInterface( final InventoryPlayer ip, final IInterfaceHost te ) - { - super( ip, te.getInterfaceDuality().getHost() ); + for (int x = 0; x < DualityInterface.NUMBER_OF_PATTERN_SLOTS; x++) { + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, + this.myDuality.getPatterns(), + x, + 8 + 18 * x, + 90 + 7, + this.getInventoryPlayer() + )); + } - this.myDuality = te.getInterfaceDuality(); + for (int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++) { + this.addSlotToContainer( + new SlotFake(this.myDuality.getConfig(), x, 8 + 18 * x, 35) + ); + } - for( int x = 0; x < DualityInterface.NUMBER_OF_PATTERN_SLOTS; x++ ) - { - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality.getPatterns(), x, 8 + 18 * x, 90 + 7, this.getInventoryPlayer() ) ); - } + for (int x = 0; x < DualityInterface.NUMBER_OF_STORAGE_SLOTS; x++) { + this.addSlotToContainer( + new SlotNormal(this.myDuality.getStorage(), x, 8 + 18 * x, 35 + 18) + ); + } + } - for( int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++ ) - { - this.addSlotToContainer( new SlotFake( this.myDuality.getConfig(), x, 8 + 18 * x, 35 ) ); - } + @Override + protected int getHeight() { + return 211; + } - for( int x = 0; x < DualityInterface.NUMBER_OF_STORAGE_SLOTS; x++ ) - { - this.addSlotToContainer( new SlotNormal( this.myDuality.getStorage(), x, 8 + 18 * x, 35 + 18 ) ); - } - } + @Override + protected void setupConfig() { + this.setupUpgrades(); + } - @Override - protected int getHeight() - { - return 211; - } + @Override + public int availableUpgrades() { + return 1; + } - @Override - protected void setupConfig() - { - this.setupUpgrades(); - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); + super.detectAndSendChanges(); + } - @Override - public int availableUpgrades() - { - return 1; - } + @Override + protected void loadSettingsFromHost(final IConfigManager cm) { + this.setBlockingMode((YesNo) cm.getSetting(Settings.BLOCK)); + this.setInterfaceTerminalMode((YesNo) cm.getSetting(Settings.INTERFACE_TERMINAL)); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); - super.detectAndSendChanges(); - } + public YesNo getBlockingMode() { + return this.bMode; + } - @Override - protected void loadSettingsFromHost( final IConfigManager cm ) - { - this.setBlockingMode( (YesNo) cm.getSetting( Settings.BLOCK ) ); - this.setInterfaceTerminalMode( (YesNo) cm.getSetting( Settings.INTERFACE_TERMINAL ) ); - } + private void setBlockingMode(final YesNo bMode) { + this.bMode = bMode; + } - public YesNo getBlockingMode() - { - return this.bMode; - } + public YesNo getInterfaceTerminalMode() { + return this.iTermMode; + } - private void setBlockingMode( final YesNo bMode ) - { - this.bMode = bMode; - } - - public YesNo getInterfaceTerminalMode() - { - return this.iTermMode; - } - - private void setInterfaceTerminalMode( final YesNo iTermMode ) - { - this.iTermMode = iTermMode; - } + private void setInterfaceTerminalMode(final YesNo iTermMode) { + this.iTermMode = iTermMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java index 72152ac5..7a4de627 100644 --- a/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java +++ b/src/main/java/appeng/container/implementations/ContainerInterfaceTerminal.java @@ -18,6 +18,10 @@ package appeng.container.implementations; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; import appeng.api.config.Settings; import appeng.api.config.YesNo; @@ -47,390 +51,363 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; +public final class ContainerInterfaceTerminal extends AEBaseContainer { + /** + * this stuff is all server side.. + */ + private static long autoBase = Long.MIN_VALUE; + private final Map diList + = new HashMap(); + private final Map byId = new HashMap(); + private IGrid grid; + private NBTTagCompound data = new NBTTagCompound(); -public final class ContainerInterfaceTerminal extends AEBaseContainer -{ + public ContainerInterfaceTerminal( + final InventoryPlayer ip, final PartInterfaceTerminal anchor + ) { + super(ip, anchor); - /** - * this stuff is all server side.. - */ + if (Platform.isServer()) { + this.grid = anchor.getActionableNode().getGrid(); + } - private static long autoBase = Long.MIN_VALUE; - private final Map diList = new HashMap(); - private final Map byId = new HashMap(); - private IGrid grid; - private NBTTagCompound data = new NBTTagCompound(); + this.bindPlayerInventory(ip, 0, 222 - /* height of player inventory */ 82); + } - public ContainerInterfaceTerminal( final InventoryPlayer ip, final PartInterfaceTerminal anchor ) - { - super( ip, anchor ); + @Override + public void detectAndSendChanges() { + if (Platform.isClient()) { + return; + } - if( Platform.isServer() ) - { - this.grid = anchor.getActionableNode().getGrid(); - } + super.detectAndSendChanges(); - this.bindPlayerInventory( ip, 0, 222 - /* height of player inventory */82 ); - } + if (this.grid == null) { + return; + } - @Override - public void detectAndSendChanges() - { - if( Platform.isClient() ) - { - return; - } + int total = 0; + boolean missing = false; - super.detectAndSendChanges(); + final IActionHost host = this.getActionHost(); + if (host != null) { + final IGridNode agn = host.getActionableNode(); + if (agn != null && agn.isActive()) { + for (final IGridNode gn : this.grid.getMachines(TileInterface.class)) { + if (gn.isActive()) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if (ih.getInterfaceDuality().getConfigManager().getSetting( + Settings.INTERFACE_TERMINAL + ) + == YesNo.NO) { + continue; + } - if( this.grid == null ) - { - return; - } + final InvTracker t = this.diList.get(ih); - int total = 0; - boolean missing = false; + if (t == null) { + missing = true; + } else { + final DualityInterface dual = ih.getInterfaceDuality(); + if (!t.unlocalizedName.equals(dual.getTermName())) { + missing = true; + } + } - final IActionHost host = this.getActionHost(); - if( host != null ) - { - final IGridNode agn = host.getActionableNode(); - if( agn != null && agn.isActive() ) - { - for( final IGridNode gn : this.grid.getMachines( TileInterface.class ) ) - { - if( gn.isActive() ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - { - continue; - } + total++; + } + } - final InvTracker t = this.diList.get( ih ); + for (final IGridNode gn : this.grid.getMachines(PartInterface.class)) { + if (gn.isActive()) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + if (ih.getInterfaceDuality().getConfigManager().getSetting( + Settings.INTERFACE_TERMINAL + ) + == YesNo.NO) { + continue; + } - if( t == null ) - { - missing = true; - } - else - { - final DualityInterface dual = ih.getInterfaceDuality(); - if( !t.unlocalizedName.equals( dual.getTermName() ) ) - { - missing = true; - } - } + final InvTracker t = this.diList.get(ih); - total++; - } - } + if (t == null) { + missing = true; + } else { + final DualityInterface dual = ih.getInterfaceDuality(); + if (!t.unlocalizedName.equals(dual.getTermName())) { + missing = true; + } + } - for( final IGridNode gn : this.grid.getMachines( PartInterface.class ) ) - { - if( gn.isActive() ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - if( ih.getInterfaceDuality().getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.NO ) - { - continue; - } + total++; + } + } + } + } - final InvTracker t = this.diList.get( ih ); + if (total != this.diList.size() || missing) { + this.regenList(this.data); + } else { + for (final Entry en : this.diList.entrySet()) { + final 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( t == null ) - { - missing = true; - } - else - { - final DualityInterface dual = ih.getInterfaceDuality(); - if( !t.unlocalizedName.equals( dual.getTermName() ) ) - { - missing = true; - } - } + if (!this.data.hasNoTags()) { + try { + NetworkHandler.instance.sendTo( + new PacketCompressedNBT(this.data), + (EntityPlayerMP) this.getPlayerInv().player + ); + } catch (final IOException e) { + // :P + } - total++; - } - } - } - } + this.data = new NBTTagCompound(); + } + } - if( total != this.diList.size() || missing ) - { - this.regenList( this.data ); - } - else - { - for( final Entry en : this.diList.entrySet() ) - { - final 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 ); - } - } - } - } + @Override + public void doAction( + final EntityPlayerMP player, + final InventoryAction action, + final int slot, + final long id + ) { + final InvTracker inv = this.byId.get(id); + if (inv != null) { + final ItemStack is = inv.server.getStackInSlot(slot); + final boolean hasItemInHand = player.inventory.getItemStack() != null; - if( !this.data.hasNoTags() ) - { - try - { - NetworkHandler.instance.sendTo( new PacketCompressedNBT( this.data ), (EntityPlayerMP) this.getPlayerInv().player ); - } - catch( final IOException e ) - { - // :P - } + final InventoryAdaptor playerHand = new AdaptorPlayerHand(player); - this.data = new NBTTagCompound(); - } - } + final WrapperInvSlot slotInv = new PatternInvSlot(inv.server); - @Override - public void doAction( final EntityPlayerMP player, final InventoryAction action, final int slot, final long id ) - { - final InvTracker inv = this.byId.get( id ); - if( inv != null ) - { - final ItemStack is = inv.server.getStackInSlot( slot ); - final boolean hasItemInHand = player.inventory.getItemStack() != null; + final IInventory theSlot = slotInv.getWrapper(slot); + final InventoryAdaptor interfaceSlot = new AdaptorIInventory(theSlot); - final InventoryAdaptor playerHand = new AdaptorPlayerHand( player ); + switch (action) { + case PICKUP_OR_SET_DOWN: - final WrapperInvSlot slotInv = new PatternInvSlot( inv.server ); + if (hasItemInHand) { + ItemStack inSlot = theSlot.getStackInSlot(0); + if (inSlot == null) { + player.inventory.setItemStack( + interfaceSlot.addItems(player.inventory.getItemStack()) + ); + } else { + inSlot = inSlot.copy(); + final ItemStack inHand + = player.inventory.getItemStack().copy(); - final IInventory theSlot = slotInv.getWrapper( slot ); - final InventoryAdaptor interfaceSlot = new AdaptorIInventory( theSlot ); + theSlot.setInventorySlotContents(0, null); + player.inventory.setItemStack(null); - switch( action ) - { - case PICKUP_OR_SET_DOWN: + player.inventory.setItemStack( + interfaceSlot.addItems(inHand.copy()) + ); - if( hasItemInHand ) - { - ItemStack inSlot = theSlot.getStackInSlot( 0 ); - if( inSlot == null ) - { - player.inventory.setItemStack( interfaceSlot.addItems( player.inventory.getItemStack() ) ); - } - else - { - inSlot = inSlot.copy(); - final ItemStack inHand = player.inventory.getItemStack().copy(); + if (player.inventory.getItemStack() == null) { + player.inventory.setItemStack(inSlot); + } else { + player.inventory.setItemStack(inHand); + theSlot.setInventorySlotContents(0, inSlot); + } + } + } else { + final IInventory mySlot = slotInv.getWrapper(slot); + mySlot.setInventorySlotContents( + 0, playerHand.addItems(mySlot.getStackInSlot(0)) + ); + } - theSlot.setInventorySlotContents( 0, null ); - player.inventory.setItemStack( null ); + break; + case SPLIT_OR_PLACE_SINGLE: - player.inventory.setItemStack( interfaceSlot.addItems( inHand.copy() ) ); + 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); + } + } - if( player.inventory.getItemStack() == null ) - { - player.inventory.setItemStack( inSlot ); - } - else - { - player.inventory.setItemStack( inHand ); - theSlot.setInventorySlotContents( 0, inSlot ); - } - } - } - else - { - final IInventory mySlot = slotInv.getWrapper( slot ); - mySlot.setInventorySlotContents( 0, playerHand.addItems( mySlot.getStackInSlot( 0 ) ) ); - } + break; + case SHIFT_CLICK: - break; - case SPLIT_OR_PLACE_SINGLE: + final IInventory mySlot = slotInv.getWrapper(slot); + final InventoryAdaptor playerInv + = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + mySlot.setInventorySlotContents( + 0, playerInv.addItems(mySlot.getStackInSlot(0)) + ); - 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 MOVE_REGION: - break; - case SHIFT_CLICK: + final 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)) + ); + } - final IInventory mySlot = slotInv.getWrapper( slot ); - final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - mySlot.setInventorySlotContents( 0, playerInv.addItems( mySlot.getStackInSlot( 0 ) ) ); + break; + case CREATIVE_DUPLICATE: - break; - case MOVE_REGION: + if (player.capabilities.isCreativeMode && !hasItemInHand) { + player.inventory.setItemStack(is == null ? null : is.copy()); + } - final 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; + default: + return; + } - break; - case CREATIVE_DUPLICATE: + this.updateHeld(player); + } + } - if( player.capabilities.isCreativeMode && !hasItemInHand ) - { - player.inventory.setItemStack( is == null ? null : is.copy() ); - } + private void regenList(final NBTTagCompound data) { + this.byId.clear(); + this.diList.clear(); - break; - default: - return; - } + final IActionHost host = this.getActionHost(); + if (host != null) { + final IGridNode agn = host.getActionableNode(); + if (agn != null && agn.isActive()) { + for (final IGridNode gn : this.grid.getMachines(TileInterface.class)) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + final DualityInterface dual = ih.getInterfaceDuality(); + if (gn.isActive() + && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) + == YesNo.YES) { + this.diList.put( + ih, + new InvTracker(dual, dual.getPatterns(), dual.getTermName()) + ); + } + } - this.updateHeld( player ); - } - } + for (final IGridNode gn : this.grid.getMachines(PartInterface.class)) { + final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); + final DualityInterface dual = ih.getInterfaceDuality(); + if (gn.isActive() + && dual.getConfigManager().getSetting(Settings.INTERFACE_TERMINAL) + == YesNo.YES) { + this.diList.put( + ih, + new InvTracker(dual, dual.getPatterns(), dual.getTermName()) + ); + } + } + } + } - private void regenList( final NBTTagCompound data ) - { - this.byId.clear(); - this.diList.clear(); + data.setBoolean("clear", true); - final IActionHost host = this.getActionHost(); - if( host != null ) - { - final IGridNode agn = host.getActionableNode(); - if( agn != null && agn.isActive() ) - { - for( final IGridNode gn : this.grid.getMachines( TileInterface.class ) ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - final DualityInterface dual = ih.getInterfaceDuality(); - if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) - { - this.diList.put( ih, new InvTracker( dual, dual.getPatterns(), dual.getTermName() ) ); - } - } + for (final Entry en : this.diList.entrySet()) { + final InvTracker inv = en.getValue(); + this.byId.put(inv.which, inv); + this.addItems(data, inv, 0, inv.server.getSizeInventory()); + } + } - for( final IGridNode gn : this.grid.getMachines( PartInterface.class ) ) - { - final IInterfaceHost ih = (IInterfaceHost) gn.getMachine(); - final DualityInterface dual = ih.getInterfaceDuality(); - if( gn.isActive() && dual.getConfigManager().getSetting( Settings.INTERFACE_TERMINAL ) == YesNo.YES ) - { - this.diList.put( ih, new InvTracker( dual, dual.getPatterns(), dual.getTermName() ) ); - } - } - } - } + private boolean isDifferent(final ItemStack a, final ItemStack b) { + if (a == null && b == null) { + return false; + } - data.setBoolean( "clear", true ); + if (a == null || b == null) { + return true; + } - for( final Entry en : this.diList.entrySet() ) - { - final InvTracker inv = en.getValue(); - this.byId.put( inv.which, inv ); - this.addItems( data, inv, 0, inv.server.getSizeInventory() ); - } - } + return !ItemStack.areItemStacksEqual(a, b); + } - private boolean isDifferent( final ItemStack a, final ItemStack b ) - { - if( a == null && b == null ) - { - return false; - } + private void addItems( + final NBTTagCompound data, + final InvTracker inv, + final int offset, + final int length + ) { + final String name = '=' + Long.toString(inv.which, Character.MAX_RADIX); + final NBTTagCompound tag = data.getCompoundTag(name); - if( a == null || b == null ) - { - return true; - } + if (tag.hasNoTags()) { + tag.setLong("sortBy", inv.sortBy); + tag.setString("un", inv.unlocalizedName); + } - return !ItemStack.areItemStacksEqual( a, b ); - } + for (int x = 0; x < length; x++) { + final NBTTagCompound itemNBT = new NBTTagCompound(); - private void addItems( final NBTTagCompound data, final InvTracker inv, final int offset, final int length ) - { - final String name = '=' + Long.toString( inv.which, Character.MAX_RADIX ); - final NBTTagCompound tag = data.getCompoundTag( name ); + final ItemStack is = inv.server.getStackInSlot(x + offset); - if( tag.hasNoTags() ) - { - tag.setLong( "sortBy", inv.sortBy ); - tag.setString( "un", inv.unlocalizedName ); - } + // "update" client side. + inv.client.setInventorySlotContents( + x + offset, is == null ? null : is.copy() + ); - for( int x = 0; x < length; x++ ) - { - final NBTTagCompound itemNBT = new NBTTagCompound(); + if (is != null) { + is.writeToNBT(itemNBT); + } - final ItemStack is = inv.server.getStackInSlot( x + offset ); + tag.setTag(Integer.toString(x + offset), itemNBT); + } - // "update" client side. - inv.client.setInventorySlotContents( x + offset, is == null ? null : is.copy() ); + data.setTag(name, tag); + } - if( is != null ) - { - is.writeToNBT( itemNBT ); - } + private static class InvTracker { + private final long sortBy; + private final long which = autoBase++; + private final String unlocalizedName; + private final IInventory client; + private final IInventory server; - tag.setTag( Integer.toString( x + offset ), itemNBT ); - } + public InvTracker( + final DualityInterface dual, + final IInventory patterns, + final String unlocalizedName + ) { + this.server = patterns; + this.client + = new AppEngInternalInventory(null, this.server.getSizeInventory()); + this.unlocalizedName = unlocalizedName; + this.sortBy = dual.getSortValue(); + } + } - data.setTag( name, tag ); - } + private static class PatternInvSlot extends WrapperInvSlot { + public PatternInvSlot(final IInventory inv) { + super(inv); + } - private static class InvTracker - { - - private final long sortBy; - private final long which = autoBase++; - private final String unlocalizedName; - private final IInventory client; - private final IInventory server; - - public InvTracker( final DualityInterface dual, final IInventory patterns, final String unlocalizedName ) - { - this.server = patterns; - this.client = new AppEngInternalInventory( null, this.server.getSizeInventory() ); - this.unlocalizedName = unlocalizedName; - this.sortBy = dual.getSortValue(); - } - } - - - private static class PatternInvSlot extends WrapperInvSlot - { - - public PatternInvSlot( final IInventory inv ) - { - super( inv ); - } - - @Override - public boolean isItemValid( final ItemStack itemstack ) - { - return itemstack != null && itemstack.getItem() instanceof ItemEncodedPattern; - } - } + @Override + public boolean isItemValid(final 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 c51f4d19..5faeb8c5 100644 --- a/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java +++ b/src/main/java/appeng/container/implementations/ContainerLevelEmitter.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotFakeTypeOnly; @@ -32,129 +31,155 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; +public class ContainerLevelEmitter extends ContainerUpgradeable { + private final PartLevelEmitter lvlEmitter; -public class ContainerLevelEmitter extends ContainerUpgradeable -{ + @SideOnly(Side.CLIENT) + private GuiTextField textField; + @GuiSync(2) + public LevelType lvType; + @GuiSync(3) + public long EmitterValue = -1; + @GuiSync(4) + public YesNo cmType; - private final PartLevelEmitter lvlEmitter; + public ContainerLevelEmitter(final InventoryPlayer ip, final PartLevelEmitter te) { + super(ip, te); + this.lvlEmitter = te; + } - @SideOnly( Side.CLIENT ) - private GuiTextField textField; - @GuiSync( 2 ) - public LevelType lvType; - @GuiSync( 3 ) - public long EmitterValue = -1; - @GuiSync( 4 ) - public YesNo cmType; + @SideOnly(Side.CLIENT) + public void setTextField(final GuiTextField level) { + this.textField = level; + this.textField.setText(String.valueOf(this.EmitterValue)); + } - public ContainerLevelEmitter( final InventoryPlayer ip, final PartLevelEmitter te ) - { - super( ip, te ); - this.lvlEmitter = te; - } + public void setLevel(final long l, final EntityPlayer player) { + this.lvlEmitter.setReportingValue(l); + this.EmitterValue = l; + } - @SideOnly( Side.CLIENT ) - public void setTextField( final GuiTextField level ) - { - this.textField = level; - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } + @Override + protected void setupConfig() { + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + if (this.availableUpgrades() > 0) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } + if (this.availableUpgrades() > 1) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } + if (this.availableUpgrades() > 2) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } + if (this.availableUpgrades() > 3) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } - public void setLevel( final long l, final EntityPlayer player ) - { - this.lvlEmitter.setReportingValue( l ); - this.EmitterValue = l; - } + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + final int y = 40; + final int x = 80 + 44; - @Override - protected void setupConfig() - { - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - if( this.availableUpgrades() > 0 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 1 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 2 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 3 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - } + this.addSlotToContainer(new SlotFakeTypeOnly(inv, 0, x, y)); + } - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - final int y = 40; - final int x = 80 + 44; + @Override + protected boolean supportCapacity() { + return false; + } - this.addSlotToContainer( new SlotFakeTypeOnly( inv, 0, x, y ) ); - } + @Override + public int availableUpgrades() { + return 1; + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - public int availableUpgrades() - { + if (Platform.isServer()) { + this.EmitterValue = this.lvlEmitter.getReportingValue(); + this.setCraftingMode( + (YesNo) this.getUpgradeable().getConfigManager().getSetting( + Settings.CRAFT_VIA_REDSTONE + ) + ); + this.setLevelMode( + (LevelType) this.getUpgradeable().getConfigManager().getSetting( + Settings.LEVEL_TYPE + ) + ); + this.setFuzzyMode( + (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.FUZZY_MODE + ) + ); + this.setRedStoneMode( + (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.REDSTONE_EMITTER + ) + ); + } - return 1; - } + this.standardDetectAndSendChanges(); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void + onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("EmitterValue")) { + if (this.textField != null) { + this.textField.setText(String.valueOf(this.EmitterValue)); + } + } + } - if( Platform.isServer() ) - { - this.EmitterValue = this.lvlEmitter.getReportingValue(); - this.setCraftingMode( (YesNo) this.getUpgradeable().getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) ); - this.setLevelMode( (LevelType) this.getUpgradeable().getConfigManager().getSetting( Settings.LEVEL_TYPE ) ); - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) ); - } + @Override + public YesNo getCraftingMode() { + return this.cmType; + } - this.standardDetectAndSendChanges(); - } + @Override + public void setCraftingMode(final YesNo cmType) { + this.cmType = cmType; + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "EmitterValue" ) ) - { - if( this.textField != null ) - { - this.textField.setText( String.valueOf( this.EmitterValue ) ); - } - } - } + public LevelType getLevelMode() { + return this.lvType; + } - @Override - public YesNo getCraftingMode() - { - return this.cmType; - } - - @Override - public void setCraftingMode( final YesNo cmType ) - { - this.cmType = cmType; - } - - public LevelType getLevelMode() - { - return this.lvType; - } - - private void setLevelMode( final LevelType lvType ) - { - this.lvType = lvType; - } + private void setLevelMode(final LevelType lvType) { + this.lvType = lvType; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMAC.java b/src/main/java/appeng/container/implementations/ContainerMAC.java index c4c0124e..b581c5fe 100644 --- a/src/main/java/appeng/container/implementations/ContainerMAC.java +++ b/src/main/java/appeng/container/implementations/ContainerMAC.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; import appeng.api.config.Settings; @@ -36,121 +35,156 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.world.World; +public class ContainerMAC extends ContainerUpgradeable implements IProgressProvider { + private static final int MAX_CRAFT_PROGRESS = 100; + private final TileMolecularAssembler tma; + @GuiSync(4) + public int craftProgress = 0; -public class ContainerMAC extends ContainerUpgradeable implements IProgressProvider -{ + public ContainerMAC(final InventoryPlayer ip, final TileMolecularAssembler te) { + super(ip, te); + this.tma = te; + } - private static final int MAX_CRAFT_PROGRESS = 100; - private final TileMolecularAssembler tma; - @GuiSync( 4 ) - public int craftProgress = 0; + public boolean isValidItemForSlot(final int slotIndex, final ItemStack i) { + final IInventory mac = this.getUpgradeable().getInventoryByName("mac"); - public ContainerMAC( final InventoryPlayer ip, final TileMolecularAssembler te ) - { - super( ip, te ); - this.tma = te; - } + final ItemStack is = mac.getStackInSlot(10); + if (is == null) { + return false; + } - public boolean isValidItemForSlot( final int slotIndex, final ItemStack i ) - { - final IInventory mac = this.getUpgradeable().getInventoryByName( "mac" ); + if (is.getItem() instanceof ItemEncodedPattern) { + final World w = this.getTileEntity().getWorldObj(); + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(is, w); + if (ph.isCraftable()) { + return ph.isValidItemForSlot(slotIndex, i, w); + } + } - final ItemStack is = mac.getStackInSlot( 10 ); - if( is == null ) - { - return false; - } + return false; + } - if( is.getItem() instanceof ItemEncodedPattern ) - { - final World w = this.getTileEntity().getWorldObj(); - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - if( ph.isCraftable() ) - { - return ph.isValidItemForSlot( slotIndex, i, w ); - } - } + @Override + protected int getHeight() { + return 197; + } - return false; - } + @Override + protected void setupConfig() { + int offX = 29; + int offY = 30; - @Override - protected int getHeight() - { - return 197; - } + final IInventory mac = this.getUpgradeable().getInventoryByName("mac"); - @Override - protected void setupConfig() - { - int offX = 29; - int offY = 30; + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + final SlotMACPattern s = new SlotMACPattern( + this, mac, x + y * 3, offX + x * 18, offY + y * 18 + ); + this.addSlotToContainer(s); + } + } - final IInventory mac = this.getUpgradeable().getInventoryByName( "mac" ); + offX = 126; + offY = 16; - for( int y = 0; y < 3; y++ ) - { - for( int x = 0; x < 3; x++ ) - { - final SlotMACPattern s = new SlotMACPattern( this, mac, x + y * 3, offX + x * 18, offY + y * 18 ); - this.addSlotToContainer( s ); - } - } + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODED_CRAFTING_PATTERN, + mac, + 10, + offX, + offY, + this.getInventoryPlayer() + )); + this.addSlotToContainer(new SlotOutput(mac, 9, offX, offY + 32, -1)); - offX = 126; - offY = 16; + offX = 122; + offY = 17; - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_CRAFTING_PATTERN, mac, 10, offX, offY, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotOutput( mac, 9, offX, offY + 32, -1 ) ); + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 4, + 187, + 8 + 18 * 4, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } - offX = 122; - offY = 17; + @Override + protected boolean supportCapacity() { + return false; + } - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ).setNotDraggable() ); - } + @Override + public int availableUpgrades() { + return 5; + } - @Override - protected boolean supportCapacity() - { - return false; - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - public int availableUpgrades() - { - return 5; - } + if (Platform.isServer()) { + this.setRedStoneMode( + (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.REDSTONE_CONTROLLED + ) + ); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + this.craftProgress = this.tma.getCraftingProgress(); - if( Platform.isServer() ) - { - this.setRedStoneMode( (RedstoneMode) this.getUpgradeable().getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ) ); - } + this.standardDetectAndSendChanges(); + } - this.craftProgress = this.tma.getCraftingProgress(); + @Override + public int getCurrentProgress() { + return this.craftProgress; + } - this.standardDetectAndSendChanges(); - } - - @Override - public int getCurrentProgress() - { - return this.craftProgress; - } - - @Override - public int getMaxProgress() - { - return MAX_CRAFT_PROGRESS; - } + @Override + public int getMaxProgress() { + 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 1ade1340..8c1519bf 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java +++ b/src/main/java/appeng/container/implementations/ContainerMEMonitorable.java @@ -18,6 +18,9 @@ package appeng.container.implementations; +import java.io.IOException; +import java.nio.BufferOverflowException; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.config.*; @@ -59,385 +62,333 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.nio.BufferOverflowException; +public class ContainerMEMonitorable + extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, + IMEMonitorHandlerReceiver { + private final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; + private final IMEMonitor monitor; + private final IItemList items + = AEApi.instance().storage().createItemList(); + private final IConfigManager clientCM; + private final ITerminalHost host; + @GuiSync(99) + public boolean canAccessViewCells = false; + @GuiSync(98) + public boolean hasPower = false; + private IConfigManagerHost gui; + private IConfigManager serverCM; + private IGridNode networkNode; + public ContainerMEMonitorable( + final InventoryPlayer ip, final ITerminalHost monitorable + ) { + this(ip, monitorable, true); + } -public class ContainerMEMonitorable extends AEBaseContainer implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver -{ + protected ContainerMEMonitorable( + final InventoryPlayer ip, + final ITerminalHost monitorable, + final boolean bindInventory + ) { + super( + ip, + monitorable instanceof TileEntity ? (TileEntity) monitorable : null, + monitorable instanceof IPart ? (IPart) monitorable : null + ); - private final SlotRestrictedInput[] cellView = new SlotRestrictedInput[5]; - private final IMEMonitor monitor; - private final IItemList items = AEApi.instance().storage().createItemList(); - private final IConfigManager clientCM; - private final ITerminalHost host; - @GuiSync( 99 ) - public boolean canAccessViewCells = false; - @GuiSync( 98 ) - public boolean hasPower = false; - private IConfigManagerHost gui; - private IConfigManager serverCM; - private IGridNode networkNode; + this.host = monitorable; + this.clientCM = new ConfigManager(this); - public ContainerMEMonitorable( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - this( ip, monitorable, true ); - } + this.clientCM.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.clientCM.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.clientCM.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); - protected ContainerMEMonitorable( final InventoryPlayer ip, final ITerminalHost monitorable, final boolean bindInventory ) - { - super( ip, monitorable instanceof TileEntity ? (TileEntity) monitorable : null, monitorable instanceof IPart ? (IPart) monitorable : null ); + if (Platform.isServer()) { + this.serverCM = monitorable.getConfigManager(); - this.host = monitorable; - this.clientCM = new ConfigManager( this ); + this.monitor = monitorable.getItemInventory(); + if (this.monitor != null) { + this.monitor.addListener(this, null); - this.clientCM.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.clientCM.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.clientCM.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); + this.setCellInventory(this.monitor); - if( Platform.isServer() ) - { - this.serverCM = monitorable.getConfigManager(); + if (monitorable instanceof IPortableCell) { + this.setPowerSource((IEnergySource) monitorable); + } else if (monitorable instanceof IMEChest) { + this.setPowerSource((IEnergySource) monitorable); + } else if (monitorable instanceof IGridHost) { + final IGridNode node + = ((IGridHost) monitorable).getGridNode(ForgeDirection.UNKNOWN); + if (node != null) { + this.networkNode = node; + final IGrid g = node.getGrid(); + if (g != null) { + this.setPowerSource(new ChannelPowerSrc( + this.networkNode, + (IEnergySource) g.getCache(IEnergyGrid.class) + )); + } + } + } + } else { + this.setValidContainer(false); + } + } else { + this.monitor = null; + } - this.monitor = monitorable.getItemInventory(); - if( this.monitor != null ) - { - this.monitor.addListener( this, null ); + this.canAccessViewCells = false; + if (monitorable instanceof IViewCellStorage) { + 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.getInventoryPlayer() + ); + this.cellView[y].setAllowEdit(this.canAccessViewCells); + this.addSlotToContainer(this.cellView[y]); + } + } - this.setCellInventory( this.monitor ); + if (bindInventory) { + this.bindPlayerInventory(ip, 0, 0); + } + } - if( monitorable instanceof IPortableCell ) - { - this.setPowerSource( (IEnergySource) monitorable ); - } - else if( monitorable instanceof IMEChest ) - { - this.setPowerSource( (IEnergySource) monitorable ); - } - else if( monitorable instanceof IGridHost ) - { - final IGridNode node = ( (IGridHost) monitorable ).getGridNode( ForgeDirection.UNKNOWN ); - if( node != null ) - { - this.networkNode = node; - final IGrid g = node.getGrid(); - if( g != null ) - { - this.setPowerSource( new ChannelPowerSrc( this.networkNode, (IEnergySource) g.getCache( IEnergyGrid.class ) ) ); - } - } - } - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.monitor = null; - } + public IGridNode getNetworkNode() { + return this.networkNode; + } - this.canAccessViewCells = false; - if( monitorable instanceof IViewCellStorage ) - { - 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.getInventoryPlayer() ); - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - this.addSlotToContainer( this.cellView[y] ); - } - } + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + if (this.monitor != this.host.getItemInventory()) { + this.setValidContainer(false); + } - if( bindInventory ) - { - this.bindPlayerInventory( ip, 0, 0 ); - } - } + for (final Settings set : this.serverCM.getSettings()) { + final Enum sideLocal = this.serverCM.getSetting(set); + final Enum sideRemote = this.clientCM.getSetting(set); - public IGridNode getNetworkNode() - { - return this.networkNode; - } + if (sideLocal != sideRemote) { + this.clientCM.putSetting(set, sideLocal); + for (final Object crafter : this.crafters) { + try { + NetworkHandler.instance.sendTo( + new PacketValueConfig(set.name(), sideLocal.name()), + (EntityPlayerMP) crafter + ); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - if( this.monitor != this.host.getItemInventory() ) - { - this.setValidContainer( false ); - } + if (!this.items.isEmpty()) { + try { + final IItemList monitorCache + = this.monitor.getStorageList(); - for( final Settings set : this.serverCM.getSettings() ) - { - final Enum sideLocal = this.serverCM.getSetting( set ); - final Enum sideRemote = this.clientCM.getSetting( set ); + final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - if( sideLocal != sideRemote ) - { - this.clientCM.putSetting( set, sideLocal ); - for( final Object crafter : this.crafters ) - { - try - { - NetworkHandler.instance.sendTo( new PacketValueConfig( set.name(), sideLocal.name() ), (EntityPlayerMP) crafter ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } + for (final IAEItemStack is : this.items) { + final IAEItemStack send = monitorCache.findPrecise(is); + if (send == null) { + is.setStackSize(0); + piu.appendItem(is); + } else { + piu.appendItem(send); + } + } - if( !this.items.isEmpty() ) - { - try - { - final IItemList monitorCache = this.monitor.getStorageList(); + if (!piu.isEmpty()) { + this.items.resetStatus(); - final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + for (final Object c : this.crafters) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } + } + } + } catch (final IOException e) { + AELog.debug(e); + } + } - for( final IAEItemStack is : this.items ) - { - final IAEItemStack send = monitorCache.findPrecise( is ); - if( send == null ) - { - is.setStackSize( 0 ); - piu.appendItem( is ); - } - else - { - piu.appendItem( send ); - } - } + this.updatePowerStatus(); - if( !piu.isEmpty() ) - { - this.items.resetStatus(); + final boolean oldAccessible = this.canAccessViewCells; + this.canAccessViewCells = this.hasAccess(SecurityPermissions.BUILD, false); + if (this.canAccessViewCells != oldAccessible) { + for (int y = 0; y < 5; y++) { + if (this.cellView[y] != null) { + this.cellView[y].setAllowEdit(this.canAccessViewCells); + } + } + } - for( final Object c : this.crafters ) - { - if( c instanceof EntityPlayer ) - { - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); - } - } - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } + super.detectAndSendChanges(); + } + } - this.updatePowerStatus(); + protected void updatePowerStatus() { + try { + if (this.networkNode != null) { + this.setPowered(this.networkNode.isActive()); + } else if (this.getPowerSource() instanceof IEnergyGrid) { + this.setPowered(((IEnergyGrid) this.getPowerSource()).isNetworkPowered()); + } else { + this.setPowered( + this.getPowerSource().extractAEPower( + 1, Actionable.SIMULATE, PowerMultiplier.CONFIG + ) + > 0.8 + ); + } + } catch (final Throwable t) { + // :P + } + } - final boolean oldAccessible = this.canAccessViewCells; - this.canAccessViewCells = this.hasAccess( SecurityPermissions.BUILD, false ); - if( this.canAccessViewCells != oldAccessible ) - { - for( int y = 0; y < 5; y++ ) - { - if( this.cellView[y] != null ) - { - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - } - } - } + @Override + public void + onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("canAccessViewCells")) { + for (int y = 0; y < 5; y++) { + if (this.cellView[y] != null) { + this.cellView[y].setAllowEdit(this.canAccessViewCells); + } + } + } - super.detectAndSendChanges(); - } - } + super.onUpdate(field, oldValue, newValue); + } - protected void updatePowerStatus() - { - try - { - if( this.networkNode != null ) - { - this.setPowered( this.networkNode.isActive() ); - } - else if( this.getPowerSource() instanceof IEnergyGrid ) - { - this.setPowered( ( (IEnergyGrid) this.getPowerSource() ).isNetworkPowered() ); - } - else - { - this.setPowered( this.getPowerSource().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.8 ); - } - } - catch( final Throwable t ) - { - // :P - } - } + @Override + public void addCraftingToCrafters(final ICrafting c) { + super.addCraftingToCrafters(c); + this.queueInventory(c); + } - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "canAccessViewCells" ) ) - { - for( int y = 0; y < 5; y++ ) - { - if( this.cellView[y] != null ) - { - this.cellView[y].setAllowEdit( this.canAccessViewCells ); - } - } - } + private void queueInventory(final ICrafting c) { + if (Platform.isServer() && c instanceof EntityPlayer && this.monitor != null) { + try { + PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + final IItemList monitorCache + = this.monitor.getStorageList(); - super.onUpdate( field, oldValue, newValue ); - } + for (final IAEItemStack send : monitorCache) { + try { + piu.appendItem(send); + } catch (final BufferOverflowException boe) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); - @Override - public void addCraftingToCrafters( final ICrafting c ) - { - super.addCraftingToCrafters( c ); - this.queueInventory( c ); - } + piu = new PacketMEInventoryUpdate(); + piu.appendItem(send); + } + } - private void queueInventory( final ICrafting c ) - { - if( Platform.isServer() && c instanceof EntityPlayer && this.monitor != null ) - { - try - { - PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - final IItemList monitorCache = this.monitor.getStorageList(); + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } catch (final IOException e) { + AELog.debug(e); + } + } + } - for( final IAEItemStack send : monitorCache ) - { - try - { - piu.appendItem( send ); - } - catch( final BufferOverflowException boe ) - { - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); + @Override + public void removeCraftingFromCrafters(final ICrafting c) { + super.removeCraftingFromCrafters(c); - piu = new PacketMEInventoryUpdate(); - piu.appendItem( send ); - } - } + if (this.crafters.isEmpty() && this.monitor != null) { + this.monitor.removeListener(this); + } + } - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); + if (this.monitor != null) { + this.monitor.removeListener(this); + } + } - @Override - public void removeCraftingFromCrafters( final ICrafting c ) - { - super.removeCraftingFromCrafters( c ); + @Override + public boolean isValid(final Object verificationToken) { + return true; + } - if( this.crafters.isEmpty() && this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource source + ) { + for (final IAEItemStack is : change) { + this.items.add(is); + } + } - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } - } + @Override + public void onListUpdate() { + for (final Object c : this.crafters) { + if (c instanceof ICrafting) { + final ICrafting cr = (ICrafting) c; + this.queueInventory(cr); + } + } + } - @Override - public boolean isValid( final Object verificationToken ) - { - return true; - } + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + if (this.getGui() != null) { + this.getGui().updateSetting(manager, settingName, newValue); + } + } - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - for( final IAEItemStack is : change ) - { - this.items.add( is ); - } - } + @Override + public IConfigManager getConfigManager() { + if (Platform.isServer()) { + return this.serverCM; + } + return this.clientCM; + } - @Override - public void onListUpdate() - { - for( final Object c : this.crafters ) - { - if( c instanceof ICrafting ) - { - final ICrafting cr = (ICrafting) c; - this.queueInventory( cr ); - } - } - } + public ItemStack[] getViewCells() { + if (host instanceof TileTerminal) { + return new ItemStack[0]; + } + final ItemStack[] list = new ItemStack[this.cellView.length]; - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - if( this.getGui() != null ) - { - this.getGui().updateSetting( manager, settingName, newValue ); - } - } + for (int x = 0; x < this.cellView.length; x++) { + list[x] = this.cellView[x].getStack(); + } - @Override - public IConfigManager getConfigManager() - { - if( Platform.isServer() ) - { - return this.serverCM; - } - return this.clientCM; - } + return list; + } - public ItemStack[] getViewCells() - { - if (host instanceof TileTerminal) { - return new ItemStack[0]; - } - final ItemStack[] list = new ItemStack[this.cellView.length]; + public SlotRestrictedInput getCellViewSlot(final int index) { + return this.cellView[index]; + } - for( int x = 0; x < this.cellView.length; x++ ) - { - list[x] = this.cellView[x].getStack(); - } + public boolean isPowered() { + return this.hasPower; + } - return list; - } + private void setPowered(final boolean isPowered) { + this.hasPower = isPowered; + } - public SlotRestrictedInput getCellViewSlot( final int index ) - { - return this.cellView[index]; - } + private IConfigManagerHost getGui() { + return this.gui; + } - public boolean isPowered() - { - return this.hasPower; - } - - private void setPowered( final boolean isPowered ) - { - this.hasPower = isPowered; - } - - private IConfigManagerHost getGui() - { - return this.gui; - } - - public void setGui( @Nonnull final IConfigManagerHost gui ) - { - this.gui = gui; - } + public void setGui(@Nonnull final IConfigManagerHost gui) { + this.gui = gui; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java index 4edea582..5d41e016 100644 --- a/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java +++ b/src/main/java/appeng/container/implementations/ContainerMEPortableCell.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.implementations.guiobjects.IPortableCell; @@ -27,82 +26,71 @@ import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; +public class ContainerMEPortableCell extends ContainerMEMonitorable { + private double powerMultiplier = 0.5; -public class ContainerMEPortableCell extends ContainerMEMonitorable -{ + private final IPortableCell civ; + private int ticks = 0; + private final int slot; - private double powerMultiplier = 0.5; + public ContainerMEPortableCell( + final InventoryPlayer ip, final IPortableCell monitorable + ) { + super(ip, monitorable, false); + if (monitorable instanceof IInventorySlotAware) { + final int slotIndex = ((IInventorySlotAware) monitorable).getInventorySlot(); + this.lockPlayerInventorySlot(slotIndex); + this.slot = slotIndex; + } else { + this.slot = -1; + this.lockPlayerInventorySlot(ip.currentItem); + } + this.civ = monitorable; + this.bindPlayerInventory(ip, 0, 0); + } - private final IPortableCell civ; - private int ticks = 0; - private final int slot; + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.slot < 0 + ? this.getPlayerInv().getCurrentItem() + : this.getPlayerInv().getStackInSlot(this.slot); - public ContainerMEPortableCell( final InventoryPlayer ip, final IPortableCell monitorable ) - { - super( ip, monitorable, false ); - if( monitorable instanceof IInventorySlotAware ) - { - final int slotIndex = ( (IInventorySlotAware) monitorable ).getInventorySlot(); - this.lockPlayerInventorySlot( slotIndex ); - this.slot = slotIndex; - } - else - { - this.slot = -1; - this.lockPlayerInventorySlot( ip.currentItem ); - } - this.civ = monitorable; - this.bindPlayerInventory( ip, 0, 0 ); - } + if (this.civ != null) { + if (currentItem != this.civ.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem(this.civ.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents( + this.getPlayerInv().currentItem, this.civ.getItemStack() + ); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } + } else { + this.setValidContainer(false); + } - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.slot < 0 ? this.getPlayerInv().getCurrentItem() : this.getPlayerInv().getStackInSlot( this.slot ); + // drain 1 ae t + this.ticks++; + if (this.ticks > 10) { + this.civ.extractAEPower( + this.getPowerMultiplier() * this.ticks, + Actionable.MODULATE, + PowerMultiplier.CONFIG + ); + this.ticks = 0; + } + super.detectAndSendChanges(); + } - if( this.civ != null ) - { - if( currentItem != this.civ.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.civ.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.civ.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } - } - else - { - this.setValidContainer( false ); - } + private double getPowerMultiplier() { + return this.powerMultiplier; + } - // drain 1 ae t - this.ticks++; - if( this.ticks > 10 ) - { - this.civ.extractAEPower( this.getPowerMultiplier() * this.ticks, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.ticks = 0; - } - super.detectAndSendChanges(); - } - - private double getPowerMultiplier() - { - return this.powerMultiplier; - } - - void setPowerMultiplier( final double powerMultiplier ) - { - this.powerMultiplier = powerMultiplier; - } + void setPowerMultiplier(final double powerMultiplier) { + this.powerMultiplier = powerMultiplier; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java b/src/main/java/appeng/container/implementations/ContainerNetworkStatus.java index 25743a74..f906668f 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 appeng.api.AEApi; import appeng.api.implementations.guiobjects.INetworkTool; @@ -40,155 +41,127 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; +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; + private IGrid network; + private int delay = 40; - -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; - private IGrid network; - private int delay = 40; - - public ContainerNetworkStatus( final InventoryPlayer ip, final INetworkTool te ) { + public ContainerNetworkStatus(final InventoryPlayer ip, final INetworkTool te) { this(ip, te.getGridHost()); } - public ContainerNetworkStatus( final InventoryPlayer ip, final IGridHost te ) - { - super( ip, null, null ); - final IGridHost host = te; + public ContainerNetworkStatus(final InventoryPlayer ip, final IGridHost te) { + super(ip, null, null); + final IGridHost host = te; - if( host != null ) - { - this.findNode( host, ForgeDirection.UNKNOWN ); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.findNode( host, d ); - } - } + if (host != null) { + this.findNode(host, ForgeDirection.UNKNOWN); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.findNode(host, d); + } + } - if( this.network == null && Platform.isServer() ) - { - this.setValidContainer( false ); - } - } + if (this.network == null && Platform.isServer()) { + this.setValidContainer(false); + } + } - private void findNode( final IGridHost host, final ForgeDirection d ) - { - if( this.network == null ) - { - final IGridNode node = host.getGridNode( d ); - if( node != null ) - { - this.network = node.getGrid(); - } - } - } + private void findNode(final IGridHost host, final ForgeDirection d) { + if (this.network == null) { + final IGridNode node = host.getGridNode(d); + if (node != null) { + this.network = node.getGrid(); + } + } + } - @Override - public void detectAndSendChanges() - { - this.delay++; - if( Platform.isServer() && this.delay > 15 && this.network != null ) - { - this.delay = 0; + @Override + public void detectAndSendChanges() { + this.delay++; + if (Platform.isServer() && this.delay > 15 && this.network != null) { + this.delay = 0; - final IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); - if( eg != null ) - { - this.setAverageAddition( (long) ( 100.0 * eg.getAvgPowerInjection() ) ); - this.setPowerUsage( (long) ( 100.0 * eg.getAvgPowerUsage() ) ); - this.setCurrentPower( (long) ( 100.0 * eg.getStoredPower() ) ); - this.setMaxPower( (long) ( 100.0 * eg.getMaxStoredPower() ) ); - } + final IEnergyGrid eg = this.network.getCache(IEnergyGrid.class); + if (eg != null) { + this.setAverageAddition((long) (100.0 * eg.getAvgPowerInjection())); + this.setPowerUsage((long) (100.0 * eg.getAvgPowerUsage())); + this.setCurrentPower((long) (100.0 * eg.getStoredPower())); + this.setMaxPower((long) (100.0 * eg.getMaxStoredPower())); + } - try - { - final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); + try { + final PacketMEInventoryUpdate piu = new PacketMEInventoryUpdate(); - for( final Class machineClass : this.network.getMachinesClasses() ) - { - final IItemList list = AEApi.instance().storage().createItemList(); - for( final IGridNode machine : this.network.getMachines( machineClass ) ) - { - final IGridBlock blk = machine.getGridBlock(); - final ItemStack is = blk.getMachineRepresentation(); - if( is != null && is.getItem() != null ) - { - final IAEItemStack ais = AEItemStack.create( is ); - ais.setStackSize( 1 ); - ais.setCountRequestable( (long) ( blk.getIdlePowerUsage() * 100.0 ) ); - list.add( ais ); - } - } + for (final Class machineClass : + this.network.getMachinesClasses()) { + final IItemList list + = AEApi.instance().storage().createItemList(); + for (final IGridNode machine : + this.network.getMachines(machineClass)) { + final IGridBlock blk = machine.getGridBlock(); + final ItemStack is = blk.getMachineRepresentation(); + if (is != null && is.getItem() != null) { + final IAEItemStack ais = AEItemStack.create(is); + ais.setStackSize(1); + ais.setCountRequestable((long + ) (blk.getIdlePowerUsage() * 100.0)); + list.add(ais); + } + } - for( final IAEItemStack ais : list ) - { - piu.appendItem( ais ); - } - } + for (final IAEItemStack ais : list) { + piu.appendItem(ais); + } + } - for( final Object c : this.crafters ) - { - if( c instanceof EntityPlayer ) - { - NetworkHandler.instance.sendTo( piu, (EntityPlayerMP) c ); - } - } - } - catch( final IOException e ) - { - // :P - } - } - super.detectAndSendChanges(); - } + for (final Object c : this.crafters) { + if (c instanceof EntityPlayer) { + NetworkHandler.instance.sendTo(piu, (EntityPlayerMP) c); + } + } + } catch (final IOException e) { + // :P + } + } + super.detectAndSendChanges(); + } - public long getCurrentPower() - { - return this.currentPower; - } + public long getCurrentPower() { + return this.currentPower; + } - private void setCurrentPower( final long currentPower ) - { - this.currentPower = currentPower; - } + private void setCurrentPower(final long currentPower) { + this.currentPower = currentPower; + } - public long getMaxPower() - { - return this.maxPower; - } + public long getMaxPower() { + return this.maxPower; + } - private void setMaxPower( final long maxPower ) - { - this.maxPower = maxPower; - } + private void setMaxPower(final long maxPower) { + this.maxPower = maxPower; + } - public long getAverageAddition() - { - return this.avgAddition; - } + public long getAverageAddition() { + return this.avgAddition; + } - private void setAverageAddition( final long avgAddition ) - { - this.avgAddition = avgAddition; - } + private void setAverageAddition(final long avgAddition) { + this.avgAddition = avgAddition; + } - public long getPowerUsage() - { - return this.powerUsage; - } + public long getPowerUsage() { + return this.powerUsage; + } - private void setPowerUsage( final long powerUsage ) - { - this.powerUsage = powerUsage; - } + private void setPowerUsage(final long powerUsage) { + this.powerUsage = powerUsage; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java index 75e75323..38da16f1 100644 --- a/src/main/java/appeng/container/implementations/ContainerNetworkTool.java +++ b/src/main/java/appeng/container/implementations/ContainerNetworkTool.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; @@ -28,80 +27,71 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public class ContainerNetworkTool extends AEBaseContainer { + private final INetworkTool toolInv; -public class ContainerNetworkTool extends AEBaseContainer -{ + @GuiSync(1) + public boolean facadeMode; - private final INetworkTool toolInv; + public ContainerNetworkTool(final InventoryPlayer ip, final INetworkTool te) { + super(ip, null, null); + this.toolInv = te; - @GuiSync( 1 ) - public boolean facadeMode; + this.lockPlayerInventorySlot(ip.currentItem); - public ContainerNetworkTool( final InventoryPlayer ip, final INetworkTool te ) - { - super( ip, null, null ); - this.toolInv = te; + 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.getInventoryPlayer() + ))); + } + } - this.lockPlayerInventorySlot( ip.currentItem ); + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } - 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.getInventoryPlayer() ) ) ); - } - } + public void toggleFacadeMode() { + final NBTTagCompound data = Platform.openNbtData(this.toolInv.getItemStack()); + data.setBoolean("hideFacades", !data.getBoolean("hideFacades")); + this.detectAndSendChanges(); + } - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - public void toggleFacadeMode() - { - final NBTTagCompound data = Platform.openNbtData( this.toolInv.getItemStack() ); - data.setBoolean( "hideFacades", !data.getBoolean( "hideFacades" ) ); - this.detectAndSendChanges(); - } + if (currentItem != this.toolInv.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem(this.toolInv.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents( + this.getPlayerInv().currentItem, this.toolInv.getItemStack() + ); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); + if (this.isValidContainer()) { + final NBTTagCompound data = Platform.openNbtData(currentItem); + this.setFacadeMode(data.getBoolean("hideFacades")); + } - if( currentItem != this.toolInv.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } + super.detectAndSendChanges(); + } - if( this.isValidContainer() ) - { - final NBTTagCompound data = Platform.openNbtData( currentItem ); - this.setFacadeMode( data.getBoolean( "hideFacades" ) ); - } + public boolean isFacadeMode() { + return this.facadeMode; + } - super.detectAndSendChanges(); - } - - public boolean isFacadeMode() - { - return this.facadeMode; - } - - private void setFacadeMode( final boolean facadeMode ) - { - this.facadeMode = facadeMode; - } + private void setFacadeMode(final boolean facadeMode) { + this.facadeMode = facadeMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java index 56c4e62a..c49c9330 100644 --- a/src/main/java/appeng/container/implementations/ContainerPatternTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerPatternTerm.java @@ -18,6 +18,8 @@ package appeng.container.implementations; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -53,504 +55,499 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.List; - - -public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket -{ - - private final PartPatternTerminal patternTerminal; - private final AppEngInternalInventory cOut = new AppEngInternalInventory( null, 1 ); - private final IInventory crafting; - private final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[9]; - private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[3]; - private final SlotPatternTerm craftSlot; - private final SlotRestrictedInput patternSlotIN; - private final SlotRestrictedInput patternSlotOUT; - @GuiSync( 97 ) - public boolean craftingMode = true; - @GuiSync( 96 ) - public boolean substitute = false; - - public ContainerPatternTerm( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); - this.patternTerminal = (PartPatternTerminal) monitorable; - - final IInventory patternInv = this.getPatternTerminal().getInventoryByName( "pattern" ); - final IInventory output = this.getPatternTerminal().getInventoryByName( "output" ); - - this.crafting = this.getPatternTerminal().getInventoryByName( "crafting" ); - - 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.getActionSource(), this.getPowerSource(), monitorable, this.crafting, patternInv, this.cOut, 110, -76 + 18, this, 2, this ) ); - this.craftSlot.setIIcon( -1 ); - - 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].setRenderDisabled( false ); - this.outputSlots[y].setIIcon( -1 ); - } - - this.addSlotToContainer( this.patternSlotIN = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, patternInv, 0, 147, -72 - 9, this.getInventoryPlayer() ) ); - this.addSlotToContainer( this.patternSlotOUT = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, patternInv, 1, 147, -72 + 34, this.getInventoryPlayer() ) ); - - this.patternSlotOUT.setStackLimit( 1 ); - - this.bindPlayerInventory( ip, 0, 0 ); - this.updateOrderOfOutputSlots(); - } - - private void updateOrderOfOutputSlots() - { - if( !this.isCraftingMode() ) - { - this.craftSlot.xDisplayPosition = -9000; - - for( int y = 0; y < 3; y++ ) - { - this.outputSlots[y].xDisplayPosition = this.outputSlots[y].getX(); - } - } - else - { - this.craftSlot.xDisplayPosition = this.craftSlot.getX(); - - for( int y = 0; y < 3; y++ ) - { - this.outputSlots[y].xDisplayPosition = -9000; - } - } - } - - @Override - public void putStackInSlot( final int par1, final ItemStack par2ItemStack ) - { - super.putStackInSlot( par1, par2ItemStack ); - this.getAndUpdateOutput(); - } - - @Override - public void putStacksInSlots( final ItemStack[] par1ArrayOfItemStack ) - { - super.putStacksInSlots( par1ArrayOfItemStack ); - this.getAndUpdateOutput(); - } - - private ItemStack getAndUpdateOutput() - { - final InventoryCrafting ic = new InventoryCrafting( this, 3, 3 ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - ic.setInventorySlotContents( x, this.crafting.getStackInSlot( x ) ); - } - - final ItemStack is = CraftingManager.getInstance().findMatchingRecipe( ic, this.getPlayerInv().player.worldObj ); - this.cOut.setInventorySlotContents( 0, is ); - return is; - } - - @Override - public void saveChanges() - { - - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - - } - - public void encode() - { - ItemStack output = this.patternSlotOUT.getStack(); - - final ItemStack[] in = this.getInputs(); - final ItemStack[] out = this.getOutputs(); - - // if there is no input, this would be silly. - if( in == null || out == null ) - { - return; - } - - // first check the output slots, should either be null, or a pattern - if( output != null && !this.isPattern( output ) ) - { - return; - }// if nothing is there we should snag a new pattern. - else if( output == null ) - { - output = this.patternSlotIN.getStack(); - if( output == null || !this.isPattern( output ) ) - { - return; // no blanks. - } - - // remove one, and clear the input slot. - output.stackSize--; - if( output.stackSize == 0 ) - { - this.patternSlotIN.putStack( null ); - } - - // add a new encoded pattern. - for( final ItemStack encodedPatternStack : AEApi.instance().definitions().items().encodedPattern().maybeStack( 1 ).asSet() ) - { - output = encodedPatternStack; - this.patternSlotOUT.putStack( output ); - } - } - - // encode the slot. - final NBTTagCompound encodedValue = new NBTTagCompound(); - - final NBTTagList tagIn = new NBTTagList(); - final NBTTagList tagOut = new NBTTagList(); - - for( final ItemStack i : in ) - { - tagIn.appendTag( this.createItemTag( i ) ); - } - - for( final ItemStack i : out ) - { - tagOut.appendTag( this.createItemTag( i ) ); - } - - encodedValue.setTag( "in", tagIn ); - encodedValue.setTag( "out", tagOut ); - encodedValue.setBoolean( "crafting", this.isCraftingMode() ); - encodedValue.setBoolean( "substitute", this.isSubstitute() ); - - output.setTagCompound( encodedValue ); - } - - private ItemStack[] getInputs() - { - final ItemStack[] input = new ItemStack[9]; - boolean hasValue = false; - - for( int x = 0; x < this.craftingSlots.length; x++ ) - { - input[x] = this.craftingSlots[x].getStack(); - if( input[x] != null ) - { - hasValue = true; - } - } - - if( hasValue ) - { - return input; - } - - return null; - } - - private ItemStack[] getOutputs() - { - if( this.isCraftingMode() ) - { - final ItemStack out = this.getAndUpdateOutput(); - - if( out != null && out.stackSize > 0 ) - { - return new ItemStack[] { out }; - } - } - else - { - final List list = new ArrayList( 3 ); - boolean hasValue = false; - - for( final OptionalSlotFake outputSlot : this.outputSlots ) - { - final ItemStack out = outputSlot.getStack(); - - if( out != null && out.stackSize > 0 ) - { - list.add( out ); - hasValue = true; - } - } - - if( hasValue ) - { - return list.toArray( new ItemStack[list.size()] ); - } - } - - return null; - } - - private boolean isPattern( final ItemStack output ) - { - if( output == null ) - { - return false; - } - - final IDefinitions definitions = AEApi.instance().definitions(); - - boolean isPattern = definitions.items().encodedPattern().isSameAs( output ); - isPattern |= definitions.materials().blankPattern().isSameAs( output ); - - return isPattern; - } - - private NBTBase createItemTag( final ItemStack i ) - { - final NBTTagCompound c = new NBTTagCompound(); - - if( i != null ) - { - i.writeToNBT( c ); - } - - return c; - } - - @Override - public boolean isSlotEnabled( final int idx ) - { - if( idx == 1 ) - { - return Platform.isServer() ? !this.getPatternTerminal().isCraftingRecipe() : !this.isCraftingMode(); - } - else if( idx == 2 ) - { - return Platform.isServer() ? this.getPatternTerminal().isCraftingRecipe() : this.isCraftingMode(); - } - else - { - return false; - } - } - - public void craftOrGetItem( final PacketPatternSlot packetPatternSlot ) - { - if( packetPatternSlot.slotItem != null && this.getCellInventory() != null ) - { - final IAEItemStack out = packetPatternSlot.slotItem.copy(); - InventoryAdaptor inv = new AdaptorPlayerHand( this.getPlayerInv().player ); - final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( this.getPlayerInv().player, ForgeDirection.UNKNOWN ); - - if( packetPatternSlot.shift ) - { - inv = playerInv; - } - - if( inv.simulateAdd( out.getItemStack() ) != null ) - { - return; - } - - final IAEItemStack extracted = Platform.poweredExtraction( this.getPowerSource(), this.getCellInventory(), out, this.getActionSource() ); - final EntityPlayer p = this.getPlayerInv().player; - - if( extracted != null ) - { - inv.addItems( extracted.getItemStack() ); - if( p instanceof EntityPlayerMP ) - { - this.updateHeld( (EntityPlayerMP) p ); - } - this.detectAndSendChanges(); - return; - } - - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - final InventoryCrafting real = new InventoryCrafting( new ContainerNull(), 3, 3 ); - - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, packetPatternSlot.pattern[x] == null ? null : packetPatternSlot.pattern[x].getItemStack() ); - } - - final IRecipe r = Platform.findMatchingRecipe( ic, p.worldObj ); - - if( r == null ) - { - return; - } - - final IMEMonitor storage = this.getPatternTerminal().getItemInventory(); - final IItemList all = storage.getStorageList(); - - final ItemStack is = r.getCraftingResult( ic ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - if( ic.getStackInSlot( x ) != null ) - { - final ItemStack pulled = Platform.extractItemsByRecipe( this.getPowerSource(), this.getActionSource(), storage, p.worldObj, r, is, ic, ic.getStackInSlot( x ), x, all, Actionable.MODULATE, ItemViewCell.createFilter( this.getViewCells() ) ); - real.setInventorySlotContents( x, pulled ); - } - } - - final IRecipe rr = Platform.findMatchingRecipe( real, p.worldObj ); - - if( rr == r && Platform.isSameItemPrecise( rr.getCraftingResult( real ), is ) ) - { - final SlotCrafting sc = new SlotCrafting( p, real, this.cOut, 0, 0, 0 ); - sc.onPickupFromSlot( p, is ); - - for( int x = 0; x < real.getSizeInventory(); x++ ) - { - final ItemStack failed = playerInv.addItems( real.getStackInSlot( x ) ); - - if( failed != null ) - { - p.dropPlayerItemWithRandomChoice( failed, false ); - } - } - - inv.addItems( is ); - if( p instanceof EntityPlayerMP ) - { - this.updateHeld( (EntityPlayerMP) p ); - } - this.detectAndSendChanges(); - } - else - { - for( int x = 0; x < real.getSizeInventory(); x++ ) - { - final ItemStack failed = real.getStackInSlot( x ); - if( failed != null ) - { - this.getCellInventory().injectItems( AEItemStack.create( failed ), Actionable.MODULATE, new MachineSource( this.getPatternTerminal() ) ); - } - } - } - } - } - - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - if( Platform.isServer() ) - { - if( this.isCraftingMode() != this.getPatternTerminal().isCraftingRecipe() ) - { - this.setCraftingMode( this.getPatternTerminal().isCraftingRecipe() ); - this.updateOrderOfOutputSlots(); - } - - this.substitute = this.patternTerminal.isSubstitution(); - } - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - super.onUpdate( field, oldValue, newValue ); - - if( field.equals( "craftingMode" ) ) - { - this.getAndUpdateOutput(); - this.updateOrderOfOutputSlots(); - } - } - - @Override - public void onSlotChange( final Slot s ) - { - if( s == this.patternSlotOUT && Platform.isServer() ) - { - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; - - for( final Object g : this.inventorySlots ) - { - if( g instanceof OptionalSlotFake || g instanceof SlotFakeCraftingMatrix ) - { - final Slot sri = (Slot) g; - icrafting.sendSlotContents( this, sri.slotNumber, sri.getStack() ); - } - } - ( (EntityPlayerMP) icrafting ).isChangingQuantityOnly = false; - } - this.detectAndSendChanges(); - } - } - - public void clear() - { - for( final Slot s : this.craftingSlots ) - { - s.putStack( null ); - } - - for( final Slot s : this.outputSlots ) - { - s.putStack( null ); - } - - this.detectAndSendChanges(); - this.getAndUpdateOutput(); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "player" ) ) - { - return this.getInventoryPlayer(); - } - return this.getPatternTerminal().getInventoryByName( name ); - } - - @Override - public boolean useRealItems() - { - return false; - } - - public void toggleSubstitute() - { - this.substitute = !this.substitute; - - this.detectAndSendChanges(); - this.getAndUpdateOutput(); - } - - public boolean isCraftingMode() - { - return this.craftingMode; - } - - private void setCraftingMode( final boolean craftingMode ) - { - this.craftingMode = craftingMode; - } - - public PartPatternTerminal getPatternTerminal() - { - return this.patternTerminal; - } - - private boolean isSubstitute() - { - return this.substitute; - } - - public void setSubstitute( final boolean substitute ) - { - this.substitute = substitute; - } +public class ContainerPatternTerm extends ContainerMEMonitorable + implements IAEAppEngInventory, IOptionalSlotHost, IContainerCraftingPacket { + private final PartPatternTerminal patternTerminal; + private final AppEngInternalInventory cOut = new AppEngInternalInventory(null, 1); + private final IInventory crafting; + private final SlotFakeCraftingMatrix[] craftingSlots = new SlotFakeCraftingMatrix[9]; + private final OptionalSlotFake[] outputSlots = new OptionalSlotFake[3]; + private final SlotPatternTerm craftSlot; + private final SlotRestrictedInput patternSlotIN; + private final SlotRestrictedInput patternSlotOUT; + @GuiSync(97) + public boolean craftingMode = true; + @GuiSync(96) + public boolean substitute = false; + + public ContainerPatternTerm( + final InventoryPlayer ip, final ITerminalHost monitorable + ) { + super(ip, monitorable, false); + this.patternTerminal = (PartPatternTerminal) monitorable; + + final IInventory patternInv + = this.getPatternTerminal().getInventoryByName("pattern"); + final IInventory output = this.getPatternTerminal().getInventoryByName("output"); + + this.crafting = this.getPatternTerminal().getInventoryByName("crafting"); + + 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.getActionSource(), + this.getPowerSource(), + monitorable, + this.crafting, + patternInv, + this.cOut, + 110, + -76 + 18, + this, + 2, + this + ) + ); + this.craftSlot.setIIcon(-1); + + 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].setRenderDisabled(false); + this.outputSlots[y].setIIcon(-1); + } + + this.addSlotToContainer( + this.patternSlotIN = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.BLANK_PATTERN, + patternInv, + 0, + 147, + -72 - 9, + this.getInventoryPlayer() + ) + ); + this.addSlotToContainer( + this.patternSlotOUT = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, + patternInv, + 1, + 147, + -72 + 34, + this.getInventoryPlayer() + ) + ); + + this.patternSlotOUT.setStackLimit(1); + + this.bindPlayerInventory(ip, 0, 0); + this.updateOrderOfOutputSlots(); + } + + private void updateOrderOfOutputSlots() { + if (!this.isCraftingMode()) { + this.craftSlot.xDisplayPosition = -9000; + + for (int y = 0; y < 3; y++) { + this.outputSlots[y].xDisplayPosition = this.outputSlots[y].getX(); + } + } else { + this.craftSlot.xDisplayPosition = this.craftSlot.getX(); + + for (int y = 0; y < 3; y++) { + this.outputSlots[y].xDisplayPosition = -9000; + } + } + } + + @Override + public void putStackInSlot(final int par1, final ItemStack par2ItemStack) { + super.putStackInSlot(par1, par2ItemStack); + this.getAndUpdateOutput(); + } + + @Override + public void putStacksInSlots(final ItemStack[] par1ArrayOfItemStack) { + super.putStacksInSlots(par1ArrayOfItemStack); + this.getAndUpdateOutput(); + } + + private ItemStack getAndUpdateOutput() { + final InventoryCrafting ic = new InventoryCrafting(this, 3, 3); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + ic.setInventorySlotContents(x, this.crafting.getStackInSlot(x)); + } + + final ItemStack is = CraftingManager.getInstance().findMatchingRecipe( + ic, this.getPlayerInv().player.worldObj + ); + this.cOut.setInventorySlotContents(0, is); + return is; + } + + @Override + public void saveChanges() {} + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) {} + + public void encode() { + ItemStack output = this.patternSlotOUT.getStack(); + + final ItemStack[] in = this.getInputs(); + final ItemStack[] out = this.getOutputs(); + + // if there is no input, this would be silly. + if (in == null || out == null) { + return; + } + + // first check the output slots, should either be null, or a pattern + if (output != null && !this.isPattern(output)) { + return; + } // if nothing is there we should snag a new pattern. + else if (output == null) { + output = this.patternSlotIN.getStack(); + if (output == null || !this.isPattern(output)) { + return; // no blanks. + } + + // remove one, and clear the input slot. + output.stackSize--; + if (output.stackSize == 0) { + this.patternSlotIN.putStack(null); + } + + // add a new encoded pattern. + for (final ItemStack encodedPatternStack : AEApi.instance() + .definitions() + .items() + .encodedPattern() + .maybeStack(1) + .asSet()) { + output = encodedPatternStack; + this.patternSlotOUT.putStack(output); + } + } + + // encode the slot. + final NBTTagCompound encodedValue = new NBTTagCompound(); + + final NBTTagList tagIn = new NBTTagList(); + final NBTTagList tagOut = new NBTTagList(); + + for (final ItemStack i : in) { + tagIn.appendTag(this.createItemTag(i)); + } + + for (final ItemStack i : out) { + tagOut.appendTag(this.createItemTag(i)); + } + + encodedValue.setTag("in", tagIn); + encodedValue.setTag("out", tagOut); + encodedValue.setBoolean("crafting", this.isCraftingMode()); + encodedValue.setBoolean("substitute", this.isSubstitute()); + + output.setTagCompound(encodedValue); + } + + private ItemStack[] getInputs() { + final ItemStack[] input = new ItemStack[9]; + boolean hasValue = false; + + for (int x = 0; x < this.craftingSlots.length; x++) { + input[x] = this.craftingSlots[x].getStack(); + if (input[x] != null) { + hasValue = true; + } + } + + if (hasValue) { + return input; + } + + return null; + } + + private ItemStack[] getOutputs() { + if (this.isCraftingMode()) { + final ItemStack out = this.getAndUpdateOutput(); + + if (out != null && out.stackSize > 0) { + return new ItemStack[] { out }; + } + } else { + final List list = new ArrayList(3); + boolean hasValue = false; + + for (final OptionalSlotFake outputSlot : this.outputSlots) { + final ItemStack out = outputSlot.getStack(); + + if (out != null && out.stackSize > 0) { + list.add(out); + hasValue = true; + } + } + + if (hasValue) { + return list.toArray(new ItemStack[list.size()]); + } + } + + return null; + } + + private boolean isPattern(final ItemStack output) { + if (output == null) { + return false; + } + + final IDefinitions definitions = AEApi.instance().definitions(); + + boolean isPattern = definitions.items().encodedPattern().isSameAs(output); + isPattern |= definitions.materials().blankPattern().isSameAs(output); + + return isPattern; + } + + private NBTBase createItemTag(final ItemStack i) { + final NBTTagCompound c = new NBTTagCompound(); + + if (i != null) { + i.writeToNBT(c); + } + + return c; + } + + @Override + public boolean isSlotEnabled(final int idx) { + if (idx == 1) { + return Platform.isServer() ? !this.getPatternTerminal().isCraftingRecipe() + : !this.isCraftingMode(); + } else if (idx == 2) { + return Platform.isServer() ? this.getPatternTerminal().isCraftingRecipe() + : this.isCraftingMode(); + } else { + return false; + } + } + + public void craftOrGetItem(final PacketPatternSlot packetPatternSlot) { + if (packetPatternSlot.slotItem != null && this.getCellInventory() != null) { + final IAEItemStack out = packetPatternSlot.slotItem.copy(); + InventoryAdaptor inv = new AdaptorPlayerHand(this.getPlayerInv().player); + final InventoryAdaptor playerInv = InventoryAdaptor.getAdaptor( + this.getPlayerInv().player, ForgeDirection.UNKNOWN + ); + + if (packetPatternSlot.shift) { + inv = playerInv; + } + + if (inv.simulateAdd(out.getItemStack()) != null) { + return; + } + + final IAEItemStack extracted = Platform.poweredExtraction( + this.getPowerSource(), + this.getCellInventory(), + out, + this.getActionSource() + ); + final EntityPlayer p = this.getPlayerInv().player; + + if (extracted != null) { + inv.addItems(extracted.getItemStack()); + if (p instanceof EntityPlayerMP) { + this.updateHeld((EntityPlayerMP) p); + } + this.detectAndSendChanges(); + return; + } + + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + final InventoryCrafting real + = new InventoryCrafting(new ContainerNull(), 3, 3); + + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents( + x, + packetPatternSlot.pattern[x] == null + ? null + : packetPatternSlot.pattern[x].getItemStack() + ); + } + + final IRecipe r = Platform.findMatchingRecipe(ic, p.worldObj); + + if (r == null) { + return; + } + + final IMEMonitor storage + = this.getPatternTerminal().getItemInventory(); + final IItemList all = storage.getStorageList(); + + final ItemStack is = r.getCraftingResult(ic); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + if (ic.getStackInSlot(x) != null) { + final ItemStack pulled = Platform.extractItemsByRecipe( + this.getPowerSource(), + this.getActionSource(), + storage, + p.worldObj, + r, + is, + ic, + ic.getStackInSlot(x), + x, + all, + Actionable.MODULATE, + ItemViewCell.createFilter(this.getViewCells()) + ); + real.setInventorySlotContents(x, pulled); + } + } + + final IRecipe rr = Platform.findMatchingRecipe(real, p.worldObj); + + if (rr == r && Platform.isSameItemPrecise(rr.getCraftingResult(real), is)) { + final SlotCrafting sc = new SlotCrafting(p, real, this.cOut, 0, 0, 0); + sc.onPickupFromSlot(p, is); + + for (int x = 0; x < real.getSizeInventory(); x++) { + final ItemStack failed = playerInv.addItems(real.getStackInSlot(x)); + + if (failed != null) { + p.dropPlayerItemWithRandomChoice(failed, false); + } + } + + inv.addItems(is); + if (p instanceof EntityPlayerMP) { + this.updateHeld((EntityPlayerMP) p); + } + this.detectAndSendChanges(); + } else { + for (int x = 0; x < real.getSizeInventory(); x++) { + final ItemStack failed = real.getStackInSlot(x); + if (failed != null) { + this.getCellInventory().injectItems( + AEItemStack.create(failed), + Actionable.MODULATE, + new MachineSource(this.getPatternTerminal()) + ); + } + } + } + } + } + + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + if (Platform.isServer()) { + if (this.isCraftingMode() != this.getPatternTerminal().isCraftingRecipe()) { + this.setCraftingMode(this.getPatternTerminal().isCraftingRecipe()); + this.updateOrderOfOutputSlots(); + } + + this.substitute = this.patternTerminal.isSubstitution(); + } + } + + @Override + public void + onUpdate(final String field, final Object oldValue, final Object newValue) { + super.onUpdate(field, oldValue, newValue); + + if (field.equals("craftingMode")) { + this.getAndUpdateOutput(); + this.updateOrderOfOutputSlots(); + } + } + + @Override + public void onSlotChange(final Slot s) { + if (s == this.patternSlotOUT && Platform.isServer()) { + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + + for (final Object g : this.inventorySlots) { + if (g instanceof OptionalSlotFake + || g instanceof SlotFakeCraftingMatrix) { + final Slot sri = (Slot) g; + icrafting.sendSlotContents(this, sri.slotNumber, sri.getStack()); + } + } + ((EntityPlayerMP) icrafting).isChangingQuantityOnly = false; + } + this.detectAndSendChanges(); + } + } + + public void clear() { + for (final Slot s : this.craftingSlots) { + s.putStack(null); + } + + for (final Slot s : this.outputSlots) { + s.putStack(null); + } + + this.detectAndSendChanges(); + this.getAndUpdateOutput(); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("player")) { + return this.getInventoryPlayer(); + } + return this.getPatternTerminal().getInventoryByName(name); + } + + @Override + public boolean useRealItems() { + return false; + } + + public void toggleSubstitute() { + this.substitute = !this.substitute; + + this.detectAndSendChanges(); + this.getAndUpdateOutput(); + } + + public boolean isCraftingMode() { + return this.craftingMode; + } + + private void setCraftingMode(final boolean craftingMode) { + this.craftingMode = craftingMode; + } + + public PartPatternTerminal getPatternTerminal() { + return this.patternTerminal; + } + + private boolean isSubstitute() { + return this.substitute; + } + + public void setSubstitute(final boolean substitute) { + this.substitute = substitute; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerPriority.java b/src/main/java/appeng/container/implementations/ContainerPriority.java index 1247c221..2ca3bf7b 100644 --- a/src/main/java/appeng/container/implementations/ContainerPriority.java +++ b/src/main/java/appeng/container/implementations/ContainerPriority.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.SecurityPermissions; import appeng.api.parts.IPart; import appeng.container.AEBaseContainer; @@ -32,59 +31,53 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.tileentity.TileEntity; +public class ContainerPriority extends AEBaseContainer { + private final IPriorityHost priHost; -public class ContainerPriority extends AEBaseContainer -{ + @SideOnly(Side.CLIENT) + private GuiTextField textField; + @GuiSync(2) + public long PriorityValue = -1; - private final IPriorityHost priHost; + public ContainerPriority(final InventoryPlayer ip, final IPriorityHost te) { + super( + ip, + (TileEntity) (te instanceof TileEntity ? te : null), + (IPart) (te instanceof IPart ? te : null) + ); + this.priHost = te; + } - @SideOnly( Side.CLIENT ) - private GuiTextField textField; - @GuiSync( 2 ) - public long PriorityValue = -1; + @SideOnly(Side.CLIENT) + public void setTextField(final GuiTextField level) { + this.textField = level; + this.textField.setText(String.valueOf(this.PriorityValue)); + } - public ContainerPriority( final InventoryPlayer ip, final IPriorityHost te ) - { - super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); - this.priHost = te; - } + public void setPriority(final int newValue, final EntityPlayer player) { + this.priHost.setPriority(newValue); + this.PriorityValue = newValue; + } - @SideOnly( Side.CLIENT ) - public void setTextField( final GuiTextField level ) - { - this.textField = level; - this.textField.setText( String.valueOf( this.PriorityValue ) ); - } + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); + this.verifyPermissions(SecurityPermissions.BUILD, false); - public void setPriority( final int newValue, final EntityPlayer player ) - { - this.priHost.setPriority( newValue ); - this.PriorityValue = newValue; - } + if (Platform.isServer()) { + this.PriorityValue = this.priHost.getPriority(); + } + } - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public void + onUpdate(final String field, final Object oldValue, final Object newValue) { + if (field.equals("PriorityValue")) { + if (this.textField != null) { + this.textField.setText(String.valueOf(this.PriorityValue)); + } + } - if( Platform.isServer() ) - { - this.PriorityValue = this.priHost.getPriority(); - } - } - - @Override - public void onUpdate( final String field, final Object oldValue, final Object newValue ) - { - if( field.equals( "PriorityValue" ) ) - { - if( this.textField != null ) - { - this.textField.setText( String.valueOf( this.PriorityValue ) ); - } - } - - super.onUpdate( field, oldValue, newValue ); - } + super.onUpdate(field, oldValue, newValue); + } } diff --git a/src/main/java/appeng/container/implementations/ContainerQNB.java b/src/main/java/appeng/container/implementations/ContainerQNB.java index 3a9f0f39..73a81216 100644 --- a/src/main/java/appeng/container/implementations/ContainerQNB.java +++ b/src/main/java/appeng/container/implementations/ContainerQNB.java @@ -18,22 +18,25 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotRestrictedInput; import appeng.tile.qnb.TileQuantumBridge; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerQNB extends AEBaseContainer { + public ContainerQNB(final InventoryPlayer ip, final TileQuantumBridge quantumBridge) { + super(ip, quantumBridge, null); -public class ContainerQNB extends AEBaseContainer -{ + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, + quantumBridge, + 0, + 80, + 37, + this.getInventoryPlayer() + )) + .setStackLimit(1)); - public ContainerQNB( final InventoryPlayer ip, final TileQuantumBridge quantumBridge ) - { - super( ip, quantumBridge, null ); - - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.QE_SINGULARITY, quantumBridge, 0, 80, 37, this.getInventoryPlayer() ) ).setStackLimit( 1 ) ); - - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + 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 f4abe674..ba133064 100644 --- a/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java +++ b/src/main/java/appeng/container/implementations/ContainerQuartzKnife.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.container.AEBaseContainer; import appeng.container.slot.QuartzKnifeOutput; @@ -36,210 +35,180 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; +public class ContainerQuartzKnife + extends AEBaseContainer implements IAEAppEngInventory, IInventory { + private final QuartzKnifeObj toolInv; -public class ContainerQuartzKnife extends AEBaseContainer implements IAEAppEngInventory, IInventory -{ + private final AppEngInternalInventory inSlot = new AppEngInternalInventory(this, 1); + private final SlotRestrictedInput metals; + private final QuartzKnifeOutput output; + private String myName = ""; - private final QuartzKnifeObj toolInv; + public ContainerQuartzKnife(final InventoryPlayer ip, final QuartzKnifeObj te) { + super(ip, null, null); + this.toolInv = te; - private final AppEngInternalInventory inSlot = new AppEngInternalInventory( this, 1 ); - private final SlotRestrictedInput metals; - private final QuartzKnifeOutput output; - private String myName = ""; + this.metals = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.METAL_INGOTS, this.inSlot, 0, 94, 44, ip + ); + this.addSlotToContainer(this.metals); - public ContainerQuartzKnife( final InventoryPlayer ip, final QuartzKnifeObj te ) - { - super( ip, null, null ); - this.toolInv = te; + this.output = new QuartzKnifeOutput(this, 0, 134, 44, -1); + this.addSlotToContainer(this.output); - this.metals = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.METAL_INGOTS, this.inSlot, 0, 94, 44, ip ); - this.addSlotToContainer( this.metals ); + this.lockPlayerInventorySlot(ip.currentItem); - this.output = new QuartzKnifeOutput( this, 0, 134, 44, -1 ); - this.addSlotToContainer( this.output ); + this.bindPlayerInventory(ip, 0, 184 - /* height of player inventory */ 82); + } - this.lockPlayerInventorySlot( ip.currentItem ); + public void setName(final String value) { + this.myName = value; + } - this.bindPlayerInventory( ip, 0, 184 - /* height of player inventory */82 ); - } + @Override + public void detectAndSendChanges() { + final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); - public void setName( final String value ) - { - this.myName = value; - } + if (currentItem != this.toolInv.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem(this.toolInv.getItemStack(), currentItem)) { + this.getPlayerInv().setInventorySlotContents( + this.getPlayerInv().currentItem, this.toolInv.getItemStack() + ); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } - @Override - public void detectAndSendChanges() - { - final ItemStack currentItem = this.getPlayerInv().getCurrentItem(); + super.detectAndSendChanges(); + } - if( currentItem != this.toolInv.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.toolInv.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.getPlayerInv().currentItem, this.toolInv.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } + @Override + public void onContainerClosed(final EntityPlayer par1EntityPlayer) { + if (this.inSlot.getStackInSlot(0) != null) { + par1EntityPlayer.dropPlayerItemWithRandomChoice( + this.inSlot.getStackInSlot(0), false + ); + } + } - super.detectAndSendChanges(); - } + @Override + public void saveChanges() {} - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - if( this.inSlot.getStackInSlot( 0 ) != null ) - { - par1EntityPlayer.dropPlayerItemWithRandomChoice( this.inSlot.getStackInSlot( 0 ), false ); - } - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) {} - @Override - public void saveChanges() - { + @Override + public int getSizeInventory() { + return 1; + } - } + @Override + public ItemStack getStackInSlot(final int var1) { + final ItemStack input = this.inSlot.getStackInSlot(0); + if (input == null) { + return null; + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { + if (SlotRestrictedInput.isMetalIngot(input)) { + if (this.myName.length() > 0) { + for (final ItemStack namePressStack : AEApi.instance() + .definitions() + .materials() + .namePress() + .maybeStack(1) + .asSet()) { + final NBTTagCompound compound = Platform.openNbtData(namePressStack); + compound.setString("InscribeName", this.myName); - } + return namePressStack; + } + } + } - @Override - public int getSizeInventory() - { - return 1; - } + return null; + } - @Override - public ItemStack getStackInSlot( final int var1 ) - { - final ItemStack input = this.inSlot.getStackInSlot( 0 ); - if( input == null ) - { - return null; - } + @Override + public ItemStack decrStackSize(final int var1, final int var2) { + final ItemStack is = this.getStackInSlot(0); + if (is != null) { + if (this.makePlate()) { + return is; + } + } + return null; + } - if( SlotRestrictedInput.isMetalIngot( input ) ) - { - if( this.myName.length() > 0 ) - { - for( final ItemStack namePressStack : AEApi.instance().definitions().materials().namePress().maybeStack( 1 ).asSet() ) - { - final NBTTagCompound compound = Platform.openNbtData( namePressStack ); - compound.setString( "InscribeName", this.myName ); + private boolean makePlate() { + if (this.inSlot.decrStackSize(0, 1) != null) { + final ItemStack item = this.toolInv.getItemStack(); + item.damageItem(1, this.getPlayerInv().player); - return namePressStack; - } - } - } + if (item.stackSize == 0) { + this.getPlayerInv().mainInventory[this.getPlayerInv().currentItem] = null; + MinecraftForge.EVENT_BUS.post( + new PlayerDestroyItemEvent(this.getPlayerInv().player, item) + ); + } - return null; - } + return true; + } + return false; + } - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - final ItemStack is = this.getStackInSlot( 0 ); - if( is != null ) - { - if( this.makePlate() ) - { - return is; - } - } - return null; - } + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } - private boolean makePlate() - { - if( this.inSlot.decrStackSize( 0, 1 ) != null ) - { - final ItemStack item = this.toolInv.getItemStack(); - item.damageItem( 1, this.getPlayerInv().player ); + @Override + public void setInventorySlotContents(final int var1, final ItemStack var2) { + if (var2 == null && Platform.isServer()) { + this.makePlate(); + } + } - if( item.stackSize == 0 ) - { - this.getPlayerInv().mainInventory[this.getPlayerInv().currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( this.getPlayerInv().player, item ) ); - } + @Override + public String getInventoryName() { + return "Quartz Knife Output"; + } - return true; - } - return false; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } + @Override + public int getInventoryStackLimit() { + return 1; + } - @Override - public void setInventorySlotContents( final int var1, final ItemStack var2 ) - { - if( var2 == null && Platform.isServer() ) - { - this.makePlate(); - } - } + @Override + public void markDirty() {} - @Override - public String getInventoryName() - { - return "Quartz Knife Output"; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return false; + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public void openInventory() {} - @Override - public int getInventoryStackLimit() - { - return 1; - } + @Override + public void closeInventory() {} - @Override - public void markDirty() - { - - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return false; - } - - @Override - public void openInventory() - { - - } - - @Override - public void closeInventory() - { - - } - - @Override - public boolean isItemValidForSlot( final int var1, final ItemStack var2 ) - { - return false; - } + @Override + public boolean isItemValidForSlot(final int var1, final 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 3c9aa485..885b8980 100644 --- a/src/main/java/appeng/container/implementations/ContainerSecurity.java +++ b/src/main/java/appeng/container/implementations/ContainerSecurity.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.features.INetworkEncodable; @@ -38,153 +37,162 @@ import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class ContainerSecurity + extends ContainerMEMonitorable implements IAEAppEngInventory { + private final SlotRestrictedInput configSlot; -public class ContainerSecurity extends ContainerMEMonitorable implements IAEAppEngInventory -{ + private final AppEngInternalInventory wirelessEncoder + = new AppEngInternalInventory(this, 2); - private final SlotRestrictedInput configSlot; + private final SlotRestrictedInput wirelessIn; + private final SlotOutput wirelessOut; - private final AppEngInternalInventory wirelessEncoder = new AppEngInternalInventory( this, 2 ); + private final TileSecurity securityBox; + @GuiSync(0) + public int permissionMode = 0; - private final SlotRestrictedInput wirelessIn; - private final SlotOutput wirelessOut; + public ContainerSecurity(final InventoryPlayer ip, final ITerminalHost monitorable) { + super(ip, monitorable, false); - private final TileSecurity securityBox; - @GuiSync( 0 ) - public int permissionMode = 0; + this.securityBox = (TileSecurity) monitorable; - public ContainerSecurity( final InventoryPlayer ip, final ITerminalHost monitorable ) - { - super( ip, monitorable, false ); + this.addSlotToContainer( + this.configSlot = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.BIOMETRIC_CARD, + this.securityBox.getConfigSlot(), + 0, + 37, + -33, + ip + ) + ); - this.securityBox = (TileSecurity) monitorable; + this.addSlotToContainer( + this.wirelessIn = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.ENCODABLE_ITEM, + this.wirelessEncoder, + 0, + 212, + 10, + ip + ) + ); + this.addSlotToContainer( + this.wirelessOut = new SlotOutput(this.wirelessEncoder, 1, 212, 68, -1) + ); - this.addSlotToContainer( this.configSlot = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.BIOMETRIC_CARD, this.securityBox.getConfigSlot(), 0, 37, -33, ip ) ); + this.bindPlayerInventory(ip, 0, 0); + } - this.addSlotToContainer( this.wirelessIn = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODABLE_ITEM, this.wirelessEncoder, 0, 212, 10, ip ) ); - this.addSlotToContainer( this.wirelessOut = new SlotOutput( this.wirelessEncoder, 1, 212, 68, -1 ) ); + public void toggleSetting(final String value, final EntityPlayer player) { + try { + final SecurityPermissions permission = SecurityPermissions.valueOf(value); - this.bindPlayerInventory( ip, 0, 0 ); - } + final ItemStack a = this.configSlot.getStack(); + if (a != null && a.getItem() instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) a.getItem(); + if (bc.hasPermission(a, permission)) { + bc.removePermission(a, permission); + } else { + bc.addPermission(a, permission); + } + } + } catch (final EnumConstantNotPresentException ex) { + // :( + } + } - public void toggleSetting( final String value, final EntityPlayer player ) - { - try - { - final SecurityPermissions permission = SecurityPermissions.valueOf( value ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.SECURITY, false); - final ItemStack a = this.configSlot.getStack(); - if( a != null && a.getItem() instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) a.getItem(); - if( bc.hasPermission( a, permission ) ) - { - bc.removePermission( a, permission ); - } - else - { - bc.addPermission( a, permission ); - } - } - } - catch( final EnumConstantNotPresentException ex ) - { - // :( - } - } + this.setPermissionMode(0); - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.SECURITY, false ); + final ItemStack a = this.configSlot.getStack(); + if (a != null && a.getItem() instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) a.getItem(); - this.setPermissionMode( 0 ); + for (final SecurityPermissions sp : bc.getPermissions(a)) { + this.setPermissionMode(this.getPermissionMode() | (1 << sp.ordinal())); + } + } - final ItemStack a = this.configSlot.getStack(); - if( a != null && a.getItem() instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) a.getItem(); + this.updatePowerStatus(); - for( final SecurityPermissions sp : bc.getPermissions( a ) ) - { - this.setPermissionMode( this.getPermissionMode() | ( 1 << sp.ordinal() ) ); - } - } + super.detectAndSendChanges(); + } - this.updatePowerStatus(); + @Override + public void onContainerClosed(final EntityPlayer player) { + super.onContainerClosed(player); - super.detectAndSendChanges(); - } + if (this.wirelessIn.getHasStack()) { + player.dropPlayerItemWithRandomChoice(this.wirelessIn.getStack(), false); + } - @Override - public void onContainerClosed( final EntityPlayer player ) - { - super.onContainerClosed( player ); + if (this.wirelessOut.getHasStack()) { + player.dropPlayerItemWithRandomChoice(this.wirelessOut.getStack(), false); + } + } - if( this.wirelessIn.getHasStack() ) - { - player.dropPlayerItemWithRandomChoice( this.wirelessIn.getStack(), false ); - } + @Override + public void saveChanges() { + // :P + } - if( this.wirelessOut.getHasStack() ) - { - player.dropPlayerItemWithRandomChoice( this.wirelessOut.getStack(), false ); - } - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) { + if (!this.wirelessOut.getHasStack()) { + if (this.wirelessIn.getHasStack()) { + final ItemStack term = this.wirelessIn.getStack().copy(); + INetworkEncodable networkEncodable = null; - @Override - public void saveChanges() - { - // :P - } + if (term.getItem() instanceof INetworkEncodable) { + networkEncodable = (INetworkEncodable) term.getItem(); + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( !this.wirelessOut.getHasStack() ) - { - if( this.wirelessIn.getHasStack() ) - { - final ItemStack term = this.wirelessIn.getStack().copy(); - INetworkEncodable networkEncodable = null; + final IWirelessTermHandler wTermHandler + = AEApi.instance().registries().wireless().getWirelessTerminalHandler( + term + ); + if (wTermHandler != null) { + networkEncodable = wTermHandler; + } - if( term.getItem() instanceof INetworkEncodable ) - { - networkEncodable = (INetworkEncodable) term.getItem(); - } + if (networkEncodable != null) { + networkEncodable.setEncryptionKey( + term, String.valueOf(this.securityBox.getSecurityKey()), "" + ); - final IWirelessTermHandler wTermHandler = AEApi.instance().registries().wireless().getWirelessTerminalHandler( term ); - if( wTermHandler != null ) - { - networkEncodable = wTermHandler; - } + this.wirelessIn.putStack(null); + this.wirelessOut.putStack(term); - if( networkEncodable != null ) - { - networkEncodable.setEncryptionKey( term, String.valueOf( this.securityBox.getSecurityKey() ), "" ); + // update the two slots in question... + for (final Object crafter : this.crafters) { + final ICrafting icrafting = (ICrafting) crafter; + icrafting.sendSlotContents( + this, this.wirelessIn.slotNumber, this.wirelessIn.getStack() + ); + icrafting.sendSlotContents( + this, this.wirelessOut.slotNumber, this.wirelessOut.getStack() + ); + } + } + } + } + } - this.wirelessIn.putStack( null ); - this.wirelessOut.putStack( term ); + public int getPermissionMode() { + return this.permissionMode; + } - // update the two slots in question... - for( final Object crafter : this.crafters ) - { - final ICrafting icrafting = (ICrafting) crafter; - icrafting.sendSlotContents( this, this.wirelessIn.slotNumber, this.wirelessIn.getStack() ); - icrafting.sendSlotContents( this, this.wirelessOut.slotNumber, this.wirelessOut.getStack() ); - } - } - } - } - } - - public int getPermissionMode() - { - return this.permissionMode; - } - - private void setPermissionMode( final int permissionMode ) - { - this.permissionMode = permissionMode; - } + private void setPermissionMode(final int permissionMode) { + this.permissionMode = permissionMode; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerSkyChest.java b/src/main/java/appeng/container/implementations/ContainerSkyChest.java index 6381b7c3..e2898d13 100644 --- a/src/main/java/appeng/container/implementations/ContainerSkyChest.java +++ b/src/main/java/appeng/container/implementations/ContainerSkyChest.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.slot.SlotNormal; import appeng.tile.storage.TileSkyChest; @@ -26,35 +25,30 @@ import invtweaks.api.container.ChestContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; - @ChestContainer -public class ContainerSkyChest extends AEBaseContainer -{ +public class ContainerSkyChest extends AEBaseContainer { + private final TileSkyChest chest; - private final TileSkyChest chest; + public ContainerSkyChest(final InventoryPlayer ip, final TileSkyChest chest) { + super(ip, chest, null); + this.chest = chest; - public ContainerSkyChest( final InventoryPlayer ip, final TileSkyChest chest ) - { - super( ip, chest, null ); - this.chest = chest; + for (int y = 0; y < 4; y++) { + for (int x = 0; x < 9; x++) { + this.addSlotToContainer( + new SlotNormal(this.chest, y * 9 + x, 8 + 18 * x, 24 + 18 * y) + ); + } + } - for( int y = 0; y < 4; y++ ) - { - for( int x = 0; x < 9; x++ ) - { - this.addSlotToContainer( new SlotNormal( this.chest, y * 9 + x, 8 + 18 * x, 24 + 18 * y ) ); - } - } + this.chest.openInventory(); - this.chest.openInventory(); + this.bindPlayerInventory(ip, 0, 195 - /* height of player inventory */ 82); + } - this.bindPlayerInventory( ip, 0, 195 - /* height of player inventory */82 ); - } - - @Override - public void onContainerClosed( final EntityPlayer par1EntityPlayer ) - { - super.onContainerClosed( par1EntityPlayer ); - this.chest.closeInventory(); - } + @Override + public void onContainerClosed(final 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 656b53f8..e4ba141d 100644 --- a/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java +++ b/src/main/java/appeng/container/implementations/ContainerSpatialIOPort.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.energy.IEnergyGrid; @@ -32,100 +31,98 @@ import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; import net.minecraftforge.common.util.ForgeDirection; +public class ContainerSpatialIOPort extends AEBaseContainer { + @GuiSync(0) + public long currentPower; + @GuiSync(1) + public long maxPower; + @GuiSync(2) + public long reqPower; + @GuiSync(3) + public long eff; + private IGrid network; + private int delay = 40; -public class ContainerSpatialIOPort extends AEBaseContainer -{ + public ContainerSpatialIOPort( + final InventoryPlayer ip, final TileSpatialIOPort spatialIOPort + ) { + super(ip, spatialIOPort, null); - @GuiSync( 0 ) - public long currentPower; - @GuiSync( 1 ) - public long maxPower; - @GuiSync( 2 ) - public long reqPower; - @GuiSync( 3 ) - public long eff; - private IGrid network; - private int delay = 40; + if (Platform.isServer()) { + this.network = spatialIOPort.getGridNode(ForgeDirection.UNKNOWN).getGrid(); + } - public ContainerSpatialIOPort( final InventoryPlayer ip, final TileSpatialIOPort spatialIOPort ) - { - super( ip, spatialIOPort, null ); + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS, + spatialIOPort, + 0, + 52, + 48, + this.getInventoryPlayer() + )); + this.addSlotToContainer(new SlotOutput( + spatialIOPort, + 1, + 113, + 48, + SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS.IIcon + )); - if( Platform.isServer() ) - { - this.network = spatialIOPort.getGridNode( ForgeDirection.UNKNOWN ).getGrid(); - } + this.bindPlayerInventory(ip, 0, 197 - /* height of player inventory */ 82); + } - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS, spatialIOPort, 0, 52, 48, this.getInventoryPlayer() ) ); - this.addSlotToContainer( new SlotOutput( spatialIOPort, 1, 113, 48, SlotRestrictedInput.PlacableItemType.SPATIAL_STORAGE_CELLS.IIcon ) ); + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - this.bindPlayerInventory( ip, 0, 197 - /* height of player inventory */82 ); - } + if (Platform.isServer()) { + this.delay++; + if (this.delay > 15 && this.network != null) { + this.delay = 0; - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + final IEnergyGrid eg = this.network.getCache(IEnergyGrid.class); + final ISpatialCache sc = this.network.getCache(ISpatialCache.class); + if (eg != null) { + this.setCurrentPower((long) (100.0 * eg.getStoredPower())); + this.setMaxPower((long) (100.0 * eg.getMaxStoredPower())); + this.setRequiredPower((long) (100.0 * sc.requiredPower())); + this.setEfficency((long) (100.0f * sc.currentEfficiency())); + } + } + } - if( Platform.isServer() ) - { - this.delay++; - if( this.delay > 15 && this.network != null ) - { - this.delay = 0; + super.detectAndSendChanges(); + } - final IEnergyGrid eg = this.network.getCache( IEnergyGrid.class ); - final ISpatialCache sc = this.network.getCache( ISpatialCache.class ); - if( eg != null ) - { - this.setCurrentPower( (long) ( 100.0 * eg.getStoredPower() ) ); - this.setMaxPower( (long) ( 100.0 * eg.getMaxStoredPower() ) ); - this.setRequiredPower( (long) ( 100.0 * sc.requiredPower() ) ); - this.setEfficency( (long) ( 100.0f * sc.currentEfficiency() ) ); - } - } - } + public long getCurrentPower() { + return this.currentPower; + } - super.detectAndSendChanges(); - } + private void setCurrentPower(final long currentPower) { + this.currentPower = currentPower; + } - public long getCurrentPower() - { - return this.currentPower; - } + public long getMaxPower() { + return this.maxPower; + } - private void setCurrentPower( final long currentPower ) - { - this.currentPower = currentPower; - } + private void setMaxPower(final long maxPower) { + this.maxPower = maxPower; + } - public long getMaxPower() - { - return this.maxPower; - } + public long getRequiredPower() { + return this.reqPower; + } - private void setMaxPower( final long maxPower ) - { - this.maxPower = maxPower; - } + private void setRequiredPower(final long reqPower) { + this.reqPower = reqPower; + } - public long getRequiredPower() - { - return this.reqPower; - } + public long getEfficency() { + return this.eff; + } - private void setRequiredPower( final long reqPower ) - { - this.reqPower = reqPower; - } - - public long getEfficency() - { - return this.eff; - } - - private void setEfficency( final long eff ) - { - this.eff = eff; - } + private void setEfficency(final long eff) { + this.eff = eff; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerStorageBus.java b/src/main/java/appeng/container/implementations/ContainerStorageBus.java index fc5df9f7..0f35a1b3 100644 --- a/src/main/java/appeng/container/implementations/ContainerStorageBus.java +++ b/src/main/java/appeng/container/implementations/ContainerStorageBus.java @@ -18,6 +18,7 @@ package appeng.container.implementations; +import java.util.Iterator; import appeng.api.AEApi; import appeng.api.config.*; @@ -35,154 +36,182 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public class ContainerStorageBus extends ContainerUpgradeable { + private final PartStorageBus storageBus; + @GuiSync(3) + public AccessRestriction rwMode = AccessRestriction.READ_WRITE; -public class ContainerStorageBus extends ContainerUpgradeable -{ + @GuiSync(4) + public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; - private final PartStorageBus storageBus; + public ContainerStorageBus(final InventoryPlayer ip, final PartStorageBus te) { + super(ip, te); + this.storageBus = te; + } - @GuiSync( 3 ) - public AccessRestriction rwMode = AccessRestriction.READ_WRITE; + @Override + protected int getHeight() { + return 251; + } - @GuiSync( 4 ) - public StorageFilter storageFilter = StorageFilter.EXTRACTABLE_ONLY; + @Override + protected void setupConfig() { + final int xo = 8; + final int yo = 23 + 6; - public ContainerStorageBus( final InventoryPlayer ip, final PartStorageBus te ) - { - super( ip, te ); - this.storageBus = te; - } + final IInventory config = this.getUpgradeable().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 + )); + } + } + } - @Override - protected int getHeight() - { - return 251; - } + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer() + )) + .setNotDraggable()); + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 4, + 187, + 8 + 18 * 4, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } - @Override - protected void setupConfig() - { - final int xo = 8; - final int yo = 23 + 6; + @Override + protected boolean supportCapacity() { + return true; + } - final IInventory config = this.getUpgradeable().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 ) ); - } - } - } + @Override + public int availableUpgrades() { + return 5; + } - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 4, 187, 8 + 18 * 4, this.getInventoryPlayer() ) ).setNotDraggable() ); - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - @Override - protected boolean supportCapacity() - { - return true; - } + if (Platform.isServer()) { + this.setFuzzyMode( + (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( + Settings.FUZZY_MODE + ) + ); + this.setReadWriteMode( + (AccessRestriction) this.getUpgradeable().getConfigManager().getSetting( + Settings.ACCESS + ) + ); + this.setStorageFilter( + (StorageFilter) this.getUpgradeable().getConfigManager().getSetting( + Settings.STORAGE_FILTER + ) + ); + } - @Override - public int availableUpgrades() - { - return 5; - } + this.standardDetectAndSendChanges(); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades + = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - if( Platform.isServer() ) - { - this.setFuzzyMode( (FuzzyMode) this.getUpgradeable().getConfigManager().getSetting( Settings.FUZZY_MODE ) ); - this.setReadWriteMode( (AccessRestriction) this.getUpgradeable().getConfigManager().getSetting( Settings.ACCESS ) ); - this.setStorageFilter( (StorageFilter) this.getUpgradeable().getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - } + return upgrades > idx; + } - this.standardDetectAndSendChanges(); - } + public void clear() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + for (int x = 0; x < inv.getSizeInventory(); x++) { + inv.setInventorySlotContents(x, null); + } + this.detectAndSendChanges(); + } - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + public void partition() { + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); - return upgrades > idx; - } + final IMEInventory cellInv = this.storageBus.getInternalHandler(); - public void clear() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - inv.setInventorySlotContents( x, null ); - } - this.detectAndSendChanges(); - } + Iterator i = new NullIterator(); + if (cellInv != null) { + final IItemList list + = cellInv.getAvailableItems(AEApi.instance().storage().createItemList()); + i = list.iterator(); + } - public void partition() - { - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); + for (int x = 0; x < inv.getSizeInventory(); x++) { + if (i.hasNext() && this.isSlotEnabled((x / 9) - 2)) { + final ItemStack g = i.next().getItemStack(); + g.stackSize = 1; + inv.setInventorySlotContents(x, g); + } else { + inv.setInventorySlotContents(x, null); + } + } - final IMEInventory cellInv = this.storageBus.getInternalHandler(); + this.detectAndSendChanges(); + } - Iterator i = new NullIterator(); - if( cellInv != null ) - { - final IItemList list = cellInv.getAvailableItems( AEApi.instance().storage().createItemList() ); - i = list.iterator(); - } + public AccessRestriction getReadWriteMode() { + return this.rwMode; + } - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - if( i.hasNext() && this.isSlotEnabled( ( x / 9 ) - 2 ) ) - { - final ItemStack g = i.next().getItemStack(); - g.stackSize = 1; - inv.setInventorySlotContents( x, g ); - } - else - { - inv.setInventorySlotContents( x, null ); - } - } + private void setReadWriteMode(final AccessRestriction rwMode) { + this.rwMode = rwMode; + } - this.detectAndSendChanges(); - } + public StorageFilter getStorageFilter() { + return this.storageFilter; + } - public AccessRestriction getReadWriteMode() - { - return this.rwMode; - } - - private void setReadWriteMode( final AccessRestriction rwMode ) - { - this.rwMode = rwMode; - } - - public StorageFilter getStorageFilter() - { - return this.storageFilter; - } - - private void setStorageFilter( final StorageFilter storageFilter ) - { - this.storageFilter = storageFilter; - } + private void setStorageFilter(final StorageFilter storageFilter) { + this.storageFilter = storageFilter; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java index 752c2515..52e8d9d3 100644 --- a/src/main/java/appeng/container/implementations/ContainerUpgradeable.java +++ b/src/main/java/appeng/container/implementations/ContainerUpgradeable.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.api.config.*; import appeng.api.implementations.IUpgradeableHost; import appeng.api.implementations.guiobjects.IGuiItem; @@ -37,269 +36,289 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSlotHost { + private 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; + @GuiSync(6) + public SchedulingMode schedulingMode = SchedulingMode.DEFAULT; + private int tbSlot; + private NetworkToolViewer tbInventory; -public class ContainerUpgradeable extends AEBaseContainer implements IOptionalSlotHost -{ + public ContainerUpgradeable(final InventoryPlayer ip, final IUpgradeableHost te) { + super( + ip, + (TileEntity) (te instanceof TileEntity ? te : null), + (IPart) (te instanceof IPart ? te : null) + ); + this.upgradeable = te; - private 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; - @GuiSync( 6 ) - public SchedulingMode schedulingMode = SchedulingMode.DEFAULT; - private int tbSlot; - private NetworkToolViewer tbInventory; + World w = null; + int xCoord = 0; + int yCoord = 0; + int zCoord = 0; - public ContainerUpgradeable( final InventoryPlayer ip, final IUpgradeableHost te ) - { - super( ip, (TileEntity) ( te instanceof TileEntity ? te : null ), (IPart) ( te instanceof IPart ? te : null ) ); - this.upgradeable = te; + if (te instanceof TileEntity) { + final TileEntity myTile = (TileEntity) te; + w = myTile.getWorldObj(); + xCoord = myTile.xCoord; + yCoord = myTile.yCoord; + zCoord = myTile.zCoord; + } - World w = null; - int xCoord = 0; - int yCoord = 0; - int zCoord = 0; + if (te instanceof IPart) { + final TileEntity mk = te.getTile(); + w = mk.getWorldObj(); + xCoord = mk.xCoord; + yCoord = mk.yCoord; + zCoord = mk.zCoord; + } - if( te instanceof TileEntity ) - { - final TileEntity myTile = (TileEntity) te; - w = myTile.getWorldObj(); - xCoord = myTile.xCoord; - yCoord = myTile.yCoord; - zCoord = myTile.zCoord; - } + final IInventory pi = this.getPlayerInv(); + for (int x = 0; x < pi.getSizeInventory(); x++) { + final ItemStack pii = pi.getStackInSlot(x); + if (pii != null && pii.getItem() instanceof ToolNetworkTool) { + this.lockPlayerInventorySlot(x); + this.tbSlot = x; + this.tbInventory = (NetworkToolViewer) ((IGuiItem) pii.getItem()) + .getGuiObject(pii, w, xCoord, yCoord, zCoord); + break; + } + } - if( te instanceof IPart ) - { - final TileEntity mk = te.getTile(); - w = mk.getWorldObj(); - xCoord = mk.xCoord; - yCoord = mk.yCoord; - zCoord = mk.zCoord; - } + 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.getInventoryPlayer() + )) + .setPlayerSide() + ); + } + } + } - final IInventory pi = this.getPlayerInv(); - for( int x = 0; x < pi.getSizeInventory(); x++ ) - { - final ItemStack pii = pi.getStackInSlot( x ); - if( pii != null && pii.getItem() instanceof ToolNetworkTool ) - { - this.lockPlayerInventorySlot( x ); - this.tbSlot = x; - this.tbInventory = (NetworkToolViewer) ( (IGuiItem) pii.getItem() ).getGuiObject( pii, w, xCoord, yCoord, zCoord ); - break; - } - } + this.setupConfig(); - 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.getInventoryPlayer() ) ).setPlayerSide() ); - } - } - } + this.bindPlayerInventory( + ip, 0, this.getHeight() - /* height of player inventory */ 82 + ); + } - this.setupConfig(); + public boolean hasToolbox() { + return this.tbInventory != null; + } - this.bindPlayerInventory( ip, 0, this.getHeight() - /* height of player inventory */82 ); - } + protected int getHeight() { + return 184; + } - public boolean hasToolbox() - { - return this.tbInventory != null; - } + protected void setupConfig() { + this.setupUpgrades(); - protected int getHeight() - { - return 184; - } + final IInventory inv = this.getUpgradeable().getInventoryByName("config"); + final int y = 40; + final int x = 80; + this.addSlotToContainer(new SlotFakeTypeOnly(inv, 0, x, y)); - protected void setupConfig() - { - this.setupUpgrades(); + 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) + ); + this.addSlotToContainer( + new OptionalSlotFakeTypeOnly(inv, this, 3, x, y, 0, -1, 1) + ); + this.addSlotToContainer( + new OptionalSlotFakeTypeOnly(inv, this, 4, x, y, 0, 1, 1) + ); - final IInventory inv = this.getUpgradeable().getInventoryByName( "config" ); - final int y = 40; - final int x = 80; - this.addSlotToContainer( new SlotFakeTypeOnly( inv, 0, x, y ) ); + this.addSlotToContainer( + new OptionalSlotFakeTypeOnly(inv, this, 5, x, y, -1, -1, 2) + ); + this.addSlotToContainer( + new OptionalSlotFakeTypeOnly(inv, this, 6, x, y, 1, -1, 2) + ); + this.addSlotToContainer( + new OptionalSlotFakeTypeOnly(inv, this, 7, x, y, -1, 1, 2) + ); + this.addSlotToContainer( + new OptionalSlotFakeTypeOnly(inv, this, 8, x, y, 1, 1, 2) + ); + } + } - 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 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 3, x, y, 0, -1, 1 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 4, x, y, 0, 1, 1 ) ); + protected void setupUpgrades() { + final IInventory upgrades = this.getUpgradeable().getInventoryByName("upgrades"); + if (this.availableUpgrades() > 0) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 0, + 187, + 8, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } + if (this.availableUpgrades() > 1) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 1, + 187, + 8 + 18, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } + if (this.availableUpgrades() > 2) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 2, + 187, + 8 + 18 * 2, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } + if (this.availableUpgrades() > 3) { + this.addSlotToContainer((new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.UPGRADES, + upgrades, + 3, + 187, + 8 + 18 * 3, + this.getInventoryPlayer() + )) + .setNotDraggable()); + } + } - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 5, x, y, -1, -1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 6, x, y, 1, -1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 7, x, y, -1, 1, 2 ) ); - this.addSlotToContainer( new OptionalSlotFakeTypeOnly( inv, this, 8, x, y, 1, 1, 2 ) ); - } - } + protected boolean supportCapacity() { + return true; + } - protected void setupUpgrades() - { - final IInventory upgrades = this.getUpgradeable().getInventoryByName( "upgrades" ); - if( this.availableUpgrades() > 0 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 0, 187, 8, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 1 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 1, 187, 8 + 18, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 2 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 2, 187, 8 + 18 * 2, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - if( this.availableUpgrades() > 3 ) - { - this.addSlotToContainer( ( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.UPGRADES, upgrades, 3, 187, 8 + 18 * 3, this.getInventoryPlayer() ) ).setNotDraggable() ); - } - } + public int availableUpgrades() { + return 4; + } - protected boolean supportCapacity() - { - return true; - } + @Override + public void detectAndSendChanges() { + this.verifyPermissions(SecurityPermissions.BUILD, false); - public int availableUpgrades() - { - return 4; - } + if (Platform.isServer()) { + final IConfigManager cm = this.getUpgradeable().getConfigManager(); + this.loadSettingsFromHost(cm); + } - @Override - public void detectAndSendChanges() - { - this.verifyPermissions( SecurityPermissions.BUILD, false ); + this.checkToolbox(); - if( Platform.isServer() ) - { - final IConfigManager cm = this.getUpgradeable().getConfigManager(); - this.loadSettingsFromHost( cm ); - } + for (final Object o : this.inventorySlots) { + if (o instanceof OptionalSlotFake) { + final OptionalSlotFake fs = (OptionalSlotFake) o; + if (!fs.isEnabled() && fs.getDisplayStack() != null) { + fs.clearStack(); + } + } + } - this.checkToolbox(); + this.standardDetectAndSendChanges(); + } - for( final Object o : this.inventorySlots ) - { - if( o instanceof OptionalSlotFake ) - { - final OptionalSlotFake fs = (OptionalSlotFake) o; - if( !fs.isEnabled() && fs.getDisplayStack() != null ) - { - fs.clearStack(); - } - } - } + protected void loadSettingsFromHost(final IConfigManager cm) { + this.setFuzzyMode((FuzzyMode) cm.getSetting(Settings.FUZZY_MODE)); + this.setRedStoneMode((RedstoneMode) cm.getSetting(Settings.REDSTONE_CONTROLLED)); + if (this.getUpgradeable() instanceof PartExportBus) { + this.setCraftingMode((YesNo) cm.getSetting(Settings.CRAFT_ONLY)); + this.setSchedulingMode((SchedulingMode) cm.getSetting(Settings.SCHEDULING_MODE + )); + } + } - this.standardDetectAndSendChanges(); - } + private void checkToolbox() { + if (this.hasToolbox()) { + final ItemStack currentItem = this.getPlayerInv().getStackInSlot(this.tbSlot); - protected void loadSettingsFromHost( final IConfigManager cm ) - { - this.setFuzzyMode( (FuzzyMode) cm.getSetting( Settings.FUZZY_MODE ) ); - this.setRedStoneMode( (RedstoneMode) cm.getSetting( Settings.REDSTONE_CONTROLLED ) ); - if( this.getUpgradeable() instanceof PartExportBus ) - { - this.setCraftingMode( (YesNo) cm.getSetting( Settings.CRAFT_ONLY ) ); - this.setSchedulingMode( (SchedulingMode) cm.getSetting( Settings.SCHEDULING_MODE ) ); - } - } + if (currentItem != this.tbInventory.getItemStack()) { + if (currentItem != null) { + if (Platform.isSameItem( + this.tbInventory.getItemStack(), currentItem + )) { + this.getPlayerInv().setInventorySlotContents( + this.tbSlot, this.tbInventory.getItemStack() + ); + } else { + this.setValidContainer(false); + } + } else { + this.setValidContainer(false); + } + } + } + } - private void checkToolbox() - { - if( this.hasToolbox() ) - { - final ItemStack currentItem = this.getPlayerInv().getStackInSlot( this.tbSlot ); + protected void standardDetectAndSendChanges() { + super.detectAndSendChanges(); + } - if( currentItem != this.tbInventory.getItemStack() ) - { - if( currentItem != null ) - { - if( Platform.isSameItem( this.tbInventory.getItemStack(), currentItem ) ) - { - this.getPlayerInv().setInventorySlotContents( this.tbSlot, this.tbInventory.getItemStack() ); - } - else - { - this.setValidContainer( false ); - } - } - else - { - this.setValidContainer( false ); - } - } - } - } + @Override + public boolean isSlotEnabled(final int idx) { + final int upgrades + = this.getUpgradeable().getInstalledUpgrades(Upgrades.CAPACITY); - protected void standardDetectAndSendChanges() - { - super.detectAndSendChanges(); - } + if (idx == 1 && upgrades > 0) { + return true; + } + return idx == 2 && upgrades > 1; + } - @Override - public boolean isSlotEnabled( final int idx ) - { - final int upgrades = this.getUpgradeable().getInstalledUpgrades( Upgrades.CAPACITY ); + public FuzzyMode getFuzzyMode() { + return this.fzMode; + } - if( idx == 1 && upgrades > 0 ) - { - return true; - } - return idx == 2 && upgrades > 1; + void setFuzzyMode(final FuzzyMode fzMode) { + this.fzMode = fzMode; + } - } + public YesNo getCraftingMode() { + return this.cMode; + } - public FuzzyMode getFuzzyMode() - { - return this.fzMode; - } + public void setCraftingMode(final YesNo cMode) { + this.cMode = cMode; + } - void setFuzzyMode( final FuzzyMode fzMode ) - { - this.fzMode = fzMode; - } + public RedstoneMode getRedStoneMode() { + return this.rsMode; + } - public YesNo getCraftingMode() - { - return this.cMode; - } + void setRedStoneMode(final RedstoneMode rsMode) { + this.rsMode = rsMode; + } - public void setCraftingMode( final YesNo cMode ) - { - this.cMode = cMode; - } + public SchedulingMode getSchedulingMode() { + return this.schedulingMode; + } - public RedstoneMode getRedStoneMode() - { - return this.rsMode; - } + private void setSchedulingMode(final SchedulingMode schedulingMode) { + this.schedulingMode = schedulingMode; + } - void setRedStoneMode( final RedstoneMode rsMode ) - { - this.rsMode = rsMode; - } - - public SchedulingMode getSchedulingMode() - { - return this.schedulingMode; - } - - private void setSchedulingMode( final SchedulingMode schedulingMode ) - { - this.schedulingMode = schedulingMode; - } - - IUpgradeableHost getUpgradeable() - { - return this.upgradeable; - } + IUpgradeableHost getUpgradeable() { + return this.upgradeable; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java index f1cd5a14..96cdcd84 100644 --- a/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java +++ b/src/main/java/appeng/container/implementations/ContainerVibrationChamber.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.container.interfaces.IProgressProvider; @@ -27,54 +26,59 @@ import appeng.tile.misc.TileVibrationChamber; import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerVibrationChamber + extends AEBaseContainer implements IProgressProvider { + private static final int MAX_BURN_TIME = 200; + private final int aePerTick = 5; + private final TileVibrationChamber vibrationChamber; + @GuiSync(0) + public int burnProgress = 0; + @GuiSync(1) + public int burnSpeed = 100; -public class ContainerVibrationChamber extends AEBaseContainer implements IProgressProvider -{ + public ContainerVibrationChamber( + final InventoryPlayer ip, final TileVibrationChamber vibrationChamber + ) { + super(ip, vibrationChamber, null); + this.vibrationChamber = vibrationChamber; - private static final int MAX_BURN_TIME = 200; - private final int aePerTick = 5; - private final TileVibrationChamber vibrationChamber; - @GuiSync( 0 ) - public int burnProgress = 0; - @GuiSync( 1 ) - public int burnSpeed = 100; + this.addSlotToContainer(new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.FUEL, + vibrationChamber, + 0, + 80, + 37, + this.getInventoryPlayer() + )); - public ContainerVibrationChamber( final InventoryPlayer ip, final TileVibrationChamber vibrationChamber ) - { - super( ip, vibrationChamber, null ); - this.vibrationChamber = vibrationChamber; + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } - this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.FUEL, vibrationChamber, 0, 80, 37, this.getInventoryPlayer() ) ); + @Override + public void detectAndSendChanges() { + if (Platform.isServer()) { + this.burnProgress = (int + ) (this.vibrationChamber.getMaxBurnTime() <= 0 + ? 0 + : 12 * this.vibrationChamber.getBurnTime() + / this.vibrationChamber.getMaxBurnTime()); + this.burnSpeed = this.vibrationChamber.getBurnSpeed(); + } - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + super.detectAndSendChanges(); + } - @Override - public void detectAndSendChanges() - { - if( Platform.isServer() ) - { - this.burnProgress = (int) ( this.vibrationChamber.getMaxBurnTime() <= 0 ? 0 : 12 * this.vibrationChamber.getBurnTime() / this.vibrationChamber.getMaxBurnTime() ); - this.burnSpeed = this.vibrationChamber.getBurnSpeed(); - } + @Override + public int getCurrentProgress() { + return this.burnProgress > 0 ? this.burnSpeed : 0; + } - super.detectAndSendChanges(); - } + @Override + public int getMaxProgress() { + return MAX_BURN_TIME; + } - @Override - public int getCurrentProgress() - { - return this.burnProgress > 0 ? this.burnSpeed : 0; - } - - @Override - public int getMaxProgress() - { - return MAX_BURN_TIME; - } - - public int getAePerTick() - { - return this.aePerTick; - } + public int getAePerTick() { + return this.aePerTick; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerWireless.java b/src/main/java/appeng/container/implementations/ContainerWireless.java index 840f1ce1..4ae44fe1 100644 --- a/src/main/java/appeng/container/implementations/ContainerWireless.java +++ b/src/main/java/appeng/container/implementations/ContainerWireless.java @@ -18,7 +18,6 @@ package appeng.container.implementations; - import appeng.container.AEBaseContainer; import appeng.container.guisync.GuiSync; import appeng.container.slot.SlotRestrictedInput; @@ -26,55 +25,57 @@ import appeng.core.AEConfig; import appeng.tile.networking.TileWireless; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerWireless extends AEBaseContainer { + private final TileWireless wirelessTerminal; + private final SlotRestrictedInput boosterSlot; + @GuiSync(1) + public long range = 0; + @GuiSync(2) + public long drain = 0; -public class ContainerWireless extends AEBaseContainer -{ + public ContainerWireless(final InventoryPlayer ip, final TileWireless te) { + super(ip, te, null); + this.wirelessTerminal = te; - private final TileWireless wirelessTerminal; - private final SlotRestrictedInput boosterSlot; - @GuiSync( 1 ) - public long range = 0; - @GuiSync( 2 ) - public long drain = 0; + this.addSlotToContainer( + this.boosterSlot = new SlotRestrictedInput( + SlotRestrictedInput.PlacableItemType.RANGE_BOOSTER, + this.wirelessTerminal, + 0, + 80, + 47, + this.getInventoryPlayer() + ) + ); - public ContainerWireless( final InventoryPlayer ip, final TileWireless te ) - { - super( ip, te, null ); - this.wirelessTerminal = te; + this.bindPlayerInventory(ip, 0, 166 - /* height of player inventory */ 82); + } - this.addSlotToContainer( this.boosterSlot = new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.RANGE_BOOSTER, this.wirelessTerminal, 0, 80, 47, this.getInventoryPlayer() ) ); + @Override + public void detectAndSendChanges() { + final int boosters = this.boosterSlot.getStack() == null + ? 0 + : this.boosterSlot.getStack().stackSize; - this.bindPlayerInventory( ip, 0, 166 - /* height of player inventory */82 ); - } + this.setRange((long) (10 * AEConfig.instance.wireless_getMaxRange(boosters))); + this.setDrain((long) (100 * AEConfig.instance.wireless_getPowerDrain(boosters))); - @Override - public void detectAndSendChanges() - { - final int boosters = this.boosterSlot.getStack() == null ? 0 : this.boosterSlot.getStack().stackSize; + super.detectAndSendChanges(); + } - this.setRange( (long) ( 10 * AEConfig.instance.wireless_getMaxRange( boosters ) ) ); - this.setDrain( (long) ( 100 * AEConfig.instance.wireless_getPowerDrain( boosters ) ) ); + public long getRange() { + return this.range; + } - super.detectAndSendChanges(); - } + private void setRange(final long range) { + this.range = range; + } - public long getRange() - { - return this.range; - } + public long getDrain() { + return this.drain; + } - private void setRange( final long range ) - { - this.range = range; - } - - public long getDrain() - { - return this.drain; - } - - private void setDrain( final long drain ) - { - this.drain = drain; - } + private void setDrain(final long drain) { + this.drain = drain; + } } diff --git a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java index e545295c..d377884f 100644 --- a/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java +++ b/src/main/java/appeng/container/implementations/ContainerWirelessTerm.java @@ -18,42 +18,37 @@ package appeng.container.implementations; - import appeng.core.AEConfig; import appeng.core.localization.PlayerMessages; import appeng.helpers.WirelessTerminalGuiObject; import appeng.util.Platform; import net.minecraft.entity.player.InventoryPlayer; +public class ContainerWirelessTerm extends ContainerMEPortableCell { + private final WirelessTerminalGuiObject wirelessTerminalGUIObject; -public class ContainerWirelessTerm extends ContainerMEPortableCell -{ + public ContainerWirelessTerm( + final InventoryPlayer ip, final WirelessTerminalGuiObject gui + ) { + super(ip, gui); + this.wirelessTerminalGUIObject = gui; + } - private final WirelessTerminalGuiObject wirelessTerminalGUIObject; + @Override + public void detectAndSendChanges() { + super.detectAndSendChanges(); - public ContainerWirelessTerm( final InventoryPlayer ip, final WirelessTerminalGuiObject gui ) - { - super( ip, gui ); - this.wirelessTerminalGUIObject = gui; - } + if (!this.wirelessTerminalGUIObject.rangeCheck()) { + if (Platform.isServer() && this.isValidContainer()) { + this.getPlayerInv().player.addChatMessage(PlayerMessages.OutOfRange.get() + ); + } - @Override - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - - if( !this.wirelessTerminalGUIObject.rangeCheck() ) - { - if( Platform.isServer() && this.isValidContainer() ) - { - this.getPlayerInv().player.addChatMessage( PlayerMessages.OutOfRange.get() ); - } - - this.setValidContainer( false ); - } - else - { - this.setPowerMultiplier( AEConfig.instance.wireless_getDrainRate( this.wirelessTerminalGUIObject.getRange() ) ); - } - } + this.setValidContainer(false); + } else { + this.setPowerMultiplier(AEConfig.instance.wireless_getDrainRate( + this.wirelessTerminalGUIObject.getRange() + )); + } + } } diff --git a/src/main/java/appeng/container/implementations/CraftingCPURecord.java b/src/main/java/appeng/container/implementations/CraftingCPURecord.java index 2e284491..659bed70 100644 --- a/src/main/java/appeng/container/implementations/CraftingCPURecord.java +++ b/src/main/java/appeng/container/implementations/CraftingCPURecord.java @@ -18,57 +18,48 @@ package appeng.container.implementations; +import javax.annotation.Nonnull; import appeng.api.networking.crafting.ICraftingCPU; import appeng.util.ItemSorters; -import javax.annotation.Nonnull; +public class CraftingCPURecord implements Comparable { + private final String myName; + private final ICraftingCPU cpu; + private final long size; + private final int processors; + public CraftingCPURecord( + final long size, final int coProcessors, final ICraftingCPU server + ) { + this.size = size; + this.processors = coProcessors; + this.cpu = server; + this.myName = server.getName(); + } -public class CraftingCPURecord implements Comparable -{ + @Override + public int compareTo(@Nonnull final CraftingCPURecord o) { + final int a = ItemSorters.compareLong(o.getProcessors(), this.getProcessors()); + if (a != 0) { + return a; + } + return ItemSorters.compareLong(o.getSize(), this.getSize()); + } - private final String myName; - private final ICraftingCPU cpu; - private final long size; - private final int processors; + ICraftingCPU getCpu() { + return this.cpu; + } - public CraftingCPURecord( final long size, final int coProcessors, final ICraftingCPU server ) - { - this.size = size; - this.processors = coProcessors; - this.cpu = server; - this.myName = server.getName(); - } + String getName() { + return this.myName; + } - @Override - public int compareTo( @Nonnull final CraftingCPURecord o ) - { - final int a = ItemSorters.compareLong( o.getProcessors(), this.getProcessors() ); - if( a != 0 ) - { - return a; - } - return ItemSorters.compareLong( o.getSize(), this.getSize() ); - } + int getProcessors() { + return this.processors; + } - ICraftingCPU getCpu() - { - return this.cpu; - } - - String getName() - { - return this.myName; - } - - int getProcessors() - { - return this.processors; - } - - long getSize() - { - return this.size; - } + long getSize() { + return this.size; + } } \ No newline at end of file diff --git a/src/main/java/appeng/container/interfaces/IInventorySlotAware.java b/src/main/java/appeng/container/interfaces/IInventorySlotAware.java index 68b65b4a..be9f4bfb 100644 --- a/src/main/java/appeng/container/interfaces/IInventorySlotAware.java +++ b/src/main/java/appeng/container/interfaces/IInventorySlotAware.java @@ -1,36 +1,34 @@ -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - -package appeng.container.interfaces; - - -/** - * Any item providing a GUI and depending on an exact inventory slot. - *

- * This interface is likely a volatile one until a general GUI refactoring occurred. - * Use it with care and expect changes. - */ -public interface IInventorySlotAware -{ - /** - * This is needed to select the correct slot index. - * - * @return the inventory index of this portable cell. - */ - int getInventorySlot(); -} +/* + * This file is part of Applied Energistics 2. + * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. + * + * Applied Energistics 2 is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Applied Energistics 2 is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Applied Energistics 2. If not, see . + */ + +package appeng.container.interfaces; + +/** + * Any item providing a GUI and depending on an exact inventory slot. + *

+ * This interface is likely a volatile one until a general GUI refactoring occurred. + * Use it with care and expect changes. + */ +public interface IInventorySlotAware { + /** + * This is needed to select the correct slot index. + * + * @return the inventory index of this portable cell. + */ + int getInventorySlot(); +} diff --git a/src/main/java/appeng/container/interfaces/IProgressProvider.java b/src/main/java/appeng/container/interfaces/IProgressProvider.java index 90171c1b..88c898e2 100644 --- a/src/main/java/appeng/container/interfaces/IProgressProvider.java +++ b/src/main/java/appeng/container/interfaces/IProgressProvider.java @@ -1,50 +1,47 @@ -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - -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 -{ - - /** - * The current value of the progress. It should cover a range from 0 to the max progress - * - * @return An int representing the current progress - */ - int getCurrentProgress(); - - /** - * The max value the progress. - *

- * It is not limited to a value of 100 and can be scaled to fit the current needs. For example scaled down to - * decrease or scaled up to increase the precision. - * - * @return An int representing the max progress - */ - int getMaxProgress(); -} +/* + * This file is part of Applied Energistics 2. + * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. + * + * Applied Energistics 2 is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Applied Energistics 2 is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Applied Energistics 2. If not, see . + */ + +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 { + /** + * The current value of the progress. It should cover a range from 0 to the max + * progress + * + * @return An int representing the current progress + */ + int getCurrentProgress(); + + /** + * The max value the progress. + *

+ * It is not limited to a value of 100 and can be scaled to fit the current needs. For + * example scaled down to decrease or scaled up to increase the precision. + * + * @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 527d0953..0626ad8d 100644 --- a/src/main/java/appeng/container/slot/AppEngCraftingSlot.java +++ b/src/main/java/appeng/container/slot/AppEngCraftingSlot.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import cpw.mods.fml.common.FMLCommonHandler; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; @@ -29,164 +28,163 @@ import net.minecraft.stats.AchievementList; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; +public class AppEngCraftingSlot extends AppEngSlot { + /** + * The craft matrix inventory linked to this result slot. + */ + private final IInventory craftMatrix; -public class AppEngCraftingSlot extends AppEngSlot -{ + /** + * The player that is using the GUI where this slot resides. + */ + private final EntityPlayer thePlayer; - /** - * The craft matrix inventory linked to this result slot. - */ - private final IInventory craftMatrix; + /** + * The number of items that have been crafted so far. Gets passed to + * ItemStack.onCrafting before being reset. + */ + private int amountCrafted; - /** - * The player that is using the GUI where this slot resides. - */ - private final EntityPlayer thePlayer; + public AppEngCraftingSlot( + final EntityPlayer par1EntityPlayer, + final IInventory par2IInventory, + final IInventory par3IInventory, + final int par4, + final int par5, + final int par6 + ) { + super(par3IInventory, par4, par5, par6); + this.thePlayer = par1EntityPlayer; + this.craftMatrix = par2IInventory; + } - /** - * The number of items that have been crafted so far. Gets passed to ItemStack.onCrafting before being reset. - */ - private int amountCrafted; + /** + * Check if the stack is a valid item for this slot. Always true beside for the armor + * slots. + */ + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - public AppEngCraftingSlot( final EntityPlayer par1EntityPlayer, final IInventory par2IInventory, final IInventory par3IInventory, final int par4, final int par5, final int par6 ) - { - super( par3IInventory, par4, par5, par6 ); - this.thePlayer = par1EntityPlayer; - this.craftMatrix = par2IInventory; - } + /** + * 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(final ItemStack par1ItemStack, final int par2) { + this.amountCrafted += par2; + this.onCrafting(par1ItemStack); + } - /** - * Check if the stack is a valid item for this slot. Always true beside for the armor slots. - */ - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + /** + * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and + * wood. + */ + @Override + protected void onCrafting(final ItemStack par1ItemStack) { + par1ItemStack.onCrafting( + this.thePlayer.worldObj, this.thePlayer, this.amountCrafted + ); + this.amountCrafted = 0; - /** - * 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( final ItemStack par1ItemStack, final int par2 ) - { - this.amountCrafted += par2; - this.onCrafting( par1ItemStack ); - } + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.crafting_table)) { + this.thePlayer.addStat(AchievementList.buildWorkBench, 1); + } - /** - * the itemStack passed in is the output - ie, iron ingots, and pickaxes, not ore and wood. - */ - @Override - protected void onCrafting( final ItemStack par1ItemStack ) - { - par1ItemStack.onCrafting( this.thePlayer.worldObj, this.thePlayer, this.amountCrafted ); - this.amountCrafted = 0; + if (par1ItemStack.getItem() instanceof ItemPickaxe) { + this.thePlayer.addStat(AchievementList.buildPickaxe, 1); + } - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.crafting_table ) ) - { - this.thePlayer.addStat( AchievementList.buildWorkBench, 1 ); - } + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.furnace)) { + this.thePlayer.addStat(AchievementList.buildFurnace, 1); + } - if( par1ItemStack.getItem() instanceof ItemPickaxe ) - { - this.thePlayer.addStat( AchievementList.buildPickaxe, 1 ); - } + if (par1ItemStack.getItem() instanceof ItemHoe) { + this.thePlayer.addStat(AchievementList.buildHoe, 1); + } - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.furnace ) ) - { - this.thePlayer.addStat( AchievementList.buildFurnace, 1 ); - } + if (par1ItemStack.getItem() == Items.bread) { + this.thePlayer.addStat(AchievementList.makeBread, 1); + } - if( par1ItemStack.getItem() instanceof ItemHoe ) - { - this.thePlayer.addStat( AchievementList.buildHoe, 1 ); - } + if (par1ItemStack.getItem() == Items.cake) { + this.thePlayer.addStat(AchievementList.bakeCake, 1); + } - if( par1ItemStack.getItem() == Items.bread ) - { - this.thePlayer.addStat( AchievementList.makeBread, 1 ); - } + if (par1ItemStack.getItem() instanceof ItemPickaxe + && ((ItemTool) par1ItemStack.getItem()).func_150913_i() + != Item.ToolMaterial.WOOD) { + this.thePlayer.addStat(AchievementList.buildBetterPickaxe, 1); + } - if( par1ItemStack.getItem() == Items.cake ) - { - this.thePlayer.addStat( AchievementList.bakeCake, 1 ); - } + if (par1ItemStack.getItem() instanceof ItemSword) { + this.thePlayer.addStat(AchievementList.buildSword, 1); + } - if( par1ItemStack.getItem() instanceof ItemPickaxe && ( (ItemTool) par1ItemStack.getItem() ).func_150913_i() != Item.ToolMaterial.WOOD ) - { - this.thePlayer.addStat( AchievementList.buildBetterPickaxe, 1 ); - } + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.enchanting_table)) { + this.thePlayer.addStat(AchievementList.enchantments, 1); + } - if( par1ItemStack.getItem() instanceof ItemSword ) - { - this.thePlayer.addStat( AchievementList.buildSword, 1 ); - } + if (par1ItemStack.getItem() == Item.getItemFromBlock(Blocks.bookshelf)) { + this.thePlayer.addStat(AchievementList.bookcase, 1); + } + } - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.enchanting_table ) ) - { - this.thePlayer.addStat( AchievementList.enchantments, 1 ); - } + @Override + public void + onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { + FMLCommonHandler.instance().firePlayerCraftingEvent( + par1EntityPlayer, par2ItemStack, this.craftMatrix + ); + this.onCrafting(par2ItemStack); - if( par1ItemStack.getItem() == Item.getItemFromBlock( Blocks.bookshelf ) ) - { - this.thePlayer.addStat( AchievementList.bookcase, 1 ); - } - } + for (int i = 0; i < this.craftMatrix.getSizeInventory(); ++i) { + final ItemStack itemstack1 = this.craftMatrix.getStackInSlot(i); - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - FMLCommonHandler.instance().firePlayerCraftingEvent( par1EntityPlayer, par2ItemStack, this.craftMatrix ); - this.onCrafting( par2ItemStack ); + if (itemstack1 != null) { + this.craftMatrix.decrStackSize(i, 1); - for( int i = 0; i < this.craftMatrix.getSizeInventory(); ++i ) - { - final ItemStack itemstack1 = this.craftMatrix.getStackInSlot( i ); + if (itemstack1.getItem().hasContainerItem(itemstack1)) { + final ItemStack itemstack2 + = itemstack1.getItem().getContainerItem(itemstack1); - if( itemstack1 != null ) - { - this.craftMatrix.decrStackSize( i, 1 ); + if (itemstack2 != null && itemstack2.isItemStackDamageable() + && itemstack2.getItemDamage() > itemstack2.getMaxDamage()) { + MinecraftForge.EVENT_BUS.post( + new PlayerDestroyItemEvent(this.thePlayer, itemstack2) + ); + continue; + } - if( itemstack1.getItem().hasContainerItem( itemstack1 ) ) - { - final ItemStack itemstack2 = itemstack1.getItem().getContainerItem( itemstack1 ); + if (!itemstack1.getItem().doesContainerItemLeaveCraftingGrid( + itemstack1 + ) + || !this.thePlayer.inventory.addItemStackToInventory(itemstack2 + )) { + if (this.craftMatrix.getStackInSlot(i) == null) { + this.craftMatrix.setInventorySlotContents(i, itemstack2); + } else { + this.thePlayer.dropPlayerItemWithRandomChoice( + itemstack2, false + ); + } + } + } + } + } + } - if( itemstack2 != null && itemstack2.isItemStackDamageable() && itemstack2.getItemDamage() > itemstack2.getMaxDamage() ) - { - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( this.thePlayer, itemstack2 ) ); - continue; - } + /** + * 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(final int par1) { + if (this.getHasStack()) { + this.amountCrafted += Math.min(par1, this.getStack().stackSize); + } - if( !itemstack1.getItem().doesContainerItemLeaveCraftingGrid( itemstack1 ) || !this.thePlayer.inventory.addItemStackToInventory( itemstack2 ) ) - { - if( this.craftMatrix.getStackInSlot( i ) == null ) - { - this.craftMatrix.setInventorySlotContents( i, itemstack2 ); - } - else - { - this.thePlayer.dropPlayerItemWithRandomChoice( itemstack2, 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( final int par1 ) - { - if( this.getHasStack() ) - { - this.amountCrafted += Math.min( par1, this.getStack().stackSize ); - } - - return super.decrStackSize( par1 ); - } + 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 5b950108..7eb101c0 100644 --- a/src/main/java/appeng/container/slot/AppEngSlot.java +++ b/src/main/java/appeng/container/slot/AppEngSlot.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import appeng.container.AEBaseContainer; import appeng.tile.inventory.AppEngInternalInventory; import net.minecraft.entity.player.EntityPlayer; @@ -26,227 +25,180 @@ import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +public class AppEngSlot extends Slot { + private final int defX; + private final int defY; + private boolean isDraggable = true; + private boolean isPlayerSide = false; + private AEBaseContainer myContainer = null; + private int IIcon = -1; + private hasCalculatedValidness isValid; + private boolean isDisplay = false; -public class AppEngSlot extends Slot -{ + public AppEngSlot(final IInventory inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + this.defX = x; + this.defY = y; + this.setIsValid(hasCalculatedValidness.NotAvailable); + } - private final int defX; - private final int defY; - private boolean isDraggable = true; - private boolean isPlayerSide = false; - private AEBaseContainer myContainer = null; - private int IIcon = -1; - private hasCalculatedValidness isValid; - private boolean isDisplay = false; + public Slot setNotDraggable() { + this.setDraggable(false); + return this; + } - public AppEngSlot( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - this.defX = x; - this.defY = y; - this.setIsValid( hasCalculatedValidness.NotAvailable ); - } + public Slot setPlayerSide() { + this.isPlayerSide = true; + return this; + } - public Slot setNotDraggable() - { - this.setDraggable( false ); - return this; - } + public String getTooltip() { + return null; + } - public Slot setPlayerSide() - { - this.isPlayerSide = true; - return this; - } + public void clearStack() { + super.putStack(null); + } - public String getTooltip() - { - return null; - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + if (this.isEnabled()) { + return super.isItemValid(par1ItemStack); + } + return false; + } - public void clearStack() - { - super.putStack( null ); - } + @Override + public ItemStack getStack() { + if (!this.isEnabled()) { + return null; + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - if( this.isEnabled() ) - { - return super.isItemValid( par1ItemStack ); - } - return false; - } + if (this.inventory.getSizeInventory() <= this.getSlotIndex()) { + return null; + } - @Override - public ItemStack getStack() - { - if( !this.isEnabled() ) - { - return null; - } + if (this.isDisplay()) { + this.setDisplay(false); + return this.getDisplayStack(); + } + return super.getStack(); + } - if( this.inventory.getSizeInventory() <= this.getSlotIndex() ) - { - return null; - } + @Override + public void putStack(final ItemStack par1ItemStack) { + if (this.isEnabled()) { + super.putStack(par1ItemStack); - if( this.isDisplay() ) - { - this.setDisplay( false ); - return this.getDisplayStack(); - } - return super.getStack(); - } + if (this.getContainer() != null) { + this.getContainer().onSlotChange(this); + } + } + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { - if( this.isEnabled() ) - { - super.putStack( par1ItemStack ); + @Override + public void onSlotChanged() { + if (this.inventory instanceof AppEngInternalInventory) { + ((AppEngInternalInventory) this.inventory).markDirty(this.getSlotIndex()); + } else { + super.onSlotChanged(); + } - if( this.getContainer() != null ) - { - this.getContainer().onSlotChange( this ); - } - } - } + this.setIsValid(hasCalculatedValidness.NotAvailable); + } - @Override - public void onSlotChanged() - { - if( this.inventory instanceof AppEngInternalInventory ) - { - ( (AppEngInternalInventory) this.inventory ).markDirty( this.getSlotIndex() ); - } - else - { - super.onSlotChanged(); - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + if (this.isEnabled()) { + return super.canTakeStack(par1EntityPlayer); + } + return false; + } - this.setIsValid( hasCalculatedValidness.NotAvailable ); - } + @Override + public boolean func_111238_b() { + return this.isEnabled(); + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - if( this.isEnabled() ) - { - return super.canTakeStack( par1EntityPlayer ); - } - return false; - } + public ItemStack getDisplayStack() { + return super.getStack(); + } - @Override - public boolean func_111238_b() - { - return this.isEnabled(); - } + public boolean isEnabled() { + return true; + } - public ItemStack getDisplayStack() - { - return super.getStack(); - } + public float getOpacityOfIcon() { + return 0.4f; + } - public boolean isEnabled() - { - return true; - } + public boolean renderIconWithItem() { + return false; + } - public float getOpacityOfIcon() - { - return 0.4f; - } + public int getIcon() { + return this.getIIcon(); + } - public boolean renderIconWithItem() - { - return false; - } + public boolean isPlayerSide() { + return this.isPlayerSide; + } - public int getIcon() - { - return this.getIIcon(); - } + public boolean shouldDisplay() { + return this.isEnabled(); + } - public boolean isPlayerSide() - { - return this.isPlayerSide; - } + public int getX() { + return this.defX; + } - public boolean shouldDisplay() - { - return this.isEnabled(); - } + public int getY() { + return this.defY; + } - public int getX() - { - return this.defX; - } + private int getIIcon() { + return this.IIcon; + } - public int getY() - { - return this.defY; - } + public void setIIcon(final int iIcon) { + this.IIcon = iIcon; + } - private int getIIcon() - { - return this.IIcon; - } + private boolean isDisplay() { + return this.isDisplay; + } - public void setIIcon( final int iIcon ) - { - this.IIcon = iIcon; - } + public void setDisplay(final boolean isDisplay) { + this.isDisplay = isDisplay; + } - private boolean isDisplay() - { - return this.isDisplay; - } + public boolean isDraggable() { + return this.isDraggable; + } - public void setDisplay( final boolean isDisplay ) - { - this.isDisplay = isDisplay; - } + private void setDraggable(final boolean isDraggable) { + this.isDraggable = isDraggable; + } - public boolean isDraggable() - { - return this.isDraggable; - } + void setPlayerSide(final boolean isPlayerSide) { + this.isPlayerSide = isPlayerSide; + } - private void setDraggable( final boolean isDraggable ) - { - this.isDraggable = isDraggable; - } + public hasCalculatedValidness getIsValid() { + return this.isValid; + } - void setPlayerSide( final boolean isPlayerSide ) - { - this.isPlayerSide = isPlayerSide; - } + public void setIsValid(final hasCalculatedValidness isValid) { + this.isValid = isValid; + } - public hasCalculatedValidness getIsValid() - { - return this.isValid; - } + AEBaseContainer getContainer() { + return this.myContainer; + } - public void setIsValid( final hasCalculatedValidness isValid ) - { - this.isValid = isValid; - } + public void setContainer(final AEBaseContainer myContainer) { + this.myContainer = myContainer; + } - AEBaseContainer getContainer() - { - return this.myContainer; - } - - public void setContainer( final AEBaseContainer myContainer ) - { - this.myContainer = myContainer; - } - - public enum hasCalculatedValidness - { - NotAvailable, Valid, Invalid - } + 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 995959ce..1e3c8e53 100644 --- a/src/main/java/appeng/container/slot/IOptionalSlotHost.java +++ b/src/main/java/appeng/container/slot/IOptionalSlotHost.java @@ -18,9 +18,6 @@ package appeng.container.slot; - -public interface IOptionalSlotHost -{ - - boolean isSlotEnabled( int idx ); +public interface IOptionalSlotHost { + 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 c018203b..902a63cb 100644 --- a/src/main/java/appeng/container/slot/NullSlot.java +++ b/src/main/java/appeng/container/slot/NullSlot.java @@ -18,84 +18,64 @@ 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() { + super(null, 0, 0, 0); + } -public class NullSlot extends Slot -{ + @Override + public void + onSlotChange(final ItemStack par1ItemStack, final ItemStack par2ItemStack) {} - public NullSlot() - { - super( null, 0, 0, 0 ); - } + @Override + public void + onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { - @Override - public void onSlotChange( final ItemStack par1ItemStack, final ItemStack par2ItemStack ) - { + } - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { + @Override + public ItemStack getStack() { + return null; + } - } + @Override + public void putStack(final ItemStack par1ItemStack) {} - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public void onSlotChanged() {} - @Override - public ItemStack getStack() - { - return null; - } + @Override + public int getSlotStackLimit() { + return 0; + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } - } + @Override + public boolean isSlotInInventory(final IInventory par1IInventory, final int par2) { + return false; + } - @Override - public void onSlotChanged() - { + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - } - - @Override - public int getSlotStackLimit() - { - return 0; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } - - @Override - public boolean isSlotInInventory( final IInventory par1IInventory, final int par2 ) - { - return false; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } - - @Override - public int getSlotIndex() - { - return 0; - } + @Override + public int getSlotIndex() { + return 0; + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFake.java b/src/main/java/appeng/container/slot/OptionalSlotFake.java index d2e5d3a6..67bb076e 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFake.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFake.java @@ -18,76 +18,70 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class OptionalSlotFake extends SlotFake { + private final int srcX; + private final int srcY; + private final int groupNum; + private final IOptionalSlotHost host; + private boolean renderDisabled = true; -public class OptionalSlotFake extends SlotFake -{ + public OptionalSlotFake( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int idx, + final int x, + final int y, + final int offX, + final int offY, + final int groupNum + ) { + super(inv, idx, x + offX * 18, y + offY * 18); + this.srcX = x; + this.srcY = y; + this.groupNum = groupNum; + this.host = containerBus; + } - private final int srcX; - private final int srcY; - private final int groupNum; - private final IOptionalSlotHost host; - private boolean renderDisabled = true; + @Override + public ItemStack getStack() { + if (!this.isEnabled()) { + if (this.getDisplayStack() != null) { + this.clearStack(); + } + } - public OptionalSlotFake( final IInventory inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, idx, x + offX * 18, y + offY * 18 ); - this.srcX = x; - this.srcY = y; - this.groupNum = groupNum; - this.host = containerBus; - } + return super.getStack(); + } - @Override - public ItemStack getStack() - { - if( !this.isEnabled() ) - { - if( this.getDisplayStack() != null ) - { - this.clearStack(); - } - } + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } - return super.getStack(); - } + return this.host.isSlotEnabled(this.groupNum); + } - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } + public boolean renderDisabled() { + return this.isRenderDisabled(); + } - return this.host.isSlotEnabled( this.groupNum ); - } + private boolean isRenderDisabled() { + return this.renderDisabled; + } - public boolean renderDisabled() - { - return this.isRenderDisabled(); - } + public void setRenderDisabled(final boolean renderDisabled) { + this.renderDisabled = renderDisabled; + } - private boolean isRenderDisabled() - { - return this.renderDisabled; - } + public int getSourceX() { + return this.srcX; + } - public void setRenderDisabled( final boolean renderDisabled ) - { - this.renderDisabled = renderDisabled; - } - - public int getSourceX() - { - return this.srcX; - } - - public int getSourceY() - { - return this.srcY; - } + public int getSourceY() { + return this.srcY; + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java index 666d9b60..91bc1255 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/OptionalSlotFakeTypeOnly.java @@ -18,35 +18,34 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class OptionalSlotFakeTypeOnly extends OptionalSlotFake { + public OptionalSlotFakeTypeOnly( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int idx, + final int x, + final int y, + final int offX, + final int offY, + final int groupNum + ) { + super(inv, containerBus, idx, x, y, offX, offY, groupNum); + } -public class OptionalSlotFakeTypeOnly extends OptionalSlotFake -{ + @Override + public void putStack(ItemStack is) { + if (is != null) { + is = is.copy(); + if (is.stackSize > 1) { + is.stackSize = 1; + } else if (is.stackSize < -1) { + is.stackSize = -1; + } + } - public OptionalSlotFakeTypeOnly( final IInventory inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, containerBus, idx, x, y, offX, offY, groupNum ); - } - - @Override - public void putStack( ItemStack is ) - { - if( is != null ) - { - is = is.copy(); - if( is.stackSize > 1 ) - { - is.stackSize = 1; - } - else if( is.stackSize < -1 ) - { - is.stackSize = -1; - } - } - - super.putStack( is ); - } + super.putStack(is); + } } diff --git a/src/main/java/appeng/container/slot/OptionalSlotNormal.java b/src/main/java/appeng/container/slot/OptionalSlotNormal.java index 95247c9e..68f7286f 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotNormal.java +++ b/src/main/java/appeng/container/slot/OptionalSlotNormal.java @@ -18,31 +18,31 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class OptionalSlotNormal extends AppEngSlot { + private final int groupNum; + private final IOptionalSlotHost host; -public class OptionalSlotNormal extends AppEngSlot -{ + public OptionalSlotNormal( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int slot, + final int xPos, + final int yPos, + final int groupNum + ) { + super(inv, slot, xPos, yPos); + this.groupNum = groupNum; + this.host = containerBus; + } - private final int groupNum; - private final IOptionalSlotHost host; + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } - public OptionalSlotNormal( final IInventory inv, final IOptionalSlotHost containerBus, final int slot, final int xPos, final int yPos, final int groupNum ) - { - super( inv, slot, xPos, yPos ); - this.groupNum = groupNum; - this.host = containerBus; - } - - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } - - return this.host.isSlotEnabled( this.groupNum ); - } + 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 a9c994af..dcabb71c 100644 --- a/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/OptionalSlotRestrictedInput.java @@ -18,32 +18,34 @@ package appeng.container.slot; - import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; +public class OptionalSlotRestrictedInput extends SlotRestrictedInput { + private final int groupNum; + private final IOptionalSlotHost host; -public class OptionalSlotRestrictedInput extends SlotRestrictedInput -{ + public OptionalSlotRestrictedInput( + final PlacableItemType valid, + final IInventory i, + final IOptionalSlotHost host, + final int slotIndex, + final int x, + final int y, + final int grpNum, + final InventoryPlayer invPlayer + ) { + super(valid, i, slotIndex, x, y, invPlayer); + this.groupNum = grpNum; + this.host = host; + } - private final int groupNum; - private final IOptionalSlotHost host; + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } - public OptionalSlotRestrictedInput( final PlacableItemType valid, final IInventory i, final IOptionalSlotHost host, final int slotIndex, final int x, final int y, final int grpNum, final InventoryPlayer invPlayer ) - { - super( valid, i, slotIndex, x, y, invPlayer ); - this.groupNum = grpNum; - this.host = host; - } - - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } - - return this.host.isSlotEnabled( this.groupNum ); - } + 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 319d479a..7531aae7 100644 --- a/src/main/java/appeng/container/slot/QuartzKnifeOutput.java +++ b/src/main/java/appeng/container/slot/QuartzKnifeOutput.java @@ -18,15 +18,12 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class QuartzKnifeOutput extends SlotOutput -{ - - public QuartzKnifeOutput( final IInventory a, final int b, final int c, final int d, final int i ) - { - super( a, b, c, d, i ); - } +public class QuartzKnifeOutput extends SlotOutput { + public QuartzKnifeOutput( + final IInventory a, final int b, final int c, final int d, final 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 e87320a5..15bacf8e 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotCraftingMatrix.java @@ -18,48 +18,45 @@ package appeng.container.slot; - import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotCraftingMatrix extends AppEngSlot { + private final Container c; -public class SlotCraftingMatrix extends AppEngSlot -{ + public SlotCraftingMatrix( + final Container c, + final IInventory par1iInventory, + final int par2, + final int par3, + final int par4 + ) { + super(par1iInventory, par2, par3, par4); + this.c = c; + } - private final Container c; + @Override + public void clearStack() { + super.clearStack(); + this.c.onCraftMatrixChanged(this.inventory); + } - public SlotCraftingMatrix( final Container c, final IInventory par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); - this.c = c; - } + @Override + public void putStack(final ItemStack par1ItemStack) { + super.putStack(par1ItemStack); + this.c.onCraftMatrixChanged(this.inventory); + } - @Override - public void clearStack() - { - super.clearStack(); - this.c.onCraftMatrixChanged( this.inventory ); - } + @Override + public boolean isPlayerSide() { + return true; + } - @Override - public void putStack( final ItemStack par1ItemStack ) - { - super.putStack( par1ItemStack ); - this.c.onCraftMatrixChanged( this.inventory ); - } - - @Override - public boolean isPlayerSide() - { - return true; - } - - @Override - public ItemStack decrStackSize( final int par1 ) - { - final ItemStack is = super.decrStackSize( par1 ); - this.c.onCraftMatrixChanged( this.inventory ); - return is; - } + @Override + public ItemStack decrStackSize(final int par1) { + final 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 4464d570..38da408d 100644 --- a/src/main/java/appeng/container/slot/SlotCraftingTerm.java +++ b/src/main/java/appeng/container/slot/SlotCraftingTerm.java @@ -18,6 +18,8 @@ package appeng.container.slot; +import java.util.ArrayList; +import java.util.List; import appeng.api.config.Actionable; import appeng.api.networking.energy.IEnergySource; @@ -41,240 +43,247 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; -import java.util.ArrayList; -import java.util.List; +public class SlotCraftingTerm extends AppEngCraftingSlot { + private final IInventory craftInv; + private final IInventory pattern; + private final BaseActionSource mySrc; + private final IEnergySource energySrc; + private final IStorageMonitorable storage; + private final IContainerCraftingPacket container; -public class SlotCraftingTerm extends AppEngCraftingSlot -{ + public SlotCraftingTerm( + final EntityPlayer player, + final BaseActionSource mySrc, + final IEnergySource energySrc, + final IStorageMonitorable storage, + final IInventory cMatrix, + final IInventory secondMatrix, + final IInventory output, + final int x, + final int y, + final IContainerCraftingPacket ccp + ) { + super(player, cMatrix, output, 0, x, y); + this.energySrc = energySrc; + this.storage = storage; + this.mySrc = mySrc; + this.pattern = cMatrix; + this.craftInv = secondMatrix; + this.container = ccp; + } - private final IInventory craftInv; - private final IInventory pattern; + public IInventory getCraftingMatrix() { + return this.craftInv; + } - private final BaseActionSource mySrc; - private final IEnergySource energySrc; - private final IStorageMonitorable storage; - private final IContainerCraftingPacket container; + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - public SlotCraftingTerm( final EntityPlayer player, final BaseActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IInventory cMatrix, final IInventory secondMatrix, final IInventory output, final int x, final int y, final IContainerCraftingPacket ccp ) - { - super( player, cMatrix, output, 0, x, y ); - this.energySrc = energySrc; - this.storage = storage; - this.mySrc = mySrc; - this.pattern = cMatrix; - this.craftInv = secondMatrix; - this.container = ccp; - } + @Override + public void onPickupFromSlot(final EntityPlayer p, final ItemStack is) {} - public IInventory getCraftingMatrix() - { - return this.craftInv; - } + public void doClick(final InventoryAction action, final EntityPlayer who) { + if (this.getStack() == null) { + return; + } + if (Platform.isClient()) { + return; + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + final IMEMonitor inv = this.storage.getItemInventory(); + final int howManyPerCraft = this.getStack().stackSize; + int maxTimesToCraft = 0; - @Override - public void onPickupFromSlot( final EntityPlayer p, final ItemStack is ) - { - } + 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; + } - public void doClick( final InventoryAction action, final EntityPlayer who ) - { - if( this.getStack() == null ) - { - return; - } - if( Platform.isClient() ) - { - return; - } + maxTimesToCraft = this.capCraftingAttempts(maxTimesToCraft); - final IMEMonitor inv = this.storage.getItemInventory(); - final int howManyPerCraft = this.getStack().stackSize; - int maxTimesToCraft = 0; + if (ia == null) { + return; + } - 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; - } + final ItemStack rs = Platform.cloneItemStack(this.getStack()); + if (rs == null) { + return; + } - maxTimesToCraft = this.capCraftingAttempts( maxTimesToCraft ); + for (int x = 0; x < maxTimesToCraft; x++) { + if (ia.simulateAdd(rs) == null) { + final IItemList all = inv.getStorageList(); + final ItemStack extra = ia.addItems(this.craftItem(who, rs, inv, all)); + if (extra != null) { + final List drops = new ArrayList(); + drops.add(extra); + Platform.spawnDrops( + who.worldObj, + (int) who.posX, + (int) who.posY, + (int) who.posZ, + drops + ); + return; + } + } + } + } - if( ia == null ) - { - return; - } + private int capCraftingAttempts(final int maxTimesToCraft) { + return maxTimesToCraft; + } - final ItemStack rs = Platform.cloneItemStack( this.getStack() ); - if( rs == null ) - { - return; - } + private ItemStack craftItem( + final EntityPlayer p, + final ItemStack request, + final IMEMonitor inv, + final IItemList all + ) { + // update crafting matrix... + ItemStack is = this.getStack(); - for( int x = 0; x < maxTimesToCraft; x++ ) - { - if( ia.simulateAdd( rs ) == null ) - { - final IItemList all = inv.getStorageList(); - final ItemStack extra = ia.addItems( this.craftItem( who, rs, inv, all ) ); - if( extra != null ) - { - final List drops = new ArrayList(); - drops.add( extra ); - Platform.spawnDrops( who.worldObj, (int) who.posX, (int) who.posY, (int) who.posZ, drops ); - return; - } - } - } - } + if (is != null && Platform.isSameItem(request, is)) { + final ItemStack[] set = new ItemStack[this.getPattern().getSizeInventory()]; - private int capCraftingAttempts( final int maxTimesToCraft ) - { - return maxTimesToCraft; - } + // add one of each item to the items on the board... + if (Platform.isServer()) { + final InventoryCrafting ic + = new InventoryCrafting(new ContainerNull(), 3, 3); + for (int x = 0; x < 9; x++) { + ic.setInventorySlotContents(x, this.getPattern().getStackInSlot(x)); + } - private ItemStack craftItem( final EntityPlayer p, final ItemStack request, final IMEMonitor inv, final IItemList all ) - { - // update crafting matrix... - ItemStack is = this.getStack(); + final IRecipe r = Platform.findMatchingRecipe(ic, p.worldObj); - if( is != null && Platform.isSameItem( request, is ) ) - { - final ItemStack[] set = new ItemStack[this.getPattern().getSizeInventory()]; + if (r == null) { + final Item target = request.getItem(); + if (target.isDamageable() && target.isRepairable()) { + boolean isBad = false; + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack pis = ic.getStackInSlot(x); + if (pis == null) { + continue; + } + if (pis.getItem() != target) { + isBad = true; + } + } + if (!isBad) { + super.onPickupFromSlot(p, is); + // actually necessary to cleanup this case... + p.openContainer.onCraftMatrixChanged(this.craftInv); + return request; + } + } + return null; + } - // add one of each item to the items on the board... - if( Platform.isServer() ) - { - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for( int x = 0; x < 9; x++ ) - { - ic.setInventorySlotContents( x, this.getPattern().getStackInSlot( x ) ); - } + is = r.getCraftingResult(ic); - final IRecipe r = Platform.findMatchingRecipe( ic, p.worldObj ); + if (inv != null) { + for (int x = 0; x < this.getPattern().getSizeInventory(); x++) { + if (this.getPattern().getStackInSlot(x) != null) { + set[x] = Platform.extractItemsByRecipe( + this.energySrc, + this.mySrc, + inv, + p.worldObj, + r, + is, + ic, + this.getPattern().getStackInSlot(x), + x, + all, + Actionable.MODULATE, + ItemViewCell.createFilter(this.container.getViewCells()) + ); + ic.setInventorySlotContents(x, set[x]); + } + } + } + } - if( r == null ) - { - final Item target = request.getItem(); - if( target.isDamageable() && target.isRepairable() ) - { - boolean isBad = false; - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack pis = ic.getStackInSlot( x ); - if( pis == null ) - { - continue; - } - if( pis.getItem() != target ) - { - isBad = true; - } - } - if( !isBad ) - { - super.onPickupFromSlot( p, is ); - // actually necessary to cleanup this case... - p.openContainer.onCraftMatrixChanged( this.craftInv ); - return request; - } - } - return null; - } + if (this.preCraft(p, inv, set, is)) { + this.makeItem(p, is); - is = r.getCraftingResult( ic ); + this.postCraft(p, inv, set, is); + } - if( inv != null ) - { - for( int x = 0; x < this.getPattern().getSizeInventory(); x++ ) - { - if( this.getPattern().getStackInSlot( x ) != null ) - { - set[x] = Platform.extractItemsByRecipe( this.energySrc, this.mySrc, inv, p.worldObj, r, is, ic, this.getPattern().getStackInSlot( x ), x, all, Actionable.MODULATE, ItemViewCell.createFilter( this.container.getViewCells() ) ); - ic.setInventorySlotContents( x, set[x] ); - } - } - } - } + // shouldn't be necessary... + p.openContainer.onCraftMatrixChanged(this.craftInv); - if( this.preCraft( p, inv, set, is ) ) - { - this.makeItem( p, is ); + return is; + } - this.postCraft( p, inv, set, is ); - } + return null; + } - // shouldn't be necessary... - p.openContainer.onCraftMatrixChanged( this.craftInv ); + private boolean preCraft( + final EntityPlayer p, + final IMEMonitor inv, + final ItemStack[] set, + final ItemStack result + ) { + return true; + } - return is; - } + private void makeItem(final EntityPlayer p, final ItemStack is) { + super.onPickupFromSlot(p, is); + } - return null; - } + private void postCraft( + final EntityPlayer p, + final IMEMonitor inv, + final ItemStack[] set, + final ItemStack result + ) { + final List drops = new ArrayList(); - private boolean preCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) - { - return true; - } + // add one of each item to the items on the board... + if (Platform.isServer()) { + // set new items onto the crafting table... + for (int x = 0; x < this.craftInv.getSizeInventory(); x++) { + if (this.craftInv.getStackInSlot(x) == null) { + this.craftInv.setInventorySlotContents(x, set[x]); + } else if (set[x] != null) { + // eek! put it back! + final IAEItemStack fail = inv.injectItems( + AEItemStack.create(set[x]), Actionable.MODULATE, this.mySrc + ); + if (fail != null) { + drops.add(fail.getItemStack()); + } + } + } + } - private void makeItem( final EntityPlayer p, final ItemStack is ) - { - super.onPickupFromSlot( p, is ); - } + if (drops.size() > 0) { + Platform.spawnDrops( + p.worldObj, (int) p.posX, (int) p.posY, (int) p.posZ, drops + ); + } + } - private void postCraft( final EntityPlayer p, final IMEMonitor inv, final ItemStack[] set, final ItemStack result ) - { - final List drops = new ArrayList(); - - // add one of each item to the items on the board... - if( Platform.isServer() ) - { - // set new items onto the crafting table... - for( int x = 0; x < this.craftInv.getSizeInventory(); x++ ) - { - if( this.craftInv.getStackInSlot( x ) == null ) - { - this.craftInv.setInventorySlotContents( x, set[x] ); - } - else if( set[x] != null ) - { - // eek! put it back! - final IAEItemStack fail = inv.injectItems( AEItemStack.create( set[x] ), Actionable.MODULATE, this.mySrc ); - 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 ); - } - } - - IInventory getPattern() - { - return this.pattern; - } + IInventory getPattern() { + return this.pattern; + } } diff --git a/src/main/java/appeng/container/slot/SlotDisabled.java b/src/main/java/appeng/container/slot/SlotDisabled.java index f298e6e7..e496ba86 100644 --- a/src/main/java/appeng/container/slot/SlotDisabled.java +++ b/src/main/java/appeng/container/slot/SlotDisabled.java @@ -18,29 +18,24 @@ 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( + final IInventory par1iInventory, final int slotIndex, final int x, final int y + ) { + super(par1iInventory, slotIndex, x, y); + } -public class SlotDisabled extends AppEngSlot -{ + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - public SlotDisabled( final IInventory par1iInventory, final int slotIndex, final int x, final int y ) - { - super( par1iInventory, slotIndex, x, y ); - } - - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final 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 28807ee0..6c8c49ae 100644 --- a/src/main/java/appeng/container/slot/SlotFake.java +++ b/src/main/java/appeng/container/slot/SlotFake.java @@ -18,51 +18,41 @@ 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 { + public SlotFake(final IInventory inv, final int idx, final int x, final int y) { + super(inv, idx, x, y); + } -public class SlotFake extends AppEngSlot -{ + @Override + public void + onPickupFromSlot(final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack) { + } - public SlotFake( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + @Override + public ItemStack decrStackSize(final int par1) { + return null; + } - @Override - public void onPickupFromSlot( final EntityPlayer par1EntityPlayer, final ItemStack par2ItemStack ) - { - } + @Override + public boolean isItemValid(final ItemStack par1ItemStack) { + return false; + } - @Override - public ItemStack decrStackSize( final int par1 ) - { - return null; - } + @Override + public void putStack(ItemStack is) { + if (is != null) { + is = is.copy(); + } - @Override - public boolean isItemValid( final ItemStack par1ItemStack ) - { - return false; - } + super.putStack(is); + } - @Override - public void putStack( ItemStack is ) - { - if( is != null ) - { - is = is.copy(); - } - - super.putStack( is ); - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } + @Override + public boolean canTakeStack(final 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 b0d9ba51..bd8fc60d 100644 --- a/src/main/java/appeng/container/slot/SlotFakeBlacklist.java +++ b/src/main/java/appeng/container/slot/SlotFakeBlacklist.java @@ -18,37 +18,30 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class SlotFakeBlacklist extends SlotFakeTypeOnly { + public SlotFakeBlacklist( + final IInventory inv, final int idx, final int x, final int y + ) { + super(inv, idx, x, y); + } -public class SlotFakeBlacklist extends SlotFakeTypeOnly -{ + @Override + public float getOpacityOfIcon() { + return 0.8f; + } - public SlotFakeBlacklist( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } + @Override + public boolean renderIconWithItem() { + return true; + } - @Override - public float getOpacityOfIcon() - { - return 0.8f; - } - - @Override - public boolean renderIconWithItem() - { - return true; - } - - @Override - public int getIcon() - { - if( this.getHasStack() ) - { - return this.getStack().stackSize > 0 ? 16 + 14 : 14; - } - return -1; - } + @Override + public int getIcon() { + 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 e1bf15b2..893aac17 100644 --- a/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java +++ b/src/main/java/appeng/container/slot/SlotFakeCraftingMatrix.java @@ -18,15 +18,12 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class SlotFakeCraftingMatrix extends SlotFake -{ - - public SlotFakeCraftingMatrix( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } +public class SlotFakeCraftingMatrix extends SlotFake { + public SlotFakeCraftingMatrix( + final IInventory inv, final int idx, final int x, final 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 809da8ac..64fcac3c 100644 --- a/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java +++ b/src/main/java/appeng/container/slot/SlotFakeTypeOnly.java @@ -18,35 +18,27 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotFakeTypeOnly extends SlotFake { + public SlotFakeTypeOnly( + final IInventory inv, final int idx, final int x, final int y + ) { + super(inv, idx, x, y); + } -public class SlotFakeTypeOnly extends SlotFake -{ + @Override + public void putStack(ItemStack is) { + if (is != null) { + is = is.copy(); + if (is.stackSize > 1) { + is.stackSize = 1; + } else if (is.stackSize < -1) { + is.stackSize = -1; + } + } - public SlotFakeTypeOnly( final IInventory inv, final int idx, final int x, final int y ) - { - super( inv, idx, x, y ); - } - - @Override - public void putStack( ItemStack is ) - { - if( is != null ) - { - is = is.copy(); - if( is.stackSize > 1 ) - { - is.stackSize = 1; - } - else if( is.stackSize < -1 ) - { - is.stackSize = -1; - } - } - - super.putStack( is ); - } + super.putStack(is); + } } diff --git a/src/main/java/appeng/container/slot/SlotInaccessible.java b/src/main/java/appeng/container/slot/SlotInaccessible.java index b385a9c5..a1b6e860 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessible.java +++ b/src/main/java/appeng/container/slot/SlotInaccessible.java @@ -18,52 +18,43 @@ 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 { + private ItemStack dspStack = null; -public class SlotInaccessible extends AppEngSlot -{ + public SlotInaccessible( + final IInventory i, final int slotIdx, final int x, final int y + ) { + super(i, slotIdx, x, y); + } - private ItemStack dspStack = null; + @Override + public boolean isItemValid(final ItemStack i) { + return false; + } - public SlotInaccessible( final IInventory i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - } + @Override + public void onSlotChanged() { + super.onSlotChanged(); + this.dspStack = null; + } - @Override - public boolean isItemValid( final ItemStack i ) - { - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return false; + } - @Override - public void onSlotChanged() - { - super.onSlotChanged(); - this.dspStack = null; - } - - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return false; - } - - @Override - public ItemStack getDisplayStack() - { - if( this.dspStack == null ) - { - final ItemStack dsp = super.getDisplayStack(); - if( dsp != null ) - { - this.dspStack = dsp.copy(); - } - } - return this.dspStack; - } + @Override + public ItemStack getDisplayStack() { + if (this.dspStack == null) { + final 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 10d675d4..8a12ef3a 100644 --- a/src/main/java/appeng/container/slot/SlotInaccessibleHD.java +++ b/src/main/java/appeng/container/slot/SlotInaccessibleHD.java @@ -18,15 +18,12 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class SlotInaccessibleHD extends SlotInaccessible -{ - - public SlotInaccessibleHD( final IInventory i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - } +public class SlotInaccessibleHD extends SlotInaccessible { + public SlotInaccessibleHD( + final IInventory i, final int slotIdx, final int x, final 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 3b9d5776..03c8e452 100644 --- a/src/main/java/appeng/container/slot/SlotMACPattern.java +++ b/src/main/java/appeng/container/slot/SlotMACPattern.java @@ -18,26 +18,26 @@ package appeng.container.slot; - import appeng.container.implementations.ContainerMAC; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotMACPattern extends AppEngSlot { + private final ContainerMAC mac; -public class SlotMACPattern extends AppEngSlot -{ + public SlotMACPattern( + final ContainerMAC mac, + final IInventory i, + final int slotIdx, + final int x, + final int y + ) { + super(i, slotIdx, x, y); + this.mac = mac; + } - private final ContainerMAC mac; - - public SlotMACPattern( final ContainerMAC mac, final IInventory i, final int slotIdx, final int x, final int y ) - { - super( i, slotIdx, x, y ); - this.mac = mac; - } - - @Override - public boolean isItemValid( final ItemStack i ) - { - return this.mac.isValidItemForSlot( this.getSlotIndex(), i ); - } + @Override + public boolean isItemValid(final 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 96e705b2..765d79f1 100644 --- a/src/main/java/appeng/container/slot/SlotNormal.java +++ b/src/main/java/appeng/container/slot/SlotNormal.java @@ -18,15 +18,12 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class SlotNormal extends AppEngSlot -{ - - public SlotNormal( final IInventory inv, final int slot, final int xPos, final int yPos ) - { - super( inv, slot, xPos, yPos ); - } +public class SlotNormal extends AppEngSlot { + public SlotNormal( + final IInventory inv, final int slot, final int xPos, final 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 3c662433..a3f49a94 100644 --- a/src/main/java/appeng/container/slot/SlotOutput.java +++ b/src/main/java/appeng/container/slot/SlotOutput.java @@ -18,23 +18,19 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class SlotOutput extends AppEngSlot { + public SlotOutput( + final IInventory a, final int b, final int c, final int d, final int i + ) { + super(a, b, c, d); + this.setIIcon(i); + } -public class SlotOutput extends AppEngSlot -{ - - public SlotOutput( final IInventory a, final int b, final int c, final int d, final int i ) - { - super( a, b, c, d ); - this.setIIcon( i ); - } - - @Override - public boolean isItemValid( final ItemStack i ) - { - return false; - } + @Override + public boolean isItemValid(final 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 49a85806..af05985e 100644 --- a/src/main/java/appeng/container/slot/SlotPatternOutputs.java +++ b/src/main/java/appeng/container/slot/SlotPatternOutputs.java @@ -18,27 +18,29 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; +public class SlotPatternOutputs extends OptionalSlotFake { + public SlotPatternOutputs( + final IInventory inv, + final IOptionalSlotHost containerBus, + final int idx, + final int x, + final int y, + final int offX, + final int offY, + final int groupNum + ) { + super(inv, containerBus, idx, x, y, offX, offY, groupNum); + } -public class SlotPatternOutputs extends OptionalSlotFake -{ + @Override + public boolean isEnabled() { + return true; + } - public SlotPatternOutputs( final IInventory inv, final IOptionalSlotHost containerBus, final int idx, final int x, final int y, final int offX, final int offY, final int groupNum ) - { - super( inv, containerBus, idx, x, y, offX, offY, groupNum ); - } - - @Override - public boolean isEnabled() - { - return true; - } - - @Override - public boolean shouldDisplay() - { - return super.isEnabled(); - } + @Override + public boolean shouldDisplay() { + return super.isEnabled(); + } } diff --git a/src/main/java/appeng/container/slot/SlotPatternTerm.java b/src/main/java/appeng/container/slot/SlotPatternTerm.java index aaf96d82..0c0062d8 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 appeng.api.AEApi; import appeng.api.networking.energy.IEnergySource; @@ -30,50 +31,55 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.io.IOException; +public class SlotPatternTerm extends SlotCraftingTerm { + private final int groupNum; + private final IOptionalSlotHost host; + public SlotPatternTerm( + final EntityPlayer player, + final BaseActionSource mySrc, + final IEnergySource energySrc, + final IStorageMonitorable storage, + final IInventory cMatrix, + final IInventory secondMatrix, + final IInventory output, + final int x, + final int y, + final IOptionalSlotHost h, + final int groupNumber, + final IContainerCraftingPacket c + ) { + super(player, mySrc, energySrc, storage, cMatrix, secondMatrix, output, x, y, c); -public class SlotPatternTerm extends SlotCraftingTerm -{ + this.host = h; + this.groupNum = groupNumber; + } - private final int groupNum; - private final IOptionalSlotHost host; + public AppEngPacket getRequest(final boolean shift) throws IOException { + return new PacketPatternSlot( + this.getPattern(), + AEApi.instance().storage().createItemStack(this.getStack()), + shift + ); + } - public SlotPatternTerm( final EntityPlayer player, final BaseActionSource mySrc, final IEnergySource energySrc, final IStorageMonitorable storage, final IInventory cMatrix, final IInventory secondMatrix, final IInventory output, final int x, final int y, final IOptionalSlotHost h, final int groupNumber, final IContainerCraftingPacket c ) - { - super( player, mySrc, energySrc, storage, cMatrix, secondMatrix, output, x, y, c ); + @Override + public ItemStack getStack() { + if (!this.isEnabled()) { + if (this.getDisplayStack() != null) { + this.clearStack(); + } + } - this.host = h; - this.groupNum = groupNumber; - } + return super.getStack(); + } - public AppEngPacket getRequest( final boolean shift ) throws IOException - { - return new PacketPatternSlot( this.getPattern(), AEApi.instance().storage().createItemStack( this.getStack() ), shift ); - } + @Override + public boolean isEnabled() { + if (this.host == null) { + return false; + } - @Override - public ItemStack getStack() - { - if( !this.isEnabled() ) - { - if( this.getDisplayStack() != null ) - { - this.clearStack(); - } - } - - return super.getStack(); - } - - @Override - public boolean isEnabled() - { - if( this.host == null ) - { - return false; - } - - return this.host.isSlotEnabled( this.groupNum ); - } + return this.host.isSlotEnabled(this.groupNum); + } } diff --git a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java index aba5e52c..6e5aa180 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerHotBar.java +++ b/src/main/java/appeng/container/slot/SlotPlayerHotBar.java @@ -18,16 +18,13 @@ package appeng.container.slot; - import net.minecraft.inventory.IInventory; - -public class SlotPlayerHotBar extends AppEngSlot -{ - - public SlotPlayerHotBar( final IInventory par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); - this.setPlayerSide( true ); - } +public class SlotPlayerHotBar extends AppEngSlot { + public SlotPlayerHotBar( + final IInventory par1iInventory, final int par2, final int par3, final int par4 + ) { + super(par1iInventory, par2, par3, par4); + this.setPlayerSide(true); + } } diff --git a/src/main/java/appeng/container/slot/SlotPlayerInv.java b/src/main/java/appeng/container/slot/SlotPlayerInv.java index a30f3766..47d0d6a3 100644 --- a/src/main/java/appeng/container/slot/SlotPlayerInv.java +++ b/src/main/java/appeng/container/slot/SlotPlayerInv.java @@ -18,19 +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. +// 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( + final IInventory par1iInventory, final int par2, final int par3, final int par4 + ) { + super(par1iInventory, par2, par3, par4); -public class SlotPlayerInv extends AppEngSlot -{ - - public SlotPlayerInv( final IInventory par1iInventory, final int par2, final int par3, final int par4 ) - { - super( par1iInventory, par2, par3, par4 ); - - this.setPlayerSide( true ); - } + this.setPlayerSide(true); + } } diff --git a/src/main/java/appeng/container/slot/SlotRestrictedInput.java b/src/main/java/appeng/container/slot/SlotRestrictedInput.java index cb7bf42d..79103aa3 100644 --- a/src/main/java/appeng/container/slot/SlotRestrictedInput.java +++ b/src/main/java/appeng/container/slot/SlotRestrictedInput.java @@ -18,7 +18,6 @@ package appeng.container.slot; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItems; @@ -43,268 +42,279 @@ import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class SlotRestrictedInput extends AppEngSlot -{ +public class SlotRestrictedInput extends AppEngSlot { + private final PlacableItemType which; + private final InventoryPlayer p; + private boolean allowEdit = true; + private int stackLimit = -1; - private final PlacableItemType which; - private final InventoryPlayer p; - private boolean allowEdit = true; - private int stackLimit = -1; + public SlotRestrictedInput( + final PlacableItemType valid, + final IInventory i, + final int slotIndex, + final int x, + final int y, + final InventoryPlayer p + ) { + super(i, slotIndex, x, y); + this.which = valid; + this.setIIcon(valid.IIcon); + this.p = p; + } - public SlotRestrictedInput( final PlacableItemType valid, final IInventory i, final int slotIndex, final int x, final int y, final InventoryPlayer p ) - { - super( i, slotIndex, x, y ); - this.which = valid; - this.setIIcon( valid.IIcon ); - this.p = p; - } + @Override + public int getSlotStackLimit() { + if (this.stackLimit != -1) { + return this.stackLimit; + } + return super.getSlotStackLimit(); + } - @Override - public int getSlotStackLimit() - { - if( this.stackLimit != -1 ) - { - return this.stackLimit; - } - return super.getSlotStackLimit(); - } + public boolean isValid(final ItemStack is, final World theWorld) { + if (this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT) { + final ICraftingPatternDetails ap + = is.getItem() instanceof ICraftingPatternItem + ? ((ICraftingPatternItem) is.getItem()).getPatternForItem(is, theWorld) + : null; + return ap != null; + } + return true; + } - public boolean isValid( final ItemStack is, final World theWorld ) - { - if( this.which == PlacableItemType.VALID_ENCODED_PATTERN_W_OUTPUT ) - { - final ICraftingPatternDetails ap = is.getItem() instanceof ICraftingPatternItem ? ( (ICraftingPatternItem) is.getItem() ).getPatternForItem( is, theWorld ) : null; - return ap != null; - } - return true; - } + public Slot setStackLimit(final int i) { + this.stackLimit = i; + return this; + } - public Slot setStackLimit( final int i ) - { - this.stackLimit = i; - return this; - } + @Override + public boolean isItemValid(final ItemStack i) { + if (!this.getContainer().isValidForSlot(this, i)) { + return false; + } - @Override - public boolean isItemValid( final ItemStack i ) - { - if( !this.getContainer().isValidForSlot( this, i ) ) - { - return false; - } + if (i == null) { + return false; + } + if (i.getItem() == null) { + return false; + } - if( i == null ) - { - return false; - } - if( i.getItem() == null ) - { - return false; - } + if (!this.inventory.isItemValidForSlot(this.getSlotIndex(), i)) { + return false; + } - if( !this.inventory.isItemValidForSlot( this.getSlotIndex(), i ) ) - { - return false; - } + if (!this.isAllowEdit()) { + return false; + } - if( !this.isAllowEdit() ) - { - return false; - } + final IDefinitions definitions = AEApi.instance().definitions(); + final IMaterials materials = definitions.materials(); + final IItems items = definitions.items(); - final IDefinitions definitions = AEApi.instance().definitions(); - final IMaterials materials = definitions.materials(); - final IItems items = definitions.items(); + switch (this.which) { + case ENCODED_CRAFTING_PATTERN: + if (i.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem b = (ICraftingPatternItem) i.getItem(); + final ICraftingPatternDetails de + = b.getPatternForItem(i, this.p.player.worldObj); + 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) { + return true; + } + // ICraftingPatternDetails pattern = i.getItem() instanceof + // ICraftingPatternItem ? + // ((ICraftingPatternItem) + // i.getItem()).getPatternForItem( i ) : null; + return false; // pattern != null; + } + case BLANK_PATTERN: + return materials.blankPattern().isSameAs(i); - switch( this.which ) - { - case ENCODED_CRAFTING_PATTERN: - if( i.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem b = (ICraftingPatternItem) i.getItem(); - final ICraftingPatternDetails de = b.getPatternForItem( i, this.p.player.worldObj ); - 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 ) - { - return true; - } - // ICraftingPatternDetails pattern = i.getItem() instanceof ICraftingPatternItem ? - // ((ICraftingPatternItem) - // i.getItem()).getPatternForItem( i ) : null; - return false;// pattern != null; - } - case BLANK_PATTERN: - return materials.blankPattern().isSameAs( i ); + case PATTERN: - case PATTERN: + if (i.getItem() instanceof ICraftingPatternItem) { + return true; + } - if( i.getItem() instanceof ICraftingPatternItem ) - { - return true; - } + return materials.blankPattern().isSameAs(i); - return materials.blankPattern().isSameAs( i ); + case INSCRIBER_PLATE: + if (materials.namePress().isSameAs(i)) { + return true; + } - case INSCRIBER_PLATE: - if( materials.namePress().isSameAs( i ) ) - { - return true; - } + for (final ItemStack optional : + AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.isSameItemPrecise(optional, i)) { + return true; + } + } - for( final ItemStack optional : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.isSameItemPrecise( optional, i ) ) - { - return true; - } - } + return false; - return false; + case INSCRIBER_INPUT: + return true; /* + * for (ItemStack is : Inscribe.inputs) if ( + * Platform.isSameItemPrecise( is, i ) ) return true; return + * false; + */ - case INSCRIBER_INPUT: - return true;/* - * for (ItemStack is : Inscribe.inputs) if ( Platform.isSameItemPrecise( is, i ) ) return - * true; - * return false; - */ + case METAL_INGOTS: - case METAL_INGOTS: + return isMetalIngot(i); - return isMetalIngot( i ); + case VIEW_CELL: + return items.viewCell().isSameAs(i); + case ORE: + return appeng.api.AEApi.instance() + .registries() + .grinder() + .getRecipeForInput(i) + != null; + case FUEL: + return TileEntityFurnace.getItemBurnTime(i) > 0; + case POWERED_TOOL: + return Platform.isChargeable(i); + case QE_SINGULARITY: + return materials.qESingularity().isSameAs(i); - case VIEW_CELL: - return items.viewCell().isSameAs( i ); - case ORE: - return appeng.api.AEApi.instance().registries().grinder().getRecipeForInput( i ) != null; - case FUEL: - return TileEntityFurnace.getItemBurnTime( i ) > 0; - case POWERED_TOOL: - return Platform.isChargeable( i ); - case QE_SINGULARITY: - return materials.qESingularity().isSameAs( i ); + case RANGE_BOOSTER: + return materials.wirelessBooster().isSameAs(i); - case RANGE_BOOSTER: - return materials.wirelessBooster().isSameAs( i ); + case SPATIAL_STORAGE_CELLS: + 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); + case STORAGE_COMPONENT: + return i.getItem() instanceof IStorageComponent + && ((IStorageComponent) i.getItem()).isStorageComponent(i); + case TRASH: + if (AEApi.instance().registries().cell().isCellHandled(i)) { + return false; + } - case SPATIAL_STORAGE_CELLS: - 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 ); - case STORAGE_COMPONENT: - return i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ); - case TRASH: - if( AEApi.instance().registries().cell().isCellHandled( i ) ) - { - return false; - } + return !( + i.getItem() instanceof IStorageComponent + && ((IStorageComponent) i.getItem()).isStorageComponent(i) + ); + case ENCODABLE_ITEM: + return i.getItem() instanceof INetworkEncodable + || AEApi.instance().registries().wireless().isWirelessTerminal(i); + case BIOMETRIC_CARD: + return i.getItem() instanceof IBiometricCard; + case UPGRADES: + return i.getItem() instanceof IUpgradeModule + && ((IUpgradeModule) i.getItem()).getType(i) != null; + default: + break; + } - return !( i.getItem() instanceof IStorageComponent && ( (IStorageComponent) i.getItem() ).isStorageComponent( i ) ); - case ENCODABLE_ITEM: - return i.getItem() instanceof INetworkEncodable || AEApi.instance().registries().wireless().isWirelessTerminal( i ); - case BIOMETRIC_CARD: - return i.getItem() instanceof IBiometricCard; - case UPGRADES: - return i.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) i.getItem() ).getType( i ) != null; - default: - break; - } + return false; + } - return false; - } + @Override + public boolean canTakeStack(final EntityPlayer par1EntityPlayer) { + return this.isAllowEdit(); + } - @Override - public boolean canTakeStack( final EntityPlayer par1EntityPlayer ) - { - return this.isAllowEdit(); - } + @Override + public ItemStack getDisplayStack() { + if (Platform.isClient() && (this.which == PlacableItemType.ENCODED_PATTERN)) { + final ItemStack is = super.getStack(); + if (is != null && is.getItem() instanceof ItemEncodedPattern) { + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ItemStack out = iep.getOutput(is); + if (out != null) { + return out; + } + } + } + return super.getStack(); + } - @Override - public ItemStack getDisplayStack() - { - if( Platform.isClient() && ( this.which == PlacableItemType.ENCODED_PATTERN ) ) - { - final ItemStack is = super.getStack(); - if( is != null && is.getItem() instanceof ItemEncodedPattern ) - { - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ItemStack out = iep.getOutput( is ); - if( out != null ) - { - return out; - } - } - } - return super.getStack(); - } + public static boolean isMetalIngot(final ItemStack i) { + if (Platform.isSameItemPrecise(i, new ItemStack(Items.iron_ingot))) { + return true; + } - public static boolean isMetalIngot( final ItemStack i ) - { - if( Platform.isSameItemPrecise( i, new ItemStack( Items.iron_ingot ) ) ) - { - return true; - } + for (final String name : new String[] { "Copper", + "Tin", + "Obsidian", + "Iron", + "Lead", + "Bronze", + "Brass", + "Nickel", + "Aluminium" }) { + for (final ItemStack ingot : OreDictionary.getOres("ingot" + name)) { + if (Platform.isSameItemPrecise(i, ingot)) { + return true; + } + } + } - for( final String name : new String[] { "Copper", "Tin", "Obsidian", "Iron", "Lead", "Bronze", "Brass", "Nickel", "Aluminium" } ) - { - for( final ItemStack ingot : OreDictionary.getOres( "ingot" + name ) ) - { - if( Platform.isSameItemPrecise( i, ingot ) ) - { - return true; - } - } - } + return false; + } - return false; - } + private boolean isAllowEdit() { + return this.allowEdit; + } - private boolean isAllowEdit() - { - return this.allowEdit; - } + public void setAllowEdit(final boolean allowEdit) { + this.allowEdit = allowEdit; + } - public void setAllowEdit( final boolean allowEdit ) - { - this.allowEdit = allowEdit; - } + public enum PlacableItemType { + STORAGE_CELLS(15), + ORE(16 + 15), + STORAGE_COMPONENT(3 * 16 + 15), - 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), - 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), - 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), - 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), - 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); - INSCRIBER_PLATE( 2 * 16 + 14 ), INSCRIBER_INPUT( 3 * 16 + 14 ), METAL_INGOTS( 3 * 16 + 14 ); + public final int IIcon; - public final int IIcon; - - PlacableItemType( final int o ) - { - this.IIcon = o; - } - } + PlacableItemType(final int o) { + this.IIcon = o; + } + } } diff --git a/src/main/java/appeng/core/AEConfig.java b/src/main/java/appeng/core/AEConfig.java index 5e430344..c9d1a615 100644 --- a/src/main/java/appeng/core/AEConfig.java +++ b/src/main/java/appeng/core/AEConfig.java @@ -18,6 +18,10 @@ package appeng.core; +import java.io.File; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; import appeng.api.config.*; import appeng.api.util.IConfigManager; @@ -35,471 +39,581 @@ import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import java.io.File; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; - - -public final class AEConfig extends Configuration implements IConfigurableObject, IConfigManagerHost -{ - - public static final double TUNNEL_POWER_LOSS = 0.05; - public static final String VERSION = "@version@"; - public static final String CHANNEL = "@aechannel@"; - public static final String PACKET_CHANNEL = "AE"; - public static AEConfig instance; - public final IConfigManager settings = new ConfigManager( this ); - public final EnumSet featureFlags = EnumSet.noneOf( AEFeature.class ); - public final int[] craftByStacks = { 1, 10, 100, 1000 }; - public final int[] priorityByStacks = { 1, 10, 100, 1000 }; - public final int[] levelByStacks = { 1, 10, 100, 1000 }; - private final double WirelessHighWirelessCount = 64; - private final 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 final int chargedChange = 4; - public int minMeteoriteDistance = 707; - public int minMeteoriteDistanceSq = this.minMeteoriteDistance * this.minMeteoriteDistance; - public double spatialPowerExponent = 1.35; - public double spatialPowerMultiplier = 1250.0; - public String[] grinderOres = { - // Vanilla Items - "Obsidian", "Ender", "EnderPearl", "Coal", "Iron", "Gold", "Charcoal", "NetherQuartz", - // Common Mod Ores - "Copper", "Tin", "Silver", "Lead", "Bronze", - // AE - "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 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; - public double meteoriteClusterChance = 0.1; - public double meteoriteSpawnChance = 0.3; - public int[] meteoriteDimensionWhitelist = { 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; - public int ItemTypeLimit = 63; - public boolean NeedController = false; - public boolean HardLegacyController = false; - - public AEConfig( final File configFile ) - { - super( configFile ); - this.configFile = configFile; - - FMLCommonHandler.instance().bus().register( this ); - - final double DEFAULT_MEKANISM_EXCHANGE = 0.2; - - PowerUnits.MK.conversionRatio = this.get( "PowerRatios", "Mekanism", DEFAULT_MEKANISM_EXCHANGE ).getDouble( DEFAULT_MEKANISM_EXCHANGE ); - final double DEFAULT_IC2_EXCHANGE = 2.0; - PowerUnits.EU.conversionRatio = this.get( "PowerRatios", "IC2", DEFAULT_IC2_EXCHANGE ).getDouble( DEFAULT_IC2_EXCHANGE ); - final double DEFAULT_RTC_EXCHANGE = 1.0 / 11256.0; - PowerUnits.WA.conversionRatio = this.get( "PowerRatios", "RotaryCraft", DEFAULT_RTC_EXCHANGE ).getDouble( DEFAULT_RTC_EXCHANGE ); - final double DEFAULT_RF_EXCHANGE = 0.5; - PowerUnits.RF.conversionRatio = this.get( "PowerRatios", "ThermalExpansion", DEFAULT_RF_EXCHANGE ).getDouble( DEFAULT_RF_EXCHANGE ); - - final double usageEffective = this.get( "PowerRatios", "UsageMultiplier", 1.0 ).getDouble( 1.0 ); - PowerMultiplier.CONFIG.multiplier = Math.max( 0.01, usageEffective ); - - CondenserOutput.MATTER_BALLS.requiredPower = this.get( "Condenser", "MatterBalls", 256 ).getInt( 256 ); - CondenserOutput.SINGULARITY.requiredPower = this.get( "Condenser", "Singularity", 256000 ).getInt( 256000 ); - - this.grinderOres = this.get( "GrindStone", "grinderOres", this.grinderOres ).getStringList(); - this.oreDoublePercentage = this.get( "GrindStone", "oreDoublePercentage", this.oreDoublePercentage ).getDouble( this.oreDoublePercentage ); - - this.settings.registerSetting( Settings.SEARCH_TOOLTIPS, YesNo.YES ); - 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.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.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.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.WirelessBoosterExp = this.get( "wireless", "WirelessBoosterExp", this.WirelessBoosterExp ).getDouble( this.WirelessBoosterExp ); - this.WirelessTerminalDrainMultiplier = this.get( "wireless", "WirelessTerminalDrainMultiplier", this.WirelessTerminalDrainMultiplier ).getDouble( this.WirelessTerminalDrainMultiplier ); - - this.formationPlaneEntityLimit = this.get( "automation", "formationPlaneEntityLimit", this.formationPlaneEntityLimit ).getInt( this.formationPlaneEntityLimit ); - - this.wirelessTerminalBattery = this.get( "battery", "wirelessTerminal", this.wirelessTerminalBattery ).getInt( this.wirelessTerminalBattery ); - this.chargedStaffBattery = this.get( "battery", "chargedStaff", this.chargedStaffBattery ).getInt( this.chargedStaffBattery ); - this.entropyManipulatorBattery = this.get( "battery", "entropyManipulator", this.entropyManipulatorBattery ).getInt( this.entropyManipulatorBattery ); - this.portableCellBattery = this.get( "battery", "portableCell", this.portableCellBattery ).getInt( this.portableCellBattery ); - this.colorApplicatorBattery = this.get( "battery", "colorApplicator", this.colorApplicatorBattery ).getInt( this.colorApplicatorBattery ); - this.matterCannonBattery = this.get( "battery", "matterCannon", this.matterCannonBattery ).getInt( this.matterCannonBattery ); - - this.ItemTypeLimit = this.get( "tileraedition", "typeLimit", this.ItemTypeLimit ).getInt( this.ItemTypeLimit ); - this.NeedController = this.get("tileraedition", "needController", this.NeedController).getBoolean( this.NeedController ); - this.HardLegacyController = this.get("tileraedition", "hardLegacyController", this.HardLegacyController).getBoolean( this.HardLegacyController ); - - this.clientSync(); - - for( final AEFeature feature : AEFeature.values() ) - { - if( feature.isVisible() ) - { - if( this.get( "Features." + feature.category, feature.name(), feature.defaultValue ).getBoolean( feature.defaultValue ) ) - { - this.featureFlags.add( feature ); - } - } - else - { - this.featureFlags.add( feature ); - } - } - - final ModContainer imb = cpw.mods.fml.common.Loader.instance().getIndexedModList().get( "ImmibisCore" ); - if( imb != null ) - { - final List version = Arrays.asList( "59.0.0", "59.0.1", "59.0.2" ); - if( version.contains( imb.getVersion() ) ) - { - this.featureFlags.remove( AEFeature.AlphaPass ); - } - } - - try - { - this.selectedPowerUnit = PowerUnits.valueOf( this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).getString() ); - } - catch( final Throwable t ) - { - this.selectedPowerUnit = PowerUnits.AE; - } - - for( final TickRates tr : TickRates.values() ) - { - tr.Load( this ); - } - - 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 ); - this.spatialPowerMultiplier = this.get( "spatialio", "spatialPowerMultiplier", this.spatialPowerMultiplier ).getDouble( this.spatialPowerMultiplier ); - this.spatialPowerExponent = this.get( "spatialio", "spatialPowerExponent", this.spatialPowerExponent ).getDouble( this.spatialPowerExponent ); - } - - if( this.isFeatureEnabled( AEFeature.CraftingCPU ) ) - { - this.craftingCalculationTimePerTick = this.get( "craftingCPU", "craftingCalculationTimePerTick", this.craftingCalculationTimePerTick ).getInt( this.craftingCalculationTimePerTick ); - } - - this.updatable = true; - } - - 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++ ) - { - final Property cmb = this.get( "Client", "craftAmtButton" + ( btnNum + 1 ), this.craftByStacks[btnNum] ); - final Property pmb = this.get( "Client", "priorityAmtButton" + ( btnNum + 1 ), this.priorityByStacks[btnNum] ); - final Property lmb = this.get( "Client", "levelAmtButton" + ( btnNum + 1 ), this.levelByStacks[btnNum] ); - - final 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( final Settings e : this.settings.getSettings() ) - { - final String Category = "Client"; // e.getClass().getSimpleName(); - Enum value = this.settings.getSetting( e ); - - final Property p = this.get( Category, e.name(), value.name(), this.getListComment( value ) ); - - try - { - value = Enum.valueOf( value.getClass(), p.getString() ); - } - catch( final IllegalArgumentException er ) - { - AELog.info( "Invalid value '" + p.getString() + "' for " + e.name() + " using '" + value.name() + "' instead" ); - } - - this.settings.putSetting( e, value ); - } - } - - private String getListComment( final Enum value ) - { - String comment = null; - - if( value != null ) - { - final EnumSet set = EnumSet.allOf( value.getClass() ); - - for( final Object Oeg : set ) - { - final Enum eg = (Enum) Oeg; - if( comment == null ) - { - comment = "Possible Values: " + eg.name(); - } - else - { - comment += ", " + eg.name(); - } - } - } - - return comment; - } - - public boolean isFeatureEnabled( final AEFeature f ) - { - return this.featureFlags.contains( f ); - } - - public double wireless_getDrainRate( final double range ) - { - return this.WirelessTerminalDrainMultiplier * range; - } - - public double wireless_getMaxRange( final int boosters ) - { - return this.WirelessBaseRange + this.WirelessBoosterRangeMultiplier * Math.pow( boosters, this.WirelessBoosterExp ); - } - - public double wireless_getPowerDrain( final int boosters ) - { - return this.WirelessBaseCost + this.WirelessCostMultiplier * Math.pow( boosters, 1 + boosters / this.WirelessHighWirelessCount ); - } - - @Override - public Property get( final String category, final String key, final String defaultValue, final String comment, final Property.Type type ) - { - final Property prop = super.get( category, key, defaultValue, comment, type ); - - if( prop != null ) - { - if( !category.equals( "Client" ) ) - { - prop.setRequiresMcRestart( true ); - } - } - - return prop; - } - - @Override - public void save() - { - if( this.isFeatureEnabled( AEFeature.SpatialIO ) ) - { - this.get( "spatialio", "storageBiomeID", this.storageBiomeID ).set( this.storageBiomeID ); - this.get( "spatialio", "storageProviderID", this.storageProviderID ).set( this.storageProviderID ); - } - - this.get( "Client", "PowerUnit", this.selectedPowerUnit.name(), this.getListComment( this.selectedPowerUnit ) ).set( this.selectedPowerUnit.name() ); - - if( this.hasChanged() ) - { - super.save(); - } - } - - @SubscribeEvent - public void onConfigChanged( final 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( final 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." ); - final Property p = this.get( "OreCamouflage", mt.name(), true ); - p.comment = "OreDictionary Names: " + mt.getOreName(); - - return !p.getBoolean( true ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum setting, final Enum newValue ) - { - for( final Settings e : this.settings.getSettings() ) - { - if( e == setting ) - { - final String Category = "Client"; - final 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( final int varID ) - { - return this.getFreeIDSLot( varID, "materials" ); - } - - public int getFreeIDSLot( final int varID, final String category ) - { - boolean alreadyUsed = false; - int min = 0; - - for( final Property p : this.getCategory( category ).getValues().values() ) - { - final int thisInt = p.getInt(); - - if( varID == thisInt ) - { - alreadyUsed = true; - } - - min = Math.max( min, thisInt + 1 ); - } - - if( alreadyUsed ) - { - if( min < 16383 ) - { - min = 16383; - } - - return min; - } - - return varID; - } - - public int getFreePart( final int varID ) - { - return this.getFreeIDSLot( varID, "parts" ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - public boolean useTerminalUseLargeFont() - { - return this.useLargeFonts; - } - - public int craftItemsByStackAmounts( final int i ) - { - return this.craftByStacks[i]; - } - - public int priorityByStacksAmounts( final int i ) - { - return this.priorityByStacks[i]; - } - - public int levelByStackAmounts( final int i ) - { - return this.levelByStacks[i]; - } - - public Enum getSetting( final String category, final Class class1, final Enum myDefault ) - { - final String name = class1.getSimpleName(); - final Property p = this.get( category, name, myDefault.name() ); - - try - { - return (Enum) class1.getField( p.toString() ).get( class1 ); - } - catch( final Throwable t ) - { - // :{ - } - - return myDefault; - } - - public void setSetting( final String category, final Enum s ) - { - final String name = s.getClass().getSimpleName(); - this.get( category, name, s.name() ).set( s.name() ); - this.save(); - } - - public PowerUnits selectedPowerUnit() - { - return this.selectedPowerUnit; - } - - public void nextPowerUnit( final boolean backwards ) - { - this.selectedPowerUnit = Platform.rotateEnum( this.selectedPowerUnit, backwards, Settings.POWER_UNITS.getPossibleValues() ); - this.save(); - } +public final class AEConfig + extends Configuration implements IConfigurableObject, IConfigManagerHost { + public static final double TUNNEL_POWER_LOSS = 0.05; + public static final String VERSION = "@version@"; + public static final String CHANNEL = "@aechannel@"; + public static final String PACKET_CHANNEL = "AE"; + public static AEConfig instance; + public final IConfigManager settings = new ConfigManager(this); + public final EnumSet featureFlags = EnumSet.noneOf(AEFeature.class); + public final int[] craftByStacks = { 1, 10, 100, 1000 }; + public final int[] priorityByStacks = { 1, 10, 100, 1000 }; + public final int[] levelByStacks = { 1, 10, 100, 1000 }; + private final double WirelessHighWirelessCount = 64; + private final 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 final int chargedChange = 4; + public int minMeteoriteDistance = 707; + public int minMeteoriteDistanceSq + = this.minMeteoriteDistance * this.minMeteoriteDistance; + public double spatialPowerExponent = 1.35; + public double spatialPowerMultiplier = 1250.0; + public String[] grinderOres = { + // Vanilla Items + "Obsidian", + "Ender", + "EnderPearl", + "Coal", + "Iron", + "Gold", + "Charcoal", + "NetherQuartz", + // Common Mod Ores + "Copper", + "Tin", + "Silver", + "Lead", + "Bronze", + // AE + "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 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; + public double meteoriteClusterChance = 0.1; + public double meteoriteSpawnChance = 0.3; + public int[] meteoriteDimensionWhitelist = { 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; + public int ItemTypeLimit = 63; + public boolean NeedController = false; + public boolean HardLegacyController = false; + + public AEConfig(final File configFile) { + super(configFile); + this.configFile = configFile; + + FMLCommonHandler.instance().bus().register(this); + + final double DEFAULT_MEKANISM_EXCHANGE = 0.2; + + PowerUnits.MK.conversionRatio + = this.get("PowerRatios", "Mekanism", DEFAULT_MEKANISM_EXCHANGE) + .getDouble(DEFAULT_MEKANISM_EXCHANGE); + final double DEFAULT_IC2_EXCHANGE = 2.0; + PowerUnits.EU.conversionRatio + = this.get("PowerRatios", "IC2", DEFAULT_IC2_EXCHANGE) + .getDouble(DEFAULT_IC2_EXCHANGE); + final double DEFAULT_RTC_EXCHANGE = 1.0 / 11256.0; + PowerUnits.WA.conversionRatio + = this.get("PowerRatios", "RotaryCraft", DEFAULT_RTC_EXCHANGE) + .getDouble(DEFAULT_RTC_EXCHANGE); + final double DEFAULT_RF_EXCHANGE = 0.5; + PowerUnits.RF.conversionRatio + = this.get("PowerRatios", "ThermalExpansion", DEFAULT_RF_EXCHANGE) + .getDouble(DEFAULT_RF_EXCHANGE); + + final double usageEffective + = this.get("PowerRatios", "UsageMultiplier", 1.0).getDouble(1.0); + PowerMultiplier.CONFIG.multiplier = Math.max(0.01, usageEffective); + + CondenserOutput.MATTER_BALLS.requiredPower + = this.get("Condenser", "MatterBalls", 256).getInt(256); + CondenserOutput.SINGULARITY.requiredPower + = this.get("Condenser", "Singularity", 256000).getInt(256000); + + this.grinderOres + = this.get("GrindStone", "grinderOres", this.grinderOres).getStringList(); + this.oreDoublePercentage + = this.get("GrindStone", "oreDoublePercentage", this.oreDoublePercentage) + .getDouble(this.oreDoublePercentage); + + this.settings.registerSetting(Settings.SEARCH_TOOLTIPS, YesNo.YES); + 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.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.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.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.WirelessBoosterExp + = this.get("wireless", "WirelessBoosterExp", this.WirelessBoosterExp) + .getDouble(this.WirelessBoosterExp); + this.WirelessTerminalDrainMultiplier + = this.get( + "wireless", + "WirelessTerminalDrainMultiplier", + this.WirelessTerminalDrainMultiplier + ) + .getDouble(this.WirelessTerminalDrainMultiplier); + + this.formationPlaneEntityLimit = this.get( + "automation", + "formationPlaneEntityLimit", + this.formationPlaneEntityLimit + ) + .getInt(this.formationPlaneEntityLimit); + + this.wirelessTerminalBattery + = this.get("battery", "wirelessTerminal", this.wirelessTerminalBattery) + .getInt(this.wirelessTerminalBattery); + this.chargedStaffBattery + = this.get("battery", "chargedStaff", this.chargedStaffBattery) + .getInt(this.chargedStaffBattery); + this.entropyManipulatorBattery + = this.get("battery", "entropyManipulator", this.entropyManipulatorBattery) + .getInt(this.entropyManipulatorBattery); + this.portableCellBattery + = this.get("battery", "portableCell", this.portableCellBattery) + .getInt(this.portableCellBattery); + this.colorApplicatorBattery + = this.get("battery", "colorApplicator", this.colorApplicatorBattery) + .getInt(this.colorApplicatorBattery); + this.matterCannonBattery + = this.get("battery", "matterCannon", this.matterCannonBattery) + .getInt(this.matterCannonBattery); + + this.ItemTypeLimit = this.get("tileraedition", "typeLimit", this.ItemTypeLimit) + .getInt(this.ItemTypeLimit); + this.NeedController + = this.get("tileraedition", "needController", this.NeedController) + .getBoolean(this.NeedController); + this.HardLegacyController + = this.get("tileraedition", "hardLegacyController", this.HardLegacyController) + .getBoolean(this.HardLegacyController); + + this.clientSync(); + + for (final AEFeature feature : AEFeature.values()) { + if (feature.isVisible()) { + if (this.get( + "Features." + feature.category, + feature.name(), + feature.defaultValue + ) + .getBoolean(feature.defaultValue)) { + this.featureFlags.add(feature); + } + } else { + this.featureFlags.add(feature); + } + } + + final ModContainer imb + = cpw.mods.fml.common.Loader.instance().getIndexedModList().get("ImmibisCore" + ); + if (imb != null) { + final List version = Arrays.asList("59.0.0", "59.0.1", "59.0.2"); + if (version.contains(imb.getVersion())) { + this.featureFlags.remove(AEFeature.AlphaPass); + } + } + + try { + this.selectedPowerUnit + = PowerUnits.valueOf(this.get( + "Client", + "PowerUnit", + this.selectedPowerUnit.name(), + this.getListComment(this.selectedPowerUnit) + ) + .getString()); + } catch (final Throwable t) { + this.selectedPowerUnit = PowerUnits.AE; + } + + for (final TickRates tr : TickRates.values()) { + tr.Load(this); + } + + 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); + this.spatialPowerMultiplier = this.get( + "spatialio", + "spatialPowerMultiplier", + this.spatialPowerMultiplier + ) + .getDouble(this.spatialPowerMultiplier); + this.spatialPowerExponent + = this.get("spatialio", "spatialPowerExponent", this.spatialPowerExponent) + .getDouble(this.spatialPowerExponent); + } + + if (this.isFeatureEnabled(AEFeature.CraftingCPU)) { + this.craftingCalculationTimePerTick + = this.get( + "craftingCPU", + "craftingCalculationTimePerTick", + this.craftingCalculationTimePerTick + ) + .getInt(this.craftingCalculationTimePerTick); + } + + this.updatable = true; + } + + 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++) { + final Property cmb = this.get( + "Client", "craftAmtButton" + (btnNum + 1), this.craftByStacks[btnNum] + ); + final Property pmb = this.get( + "Client", + "priorityAmtButton" + (btnNum + 1), + this.priorityByStacks[btnNum] + ); + final Property lmb = this.get( + "Client", "levelAmtButton" + (btnNum + 1), this.levelByStacks[btnNum] + ); + + final 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 (final Settings e : this.settings.getSettings()) { + final String Category = "Client"; // e.getClass().getSimpleName(); + Enum value = this.settings.getSetting(e); + + final Property p + = this.get(Category, e.name(), value.name(), this.getListComment(value)); + + try { + value = Enum.valueOf(value.getClass(), p.getString()); + } catch (final IllegalArgumentException er) { + AELog.info( + "Invalid value '" + p.getString() + "' for " + e.name() + " using '" + + value.name() + "' instead" + ); + } + + this.settings.putSetting(e, value); + } + } + + private String getListComment(final Enum value) { + String comment = null; + + if (value != null) { + final EnumSet set = EnumSet.allOf(value.getClass()); + + for (final Object Oeg : set) { + final Enum eg = (Enum) Oeg; + if (comment == null) { + comment = "Possible Values: " + eg.name(); + } else { + comment += ", " + eg.name(); + } + } + } + + return comment; + } + + public boolean isFeatureEnabled(final AEFeature f) { + return this.featureFlags.contains(f); + } + + public double wireless_getDrainRate(final double range) { + return this.WirelessTerminalDrainMultiplier * range; + } + + public double wireless_getMaxRange(final int boosters) { + return this.WirelessBaseRange + + this.WirelessBoosterRangeMultiplier + * Math.pow(boosters, this.WirelessBoosterExp); + } + + public double wireless_getPowerDrain(final int boosters) { + return this.WirelessBaseCost + + this.WirelessCostMultiplier + * Math.pow(boosters, 1 + boosters / this.WirelessHighWirelessCount); + } + + @Override + public Property + get(final String category, + final String key, + final String defaultValue, + final String comment, + final Property.Type type) { + final Property prop = super.get(category, key, defaultValue, comment, type); + + if (prop != null) { + if (!category.equals("Client")) { + prop.setRequiresMcRestart(true); + } + } + + return prop; + } + + @Override + public void save() { + if (this.isFeatureEnabled(AEFeature.SpatialIO)) { + this.get("spatialio", "storageBiomeID", this.storageBiomeID) + .set(this.storageBiomeID); + this.get("spatialio", "storageProviderID", this.storageProviderID) + .set(this.storageProviderID); + } + + this.get( + "Client", + "PowerUnit", + this.selectedPowerUnit.name(), + this.getListComment(this.selectedPowerUnit) + ) + .set(this.selectedPowerUnit.name()); + + if (this.hasChanged()) { + super.save(); + } + } + + @SubscribeEvent + public void onConfigChanged(final 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(final 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." + ); + final Property p = this.get("OreCamouflage", mt.name(), true); + p.comment = "OreDictionary Names: " + mt.getOreName(); + + return !p.getBoolean(true); + } + + @Override + public void + updateSetting(final IConfigManager manager, final Enum setting, final Enum newValue) { + for (final Settings e : this.settings.getSettings()) { + if (e == setting) { + final String Category = "Client"; + final 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(final int varID) { + return this.getFreeIDSLot(varID, "materials"); + } + + public int getFreeIDSLot(final int varID, final String category) { + boolean alreadyUsed = false; + int min = 0; + + for (final Property p : this.getCategory(category).getValues().values()) { + final int thisInt = p.getInt(); + + if (varID == thisInt) { + alreadyUsed = true; + } + + min = Math.max(min, thisInt + 1); + } + + if (alreadyUsed) { + if (min < 16383) { + min = 16383; + } + + return min; + } + + return varID; + } + + public int getFreePart(final int varID) { + return this.getFreeIDSLot(varID, "parts"); + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + public boolean useTerminalUseLargeFont() { + return this.useLargeFonts; + } + + public int craftItemsByStackAmounts(final int i) { + return this.craftByStacks[i]; + } + + public int priorityByStacksAmounts(final int i) { + return this.priorityByStacks[i]; + } + + public int levelByStackAmounts(final int i) { + return this.levelByStacks[i]; + } + + public Enum getSetting( + final String category, final Class class1, final Enum myDefault + ) { + final String name = class1.getSimpleName(); + final Property p = this.get(category, name, myDefault.name()); + + try { + return (Enum) class1.getField(p.toString()).get(class1); + } catch (final Throwable t) { + // :{ + } + + return myDefault; + } + + public void setSetting(final String category, final Enum s) { + final String name = s.getClass().getSimpleName(); + this.get(category, name, s.name()).set(s.name()); + this.save(); + } + + public PowerUnits selectedPowerUnit() { + return this.selectedPowerUnit; + } + + public void nextPowerUnit(final 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 4dfa483f..6dce76f9 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 javax.annotation.Nonnull; import appeng.core.features.AEFeature; import appeng.tile.AEBaseTile; @@ -27,356 +28,334 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; -import javax.annotation.Nonnull; - - /** * Utility class for easier logging. */ -public final class AELog -{ +public final class AELog { + private static final String LOGGER_PREFIX = "AE2:"; + private static final String SERVER_SUFFIX = "S"; + private static final String CLIENT_SUFFIX = "C"; - private static final String LOGGER_PREFIX = "AE2:"; - private static final String SERVER_SUFFIX = "S"; - private static final String CLIENT_SUFFIX = "C"; + private static final String BLOCK_UPDATE = "Block Update of %s @ ( %d, %d, %d )"; - private static final String BLOCK_UPDATE = "Block Update of %s @ ( %d, %d, %d )"; + private static final String DEFAULT_EXCEPTION_MESSAGE = "Exception: "; - private static final String DEFAULT_EXCEPTION_MESSAGE = "Exception: "; + private AELog() {} - private AELog() - { - } + /** + * Returns a {@link Logger} logger suitable for the effective side (client/server). + * + * @return a suitable logger instance + */ + private static Logger getLogger() { + final String loggerName + = LOGGER_PREFIX + (Platform.isServer() ? SERVER_SUFFIX : CLIENT_SUFFIX); + final Logger logger = LogManager.getLogger(loggerName); - /** - * Returns a {@link Logger} logger suitable for the effective side (client/server). - * - * @return a suitable logger instance - */ - private static Logger getLogger() - { - final String loggerName = LOGGER_PREFIX + ( Platform.isServer() ? SERVER_SUFFIX : CLIENT_SUFFIX ); - final Logger logger = LogManager.getLogger( loggerName ); + return logger; + } - return logger; - } + /** + * Indicates of the global log is enabled or disabled. + *

+ * By default it is enabled. + * + * @return true when the log is enabled. + */ + public static boolean isLogEnabled() { + return AEConfig.instance == null + || AEConfig.instance.isFeatureEnabled(AEFeature.Logging); + } - /** - * Indicates of the global log is enabled or disabled. - *

- * By default it is enabled. - * - * @return true when the log is enabled. - */ - public static boolean isLogEnabled() - { - return AEConfig.instance == null || AEConfig.instance.isFeatureEnabled( AEFeature.Logging ); - } + /** + * Logs a formatted message with a specific log level. + *

+ * This uses {@link String#format(String, Object...)} as opposed to the {@link + * ParameterizedMessage} to allow a more flexible formatting.

The output can be + * globally disabled via the configuration file. + * + * @param level the intended level. + * @param message the message to be formatted. + * @param params the parameters used for {@link String#format(String, Object...)}. + */ + public static void + log(@Nonnull final Level level, @Nonnull final String message, final Object... params + ) { + if (AELog.isLogEnabled()) { + final String formattedMessage = String.format(message, params); + final Logger logger = getLogger(); - /** - * Logs a formatted message with a specific log level. - *

- * This uses {@link String#format(String, Object...)} as opposed to the {@link ParameterizedMessage} to allow a more - * flexible formatting. - *

- * The output can be globally disabled via the configuration file. - * - * @param level the intended level. - * @param message the message to be formatted. - * @param params the parameters used for {@link String#format(String, Object...)}. - */ - public static void log( @Nonnull final Level level, @Nonnull final String message, final Object... params ) - { - if( AELog.isLogEnabled() ) - { - final String formattedMessage = String.format( message, params ); - final Logger logger = getLogger(); + logger.log(level, formattedMessage); + } + } - logger.log( level, formattedMessage ); - } - } + /** + * Log an exception with a custom message formated via {@link String#format(String, + * Object...)}

Similar to {@link AELog#log(Level, String, Object...)}. + * + * @param level the intended level. + * @param exception + * @param message the message to be formatted. + * @param params the parameters used for {@link String#format(String, Object...)}. + * @see AELog#log(Level, String, Object...) + */ + public static void + log(@Nonnull final Level level, + @Nonnull final Throwable exception, + @Nonnull String message, + final Object... params) { + if (AELog.isLogEnabled()) { + final String formattedMessage = String.format(message, params); + final Logger logger = getLogger(); - /** - * Log an exception with a custom message formated via {@link String#format(String, Object...)} - *

- * Similar to {@link AELog#log(Level, String, Object...)}. - * - * @param level the intended level. - * @param exception - * @param message the message to be formatted. - * @param params the parameters used for {@link String#format(String, Object...)}. - * @see AELog#log(Level, String, Object...) - */ - public static void log( @Nonnull final Level level, @Nonnull final Throwable exception, @Nonnull String message, final Object... params ) - { - if( AELog.isLogEnabled() ) - { - final String formattedMessage = String.format( message, params ); - final Logger logger = getLogger(); + logger.log(level, formattedMessage, exception); + } + } - logger.log( level, formattedMessage, exception ); - } - } + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void info(@Nonnull final String format, final Object... params) { + log(Level.INFO, format, params); + } - /** - * @param format - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void info( @Nonnull final String format, final Object... params ) - { - log( Level.INFO, format, params ); - } + /** + * Log exception as {@link Level#INFO} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void info(@Nonnull final Throwable exception) { + log(Level.INFO, exception, DEFAULT_EXCEPTION_MESSAGE); + } - /** - * Log exception as {@link Level#INFO} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void info( @Nonnull final Throwable exception ) - { - log( Level.INFO, exception, DEFAULT_EXCEPTION_MESSAGE ); - } + /** + * Log exception as {@link Level#INFO} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void + info(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.INFO, exception, message); + } - /** - * Log exception as {@link Level#INFO} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void info( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.INFO, exception, message ); - } + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void warn(@Nonnull final String format, final Object... params) { + log(Level.WARN, format, params); + } - /** - * @param format - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void warn( @Nonnull final String format, final Object... params ) - { - log( Level.WARN, format, params ); - } + /** + * Log exception as {@link Level#WARN} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void warn(@Nonnull final Throwable exception) { + log(Level.WARN, exception, DEFAULT_EXCEPTION_MESSAGE); + } - /** - * Log exception as {@link Level#WARN} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void warn( @Nonnull final Throwable exception ) - { - log( Level.WARN, exception, DEFAULT_EXCEPTION_MESSAGE ); - } + /** + * Log exception as {@link Level#WARN} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void + warn(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.WARN, exception, message); + } - /** - * Log exception as {@link Level#WARN} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void warn( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.WARN, exception, message ); - } + /** + * @param format + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void error(@Nonnull final String format, final Object... params) { + log(Level.ERROR, format, params); + } - /** - * @param format - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void error( @Nonnull final String format, final Object... params ) - { - log( Level.ERROR, format, params ); - } + /** + * Log exception as {@link Level#ERROR} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void error(@Nonnull final Throwable exception) { + log(Level.ERROR, exception, DEFAULT_EXCEPTION_MESSAGE); + } - /** - * Log exception as {@link Level#ERROR} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void error( @Nonnull final Throwable exception ) - { - log( Level.ERROR, exception, DEFAULT_EXCEPTION_MESSAGE ); - } + /** + * Log exception as {@link Level#ERROR} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void + error(@Nonnull final Throwable exception, @Nonnull final String message) { + log(Level.ERROR, exception, message); + } - /** - * Log exception as {@link Level#ERROR} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void error( @Nonnull final Throwable exception, @Nonnull final String message ) - { - log( Level.ERROR, exception, message ); - } + /** + * Log message as {@link Level#DEBUG} + * + * @param format + * @param data + * @see AELog#log(Level, String, Object...) + */ + public static void debug(@Nonnull final String format, final Object... data) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, format, data); + } + } - /** - * Log message as {@link Level#DEBUG} - * - * @param format - * @param data - * @see AELog#log(Level, String, Object...) - */ - public static void debug( @Nonnull final String format, final Object... data ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, format, data ); - } - } + /** + * Log exception as {@link Level#DEBUG} + * + * @param exception + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void debug(@Nonnull final Throwable exception) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, exception, DEFAULT_EXCEPTION_MESSAGE); + } + } - /** - * Log exception as {@link Level#DEBUG} - * - * @param exception - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void debug( @Nonnull final Throwable exception ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, exception, DEFAULT_EXCEPTION_MESSAGE ); - } - } + /** + * Log exception as {@link Level#DEBUG} + * + * @param exception + * @param message + * @see AELog#log(Level, Throwable, String, Object...) + */ + public static void + debug(@Nonnull final Throwable exception, @Nonnull final String message) { + if (AELog.isDebugLogEnabled()) { + log(Level.DEBUG, exception, message); + } + } - /** - * Log exception as {@link Level#DEBUG} - * - * @param exception - * @param message - * @see AELog#log(Level, Throwable, String, Object...) - */ - public static void debug( @Nonnull final Throwable exception, @Nonnull final String message ) - { - if( AELog.isDebugLogEnabled() ) - { - log( Level.DEBUG, exception, message ); - } - } + /** + * Use to check for an enabled debug log. + *

+ * Can be used to prevent the execution of debug logic. + * + * @return true when the debug log is enabled. + */ + public static boolean isDebugLogEnabled() { + return AEConfig.instance.isFeatureEnabled(AEFeature.DebugLogging); + } - /** - * Use to check for an enabled debug log. - *

- * Can be used to prevent the execution of debug logic. - * - * @return true when the debug log is enabled. - */ - public static boolean isDebugLogEnabled() - { - return AEConfig.instance.isFeatureEnabled( AEFeature.DebugLogging ); - } + // + // Specialized handlers + // - // - // Specialized handlers - // + /** + * A specialized logging for grinder recipes, can be disabled inside configuration + * file. + * + * @param message String to be logged + */ + public static void grinder(@Nonnull final String message) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.GrinderLogging)) { + log(Level.DEBUG, "grinder: " + message); + } + } - /** - * A specialized logging for grinder recipes, can be disabled inside configuration file. - * - * @param message String to be logged - */ - public static void grinder( @Nonnull final String message ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.GrinderLogging ) ) - { - log( Level.DEBUG, "grinder: " + message ); - } - } + /** + * A specialized logging for mod integration errors, can be disabled inside + * configuration file. + * + * @param exception + */ + public static void integration(@Nonnull final Throwable exception) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.IntegrationLogging)) { + debug(exception); + } + } - /** - * A specialized logging for mod integration errors, can be disabled inside configuration file. - * - * @param exception - */ - public static void integration( @Nonnull final Throwable exception ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.IntegrationLogging ) ) - { - debug( exception ); - } - } + /** + * Logging of block updates. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param xCoord + * @param yCoord + * @param zCoord + * @param aeBaseTile + * @see AELog#log(Level, String, Object...) + */ + public static void blockUpdate( + final int xCoord, + final int yCoord, + final int zCoord, + @Nonnull final AEBaseTile aeBaseTile + ) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.UpdateLogging)) { + info(BLOCK_UPDATE, aeBaseTile.getClass().getName(), xCoord, +yCoord, +zCoord); + } + } - /** - * Logging of block updates. - *

- * Off by default, can be enabled inside the configuration file. - * - * @param xCoord - * @param yCoord - * @param zCoord - * @param aeBaseTile - * @see AELog#log(Level, String, Object...) - */ - public static void blockUpdate( final int xCoord, final int yCoord, final int zCoord, @Nonnull final AEBaseTile aeBaseTile ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.UpdateLogging ) ) - { - info( BLOCK_UPDATE, aeBaseTile.getClass().getName(), xCoord, +yCoord, +zCoord ); - } - } + /** + * Use to check for an enabled crafting log. + *

+ * Can be used to prevent the execution of unneeded logic. + * + * @return true when the crafting log is enabled. + */ + public static boolean isCraftingLogEnabled() { + return AEConfig.instance.isFeatureEnabled(AEFeature.CraftingLog); + } - /** - * Use to check for an enabled crafting log. - *

- * Can be used to prevent the execution of unneeded logic. - * - * @return true when the crafting log is enabled. - */ - public static boolean isCraftingLogEnabled() - { - return AEConfig.instance.isFeatureEnabled( AEFeature.CraftingLog ); - } + /** + * Logging for autocrafting. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param message + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void crafting(@Nonnull final String message, final Object... params) { + if (AELog.isCraftingLogEnabled()) { + log(Level.INFO, message, params); + } + } - /** - * Logging for autocrafting. - *

- * Off by default, can be enabled inside the configuration file. - * - * @param message - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void crafting( @Nonnull final String message, final Object... params ) - { - if( AELog.isCraftingLogEnabled() ) - { - log( Level.INFO, message, params ); - } - } + /** + * Use to check for an enabled crafting debug log. + *

+ * Can be used to prevent the execution of unneeded logic. + * + * @return true when the crafting debug log is enabled. + */ + public static boolean isCraftingDebugLogEnabled() { + return AEConfig.instance.isFeatureEnabled(AEFeature.CraftingLog) + && AEConfig.instance.isFeatureEnabled(AEFeature.DebugLogging); + } - /** - * Use to check for an enabled crafting debug log. - *

- * Can be used to prevent the execution of unneeded logic. - * - * @return true when the crafting debug log is enabled. - */ - public static boolean isCraftingDebugLogEnabled() - { - return AEConfig.instance.isFeatureEnabled( AEFeature.CraftingLog ) && AEConfig.instance.isFeatureEnabled( AEFeature.DebugLogging ); - } - - /** - * Debug logging for autocrafting. - *

- * Off by default, can be enabled inside the configuration file. - * - * @param message - * @param params - * @see AELog#log(Level, String, Object...) - */ - public static void craftingDebug( @Nonnull final String message, final Object... params ) - { - if( AELog.isCraftingDebugLogEnabled() ) - { - log( Level.DEBUG, message, params ); - } - } + /** + * Debug logging for autocrafting. + *

+ * Off by default, can be enabled inside the configuration file. + * + * @param message + * @param params + * @see AELog#log(Level, String, Object...) + */ + public static void + craftingDebug(@Nonnull final String message, final Object... params) { + if (AELog.isCraftingDebugLogEnabled()) { + log(Level.DEBUG, message, params); + } + } } diff --git a/src/main/java/appeng/core/Api.java b/src/main/java/appeng/core/Api.java index 3333cffb..9e57e134 100644 --- a/src/main/java/appeng/core/Api.java +++ b/src/main/java/appeng/core/Api.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.IAppEngApi; import appeng.api.definitions.Blocks; import appeng.api.definitions.Items; @@ -38,96 +37,85 @@ import appeng.me.GridNode; import appeng.util.Platform; import net.minecraftforge.common.util.ForgeDirection; +public final class Api implements IAppEngApi { + public static final Api INSTANCE = new Api(); -public final class Api implements IAppEngApi -{ - public static final Api INSTANCE = new Api(); + private final ApiPart partHelper; - private final ApiPart partHelper; + // private MovableTileRegistry MovableRegistry = new MovableTileRegistry(); + private final IRegistryContainer registryContainer; + private final IStorageHelper storageHelper; + private final Materials materials; + private final Items items; + private final Blocks blocks; + private final Parts parts; + private final ApiDefinitions definitions; - // private MovableTileRegistry MovableRegistry = new MovableTileRegistry(); - private final IRegistryContainer registryContainer; - private final IStorageHelper storageHelper; - private final Materials materials; - private final Items items; - private final Blocks blocks; - private final Parts parts; - private final ApiDefinitions definitions; + private Api() { + this.parts = new Parts(); + this.blocks = new Blocks(); + this.items = new Items(); + this.materials = new Materials(); + this.storageHelper = new ApiStorage(); + this.registryContainer = new RegistryContainer(); + this.partHelper = new ApiPart(); + this.definitions = new ApiDefinitions(this.partHelper); + } - private Api() - { - this.parts = new Parts(); - this.blocks = new Blocks(); - this.items = new Items(); - this.materials = new Materials(); - this.storageHelper = new ApiStorage(); - this.registryContainer = new RegistryContainer(); - this.partHelper = new ApiPart(); - this.definitions = new ApiDefinitions( this.partHelper ); - } + @Override + public IRegistryContainer registries() { + return this.registryContainer; + } - @Override - public IRegistryContainer registries() - { - return this.registryContainer; - } + @Override + public IStorageHelper storage() { + return this.storageHelper; + } - @Override - public IStorageHelper storage() - { - return this.storageHelper; - } + @Override + public ApiPart partHelper() { + return this.partHelper; + } - @Override - public ApiPart partHelper() - { - return this.partHelper; - } + @Override + public Items items() { + return this.items; + } - @Override - public Items items() - { - return this.items; - } + @Override + public Materials materials() { + return this.materials; + } - @Override - public Materials materials() - { - return this.materials; - } + @Override + public Blocks blocks() { + return this.blocks; + } - @Override - public Blocks blocks() - { - return this.blocks; - } + @Override + public Parts parts() { + return this.parts; + } - @Override - public Parts parts() - { - return this.parts; - } + @Override + public ApiDefinitions definitions() { + return this.definitions; + } - @Override - public ApiDefinitions definitions() - { - return this.definitions; - } + @Override + public IGridNode createGridNode(final IGridBlock blk) { + if (Platform.isClient()) { + throw new IllegalStateException( + "Grid features for " + blk + " are server side only." + ); + } - @Override - public IGridNode createGridNode( final IGridBlock blk ) - { - if( Platform.isClient() ) - { - throw new IllegalStateException( "Grid features for " + blk + " are server side only." ); - } + return new GridNode(blk); + } - return new GridNode( blk ); - } - - @Override - public IGridConnection createGridConnection( final IGridNode a, final IGridNode b ) throws FailedConnection - { - return new GridConnection( a, b, ForgeDirection.UNKNOWN ); - } + @Override + public IGridConnection createGridConnection(final IGridNode a, final IGridNode b) + throws FailedConnection { + return new GridConnection(a, b, ForgeDirection.UNKNOWN); + } } diff --git a/src/main/java/appeng/core/ApiDefinitions.java b/src/main/java/appeng/core/ApiDefinitions.java index 5d1a44bf..dddd0324 100644 --- a/src/main/java/appeng/core/ApiDefinitions.java +++ b/src/main/java/appeng/core/ApiDefinitions.java @@ -18,68 +18,59 @@ package appeng.core; - import appeng.api.definitions.IDefinitions; import appeng.api.parts.IPartHelper; import appeng.core.api.definitions.*; - /** * Internal implementation of the definitions for the API */ -public final class ApiDefinitions implements IDefinitions -{ - private final ApiBlocks blocks; - private final ApiItems items; - private final ApiMaterials materials; - private final ApiParts parts; - private final FeatureHandlerRegistry handlers; - private final FeatureRegistry features; +public final class ApiDefinitions implements IDefinitions { + private final ApiBlocks blocks; + private final ApiItems items; + private final ApiMaterials materials; + private final ApiParts parts; + private final FeatureHandlerRegistry handlers; + private final FeatureRegistry features; - public ApiDefinitions( final IPartHelper partHelper ) - { - this.features = new FeatureRegistry(); - this.handlers = new FeatureHandlerRegistry(); + public ApiDefinitions(final IPartHelper partHelper) { + this.features = new FeatureRegistry(); + this.handlers = new FeatureHandlerRegistry(); - final DefinitionConstructor constructor = new DefinitionConstructor( this.features, this.handlers ); + final DefinitionConstructor constructor + = new DefinitionConstructor(this.features, this.handlers); - this.blocks = new ApiBlocks( constructor ); - this.items = new ApiItems( constructor ); - this.materials = new ApiMaterials( constructor ); - this.parts = new ApiParts( constructor, partHelper ); - } + this.blocks = new ApiBlocks(constructor); + this.items = new ApiItems(constructor); + this.materials = new ApiMaterials(constructor); + this.parts = new ApiParts(constructor, partHelper); + } - FeatureHandlerRegistry getFeatureHandlerRegistry() - { - return this.handlers; - } + FeatureHandlerRegistry getFeatureHandlerRegistry() { + return this.handlers; + } - FeatureRegistry getFeatureRegistry() - { - return this.features; - } + FeatureRegistry getFeatureRegistry() { + return this.features; + } - @Override - public ApiBlocks blocks() - { - return this.blocks; - } + @Override + public ApiBlocks blocks() { + return this.blocks; + } - @Override - public ApiItems items() - { - return this.items; - } + @Override + public ApiItems items() { + return this.items; + } - @Override - public ApiMaterials materials() - { - return this.materials; - } + @Override + public ApiMaterials materials() { + return this.materials; + } - @Override - public ApiParts parts() - { - return this.parts; - } + @Override + public ApiParts parts() { + return this.parts; + } } diff --git a/src/main/java/appeng/core/AppEng.java b/src/main/java/appeng/core/AppEng.java index 537b7c9f..1b43171e 100644 --- a/src/main/java/appeng/core/AppEng.java +++ b/src/main/java/appeng/core/AppEng.java @@ -18,6 +18,9 @@ package appeng.core; +import java.io.File; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nonnull; import appeng.core.crash.CrashInfo; import appeng.core.crash.IntegrationCrashEnhancement; @@ -46,203 +49,207 @@ import cpw.mods.fml.common.event.*; import cpw.mods.fml.common.network.NetworkRegistry; import net.minecraftforge.common.config.Configuration; -import javax.annotation.Nonnull; -import java.io.File; -import java.util.concurrent.TimeUnit; +@Mod( + modid = AppEng.MOD_ID, + acceptedMinecraftVersions = "[1.7.10]", + name = AppEng.MOD_NAME, + version = AEConfig.VERSION, + dependencies = AppEng.MOD_DEPENDENCIES, + guiFactory = "appeng.client.gui.config.AEConfigGuiFactory" +) +public final class AppEng { + public static final String MOD_ID = "appliedenergistics2"; + public static final String MOD_NAME = "Applied Energistics 2"; + public static final String MOD_DEPENDENCIES = + // a few mods, AE should load after, probably. + // required-after:AppliedEnergistics2API|all; + // "after:gregtech_addon;after:Mekanism;after:IC2;after:ThermalExpansion;after:BuildCraft|Core;" + // + + // depend on version of forge used for build. + "after:appliedenergistics2-core;" + + "required-after:Forge@[" // require forge. + + net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion + + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion + + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion + + net.minecraftforge.common.ForgeVersion.buildVersion + ",)"; // buildVersion -@Mod( modid = AppEng.MOD_ID, acceptedMinecraftVersions = "[1.7.10]", name = AppEng.MOD_NAME, version = AEConfig.VERSION, dependencies = AppEng.MOD_DEPENDENCIES, guiFactory = "appeng.client.gui.config.AEConfigGuiFactory" ) -public final class AppEng -{ - public static final String MOD_ID = "appliedenergistics2"; - public static final String MOD_NAME = "Applied Energistics 2"; - public static final String MOD_DEPENDENCIES = - // a few mods, AE should load after, probably. - // required-after:AppliedEnergistics2API|all; - // "after:gregtech_addon;after:Mekanism;after:IC2;after:ThermalExpansion;after:BuildCraft|Core;" + + @Nonnull + private static final AppEng INSTANCE = new AppEng(); - // depend on version of forge used for build. - "after:appliedenergistics2-core;" + "required-after:Forge@[" // require forge. - + net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion - + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion - + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion - + net.minecraftforge.common.ForgeVersion.buildVersion + ",)"; // buildVersion + private final Registration registration; - @Nonnull - private static final AppEng INSTANCE = new AppEng(); + private File configDirectory; + private CustomRecipeConfig customRecipeConfig; - private final Registration registration; + /** + * Folder for recipes + *

+ * used for CSV item names and the recipes + */ + private File recipeDirectory; - private File configDirectory; - private CustomRecipeConfig customRecipeConfig; + /** + * determined in pre-init but used in init + */ + private ExportConfig exportConfig; - /** - * Folder for recipes - *

- * used for CSV item names and the recipes - */ - private File recipeDirectory; + AppEng() { + FMLCommonHandler.instance().registerCrashCallable( + new ModCrashEnhancement(CrashInfo.MOD_VERSION) + ); - /** - * determined in pre-init but used in init - */ - private ExportConfig exportConfig; + this.registration = new Registration(); + } - AppEng() - { - FMLCommonHandler.instance().registerCrashCallable( new ModCrashEnhancement( CrashInfo.MOD_VERSION ) ); + @Nonnull + @Mod.InstanceFactory + public static AppEng instance() { + return INSTANCE; + } - this.registration = new Registration(); - } + @Nonnull + public final Registration getRegistration() { + return this.registration; + } - @Nonnull - @Mod.InstanceFactory - public static AppEng instance() - { - return INSTANCE; - } + @EventHandler + private void preInit(final FMLPreInitializationEvent event) { + if (!Loader.isModLoaded("appliedenergistics2-core")) { + CommonHelper.proxy.missingCoreMod(); + } - @Nonnull - public final Registration getRegistration() - { - return this.registration; - } + final Stopwatch watch = Stopwatch.createStarted(); + this.configDirectory = new File( + event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2" + ); + this.recipeDirectory = new File(this.configDirectory, "recipes"); - @EventHandler - private void preInit( final FMLPreInitializationEvent event ) - { - if( !Loader.isModLoaded( "appliedenergistics2-core" ) ) - { - CommonHelper.proxy.missingCoreMod(); - } + 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"); + final File recipeFile = new File(this.configDirectory, "CustomRecipes.cfg"); + final Configuration recipeConfiguration = new Configuration(recipeFile); - final Stopwatch watch = Stopwatch.createStarted(); - this.configDirectory = new File( event.getModConfigurationDirectory().getPath(), "AppliedEnergistics2" ); - this.recipeDirectory = new File( this.configDirectory, "recipes" ); + AEConfig.instance = new AEConfig(configFile); + FacadeConfig.instance = new FacadeConfig(facadeFile); + final VersionCheckerConfig versionCheckerConfig + = new VersionCheckerConfig(versionFile); + this.customRecipeConfig = new CustomRecipeForgeConfiguration(recipeConfiguration); + this.exportConfig = new ForgeExportConfig(recipeConfiguration); - 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" ); - final File recipeFile = new File( this.configDirectory, "CustomRecipes.cfg" ); - final Configuration recipeConfiguration = new Configuration( recipeFile ); + AELog.info("Pre Initialization ( started )"); - AEConfig.instance = new AEConfig( configFile ); - FacadeConfig.instance = new FacadeConfig( facadeFile ); - final VersionCheckerConfig versionCheckerConfig = new VersionCheckerConfig( versionFile ); - this.customRecipeConfig = new CustomRecipeForgeConfiguration( recipeConfiguration ); - this.exportConfig = new ForgeExportConfig( recipeConfiguration ); + CreativeTab.init(); + if (AEConfig.instance.isFeatureEnabled(AEFeature.Facades)) { + CreativeTabFacade.init(); + } - AELog.info( "Pre Initialization ( started )" ); + if (Platform.isClient()) { + CommonHelper.proxy.init(); + } - CreativeTab.init(); - if( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) ) - { - CreativeTabFacade.init(); - } + this.registration.preInitialize(event); - if( Platform.isClient() ) - { - CommonHelper.proxy.init(); - } + if (versionCheckerConfig.isVersionCheckingEnabled()) { + final VersionChecker versionChecker + = new VersionChecker(versionCheckerConfig); + final Thread versionCheckerThread = new Thread(versionChecker); - this.registration.preInitialize( event ); + this.startService("AE2 VersionChecker", versionCheckerThread); + } - if( versionCheckerConfig.isVersionCheckingEnabled() ) - { - final VersionChecker versionChecker = new VersionChecker( versionCheckerConfig ); - final Thread versionCheckerThread = new Thread( versionChecker ); + AELog.info( + "Pre Initialization ( ended after " + watch.elapsed(TimeUnit.MILLISECONDS) + + "ms )" + ); + } - this.startService( "AE2 VersionChecker", versionCheckerThread ); - } + private void startService(final String serviceName, final Thread thread) { + thread.setName(serviceName); + thread.setPriority(Thread.MIN_PRIORITY); - AELog.info( "Pre Initialization ( ended after " + watch.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } + AELog.info("Starting " + serviceName); + thread.start(); + } - private void startService( final String serviceName, final Thread thread ) - { - thread.setName( serviceName ); - thread.setPriority( Thread.MIN_PRIORITY ); + @EventHandler + private void init(final FMLInitializationEvent event) { + final Stopwatch start = Stopwatch.createStarted(); + AELog.info("Initialization ( started )"); - AELog.info( "Starting " + serviceName ); - thread.start(); - } + if (this.exportConfig.isExportingItemNamesEnabled()) { + if (FMLCommonHandler.instance().getSide().isClient()) { + final ExportProcess process + = new ExportProcess(this.recipeDirectory, this.exportConfig); + final Thread exportProcessThread = new Thread(process); - @EventHandler - private void init( final FMLInitializationEvent event ) - { - final Stopwatch start = Stopwatch.createStarted(); - AELog.info( "Initialization ( started )" ); + this.startService("AE2 CSV Export", exportProcessThread); + } else { + AELog.info( + "Disabling item.csv export for custom recipes, since creative tab information is only available on the client." + ); + } + } - if( this.exportConfig.isExportingItemNamesEnabled() ) - { - if( FMLCommonHandler.instance().getSide().isClient() ) - { - final ExportProcess process = new ExportProcess( this.recipeDirectory, this.exportConfig ); - final Thread exportProcessThread = new Thread( process ); + this.registration.initialize( + event, this.recipeDirectory, this.customRecipeConfig + ); + IntegrationRegistry.INSTANCE.init(); - this.startService( "AE2 CSV Export", exportProcessThread ); - } - else - { - AELog.info( "Disabling item.csv export for custom recipes, since creative tab information is only available on the client." ); - } - } + AELog.info( + "Initialization ( ended after " + start.elapsed(TimeUnit.MILLISECONDS) + + "ms )" + ); + } - this.registration.initialize( event, this.recipeDirectory, this.customRecipeConfig ); - IntegrationRegistry.INSTANCE.init(); + @EventHandler + private void postInit(final FMLPostInitializationEvent event) { + final Stopwatch start = Stopwatch.createStarted(); + AELog.info("Post Initialization ( started )"); - AELog.info( "Initialization ( ended after " + start.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } + this.registration.postInit(event); + IntegrationRegistry.INSTANCE.postInit(); + FMLCommonHandler.instance().registerCrashCallable(new IntegrationCrashEnhancement( + )); - @EventHandler - private void postInit( final FMLPostInitializationEvent event ) - { - final Stopwatch start = Stopwatch.createStarted(); - AELog.info( "Post Initialization ( started )" ); + CommonHelper.proxy.postInit(); + AEConfig.instance.save(); - this.registration.postInit( event ); - IntegrationRegistry.INSTANCE.postInit(); - FMLCommonHandler.instance().registerCrashCallable( new IntegrationCrashEnhancement() ); + NetworkRegistry.INSTANCE.registerGuiHandler(this, GuiBridge.GUI_Handler); + NetworkHandler.instance = new NetworkHandler("AE2"); - CommonHelper.proxy.postInit(); - AEConfig.instance.save(); + AELog.info( + "Post Initialization ( ended after " + start.elapsed(TimeUnit.MILLISECONDS) + + "ms )" + ); + } - NetworkRegistry.INSTANCE.registerGuiHandler( this, GuiBridge.GUI_Handler ); - NetworkHandler.instance = new NetworkHandler( "AE2" ); + @EventHandler + private void handleIMCEvent(final FMLInterModComms.IMCEvent event) { + final IMCHandler imcHandler = new IMCHandler(); - AELog.info( "Post Initialization ( ended after " + start.elapsed( TimeUnit.MILLISECONDS ) + "ms )" ); - } + imcHandler.handleIMCEvent(event); + } - @EventHandler - private void handleIMCEvent( final FMLInterModComms.IMCEvent event ) - { - final IMCHandler imcHandler = new IMCHandler(); + @EventHandler + private void serverAboutToStart(final FMLServerAboutToStartEvent evt) { + WorldData.onServerAboutToStart(); + } - imcHandler.handleIMCEvent( event ); - } + @EventHandler + private void serverStopping(final FMLServerStoppingEvent event) { + WorldData.instance().onServerStopping(); + } - @EventHandler - private void serverAboutToStart( final FMLServerAboutToStartEvent evt ) - { - WorldData.onServerAboutToStart(); - } + @EventHandler + private void serverStopped(final FMLServerStoppedEvent event) { + WorldData.instance().onServerStoppped(); + TickHandler.INSTANCE.shutdown(); + } - @EventHandler - private void serverStopping( final FMLServerStoppingEvent event ) - { - WorldData.instance().onServerStopping(); - } - - @EventHandler - private void serverStopped( final FMLServerStoppedEvent event ) - { - WorldData.instance().onServerStoppped(); - TickHandler.INSTANCE.shutdown(); - } - - @EventHandler - private void serverStarting( final FMLServerStartingEvent evt ) - { - evt.registerServerCommand( new AECommand( evt.getServer() ) ); - } + @EventHandler + private void serverStarting(final FMLServerStartingEvent evt) { + evt.registerServerCommand(new AECommand(evt.getServer())); + } } diff --git a/src/main/java/appeng/core/CommonHelper.java b/src/main/java/appeng/core/CommonHelper.java index 9d2f25b8..68cad5af 100644 --- a/src/main/java/appeng/core/CommonHelper.java +++ b/src/main/java/appeng/core/CommonHelper.java @@ -18,6 +18,8 @@ package appeng.core; +import java.util.List; +import java.util.Random; import appeng.api.parts.CableRenderMode; import appeng.block.AEBaseBlock; @@ -29,41 +31,53 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -import java.util.List; -import java.util.Random; +public abstract class CommonHelper { + @SidedProxy( + clientSide = "appeng.client.ClientHelper", + serverSide = "appeng.server.ServerHelper" + ) + public static CommonHelper proxy; + public abstract void init(); -public abstract class CommonHelper -{ + public abstract World getWorld(); - @SidedProxy( clientSide = "appeng.client.ClientHelper", serverSide = "appeng.server.ServerHelper" ) - public static CommonHelper proxy; + public abstract void bindTileEntitySpecialRenderer(Class tile, AEBaseBlock blk); - public abstract void init(); + public abstract List getPlayers(); - public abstract World getWorld(); + public abstract void sendToAllNearExcept( + EntityPlayer p, + double x, + double y, + double z, + double dist, + World w, + AppEngPacket packet + ); - public abstract void bindTileEntitySpecialRenderer( Class tile, AEBaseBlock blk ); + public abstract void spawnEffect( + EffectType effect, + World worldObj, + double posX, + double posY, + double posZ, + Object extra + ); - public abstract List getPlayers(); + public abstract boolean shouldAddParticles(Random r); - public abstract void sendToAllNearExcept( EntityPlayer p, double x, double y, double z, double dist, World w, AppEngPacket packet ); + public abstract MovingObjectPosition getMOP(); - public abstract void spawnEffect( EffectType effect, World worldObj, double posX, double posY, double posZ, Object extra ); + public abstract void doRenderItem(ItemStack itemstack, World w); - public abstract boolean shouldAddParticles( Random r ); + public abstract void postInit(); - public abstract MovingObjectPosition getMOP(); + public abstract CableRenderMode getRenderMode(); - public abstract void doRenderItem( ItemStack itemstack, World w ); + public abstract void triggerUpdates(); - public abstract void postInit(); + public abstract void updateRenderMode(EntityPlayer player); - public abstract CableRenderMode getRenderMode(); - - public abstract void triggerUpdates(); - - public abstract void updateRenderMode( EntityPlayer player ); - - public abstract void missingCoreMod(); + public abstract void missingCoreMod(); } diff --git a/src/main/java/appeng/core/CreativeTab.java b/src/main/java/appeng/core/CreativeTab.java index c61f8844..51f31de9 100644 --- a/src/main/java/appeng/core/CreativeTab.java +++ b/src/main/java/appeng/core/CreativeTab.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.AEApi; import appeng.api.definitions.*; import net.minecraft.creativetab.CreativeTabs; @@ -26,48 +25,48 @@ import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public final class CreativeTab extends CreativeTabs { + public static CreativeTab instance = null; -public final class CreativeTab extends CreativeTabs -{ - public static CreativeTab instance = null; + public CreativeTab() { + super("appliedenergistics2"); + } - public CreativeTab() - { - super( "appliedenergistics2" ); - } + static void init() { + instance = new CreativeTab(); + } - static void init() - { - instance = new CreativeTab(); - } + @Override + public Item getTabIconItem() { + return this.getIconItemStack().getItem(); + } - @Override - public Item getTabIconItem() - { - return this.getIconItemStack().getItem(); - } + @Override + public ItemStack getIconItemStack() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + final IMaterials materials = definitions.materials(); - @Override - public ItemStack getIconItemStack() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - final IMaterials materials = definitions.materials(); + return this.findFirst( + blocks.controller(), + blocks.chest(), + blocks.cellWorkbench(), + blocks.fluix(), + items.cell1k(), + items.networkTool(), + materials.fluixCrystal(), + materials.certusQuartzCrystal() + ); + } - return this.findFirst( blocks.controller(), blocks.chest(), blocks.cellWorkbench(), blocks.fluix(), items.cell1k(), items.networkTool(), materials.fluixCrystal(), materials.certusQuartzCrystal() ); - } + private ItemStack findFirst(final IItemDefinition... choices) { + for (final IItemDefinition definition : choices) { + for (final ItemStack definitionStack : definition.maybeStack(1).asSet()) { + return definitionStack; + } + } - private ItemStack findFirst( final IItemDefinition... choices ) - { - for( final IItemDefinition definition : choices ) - { - for( final ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) - { - return definitionStack; - } - } - - return new ItemStack( Blocks.chest ); - } + return new ItemStack(Blocks.chest); + } } \ No newline at end of file diff --git a/src/main/java/appeng/core/CreativeTabFacade.java b/src/main/java/appeng/core/CreativeTabFacade.java index 3dc5d342..1ecefb61 100644 --- a/src/main/java/appeng/core/CreativeTabFacade.java +++ b/src/main/java/appeng/core/CreativeTabFacade.java @@ -18,7 +18,6 @@ package appeng.core; - import appeng.api.AEApi; import appeng.items.parts.ItemFacade; import com.google.common.base.Optional; @@ -27,37 +26,30 @@ import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public final class CreativeTabFacade extends CreativeTabs { + public static CreativeTabFacade instance = null; -public final class CreativeTabFacade extends CreativeTabs -{ + public CreativeTabFacade() { + super("appliedenergistics2.facades"); + } - public static CreativeTabFacade instance = null; + static void init() { + instance = new CreativeTabFacade(); + } - public CreativeTabFacade() - { - super( "appliedenergistics2.facades" ); - } + @Override + public Item getTabIconItem() { + return this.getIconItemStack().getItem(); + } - static void init() - { - instance = new CreativeTabFacade(); - } + @Override + public ItemStack getIconItemStack() { + final Optional maybeFacade + = AEApi.instance().definitions().items().facade().maybeItem(); + if (maybeFacade.isPresent()) { + return ((ItemFacade) maybeFacade.get()).getCreativeTabIcon(); + } - @Override - public Item getTabIconItem() - { - return this.getIconItemStack().getItem(); - } - - @Override - public ItemStack getIconItemStack() - { - final Optional maybeFacade = AEApi.instance().definitions().items().facade().maybeItem(); - if( maybeFacade.isPresent() ) - { - return ( (ItemFacade) maybeFacade.get() ).getCreativeTabIcon(); - } - - return new ItemStack( Blocks.planks ); - } + return new ItemStack(Blocks.planks); + } } \ 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 a95613cd..36f99bf5 100644 --- a/src/main/java/appeng/core/FacadeConfig.java +++ b/src/main/java/appeng/core/FacadeConfig.java @@ -18,62 +18,60 @@ package appeng.core; +import java.io.File; +import java.lang.reflect.Field; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; import net.minecraft.block.Block; import net.minecraftforge.common.config.Configuration; -import java.io.File; -import java.lang.reflect.Field; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +public class FacadeConfig extends Configuration { + public static FacadeConfig instance; + private final Pattern replacementPattern; + public FacadeConfig(final File facadeFile) { + super(facadeFile); + this.replacementPattern = Pattern.compile("[^a-zA-Z0-9]"); + } -public class FacadeConfig extends Configuration -{ + public boolean + checkEnabled(final Block id, final int metadata, final boolean automatic) { + if (id == null) { + return false; + } - public static FacadeConfig instance; - private final Pattern replacementPattern; + final UniqueIdentifier blk = GameRegistry.findUniqueIdentifierFor(id); + if (blk == null) { + for (final Field f : Block.class.getFields()) { + try { + if (f.get(Block.class) == id) { + return this + .get( + "minecraft", + f.getName() + (metadata == 0 ? "" : "." + metadata), + automatic + ) + .getBoolean(automatic); + } + } catch (final Throwable e) { + // :P + } + } + } else { + final Matcher mod = this.replacementPattern.matcher(blk.modId); + final Matcher name = this.replacementPattern.matcher(blk.name); + return this + .get( + mod.replaceAll(""), + name.replaceAll("") + (metadata == 0 ? "" : "." + metadata), + automatic + ) + .getBoolean(automatic); + } - public FacadeConfig( final File facadeFile ) - { - super( facadeFile ); - this.replacementPattern = Pattern.compile( "[^a-zA-Z0-9]" ); - } - - public boolean checkEnabled( final Block id, final int metadata, final boolean automatic ) - { - if( id == null ) - { - return false; - } - - final UniqueIdentifier blk = GameRegistry.findUniqueIdentifierFor( id ); - if( blk == null ) - { - for( final Field f : Block.class.getFields() ) - { - try - { - if( f.get( Block.class ) == id ) - { - return this.get( "minecraft", f.getName() + ( metadata == 0 ? "" : "." + metadata ), automatic ).getBoolean( automatic ); - } - } - catch( final Throwable e ) - { - // :P - } - } - } - else - { - final Matcher mod = this.replacementPattern.matcher( blk.modId ); - final Matcher name = this.replacementPattern.matcher( blk.name ); - return this.get( mod.replaceAll( "" ), name.replaceAll( "" ) + ( metadata == 0 ? "" : "." + metadata ), automatic ).getBoolean( automatic ); - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/core/FeatureHandlerRegistry.java b/src/main/java/appeng/core/FeatureHandlerRegistry.java index 8494160d..dfacdaf6 100644 --- a/src/main/java/appeng/core/FeatureHandlerRegistry.java +++ b/src/main/java/appeng/core/FeatureHandlerRegistry.java @@ -18,24 +18,19 @@ package appeng.core; - -import appeng.core.features.IFeatureHandler; - import java.util.LinkedHashSet; import java.util.Set; +import appeng.core.features.IFeatureHandler; -public final class FeatureHandlerRegistry -{ - private final Set registry = new LinkedHashSet(); +public final class FeatureHandlerRegistry { + private final Set registry = new LinkedHashSet(); - public void addFeatureHandler( final IFeatureHandler feature ) - { - this.registry.add( feature ); - } + public void addFeatureHandler(final IFeatureHandler feature) { + this.registry.add(feature); + } - Set getRegisteredFeatureHandlers() - { - return this.registry; - } + Set getRegisteredFeatureHandlers() { + return this.registry; + } } diff --git a/src/main/java/appeng/core/FeatureRegistry.java b/src/main/java/appeng/core/FeatureRegistry.java index aff90ceb..8b478b0c 100644 --- a/src/main/java/appeng/core/FeatureRegistry.java +++ b/src/main/java/appeng/core/FeatureRegistry.java @@ -18,24 +18,19 @@ package appeng.core; - -import appeng.core.features.IAEFeature; - import java.util.LinkedHashSet; import java.util.Set; +import appeng.core.features.IAEFeature; -public final class FeatureRegistry -{ - private final Set registry = new LinkedHashSet(); +public final class FeatureRegistry { + private final Set registry = new LinkedHashSet(); - public void addFeature( final IAEFeature feature ) - { - this.registry.add( feature ); - } + public void addFeature(final IAEFeature feature) { + this.registry.add(feature); + } - Set getRegisteredFeatures() - { - return this.registry; - } + Set getRegisteredFeatures() { + return this.registry; + } } diff --git a/src/main/java/appeng/core/IMCHandler.java b/src/main/java/appeng/core/IMCHandler.java index d61ccc95..236a06db 100644 --- a/src/main/java/appeng/core/IMCHandler.java +++ b/src/main/java/appeng/core/IMCHandler.java @@ -18,17 +18,15 @@ package appeng.core; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; import appeng.api.config.TunnelType; import appeng.core.api.IIMCProcessor; import appeng.core.api.imc.*; import cpw.mods.fml.common.event.FMLInterModComms; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - /** * Handles the delegation of the corresponding IMC messages to the suitable IMC processors * @@ -36,63 +34,60 @@ import java.util.Map; * @version rv3 - 10.08.2015 * @since rv1 */ -public class IMCHandler -{ - private static final int INITIAL_PROCESSORS_CAPACITY = 20; +public class IMCHandler { + private static final int INITIAL_PROCESSORS_CAPACITY = 20; - /** - * Contains the processors, - *

- * is mutable, but write access only by the constructor - */ - private final Map processors; + /** + * Contains the processors, + *

+ * is mutable, but write access only by the constructor + */ + private final Map processors; - /** - * Initializes the processors - */ - public IMCHandler() - { - this.processors = new HashMap( INITIAL_PROCESSORS_CAPACITY ); + /** + * Initializes the processors + */ + public IMCHandler() { + this.processors = new HashMap(INITIAL_PROCESSORS_CAPACITY); - this.processors.put( "blacklist-block-spatial", new IMCBlackListSpatial() ); - this.processors.put( "whitelist-spatial", new IMCSpatial() ); - this.processors.put( "add-grindable", new IMCGrinder() ); - this.processors.put( "add-mattercannon-ammo", new IMCMatterCannon() ); + this.processors.put("blacklist-block-spatial", new IMCBlackListSpatial()); + this.processors.put("whitelist-spatial", new IMCSpatial()); + this.processors.put("add-grindable", new IMCGrinder()); + this.processors.put("add-mattercannon-ammo", new IMCMatterCannon()); - for( final TunnelType type : TunnelType.values() ) - { - this.processors.put( "add-p2p-attunement-" + type.name().replace( '_', '-' ).toLowerCase( Locale.ENGLISH ), new IMCP2PAttunement() ); - } - } + for (final TunnelType type : TunnelType.values()) { + this.processors.put( + "add-p2p-attunement-" + + type.name().replace('_', '-').toLowerCase(Locale.ENGLISH), + new IMCP2PAttunement() + ); + } + } - /** - * Tries to find every message matching the internal IMC keys. When found the corresponding handler will process the attached message. - * - * @param event Event carrying the identifier and message for the handlers - */ - void handleIMCEvent( final FMLInterModComms.IMCEvent event ) - { - for( final FMLInterModComms.IMCMessage message : event.getMessages() ) - { - final String key = message.key; + /** + * Tries to find every message matching the internal IMC keys. When found the + * corresponding handler will process the attached message. + * + * @param event Event carrying the identifier and message for the handlers + */ + void handleIMCEvent(final FMLInterModComms.IMCEvent event) { + for (final FMLInterModComms.IMCMessage message : event.getMessages()) { + final String key = message.key; - try - { - final IIMCProcessor handler = this.processors.get( key ); - if( handler != null ) - { - handler.process( message ); - } - else - { - throw new IllegalStateException( "Invalid IMC Called: " + key ); - } - } - catch( final Exception t ) - { - AELog.warn( "Problem detected when processing IMC " + key + " from " + message.getSender() ); - AELog.debug( t ); - } - } - } + try { + final IIMCProcessor handler = this.processors.get(key); + if (handler != null) { + handler.process(message); + } else { + throw new IllegalStateException("Invalid IMC Called: " + key); + } + } catch (final Exception t) { + AELog.warn( + "Problem detected when processing IMC " + key + " from " + + message.getSender() + ); + AELog.debug(t); + } + } + } } diff --git a/src/main/java/appeng/core/RecipeLoader.java b/src/main/java/appeng/core/RecipeLoader.java index a5208f05..5e7f7791 100644 --- a/src/main/java/appeng/core/RecipeLoader.java +++ b/src/main/java/appeng/core/RecipeLoader.java @@ -18,6 +18,10 @@ package appeng.core; +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import javax.annotation.Nonnull; import appeng.api.recipes.IRecipeHandler; import appeng.recipes.CustomRecipeConfig; @@ -27,88 +31,86 @@ import appeng.recipes.loader.RecipeResourceCopier; import com.google.common.base.Preconditions; import org.apache.commons.io.FileUtils; -import javax.annotation.Nonnull; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; - - /** - * handles the decision if recipes should be loaded from jar, loaded from file system or force copied from jar + * handles the decision if recipes should be loaded from jar, loaded from file system or + * force copied from jar * * @author thatsIch * @version rv3 - 12.05.2015 * @since rv3 12.05.2015 */ -public class RecipeLoader implements Runnable -{ - /** - * recipe path in the jar - */ - private static final String ASSETS_RECIPE_PATH = "/assets/appliedenergistics2/recipes/"; +public class RecipeLoader implements Runnable { + /** + * recipe path in the jar + */ + private static final String ASSETS_RECIPE_PATH + = "/assets/appliedenergistics2/recipes/"; - @Nonnull - private final IRecipeHandler handler; - @Nonnull - private final CustomRecipeConfig config; - @Nonnull - private final File recipeDirectory; + @Nonnull + private final IRecipeHandler handler; + @Nonnull + private final CustomRecipeConfig config; + @Nonnull + private final File recipeDirectory; - /** - * @param config configuration for the knowledge how to handle the loading process - * @param handler handler to load the recipes - * @throws NullPointerException if handler is null - */ - public RecipeLoader( @Nonnull final File recipeDirectory, @Nonnull final CustomRecipeConfig config, @Nonnull final IRecipeHandler handler ) - { - this.recipeDirectory = Preconditions.checkNotNull( recipeDirectory ); - Preconditions.checkArgument( !recipeDirectory.isFile() ); - this.config = Preconditions.checkNotNull( config ); - this.handler = Preconditions.checkNotNull( handler ); - } + /** + * @param config configuration for the knowledge how to handle the loading process + * @param handler handler to load the recipes + * @throws NullPointerException if handler is null + */ + public RecipeLoader( + @Nonnull final File recipeDirectory, + @Nonnull final CustomRecipeConfig config, + @Nonnull final IRecipeHandler handler + ) { + this.recipeDirectory = Preconditions.checkNotNull(recipeDirectory); + Preconditions.checkArgument(!recipeDirectory.isFile()); + this.config = Preconditions.checkNotNull(config); + this.handler = Preconditions.checkNotNull(handler); + } - @Override - public final void run() - { - if( this.config.isEnabled() ) - { - // setup copying - final RecipeResourceCopier copier = new RecipeResourceCopier( "assets/appliedenergistics2/recipes/" ); + @Override + public final void run() { + if (this.config.isEnabled()) { + // setup copying + final RecipeResourceCopier copier + = new RecipeResourceCopier("assets/appliedenergistics2/recipes/"); - final File generatedRecipesDir = new File( this.recipeDirectory, "generated" ); - final File userRecipesDir = new File( this.recipeDirectory, "user" ); + final File generatedRecipesDir = new File(this.recipeDirectory, "generated"); + final File userRecipesDir = new File(this.recipeDirectory, "user"); - // generates generated and user recipes dir - // will clean the generated every time to keep it up to date - // copies over the recipes in the jar over to the generated folder - // copies over the readmes - try - { - FileUtils.forceMkdir( generatedRecipesDir ); - FileUtils.forceMkdir( userRecipesDir ); - FileUtils.cleanDirectory( generatedRecipesDir ); + // generates generated and user recipes dir + // will clean the generated every time to keep it up to date + // copies over the recipes in the jar over to the generated folder + // copies over the readmes + try { + FileUtils.forceMkdir(generatedRecipesDir); + FileUtils.forceMkdir(userRecipesDir); + FileUtils.cleanDirectory(generatedRecipesDir); - copier.copyTo( ".recipe", generatedRecipesDir ); - copier.copyTo( ".html", this.recipeDirectory ); + copier.copyTo(".recipe", generatedRecipesDir); + copier.copyTo(".html", this.recipeDirectory); - // parse recipes prioritising the user scripts by using the generated as template - this.handler.parseRecipes( new ConfigLoader( generatedRecipesDir, userRecipesDir ), "index.recipe" ); - } - // on failure use jar parsing - catch( final IOException e ) - { - AELog.debug( e ); - this.handler.parseRecipes( new JarLoader( ASSETS_RECIPE_PATH ), "index.recipe" ); - } - catch( final URISyntaxException e ) - { - AELog.debug( e ); - this.handler.parseRecipes( new JarLoader( ASSETS_RECIPE_PATH ), "index.recipe" ); - } - } - else - { - this.handler.parseRecipes( new JarLoader( ASSETS_RECIPE_PATH ), "index.recipe" ); - } - } + // parse recipes prioritising the user scripts by using the generated as + // template + this.handler.parseRecipes( + new ConfigLoader(generatedRecipesDir, userRecipesDir), "index.recipe" + ); + } + // on failure use jar parsing + catch (final IOException e) { + AELog.debug(e); + this.handler.parseRecipes( + new JarLoader(ASSETS_RECIPE_PATH), "index.recipe" + ); + } catch (final URISyntaxException e) { + AELog.debug(e); + this.handler.parseRecipes( + new JarLoader(ASSETS_RECIPE_PATH), "index.recipe" + ); + } + } else { + this.handler.parseRecipes(new JarLoader(ASSETS_RECIPE_PATH), "index.recipe"); + } + } } diff --git a/src/main/java/appeng/core/Registration.java b/src/main/java/appeng/core/Registration.java index 01b8ce8c..01e892d2 100644 --- a/src/main/java/appeng/core/Registration.java +++ b/src/main/java/appeng/core/Registration.java @@ -18,6 +18,8 @@ package appeng.core; +import java.io.File; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.IAppEngApi; @@ -87,650 +89,668 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.oredict.RecipeSorter; import net.minecraftforge.oredict.RecipeSorter.Category; -import javax.annotation.Nonnull; -import java.io.File; - - -public final class Registration -{ - private final RecipeHandler recipeHandler; - private final DefinitionConverter converter; - private BiomeGenBase storageBiome; - - Registration() - { - this.converter = new DefinitionConverter(); - this.recipeHandler = new RecipeHandler(); - } - - public BiomeGenBase getStorageBiome() - { - return this.storageBiome; - } - - void preInitialize( final FMLPreInitializationEvent event ) - { - this.registerSpatial( false ); - - final Api api = Api.INSTANCE; - final IRecipeHandlerRegistry recipeRegistry = api.registries().recipes(); - this.registerCraftHandlers( recipeRegistry ); - - RecipeSorter.register( "AE2-Facade", FacadeRecipe.class, Category.SHAPED, "" ); - RecipeSorter.register( "AE2-Shaped", ShapedRecipe.class, Category.SHAPED, "" ); - RecipeSorter.register( "AE2-Shapeless", ShapelessRecipe.class, Category.SHAPELESS, "" ); - - MinecraftForge.EVENT_BUS.register( OreDictionaryHandler.INSTANCE ); - - final ApiDefinitions definitions = api.definitions(); - - final IBlocks apiBlocks = definitions.blocks(); - final IItems apiItems = definitions.items(); - final IMaterials apiMaterials = definitions.materials(); - final IParts apiParts = definitions.parts(); - - final Items items = api.items(); - final Materials materials = api.materials(); - final Parts parts = api.parts(); - final Blocks blocks = api.blocks(); - - this.assignMaterials( materials, apiMaterials ); - this.assignParts( parts, apiParts ); - this.assignBlocks( blocks, apiBlocks ); - this.assignItems( items, apiItems ); - - // Register all detected handlers and features (items, blocks) in pre-init - for( final IFeatureHandler handler : definitions.getFeatureHandlerRegistry().getRegisteredFeatureHandlers() ) - { - handler.register(); - } - - for( final IAEFeature feature : definitions.getFeatureRegistry().getRegisteredFeatures() ) - { - feature.postInit(); - } - } - - private void registerSpatial( final boolean force ) - { - if( !AEConfig.instance.isFeatureEnabled( AEFeature.SpatialIO ) ) - { - return; - } - - final AEConfig config = AEConfig.instance; - - if( this.storageBiome == null ) - { - if( force && config.storageBiomeID == -1 ) - { - config.storageBiomeID = Platform.findEmpty( BiomeGenBase.getBiomeGenArray() ); - if( config.storageBiomeID == -1 ) - { - throw new IllegalStateException( "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 ) - { - this.storageBiome = new BiomeGenStorage( config.storageBiomeID ); - } - } - - if( config.storageProviderID != -1 ) - { - DimensionManager.registerProviderType( config.storageProviderID, StorageWorldProvider.class, false ); - } - - if( config.storageProviderID == -1 && force ) - { - config.storageProviderID = -11; - - while( !DimensionManager.registerProviderType( config.storageProviderID, StorageWorldProvider.class, false ) ) - { - config.storageProviderID--; - } - - config.save(); - } - } - - private void registerCraftHandlers( final IRecipeHandlerRegistry registry ) - { - registry.addNewSubItemResolver( new AEItemResolver() ); - - registry.addNewCraftHandler( "hccrusher", HCCrusher.class ); - registry.addNewCraftHandler( "mekcrusher", MekCrusher.class ); - registry.addNewCraftHandler( "mekechamber", MekEnrichment.class ); - registry.addNewCraftHandler( "grind", Grind.class ); - registry.addNewCraftHandler( "crusher", Crusher.class ); - registry.addNewCraftHandler( "grindfz", GrindFZ.class ); - registry.addNewCraftHandler( "pulverizer", Pulverizer.class ); - registry.addNewCraftHandler( "macerator", Macerator.class ); - - registry.addNewCraftHandler( "smelt", Smelt.class ); - registry.addNewCraftHandler( "inscribe", Inscribe.class ); - registry.addNewCraftHandler( "press", Press.class ); - - registry.addNewCraftHandler( "shaped", Shaped.class ); - registry.addNewCraftHandler( "shapeless", Shapeless.class ); - } - - /** - * Assigns materials from the new API to the old API - *

- * Uses direct cast, since its only a temporary solution anyways - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignMaterials( final Materials target, final IMaterials source ) - { - target.materialCell2SpatialPart = this.converter.of( source.cell2SpatialPart() ); - target.materialCell16SpatialPart = this.converter.of( source.cell16SpatialPart() ); - target.materialCell128SpatialPart = this.converter.of( source.cell128SpatialPart() ); - - target.materialSilicon = this.converter.of( source.silicon() ); - target.materialSkyDust = this.converter.of( source.skyDust() ); - - target.materialCalcProcessorPress = this.converter.of( source.calcProcessorPress() ); - target.materialEngProcessorPress = this.converter.of( source.engProcessorPress() ); - target.materialLogicProcessorPress = this.converter.of( source.logicProcessorPress() ); - - target.materialCalcProcessorPrint = this.converter.of( source.calcProcessorPrint() ); - target.materialEngProcessorPrint = this.converter.of( source.engProcessorPrint() ); - target.materialLogicProcessorPrint = this.converter.of( source.logicProcessorPrint() ); - - target.materialSiliconPress = this.converter.of( source.siliconPress() ); - target.materialSiliconPrint = this.converter.of( source.siliconPrint() ); - - target.materialNamePress = this.converter.of( source.namePress() ); - - target.materialLogicProcessor = this.converter.of( source.logicProcessor() ); - target.materialCalcProcessor = this.converter.of( source.calcProcessor() ); - target.materialEngProcessor = this.converter.of( source.engProcessor() ); - - target.materialBasicCard = this.converter.of( source.basicCard() ); - target.materialAdvCard = this.converter.of( source.advCard() ); - - target.materialPurifiedCertusQuartzCrystal = this.converter.of( source.purifiedCertusQuartzCrystal() ); - target.materialPurifiedNetherQuartzCrystal = this.converter.of( source.purifiedNetherQuartzCrystal() ); - target.materialPurifiedFluixCrystal = this.converter.of( source.purifiedFluixCrystal() ); - - target.materialCell1kPart = this.converter.of( source.cell1kPart() ); - target.materialCell4kPart = this.converter.of( source.cell4kPart() ); - target.materialCell16kPart = this.converter.of( source.cell16kPart() ); - target.materialCell64kPart = this.converter.of( source.cell64kPart() ); - target.materialEmptyStorageCell = this.converter.of( source.emptyStorageCell() ); - - target.materialCardRedstone = this.converter.of( source.cardRedstone() ); - target.materialCardSpeed = this.converter.of( source.cardSpeed() ); - target.materialCardCapacity = this.converter.of( source.cardCapacity() ); - target.materialCardFuzzy = this.converter.of( source.cardFuzzy() ); - target.materialCardInverter = this.converter.of( source.cardInverter() ); - target.materialCardCrafting = this.converter.of( source.cardCrafting() ); - - target.materialEnderDust = this.converter.of( source.enderDust() ); - target.materialFlour = this.converter.of( source.flour() ); - target.materialGoldDust = this.converter.of( source.goldDust() ); - target.materialIronDust = this.converter.of( source.ironDust() ); - target.materialFluixDust = this.converter.of( source.fluixDust() ); - target.materialCertusQuartzDust = this.converter.of( source.certusQuartzDust() ); - target.materialNetherQuartzDust = this.converter.of( source.netherQuartzDust() ); - - target.materialMatterBall = this.converter.of( source.matterBall() ); - target.materialIronNugget = this.converter.of( source.ironNugget() ); - - target.materialCertusQuartzCrystal = this.converter.of( source.certusQuartzCrystal() ); - target.materialCertusQuartzCrystalCharged = this.converter.of( source.certusQuartzCrystalCharged() ); - target.materialFluixCrystal = this.converter.of( source.fluixCrystal() ); - target.materialFluixPearl = this.converter.of( source.fluixPearl() ); - - target.materialWoodenGear = this.converter.of( source.woodenGear() ); - - target.materialWireless = this.converter.of( source.wireless() ); - target.materialWirelessBooster = this.converter.of( source.wirelessBooster() ); - - target.materialAnnihilationCore = this.converter.of( source.annihilationCore() ); - target.materialFormationCore = this.converter.of( source.formationCore() ); - - target.materialSingularity = this.converter.of( source.singularity() ); - target.materialQESingularity = this.converter.of( source.qESingularity() ); - target.materialBlankPattern = this.converter.of( source.blankPattern() ); - } - - /** - * Assigns parts from the new API to the old API - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignParts( final Parts target, final IParts source ) - { - target.partCableSmart = source.cableSmart(); - target.partCableCovered = source.cableCovered(); - target.partCableGlass = source.cableGlass(); - target.partCableDense = source.cableDense(); - // target.partLumenCableSmart = source.lumenCableSmart(); - // target.partLumenCableCovered = source.lumenCableCovered(); - // target.partLumenCableGlass = source.lumenCableGlass(); - // target.partLumenCableDense = source.lumenCableDense(); - target.partQuartzFiber = this.converter.of( source.quartzFiber() ); - target.partToggleBus = this.converter.of( source.toggleBus() ); - target.partInvertedToggleBus = this.converter.of( source.invertedToggleBus() ); - target.partStorageBus = this.converter.of( source.storageBus() ); - target.partImportBus = this.converter.of( source.importBus() ); - target.partExportBus = this.converter.of( source.exportBus() ); - target.partInterface = this.converter.of( source.iface() ); - target.partLevelEmitter = this.converter.of( source.levelEmitter() ); - target.partAnnihilationPlane = this.converter.of( source.annihilationPlane() ); - target.partFormationPlane = this.converter.of( source.formationPlane() ); - - target.partCableAnchor = this.converter.of( source.cableAnchor() ); - target.partP2PTunnelLight = target.partCableAnchor; - target.partP2PTunnelRF = target.partP2PTunnelLight; - target.partP2PTunnelEU = target.partP2PTunnelRF; - target.partP2PTunnelLiquids = target.partP2PTunnelEU; - target.partP2PTunnelItems = target.partP2PTunnelLiquids; - target.partP2PTunnelRedstone = target.partP2PTunnelItems; - target.partP2PTunnelME = target.partP2PTunnelRedstone; - target.partMonitor = this.converter.of( source.monitor() ); - target.partSemiDarkMonitor = this.converter.of( source.semiDarkMonitor() ); - target.partDarkMonitor = this.converter.of( source.darkMonitor() ); - target.partInterfaceTerminal = this.converter.of( source.interfaceTerminal() ); - target.partPatternTerminal = this.converter.of( source.patternTerminal() ); - target.partCraftingTerminal = this.converter.of( source.craftingTerminal() ); - target.partTerminal = this.converter.of( source.terminal() ); - target.partStorageMonitor = this.converter.of( source.storageMonitor() ); - target.partConversionMonitor = this.converter.of( source.conversionMonitor() ); - } - - /** - * Assigns blocks from the new API to the old API - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignBlocks( final Blocks target, final IBlocks source ) - { - target.blockMultiPart = this.converter.of( source.multiPart() ); - - target.blockCraftingUnit = this.converter.of( source.craftingUnit() ); - target.blockCraftingAccelerator = this.converter.of( source.craftingAccelerator() ); - target.blockCraftingMonitor = this.converter.of( source.craftingMonitor() ); - target.blockCraftingStorage1k = this.converter.of( source.craftingStorage1k() ); - target.blockCraftingStorage4k = this.converter.of( source.craftingStorage4k() ); - target.blockCraftingStorage16k = this.converter.of( source.craftingStorage16k() ); - target.blockCraftingStorage64k = this.converter.of( source.craftingStorage64k() ); - target.blockMolecularAssembler = this.converter.of( source.molecularAssembler() ); - - target.blockQuartzOre = this.converter.of( source.quartzOre() ); - target.blockQuartzOreCharged = this.converter.of( source.quartzOreCharged() ); - target.blockMatrixFrame = this.converter.of( source.matrixFrame() ); - target.blockQuartz = this.converter.of( source.quartz() ); - target.blockFluix = this.converter.of( source.fluix() ); - target.blockSkyStone = this.converter.of( source.skyStone() ); - target.blockSkyChest = this.converter.of( source.skyChest() ); - target.blockSkyCompass = this.converter.of( source.skyCompass() ); - - target.blockQuartzGlass = this.converter.of( source.quartzGlass() ); - target.blockQuartzVibrantGlass = this.converter.of( source.quartzVibrantGlass() ); - target.blockQuartzPillar = this.converter.of( source.quartzPillar() ); - target.blockQuartzChiseled = this.converter.of( source.quartzChiseled() ); - target.blockQuartzTorch = this.converter.of( source.quartzTorch() ); - target.blockLightDetector = this.converter.of( source.lightDetector() ); - target.blockCharger = this.converter.of( source.charger() ); - target.blockQuartzGrowthAccelerator = this.converter.of( source.quartzGrowthAccelerator() ); - - target.blockGrindStone = this.converter.of( source.grindStone() ); - target.blockCrankHandle = this.converter.of( source.crankHandle() ); - target.blockInscriber = this.converter.of( source.inscriber() ); - target.blockWireless = this.converter.of( source.wireless() ); - target.blockTinyTNT = this.converter.of( source.tinyTNT() ); - - target.blockQuantumRing = this.converter.of( source.quantumRing() ); - target.blockQuantumLink = this.converter.of( source.quantumLink() ); - - target.blockSpatialPylon = this.converter.of( source.spatialPylon() ); - target.blockSpatialIOPort = this.converter.of( source.spatialIOPort() ); - - target.blockController = this.converter.of( source.controller() ); - target.blockDrive = this.converter.of( source.drive() ); - target.blockChest = this.converter.of( source.chest() ); - target.blockInterface = this.converter.of( source.iface() ); - target.blockCellWorkbench = this.converter.of( source.cellWorkbench() ); - target.blockIOPort = this.converter.of( source.iOPort() ); - target.blockCondenser = this.converter.of( source.condenser() ); - target.blockEnergyAcceptor = this.converter.of( source.energyAcceptor() ); - target.blockVibrationChamber = this.converter.of( source.vibrationChamber() ); - - target.blockEnergyCell = this.converter.of( source.energyCell() ); - target.blockEnergyCellDense = this.converter.of( source.energyCellDense() ); - target.blockEnergyCellCreative = this.converter.of( source.energyCellCreative() ); - - target.blockSecurity = this.converter.of( source.security() ); - target.blockPaint = this.converter.of( source.paint() ); - } - - /** - * Assigns materials from the new API to the old API - * - * @param target old API - * @param source new API - * @deprecated to be removed when the public definition API is removed - */ - @Deprecated - private void assignItems( final Items target, final IItems source ) - { - target.itemCellCreative = this.converter.of( source.cellCreative() ); - target.itemViewCell = this.converter.of( source.viewCell() ); - target.itemEncodedPattern = this.converter.of( source.encodedPattern() ); - - target.itemCell1k = this.converter.of( source.cell1k() ); - target.itemCell4k = this.converter.of( source.cell4k() ); - target.itemCell16k = this.converter.of( source.cell16k() ); - target.itemCell64k = this.converter.of( source.cell64k() ); - - target.itemSpatialCell2 = this.converter.of( source.spatialCell2() ); - target.itemSpatialCell16 = this.converter.of( source.spatialCell16() ); - target.itemSpatialCell128 = this.converter.of( source.spatialCell128() ); - - target.itemCertusQuartzKnife = this.converter.of( source.certusQuartzKnife() ); - target.itemCertusQuartzWrench = this.converter.of( source.certusQuartzWrench() ); - target.itemCertusQuartzAxe = this.converter.of( source.certusQuartzAxe() ); - target.itemCertusQuartzHoe = this.converter.of( source.certusQuartzHoe() ); - target.itemCertusQuartzPick = this.converter.of( source.certusQuartzPick() ); - target.itemCertusQuartzShovel = this.converter.of( source.certusQuartzShovel() ); - target.itemCertusQuartzSword = this.converter.of( source.certusQuartzSword() ); - - target.itemNetherQuartzKnife = this.converter.of( source.netherQuartzKnife() ); - target.itemNetherQuartzWrench = this.converter.of( source.netherQuartzWrench() ); - target.itemNetherQuartzAxe = this.converter.of( source.netherQuartzAxe() ); - target.itemNetherQuartzHoe = this.converter.of( source.netherQuartzHoe() ); - target.itemNetherQuartzPick = this.converter.of( source.netherQuartzPick() ); - target.itemNetherQuartzShovel = this.converter.of( source.netherQuartzShovel() ); - target.itemNetherQuartzSword = this.converter.of( source.netherQuartzSword() ); - - target.itemMassCannon = this.converter.of( source.massCannon() ); - target.itemMemoryCard = this.converter.of( source.memoryCard() ); - target.itemChargedStaff = this.converter.of( source.chargedStaff() ); - target.itemEntropyManipulator = this.converter.of( source.entropyManipulator() ); - target.itemColorApplicator = this.converter.of( source.colorApplicator() ); - - target.itemWirelessTerminal = this.converter.of( source.wirelessTerminal() ); - target.itemNetworkTool = this.converter.of( source.networkTool() ); - target.itemPortableCell = this.converter.of( source.portableCell() ); - target.itemBiometricCard = this.converter.of( source.biometricCard() ); - - target.itemFacade = this.converter.of( source.facade() ); - target.itemCrystalSeed = this.converter.of( source.crystalSeed() ); - - target.itemPaintBall = source.coloredPaintBall(); - target.itemLumenPaintBall = source.coloredLumenPaintBall(); - } - - void initialize( @Nonnull final FMLInitializationEvent event, @Nonnull final File recipeDirectory, @Nonnull final CustomRecipeConfig customRecipeConfig ) - { - Preconditions.checkNotNull( event ); - Preconditions.checkNotNull( recipeDirectory ); - Preconditions.checkArgument( !recipeDirectory.isFile() ); - Preconditions.checkNotNull( customRecipeConfig ); - - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); - final IRegistryContainer registries = api.registries(); - - // Perform ore camouflage! - ItemMultiMaterial.instance.makeUnique(); - - final Runnable recipeLoader = new RecipeLoader( recipeDirectory, customRecipeConfig, this.recipeHandler ); - recipeLoader.run(); - - partHelper.registerNewLayer( "appeng.parts.layers.LayerISidedInventory", "net.minecraft.inventory.ISidedInventory" ); - partHelper.registerNewLayer( "appeng.parts.layers.LayerIFluidHandler", "net.minecraftforge.fluids.IFluidHandler" ); - partHelper.registerNewLayer( "appeng.parts.layers.LayerITileStorageMonitorable", "appeng.api.implementations.tiles.ITileStorageMonitorable" ); - - FMLCommonHandler.instance().bus().register( TickHandler.INSTANCE ); - MinecraftForge.EVENT_BUS.register( TickHandler.INSTANCE ); - - final PartPlacement pp = new PartPlacement(); - MinecraftForge.EVENT_BUS.register( pp ); - FMLCommonHandler.instance().bus().register( pp ); - - final IGridCacheRegistry gcr = registries.gridCache(); - gcr.registerGridCache( ITickManager.class, TickManagerCache.class ); - gcr.registerGridCache( IEnergyGrid.class, EnergyGridCache.class ); - gcr.registerGridCache( IPathingGrid.class, PathGridCache.class ); - gcr.registerGridCache( IStorageGrid.class, GridStorageCache.class ); - gcr.registerGridCache( P2PCache.class, P2PCache.class ); - gcr.registerGridCache( ISpatialCache.class, SpatialPylonCache.class ); - gcr.registerGridCache( ISecurityGrid.class, SecurityCache.class ); - gcr.registerGridCache( ICraftingGrid.class, CraftingGridCache.class ); - - registries.externalStorage().addExternalStorageInterface( new AEExternalHandler() ); - - registries.cell().addCellHandler( new BasicCellHandler() ); - registries.cell().addCellHandler( new CreativeCellHandler() ); - - for( final ItemStack ammoStack : api.definitions().materials().matterBall().maybeStack( 1 ).asSet() ) - { - final double weight = 32; - - registries.matterCannon().registerAmmo( ammoStack, weight ); - } - - this.recipeHandler.injectRecipes(); - - final PlayerStatsRegistration registration = new PlayerStatsRegistration( FMLCommonHandler.instance().bus(), AEConfig.instance ); - registration.registerAchievementHandlers(); - registration.registerAchievements(); - - if( AEConfig.instance.isFeatureEnabled( AEFeature.EnableDisassemblyCrafting ) ) - { - GameRegistry.addRecipe( new DisassembleRecipe() ); - RecipeSorter.register( "appliedenergistics2:disassemble", DisassembleRecipe.class, Category.SHAPELESS, "after:minecraft:shapeless" ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.EnableFacadeCrafting ) ) - { - GameRegistry.addRecipe( new FacadeRecipe() ); - RecipeSorter.register( "appliedenergistics2:facade", FacadeRecipe.class, Category.SHAPED, "after:minecraft:shaped" ); - } - } - - void postInit( final FMLPostInitializationEvent event ) - { - this.registerSpatial( true ); - - final IAppEngApi api = AEApi.instance(); - final IRegistryContainer registries = api.registries(); - final IDefinitions definitions = api.definitions(); - final IParts parts = definitions.parts(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - - // default settings.. - ( (P2PTunnelRegistry) registries.p2pTunnel() ).configure(); - - // add to localization.. - PlayerMessages.values(); - GuiText.values(); - - Api.INSTANCE.partHelper().initFMPSupport(); - for( final Block block : blocks.multiPart().maybeBlock().asSet() ) - { - ( (BlockCableBus) block ).setupTile(); - } - - // Interface - Upgrades.CRAFTING.registerItem( parts.iface(), 1 ); - Upgrades.CRAFTING.registerItem( blocks.iface(), 1 ); - - // IO Port! - Upgrades.SPEED.registerItem( blocks.iOPort(), 3 ); - Upgrades.REDSTONE.registerItem( blocks.iOPort(), 1 ); - - // Level Emitter! - Upgrades.FUZZY.registerItem( parts.levelEmitter(), 1 ); - Upgrades.CRAFTING.registerItem( parts.levelEmitter(), 1 ); - - // Import Bus - Upgrades.FUZZY.registerItem( parts.importBus(), 1 ); - Upgrades.REDSTONE.registerItem( parts.importBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.importBus(), 2 ); - Upgrades.SPEED.registerItem( parts.importBus(), 4 ); - - // Export Bus - Upgrades.FUZZY.registerItem( parts.exportBus(), 1 ); - Upgrades.REDSTONE.registerItem( parts.exportBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.exportBus(), 2 ); - Upgrades.SPEED.registerItem( parts.exportBus(), 4 ); - Upgrades.CRAFTING.registerItem( parts.exportBus(), 1 ); - - // Storage Cells - Upgrades.FUZZY.registerItem( items.cell1k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell1k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell4k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell4k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell16k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell16k(), 1 ); - - Upgrades.FUZZY.registerItem( items.cell64k(), 1 ); - Upgrades.INVERTER.registerItem( items.cell64k(), 1 ); - - Upgrades.FUZZY.registerItem( items.portableCell(), 1 ); - Upgrades.INVERTER.registerItem( items.portableCell(), 1 ); - - Upgrades.FUZZY.registerItem( items.viewCell(), 1 ); - Upgrades.INVERTER.registerItem( items.viewCell(), 1 ); - - // Storage Bus - Upgrades.FUZZY.registerItem( parts.storageBus(), 1 ); - Upgrades.INVERTER.registerItem( parts.storageBus(), 1 ); - Upgrades.CAPACITY.registerItem( parts.storageBus(), 5 ); - - // Formation Plane - Upgrades.FUZZY.registerItem( parts.formationPlane(), 1 ); - Upgrades.INVERTER.registerItem( parts.formationPlane(), 1 ); - Upgrades.CAPACITY.registerItem( parts.formationPlane(), 5 ); - - // Matter Cannon - Upgrades.FUZZY.registerItem( items.massCannon(), 1 ); - Upgrades.INVERTER.registerItem( items.massCannon(), 1 ); - Upgrades.SPEED.registerItem( items.massCannon(), 4 ); - - // Molecular Assembler - Upgrades.SPEED.registerItem( blocks.molecularAssembler(), 5 ); - - // Inscriber - Upgrades.SPEED.registerItem( blocks.inscriber(), 3 ); - - for( final Item wirelessTerminalItem : items.wirelessTerminal().maybeItem().asSet() ) - { - registries.wireless().registerWirelessHandler( (IWirelessTermHandler) wirelessTerminalItem ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.ChestLoot ) ) - { - final ChestGenHooks d = ChestGenHooks.getInfo( ChestGenHooks.MINESHAFT_CORRIDOR ); - - final IMaterials materials = definitions.materials(); - - for( final ItemStack crystal : materials.certusQuartzCrystal().maybeStack( 1 ).asSet() ) - { - d.addItem( new WeightedRandomChestContent( crystal, 1, 4, 2 ) ); - } - for( final 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 ) ) - { - VillagerRegistry.instance().registerVillageTradeHandler( 3, new AETrading() ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) - { - GameRegistry.registerWorldGenerator( new QuartzWorldGen(), 0 ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.MeteoriteWorldGen ) ) - { - GameRegistry.registerWorldGenerator( new MeteoriteWorldGen(), 0 ); - } - - final IMovableRegistry mr = registries.movable(); - - /** - * You can't move bed rock. - */ - mr.blacklistBlock( net.minecraft.init.Blocks.bedrock ); - - /* - * White List Vanilla... - */ - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityBeacon.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityBrewingStand.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityChest.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityCommandBlock.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityComparator.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDaylightDetector.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDispenser.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityDropper.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEnchantmentTable.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEnderChest.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityEndPortal.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntitySkull.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityFurnace.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityMobSpawner.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntitySign.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityPiston.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityFlowerPot.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityNote.class ); - mr.whiteListTileEntity( net.minecraft.tileentity.TileEntityHopper.class ); - - /** - * Whitelist AE2 - */ - mr.whiteListTileEntity( AEBaseTile.class ); - - /** - * world gen - */ - for( final WorldGenType type : WorldGenType.values() ) - { - registries.worldgen().disableWorldGenForProviderID( type, StorageWorldProvider.class ); - - // nether - registries.worldgen().disableWorldGenForDimension( type, -1 ); - - // end - registries.worldgen().disableWorldGenForDimension( type, 1 ); - } - - // whitelist from config - for( final int dimension : AEConfig.instance.meteoriteDimensionWhitelist ) - { - registries.worldgen().enableWorldGenForDimension( WorldGenType.Meteorites, dimension ); - } - - /** - * initial recipe bake, if ore dictionary changes after this it re-bakes. - */ - OreDictionaryHandler.INSTANCE.bakeRecipes(); - } +public final class Registration { + private final RecipeHandler recipeHandler; + private final DefinitionConverter converter; + private BiomeGenBase storageBiome; + + Registration() { + this.converter = new DefinitionConverter(); + this.recipeHandler = new RecipeHandler(); + } + + public BiomeGenBase getStorageBiome() { + return this.storageBiome; + } + + void preInitialize(final FMLPreInitializationEvent event) { + this.registerSpatial(false); + + final Api api = Api.INSTANCE; + final IRecipeHandlerRegistry recipeRegistry = api.registries().recipes(); + this.registerCraftHandlers(recipeRegistry); + + RecipeSorter.register("AE2-Facade", FacadeRecipe.class, Category.SHAPED, ""); + RecipeSorter.register("AE2-Shaped", ShapedRecipe.class, Category.SHAPED, ""); + RecipeSorter.register( + "AE2-Shapeless", ShapelessRecipe.class, Category.SHAPELESS, "" + ); + + MinecraftForge.EVENT_BUS.register(OreDictionaryHandler.INSTANCE); + + final ApiDefinitions definitions = api.definitions(); + + final IBlocks apiBlocks = definitions.blocks(); + final IItems apiItems = definitions.items(); + final IMaterials apiMaterials = definitions.materials(); + final IParts apiParts = definitions.parts(); + + final Items items = api.items(); + final Materials materials = api.materials(); + final Parts parts = api.parts(); + final Blocks blocks = api.blocks(); + + this.assignMaterials(materials, apiMaterials); + this.assignParts(parts, apiParts); + this.assignBlocks(blocks, apiBlocks); + this.assignItems(items, apiItems); + + // Register all detected handlers and features (items, blocks) in pre-init + for (final IFeatureHandler handler : + definitions.getFeatureHandlerRegistry().getRegisteredFeatureHandlers()) { + handler.register(); + } + + for (final IAEFeature feature : + definitions.getFeatureRegistry().getRegisteredFeatures()) { + feature.postInit(); + } + } + + private void registerSpatial(final boolean force) { + if (!AEConfig.instance.isFeatureEnabled(AEFeature.SpatialIO)) { + return; + } + + final AEConfig config = AEConfig.instance; + + if (this.storageBiome == null) { + if (force && config.storageBiomeID == -1) { + config.storageBiomeID + = Platform.findEmpty(BiomeGenBase.getBiomeGenArray()); + if (config.storageBiomeID == -1) { + throw new IllegalStateException( + "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) { + this.storageBiome = new BiomeGenStorage(config.storageBiomeID); + } + } + + if (config.storageProviderID != -1) { + DimensionManager.registerProviderType( + config.storageProviderID, StorageWorldProvider.class, false + ); + } + + if (config.storageProviderID == -1 && force) { + config.storageProviderID = -11; + + while (!DimensionManager.registerProviderType( + config.storageProviderID, StorageWorldProvider.class, false + )) { + config.storageProviderID--; + } + + config.save(); + } + } + + private void registerCraftHandlers(final IRecipeHandlerRegistry registry) { + registry.addNewSubItemResolver(new AEItemResolver()); + + registry.addNewCraftHandler("hccrusher", HCCrusher.class); + registry.addNewCraftHandler("mekcrusher", MekCrusher.class); + registry.addNewCraftHandler("mekechamber", MekEnrichment.class); + registry.addNewCraftHandler("grind", Grind.class); + registry.addNewCraftHandler("crusher", Crusher.class); + registry.addNewCraftHandler("grindfz", GrindFZ.class); + registry.addNewCraftHandler("pulverizer", Pulverizer.class); + registry.addNewCraftHandler("macerator", Macerator.class); + + registry.addNewCraftHandler("smelt", Smelt.class); + registry.addNewCraftHandler("inscribe", Inscribe.class); + registry.addNewCraftHandler("press", Press.class); + + registry.addNewCraftHandler("shaped", Shaped.class); + registry.addNewCraftHandler("shapeless", Shapeless.class); + } + + /** + * Assigns materials from the new API to the old API + *

+ * Uses direct cast, since its only a temporary solution anyways + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignMaterials(final Materials target, final IMaterials source) { + target.materialCell2SpatialPart = this.converter.of(source.cell2SpatialPart()); + target.materialCell16SpatialPart = this.converter.of(source.cell16SpatialPart()); + target.materialCell128SpatialPart + = this.converter.of(source.cell128SpatialPart()); + + target.materialSilicon = this.converter.of(source.silicon()); + target.materialSkyDust = this.converter.of(source.skyDust()); + + target.materialCalcProcessorPress + = this.converter.of(source.calcProcessorPress()); + target.materialEngProcessorPress = this.converter.of(source.engProcessorPress()); + target.materialLogicProcessorPress + = this.converter.of(source.logicProcessorPress()); + + target.materialCalcProcessorPrint + = this.converter.of(source.calcProcessorPrint()); + target.materialEngProcessorPrint = this.converter.of(source.engProcessorPrint()); + target.materialLogicProcessorPrint + = this.converter.of(source.logicProcessorPrint()); + + target.materialSiliconPress = this.converter.of(source.siliconPress()); + target.materialSiliconPrint = this.converter.of(source.siliconPrint()); + + target.materialNamePress = this.converter.of(source.namePress()); + + target.materialLogicProcessor = this.converter.of(source.logicProcessor()); + target.materialCalcProcessor = this.converter.of(source.calcProcessor()); + target.materialEngProcessor = this.converter.of(source.engProcessor()); + + target.materialBasicCard = this.converter.of(source.basicCard()); + target.materialAdvCard = this.converter.of(source.advCard()); + + target.materialPurifiedCertusQuartzCrystal + = this.converter.of(source.purifiedCertusQuartzCrystal()); + target.materialPurifiedNetherQuartzCrystal + = this.converter.of(source.purifiedNetherQuartzCrystal()); + target.materialPurifiedFluixCrystal + = this.converter.of(source.purifiedFluixCrystal()); + + target.materialCell1kPart = this.converter.of(source.cell1kPart()); + target.materialCell4kPart = this.converter.of(source.cell4kPart()); + target.materialCell16kPart = this.converter.of(source.cell16kPart()); + target.materialCell64kPart = this.converter.of(source.cell64kPart()); + target.materialEmptyStorageCell = this.converter.of(source.emptyStorageCell()); + + target.materialCardRedstone = this.converter.of(source.cardRedstone()); + target.materialCardSpeed = this.converter.of(source.cardSpeed()); + target.materialCardCapacity = this.converter.of(source.cardCapacity()); + target.materialCardFuzzy = this.converter.of(source.cardFuzzy()); + target.materialCardInverter = this.converter.of(source.cardInverter()); + target.materialCardCrafting = this.converter.of(source.cardCrafting()); + + target.materialEnderDust = this.converter.of(source.enderDust()); + target.materialFlour = this.converter.of(source.flour()); + target.materialGoldDust = this.converter.of(source.goldDust()); + target.materialIronDust = this.converter.of(source.ironDust()); + target.materialFluixDust = this.converter.of(source.fluixDust()); + target.materialCertusQuartzDust = this.converter.of(source.certusQuartzDust()); + target.materialNetherQuartzDust = this.converter.of(source.netherQuartzDust()); + + target.materialMatterBall = this.converter.of(source.matterBall()); + target.materialIronNugget = this.converter.of(source.ironNugget()); + + target.materialCertusQuartzCrystal + = this.converter.of(source.certusQuartzCrystal()); + target.materialCertusQuartzCrystalCharged + = this.converter.of(source.certusQuartzCrystalCharged()); + target.materialFluixCrystal = this.converter.of(source.fluixCrystal()); + target.materialFluixPearl = this.converter.of(source.fluixPearl()); + + target.materialWoodenGear = this.converter.of(source.woodenGear()); + + target.materialWireless = this.converter.of(source.wireless()); + target.materialWirelessBooster = this.converter.of(source.wirelessBooster()); + + target.materialAnnihilationCore = this.converter.of(source.annihilationCore()); + target.materialFormationCore = this.converter.of(source.formationCore()); + + target.materialSingularity = this.converter.of(source.singularity()); + target.materialQESingularity = this.converter.of(source.qESingularity()); + target.materialBlankPattern = this.converter.of(source.blankPattern()); + } + + /** + * Assigns parts from the new API to the old API + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignParts(final Parts target, final IParts source) { + target.partCableSmart = source.cableSmart(); + target.partCableCovered = source.cableCovered(); + target.partCableGlass = source.cableGlass(); + target.partCableDense = source.cableDense(); + // target.partLumenCableSmart = source.lumenCableSmart(); + // target.partLumenCableCovered = source.lumenCableCovered(); + // target.partLumenCableGlass = source.lumenCableGlass(); + // target.partLumenCableDense = source.lumenCableDense(); + target.partQuartzFiber = this.converter.of(source.quartzFiber()); + target.partToggleBus = this.converter.of(source.toggleBus()); + target.partInvertedToggleBus = this.converter.of(source.invertedToggleBus()); + target.partStorageBus = this.converter.of(source.storageBus()); + target.partImportBus = this.converter.of(source.importBus()); + target.partExportBus = this.converter.of(source.exportBus()); + target.partInterface = this.converter.of(source.iface()); + target.partLevelEmitter = this.converter.of(source.levelEmitter()); + target.partAnnihilationPlane = this.converter.of(source.annihilationPlane()); + target.partFormationPlane = this.converter.of(source.formationPlane()); + + target.partCableAnchor = this.converter.of(source.cableAnchor()); + target.partP2PTunnelLight = target.partCableAnchor; + target.partP2PTunnelRF = target.partP2PTunnelLight; + target.partP2PTunnelEU = target.partP2PTunnelRF; + target.partP2PTunnelLiquids = target.partP2PTunnelEU; + target.partP2PTunnelItems = target.partP2PTunnelLiquids; + target.partP2PTunnelRedstone = target.partP2PTunnelItems; + target.partP2PTunnelME = target.partP2PTunnelRedstone; + target.partMonitor = this.converter.of(source.monitor()); + target.partSemiDarkMonitor = this.converter.of(source.semiDarkMonitor()); + target.partDarkMonitor = this.converter.of(source.darkMonitor()); + target.partInterfaceTerminal = this.converter.of(source.interfaceTerminal()); + target.partPatternTerminal = this.converter.of(source.patternTerminal()); + target.partCraftingTerminal = this.converter.of(source.craftingTerminal()); + target.partTerminal = this.converter.of(source.terminal()); + target.partStorageMonitor = this.converter.of(source.storageMonitor()); + target.partConversionMonitor = this.converter.of(source.conversionMonitor()); + } + + /** + * Assigns blocks from the new API to the old API + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignBlocks(final Blocks target, final IBlocks source) { + target.blockMultiPart = this.converter.of(source.multiPart()); + + target.blockCraftingUnit = this.converter.of(source.craftingUnit()); + target.blockCraftingAccelerator = this.converter.of(source.craftingAccelerator()); + target.blockCraftingMonitor = this.converter.of(source.craftingMonitor()); + target.blockCraftingStorage1k = this.converter.of(source.craftingStorage1k()); + target.blockCraftingStorage4k = this.converter.of(source.craftingStorage4k()); + target.blockCraftingStorage16k = this.converter.of(source.craftingStorage16k()); + target.blockCraftingStorage64k = this.converter.of(source.craftingStorage64k()); + target.blockMolecularAssembler = this.converter.of(source.molecularAssembler()); + + target.blockQuartzOre = this.converter.of(source.quartzOre()); + target.blockQuartzOreCharged = this.converter.of(source.quartzOreCharged()); + target.blockMatrixFrame = this.converter.of(source.matrixFrame()); + target.blockQuartz = this.converter.of(source.quartz()); + target.blockFluix = this.converter.of(source.fluix()); + target.blockSkyStone = this.converter.of(source.skyStone()); + target.blockSkyChest = this.converter.of(source.skyChest()); + target.blockSkyCompass = this.converter.of(source.skyCompass()); + + target.blockQuartzGlass = this.converter.of(source.quartzGlass()); + target.blockQuartzVibrantGlass = this.converter.of(source.quartzVibrantGlass()); + target.blockQuartzPillar = this.converter.of(source.quartzPillar()); + target.blockQuartzChiseled = this.converter.of(source.quartzChiseled()); + target.blockQuartzTorch = this.converter.of(source.quartzTorch()); + target.blockLightDetector = this.converter.of(source.lightDetector()); + target.blockCharger = this.converter.of(source.charger()); + target.blockQuartzGrowthAccelerator + = this.converter.of(source.quartzGrowthAccelerator()); + + target.blockGrindStone = this.converter.of(source.grindStone()); + target.blockCrankHandle = this.converter.of(source.crankHandle()); + target.blockInscriber = this.converter.of(source.inscriber()); + target.blockWireless = this.converter.of(source.wireless()); + target.blockTinyTNT = this.converter.of(source.tinyTNT()); + + target.blockQuantumRing = this.converter.of(source.quantumRing()); + target.blockQuantumLink = this.converter.of(source.quantumLink()); + + target.blockSpatialPylon = this.converter.of(source.spatialPylon()); + target.blockSpatialIOPort = this.converter.of(source.spatialIOPort()); + + target.blockController = this.converter.of(source.controller()); + target.blockDrive = this.converter.of(source.drive()); + target.blockChest = this.converter.of(source.chest()); + target.blockInterface = this.converter.of(source.iface()); + target.blockCellWorkbench = this.converter.of(source.cellWorkbench()); + target.blockIOPort = this.converter.of(source.iOPort()); + target.blockCondenser = this.converter.of(source.condenser()); + target.blockEnergyAcceptor = this.converter.of(source.energyAcceptor()); + target.blockVibrationChamber = this.converter.of(source.vibrationChamber()); + + target.blockEnergyCell = this.converter.of(source.energyCell()); + target.blockEnergyCellDense = this.converter.of(source.energyCellDense()); + target.blockEnergyCellCreative = this.converter.of(source.energyCellCreative()); + + target.blockSecurity = this.converter.of(source.security()); + target.blockPaint = this.converter.of(source.paint()); + } + + /** + * Assigns materials from the new API to the old API + * + * @param target old API + * @param source new API + * @deprecated to be removed when the public definition API is removed + */ + @Deprecated + private void assignItems(final Items target, final IItems source) { + target.itemCellCreative = this.converter.of(source.cellCreative()); + target.itemViewCell = this.converter.of(source.viewCell()); + target.itemEncodedPattern = this.converter.of(source.encodedPattern()); + + target.itemCell1k = this.converter.of(source.cell1k()); + target.itemCell4k = this.converter.of(source.cell4k()); + target.itemCell16k = this.converter.of(source.cell16k()); + target.itemCell64k = this.converter.of(source.cell64k()); + + target.itemSpatialCell2 = this.converter.of(source.spatialCell2()); + target.itemSpatialCell16 = this.converter.of(source.spatialCell16()); + target.itemSpatialCell128 = this.converter.of(source.spatialCell128()); + + target.itemCertusQuartzKnife = this.converter.of(source.certusQuartzKnife()); + target.itemCertusQuartzWrench = this.converter.of(source.certusQuartzWrench()); + target.itemCertusQuartzAxe = this.converter.of(source.certusQuartzAxe()); + target.itemCertusQuartzHoe = this.converter.of(source.certusQuartzHoe()); + target.itemCertusQuartzPick = this.converter.of(source.certusQuartzPick()); + target.itemCertusQuartzShovel = this.converter.of(source.certusQuartzShovel()); + target.itemCertusQuartzSword = this.converter.of(source.certusQuartzSword()); + + target.itemNetherQuartzKnife = this.converter.of(source.netherQuartzKnife()); + target.itemNetherQuartzWrench = this.converter.of(source.netherQuartzWrench()); + target.itemNetherQuartzAxe = this.converter.of(source.netherQuartzAxe()); + target.itemNetherQuartzHoe = this.converter.of(source.netherQuartzHoe()); + target.itemNetherQuartzPick = this.converter.of(source.netherQuartzPick()); + target.itemNetherQuartzShovel = this.converter.of(source.netherQuartzShovel()); + target.itemNetherQuartzSword = this.converter.of(source.netherQuartzSword()); + + target.itemMassCannon = this.converter.of(source.massCannon()); + target.itemMemoryCard = this.converter.of(source.memoryCard()); + target.itemChargedStaff = this.converter.of(source.chargedStaff()); + target.itemEntropyManipulator = this.converter.of(source.entropyManipulator()); + target.itemColorApplicator = this.converter.of(source.colorApplicator()); + + target.itemWirelessTerminal = this.converter.of(source.wirelessTerminal()); + target.itemNetworkTool = this.converter.of(source.networkTool()); + target.itemPortableCell = this.converter.of(source.portableCell()); + target.itemBiometricCard = this.converter.of(source.biometricCard()); + + target.itemFacade = this.converter.of(source.facade()); + target.itemCrystalSeed = this.converter.of(source.crystalSeed()); + + target.itemPaintBall = source.coloredPaintBall(); + target.itemLumenPaintBall = source.coloredLumenPaintBall(); + } + + void initialize( + @Nonnull final FMLInitializationEvent event, + @Nonnull final File recipeDirectory, + @Nonnull final CustomRecipeConfig customRecipeConfig + ) { + Preconditions.checkNotNull(event); + Preconditions.checkNotNull(recipeDirectory); + Preconditions.checkArgument(!recipeDirectory.isFile()); + Preconditions.checkNotNull(customRecipeConfig); + + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); + final IRegistryContainer registries = api.registries(); + + // Perform ore camouflage! + ItemMultiMaterial.instance.makeUnique(); + + final Runnable recipeLoader + = new RecipeLoader(recipeDirectory, customRecipeConfig, this.recipeHandler); + recipeLoader.run(); + + partHelper.registerNewLayer( + "appeng.parts.layers.LayerISidedInventory", + "net.minecraft.inventory.ISidedInventory" + ); + partHelper.registerNewLayer( + "appeng.parts.layers.LayerIFluidHandler", + "net.minecraftforge.fluids.IFluidHandler" + ); + partHelper.registerNewLayer( + "appeng.parts.layers.LayerITileStorageMonitorable", + "appeng.api.implementations.tiles.ITileStorageMonitorable" + ); + + FMLCommonHandler.instance().bus().register(TickHandler.INSTANCE); + MinecraftForge.EVENT_BUS.register(TickHandler.INSTANCE); + + final PartPlacement pp = new PartPlacement(); + MinecraftForge.EVENT_BUS.register(pp); + FMLCommonHandler.instance().bus().register(pp); + + final IGridCacheRegistry gcr = registries.gridCache(); + gcr.registerGridCache(ITickManager.class, TickManagerCache.class); + gcr.registerGridCache(IEnergyGrid.class, EnergyGridCache.class); + gcr.registerGridCache(IPathingGrid.class, PathGridCache.class); + gcr.registerGridCache(IStorageGrid.class, GridStorageCache.class); + gcr.registerGridCache(P2PCache.class, P2PCache.class); + gcr.registerGridCache(ISpatialCache.class, SpatialPylonCache.class); + gcr.registerGridCache(ISecurityGrid.class, SecurityCache.class); + gcr.registerGridCache(ICraftingGrid.class, CraftingGridCache.class); + + registries.externalStorage().addExternalStorageInterface(new AEExternalHandler()); + + registries.cell().addCellHandler(new BasicCellHandler()); + registries.cell().addCellHandler(new CreativeCellHandler()); + + for (final ItemStack ammoStack : + api.definitions().materials().matterBall().maybeStack(1).asSet()) { + final double weight = 32; + + registries.matterCannon().registerAmmo(ammoStack, weight); + } + + this.recipeHandler.injectRecipes(); + + final PlayerStatsRegistration registration = new PlayerStatsRegistration( + FMLCommonHandler.instance().bus(), AEConfig.instance + ); + registration.registerAchievementHandlers(); + registration.registerAchievements(); + + if (AEConfig.instance.isFeatureEnabled(AEFeature.EnableDisassemblyCrafting)) { + GameRegistry.addRecipe(new DisassembleRecipe()); + RecipeSorter.register( + "appliedenergistics2:disassemble", + DisassembleRecipe.class, + Category.SHAPELESS, + "after:minecraft:shapeless" + ); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.EnableFacadeCrafting)) { + GameRegistry.addRecipe(new FacadeRecipe()); + RecipeSorter.register( + "appliedenergistics2:facade", + FacadeRecipe.class, + Category.SHAPED, + "after:minecraft:shaped" + ); + } + } + + void postInit(final FMLPostInitializationEvent event) { + this.registerSpatial(true); + + final IAppEngApi api = AEApi.instance(); + final IRegistryContainer registries = api.registries(); + final IDefinitions definitions = api.definitions(); + final IParts parts = definitions.parts(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + + // default settings.. + ((P2PTunnelRegistry) registries.p2pTunnel()).configure(); + + // add to localization.. + PlayerMessages.values(); + GuiText.values(); + + Api.INSTANCE.partHelper().initFMPSupport(); + for (final Block block : blocks.multiPart().maybeBlock().asSet()) { + ((BlockCableBus) block).setupTile(); + } + + // Interface + Upgrades.CRAFTING.registerItem(parts.iface(), 1); + Upgrades.CRAFTING.registerItem(blocks.iface(), 1); + + // IO Port! + Upgrades.SPEED.registerItem(blocks.iOPort(), 3); + Upgrades.REDSTONE.registerItem(blocks.iOPort(), 1); + + // Level Emitter! + Upgrades.FUZZY.registerItem(parts.levelEmitter(), 1); + Upgrades.CRAFTING.registerItem(parts.levelEmitter(), 1); + + // Import Bus + Upgrades.FUZZY.registerItem(parts.importBus(), 1); + Upgrades.REDSTONE.registerItem(parts.importBus(), 1); + Upgrades.CAPACITY.registerItem(parts.importBus(), 2); + Upgrades.SPEED.registerItem(parts.importBus(), 4); + + // Export Bus + Upgrades.FUZZY.registerItem(parts.exportBus(), 1); + Upgrades.REDSTONE.registerItem(parts.exportBus(), 1); + Upgrades.CAPACITY.registerItem(parts.exportBus(), 2); + Upgrades.SPEED.registerItem(parts.exportBus(), 4); + Upgrades.CRAFTING.registerItem(parts.exportBus(), 1); + + // Storage Cells + Upgrades.FUZZY.registerItem(items.cell1k(), 1); + Upgrades.INVERTER.registerItem(items.cell1k(), 1); + + Upgrades.FUZZY.registerItem(items.cell4k(), 1); + Upgrades.INVERTER.registerItem(items.cell4k(), 1); + + Upgrades.FUZZY.registerItem(items.cell16k(), 1); + Upgrades.INVERTER.registerItem(items.cell16k(), 1); + + Upgrades.FUZZY.registerItem(items.cell64k(), 1); + Upgrades.INVERTER.registerItem(items.cell64k(), 1); + + Upgrades.FUZZY.registerItem(items.portableCell(), 1); + Upgrades.INVERTER.registerItem(items.portableCell(), 1); + + Upgrades.FUZZY.registerItem(items.viewCell(), 1); + Upgrades.INVERTER.registerItem(items.viewCell(), 1); + + // Storage Bus + Upgrades.FUZZY.registerItem(parts.storageBus(), 1); + Upgrades.INVERTER.registerItem(parts.storageBus(), 1); + Upgrades.CAPACITY.registerItem(parts.storageBus(), 5); + + // Formation Plane + Upgrades.FUZZY.registerItem(parts.formationPlane(), 1); + Upgrades.INVERTER.registerItem(parts.formationPlane(), 1); + Upgrades.CAPACITY.registerItem(parts.formationPlane(), 5); + + // Matter Cannon + Upgrades.FUZZY.registerItem(items.massCannon(), 1); + Upgrades.INVERTER.registerItem(items.massCannon(), 1); + Upgrades.SPEED.registerItem(items.massCannon(), 4); + + // Molecular Assembler + Upgrades.SPEED.registerItem(blocks.molecularAssembler(), 5); + + // Inscriber + Upgrades.SPEED.registerItem(blocks.inscriber(), 3); + + for (final Item wirelessTerminalItem : + items.wirelessTerminal().maybeItem().asSet()) { + registries.wireless().registerWirelessHandler((IWirelessTermHandler + ) wirelessTerminalItem); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.ChestLoot)) { + final ChestGenHooks d + = ChestGenHooks.getInfo(ChestGenHooks.MINESHAFT_CORRIDOR); + + final IMaterials materials = definitions.materials(); + + for (final ItemStack crystal : + materials.certusQuartzCrystal().maybeStack(1).asSet()) { + d.addItem(new WeightedRandomChestContent(crystal, 1, 4, 2)); + } + for (final 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)) { + VillagerRegistry.instance().registerVillageTradeHandler(3, new AETrading()); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.CertusQuartzWorldGen)) { + GameRegistry.registerWorldGenerator(new QuartzWorldGen(), 0); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.MeteoriteWorldGen)) { + GameRegistry.registerWorldGenerator(new MeteoriteWorldGen(), 0); + } + + final IMovableRegistry mr = registries.movable(); + + /** + * You can't move bed rock. + */ + mr.blacklistBlock(net.minecraft.init.Blocks.bedrock); + + /* + * White List Vanilla... + */ + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityBeacon.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityBrewingStand.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityChest.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityCommandBlock.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityComparator.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDaylightDetector.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDispenser.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityDropper.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEnchantmentTable.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEnderChest.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityEndPortal.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntitySkull.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityFurnace.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityMobSpawner.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntitySign.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityPiston.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityFlowerPot.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityNote.class); + mr.whiteListTileEntity(net.minecraft.tileentity.TileEntityHopper.class); + + /** + * Whitelist AE2 + */ + mr.whiteListTileEntity(AEBaseTile.class); + + /** + * world gen + */ + for (final WorldGenType type : WorldGenType.values()) { + registries.worldgen() + .disableWorldGenForProviderID(type, StorageWorldProvider.class); + + // nether + registries.worldgen().disableWorldGenForDimension(type, -1); + + // end + registries.worldgen().disableWorldGenForDimension(type, 1); + } + + // whitelist from config + for (final int dimension : AEConfig.instance.meteoriteDimensionWhitelist) { + registries.worldgen().enableWorldGenForDimension( + WorldGenType.Meteorites, dimension + ); + } + + /** + * initial recipe bake, if ore dictionary changes after this it re-bakes. + */ + OreDictionaryHandler.INSTANCE.bakeRecipes(); + } } diff --git a/src/main/java/appeng/core/api/ApiPart.java b/src/main/java/appeng/core/api/ApiPart.java index 2ebcadb2..16641a2a 100644 --- a/src/main/java/appeng/core/api/ApiPart.java +++ b/src/main/java/appeng/core/api/ApiPart.java @@ -18,6 +18,10 @@ package appeng.core.api; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.util.*; import appeng.api.parts.CableRenderMode; import appeng.api.parts.IPartHelper; @@ -48,313 +52,270 @@ import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Method; -import java.util.*; +public class ApiPart implements IPartHelper { + private final Map tileImplementations = new HashMap(); + private final Map, String> interfaces2Layer + = new HashMap, String>(); + private final Map roots = new HashMap(); + private final List desc = new LinkedList(); + public void initFMPSupport() { + for (final Class layerInterface : this.interfaces2Layer.keySet()) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)) + .registerPassThrough(layerInterface); + } + } + } -public class ApiPart implements IPartHelper -{ + public Class getCombinedInstance(final String base) { + if (this.desc.isEmpty()) { + try { + return Class.forName(base); + } catch (final ClassNotFoundException e) { + throw new IllegalStateException(e); + } + } - private final Map tileImplementations = new HashMap(); - private final Map, String> interfaces2Layer = new HashMap, String>(); - private final Map roots = new HashMap(); - private final List desc = new LinkedList(); + final String description + = base + ':' + Joiner.on(";").skipNulls().join(this.desc.iterator()); - public void initFMPSupport() - { - for( final Class layerInterface : this.interfaces2Layer.keySet() ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).registerPassThrough( layerInterface ); - } - } - } + if (this.tileImplementations.get(description) != null) { + return this.tileImplementations.get(description); + } - public Class getCombinedInstance( final String base ) - { - if( this.desc.isEmpty() ) - { - try - { - return Class.forName( base ); - } - catch( final ClassNotFoundException e ) - { - throw new IllegalStateException( e ); - } - } + String f = base; // TileCableBus.class.getName(); + String Addendum = ""; + try { + Addendum = Class.forName(base).getSimpleName(); + } catch (final ClassNotFoundException e) { + AELog.debug(e); + } + Class myCLass; - final String description = base + ':' + Joiner.on( ";" ).skipNulls().join( this.desc.iterator() ); + try { + myCLass = Class.forName(f); + } catch (final ClassNotFoundException e) { + throw new IllegalStateException(e); + } - if( this.tileImplementations.get( description ) != null ) - { - return this.tileImplementations.get( description ); - } + String path = f; - String f = base;// TileCableBus.class.getName(); - String Addendum = ""; - try - { - Addendum = Class.forName( base ).getSimpleName(); - } - catch( final ClassNotFoundException e ) - { - AELog.debug( e ); - } - Class myCLass; + for (final String name : this.desc) { + try { + final String newPath = path + ';' + name; + myCLass = this.getClassByDesc( + Addendum, newPath, f, this.interfaces2Layer.get(Class.forName(name)) + ); + path = newPath; + } catch (final Throwable t) { + AELog.warn("Error loading " + name); + AELog.debug(t); + // throw new RuntimeException( t ); + } + f = myCLass.getName(); + } - try - { - myCLass = Class.forName( f ); - } - catch( final ClassNotFoundException e ) - { - throw new IllegalStateException( e ); - } + this.tileImplementations.put(description, myCLass); - String path = f; + return myCLass; + } - for( final String name : this.desc ) - { - try - { - final String newPath = path + ';' + name; - myCLass = this.getClassByDesc( Addendum, newPath, f, this.interfaces2Layer.get( Class.forName( name ) ) ); - path = newPath; - } - catch( final Throwable t ) - { - AELog.warn( "Error loading " + name ); - AELog.debug( t ); - // throw new RuntimeException( t ); - } - f = myCLass.getName(); - } + private Class getClassByDesc( + final String addendum, final String fullPath, final String root, final String next + ) { + if (this.roots.get(fullPath) != null) { + return this.roots.get(fullPath); + } - this.tileImplementations.put( description, myCLass ); + final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); + final ClassNode n = this.getReader(next); + final String originalName = n.name; - return myCLass; - } + try { + n.name = n.name + '_' + addendum; + n.superName = Class.forName(root).getName().replace(".", "/"); + } catch (final Throwable t) { + AELog.debug(t); + } - private Class getClassByDesc( final String addendum, final String fullPath, final String root, final String next ) - { - if( this.roots.get( fullPath ) != null ) - { - return this.roots.get( fullPath ); - } + for (final MethodNode mn : n.methods) { + final Iterator i = mn.instructions.iterator(); + while (i.hasNext()) { + this.processNode(i.next(), n.superName); + } + } - final ClassWriter cw = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - final ClassNode n = this.getReader( next ); - final String originalName = n.name; + final 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 ); - try - { - n.name = n.name + '_' + addendum; - n.superName = Class.forName( root ).getName().replace( ".", "/" ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } + // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); + final byte[] byteArray = cw.toByteArray(); + final int size = byteArray.length; + final Class clazz = this.loadClass(n.name.replace("/", "."), byteArray); - for( final MethodNode mn : n.methods ) - { - final Iterator i = mn.instructions.iterator(); - while( i.hasNext() ) - { - this.processNode( i.next(), n.superName ); - } - } + try { + final Object fish = clazz.newInstance(); + final Class rootC = Class.forName(root); - final 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 ); + boolean hasError = false; - // n.accept( new TraceClassVisitor( new PrintWriter( System.out ) ) ); - final byte[] byteArray = cw.toByteArray(); - final int size = byteArray.length; - final Class clazz = this.loadClass( n.name.replace( "/", "." ), byteArray ); + if (!rootC.isInstance(fish)) { + hasError = true; + AELog.error("Error, Expected layer to implement " + root + " did not."); + } - try - { - final Object fish = clazz.newInstance(); - final Class rootC = Class.forName( root ); + if (fish instanceof LayerBase) { + hasError = true; + AELog.error("Error, Expected layer to NOT implement LayerBase but it DID." + ); + } - boolean hasError = false; + if (!fullPath.contains(".fmp.")) { + if (!(fish instanceof TileCableBus)) { + hasError = true; + AELog.error("Error, Expected layer to implement TileCableBus did not." + ); + } - if( !rootC.isInstance( fish ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement " + root + " did not." ); - } + if (!(fish instanceof TileEntity)) { + hasError = true; + AELog.error("Error, Expected layer to implement TileEntity did not."); + } + } - if( fish instanceof LayerBase ) - { - hasError = true; - AELog.error( "Error, Expected layer to NOT implement LayerBase but it DID." ); - } + if (!hasError) { + AELog.info( + "Layer: " + n.name + " loaded successfully - " + size + " bytes" + ); + } + } catch (final Throwable t) { + AELog.error("Layer: " + n.name + " Failed."); + AELog.debug(t); + } - if( !fullPath.contains( ".fmp." ) ) - { - if( !( fish instanceof TileCableBus ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement TileCableBus did not." ); - } + this.roots.put(fullPath, clazz); + return clazz; + } - if( !( fish instanceof TileEntity ) ) - { - hasError = true; - AELog.error( "Error, Expected layer to implement TileEntity did not." ); - } - } + private ClassNode getReader(final String name) { + final String path = '/' + name.replace(".", "/") + ".class"; + final InputStream is = this.getClass().getResourceAsStream(path); + try { + final ClassReader cr = new ClassReader(is); - if( !hasError ) - { - AELog.info( "Layer: " + n.name + " loaded successfully - " + size + " bytes" ); - } - } - catch( final Throwable t ) - { - AELog.error( "Layer: " + n.name + " Failed." ); - AELog.debug( t ); - } + final ClassNode cn = new ClassNode(); + cr.accept(cn, ClassReader.EXPAND_FRAMES); - this.roots.put( fullPath, clazz ); - return clazz; - } + return cn; + } catch (final IOException e) { + throw new IllegalStateException("Error loading " + name, e); + } + } - private ClassNode getReader( final String name ) - { - final String path = '/' + name.replace( ".", "/" ) + ".class"; - final InputStream is = this.getClass().getResourceAsStream( path ); - try - { - final ClassReader cr = new ClassReader( is ); + private void processNode(final AbstractInsnNode next, final String nePar) { + if (next instanceof MethodInsnNode) { + final MethodInsnNode min = (MethodInsnNode) next; + if (min.owner.equals("appeng/api/parts/LayerBase")) { + min.owner = nePar; + } + } + } - final ClassNode cn = new ClassNode(); - cr.accept( cn, ClassReader.EXPAND_FRAMES ); + private Class loadClass(final String name, byte[] b) { + // override classDefine (as it is protected) and define the class. + Class clazz = null; + try { + final ClassLoader loader + = this.getClass().getClassLoader(); // ClassLoader.getSystemClassLoader(); + final Class root = ClassLoader.class; + final Class cls = loader.getClass(); + final Method defineClassMethod = root.getDeclaredMethod( + "defineClass", String.class, byte[].class, int.class, int.class + ); + final Method runTransformersMethod = cls.getDeclaredMethod( + "runTransformers", String.class, String.class, byte[].class + ); - return cn; - } - catch( final IOException e ) - { - throw new IllegalStateException( "Error loading " + name, e ); - } - } + runTransformersMethod.setAccessible(true); + defineClassMethod.setAccessible(true); + try { + final Object[] argsA = { name, name, b }; + b = (byte[]) runTransformersMethod.invoke(loader, argsA); - private void processNode( final AbstractInsnNode next, final String nePar ) - { - if( next instanceof MethodInsnNode ) - { - final MethodInsnNode min = (MethodInsnNode) next; - if( min.owner.equals( "appeng/api/parts/LayerBase" ) ) - { - min.owner = nePar; - } - } - } + final Object[] args = { name, b, 0, b.length }; + clazz = (Class) defineClassMethod.invoke(loader, args); + } finally { + runTransformersMethod.setAccessible(false); + defineClassMethod.setAccessible(false); + } + } catch (final Exception e) { + AELog.debug(e); + throw new IllegalStateException("Unable to manage part API.", e); + } + return clazz; + } - private Class loadClass( final String name, byte[] b ) - { - // override classDefine (as it is protected) and define the class. - Class clazz = null; - try - { - final ClassLoader loader = this.getClass().getClassLoader();// ClassLoader.getSystemClassLoader(); - final Class root = ClassLoader.class; - final Class cls = loader.getClass(); - final Method defineClassMethod = root.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class ); - final Method runTransformersMethod = cls.getDeclaredMethod( "runTransformers", String.class, String.class, byte[].class ); + @Override + public boolean registerNewLayer(final String layer, final String layerInterface) { + try { + final Class layerInterfaceClass = Class.forName(layerInterface); + if (this.interfaces2Layer.get(layerInterfaceClass) == null) { + this.interfaces2Layer.put(layerInterfaceClass, layer); + this.desc.add(layerInterface); + return true; + } else { + AELog.info( + "Layer " + layer + " not registered, " + layerInterface + + " already has a layer." + ); + } + } catch (final Throwable ignored) {} - runTransformersMethod.setAccessible( true ); - defineClassMethod.setAccessible( true ); - try - { - final Object[] argsA = { name, name, b }; - b = (byte[]) runTransformersMethod.invoke( loader, argsA ); + return false; + } - final Object[] args = { name, b, 0, b.length }; - clazz = (Class) defineClassMethod.invoke( loader, args ); - } - finally - { - runTransformersMethod.setAccessible( false ); - defineClassMethod.setAccessible( false ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - throw new IllegalStateException( "Unable to manage part API.", e ); - } - return clazz; - } + @Override + public void setItemBusRenderer(final IPartItem i) { + if (Platform.isClient() && i instanceof Item) { + MinecraftForgeClient.registerItemRenderer((Item) i, BusRenderer.INSTANCE); + } + } - @Override - public boolean registerNewLayer( final String layer, final String layerInterface ) - { - try - { - final Class layerInterfaceClass = Class.forName( layerInterface ); - if( this.interfaces2Layer.get( layerInterfaceClass ) == null ) - { - this.interfaces2Layer.put( layerInterfaceClass, layer ); - this.desc.add( layerInterface ); - return true; - } - else - { - AELog.info( "Layer " + layer + " not registered, " + layerInterface + " already has a layer." ); - } - } - catch( final Throwable ignored ) - { - } + @Override + public boolean placeBus( + final ItemStack is, + final int x, + final int y, + final int z, + final int side, + final EntityPlayer player, + final World w + ) { + return PartPlacement.place( + is, x, y, z, side, player, w, PartPlacement.PlaceType.PLACE_ITEM, 0 + ); + } - return false; - } + @Override + public CableRenderMode getCableRenderMode() { + return CommonHelper.proxy.getRenderMode(); + } - @Override - public void setItemBusRenderer( final IPartItem i ) - { - if( Platform.isClient() && i instanceof Item ) - { - MinecraftForgeClient.registerItemRenderer( (Item) i, BusRenderer.INSTANCE ); - } - } + private static class DefaultPackageClassNameRemapper extends Remapper { + private final HashMap inputOutput = new HashMap(); - @Override - public boolean placeBus( final ItemStack is, final int x, final int y, final int z, final int side, final EntityPlayer player, final 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(); - } - - private static class DefaultPackageClassNameRemapper extends Remapper - { - - private final HashMap inputOutput = new HashMap(); - - @Override - public String map( final String typeName ) - { - final String o = this.inputOutput.get( typeName ); - if( o == null ) - { - return typeName; - } - return o; - } - } + @Override + public String map(final String typeName) { + final 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 6d07f950..4fdf4403 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 appeng.api.networking.crafting.ICraftingLink; import appeng.api.networking.crafting.ICraftingRequester; @@ -39,63 +40,60 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; -import java.io.IOException; +public class ApiStorage implements IStorageHelper { + @Override + public ICraftingLink + loadCraftingLink(final NBTTagCompound data, final ICraftingRequester req) { + return new CraftingLink(data, req); + } + @Override + public IAEItemStack createItemStack(final ItemStack is) { + return AEItemStack.create(is); + } -public class ApiStorage implements IStorageHelper -{ + @Override + public IAEFluidStack createFluidStack(final FluidStack is) { + return AEFluidStack.create(is); + } - @Override - public ICraftingLink loadCraftingLink( final NBTTagCompound data, final ICraftingRequester req ) - { - return new CraftingLink( data, req ); - } + @Override + public IItemList createItemList() { + return new ItemList(); + } - @Override - public IAEItemStack createItemStack( final ItemStack is ) - { - return AEItemStack.create( is ); - } + @Override + public IItemList createFluidList() { + return new FluidList(); + } - @Override - public IAEFluidStack createFluidStack( final FluidStack is ) - { - return AEFluidStack.create( is ); - } + @Override + public IAEItemStack readItemFromPacket(final ByteBuf input) throws IOException { + return AEItemStack.loadItemStackFromPacket(input); + } - @Override - public IItemList createItemList() - { - return new ItemList(); - } + @Override + public IAEFluidStack readFluidFromPacket(final ByteBuf input) throws IOException { + return AEFluidStack.loadFluidStackFromPacket(input); + } - @Override - public IItemList createFluidList() - { - return new FluidList(); - } + @Override + public IAEItemStack poweredExtraction( + final IEnergySource energy, + final IMEInventory cell, + final IAEItemStack request, + final BaseActionSource src + ) { + return Platform.poweredExtraction(energy, cell, request, src); + } - @Override - public IAEItemStack readItemFromPacket( final ByteBuf input ) throws IOException - { - return AEItemStack.loadItemStackFromPacket( input ); - } - - @Override - public IAEFluidStack readFluidFromPacket( final ByteBuf input ) throws IOException - { - return AEFluidStack.loadFluidStackFromPacket( input ); - } - - @Override - public IAEItemStack poweredExtraction( final IEnergySource energy, final IMEInventory cell, final IAEItemStack request, final BaseActionSource src ) - { - return Platform.poweredExtraction( energy, cell, request, src ); - } - - @Override - public IAEItemStack poweredInsert( final IEnergySource energy, final IMEInventory cell, final IAEItemStack input, final BaseActionSource src ) - { - return Platform.poweredInsert( energy, cell, input, src ); - } + @Override + public IAEItemStack poweredInsert( + final IEnergySource energy, + final IMEInventory cell, + final IAEItemStack input, + final BaseActionSource src + ) { + return Platform.poweredInsert(energy, cell, input, src); + } } diff --git a/src/main/java/appeng/core/api/ICraftingTerminal.java b/src/main/java/appeng/core/api/ICraftingTerminal.java index 528334b2..55078d61 100644 --- a/src/main/java/appeng/core/api/ICraftingTerminal.java +++ b/src/main/java/appeng/core/api/ICraftingTerminal.java @@ -4,7 +4,5 @@ import appeng.api.storage.ITerminalHost; import net.minecraft.inventory.IInventory; public interface ICraftingTerminal extends ITerminalHost { - IInventory getInventoryByName(final String name); - } diff --git a/src/main/java/appeng/core/api/IIMCProcessor.java b/src/main/java/appeng/core/api/IIMCProcessor.java index 47e0b55b..e449d07f 100644 --- a/src/main/java/appeng/core/api/IIMCProcessor.java +++ b/src/main/java/appeng/core/api/IIMCProcessor.java @@ -18,11 +18,8 @@ package appeng.core.api; - import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; - -public interface IIMCProcessor -{ - void process( IMCMessage m ); +public interface IIMCProcessor { + void process(IMCMessage m); } diff --git a/src/main/java/appeng/core/api/definitions/ApiBlocks.java b/src/main/java/appeng/core/api/definitions/ApiBlocks.java index fbfa46b8..e8a3da5a 100644 --- a/src/main/java/appeng/core/api/definitions/ApiBlocks.java +++ b/src/main/java/appeng/core/api/definitions/ApiBlocks.java @@ -18,6 +18,8 @@ package appeng.core.api.definitions; +import java.util.EnumSet; +import java.util.Set; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -53,597 +55,602 @@ import appeng.debug.BlockItemGen; import appeng.debug.BlockPhantomNode; import com.google.common.collect.ImmutableSet; -import java.util.EnumSet; -import java.util.Set; - - /** * Internal implementation for the API blocks */ -public final class ApiBlocks implements IBlocks -{ - private final IBlockDefinition quartzOre; - private final IBlockDefinition quartzOreCharged; - private final IBlockDefinition matrixFrame; - private final IBlockDefinition quartz; - private final IBlockDefinition quartzPillar; - private final IBlockDefinition quartzChiseled; - private final IBlockDefinition quartzGlass; - private final IBlockDefinition quartzVibrantGlass; - private final IBlockDefinition quartzTorch; - private final IBlockDefinition fluix; - private final IBlockDefinition skyStone; - private final IBlockDefinition skyChest; - private final IBlockDefinition skyCompass; - private final ITileDefinition grindStone; - private final ITileDefinition crankHandle; - private final ITileDefinition inscriber; - private final ITileDefinition wireless; - private final ITileDefinition charger; - private final IBlockDefinition tinyTNT; - private final ITileDefinition security; - private final ITileDefinition quantumRing; - private final ITileDefinition quantumLink; - private final ITileDefinition spatialPylon; - private final ITileDefinition spatialIOPort; - private final ITileDefinition multiPart; - private final ITileDefinition controller; - private final ITileDefinition drive; - private final ITileDefinition chest; - private final ITileDefinition iface; - private final ITileDefinition cellWorkbench; - private final ITileDefinition iOPort; - private final ITileDefinition condenser; - private final ITileDefinition energyAcceptor; - private final ITileDefinition vibrationChamber; - private final ITileDefinition quartzGrowthAccelerator; - private final ITileDefinition energyCell; - private final ITileDefinition energyCellDense; - private final ITileDefinition energyCellCreative; - private final ITileDefinition craftingUnit; - private final ITileDefinition craftingAccelerator; - private final ITileDefinition craftingStorage1k; - private final ITileDefinition craftingStorage4k; - private final ITileDefinition craftingStorage16k; - private final ITileDefinition craftingStorage64k; - private final ITileDefinition craftingMonitor; - private final ITileDefinition molecularAssembler; - private final ITileDefinition lightDetector; - private final ITileDefinition paint; - private final IBlockDefinition skyStoneStair; - private final IBlockDefinition skyStoneBlockStair; - private final IBlockDefinition skyStoneBrickStair; - private final IBlockDefinition skyStoneSmallBrickStair; - private final IBlockDefinition fluixStair; - private final IBlockDefinition quartzStair; - private final IBlockDefinition chiseledQuartzStair; - private final IBlockDefinition quartzPillarStair; - private final IBlockDefinition skyStoneSlab; - private final IBlockDefinition skyStoneBlockSlab; - private final IBlockDefinition skyStoneBrickSlab; - private final IBlockDefinition skyStoneSmallBrickSlab; - private final IBlockDefinition fluixSlab; - private final IBlockDefinition quartzSlab; - private final IBlockDefinition chiseledQuartzSlab; - private final IBlockDefinition quartzPillarSlab; +public final class ApiBlocks implements IBlocks { + private final IBlockDefinition quartzOre; + private final IBlockDefinition quartzOreCharged; + private final IBlockDefinition matrixFrame; + private final IBlockDefinition quartz; + private final IBlockDefinition quartzPillar; + private final IBlockDefinition quartzChiseled; + private final IBlockDefinition quartzGlass; + private final IBlockDefinition quartzVibrantGlass; + private final IBlockDefinition quartzTorch; + private final IBlockDefinition fluix; + private final IBlockDefinition skyStone; + private final IBlockDefinition skyChest; + private final IBlockDefinition skyCompass; + private final ITileDefinition grindStone; + private final ITileDefinition crankHandle; + private final ITileDefinition inscriber; + private final ITileDefinition wireless; + private final ITileDefinition charger; + private final IBlockDefinition tinyTNT; + private final ITileDefinition security; + private final ITileDefinition quantumRing; + private final ITileDefinition quantumLink; + private final ITileDefinition spatialPylon; + private final ITileDefinition spatialIOPort; + private final ITileDefinition multiPart; + private final ITileDefinition controller; + private final ITileDefinition drive; + private final ITileDefinition chest; + private final ITileDefinition iface; + private final ITileDefinition cellWorkbench; + private final ITileDefinition iOPort; + private final ITileDefinition condenser; + private final ITileDefinition energyAcceptor; + private final ITileDefinition vibrationChamber; + private final ITileDefinition quartzGrowthAccelerator; + private final ITileDefinition energyCell; + private final ITileDefinition energyCellDense; + private final ITileDefinition energyCellCreative; + private final ITileDefinition craftingUnit; + private final ITileDefinition craftingAccelerator; + private final ITileDefinition craftingStorage1k; + private final ITileDefinition craftingStorage4k; + private final ITileDefinition craftingStorage16k; + private final ITileDefinition craftingStorage64k; + private final ITileDefinition craftingMonitor; + private final ITileDefinition molecularAssembler; + private final ITileDefinition lightDetector; + private final ITileDefinition paint; + private final IBlockDefinition skyStoneStair; + private final IBlockDefinition skyStoneBlockStair; + private final IBlockDefinition skyStoneBrickStair; + private final IBlockDefinition skyStoneSmallBrickStair; + private final IBlockDefinition fluixStair; + private final IBlockDefinition quartzStair; + private final IBlockDefinition chiseledQuartzStair; + private final IBlockDefinition quartzPillarStair; + private final IBlockDefinition skyStoneSlab; + private final IBlockDefinition skyStoneBlockSlab; + private final IBlockDefinition skyStoneBrickSlab; + private final IBlockDefinition skyStoneSmallBrickSlab; + private final IBlockDefinition fluixSlab; + private final IBlockDefinition quartzSlab; + private final IBlockDefinition chiseledQuartzSlab; + private final IBlockDefinition quartzPillarSlab; - private final IBlockDefinition itemGen; - private final IBlockDefinition chunkLoader; - private final IBlockDefinition phantomNode; - private final IBlockDefinition cubeGenerator; + private final IBlockDefinition itemGen; + private final IBlockDefinition chunkLoader; + private final IBlockDefinition phantomNode; + private final IBlockDefinition cubeGenerator; - private final Set orientables; + private final Set orientables; - // Legacy - private final ITileDefinition terminal; - private final ITileDefinition craftTerminal; - private final ITileDefinition craftMonitor; - private final ITileDefinition legacyController; + // Legacy + private final ITileDefinition terminal; + private final ITileDefinition craftTerminal; + private final ITileDefinition craftMonitor; + private final ITileDefinition legacyController; private final ITileDefinition legacyWirelessAccessPoint; - public ApiBlocks( final DefinitionConstructor constructor ) - { - final BlockLightDetector lightDetector = new BlockLightDetector(); - final BlockQuartzPillar quartzPillar = new BlockQuartzPillar(); - final BlockSkyStone skyStone = new BlockSkyStone(); - final BlockFluix fluixBlock = new BlockFluix(); - final BlockQuartzGrowthAccelerator cga = new BlockQuartzGrowthAccelerator(); - final BlockQuartzTorch quartzTorch = new BlockQuartzTorch(); - final BlockQuartz quartzBlock = new BlockQuartz(); - final BlockQuartzChiseled chiseledQuartz = new BlockQuartzChiseled(); - - this.orientables = ImmutableSet.of( lightDetector, quartzPillar, skyStone, cga, quartzTorch ); - - this.quartzOre = constructor.registerBlockDefinition( new OreQuartz() ); - this.quartzOreCharged = constructor.registerBlockDefinition( new OreQuartzCharged() ); - this.matrixFrame = constructor.registerBlockDefinition( new BlockMatrixFrame() ); - this.quartz = constructor.registerBlockDefinition( quartzBlock ); - this.quartzPillar = constructor.registerBlockDefinition( quartzPillar ); - this.quartzChiseled = constructor.registerBlockDefinition( chiseledQuartz ); - this.quartzGlass = constructor.registerBlockDefinition( new BlockQuartzGlass() ); - this.quartzVibrantGlass = constructor.registerBlockDefinition( new BlockQuartzLamp() ); - this.quartzTorch = constructor.registerBlockDefinition( quartzTorch ); - this.fluix = constructor.registerBlockDefinition( fluixBlock ); - this.skyStone = constructor.registerBlockDefinition( skyStone ); - this.skyChest = constructor.registerBlockDefinition( new BlockSkyChest() ); - this.skyCompass = constructor.registerBlockDefinition( new BlockSkyCompass() ); - this.grindStone = constructor.registerTileDefinition( new BlockGrinder() ); - this.crankHandle = constructor.registerTileDefinition( new BlockCrank() ); - this.inscriber = constructor.registerTileDefinition( new BlockInscriber() ); - this.wireless = constructor.registerTileDefinition( new BlockWireless() ); - this.charger = constructor.registerTileDefinition( new BlockCharger() ); - this.tinyTNT = constructor.registerBlockDefinition( new BlockTinyTNT() ); - this.security = constructor.registerTileDefinition( new BlockSecurity() ); - this.quantumRing = constructor.registerTileDefinition( new BlockQuantumRing() ); - this.quantumLink = constructor.registerTileDefinition( new BlockQuantumLinkChamber() ); - this.spatialPylon = constructor.registerTileDefinition( new BlockSpatialPylon() ); - this.spatialIOPort = constructor.registerTileDefinition( new BlockSpatialIOPort() ); - this.multiPart = constructor.registerTileDefinition( new BlockCableBus() ); - this.controller = constructor.registerTileDefinition( new BlockController() ); - this.drive = constructor.registerTileDefinition( new BlockDrive() ); - this.chest = constructor.registerTileDefinition( new BlockChest() ); - this.iface = constructor.registerTileDefinition( new BlockInterface() ); - this.cellWorkbench = constructor.registerTileDefinition( new BlockCellWorkbench() ); - this.iOPort = constructor.registerTileDefinition( new BlockIOPort() ); - this.condenser = constructor.registerTileDefinition( new BlockCondenser() ); - this.energyAcceptor = constructor.registerTileDefinition( new BlockEnergyAcceptor() ); - this.vibrationChamber = constructor.registerTileDefinition( new BlockVibrationChamber() ); - this.quartzGrowthAccelerator = constructor.registerTileDefinition( cga ); - this.energyCell = constructor.registerTileDefinition( new BlockEnergyCell() ); - this.energyCellDense = constructor.registerTileDefinition( new BlockDenseEnergyCell() ); - this.energyCellCreative = constructor.registerTileDefinition( new BlockCreativeEnergyCell() ); - this.craftingUnit = constructor.registerTileDefinition( new BlockCraftingUnit() ); - this.craftingAccelerator = new WrappedDamageItemDefinition( this.craftingUnit, 1 ); - this.craftingStorage1k = constructor.registerTileDefinition( new BlockCraftingStorage() ); - this.craftingStorage4k = new WrappedDamageItemDefinition( this.craftingStorage1k, 1 ); - this.craftingStorage16k = new WrappedDamageItemDefinition( this.craftingStorage1k, 2 ); - this.craftingStorage64k = new WrappedDamageItemDefinition( this.craftingStorage1k, 3 ); - this.craftingMonitor = constructor.registerTileDefinition( new BlockCraftingMonitor() ); - this.molecularAssembler = constructor.registerTileDefinition( new BlockMolecularAssembler() ); - this.lightDetector = constructor.registerTileDefinition( lightDetector ); - this.paint = constructor.registerTileDefinition( new BlockPaint() ); - - this.skyStoneStair = constructor.registerBlockDefinition( new SkyStoneStairBlock( skyStone, 0 ) ); - this.skyStoneBlockStair = constructor.registerBlockDefinition( new SkyStoneBlockStairBlock( skyStone, 1 ) ); - this.skyStoneBrickStair = constructor.registerBlockDefinition( new SkyStoneBrickStairBlock( skyStone, 2 ) ); - this.skyStoneSmallBrickStair = constructor.registerBlockDefinition( new SkyStoneSmallBrickStairBlock( skyStone, 3 ) ); - - this.fluixStair = constructor.registerBlockDefinition( new FluixStairBlock( fluixBlock ) ); - - this.quartzStair = constructor.registerBlockDefinition( new QuartzStairBlock( quartzBlock ) ); - - this.chiseledQuartzStair = constructor.registerBlockDefinition( new ChiseledQuartzStairBlock( chiseledQuartz ) ); - - this.quartzPillarStair = constructor.registerBlockDefinition( new QuartzPillarStairBlock( quartzPillar ) ); - - this.skyStoneSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneSlabBlock" ) ); - this.skyStoneBlockSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 1, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneBlockSlabBlock" ) ); - this.skyStoneBrickSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 2, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneBrickSlabBlock" ) ); - this.skyStoneSmallBrickSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( skyStone, 3, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "SkyStoneSmallBrickSlabBlock" ) ); - this.fluixSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( fluixBlock, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "FluixSlabBlock" ) ); - this.quartzSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( quartzBlock, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "QuartzSlabBlock" ) ); - this.chiseledQuartzSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( chiseledQuartz, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "ChiseledQuartzSlabBlock" ) ); - this.quartzPillarSlab = constructor.registerBlockDefinition( new AEBaseSlabBlock( quartzPillar, 0, EnumSet.of( AEFeature.DecorativeQuartzBlocks ), false, "QuartzPillarSlabBlock" ) ); - - this.itemGen = constructor.registerBlockDefinition( new BlockItemGen() ); - this.chunkLoader = constructor.registerBlockDefinition( new BlockChunkloader() ); - this.phantomNode = constructor.registerBlockDefinition( new BlockPhantomNode() ); - this.cubeGenerator = constructor.registerBlockDefinition( new BlockCubeGenerator() ); - - // Legacy - this.terminal = constructor.registerTileDefinition( new BlockTerminal() ); - this.craftTerminal = constructor.registerTileDefinition( new BlockCraftTerminal() ); - this.craftMonitor = constructor.registerTileDefinition( new BlockCraftMonitor() ); - this.legacyController = constructor.registerTileDefinition( new BlockLegacyController() ); - this.legacyWirelessAccessPoint = constructor.registerTileDefinition(new BlockWirelessAccessPoint()); - } - - @Override - public IBlockDefinition quartzOre() - { - return this.quartzOre; - } - - @Override - public IBlockDefinition quartzOreCharged() - { - return this.quartzOreCharged; - } - - @Override - public IBlockDefinition matrixFrame() - { - return this.matrixFrame; - } - - @Override - public IBlockDefinition quartz() - { - return this.quartz; - } - - @Override - public IBlockDefinition quartzPillar() - { - return this.quartzPillar; - } - - @Override - public IBlockDefinition quartzChiseled() - { - return this.quartzChiseled; - } - - @Override - public IBlockDefinition quartzGlass() - { - return this.quartzGlass; - } - - @Override - public IBlockDefinition quartzVibrantGlass() - { - return this.quartzVibrantGlass; - } - - @Override - public IBlockDefinition quartzTorch() - { - return this.quartzTorch; - } - - @Override - public IBlockDefinition fluix() - { - return this.fluix; - } - - @Override - public IBlockDefinition skyStone() - { - return this.skyStone; - } - - @Override - public IBlockDefinition skyChest() - { - return this.skyChest; - } - - @Override - public IBlockDefinition skyCompass() - { - return this.skyCompass; - } - - @Override - public IBlockDefinition skyStoneStair() - { - return this.skyStoneStair; - } - - @Override - public IBlockDefinition skyStoneBlockStair() - { - return this.skyStoneBlockStair; - } - - @Override - public IBlockDefinition skyStoneBrickStair() - { - return this.skyStoneBrickStair; - } - - @Override - public IBlockDefinition skyStoneSmallBrickStair() - { - return this.skyStoneSmallBrickStair; - } - - @Override - public IBlockDefinition fluixStair() - { - return this.fluixStair; - } - - @Override - public IBlockDefinition quartzStair() - { - return this.quartzStair; - } - - @Override - public IBlockDefinition chiseledQuartzStair() - { - return this.chiseledQuartzStair; - } - - @Override - public IBlockDefinition quartzPillarStair() - { - return this.quartzPillarStair; - } - - @Override - public IBlockDefinition skyStoneSlab() - { - return this.skyStoneSlab; - } - - @Override - public IBlockDefinition skyStoneBlockSlab() - { - return this.skyStoneBlockSlab; - } - - @Override - public IBlockDefinition skyStoneBrickSlab() - { - return this.skyStoneBrickSlab; - } - - @Override - public IBlockDefinition skyStoneSmallBrickSlab() - { - return this.skyStoneSmallBrickSlab; - } - - @Override - public IBlockDefinition fluixSlab() - { - return this.fluixSlab; - } - - @Override - public IBlockDefinition quartzSlab() - { - return this.quartzSlab; - } - - @Override - public IBlockDefinition chiseledQuartzSlab() - { - return this.chiseledQuartzSlab; - } - - @Override - public IBlockDefinition quartzPillarSlab() - { - return this.quartzPillarSlab; - } - - @Override - public ITileDefinition grindStone() - { - return this.grindStone; - } - - @Override - public ITileDefinition crankHandle() - { - return this.crankHandle; - } - - @Override - public ITileDefinition inscriber() - { - return this.inscriber; - } - - @Override - public ITileDefinition wireless() - { - return this.wireless; - } - - @Override - public ITileDefinition charger() - { - return this.charger; - } - - @Override - public IBlockDefinition tinyTNT() - { - return this.tinyTNT; - } - - @Override - public ITileDefinition security() - { - return this.security; - } - - @Override - public ITileDefinition quantumRing() - { - return this.quantumRing; - } - - @Override - public ITileDefinition quantumLink() - { - return this.quantumLink; - } - - @Override - public ITileDefinition spatialPylon() - { - return this.spatialPylon; - } - - @Override - public ITileDefinition spatialIOPort() - { - return this.spatialIOPort; - } - - @Override - public ITileDefinition multiPart() - { - return this.multiPart; - } - - @Override - public ITileDefinition controller() - { - return this.controller; - } - - @Override - public ITileDefinition drive() - { - return this.drive; - } - - @Override - public ITileDefinition chest() - { - return this.chest; - } - - @Override - public ITileDefinition iface() - { - return this.iface; - } - - @Override - public ITileDefinition cellWorkbench() - { - return this.cellWorkbench; - } - - @Override - public ITileDefinition iOPort() - { - return this.iOPort; - } - - @Override - public ITileDefinition condenser() - { - return this.condenser; - } - - @Override - public ITileDefinition energyAcceptor() - { - return this.energyAcceptor; - } - - @Override - public ITileDefinition vibrationChamber() - { - return this.vibrationChamber; - } - - @Override - public ITileDefinition quartzGrowthAccelerator() - { - return this.quartzGrowthAccelerator; - } - - @Override - public ITileDefinition energyCell() - { - return this.energyCell; - } - - @Override - public ITileDefinition energyCellDense() - { - return this.energyCellDense; - } - - @Override - public ITileDefinition energyCellCreative() - { - return this.energyCellCreative; - } - - @Override - public ITileDefinition craftingUnit() - { - return this.craftingUnit; - } - - @Override - public ITileDefinition craftingAccelerator() - { - return this.craftingAccelerator; - } - - @Override - public ITileDefinition craftingStorage1k() - { - return this.craftingStorage1k; - } - - @Override - public ITileDefinition craftingStorage4k() - { - return this.craftingStorage4k; - } - - @Override - public ITileDefinition craftingStorage16k() - { - return this.craftingStorage16k; - } - - @Override - public ITileDefinition craftingStorage64k() - { - return this.craftingStorage64k; - } - - @Override - public ITileDefinition craftingMonitor() - { - return this.craftingMonitor; - } - - @Override - public ITileDefinition molecularAssembler() - { - return this.molecularAssembler; - } - - @Override - public ITileDefinition lightDetector() - { - return this.lightDetector; - } - - @Override - public ITileDefinition paint() - { - return this.paint; - } - - public IBlockDefinition chunkLoader() - { - return this.chunkLoader; - } - - public IBlockDefinition itemGen() - { - return this.itemGen; - } - - public IBlockDefinition phantomNode() - { - return this.phantomNode; - } - - public IBlockDefinition cubeGenerator() - { - return this.cubeGenerator; - } - - public Set orientables() - { - return this.orientables; - } + public ApiBlocks(final DefinitionConstructor constructor) { + final BlockLightDetector lightDetector = new BlockLightDetector(); + final BlockQuartzPillar quartzPillar = new BlockQuartzPillar(); + final BlockSkyStone skyStone = new BlockSkyStone(); + final BlockFluix fluixBlock = new BlockFluix(); + final BlockQuartzGrowthAccelerator cga = new BlockQuartzGrowthAccelerator(); + final BlockQuartzTorch quartzTorch = new BlockQuartzTorch(); + final BlockQuartz quartzBlock = new BlockQuartz(); + final BlockQuartzChiseled chiseledQuartz = new BlockQuartzChiseled(); + + this.orientables = ImmutableSet.of( + lightDetector, quartzPillar, skyStone, cga, quartzTorch + ); + + this.quartzOre = constructor.registerBlockDefinition(new OreQuartz()); + this.quartzOreCharged + = constructor.registerBlockDefinition(new OreQuartzCharged()); + this.matrixFrame = constructor.registerBlockDefinition(new BlockMatrixFrame()); + this.quartz = constructor.registerBlockDefinition(quartzBlock); + this.quartzPillar = constructor.registerBlockDefinition(quartzPillar); + this.quartzChiseled = constructor.registerBlockDefinition(chiseledQuartz); + this.quartzGlass = constructor.registerBlockDefinition(new BlockQuartzGlass()); + this.quartzVibrantGlass + = constructor.registerBlockDefinition(new BlockQuartzLamp()); + this.quartzTorch = constructor.registerBlockDefinition(quartzTorch); + this.fluix = constructor.registerBlockDefinition(fluixBlock); + this.skyStone = constructor.registerBlockDefinition(skyStone); + this.skyChest = constructor.registerBlockDefinition(new BlockSkyChest()); + this.skyCompass = constructor.registerBlockDefinition(new BlockSkyCompass()); + this.grindStone = constructor.registerTileDefinition(new BlockGrinder()); + this.crankHandle = constructor.registerTileDefinition(new BlockCrank()); + this.inscriber = constructor.registerTileDefinition(new BlockInscriber()); + this.wireless = constructor.registerTileDefinition(new BlockWireless()); + this.charger = constructor.registerTileDefinition(new BlockCharger()); + this.tinyTNT = constructor.registerBlockDefinition(new BlockTinyTNT()); + this.security = constructor.registerTileDefinition(new BlockSecurity()); + this.quantumRing = constructor.registerTileDefinition(new BlockQuantumRing()); + this.quantumLink + = constructor.registerTileDefinition(new BlockQuantumLinkChamber()); + this.spatialPylon = constructor.registerTileDefinition(new BlockSpatialPylon()); + this.spatialIOPort = constructor.registerTileDefinition(new BlockSpatialIOPort()); + this.multiPart = constructor.registerTileDefinition(new BlockCableBus()); + this.controller = constructor.registerTileDefinition(new BlockController()); + this.drive = constructor.registerTileDefinition(new BlockDrive()); + this.chest = constructor.registerTileDefinition(new BlockChest()); + this.iface = constructor.registerTileDefinition(new BlockInterface()); + this.cellWorkbench = constructor.registerTileDefinition(new BlockCellWorkbench()); + this.iOPort = constructor.registerTileDefinition(new BlockIOPort()); + this.condenser = constructor.registerTileDefinition(new BlockCondenser()); + this.energyAcceptor + = constructor.registerTileDefinition(new BlockEnergyAcceptor()); + this.vibrationChamber + = constructor.registerTileDefinition(new BlockVibrationChamber()); + this.quartzGrowthAccelerator = constructor.registerTileDefinition(cga); + this.energyCell = constructor.registerTileDefinition(new BlockEnergyCell()); + this.energyCellDense + = constructor.registerTileDefinition(new BlockDenseEnergyCell()); + this.energyCellCreative + = constructor.registerTileDefinition(new BlockCreativeEnergyCell()); + this.craftingUnit = constructor.registerTileDefinition(new BlockCraftingUnit()); + this.craftingAccelerator = new WrappedDamageItemDefinition(this.craftingUnit, 1); + this.craftingStorage1k + = constructor.registerTileDefinition(new BlockCraftingStorage()); + this.craftingStorage4k + = new WrappedDamageItemDefinition(this.craftingStorage1k, 1); + this.craftingStorage16k + = new WrappedDamageItemDefinition(this.craftingStorage1k, 2); + this.craftingStorage64k + = new WrappedDamageItemDefinition(this.craftingStorage1k, 3); + this.craftingMonitor + = constructor.registerTileDefinition(new BlockCraftingMonitor()); + this.molecularAssembler + = constructor.registerTileDefinition(new BlockMolecularAssembler()); + this.lightDetector = constructor.registerTileDefinition(lightDetector); + this.paint = constructor.registerTileDefinition(new BlockPaint()); + + this.skyStoneStair + = constructor.registerBlockDefinition(new SkyStoneStairBlock(skyStone, 0)); + this.skyStoneBlockStair + = constructor.registerBlockDefinition(new SkyStoneBlockStairBlock(skyStone, 1) + ); + this.skyStoneBrickStair + = constructor.registerBlockDefinition(new SkyStoneBrickStairBlock(skyStone, 2) + ); + this.skyStoneSmallBrickStair = constructor.registerBlockDefinition( + new SkyStoneSmallBrickStairBlock(skyStone, 3) + ); + + this.fluixStair + = constructor.registerBlockDefinition(new FluixStairBlock(fluixBlock)); + + this.quartzStair + = constructor.registerBlockDefinition(new QuartzStairBlock(quartzBlock)); + + this.chiseledQuartzStair = constructor.registerBlockDefinition( + new ChiseledQuartzStairBlock(chiseledQuartz) + ); + + this.quartzPillarStair + = constructor.registerBlockDefinition(new QuartzPillarStairBlock(quartzPillar) + ); + + this.skyStoneSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, + 0, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "SkyStoneSlabBlock" + )); + this.skyStoneBlockSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, + 1, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "SkyStoneBlockSlabBlock" + )); + this.skyStoneBrickSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, + 2, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "SkyStoneBrickSlabBlock" + )); + this.skyStoneSmallBrickSlab + = constructor.registerBlockDefinition(new AEBaseSlabBlock( + skyStone, + 3, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "SkyStoneSmallBrickSlabBlock" + )); + this.fluixSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + fluixBlock, + 0, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "FluixSlabBlock" + )); + this.quartzSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + quartzBlock, + 0, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "QuartzSlabBlock" + )); + this.chiseledQuartzSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + chiseledQuartz, + 0, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "ChiseledQuartzSlabBlock" + )); + this.quartzPillarSlab = constructor.registerBlockDefinition(new AEBaseSlabBlock( + quartzPillar, + 0, + EnumSet.of(AEFeature.DecorativeQuartzBlocks), + false, + "QuartzPillarSlabBlock" + )); + + this.itemGen = constructor.registerBlockDefinition(new BlockItemGen()); + this.chunkLoader = constructor.registerBlockDefinition(new BlockChunkloader()); + this.phantomNode = constructor.registerBlockDefinition(new BlockPhantomNode()); + this.cubeGenerator + = constructor.registerBlockDefinition(new BlockCubeGenerator()); + + // Legacy + this.terminal = constructor.registerTileDefinition(new BlockTerminal()); + this.craftTerminal = constructor.registerTileDefinition(new BlockCraftTerminal()); + this.craftMonitor = constructor.registerTileDefinition(new BlockCraftMonitor()); + this.legacyController + = constructor.registerTileDefinition(new BlockLegacyController()); + this.legacyWirelessAccessPoint + = constructor.registerTileDefinition(new BlockWirelessAccessPoint()); + } + + @Override + public IBlockDefinition quartzOre() { + return this.quartzOre; + } + + @Override + public IBlockDefinition quartzOreCharged() { + return this.quartzOreCharged; + } + + @Override + public IBlockDefinition matrixFrame() { + return this.matrixFrame; + } + + @Override + public IBlockDefinition quartz() { + return this.quartz; + } + + @Override + public IBlockDefinition quartzPillar() { + return this.quartzPillar; + } + + @Override + public IBlockDefinition quartzChiseled() { + return this.quartzChiseled; + } + + @Override + public IBlockDefinition quartzGlass() { + return this.quartzGlass; + } + + @Override + public IBlockDefinition quartzVibrantGlass() { + return this.quartzVibrantGlass; + } + + @Override + public IBlockDefinition quartzTorch() { + return this.quartzTorch; + } + + @Override + public IBlockDefinition fluix() { + return this.fluix; + } + + @Override + public IBlockDefinition skyStone() { + return this.skyStone; + } + + @Override + public IBlockDefinition skyChest() { + return this.skyChest; + } + + @Override + public IBlockDefinition skyCompass() { + return this.skyCompass; + } + + @Override + public IBlockDefinition skyStoneStair() { + return this.skyStoneStair; + } + + @Override + public IBlockDefinition skyStoneBlockStair() { + return this.skyStoneBlockStair; + } + + @Override + public IBlockDefinition skyStoneBrickStair() { + return this.skyStoneBrickStair; + } + + @Override + public IBlockDefinition skyStoneSmallBrickStair() { + return this.skyStoneSmallBrickStair; + } + + @Override + public IBlockDefinition fluixStair() { + return this.fluixStair; + } + + @Override + public IBlockDefinition quartzStair() { + return this.quartzStair; + } + + @Override + public IBlockDefinition chiseledQuartzStair() { + return this.chiseledQuartzStair; + } + + @Override + public IBlockDefinition quartzPillarStair() { + return this.quartzPillarStair; + } + + @Override + public IBlockDefinition skyStoneSlab() { + return this.skyStoneSlab; + } + + @Override + public IBlockDefinition skyStoneBlockSlab() { + return this.skyStoneBlockSlab; + } + + @Override + public IBlockDefinition skyStoneBrickSlab() { + return this.skyStoneBrickSlab; + } + + @Override + public IBlockDefinition skyStoneSmallBrickSlab() { + return this.skyStoneSmallBrickSlab; + } + + @Override + public IBlockDefinition fluixSlab() { + return this.fluixSlab; + } + + @Override + public IBlockDefinition quartzSlab() { + return this.quartzSlab; + } + + @Override + public IBlockDefinition chiseledQuartzSlab() { + return this.chiseledQuartzSlab; + } + + @Override + public IBlockDefinition quartzPillarSlab() { + return this.quartzPillarSlab; + } + + @Override + public ITileDefinition grindStone() { + return this.grindStone; + } + + @Override + public ITileDefinition crankHandle() { + return this.crankHandle; + } + + @Override + public ITileDefinition inscriber() { + return this.inscriber; + } + + @Override + public ITileDefinition wireless() { + return this.wireless; + } + + @Override + public ITileDefinition charger() { + return this.charger; + } + + @Override + public IBlockDefinition tinyTNT() { + return this.tinyTNT; + } + + @Override + public ITileDefinition security() { + return this.security; + } + + @Override + public ITileDefinition quantumRing() { + return this.quantumRing; + } + + @Override + public ITileDefinition quantumLink() { + return this.quantumLink; + } + + @Override + public ITileDefinition spatialPylon() { + return this.spatialPylon; + } + + @Override + public ITileDefinition spatialIOPort() { + return this.spatialIOPort; + } + + @Override + public ITileDefinition multiPart() { + return this.multiPart; + } + + @Override + public ITileDefinition controller() { + return this.controller; + } + + @Override + public ITileDefinition drive() { + return this.drive; + } + + @Override + public ITileDefinition chest() { + return this.chest; + } + + @Override + public ITileDefinition iface() { + return this.iface; + } + + @Override + public ITileDefinition cellWorkbench() { + return this.cellWorkbench; + } + + @Override + public ITileDefinition iOPort() { + return this.iOPort; + } + + @Override + public ITileDefinition condenser() { + return this.condenser; + } + + @Override + public ITileDefinition energyAcceptor() { + return this.energyAcceptor; + } + + @Override + public ITileDefinition vibrationChamber() { + return this.vibrationChamber; + } + + @Override + public ITileDefinition quartzGrowthAccelerator() { + return this.quartzGrowthAccelerator; + } + + @Override + public ITileDefinition energyCell() { + return this.energyCell; + } + + @Override + public ITileDefinition energyCellDense() { + return this.energyCellDense; + } + + @Override + public ITileDefinition energyCellCreative() { + return this.energyCellCreative; + } + + @Override + public ITileDefinition craftingUnit() { + return this.craftingUnit; + } + + @Override + public ITileDefinition craftingAccelerator() { + return this.craftingAccelerator; + } + + @Override + public ITileDefinition craftingStorage1k() { + return this.craftingStorage1k; + } + + @Override + public ITileDefinition craftingStorage4k() { + return this.craftingStorage4k; + } + + @Override + public ITileDefinition craftingStorage16k() { + return this.craftingStorage16k; + } + + @Override + public ITileDefinition craftingStorage64k() { + return this.craftingStorage64k; + } + + @Override + public ITileDefinition craftingMonitor() { + return this.craftingMonitor; + } + + @Override + public ITileDefinition molecularAssembler() { + return this.molecularAssembler; + } + + @Override + public ITileDefinition lightDetector() { + return this.lightDetector; + } + + @Override + public ITileDefinition paint() { + return this.paint; + } + + public IBlockDefinition chunkLoader() { + return this.chunkLoader; + } + + public IBlockDefinition itemGen() { + return this.itemGen; + } + + public IBlockDefinition phantomNode() { + return this.phantomNode; + } + + public IBlockDefinition cubeGenerator() { + return this.cubeGenerator; + } + + public Set orientables() { + return this.orientables; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiItems.java b/src/main/java/appeng/core/api/definitions/ApiItems.java index c86dd7cd..3885b59a 100644 --- a/src/main/java/appeng/core/api/definitions/ApiItems.java +++ b/src/main/java/appeng/core/api/definitions/ApiItems.java @@ -18,7 +18,6 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IItems; import appeng.api.util.AEColoredItemDefinition; @@ -42,366 +41,368 @@ import appeng.items.tools.ToolNetworkTool; import appeng.items.tools.powered.*; import appeng.items.tools.quartz.*; - /** * Internal implementation for the API items */ -public final class ApiItems implements IItems -{ - private final IItemDefinition certusQuartzAxe; - private final IItemDefinition certusQuartzHoe; - private final IItemDefinition certusQuartzShovel; - private final IItemDefinition certusQuartzPick; - private final IItemDefinition certusQuartzSword; - private final IItemDefinition certusQuartzWrench; - private final IItemDefinition certusQuartzKnife; +public final class ApiItems implements IItems { + private final IItemDefinition certusQuartzAxe; + private final IItemDefinition certusQuartzHoe; + private final IItemDefinition certusQuartzShovel; + private final IItemDefinition certusQuartzPick; + private final IItemDefinition certusQuartzSword; + private final IItemDefinition certusQuartzWrench; + private final IItemDefinition certusQuartzKnife; - private final IItemDefinition netherQuartzAxe; - private final IItemDefinition netherQuartzHoe; - private final IItemDefinition netherQuartzShovel; - private final IItemDefinition netherQuartzPick; - private final IItemDefinition netherQuartzSword; - private final IItemDefinition netherQuartzWrench; - private final IItemDefinition netherQuartzKnife; + private final IItemDefinition netherQuartzAxe; + private final IItemDefinition netherQuartzHoe; + private final IItemDefinition netherQuartzShovel; + private final IItemDefinition netherQuartzPick; + private final IItemDefinition netherQuartzSword; + private final IItemDefinition netherQuartzWrench; + private final IItemDefinition netherQuartzKnife; - private final IItemDefinition entropyManipulator; - private final IItemDefinition wirelessTerminal; - private final IItemDefinition biometricCard; - private final IItemDefinition chargedStaff; - private final IItemDefinition massCannon; - private final IItemDefinition memoryCard; - private final IItemDefinition networkTool; - private final IItemDefinition portableCell; + private final IItemDefinition entropyManipulator; + private final IItemDefinition wirelessTerminal; + private final IItemDefinition biometricCard; + private final IItemDefinition chargedStaff; + private final IItemDefinition massCannon; + private final IItemDefinition memoryCard; + private final IItemDefinition networkTool; + private final IItemDefinition portableCell; - private final IItemDefinition cellCreative; - private final IItemDefinition viewCell; + private final IItemDefinition cellCreative; + private final IItemDefinition viewCell; - private final IItemDefinition cell1k; - private final IItemDefinition cell4k; - private final IItemDefinition cell16k; - private final IItemDefinition cell64k; + private final IItemDefinition cell1k; + private final IItemDefinition cell4k; + private final IItemDefinition cell16k; + private final IItemDefinition cell64k; - private final IItemDefinition spatialCell2; - private final IItemDefinition spatialCell16; - private final IItemDefinition spatialCell128; + private final IItemDefinition spatialCell2; + private final IItemDefinition spatialCell16; + private final IItemDefinition spatialCell128; - private final IItemDefinition facade; - private final IItemDefinition crystalSeed; + private final IItemDefinition facade; + private final IItemDefinition crystalSeed; - // rv1 - private final IItemDefinition encodedPattern; - private final IItemDefinition colorApplicator; + // rv1 + private final IItemDefinition encodedPattern; + private final IItemDefinition colorApplicator; - private final IItemDefinition paintBall; - private final AEColoredItemDefinition coloredPaintBall; - private final AEColoredItemDefinition coloredLumenPaintBall; + private final IItemDefinition paintBall; + private final AEColoredItemDefinition coloredPaintBall; + private final AEColoredItemDefinition coloredLumenPaintBall; - // unsupported dev tools - private final IItemDefinition toolEraser; - private final IItemDefinition toolMeteoritePlacer; - private final IItemDefinition toolDebugCard; - private final IItemDefinition toolReplicatorCard; + // unsupported dev tools + private final IItemDefinition toolEraser; + private final IItemDefinition toolMeteoritePlacer; + private final IItemDefinition toolDebugCard; + private final IItemDefinition toolReplicatorCard; - public ApiItems( final DefinitionConstructor constructor ) - { - this.certusQuartzAxe = constructor.registerItemDefinition( new ToolQuartzAxe( AEFeature.CertusQuartzTools ) ); - this.certusQuartzHoe = constructor.registerItemDefinition( new ToolQuartzHoe( AEFeature.CertusQuartzTools ) ); - this.certusQuartzShovel = constructor.registerItemDefinition( new ToolQuartzSpade( AEFeature.CertusQuartzTools ) ); - this.certusQuartzPick = constructor.registerItemDefinition( new ToolQuartzPickaxe( AEFeature.CertusQuartzTools ) ); - this.certusQuartzSword = constructor.registerItemDefinition( new ToolQuartzSword( AEFeature.CertusQuartzTools ) ); - this.certusQuartzWrench = constructor.registerItemDefinition( new ToolQuartzWrench( AEFeature.CertusQuartzTools ) ); - this.certusQuartzKnife = constructor.registerItemDefinition( new ToolQuartzCuttingKnife( AEFeature.CertusQuartzTools ) ); + public ApiItems(final DefinitionConstructor constructor) { + this.certusQuartzAxe = constructor.registerItemDefinition( + new ToolQuartzAxe(AEFeature.CertusQuartzTools) + ); + this.certusQuartzHoe = constructor.registerItemDefinition( + new ToolQuartzHoe(AEFeature.CertusQuartzTools) + ); + this.certusQuartzShovel = constructor.registerItemDefinition( + new ToolQuartzSpade(AEFeature.CertusQuartzTools) + ); + this.certusQuartzPick = constructor.registerItemDefinition( + new ToolQuartzPickaxe(AEFeature.CertusQuartzTools) + ); + this.certusQuartzSword = constructor.registerItemDefinition( + new ToolQuartzSword(AEFeature.CertusQuartzTools) + ); + this.certusQuartzWrench = constructor.registerItemDefinition( + new ToolQuartzWrench(AEFeature.CertusQuartzTools) + ); + this.certusQuartzKnife = constructor.registerItemDefinition( + new ToolQuartzCuttingKnife(AEFeature.CertusQuartzTools) + ); - this.netherQuartzAxe = constructor.registerItemDefinition( new ToolQuartzAxe( AEFeature.NetherQuartzTools ) ); - this.netherQuartzHoe = constructor.registerItemDefinition( new ToolQuartzHoe( AEFeature.NetherQuartzTools ) ); - this.netherQuartzShovel = constructor.registerItemDefinition( new ToolQuartzSpade( AEFeature.NetherQuartzTools ) ); - this.netherQuartzPick = constructor.registerItemDefinition( new ToolQuartzPickaxe( AEFeature.NetherQuartzTools ) ); - this.netherQuartzSword = constructor.registerItemDefinition( new ToolQuartzSword( AEFeature.NetherQuartzTools ) ); - this.netherQuartzWrench = constructor.registerItemDefinition( new ToolQuartzWrench( AEFeature.NetherQuartzTools ) ); - this.netherQuartzKnife = constructor.registerItemDefinition( new ToolQuartzCuttingKnife( AEFeature.NetherQuartzTools ) ); + this.netherQuartzAxe = constructor.registerItemDefinition( + new ToolQuartzAxe(AEFeature.NetherQuartzTools) + ); + this.netherQuartzHoe = constructor.registerItemDefinition( + new ToolQuartzHoe(AEFeature.NetherQuartzTools) + ); + this.netherQuartzShovel = constructor.registerItemDefinition( + new ToolQuartzSpade(AEFeature.NetherQuartzTools) + ); + this.netherQuartzPick = constructor.registerItemDefinition( + new ToolQuartzPickaxe(AEFeature.NetherQuartzTools) + ); + this.netherQuartzSword = constructor.registerItemDefinition( + new ToolQuartzSword(AEFeature.NetherQuartzTools) + ); + this.netherQuartzWrench = constructor.registerItemDefinition( + new ToolQuartzWrench(AEFeature.NetherQuartzTools) + ); + this.netherQuartzKnife = constructor.registerItemDefinition( + new ToolQuartzCuttingKnife(AEFeature.NetherQuartzTools) + ); - this.entropyManipulator = constructor.registerItemDefinition( new ToolEntropyManipulator() ); - this.wirelessTerminal = constructor.registerItemDefinition( new ToolWirelessTerminal() ); - this.biometricCard = constructor.registerItemDefinition( new ToolBiometricCard() ); - this.chargedStaff = constructor.registerItemDefinition( new ToolChargedStaff() ); - this.massCannon = constructor.registerItemDefinition( new ToolMassCannon() ); - this.memoryCard = constructor.registerItemDefinition( new ToolMemoryCard() ); - this.networkTool = constructor.registerItemDefinition( new ToolNetworkTool() ); - this.portableCell = constructor.registerItemDefinition( new ToolPortableCell() ); + this.entropyManipulator + = constructor.registerItemDefinition(new ToolEntropyManipulator()); + this.wirelessTerminal + = constructor.registerItemDefinition(new ToolWirelessTerminal()); + this.biometricCard = constructor.registerItemDefinition(new ToolBiometricCard()); + this.chargedStaff = constructor.registerItemDefinition(new ToolChargedStaff()); + this.massCannon = constructor.registerItemDefinition(new ToolMassCannon()); + this.memoryCard = constructor.registerItemDefinition(new ToolMemoryCard()); + this.networkTool = constructor.registerItemDefinition(new ToolNetworkTool()); + this.portableCell = constructor.registerItemDefinition(new ToolPortableCell()); - this.cellCreative = constructor.registerItemDefinition( new ItemCreativeStorageCell() ); - this.viewCell = constructor.registerItemDefinition( new ItemViewCell() ); + this.cellCreative + = constructor.registerItemDefinition(new ItemCreativeStorageCell()); + this.viewCell = constructor.registerItemDefinition(new ItemViewCell()); - this.cell1k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell1kPart, 1 ) ); - this.cell4k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell4kPart, 4 ) ); - this.cell16k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell16kPart, 16 ) ); - this.cell64k = constructor.registerItemDefinition( new ItemBasicStorageCell( MaterialType.Cell64kPart, 64 ) ); + this.cell1k = constructor.registerItemDefinition( + new ItemBasicStorageCell(MaterialType.Cell1kPart, 1) + ); + this.cell4k = constructor.registerItemDefinition( + new ItemBasicStorageCell(MaterialType.Cell4kPart, 4) + ); + this.cell16k = constructor.registerItemDefinition( + new ItemBasicStorageCell(MaterialType.Cell16kPart, 16) + ); + this.cell64k = constructor.registerItemDefinition( + new ItemBasicStorageCell(MaterialType.Cell64kPart, 64) + ); - this.spatialCell2 = constructor.registerItemDefinition( new ItemSpatialStorageCell( 2 ) ); - this.spatialCell16 = constructor.registerItemDefinition( new ItemSpatialStorageCell( 16 ) ); - this.spatialCell128 = constructor.registerItemDefinition( new ItemSpatialStorageCell( 128 ) ); + this.spatialCell2 + = constructor.registerItemDefinition(new ItemSpatialStorageCell(2)); + this.spatialCell16 + = constructor.registerItemDefinition(new ItemSpatialStorageCell(16)); + this.spatialCell128 + = constructor.registerItemDefinition(new ItemSpatialStorageCell(128)); - this.facade = constructor.registerItemDefinition( new ItemFacade() ); - this.crystalSeed = constructor.registerItemDefinition( new ItemCrystalSeed() ); + this.facade = constructor.registerItemDefinition(new ItemFacade()); + this.crystalSeed = constructor.registerItemDefinition(new ItemCrystalSeed()); - // rv1 - this.encodedPattern = constructor.registerItemDefinition( new ItemEncodedPattern() ); - this.colorApplicator = constructor.registerItemDefinition( new ToolColorApplicator() ); + // rv1 + this.encodedPattern + = constructor.registerItemDefinition(new ItemEncodedPattern()); + this.colorApplicator + = constructor.registerItemDefinition(new ToolColorApplicator()); - this.paintBall = constructor.registerItemDefinition( new ItemPaintBall() ); - this.coloredPaintBall = constructor.constructColoredDefinition( this.paintBall, 0 ); - this.coloredLumenPaintBall = constructor.constructColoredDefinition( this.paintBall, 20 ); + this.paintBall = constructor.registerItemDefinition(new ItemPaintBall()); + this.coloredPaintBall = constructor.constructColoredDefinition(this.paintBall, 0); + this.coloredLumenPaintBall + = constructor.constructColoredDefinition(this.paintBall, 20); - this.toolEraser = constructor.registerItemDefinition( new ToolEraser() ); - this.toolMeteoritePlacer = constructor.registerItemDefinition( new ToolMeteoritePlacer() ); - this.toolDebugCard = constructor.registerItemDefinition( new ToolDebugCard() ); - this.toolReplicatorCard = constructor.registerItemDefinition( new ToolReplicatorCard() ); - } + this.toolEraser = constructor.registerItemDefinition(new ToolEraser()); + this.toolMeteoritePlacer + = constructor.registerItemDefinition(new ToolMeteoritePlacer()); + this.toolDebugCard = constructor.registerItemDefinition(new ToolDebugCard()); + this.toolReplicatorCard + = constructor.registerItemDefinition(new ToolReplicatorCard()); + } - @Override - public IItemDefinition certusQuartzAxe() - { - return this.certusQuartzAxe; - } + @Override + public IItemDefinition certusQuartzAxe() { + return this.certusQuartzAxe; + } - @Override - public IItemDefinition certusQuartzHoe() - { - return this.certusQuartzHoe; - } + @Override + public IItemDefinition certusQuartzHoe() { + return this.certusQuartzHoe; + } - @Override - public IItemDefinition certusQuartzShovel() - { - return this.certusQuartzShovel; - } + @Override + public IItemDefinition certusQuartzShovel() { + return this.certusQuartzShovel; + } - @Override - public IItemDefinition certusQuartzPick() - { - return this.certusQuartzPick; - } + @Override + public IItemDefinition certusQuartzPick() { + return this.certusQuartzPick; + } - @Override - public IItemDefinition certusQuartzSword() - { - return this.certusQuartzSword; - } + @Override + public IItemDefinition certusQuartzSword() { + return this.certusQuartzSword; + } - @Override - public IItemDefinition certusQuartzWrench() - { - return this.certusQuartzWrench; - } + @Override + public IItemDefinition certusQuartzWrench() { + return this.certusQuartzWrench; + } - @Override - public IItemDefinition certusQuartzKnife() - { - return this.certusQuartzKnife; - } + @Override + public IItemDefinition certusQuartzKnife() { + return this.certusQuartzKnife; + } - @Override - public IItemDefinition netherQuartzAxe() - { - return this.netherQuartzAxe; - } + @Override + public IItemDefinition netherQuartzAxe() { + return this.netherQuartzAxe; + } - @Override - public IItemDefinition netherQuartzHoe() - { - return this.netherQuartzHoe; - } + @Override + public IItemDefinition netherQuartzHoe() { + return this.netherQuartzHoe; + } - @Override - public IItemDefinition netherQuartzShovel() - { - return this.netherQuartzShovel; - } + @Override + public IItemDefinition netherQuartzShovel() { + return this.netherQuartzShovel; + } - @Override - public IItemDefinition netherQuartzPick() - { - return this.netherQuartzPick; - } + @Override + public IItemDefinition netherQuartzPick() { + return this.netherQuartzPick; + } - @Override - public IItemDefinition netherQuartzSword() - { - return this.netherQuartzSword; - } + @Override + public IItemDefinition netherQuartzSword() { + return this.netherQuartzSword; + } - @Override - public IItemDefinition netherQuartzWrench() - { - return this.netherQuartzWrench; - } + @Override + public IItemDefinition netherQuartzWrench() { + return this.netherQuartzWrench; + } - @Override - public IItemDefinition netherQuartzKnife() - { - return this.netherQuartzKnife; - } + @Override + public IItemDefinition netherQuartzKnife() { + return this.netherQuartzKnife; + } - @Override - public IItemDefinition entropyManipulator() - { - return this.entropyManipulator; - } + @Override + public IItemDefinition entropyManipulator() { + return this.entropyManipulator; + } - @Override - public IItemDefinition wirelessTerminal() - { - return this.wirelessTerminal; - } + @Override + public IItemDefinition wirelessTerminal() { + return this.wirelessTerminal; + } - @Override - public IItemDefinition biometricCard() - { - return this.biometricCard; - } + @Override + public IItemDefinition biometricCard() { + return this.biometricCard; + } - @Override - public IItemDefinition chargedStaff() - { - return this.memoryCard; - } + @Override + public IItemDefinition chargedStaff() { + return this.memoryCard; + } - @Override - public IItemDefinition massCannon() - { - return this.massCannon; - } + @Override + public IItemDefinition massCannon() { + return this.massCannon; + } - @Override - public IItemDefinition memoryCard() - { - return this.memoryCard; - } + @Override + public IItemDefinition memoryCard() { + return this.memoryCard; + } - @Override - public IItemDefinition networkTool() - { - return this.networkTool; - } + @Override + public IItemDefinition networkTool() { + return this.networkTool; + } - @Override - public IItemDefinition portableCell() - { - return this.portableCell; - } + @Override + public IItemDefinition portableCell() { + return this.portableCell; + } - @Override - public IItemDefinition cellCreative() - { - return this.cellCreative; - } + @Override + public IItemDefinition cellCreative() { + return this.cellCreative; + } - @Override - public IItemDefinition viewCell() - { - return this.viewCell; - } + @Override + public IItemDefinition viewCell() { + return this.viewCell; + } - @Override - public IItemDefinition cell1k() - { - return this.cell1k; - } + @Override + public IItemDefinition cell1k() { + return this.cell1k; + } - @Override - public IItemDefinition cell4k() - { - return this.cell4k; - } + @Override + public IItemDefinition cell4k() { + return this.cell4k; + } - @Override - public IItemDefinition cell16k() - { - return this.cell16k; - } + @Override + public IItemDefinition cell16k() { + return this.cell16k; + } - @Override - public IItemDefinition cell64k() - { - return this.cell64k; - } + @Override + public IItemDefinition cell64k() { + return this.cell64k; + } - @Override - public IItemDefinition spatialCell2() - { - return this.spatialCell2; - } + @Override + public IItemDefinition spatialCell2() { + return this.spatialCell2; + } - @Override - public IItemDefinition spatialCell16() - { - return this.spatialCell16; - } + @Override + public IItemDefinition spatialCell16() { + return this.spatialCell16; + } - @Override - public IItemDefinition spatialCell128() - { - return this.spatialCell128; - } + @Override + public IItemDefinition spatialCell128() { + return this.spatialCell128; + } - @Override - public IItemDefinition facade() - { - return this.facade; - } + @Override + public IItemDefinition facade() { + return this.facade; + } - @Override - public IItemDefinition crystalSeed() - { - return this.crystalSeed; - } + @Override + public IItemDefinition crystalSeed() { + return this.crystalSeed; + } - @Override - public IItemDefinition encodedPattern() - { - return this.encodedPattern; - } + @Override + public IItemDefinition encodedPattern() { + return this.encodedPattern; + } - @Override - public IItemDefinition colorApplicator() - { - return this.colorApplicator; - } + @Override + public IItemDefinition colorApplicator() { + return this.colorApplicator; + } - @Override - public AEColoredItemDefinition coloredPaintBall() - { - return this.coloredPaintBall; - } + @Override + public AEColoredItemDefinition coloredPaintBall() { + return this.coloredPaintBall; + } - @Override - public AEColoredItemDefinition coloredLumenPaintBall() - { - return this.coloredLumenPaintBall; - } + @Override + public AEColoredItemDefinition coloredLumenPaintBall() { + return this.coloredLumenPaintBall; + } - public IItemDefinition paintBall() - { - return this.paintBall; - } + public IItemDefinition paintBall() { + return this.paintBall; + } - public IItemDefinition toolEraser() - { - return this.toolEraser; - } + public IItemDefinition toolEraser() { + return this.toolEraser; + } - public IItemDefinition toolMeteoritePlacer() - { - return this.toolMeteoritePlacer; - } + public IItemDefinition toolMeteoritePlacer() { + return this.toolMeteoritePlacer; + } - public IItemDefinition toolDebugCard() - { - return this.toolDebugCard; - } + public IItemDefinition toolDebugCard() { + return this.toolDebugCard; + } - public IItemDefinition toolReplicatorCard() - { - return this.toolReplicatorCard; - } + public IItemDefinition toolReplicatorCard() { + return this.toolReplicatorCard; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiMaterials.java b/src/main/java/appeng/core/api/definitions/ApiMaterials.java index f44a0bb2..dcc98022 100644 --- a/src/main/java/appeng/core/api/definitions/ApiMaterials.java +++ b/src/main/java/appeng/core/api/definitions/ApiMaterials.java @@ -18,496 +18,548 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IMaterials; import appeng.core.features.DamagedItemDefinition; import appeng.items.materials.ItemMultiMaterial; import appeng.items.materials.MaterialType; - /** * Internal implementation for the API materials */ -public final class ApiMaterials implements IMaterials -{ - private final IItemDefinition cell2SpatialPart; - private final IItemDefinition cell16SpatialPart; - private final IItemDefinition cell128SpatialPart; - - private final IItemDefinition silicon; - private final IItemDefinition skyDust; - - private final IItemDefinition calcProcessorPress; - private final IItemDefinition engProcessorPress; - private final IItemDefinition logicProcessorPress; - - private final IItemDefinition calcProcessorPrint; - private final IItemDefinition engProcessorPrint; - private final IItemDefinition logicProcessorPrint; - - private final IItemDefinition siliconPress; - private final IItemDefinition siliconPrint; - - private final IItemDefinition namePress; - - private final IItemDefinition logicProcessor; - private final IItemDefinition calcProcessor; - private final IItemDefinition engProcessor; - - private final IItemDefinition basicCard; - private final IItemDefinition advCard; - - private final IItemDefinition purifiedCertusQuartzCrystal; - private final IItemDefinition purifiedNetherQuartzCrystal; - private final IItemDefinition purifiedFluixCrystal; - - private final IItemDefinition cell1kPart; - private final IItemDefinition cell4kPart; - private final IItemDefinition cell16kPart; - private final IItemDefinition cell64kPart; - private final IItemDefinition emptyStorageCell; - - private final IItemDefinition cardRedstone; - private final IItemDefinition cardSpeed; - private final IItemDefinition cardCapacity; - private final IItemDefinition cardFuzzy; - private final IItemDefinition cardInverter; - private final IItemDefinition cardCrafting; - - private final IItemDefinition enderDust; - private final IItemDefinition flour; - private final IItemDefinition goldDust; - private final IItemDefinition ironDust; - private final IItemDefinition fluixDust; - private final IItemDefinition certusQuartzDust; - private final IItemDefinition netherQuartzDust; - - private final IItemDefinition matterBall; - private final IItemDefinition ironNugget; - - private final IItemDefinition certusQuartzCrystal; - private final IItemDefinition certusQuartzCrystalCharged; - private final IItemDefinition fluixCrystal; - private final IItemDefinition fluixPearl; - - private final IItemDefinition woodenGear; - - private final IItemDefinition wireless; - private final IItemDefinition wirelessBooster; - - private final IItemDefinition annihilationCore; - private final IItemDefinition formationCore; - - private final IItemDefinition singularity; - private final IItemDefinition qESingularity; - private final IItemDefinition blankPattern; - - //Legacy - private final IItemDefinition conversionMatrix; - - public ApiMaterials( final DefinitionConstructor constructor ) - { - final ItemMultiMaterial itemMultiMaterial = new ItemMultiMaterial(); - constructor.registerItemDefinition( itemMultiMaterial ); - - this.cell2SpatialPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell2SpatialPart ) ); - this.cell16SpatialPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell16SpatialPart ) ); - this.cell128SpatialPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell128SpatialPart ) ); - - this.silicon = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Silicon ) ); - this.skyDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.SkyDust ) ); - - this.calcProcessorPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CalcProcessorPress ) ); - this.engProcessorPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EngProcessorPress ) ); - this.logicProcessorPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.LogicProcessorPress ) ); - - this.calcProcessorPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CalcProcessorPrint ) ); - this.engProcessorPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EngProcessorPrint ) ); - this.logicProcessorPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.LogicProcessorPrint ) ); - - this.siliconPress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.SiliconPress ) ); - this.siliconPrint = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.SiliconPrint ) ); - - this.namePress = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.NamePress ) ); - - this.logicProcessor = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.LogicProcessor ) ); - this.calcProcessor = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CalcProcessor ) ); - this.engProcessor = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EngProcessor ) ); - - this.basicCard = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.BasicCard ) ); - this.advCard = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.AdvCard ) ); - - this.purifiedCertusQuartzCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.PurifiedCertusQuartzCrystal ) ); - this.purifiedNetherQuartzCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.PurifiedNetherQuartzCrystal ) ); - this.purifiedFluixCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.PurifiedFluixCrystal ) ); - - this.cell1kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell1kPart ) ); - this.cell4kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell4kPart ) ); - this.cell16kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell16kPart ) ); - this.cell64kPart = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Cell64kPart ) ); - this.emptyStorageCell = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EmptyStorageCell ) ); - - this.cardRedstone = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardRedstone ) ); - this.cardSpeed = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardSpeed ) ); - this.cardCapacity = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardCapacity ) ); - this.cardFuzzy = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardFuzzy ) ); - this.cardInverter = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardInverter ) ); - this.cardCrafting = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CardCrafting ) ); - - this.enderDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.EnderDust ) ); - this.flour = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Flour ) ); - this.goldDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.GoldDust ) ); - this.ironDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.IronDust ) ); - this.fluixDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FluixDust ) ); - this.certusQuartzDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CertusQuartzDust ) ); - this.netherQuartzDust = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.NetherQuartzDust ) ); - - this.matterBall = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.MatterBall ) ); - this.ironNugget = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.IronNugget ) ); - - this.certusQuartzCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CertusQuartzCrystal ) ); - this.certusQuartzCrystalCharged = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.CertusQuartzCrystalCharged ) ); - this.fluixCrystal = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FluixCrystal ) ); - this.fluixPearl = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FluixPearl ) ); - - this.woodenGear = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.WoodenGear ) ); - - this.wireless = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Wireless ) ); - this.wirelessBooster = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.WirelessBooster ) ); - - this.annihilationCore = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.AnnihilationCore ) ); - this.formationCore = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.FormationCore ) ); - - this.singularity = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.Singularity ) ); - this.qESingularity = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.QESingularity ) ); - this.blankPattern = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.BlankPattern ) ); - - //Legacy - this.conversionMatrix = new DamagedItemDefinition( itemMultiMaterial.createMaterial( MaterialType.ConversionMatrix )); - } - - @Override - public IItemDefinition cell2SpatialPart() - { - return this.cell2SpatialPart; - } - - @Override - public IItemDefinition cell16SpatialPart() - { - return this.cell16SpatialPart; - } - - @Override - public IItemDefinition cell128SpatialPart() - { - return this.cell128SpatialPart; - } - - @Override - public IItemDefinition silicon() - { - return this.silicon; - } - - @Override - public IItemDefinition skyDust() - { - return this.skyDust; - } - - @Override - public IItemDefinition calcProcessorPress() - { - return this.calcProcessorPress; - } - - @Override - public IItemDefinition engProcessorPress() - { - return this.engProcessorPress; - } - - @Override - public IItemDefinition logicProcessorPress() - { - return this.logicProcessorPress; - } - - @Override - public IItemDefinition calcProcessorPrint() - { - return this.calcProcessorPrint; - } - - @Override - public IItemDefinition engProcessorPrint() - { - return this.engProcessorPrint; - } - - @Override - public IItemDefinition logicProcessorPrint() - { - return this.logicProcessorPrint; - } - - @Override - public IItemDefinition siliconPress() - { - return this.siliconPress; - } - - @Override - public IItemDefinition siliconPrint() - { - return this.siliconPrint; - } - - @Override - public IItemDefinition namePress() - { - return this.namePress; - } - - @Override - public IItemDefinition logicProcessor() - { - return this.logicProcessor; - } - - @Override - public IItemDefinition calcProcessor() - { - return this.calcProcessor; - } - - @Override - public IItemDefinition engProcessor() - { - return this.engProcessor; - } - - @Override - public IItemDefinition basicCard() - { - return this.basicCard; - } - - @Override - public IItemDefinition advCard() - { - return this.advCard; - } - - @Override - public IItemDefinition purifiedCertusQuartzCrystal() - { - return this.purifiedCertusQuartzCrystal; - } - - @Override - public IItemDefinition purifiedNetherQuartzCrystal() - { - return this.purifiedNetherQuartzCrystal; - } - - @Override - public IItemDefinition purifiedFluixCrystal() - { - return this.purifiedFluixCrystal; - } - - @Override - public IItemDefinition cell1kPart() - { - return this.cell1kPart; - } - - @Override - public IItemDefinition cell4kPart() - { - return this.cell4kPart; - } - - @Override - public IItemDefinition cell16kPart() - { - return this.cell16kPart; - } - - @Override - public IItemDefinition cell64kPart() - { - return this.cell64kPart; - } - - @Override - public IItemDefinition emptyStorageCell() - { - return this.emptyStorageCell; - } - - @Override - public IItemDefinition cardRedstone() - { - return this.cardRedstone; - } - - @Override - public IItemDefinition cardSpeed() - { - return this.cardSpeed; - } - - @Override - public IItemDefinition cardCapacity() - { - return this.cardCapacity; - } - - @Override - public IItemDefinition cardFuzzy() - { - return this.cardFuzzy; - } - - @Override - public IItemDefinition cardInverter() - { - return this.cardInverter; - } - - @Override - public IItemDefinition cardCrafting() - { - return this.cardCrafting; - } - - @Override - public IItemDefinition enderDust() - { - return this.enderDust; - } - - @Override - public IItemDefinition flour() - { - return this.flour; - } - - @Override - public IItemDefinition goldDust() - { - return this.goldDust; - } - - @Override - public IItemDefinition ironDust() - { - return this.ironDust; - } - - @Override - public IItemDefinition fluixDust() - { - return this.fluixDust; - } - - @Override - public IItemDefinition certusQuartzDust() - { - return this.certusQuartzDust; - } - - @Override - public IItemDefinition netherQuartzDust() - { - return this.netherQuartzDust; - } - - @Override - public IItemDefinition matterBall() - { - return this.matterBall; - } - - @Override - public IItemDefinition ironNugget() - { - return this.ironNugget; - } - - @Override - public IItemDefinition certusQuartzCrystal() - { - return this.certusQuartzCrystal; - } - - @Override - public IItemDefinition certusQuartzCrystalCharged() - { - return this.certusQuartzCrystalCharged; - } - - @Override - public IItemDefinition fluixCrystal() - { - return this.fluixCrystal; - } - - @Override - public IItemDefinition fluixPearl() - { - return this.fluixPearl; - } - - @Override - public IItemDefinition woodenGear() - { - return this.woodenGear; - } - - @Override - public IItemDefinition wireless() - { - return this.wireless; - } - - @Override - public IItemDefinition wirelessBooster() - { - return this.wirelessBooster; - } - - @Override - public IItemDefinition annihilationCore() - { - return this.annihilationCore; - } - - @Override - public IItemDefinition formationCore() - { - return this.formationCore; - } - - @Override - public IItemDefinition singularity() - { - return this.singularity; - } - - @Override - public IItemDefinition qESingularity() - { - return this.qESingularity; - } - - @Override - public IItemDefinition blankPattern() - { - return this.blankPattern; - } +public final class ApiMaterials implements IMaterials { + private final IItemDefinition cell2SpatialPart; + private final IItemDefinition cell16SpatialPart; + private final IItemDefinition cell128SpatialPart; + + private final IItemDefinition silicon; + private final IItemDefinition skyDust; + + private final IItemDefinition calcProcessorPress; + private final IItemDefinition engProcessorPress; + private final IItemDefinition logicProcessorPress; + + private final IItemDefinition calcProcessorPrint; + private final IItemDefinition engProcessorPrint; + private final IItemDefinition logicProcessorPrint; + + private final IItemDefinition siliconPress; + private final IItemDefinition siliconPrint; + + private final IItemDefinition namePress; + + private final IItemDefinition logicProcessor; + private final IItemDefinition calcProcessor; + private final IItemDefinition engProcessor; + + private final IItemDefinition basicCard; + private final IItemDefinition advCard; + + private final IItemDefinition purifiedCertusQuartzCrystal; + private final IItemDefinition purifiedNetherQuartzCrystal; + private final IItemDefinition purifiedFluixCrystal; + + private final IItemDefinition cell1kPart; + private final IItemDefinition cell4kPart; + private final IItemDefinition cell16kPart; + private final IItemDefinition cell64kPart; + private final IItemDefinition emptyStorageCell; + + private final IItemDefinition cardRedstone; + private final IItemDefinition cardSpeed; + private final IItemDefinition cardCapacity; + private final IItemDefinition cardFuzzy; + private final IItemDefinition cardInverter; + private final IItemDefinition cardCrafting; + + private final IItemDefinition enderDust; + private final IItemDefinition flour; + private final IItemDefinition goldDust; + private final IItemDefinition ironDust; + private final IItemDefinition fluixDust; + private final IItemDefinition certusQuartzDust; + private final IItemDefinition netherQuartzDust; + + private final IItemDefinition matterBall; + private final IItemDefinition ironNugget; + + private final IItemDefinition certusQuartzCrystal; + private final IItemDefinition certusQuartzCrystalCharged; + private final IItemDefinition fluixCrystal; + private final IItemDefinition fluixPearl; + + private final IItemDefinition woodenGear; + + private final IItemDefinition wireless; + private final IItemDefinition wirelessBooster; + + private final IItemDefinition annihilationCore; + private final IItemDefinition formationCore; + + private final IItemDefinition singularity; + private final IItemDefinition qESingularity; + private final IItemDefinition blankPattern; + + //Legacy + private final IItemDefinition conversionMatrix; + + public ApiMaterials(final DefinitionConstructor constructor) { + final ItemMultiMaterial itemMultiMaterial = new ItemMultiMaterial(); + constructor.registerItemDefinition(itemMultiMaterial); + + this.cell2SpatialPart = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Cell2SpatialPart) + ); + this.cell16SpatialPart = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Cell16SpatialPart) + ); + this.cell128SpatialPart = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Cell128SpatialPart) + ); + + this.silicon = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Silicon) + ); + this.skyDust = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.SkyDust) + ); + + this.calcProcessorPress = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CalcProcessorPress) + ); + this.engProcessorPress = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.EngProcessorPress) + ); + this.logicProcessorPress = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.LogicProcessorPress) + ); + + this.calcProcessorPrint = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CalcProcessorPrint) + ); + this.engProcessorPrint = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.EngProcessorPrint) + ); + this.logicProcessorPrint = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.LogicProcessorPrint) + ); + + this.siliconPress = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.SiliconPress) + ); + this.siliconPrint = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.SiliconPrint) + ); + + this.namePress = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.NamePress) + ); + + this.logicProcessor = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.LogicProcessor) + ); + this.calcProcessor = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CalcProcessor) + ); + this.engProcessor = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.EngProcessor) + ); + + this.basicCard = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.BasicCard) + ); + this.advCard = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.AdvCard) + ); + + this.purifiedCertusQuartzCrystal = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.PurifiedCertusQuartzCrystal) + ); + this.purifiedNetherQuartzCrystal = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.PurifiedNetherQuartzCrystal) + ); + this.purifiedFluixCrystal = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.PurifiedFluixCrystal) + ); + + this.cell1kPart = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Cell1kPart) + ); + this.cell4kPart = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Cell4kPart) + ); + this.cell16kPart = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Cell16kPart) + ); + this.cell64kPart = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Cell64kPart) + ); + this.emptyStorageCell = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.EmptyStorageCell) + ); + + this.cardRedstone = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CardRedstone) + ); + this.cardSpeed = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CardSpeed) + ); + this.cardCapacity = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CardCapacity) + ); + this.cardFuzzy = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CardFuzzy) + ); + this.cardInverter = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CardInverter) + ); + this.cardCrafting = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CardCrafting) + ); + + this.enderDust = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.EnderDust) + ); + this.flour = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Flour) + ); + this.goldDust = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.GoldDust) + ); + this.ironDust = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.IronDust) + ); + this.fluixDust = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.FluixDust) + ); + this.certusQuartzDust = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CertusQuartzDust) + ); + this.netherQuartzDust = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.NetherQuartzDust) + ); + + this.matterBall = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.MatterBall) + ); + this.ironNugget = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.IronNugget) + ); + + this.certusQuartzCrystal = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CertusQuartzCrystal) + ); + this.certusQuartzCrystalCharged = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.CertusQuartzCrystalCharged) + ); + this.fluixCrystal = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.FluixCrystal) + ); + this.fluixPearl = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.FluixPearl) + ); + + this.woodenGear = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.WoodenGear) + ); + + this.wireless = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Wireless) + ); + this.wirelessBooster = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.WirelessBooster) + ); + + this.annihilationCore = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.AnnihilationCore) + ); + this.formationCore = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.FormationCore) + ); + + this.singularity = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.Singularity) + ); + this.qESingularity = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.QESingularity) + ); + this.blankPattern = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.BlankPattern) + ); + + //Legacy + this.conversionMatrix = new DamagedItemDefinition( + itemMultiMaterial.createMaterial(MaterialType.ConversionMatrix) + ); + } + + @Override + public IItemDefinition cell2SpatialPart() { + return this.cell2SpatialPart; + } + + @Override + public IItemDefinition cell16SpatialPart() { + return this.cell16SpatialPart; + } + + @Override + public IItemDefinition cell128SpatialPart() { + return this.cell128SpatialPart; + } + + @Override + public IItemDefinition silicon() { + return this.silicon; + } + + @Override + public IItemDefinition skyDust() { + return this.skyDust; + } + + @Override + public IItemDefinition calcProcessorPress() { + return this.calcProcessorPress; + } + + @Override + public IItemDefinition engProcessorPress() { + return this.engProcessorPress; + } + + @Override + public IItemDefinition logicProcessorPress() { + return this.logicProcessorPress; + } + + @Override + public IItemDefinition calcProcessorPrint() { + return this.calcProcessorPrint; + } + + @Override + public IItemDefinition engProcessorPrint() { + return this.engProcessorPrint; + } + + @Override + public IItemDefinition logicProcessorPrint() { + return this.logicProcessorPrint; + } + + @Override + public IItemDefinition siliconPress() { + return this.siliconPress; + } + + @Override + public IItemDefinition siliconPrint() { + return this.siliconPrint; + } + + @Override + public IItemDefinition namePress() { + return this.namePress; + } + + @Override + public IItemDefinition logicProcessor() { + return this.logicProcessor; + } + + @Override + public IItemDefinition calcProcessor() { + return this.calcProcessor; + } + + @Override + public IItemDefinition engProcessor() { + return this.engProcessor; + } + + @Override + public IItemDefinition basicCard() { + return this.basicCard; + } + + @Override + public IItemDefinition advCard() { + return this.advCard; + } + + @Override + public IItemDefinition purifiedCertusQuartzCrystal() { + return this.purifiedCertusQuartzCrystal; + } + + @Override + public IItemDefinition purifiedNetherQuartzCrystal() { + return this.purifiedNetherQuartzCrystal; + } + + @Override + public IItemDefinition purifiedFluixCrystal() { + return this.purifiedFluixCrystal; + } + + @Override + public IItemDefinition cell1kPart() { + return this.cell1kPart; + } + + @Override + public IItemDefinition cell4kPart() { + return this.cell4kPart; + } + + @Override + public IItemDefinition cell16kPart() { + return this.cell16kPart; + } + + @Override + public IItemDefinition cell64kPart() { + return this.cell64kPart; + } + + @Override + public IItemDefinition emptyStorageCell() { + return this.emptyStorageCell; + } + + @Override + public IItemDefinition cardRedstone() { + return this.cardRedstone; + } + + @Override + public IItemDefinition cardSpeed() { + return this.cardSpeed; + } + + @Override + public IItemDefinition cardCapacity() { + return this.cardCapacity; + } + + @Override + public IItemDefinition cardFuzzy() { + return this.cardFuzzy; + } + + @Override + public IItemDefinition cardInverter() { + return this.cardInverter; + } + + @Override + public IItemDefinition cardCrafting() { + return this.cardCrafting; + } + + @Override + public IItemDefinition enderDust() { + return this.enderDust; + } + + @Override + public IItemDefinition flour() { + return this.flour; + } + + @Override + public IItemDefinition goldDust() { + return this.goldDust; + } + + @Override + public IItemDefinition ironDust() { + return this.ironDust; + } + + @Override + public IItemDefinition fluixDust() { + return this.fluixDust; + } + + @Override + public IItemDefinition certusQuartzDust() { + return this.certusQuartzDust; + } + + @Override + public IItemDefinition netherQuartzDust() { + return this.netherQuartzDust; + } + + @Override + public IItemDefinition matterBall() { + return this.matterBall; + } + + @Override + public IItemDefinition ironNugget() { + return this.ironNugget; + } + + @Override + public IItemDefinition certusQuartzCrystal() { + return this.certusQuartzCrystal; + } + + @Override + public IItemDefinition certusQuartzCrystalCharged() { + return this.certusQuartzCrystalCharged; + } + + @Override + public IItemDefinition fluixCrystal() { + return this.fluixCrystal; + } + + @Override + public IItemDefinition fluixPearl() { + return this.fluixPearl; + } + + @Override + public IItemDefinition woodenGear() { + return this.woodenGear; + } + + @Override + public IItemDefinition wireless() { + return this.wireless; + } + + @Override + public IItemDefinition wirelessBooster() { + return this.wirelessBooster; + } + + @Override + public IItemDefinition annihilationCore() { + return this.annihilationCore; + } + + @Override + public IItemDefinition formationCore() { + return this.formationCore; + } + + @Override + public IItemDefinition singularity() { + return this.singularity; + } + + @Override + public IItemDefinition qESingularity() { + return this.qESingularity; + } + + @Override + public IItemDefinition blankPattern() { + return this.blankPattern; + } } diff --git a/src/main/java/appeng/core/api/definitions/ApiParts.java b/src/main/java/appeng/core/api/definitions/ApiParts.java index 0f57f9e2..2bab77a7 100644 --- a/src/main/java/appeng/core/api/definitions/ApiParts.java +++ b/src/main/java/appeng/core/api/definitions/ApiParts.java @@ -18,7 +18,6 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.IParts; import appeng.api.exceptions.MissingDefinition; @@ -28,325 +27,339 @@ import appeng.core.features.DamagedItemDefinition; import appeng.items.parts.ItemMultiPart; import appeng.items.parts.PartType; - /** * Internal implementation for the API parts */ -public final class ApiParts implements IParts -{ - private final AEColoredItemDefinition cableSmart; - 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 IItemDefinition quartzFiber; - private final IItemDefinition toggleBus; - private final IItemDefinition invertedToggleBus; - private final IItemDefinition storageBus; - private final IItemDefinition importBus; - private final IItemDefinition exportBus; - private final IItemDefinition iface; - private final IItemDefinition levelEmitter; - private final IItemDefinition annihilationPlane; - private final IItemDefinition identityAnnihilationPlane; - private final IItemDefinition formationPlane; - private final IItemDefinition p2PTunnelME; - private final IItemDefinition p2PTunnelRedstone; - private final IItemDefinition p2PTunnelItems; - private final IItemDefinition p2PTunnelLiquids; - private final IItemDefinition p2PTunnelEU; - private final IItemDefinition p2PTunnelRF; - private final IItemDefinition p2PTunnelLight; - private final IItemDefinition p2PTunnelOpenComputers; - private final IItemDefinition p2PTunnelPneumaticCraft; - private final IItemDefinition cableAnchor; - private final IItemDefinition monitor; - private final IItemDefinition semiDarkMonitor; - private final IItemDefinition darkMonitor; - private final IItemDefinition interfaceTerminal; - private final IItemDefinition patternTerminal; - private final IItemDefinition craftingTerminal; - private final IItemDefinition terminal; - private final IItemDefinition storageMonitor; - private final IItemDefinition conversionMonitor; +public final class ApiParts implements IParts { + private final AEColoredItemDefinition cableSmart; + 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 IItemDefinition quartzFiber; + private final IItemDefinition toggleBus; + private final IItemDefinition invertedToggleBus; + private final IItemDefinition storageBus; + private final IItemDefinition importBus; + private final IItemDefinition exportBus; + private final IItemDefinition iface; + private final IItemDefinition levelEmitter; + private final IItemDefinition annihilationPlane; + private final IItemDefinition identityAnnihilationPlane; + private final IItemDefinition formationPlane; + private final IItemDefinition p2PTunnelME; + private final IItemDefinition p2PTunnelRedstone; + private final IItemDefinition p2PTunnelItems; + private final IItemDefinition p2PTunnelLiquids; + private final IItemDefinition p2PTunnelEU; + private final IItemDefinition p2PTunnelRF; + private final IItemDefinition p2PTunnelLight; + private final IItemDefinition p2PTunnelOpenComputers; + private final IItemDefinition p2PTunnelPneumaticCraft; + private final IItemDefinition cableAnchor; + private final IItemDefinition monitor; + private final IItemDefinition semiDarkMonitor; + private final IItemDefinition darkMonitor; + private final IItemDefinition interfaceTerminal; + private final IItemDefinition patternTerminal; + private final IItemDefinition craftingTerminal; + private final IItemDefinition terminal; + private final IItemDefinition storageMonitor; + private final IItemDefinition conversionMonitor; - public ApiParts( final DefinitionConstructor constructor, final IPartHelper partHelper ) - { - final ItemMultiPart itemMultiPart = new ItemMultiPart( partHelper ); - constructor.registerItemDefinition( itemMultiPart ); + public ApiParts( + final DefinitionConstructor constructor, final IPartHelper partHelper + ) { + final ItemMultiPart itemMultiPart = new ItemMultiPart(partHelper); + constructor.registerItemDefinition(itemMultiPart); - this.cableSmart = constructor.constructColoredDefinition( itemMultiPart, PartType.CableSmart ); - 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.quartzFiber = new DamagedItemDefinition( itemMultiPart.createPart( PartType.QuartzFiber ) ); - this.toggleBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ToggleBus ) ); - this.invertedToggleBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.InvertedToggleBus ) ); - this.storageBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.StorageBus ) ); - this.importBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ImportBus ) ); - this.exportBus = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ExportBus ) ); - this.iface = new DamagedItemDefinition( itemMultiPart.createPart( PartType.Interface ) ); - this.levelEmitter = new DamagedItemDefinition( itemMultiPart.createPart( PartType.LevelEmitter ) ); - this.annihilationPlane = new DamagedItemDefinition( itemMultiPart.createPart( PartType.AnnihilationPlane ) ); - this.identityAnnihilationPlane = new DamagedItemDefinition( itemMultiPart.createPart( PartType.IdentityAnnihilationPlane ) ); - this.formationPlane = new DamagedItemDefinition( itemMultiPart.createPart( PartType.FormationPlane ) ); - this.p2PTunnelME = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelME ) ); - this.p2PTunnelRedstone = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelRedstone ) ); - this.p2PTunnelItems = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelItems ) ); - this.p2PTunnelLiquids = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelLiquids ) ); - this.p2PTunnelEU = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelEU ) ); - this.p2PTunnelRF = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelRF ) ); - this.p2PTunnelLight = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelLight ) ); - this.p2PTunnelOpenComputers = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelOpenComputers ) ); - this.p2PTunnelPneumaticCraft = new DamagedItemDefinition( itemMultiPart.createPart( PartType.P2PTunnelPressure ) ); - this.cableAnchor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.CableAnchor ) ); - this.monitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.Monitor ) ); - this.semiDarkMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.SemiDarkMonitor ) ); - this.darkMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.DarkMonitor ) ); - this.interfaceTerminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.InterfaceTerminal ) ); - this.patternTerminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.PatternTerminal ) ); - this.craftingTerminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.CraftingTerminal ) ); - this.terminal = new DamagedItemDefinition( itemMultiPart.createPart( PartType.Terminal ) ); - this.storageMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.StorageMonitor ) ); - this.conversionMonitor = new DamagedItemDefinition( itemMultiPart.createPart( PartType.ConversionMonitor ) ); - } + this.cableSmart + = constructor.constructColoredDefinition(itemMultiPart, PartType.CableSmart); + 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.quartzFiber + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.QuartzFiber)); + this.toggleBus + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.ToggleBus)); + this.invertedToggleBus = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.InvertedToggleBus) + ); + this.storageBus + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.StorageBus)); + this.importBus + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.ImportBus)); + this.exportBus + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.ExportBus)); + this.iface + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.Interface)); + this.levelEmitter + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.LevelEmitter)); + this.annihilationPlane = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.AnnihilationPlane) + ); + this.identityAnnihilationPlane = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.IdentityAnnihilationPlane) + ); + this.formationPlane + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.FormationPlane) + ); + this.p2PTunnelME + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelME)); + this.p2PTunnelRedstone = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.P2PTunnelRedstone) + ); + this.p2PTunnelItems + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelItems) + ); + this.p2PTunnelLiquids + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelLiquids + )); + this.p2PTunnelEU + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelEU)); + this.p2PTunnelRF + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelRF)); + this.p2PTunnelLight + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.P2PTunnelLight) + ); + this.p2PTunnelOpenComputers = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.P2PTunnelOpenComputers) + ); + this.p2PTunnelPneumaticCraft = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.P2PTunnelPressure) + ); + this.cableAnchor + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.CableAnchor)); + this.monitor + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.Monitor)); + this.semiDarkMonitor + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.SemiDarkMonitor) + ); + this.darkMonitor + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.DarkMonitor)); + this.interfaceTerminal = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.InterfaceTerminal) + ); + this.patternTerminal + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.PatternTerminal) + ); + this.craftingTerminal + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.CraftingTerminal + )); + this.terminal + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.Terminal)); + this.storageMonitor + = new DamagedItemDefinition(itemMultiPart.createPart(PartType.StorageMonitor) + ); + this.conversionMonitor = new DamagedItemDefinition( + itemMultiPart.createPart(PartType.ConversionMonitor) + ); + } - @Override - public AEColoredItemDefinition cableSmart() - { - return this.cableSmart; - } + @Override + public AEColoredItemDefinition cableSmart() { + return this.cableSmart; + } - @Override - public AEColoredItemDefinition cableCovered() - { - return this.cableCovered; - } + @Override + public AEColoredItemDefinition cableCovered() { + return this.cableCovered; + } - @Override - public AEColoredItemDefinition cableGlass() - { - return this.cableGlass; - } + @Override + public AEColoredItemDefinition cableGlass() { + return this.cableGlass; + } - @Override - public AEColoredItemDefinition cableDense() - { - return this.cableDense; - } + @Override + public AEColoredItemDefinition cableDense() { + return this.cableDense; + } - @Override - public AEColoredItemDefinition lumenCableSmart() - { - throw new MissingDefinition( "Lumen Smart Cable has yet to be implemented." ); - // return this.lumenCableSmart; - } + @Override + public AEColoredItemDefinition lumenCableSmart() { + throw new MissingDefinition("Lumen Smart Cable has yet to be implemented."); + // return this.lumenCableSmart; + } - @Override - public AEColoredItemDefinition lumenCableCovered() - { - throw new MissingDefinition( "Lumen Covered Cable has yet to be implemented." ); - // return this.lumenCableCovered; - } + @Override + public AEColoredItemDefinition lumenCableCovered() { + throw new MissingDefinition("Lumen Covered Cable has yet to be implemented."); + // return this.lumenCableCovered; + } - @Override - public AEColoredItemDefinition lumenCableGlass() - { - throw new MissingDefinition( "Lumen Glass Cable has yet to be implemented." ); - // return this.lumenCableGlass; - } + @Override + public AEColoredItemDefinition lumenCableGlass() { + throw new MissingDefinition("Lumen Glass Cable has yet to be implemented."); + // return this.lumenCableGlass; + } - @Override - public AEColoredItemDefinition lumenCableDense() - { - throw new MissingDefinition( "Lumen Dense Cable has yet to be implemented." ); - // return this.lumenCableDense; - } + @Override + public AEColoredItemDefinition lumenCableDense() { + throw new MissingDefinition("Lumen Dense Cable has yet to be implemented."); + // return this.lumenCableDense; + } - @Override - public IItemDefinition quartzFiber() - { - return this.quartzFiber; - } + @Override + public IItemDefinition quartzFiber() { + return this.quartzFiber; + } - @Override - public IItemDefinition toggleBus() - { - return this.toggleBus; - } + @Override + public IItemDefinition toggleBus() { + return this.toggleBus; + } - @Override - public IItemDefinition invertedToggleBus() - { - return this.invertedToggleBus; - } + @Override + public IItemDefinition invertedToggleBus() { + return this.invertedToggleBus; + } - @Override - public IItemDefinition storageBus() - { - return this.storageBus; - } + @Override + public IItemDefinition storageBus() { + return this.storageBus; + } - @Override - public IItemDefinition importBus() - { - return this.importBus; - } + @Override + public IItemDefinition importBus() { + return this.importBus; + } - @Override - public IItemDefinition exportBus() - { - return this.exportBus; - } + @Override + public IItemDefinition exportBus() { + return this.exportBus; + } - @Override - public IItemDefinition iface() - { - return this.iface; - } + @Override + public IItemDefinition iface() { + return this.iface; + } - @Override - public IItemDefinition levelEmitter() - { - return this.levelEmitter; - } + @Override + public IItemDefinition levelEmitter() { + return this.levelEmitter; + } - @Override - public IItemDefinition annihilationPlane() - { - return this.annihilationPlane; - } + @Override + public IItemDefinition annihilationPlane() { + return this.annihilationPlane; + } - @Override - public IItemDefinition identityAnnihilationPlane() - { - return this.identityAnnihilationPlane; - } + @Override + public IItemDefinition identityAnnihilationPlane() { + return this.identityAnnihilationPlane; + } - @Override - public IItemDefinition formationPlane() - { - return this.formationPlane; - } + @Override + public IItemDefinition formationPlane() { + return this.formationPlane; + } - @Override - public IItemDefinition p2PTunnelME() - { - return this.p2PTunnelME; - } + @Override + public IItemDefinition p2PTunnelME() { + return this.p2PTunnelME; + } - @Override - public IItemDefinition p2PTunnelRedstone() - { - return this.p2PTunnelRedstone; - } + @Override + public IItemDefinition p2PTunnelRedstone() { + return this.p2PTunnelRedstone; + } - @Override - public IItemDefinition p2PTunnelItems() - { - return this.p2PTunnelItems; - } + @Override + public IItemDefinition p2PTunnelItems() { + return this.p2PTunnelItems; + } - @Override - public IItemDefinition p2PTunnelLiquids() - { - return this.p2PTunnelLiquids; - } + @Override + public IItemDefinition p2PTunnelLiquids() { + return this.p2PTunnelLiquids; + } - @Override - public IItemDefinition p2PTunnelEU() - { - return this.p2PTunnelEU; - } + @Override + public IItemDefinition p2PTunnelEU() { + return this.p2PTunnelEU; + } - @Override - public IItemDefinition p2PTunnelRF() - { - return this.p2PTunnelRF; - } + @Override + public IItemDefinition p2PTunnelRF() { + return this.p2PTunnelRF; + } - @Override - public IItemDefinition p2PTunnelLight() - { - return this.p2PTunnelLight; - } + @Override + public IItemDefinition p2PTunnelLight() { + return this.p2PTunnelLight; + } - @Override - public IItemDefinition p2PTunnelOpenComputers() - { - return this.p2PTunnelOpenComputers; - } + @Override + public IItemDefinition p2PTunnelOpenComputers() { + return this.p2PTunnelOpenComputers; + } - @Override - public IItemDefinition p2PTunnelPneumaticCraft() - { - return this.p2PTunnelPneumaticCraft; - } + @Override + public IItemDefinition p2PTunnelPneumaticCraft() { + return this.p2PTunnelPneumaticCraft; + } - @Override - public IItemDefinition cableAnchor() - { - return this.cableAnchor; - } + @Override + public IItemDefinition cableAnchor() { + return this.cableAnchor; + } - @Override - public IItemDefinition monitor() - { - return this.monitor; - } + @Override + public IItemDefinition monitor() { + return this.monitor; + } - @Override - public IItemDefinition semiDarkMonitor() - { - return this.semiDarkMonitor; - } + @Override + public IItemDefinition semiDarkMonitor() { + return this.semiDarkMonitor; + } - @Override - public IItemDefinition darkMonitor() - { - return this.darkMonitor; - } + @Override + public IItemDefinition darkMonitor() { + return this.darkMonitor; + } - @Override - public IItemDefinition interfaceTerminal() - { - return this.interfaceTerminal; - } + @Override + public IItemDefinition interfaceTerminal() { + return this.interfaceTerminal; + } - @Override - public IItemDefinition patternTerminal() - { - return this.patternTerminal; - } + @Override + public IItemDefinition patternTerminal() { + return this.patternTerminal; + } - @Override - public IItemDefinition craftingTerminal() - { - return this.craftingTerminal; - } + @Override + public IItemDefinition craftingTerminal() { + return this.craftingTerminal; + } - @Override - public IItemDefinition terminal() - { - return this.terminal; - } + @Override + public IItemDefinition terminal() { + return this.terminal; + } - @Override - public IItemDefinition storageMonitor() - { - return this.storageMonitor; - } + @Override + public IItemDefinition storageMonitor() { + return this.storageMonitor; + } - @Override - public IItemDefinition conversionMonitor() - { - return this.conversionMonitor; - } + @Override + public IItemDefinition conversionMonitor() { + return this.conversionMonitor; + } } diff --git a/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java b/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java index c81805c9..c0d3d8f8 100644 --- a/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java +++ b/src/main/java/appeng/core/api/definitions/DefinitionConstructor.java @@ -18,7 +18,6 @@ package appeng.core.api.definitions; - import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IItemDefinition; import appeng.api.definitions.ITileDefinition; @@ -31,85 +30,77 @@ import appeng.items.parts.ItemMultiPart; import appeng.items.parts.PartType; import net.minecraft.item.Item; +public class DefinitionConstructor { + private final FeatureRegistry features; + private final FeatureHandlerRegistry handlers; -public class DefinitionConstructor -{ - private final FeatureRegistry features; - private final FeatureHandlerRegistry handlers; + public DefinitionConstructor( + final FeatureRegistry features, final FeatureHandlerRegistry handlers + ) { + this.features = features; + this.handlers = handlers; + } - public DefinitionConstructor( final FeatureRegistry features, final FeatureHandlerRegistry handlers ) - { - this.features = features; - this.handlers = handlers; - } + final ITileDefinition registerTileDefinition(final IAEFeature feature) { + final IBlockDefinition definition = this.registerBlockDefinition(feature); - final ITileDefinition registerTileDefinition( final IAEFeature feature ) - { - final IBlockDefinition definition = this.registerBlockDefinition( feature ); + if (definition instanceof ITileDefinition) { + return ((ITileDefinition) definition); + } - if( definition instanceof ITileDefinition ) - { - return ( (ITileDefinition) definition ); - } + throw new IllegalStateException("No tile definition for " + feature); + } - throw new IllegalStateException( "No tile definition for " + feature ); - } + final IBlockDefinition registerBlockDefinition(final IAEFeature feature) { + final IItemDefinition definition = this.registerItemDefinition(feature); - final IBlockDefinition registerBlockDefinition( final IAEFeature feature ) - { - final IItemDefinition definition = this.registerItemDefinition( feature ); + if (definition instanceof IBlockDefinition) { + return ((IBlockDefinition) definition); + } - if( definition instanceof IBlockDefinition ) - { - return ( (IBlockDefinition) definition ); - } + throw new IllegalStateException("No block definition for " + feature); + } - throw new IllegalStateException( "No block definition for " + feature ); - } + final IItemDefinition registerItemDefinition(final IAEFeature feature) { + final IFeatureHandler handler = feature.handler(); - final IItemDefinition registerItemDefinition( final IAEFeature feature ) - { - final IFeatureHandler handler = feature.handler(); + if (handler.isFeatureAvailable()) { + this.handlers.addFeatureHandler(handler); + this.features.addFeature(feature); + } - if( handler.isFeatureAvailable() ) - { - this.handlers.addFeatureHandler( handler ); - this.features.addFeature( feature ); - } + final IItemDefinition definition = handler.getDefinition(); - final IItemDefinition definition = handler.getDefinition(); + return definition; + } - return definition; - } + final AEColoredItemDefinition + constructColoredDefinition(final IItemDefinition target, final int offset) { + final ColoredItemDefinition definition = new ColoredItemDefinition(); - final AEColoredItemDefinition constructColoredDefinition( final IItemDefinition target, final int offset ) - { - final ColoredItemDefinition definition = new ColoredItemDefinition(); + for (final Item targetItem : target.maybeItem().asSet()) { + for (final AEColor color : AEColor.VALID_COLORS) { + final ActivityState state = ActivityState.from(target.isEnabled()); - for( final Item targetItem : target.maybeItem().asSet() ) - { - for( final AEColor color : AEColor.VALID_COLORS ) - { - final ActivityState state = ActivityState.from( target.isEnabled() ); + definition.add( + color, new ItemStackSrc(targetItem, offset + color.ordinal(), state) + ); + } + } - definition.add( color, new ItemStackSrc( targetItem, offset + color.ordinal(), state ) ); - } - } + return definition; + } - return definition; - } + final AEColoredItemDefinition + constructColoredDefinition(final ItemMultiPart target, final PartType type) { + final ColoredItemDefinition definition = new ColoredItemDefinition(); - final AEColoredItemDefinition constructColoredDefinition( final ItemMultiPart target, final PartType type ) - { - final ColoredItemDefinition definition = new ColoredItemDefinition(); + for (final AEColor color : AEColor.values()) { + final ItemStackSrc multiPartSource = target.createPart(type, color); - for( final AEColor color : AEColor.values() ) - { - final ItemStackSrc multiPartSource = target.createPart( type, color ); + definition.add(color, multiPartSource); + } - definition.add( color, multiPartSource ); - } - - return definition; - } + return definition; + } } diff --git a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java index af040c5e..f2d9404c 100644 --- a/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCBlackListSpatial.java @@ -18,7 +18,6 @@ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.AELog; import appeng.core.api.IIMCProcessor; @@ -26,25 +25,18 @@ import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; +public class IMCBlackListSpatial implements IIMCProcessor { + @Override + public void process(final IMCMessage m) { + final ItemStack is = m.getItemStackValue(); + if (is != null) { + final Block blk = Block.getBlockFromItem(is.getItem()); + if (blk != null) { + AEApi.instance().registries().movable().blacklistBlock(blk); + return; + } + } -public class IMCBlackListSpatial implements IIMCProcessor -{ - - @Override - public void process( final IMCMessage m ) - { - - final ItemStack is = m.getItemStackValue(); - if( is != null ) - { - final Block blk = Block.getBlockFromItem( is.getItem() ); - if( blk != null ) - { - AEApi.instance().registries().movable().blacklistBlock( blk ); - return; - } - } - - AELog.info( "Bad Block blacklisted by " + m.getSender() ); - } + 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 e8e6ed91..519907f6 100644 --- a/src/main/java/appeng/core/api/imc/IMCGrinder.java +++ b/src/main/java/appeng/core/api/imc/IMCGrinder.java @@ -52,55 +52,47 @@ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.api.IIMCProcessor; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public class IMCGrinder implements IIMCProcessor { + @Override + public void process(final IMCMessage m) { + final NBTTagCompound msg = m.getNBTValue(); + final NBTTagCompound inTag = (NBTTagCompound) msg.getTag("in"); + final NBTTagCompound outTag = (NBTTagCompound) msg.getTag("out"); -public class IMCGrinder implements IIMCProcessor -{ - @Override - public void process( final IMCMessage m ) - { - final NBTTagCompound msg = m.getNBTValue(); - final NBTTagCompound inTag = (NBTTagCompound) msg.getTag( "in" ); - final NBTTagCompound outTag = (NBTTagCompound) msg.getTag( "out" ); + final ItemStack in = ItemStack.loadItemStackFromNBT(inTag); + final ItemStack out = ItemStack.loadItemStackFromNBT(outTag); - final ItemStack in = ItemStack.loadItemStackFromNBT( inTag ); - final ItemStack out = ItemStack.loadItemStackFromNBT( outTag ); + final int turns = msg.getInteger("turns"); - final int turns = msg.getInteger( "turns" ); + if (in == null) { + throw new IllegalStateException("invalid input"); + } - if( in == null ) - { - throw new IllegalStateException( "invalid input" ); - } + if (out == null) { + throw new IllegalStateException("invalid output"); + } - if( out == null ) - { - throw new IllegalStateException( "invalid output" ); - } + if (msg.hasKey("optional")) { + final NBTTagCompound optionalTag = (NBTTagCompound) msg.getTag("optional"); + final ItemStack optional = ItemStack.loadItemStackFromNBT(optionalTag); - if( msg.hasKey( "optional" ) ) - { - final NBTTagCompound optionalTag = (NBTTagCompound) msg.getTag( "optional" ); - final ItemStack optional = ItemStack.loadItemStackFromNBT( optionalTag ); + if (optional == null) { + throw new IllegalStateException("invalid optional"); + } - if( optional == null ) - { - throw new IllegalStateException( "invalid optional" ); - } + final float chance = msg.getFloat("chance"); - final float chance = msg.getFloat( "chance" ); - - AEApi.instance().registries().grinder().addRecipe( in, out, optional, chance, turns ); - } - else - { - AEApi.instance().registries().grinder().addRecipe( in, out, turns ); - } - } + AEApi.instance().registries().grinder().addRecipe( + in, out, optional, chance, turns + ); + } else { + AEApi.instance().registries().grinder().addRecipe(in, out, turns); + } + } } diff --git a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java index cf3171ca..fdfe60af 100644 --- a/src/main/java/appeng/core/api/imc/IMCMatterCannon.java +++ b/src/main/java/appeng/core/api/imc/IMCMatterCannon.java @@ -31,31 +31,25 @@ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.api.IIMCProcessor; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public class IMCMatterCannon implements IIMCProcessor { + @Override + public void process(final IMCMessage m) { + final NBTTagCompound msg = m.getNBTValue(); + final NBTTagCompound item = (NBTTagCompound) msg.getTag("item"); -public class IMCMatterCannon implements IIMCProcessor -{ + final ItemStack ammo = ItemStack.loadItemStackFromNBT(item); + final double weight = msg.getDouble("weight"); - @Override - public void process( final IMCMessage m ) - { - final NBTTagCompound msg = m.getNBTValue(); - final NBTTagCompound item = (NBTTagCompound) msg.getTag( "item" ); + if (ammo == null) { + throw new IllegalStateException("invalid item in message " + m); + } - final ItemStack ammo = ItemStack.loadItemStackFromNBT( item ); - final double weight = msg.getDouble( "weight" ); - - if( ammo == null ) - { - throw new IllegalStateException( "invalid item in message " + m ); - } - - AEApi.instance().registries().matterCannon().registerAmmo( ammo, weight ); - } + 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 c32bf22d..f76332b7 100644 --- a/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java +++ b/src/main/java/appeng/core/api/imc/IMCP2PAttunement.java @@ -18,17 +18,22 @@ /* Example: - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-me", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-bc-power", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-ic2-power", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-redstone", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-fluid", new ItemStack( myBlockOrItem ) ); - FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-item", new ItemStack( myBlockOrItem ) ); + FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-me", new + ItemStack( myBlockOrItem ) ); FMLInterModComms.sendMessage( "appliedenergistics2", + "add-p2p-attunement-bc-power", new ItemStack( myBlockOrItem ) ); + FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-ic2-power", new + ItemStack( myBlockOrItem ) ); FMLInterModComms.sendMessage( "appliedenergistics2", + "add-p2p-attunement-redstone", new ItemStack( myBlockOrItem ) ); + FMLInterModComms.sendMessage( "appliedenergistics2", "add-p2p-attunement-fluid", new + ItemStack( myBlockOrItem ) ); FMLInterModComms.sendMessage( "appliedenergistics2", + "add-p2p-attunement-item", new ItemStack( myBlockOrItem ) ); */ package appeng.core.api.imc; +import java.util.Arrays; +import java.util.Locale; import appeng.api.AEApi; import appeng.api.config.TunnelType; @@ -36,35 +41,27 @@ import appeng.core.api.IIMCProcessor; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; import net.minecraft.item.ItemStack; -import java.util.Arrays; -import java.util.Locale; +public class IMCP2PAttunement implements IIMCProcessor { + @Override + public void process(final IMCMessage m) { + final String key = m.key.substring("add-p2p-attunement-".length()) + .replace('-', '_') + .toUpperCase(Locale.ENGLISH); + final TunnelType type = TunnelType.valueOf(key); -public class IMCP2PAttunement implements IIMCProcessor -{ - - @Override - public void process( final IMCMessage m ) - { - final String key = m.key.substring( "add-p2p-attunement-".length() ).replace( '-', '_' ).toUpperCase( Locale.ENGLISH ); - - final TunnelType type = TunnelType.valueOf( key ); - - if( type != null ) - { - final ItemStack is = m.getItemStackValue(); - if( is != null ) - { - AEApi.instance().registries().p2pTunnel().addNewAttunement( is, type ); - } - else - { - throw new IllegalStateException( "invalid item in message " + m ); - } - } - else - { - throw new IllegalStateException( "invalid type in message " + m + " is not contained in " + Arrays.toString( TunnelType.values() ) ); - } - } + if (type != null) { + final ItemStack is = m.getItemStackValue(); + if (is != null) { + AEApi.instance().registries().p2pTunnel().addNewAttunement(is, type); + } else { + throw new IllegalStateException("invalid item in message " + m); + } + } else { + throw new IllegalStateException( + "invalid type in message " + m + " is not contained in " + + Arrays.toString(TunnelType.values()) + ); + } + } } diff --git a/src/main/java/appeng/core/api/imc/IMCSpatial.java b/src/main/java/appeng/core/api/imc/IMCSpatial.java index ce46885d..e29be711 100644 --- a/src/main/java/appeng/core/api/imc/IMCSpatial.java +++ b/src/main/java/appeng/core/api/imc/IMCSpatial.java @@ -18,34 +18,28 @@ /* Example: - FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", "mymod.tileentities.MyTileEntity" ); + FMLInterModComms.sendMessage( "appliedenergistics2", "whitelist-spatial", + "mymod.tileentities.MyTileEntity" ); */ package appeng.core.api.imc; - import appeng.api.AEApi; import appeng.core.AELog; import appeng.core.api.IIMCProcessor; import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; - -public class IMCSpatial implements IIMCProcessor -{ - - @Override - public void process( final IMCMessage m ) - { - - try - { - final Class classInstance = Class.forName( m.getStringValue() ); - AEApi.instance().registries().movable().whiteListTileEntity( classInstance ); - } - catch( final ClassNotFoundException e ) - { - AELog.info( "Bad Class Registered: " + m.getStringValue() + " by " + m.getSender() ); - } - } +public class IMCSpatial implements IIMCProcessor { + @Override + public void process(final IMCMessage m) { + try { + final Class classInstance = Class.forName(m.getStringValue()); + AEApi.instance().registries().movable().whiteListTileEntity(classInstance); + } catch (final ClassNotFoundException e) { + AELog.info( + "Bad Class Registered: " + m.getStringValue() + " by " + m.getSender() + ); + } + } } diff --git a/src/main/java/appeng/core/crash/BaseCrashEnhancement.java b/src/main/java/appeng/core/crash/BaseCrashEnhancement.java index d19ed92d..b710b4fa 100644 --- a/src/main/java/appeng/core/crash/BaseCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/BaseCrashEnhancement.java @@ -18,30 +18,24 @@ package appeng.core.crash; - import cpw.mods.fml.common.ICrashCallable; +abstract class BaseCrashEnhancement implements ICrashCallable { + private final String name; + private final String value; -abstract class BaseCrashEnhancement implements ICrashCallable -{ - private final String name; - private final String value; + public BaseCrashEnhancement(final String name, final String value) { + this.name = name; + this.value = value; + } - public BaseCrashEnhancement( final String name, final String value ) - { - this.name = name; - this.value = value; - } + @Override + public final String call() throws Exception { + return this.value; + } - @Override - public final String call() throws Exception - { - return this.value; - } - - @Override - public final String getLabel() - { - return this.name; - } + @Override + public final String getLabel() { + return this.name; + } } diff --git a/src/main/java/appeng/core/crash/CrashInfo.java b/src/main/java/appeng/core/crash/CrashInfo.java index 7a25618f..c7f4c537 100644 --- a/src/main/java/appeng/core/crash/CrashInfo.java +++ b/src/main/java/appeng/core/crash/CrashInfo.java @@ -18,8 +18,4 @@ package appeng.core.crash; - -public enum CrashInfo -{ - MOD_VERSION, INTEGRATION -} +public enum CrashInfo { MOD_VERSION, INTEGRATION } diff --git a/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java b/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java index 72cbde52..daa8de12 100644 --- a/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/IntegrationCrashEnhancement.java @@ -1,13 +1,9 @@ package appeng.core.crash; - import appeng.integration.IntegrationRegistry; - -public class IntegrationCrashEnhancement extends BaseCrashEnhancement -{ - public IntegrationCrashEnhancement() - { - super( "AE2 Integration", IntegrationRegistry.INSTANCE.getStatus() ); - } +public class IntegrationCrashEnhancement extends BaseCrashEnhancement { + public IntegrationCrashEnhancement() { + super("AE2 Integration", IntegrationRegistry.INSTANCE.getStatus()); + } } diff --git a/src/main/java/appeng/core/crash/ModCrashEnhancement.java b/src/main/java/appeng/core/crash/ModCrashEnhancement.java index 43abe783..83d990c6 100644 --- a/src/main/java/appeng/core/crash/ModCrashEnhancement.java +++ b/src/main/java/appeng/core/crash/ModCrashEnhancement.java @@ -1,19 +1,16 @@ package appeng.core.crash; - import appeng.core.AEConfig; +public class ModCrashEnhancement extends BaseCrashEnhancement { + private static final String MOD_VERSION = AEConfig.CHANNEL + ' ' + AEConfig.VERSION + + " for Forge " + // WHAT? + net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion + + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion + + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion + + net.minecraftforge.common.ForgeVersion.buildVersion; -public class ModCrashEnhancement extends BaseCrashEnhancement -{ - private static final String MOD_VERSION = AEConfig.CHANNEL + ' ' + AEConfig.VERSION + " for Forge " + // WHAT? - net.minecraftforge.common.ForgeVersion.majorVersion + '.' // majorVersion - + net.minecraftforge.common.ForgeVersion.minorVersion + '.' // minorVersion - + net.minecraftforge.common.ForgeVersion.revisionVersion + '.' // revisionVersion - + net.minecraftforge.common.ForgeVersion.buildVersion; - - public ModCrashEnhancement( final CrashInfo output ) - { - super( "AE2 Version", MOD_VERSION ); - } + public ModCrashEnhancement(final CrashInfo output) { + super("AE2 Version", MOD_VERSION); + } } diff --git a/src/main/java/appeng/core/features/AEBlockFeatureHandler.java b/src/main/java/appeng/core/features/AEBlockFeatureHandler.java index 73759533..cb4903d7 100644 --- a/src/main/java/appeng/core/features/AEBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/AEBlockFeatureHandler.java @@ -18,6 +18,7 @@ package appeng.core.features; +import java.util.EnumSet; import appeng.api.definitions.IBlockDefinition; import appeng.block.AEBaseBlock; @@ -25,53 +26,49 @@ import appeng.core.CreativeTab; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; -import java.util.EnumSet; +public final class AEBlockFeatureHandler implements IFeatureHandler { + private final AEBaseBlock featured; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final BlockDefinition definition; + public AEBlockFeatureHandler( + final EnumSet features, + final AEBaseBlock featured, + final Optional subName + ) { + final ActivityState state + = new FeaturedActiveChecker(features).getActivityState(); -public final class AEBlockFeatureHandler implements IFeatureHandler -{ - private final AEBaseBlock featured; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final BlockDefinition definition; + this.featured = featured; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new BlockDefinition(featured, state); + } - public AEBlockFeatureHandler( final EnumSet features, final AEBaseBlock featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - this.featured = featured; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new BlockDefinition( featured, state ); - } + @Override + public IBlockDefinition getDefinition() { + return this.definition; + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.featured.setCreativeTab(CreativeTab.instance); + this.featured.setBlockName(/* "tile." */ "appliedenergistics2." + name); + this.featured.setBlockTextureName("appliedenergistics2:" + name); - @Override - public IBlockDefinition getDefinition() - { - return this.definition; - } + final String registryName = "tile." + name; - @Override - public void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.featured.setCreativeTab( CreativeTab.instance ); - this.featured.setBlockName( /* "tile." */"appliedenergistics2." + name ); - this.featured.setBlockTextureName( "appliedenergistics2:" + name ); - - final String registryName = "tile." + name; - - // Bypass the forge magic with null to register our own itemblock later. - GameRegistry.registerBlock( this.featured, null, registryName ); - GameRegistry.registerItem( this.definition.maybeItem().get(), registryName ); - } - } + // Bypass the forge magic with null to register our own itemblock later. + GameRegistry.registerBlock(this.featured, null, registryName); + GameRegistry.registerItem(this.definition.maybeItem().get(), registryName); + } + } } diff --git a/src/main/java/appeng/core/features/AECableBusFeatureHandler.java b/src/main/java/appeng/core/features/AECableBusFeatureHandler.java index dd904d4f..bd489997 100644 --- a/src/main/java/appeng/core/features/AECableBusFeatureHandler.java +++ b/src/main/java/appeng/core/features/AECableBusFeatureHandler.java @@ -18,6 +18,7 @@ package appeng.core.features; +import java.util.EnumSet; import appeng.api.definitions.ITileDefinition; import appeng.block.AEBaseTileBlock; @@ -29,61 +30,59 @@ import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.tileentity.TileEntity; -import java.util.EnumSet; +public final class AECableBusFeatureHandler implements IFeatureHandler { + private final AEBaseTileBlock featured; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final TileDefinition definition; + public AECableBusFeatureHandler( + final EnumSet features, + final BlockCableBus featured, + final Optional subName + ) { + final ActivityState state + = new FeaturedActiveChecker(features).getActivityState(); -public final class AECableBusFeatureHandler implements IFeatureHandler -{ - private final AEBaseTileBlock featured; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final TileDefinition definition; + this.featured = featured; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new TileDefinition(featured, state); + } - public AECableBusFeatureHandler( final EnumSet features, final BlockCableBus featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - this.featured = featured; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new TileDefinition( featured, state ); - } + @Override + public ITileDefinition getDefinition() { + return this.definition; + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + /** + * Registration of the {@link TileEntity} will actually be handled by {@link + * BlockCableBus#setupTile()}. + */ + @Override + public void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.featured.setCreativeTab(CreativeTab.instance); + this.featured.setBlockName(/* "tile." */ "appliedenergistics2." + name); + this.featured.setBlockTextureName("appliedenergistics2:" + name); - @Override - public ITileDefinition getDefinition() - { - return this.definition; - } + if (Platform.isClient()) { + CommonHelper.proxy.bindTileEntitySpecialRenderer( + this.featured.getTileEntityClass(), this.featured + ); + } - /** - * Registration of the {@link TileEntity} will actually be handled by {@link BlockCableBus#setupTile()}. - */ - @Override - public void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.featured.setCreativeTab( CreativeTab.instance ); - this.featured.setBlockName( /* "tile." */"appliedenergistics2." + name ); - this.featured.setBlockTextureName( "appliedenergistics2:" + name ); + final String registryName = "tile." + name; - if( Platform.isClient() ) - { - CommonHelper.proxy.bindTileEntitySpecialRenderer( this.featured.getTileEntityClass(), this.featured ); - } - - final String registryName = "tile." + name; - - // Bypass the forge magic with null to register our own itemblock later. - GameRegistry.registerBlock( this.featured, null, registryName ); - GameRegistry.registerItem( this.definition.maybeItem().get(), registryName ); - } - } + // Bypass the forge magic with null to register our own itemblock later. + GameRegistry.registerBlock(this.featured, null, registryName); + GameRegistry.registerItem(this.definition.maybeItem().get(), registryName); + } + } } diff --git a/src/main/java/appeng/core/features/AEFeature.java b/src/main/java/appeng/core/features/AEFeature.java index f6fd3875..e880ec30 100644 --- a/src/main/java/appeng/core/features/AEFeature.java +++ b/src/main/java/appeng/core/features/AEFeature.java @@ -18,171 +18,165 @@ package appeng.core.features; +public enum AEFeature { + // stuff that has no reason for ever being turned off, or that + // is just flat out required by tons of + // important stuff. + Core(null) { + @Override + public boolean isVisible() { + return false; + } + }, -public enum AEFeature -{ - // stuff that has no reason for ever being turned off, or that - // is just flat out required by tons of - // important stuff. - Core( null ) - { - @Override - public boolean isVisible() - { - return false; - } - }, + CertusQuartzWorldGen(Constants.CATEGORY_WORLD), + MeteoriteWorldGen(Constants.CATEGORY_WORLD), + DecorativeLights(Constants.CATEGORY_WORLD), + DecorativeQuartzBlocks(Constants.CATEGORY_WORLD), + SkyStoneChests(Constants.CATEGORY_WORLD), + SpawnPressesInMeteorites(Constants.CATEGORY_WORLD), + GrindStone(Constants.CATEGORY_WORLD), + Flour(Constants.CATEGORY_WORLD), + Inscriber(Constants.CATEGORY_WORLD), + ChestLoot(Constants.CATEGORY_WORLD), + VillagerTrading(Constants.CATEGORY_WORLD), + TinyTNT(Constants.CATEGORY_WORLD), - CertusQuartzWorldGen( Constants.CATEGORY_WORLD ), - MeteoriteWorldGen( Constants.CATEGORY_WORLD ), - DecorativeLights( Constants.CATEGORY_WORLD ), - DecorativeQuartzBlocks( Constants.CATEGORY_WORLD ), - SkyStoneChests( Constants.CATEGORY_WORLD ), - SpawnPressesInMeteorites( Constants.CATEGORY_WORLD ), - GrindStone( Constants.CATEGORY_WORLD ), - Flour( Constants.CATEGORY_WORLD ), - Inscriber( Constants.CATEGORY_WORLD ), - ChestLoot( Constants.CATEGORY_WORLD ), - VillagerTrading( Constants.CATEGORY_WORLD ), - TinyTNT( Constants.CATEGORY_WORLD ), + PoweredTools(Constants.CATEGORY_TOOLS_CLASSIFICATIONS), + CertusQuartzTools(Constants.CATEGORY_TOOLS_CLASSIFICATIONS), + NetherQuartzTools(Constants.CATEGORY_TOOLS_CLASSIFICATIONS), - PoweredTools( Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), - CertusQuartzTools( Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), - NetherQuartzTools( Constants.CATEGORY_TOOLS_CLASSIFICATIONS ), + QuartzHoe(Constants.CATEGORY_TOOLS), + QuartzSpade(Constants.CATEGORY_TOOLS), + QuartzSword(Constants.CATEGORY_TOOLS), + QuartzPickaxe(Constants.CATEGORY_TOOLS), + QuartzAxe(Constants.CATEGORY_TOOLS), + QuartzKnife(Constants.CATEGORY_TOOLS), + QuartzWrench(Constants.CATEGORY_TOOLS), + ChargedStaff(Constants.CATEGORY_TOOLS), + EntropyManipulator(Constants.CATEGORY_TOOLS), + MatterCannon(Constants.CATEGORY_TOOLS), + WirelessAccessTerminal(Constants.CATEGORY_TOOLS), + ColorApplicator(Constants.CATEGORY_TOOLS), + MeteoriteCompass(Constants.CATEGORY_TOOLS), - QuartzHoe( Constants.CATEGORY_TOOLS ), - QuartzSpade( Constants.CATEGORY_TOOLS ), - QuartzSword( Constants.CATEGORY_TOOLS ), - QuartzPickaxe( Constants.CATEGORY_TOOLS ), - QuartzAxe( Constants.CATEGORY_TOOLS ), - QuartzKnife( Constants.CATEGORY_TOOLS ), - QuartzWrench( Constants.CATEGORY_TOOLS ), - ChargedStaff( Constants.CATEGORY_TOOLS ), - EntropyManipulator( Constants.CATEGORY_TOOLS ), - MatterCannon( Constants.CATEGORY_TOOLS ), - WirelessAccessTerminal( Constants.CATEGORY_TOOLS ), - ColorApplicator( Constants.CATEGORY_TOOLS ), - MeteoriteCompass( Constants.CATEGORY_TOOLS ), + PowerGen(Constants.CATEGORY_NETWORK_FEATURES), + Security(Constants.CATEGORY_NETWORK_FEATURES), + SpatialIO(Constants.CATEGORY_NETWORK_FEATURES), + QuantumNetworkBridge(Constants.CATEGORY_NETWORK_FEATURES), + Channels(Constants.CATEGORY_NETWORK_FEATURES), + Legacy(Constants.CATEGORY_NETWORK_FEATURES), - PowerGen( Constants.CATEGORY_NETWORK_FEATURES ), - Security( Constants.CATEGORY_NETWORK_FEATURES ), - SpatialIO( Constants.CATEGORY_NETWORK_FEATURES ), - QuantumNetworkBridge( Constants.CATEGORY_NETWORK_FEATURES ), - Channels( Constants.CATEGORY_NETWORK_FEATURES ), - Legacy( Constants.CATEGORY_NETWORK_FEATURES ), + LevelEmitter(Constants.CATEGORY_NETWORK_BUSES), + CraftingTerminal(Constants.CATEGORY_NETWORK_BUSES), + StorageMonitor(Constants.CATEGORY_NETWORK_BUSES), + P2PTunnel(Constants.CATEGORY_NETWORK_BUSES), + FormationPlane(Constants.CATEGORY_NETWORK_BUSES), + AnnihilationPlane(Constants.CATEGORY_NETWORK_BUSES), + IdentityAnnihilationPlane(Constants.CATEGORY_NETWORK_BUSES), + ImportBus(Constants.CATEGORY_NETWORK_BUSES), + ExportBus(Constants.CATEGORY_NETWORK_BUSES), + StorageBus(Constants.CATEGORY_NETWORK_BUSES), + PartConversionMonitor(Constants.CATEGORY_NETWORK_BUSES), - LevelEmitter( Constants.CATEGORY_NETWORK_BUSES ), - CraftingTerminal( Constants.CATEGORY_NETWORK_BUSES ), - StorageMonitor( Constants.CATEGORY_NETWORK_BUSES ), - P2PTunnel( Constants.CATEGORY_NETWORK_BUSES ), - FormationPlane( Constants.CATEGORY_NETWORK_BUSES ), - AnnihilationPlane( Constants.CATEGORY_NETWORK_BUSES ), - IdentityAnnihilationPlane( Constants.CATEGORY_NETWORK_BUSES ), - ImportBus( Constants.CATEGORY_NETWORK_BUSES ), - ExportBus( Constants.CATEGORY_NETWORK_BUSES ), - StorageBus( Constants.CATEGORY_NETWORK_BUSES ), - PartConversionMonitor( Constants.CATEGORY_NETWORK_BUSES ), + PortableCell(Constants.CATEGORY_PORTABLE_CELL), - PortableCell( Constants.CATEGORY_PORTABLE_CELL ), + StorageCells(Constants.CATEGORY_STORAGE), + MEChest(Constants.CATEGORY_STORAGE), + MEDrive(Constants.CATEGORY_STORAGE), + IOPort(Constants.CATEGORY_STORAGE), - StorageCells( Constants.CATEGORY_STORAGE ), - MEChest( Constants.CATEGORY_STORAGE ), - MEDrive( Constants.CATEGORY_STORAGE ), - IOPort( Constants.CATEGORY_STORAGE ), + NetworkTool(Constants.CATEGORY_NETWORK_TOOL), - NetworkTool( Constants.CATEGORY_NETWORK_TOOL ), + DenseEnergyCells(Constants.CATEGORY_HIGHER_CAPACITY), + DenseCables(Constants.CATEGORY_HIGHER_CAPACITY), - DenseEnergyCells( Constants.CATEGORY_HIGHER_CAPACITY ), - DenseCables( Constants.CATEGORY_HIGHER_CAPACITY ), + P2PTunnelRF(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelME(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelItems(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelRedstone(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelEU(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelLiquids(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelLight(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelOpenComputers(Constants.CATEGORY_P2P_TUNNELS), + P2PTunnelPressure(Constants.CATEGORY_P2P_TUNNELS), - P2PTunnelRF( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelME( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelItems( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelRedstone( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelEU( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelLiquids( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelLight( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelOpenComputers( Constants.CATEGORY_P2P_TUNNELS ), - P2PTunnelPressure( Constants.CATEGORY_P2P_TUNNELS ), + MassCannonBlockDamage(Constants.CATEGORY_BLOCK_FEATURES), + TinyTNTBlockDamage(Constants.CATEGORY_BLOCK_FEATURES), - MassCannonBlockDamage( Constants.CATEGORY_BLOCK_FEATURES ), - TinyTNTBlockDamage( Constants.CATEGORY_BLOCK_FEATURES ), + Facades(Constants.CATEGORY_FACADES), - Facades( Constants.CATEGORY_FACADES ), + UnsupportedDeveloperTools(Constants.CATEGORY_MISC, false), + Creative(Constants.CATEGORY_MISC), + GrinderLogging(Constants.CATEGORY_MISC, false), + Logging(Constants.CATEGORY_MISC), + IntegrationLogging(Constants.CATEGORY_MISC, false), + WebsiteRecipes(Constants.CATEGORY_MISC, false), + LogSecurityAudits(Constants.CATEGORY_MISC, false), + Achievements(Constants.CATEGORY_MISC), + UpdateLogging(Constants.CATEGORY_MISC, false), + PacketLogging(Constants.CATEGORY_MISC, false), + CraftingLog(Constants.CATEGORY_MISC, false), + LightDetector(Constants.CATEGORY_MISC), + DebugLogging(Constants.CATEGORY_MISC, false), - UnsupportedDeveloperTools( Constants.CATEGORY_MISC, false ), - Creative( Constants.CATEGORY_MISC ), - GrinderLogging( Constants.CATEGORY_MISC, false ), - Logging( Constants.CATEGORY_MISC ), - IntegrationLogging( Constants.CATEGORY_MISC, false ), - WebsiteRecipes( Constants.CATEGORY_MISC, false ), - LogSecurityAudits( Constants.CATEGORY_MISC, false ), - Achievements( Constants.CATEGORY_MISC ), - UpdateLogging( Constants.CATEGORY_MISC, false ), - PacketLogging( Constants.CATEGORY_MISC, false ), - CraftingLog( Constants.CATEGORY_MISC, false ), - LightDetector( Constants.CATEGORY_MISC ), - DebugLogging( Constants.CATEGORY_MISC, false ), + EnableFacadeCrafting(Constants.CATEGORY_CRAFTING), + InWorldSingularity(Constants.CATEGORY_CRAFTING), + InWorldFluix(Constants.CATEGORY_CRAFTING), + InWorldPurification(Constants.CATEGORY_CRAFTING), + InterfaceTerminal(Constants.CATEGORY_CRAFTING), + EnableDisassemblyCrafting(Constants.CATEGORY_CRAFTING), - EnableFacadeCrafting( Constants.CATEGORY_CRAFTING ), - InWorldSingularity( Constants.CATEGORY_CRAFTING ), - InWorldFluix( Constants.CATEGORY_CRAFTING ), - InWorldPurification( Constants.CATEGORY_CRAFTING ), - InterfaceTerminal( Constants.CATEGORY_CRAFTING ), - EnableDisassemblyCrafting( Constants.CATEGORY_CRAFTING ), + AlphaPass(Constants.CATEGORY_RENDERING), + PaintBalls(Constants.CATEGORY_TOOLS), - AlphaPass( Constants.CATEGORY_RENDERING ), PaintBalls( Constants.CATEGORY_TOOLS ), + MolecularAssembler(Constants.CATEGORY_CRAFTING_FEATURES), + Patterns(Constants.CATEGORY_CRAFTING_FEATURES), + CraftingCPU(Constants.CATEGORY_CRAFTING_FEATURES), - MolecularAssembler( Constants.CATEGORY_CRAFTING_FEATURES ), - Patterns( Constants.CATEGORY_CRAFTING_FEATURES ), - CraftingCPU( Constants.CATEGORY_CRAFTING_FEATURES ), + ChunkLoggerTrace(Constants.CATEGORY_COMMANDS, false); - ChunkLoggerTrace( Constants.CATEGORY_COMMANDS, false ); + public final String category; + public final boolean defaultValue; - public final String category; - public final boolean defaultValue; + AEFeature(final String cat) { + this(cat, true); + } - AEFeature( final String cat ) - { - this( cat, true ); - } + AEFeature(final String cat, final boolean defaultValue) { + this.category = cat; + this.defaultValue = defaultValue; + } - AEFeature( final String cat, final boolean defaultValue ) - { - this.category = cat; - this.defaultValue = defaultValue; - } + /** + * override to set visibility + * + * @return default true + */ + public boolean isVisible() { + return true; + } - /** - * override to set visibility - * - * @return default true - */ - public boolean isVisible() - { - return true; - } + private enum Constants { + ; - private enum Constants - { - ; - - private static final String CATEGORY_MISC = "Misc"; - private static final String CATEGORY_CRAFTING = "Crafting"; - private static final String CATEGORY_WORLD = "World"; - private static final String CATEGORY_TOOLS = "Tools"; - private static final String CATEGORY_TOOLS_CLASSIFICATIONS = "ToolsClassifications"; - private static final String CATEGORY_NETWORK_BUSES = "NetworkBuses"; - private static final String CATEGORY_P2P_TUNNELS = "P2PTunnels"; - private static final String CATEGORY_BLOCK_FEATURES = "BlockFeatures"; - private static final String CATEGORY_CRAFTING_FEATURES = "CraftingFeatures"; - private static final String CATEGORY_STORAGE = "Storage"; - private static final String CATEGORY_HIGHER_CAPACITY = "HigherCapacity"; - private static final String CATEGORY_NETWORK_FEATURES = "NetworkFeatures"; - private static final String CATEGORY_COMMANDS = "Commands"; - private static final String CATEGORY_RENDERING = "Rendering"; - private static final String CATEGORY_FACADES = "Facades"; - private static final String CATEGORY_NETWORK_TOOL = "NetworkTool"; - private static final String CATEGORY_PORTABLE_CELL = "PortableCell"; - } + private static final String CATEGORY_MISC = "Misc"; + private static final String CATEGORY_CRAFTING = "Crafting"; + private static final String CATEGORY_WORLD = "World"; + private static final String CATEGORY_TOOLS = "Tools"; + private static final String CATEGORY_TOOLS_CLASSIFICATIONS + = "ToolsClassifications"; + private static final String CATEGORY_NETWORK_BUSES = "NetworkBuses"; + private static final String CATEGORY_P2P_TUNNELS = "P2PTunnels"; + private static final String CATEGORY_BLOCK_FEATURES = "BlockFeatures"; + private static final String CATEGORY_CRAFTING_FEATURES = "CraftingFeatures"; + private static final String CATEGORY_STORAGE = "Storage"; + private static final String CATEGORY_HIGHER_CAPACITY = "HigherCapacity"; + private static final String CATEGORY_NETWORK_FEATURES = "NetworkFeatures"; + private static final String CATEGORY_COMMANDS = "Commands"; + private static final String CATEGORY_RENDERING = "Rendering"; + private static final String CATEGORY_FACADES = "Facades"; + private static final String CATEGORY_NETWORK_TOOL = "NetworkTool"; + private static final String CATEGORY_PORTABLE_CELL = "PortableCell"; + } } diff --git a/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java b/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java index 84e5b49d..bbdd5277 100644 --- a/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/AETileBlockFeatureHandler.java @@ -18,6 +18,7 @@ package appeng.core.features; +import java.util.EnumSet; import appeng.api.definitions.ITileDefinition; import appeng.block.AEBaseTileBlock; @@ -28,60 +29,64 @@ import appeng.util.Platform; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; -import java.util.EnumSet; +public final class AETileBlockFeatureHandler implements IFeatureHandler { + private final AEBaseTileBlock featured; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final TileDefinition definition; + public AETileBlockFeatureHandler( + final EnumSet features, + final AEBaseTileBlock featured, + final Optional subName + ) { + final ActivityState state + = new FeaturedActiveChecker(features).getActivityState(); -public final class AETileBlockFeatureHandler implements IFeatureHandler -{ - private final AEBaseTileBlock featured; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final TileDefinition definition; + this.featured = featured; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new TileDefinition(featured, state); + } - public AETileBlockFeatureHandler( final EnumSet features, final AEBaseTileBlock featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - this.featured = featured; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new TileDefinition( featured, state ); - } + @Override + public ITileDefinition getDefinition() { + return this.definition; + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.featured.setCreativeTab(CreativeTab.instance); + this.featured.setBlockName(/* "tile." */ "appliedenergistics2." + name); + this.featured.setBlockTextureName("appliedenergistics2:" + name); - @Override - public ITileDefinition getDefinition() - { - return this.definition; - } + if (Platform.isClient()) { + CommonHelper.proxy.bindTileEntitySpecialRenderer( + this.featured.getTileEntityClass(), this.featured + ); + } - @Override - public void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.featured.setCreativeTab( CreativeTab.instance ); - this.featured.setBlockName( /* "tile." */"appliedenergistics2." + name ); - this.featured.setBlockTextureName( "appliedenergistics2:" + name ); + final String registryName = "tile." + name; - if( Platform.isClient() ) - { - CommonHelper.proxy.bindTileEntitySpecialRenderer( this.featured.getTileEntityClass(), this.featured ); - } - - final String registryName = "tile." + name; - - // Bypass the forge magic with null to register our own itemblock later. - GameRegistry.registerBlock( this.featured, null, registryName ); - GameRegistry.registerItem( this.definition.maybeItem().get(), registryName ); - GameRegistry.registerTileEntity( this.featured.getTileEntityClass(), this.featured.toString() ); - AEBaseTile.registerTileItem( this.featured.getTileEntityClass(), new BlockStackSrc( this.featured, 0, ActivityState.from( this.isFeatureAvailable() ) ) ); - } - } + // Bypass the forge magic with null to register our own itemblock later. + GameRegistry.registerBlock(this.featured, null, registryName); + GameRegistry.registerItem(this.definition.maybeItem().get(), registryName); + GameRegistry.registerTileEntity( + this.featured.getTileEntityClass(), this.featured.toString() + ); + AEBaseTile.registerTileItem( + this.featured.getTileEntityClass(), + new BlockStackSrc( + this.featured, 0, ActivityState.from(this.isFeatureAvailable()) + ) + ); + } + } } diff --git a/src/main/java/appeng/core/features/ActivityState.java b/src/main/java/appeng/core/features/ActivityState.java index 1c4f71d1..7c25adbf 100644 --- a/src/main/java/appeng/core/features/ActivityState.java +++ b/src/main/java/appeng/core/features/ActivityState.java @@ -18,21 +18,15 @@ package appeng.core.features; +public enum ActivityState { + Enabled, + Disabled; -public enum ActivityState -{ - Enabled, - Disabled; - - public static ActivityState from( final boolean enabled ) - { - if( enabled ) - { - return ActivityState.Enabled; - } - else - { - return ActivityState.Disabled; - } - } + public static ActivityState from(final boolean enabled) { + if (enabled) { + return ActivityState.Enabled; + } else { + return ActivityState.Disabled; + } + } } diff --git a/src/main/java/appeng/core/features/BlockDefinition.java b/src/main/java/appeng/core/features/BlockDefinition.java index 3be8f567..d63fd415 100644 --- a/src/main/java/appeng/core/features/BlockDefinition.java +++ b/src/main/java/appeng/core/features/BlockDefinition.java @@ -18,6 +18,7 @@ package appeng.core.features; +import java.lang.reflect.Constructor; import appeng.api.definitions.IBlockDefinition; import appeng.block.AEBaseBlock; @@ -31,144 +32,123 @@ import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; -import java.lang.reflect.Constructor; +public class BlockDefinition extends ItemDefinition implements IBlockDefinition { + private static final ItemBlockTransformer ITEMBLOCK_TRANSFORMER + = new ItemBlockTransformer(); + private final Optional block; + public BlockDefinition(final Block block, final ActivityState state) { + super(constructItemFromBlock(block), state); -public class BlockDefinition extends ItemDefinition implements IBlockDefinition -{ - private static final ItemBlockTransformer ITEMBLOCK_TRANSFORMER = new ItemBlockTransformer(); - private final Optional block; + Preconditions.checkNotNull(block); + Preconditions.checkNotNull(state); - public BlockDefinition( final Block block, final ActivityState state ) - { - super( constructItemFromBlock( block ), state ); + if (state == ActivityState.Enabled) { + this.block = Optional.of(block); + } else { + this.block = Optional.absent(); + } + } - Preconditions.checkNotNull( block ); - Preconditions.checkNotNull( state ); + /** + * Create an {@link ItemBlock} from a {@link Block} to register it later as {@link + * Item} + * + * @param block source block + * @return item from block + */ + private static Item constructItemFromBlock(final Block block) { + final Class itemclass = getItemBlockConstructor(block); + return constructItemBlock(block, itemclass); + } - if( state == ActivityState.Enabled ) - { - this.block = Optional.of( block ); - } - else - { - this.block = Optional.absent(); - } - } + /** + * Returns the constructor to use. + *

+ * Either {@link ItemBlock} or in case of an {@link AEBaseBlock} the class returned by + * AEBaseBlock.getItemBlockClass(). + * + * @param block the block used to determine the used constructor. + * @return a {@link Class} extending ItemBlock + */ + private static Class getItemBlockConstructor(final Block block) { + if (block instanceof AEBaseBlock) { + final AEBaseBlock aeBaseBlock = (AEBaseBlock) block; + return aeBaseBlock.getItemBlockClass(); + } - /** - * Create an {@link ItemBlock} from a {@link Block} to register it later as {@link Item} - * - * @param block source block - * @return item from block - */ - private static Item constructItemFromBlock( final Block block ) - { - final Class itemclass = getItemBlockConstructor( block ); - return constructItemBlock( block, itemclass ); - } + return ItemBlock.class; + } - /** - * Returns the constructor to use. - *

- * Either {@link ItemBlock} or in case of an {@link AEBaseBlock} the class returned by - * AEBaseBlock.getItemBlockClass(). - * - * @param block the block used to determine the used constructor. - * @return a {@link Class} extending ItemBlock - */ - private static Class getItemBlockConstructor( final Block block ) - { - if( block instanceof AEBaseBlock ) - { - final AEBaseBlock aeBaseBlock = (AEBaseBlock) block; - return aeBaseBlock.getItemBlockClass(); - } + /** + * Actually construct an instance of {@link Item} with the block and earlier + * determined constructor.

Shamelessly stolen from the forge magic.

+ * TODO: throw an exception instead of returning null? As this could cause issue later + * on. + * + * @param block the block to create the {@link ItemBlock} from + * @param itemclass the class used to construct it. + * @return an {@link Item} for the block. Actually always a sub type of {@link + * ItemBlock} + */ + private static Item + constructItemBlock(final Block block, final Class itemclass) { + try { + final Object[] itemCtorArgs = {}; + final Class[] ctorArgClasses = new Class[itemCtorArgs.length + 1]; + ctorArgClasses[0] = Block.class; + for (int idx = 1; idx < ctorArgClasses.length; idx++) { + ctorArgClasses[idx] = itemCtorArgs[idx - 1].getClass(); + } - return ItemBlock.class; - } + final Constructor itemCtor + = itemclass.getConstructor(ctorArgClasses); + return itemCtor.newInstance(ObjectArrays.concat(block, itemCtorArgs)); + } catch (final Throwable t) { + return null; + } + } - /** - * Actually construct an instance of {@link Item} with the block and earlier determined constructor. - *

- * Shamelessly stolen from the forge magic. - *

- * TODO: throw an exception instead of returning null? As this could cause issue later on. - * - * @param block the block to create the {@link ItemBlock} from - * @param itemclass the class used to construct it. - * @return an {@link Item} for the block. Actually always a sub type of {@link ItemBlock} - */ - private static Item constructItemBlock( final Block block, final Class itemclass ) - { - try - { - final Object[] itemCtorArgs = {}; - final Class[] ctorArgClasses = new Class[itemCtorArgs.length + 1]; - ctorArgClasses[0] = Block.class; - for( int idx = 1; idx < ctorArgClasses.length; idx++ ) - { - ctorArgClasses[idx] = itemCtorArgs[idx - 1].getClass(); - } + @Override + public final Optional maybeBlock() { + return this.block; + } - final Constructor itemCtor = itemclass.getConstructor( ctorArgClasses ); - return itemCtor.newInstance( ObjectArrays.concat( block, itemCtorArgs ) ); - } - catch( final Throwable t ) - { - return null; - } - } + @Override + public final Optional maybeItemBlock() { + return this.block.transform(ITEMBLOCK_TRANSFORMER); + } - @Override - public final Optional maybeBlock() - { - return this.block; - } + @Override + public final Optional maybeStack(final int stackSize) { + return this.block.transform(new ItemStackTransformer(stackSize)); + } - @Override - public final Optional maybeItemBlock() - { - return this.block.transform( ITEMBLOCK_TRANSFORMER ); - } + @Override + public final boolean + isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return this.isEnabled() && world.getBlock(x, y, z) == this.block.get(); + } - @Override - public final Optional maybeStack( final int stackSize ) - { - return this.block.transform( new ItemStackTransformer( stackSize ) ); - } + private static class ItemBlockTransformer implements Function { + @Override + public ItemBlock apply(final Block input) { + return new ItemBlock(input); + } + } - @Override - public final boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.isEnabled() && world.getBlock( x, y, z ) == this.block.get(); - } + private static class ItemStackTransformer implements Function { + private final int stackSize; - private static class ItemBlockTransformer implements Function - { - @Override - public ItemBlock apply( final Block input ) - { - return new ItemBlock( input ); - } - } + public ItemStackTransformer(final int stackSize) { + Preconditions.checkArgument(stackSize > 0); + this.stackSize = stackSize; + } - private static class ItemStackTransformer implements Function - { - private final int stackSize; - - public ItemStackTransformer( final int stackSize ) - { - Preconditions.checkArgument( stackSize > 0 ); - - this.stackSize = stackSize; - } - - @Override - public ItemStack apply( final Block input ) - { - return new ItemStack( input, this.stackSize ); - } - } + @Override + public ItemStack apply(final Block input) { + return new ItemStack(input, this.stackSize); + } + } } diff --git a/src/main/java/appeng/core/features/BlockStackSrc.java b/src/main/java/appeng/core/features/BlockStackSrc.java index 382d3bc8..324319a6 100644 --- a/src/main/java/appeng/core/features/BlockStackSrc.java +++ b/src/main/java/appeng/core/features/BlockStackSrc.java @@ -18,56 +18,49 @@ package appeng.core.features; +import javax.annotation.Nullable; import com.google.common.base.Preconditions; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import javax.annotation.Nullable; +public class BlockStackSrc implements IStackSrc { + private final Block block; + private final int damage; + private final boolean enabled; + public BlockStackSrc(final Block block, final int damage, final ActivityState state) { + Preconditions.checkNotNull(block); + Preconditions.checkArgument(damage >= 0); + Preconditions.checkNotNull(state); + Preconditions.checkArgument( + state == ActivityState.Enabled || state == ActivityState.Disabled + ); -public class BlockStackSrc implements IStackSrc -{ + this.block = block; + this.damage = damage; + this.enabled = state == ActivityState.Enabled; + } - private final Block block; - private final int damage; - private final boolean enabled; + @Nullable + @Override + public ItemStack stack(final int i) { + return new ItemStack(this.block, i, this.damage); + } - public BlockStackSrc( final Block block, final int damage, final ActivityState state ) - { - Preconditions.checkNotNull( block ); - Preconditions.checkArgument( damage >= 0 ); - Preconditions.checkNotNull( state ); - Preconditions.checkArgument( state == ActivityState.Enabled || state == ActivityState.Disabled ); + @Override + public Item getItem() { + return null; + } - this.block = block; - this.damage = damage; - this.enabled = state == ActivityState.Enabled; - } + @Override + public int getDamage() { + return this.damage; + } - @Nullable - @Override - public ItemStack stack( final int i ) - { - return new ItemStack( this.block, i, this.damage ); - } - - @Override - public Item getItem() - { - return null; - } - - @Override - public int getDamage() - { - return this.damage; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } + @Override + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/appeng/core/features/ColoredItemDefinition.java b/src/main/java/appeng/core/features/ColoredItemDefinition.java index c685951e..9cd3e8b7 100644 --- a/src/main/java/appeng/core/features/ColoredItemDefinition.java +++ b/src/main/java/appeng/core/features/ColoredItemDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.util.AEColor; import appeng.api.util.AEColoredItemDefinition; import net.minecraft.block.Block; @@ -26,76 +25,63 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public final class ColoredItemDefinition implements AEColoredItemDefinition { + private final ItemStackSrc[] colors = new ItemStackSrc[17]; -public final class ColoredItemDefinition implements AEColoredItemDefinition -{ + public void add(final AEColor v, final ItemStackSrc is) { + this.colors[v.ordinal()] = is; + } - private final ItemStackSrc[] colors = new ItemStackSrc[17]; + @Override + public Block block(final AEColor color) { + return null; + } - public void add( final AEColor v, final ItemStackSrc is ) - { - this.colors[v.ordinal()] = is; - } + @Override + public Item item(final AEColor color) { + final ItemStackSrc is = this.colors[color.ordinal()]; - @Override - public Block block( final AEColor color ) - { - return null; - } + if (is == null) { + return null; + } - @Override - public Item item( final AEColor color ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; + return is.getItem(); + } - if( is == null ) - { - return null; - } + @Override + public Class entity(final AEColor color) { + return null; + } - return is.getItem(); - } + @Override + public ItemStack stack(final AEColor color, final int stackSize) { + final ItemStackSrc is = this.colors[color.ordinal()]; - @Override - public Class entity( final AEColor color ) - { - return null; - } + if (is == null) { + return null; + } - @Override - public ItemStack stack( final AEColor color, final int stackSize ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; + return is.stack(stackSize); + } - if( is == null ) - { - return null; - } + @Override + public ItemStack[] allStacks(final int stackSize) { + final ItemStack[] is = new ItemStack[this.colors.length]; + for (int x = 0; x < is.length; x++) { + is[x] = this.colors[x].stack(1); + } + return is; + } - return is.stack( stackSize ); - } + @Override + public boolean sameAs(final AEColor color, final ItemStack comparableItem) { + final ItemStackSrc is = this.colors[color.ordinal()]; - @Override - public ItemStack[] allStacks( final int stackSize ) - { - final ItemStack[] is = new ItemStack[this.colors.length]; - for( int x = 0; x < is.length; x++ ) - { - is[x] = this.colors[x].stack( 1 ); - } - return is; - } + if (comparableItem == null || is == null) { + return false; + } - @Override - public boolean sameAs( final AEColor color, final ItemStack comparableItem ) - { - final ItemStackSrc is = this.colors[color.ordinal()]; - - if( comparableItem == null || is == null ) - { - return false; - } - - return comparableItem.getItem() == is.getItem() && comparableItem.getItemDamage() == is.getDamage(); - } + return comparableItem.getItem() == is.getItem() + && comparableItem.getItemDamage() == is.getDamage(); + } } diff --git a/src/main/java/appeng/core/features/DamagedItemDefinition.java b/src/main/java/appeng/core/features/DamagedItemDefinition.java index 98f0cf16..d08fb36b 100644 --- a/src/main/java/appeng/core/features/DamagedItemDefinition.java +++ b/src/main/java/appeng/core/features/DamagedItemDefinition.java @@ -18,6 +18,7 @@ package appeng.core.features; +import javax.annotation.Nonnull; import appeng.api.definitions.IItemDefinition; import com.google.common.base.Function; @@ -27,88 +28,71 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; -import javax.annotation.Nonnull; +public final class DamagedItemDefinition implements IItemDefinition { + private static final ItemTransformer ITEM_TRANSFORMER = new ItemTransformer(); + private final Optional source; + public DamagedItemDefinition(@Nonnull final IStackSrc source) { + Preconditions.checkNotNull(source); -public final class DamagedItemDefinition implements IItemDefinition -{ - private static final ItemTransformer ITEM_TRANSFORMER = new ItemTransformer(); - private final Optional source; + if (source.isEnabled()) { + this.source = Optional.of(source); + } else { + this.source = Optional.absent(); + } + } - public DamagedItemDefinition( @Nonnull final IStackSrc source ) - { - Preconditions.checkNotNull( source ); + @Override + public Optional maybeItem() { + return this.source.transform(ITEM_TRANSFORMER); + } - if( source.isEnabled() ) - { - this.source = Optional.of( source ); - } - else - { - this.source = Optional.absent(); - } - } + @Override + public Optional maybeStack(final int stackSize) { + return this.source.transform(new ItemStackTransformer(stackSize)); + } - @Override - public Optional maybeItem() - { - return this.source.transform( ITEM_TRANSFORMER ); - } + @Override + public boolean isEnabled() { + return this.source.isPresent(); + } - @Override - public Optional maybeStack( final int stackSize ) - { - return this.source.transform( new ItemStackTransformer( stackSize ) ); - } + @Override + public boolean isSameAs(final ItemStack comparableStack) { + if (comparableStack == null) { + return false; + } - @Override - public boolean isEnabled() - { - return this.source.isPresent(); - } + return this.isEnabled() + && comparableStack.getItem() == this.source.get().getItem() + && comparableStack.getItemDamage() == this.source.get().getDamage(); + } - @Override - public boolean isSameAs( final ItemStack comparableStack ) - { - if( comparableStack == null ) - { - return false; - } + @Override + public boolean + isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return false; + } - return this.isEnabled() && comparableStack.getItem() == this.source.get().getItem() && comparableStack.getItemDamage() == this.source.get().getDamage(); - } + private static class ItemTransformer implements Function { + @Override + public Item apply(final IStackSrc input) { + return input.getItem(); + } + } - @Override - public boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return false; - } + private static class ItemStackTransformer implements Function { + private final int stackSize; - private static class ItemTransformer implements Function - { - @Override - public Item apply( final IStackSrc input ) - { - return input.getItem(); - } - } + public ItemStackTransformer(final int stackSize) { + Preconditions.checkArgument(stackSize > 0); + this.stackSize = stackSize; + } - private static class ItemStackTransformer implements Function - { - private final int stackSize; - - public ItemStackTransformer( final int stackSize ) - { - Preconditions.checkArgument( stackSize > 0 ); - - this.stackSize = stackSize; - } - - @Override - public ItemStack apply( final IStackSrc input ) - { - return input.stack( this.stackSize ); - } - } + @Override + public ItemStack apply(final IStackSrc input) { + return input.stack(this.stackSize); + } + } } diff --git a/src/main/java/appeng/core/features/DefinitionConverter.java b/src/main/java/appeng/core/features/DefinitionConverter.java index 3e62abff..fcb0425d 100644 --- a/src/main/java/appeng/core/features/DefinitionConverter.java +++ b/src/main/java/appeng/core/features/DefinitionConverter.java @@ -1,5 +1,6 @@ package appeng.core.features; +import javax.annotation.Nullable; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IComparableDefinition; @@ -12,155 +13,127 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; -import javax.annotation.Nullable; - - /** * @deprecated */ @Deprecated -public final class DefinitionConverter -{ - public AEItemDefinition of( final ITileDefinition definition ) - { - return new AETile( definition ); - } +public final class DefinitionConverter { + public AEItemDefinition of(final ITileDefinition definition) { + return new AETile(definition); + } - public AEItemDefinition of( final IBlockDefinition definition ) - { - return new AEBlock( definition ); - } + public AEItemDefinition of(final IBlockDefinition definition) { + return new AEBlock(definition); + } - public AEItemDefinition of( final IItemDefinition definition ) - { - return new AEItem( definition ); - } + public AEItemDefinition of(final IItemDefinition definition) { + return new AEItem(definition); + } - public AEItemDefinition of( final IComparableDefinition definition ) - { - return new AEComparable( definition ); - } + public AEItemDefinition of(final IComparableDefinition definition) { + return new AEComparable(definition); + } - private static class AEComparable implements AEItemDefinition - { - private final IComparableDefinition definition; + private static class AEComparable implements AEItemDefinition { + private final IComparableDefinition definition; - public AEComparable( final IComparableDefinition definition ) - { - this.definition = definition; - } + public AEComparable(final IComparableDefinition definition) { + this.definition = definition; + } - @Nullable - @Override - public Block block() - { - return null; - } + @Nullable + @Override + public Block block() { + return null; + } - @Nullable - @Override - public Item item() - { - return null; - } + @Nullable + @Override + public Item item() { + return null; + } - @Nullable - @Override - public Class entity() - { - return null; - } + @Nullable + @Override + public Class entity() { + return null; + } - @Nullable - @Override - public ItemStack stack( final int stackSize ) - { - return null; - } + @Nullable + @Override + public ItemStack stack(final int stackSize) { + return null; + } - @Override - public boolean sameAsStack( final ItemStack comparableItem ) - { - return this.definition.isSameAs( comparableItem ); - } + @Override + public boolean sameAsStack(final ItemStack comparableItem) { + return this.definition.isSameAs(comparableItem); + } - @Override - public boolean sameAsBlock( final IBlockAccess world, final int x, final int y, final int z ) - { - return false; - } - } + @Override + public boolean + sameAsBlock(final IBlockAccess world, final int x, final int y, final int z) { + return false; + } + } + private static class AEItem extends AEComparable { + private final IItemDefinition definition; - private static class AEItem extends AEComparable - { - private final IItemDefinition definition; + public AEItem(final IItemDefinition definition) { + super(definition); - public AEItem( final IItemDefinition definition ) - { - super( definition ); + this.definition = definition; + } - this.definition = definition; - } + @Nullable + @Override + public ItemStack stack(final int stackSize) { + return this.definition.maybeStack(stackSize).orNull(); + } - @Nullable - @Override - public ItemStack stack( final int stackSize ) - { - return this.definition.maybeStack( stackSize ).orNull(); - } + @Nullable + @Override + public Item item() { + return this.definition.maybeItem().orNull(); + } + } - @Nullable - @Override - public Item item() - { - return this.definition.maybeItem().orNull(); - } - } + private static class AEBlock extends AEItem { + private final IBlockDefinition definition; + public AEBlock(final IBlockDefinition definition) { + super(definition); - private static class AEBlock extends AEItem - { - private final IBlockDefinition definition; + this.definition = definition; + } - public AEBlock( final IBlockDefinition definition ) - { - super( definition ); + @Nullable + @Override + public Block block() { + return this.definition.maybeBlock().orNull(); + } - this.definition = definition; - } + @Override + public boolean + sameAsBlock(final IBlockAccess world, final int x, final int y, final int z) { + return this.definition.isSameAs(world, x, y, z); + } + } - @Nullable - @Override - public Block block() - { - return this.definition.maybeBlock().orNull(); - } + private static class AETile extends AEBlock { + private final ITileDefinition definition; - @Override - public boolean sameAsBlock( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.definition.isSameAs( world, x, y, z ); - } - } + public AETile(final ITileDefinition definition) { + super(definition); + this.definition = definition; + } - private static class AETile extends AEBlock - { - private final ITileDefinition definition; - - public AETile( final ITileDefinition definition ) - { - super( definition ); - - this.definition = definition; - } - - @Nullable - @Override - public Class entity() - { - return this.definition.maybeEntity().orNull(); - } - } + @Nullable + @Override + public Class entity() { + 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 ce7a0652..5da8952b 100644 --- a/src/main/java/appeng/core/features/FeatureNameExtractor.java +++ b/src/main/java/appeng/core/features/FeatureNameExtractor.java @@ -18,61 +18,50 @@ package appeng.core.features; +import java.util.regex.Pattern; import com.google.common.base.Optional; -import java.util.regex.Pattern; +public class FeatureNameExtractor { + private static final Pattern PATTERN_ITEM_MULTI_PART + = Pattern.compile("ItemMultiPart", Pattern.LITERAL); + private static final Pattern PATTERN_ITEM_MULTI_MATERIAL + = Pattern.compile("ItemMultiMaterial", Pattern.LITERAL); + private static final Pattern PATTERN_QUARTZ + = Pattern.compile("Quartz", Pattern.LITERAL); + private final Class clazz; + private final Optional subName; -public class FeatureNameExtractor -{ - private static final Pattern PATTERN_ITEM_MULTI_PART = Pattern.compile( "ItemMultiPart", Pattern.LITERAL ); - private static final Pattern PATTERN_ITEM_MULTI_MATERIAL = Pattern.compile( "ItemMultiMaterial", Pattern.LITERAL ); - private static final Pattern PATTERN_QUARTZ = Pattern.compile( "Quartz", Pattern.LITERAL ); + public FeatureNameExtractor(final Class clazz, final Optional subName) { + this.clazz = clazz; + this.subName = subName; + } - private final Class clazz; - private final Optional subName; + public String get() { + String name = this.clazz.getSimpleName(); - public FeatureNameExtractor( final Class clazz, final Optional subName ) - { - this.clazz = clazz; - this.subName = subName; - } + if (name.startsWith("ItemMultiPart")) { + name = PATTERN_ITEM_MULTI_PART.matcher(name).replaceAll("ItemPart"); + } else if (name.startsWith("ItemMultiMaterial")) { + name = PATTERN_ITEM_MULTI_MATERIAL.matcher(name).replaceAll("ItemMaterial"); + } - public String get() - { - String name = this.clazz.getSimpleName(); + 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")) { + return "ItemPart.P2PTunnel"; + } else if (subName.equals("CertusQuartzTools")) { + return PATTERN_QUARTZ.matcher(name).replaceAll("CertusQuartz"); + } else if (subName.equals("NetherQuartzTools")) { + return PATTERN_QUARTZ.matcher(name).replaceAll("NetherQuartz"); + } - if( name.startsWith( "ItemMultiPart" ) ) - { - name = PATTERN_ITEM_MULTI_PART.matcher( name ).replaceAll( "ItemPart" ); - } - else if( name.startsWith( "ItemMultiMaterial" ) ) - { - name = PATTERN_ITEM_MULTI_MATERIAL.matcher( name ).replaceAll( "ItemMaterial" ); - } + name += '.' + subName; + } - 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" ) ) - { - return "ItemPart.P2PTunnel"; - } - else if( subName.equals( "CertusQuartzTools" ) ) - { - return PATTERN_QUARTZ.matcher( name ).replaceAll( "CertusQuartz" ); - } - else if( subName.equals( "NetherQuartzTools" ) ) - { - return PATTERN_QUARTZ.matcher( name ).replaceAll( "NetherQuartz" ); - } - - name += '.' + subName; - } - - return name; - } + return name; + } } diff --git a/src/main/java/appeng/core/features/FeaturedActiveChecker.java b/src/main/java/appeng/core/features/FeaturedActiveChecker.java index 421198a9..1abadfc9 100644 --- a/src/main/java/appeng/core/features/FeaturedActiveChecker.java +++ b/src/main/java/appeng/core/features/FeaturedActiveChecker.java @@ -18,31 +18,24 @@ package appeng.core.features; +import java.util.Set; import appeng.core.AEConfig; -import java.util.Set; +public final class FeaturedActiveChecker { + private final Set features; + public FeaturedActiveChecker(final Set features) { + this.features = features; + } -public final class FeaturedActiveChecker -{ - private final Set features; + ActivityState getActivityState() { + for (final AEFeature f : this.features) { + if (!AEConfig.instance.isFeatureEnabled(f)) { + return ActivityState.Disabled; + } + } - public FeaturedActiveChecker( final Set features ) - { - this.features = features; - } - - ActivityState getActivityState() - { - for( final AEFeature f : this.features ) - { - if( !AEConfig.instance.isFeatureEnabled( f ) ) - { - return ActivityState.Disabled; - } - } - - return ActivityState.Enabled; - } + return ActivityState.Enabled; + } } diff --git a/src/main/java/appeng/core/features/IAEFeature.java b/src/main/java/appeng/core/features/IAEFeature.java index c819f1e7..6ce85f31 100644 --- a/src/main/java/appeng/core/features/IAEFeature.java +++ b/src/main/java/appeng/core/features/IAEFeature.java @@ -18,10 +18,8 @@ package appeng.core.features; +public interface IAEFeature { + IFeatureHandler handler(); -public interface IAEFeature -{ - IFeatureHandler handler(); - - void postInit(); + void postInit(); } diff --git a/src/main/java/appeng/core/features/IFeatureHandler.java b/src/main/java/appeng/core/features/IFeatureHandler.java index de16fc2e..737ff43e 100644 --- a/src/main/java/appeng/core/features/IFeatureHandler.java +++ b/src/main/java/appeng/core/features/IFeatureHandler.java @@ -18,15 +18,12 @@ package appeng.core.features; - import appeng.api.definitions.IItemDefinition; +public interface IFeatureHandler { + boolean isFeatureAvailable(); -public interface IFeatureHandler -{ - boolean isFeatureAvailable(); + IItemDefinition getDefinition(); - IItemDefinition getDefinition(); - - void register(); + void register(); } diff --git a/src/main/java/appeng/core/features/IStackSrc.java b/src/main/java/appeng/core/features/IStackSrc.java index cc7e1aa2..216c5247 100644 --- a/src/main/java/appeng/core/features/IStackSrc.java +++ b/src/main/java/appeng/core/features/IStackSrc.java @@ -18,19 +18,15 @@ package appeng.core.features; - import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public interface IStackSrc { + ItemStack stack(int i); -public interface IStackSrc -{ + Item getItem(); - ItemStack stack( int i ); + int getDamage(); - Item getItem(); - - int getDamage(); - - boolean isEnabled(); + boolean isEnabled(); } diff --git a/src/main/java/appeng/core/features/ItemDefinition.java b/src/main/java/appeng/core/features/ItemDefinition.java index 39d23afc..e051fdcd 100644 --- a/src/main/java/appeng/core/features/ItemDefinition.java +++ b/src/main/java/appeng/core/features/ItemDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.IItemDefinition; import appeng.util.Platform; import com.google.common.base.Function; @@ -28,71 +27,59 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; +public class ItemDefinition implements IItemDefinition { + private final Optional item; -public class ItemDefinition implements IItemDefinition -{ - private final Optional item; + public ItemDefinition(final Item item, final ActivityState state) { + Preconditions.checkNotNull(item); + Preconditions.checkNotNull(state); - public ItemDefinition( final Item item, final ActivityState state ) - { - Preconditions.checkNotNull( item ); - Preconditions.checkNotNull( state ); + if (state == ActivityState.Enabled) { + this.item = Optional.of(item); + } else { + this.item = Optional.absent(); + } + } - if( state == ActivityState.Enabled ) - { - this.item = Optional.of( item ); - } - else - { - this.item = Optional.absent(); - } - } + @Override + public final Optional maybeItem() { + return this.item; + } - @Override - public final Optional maybeItem() - { - return this.item; - } + @Override + public Optional maybeStack(final int stackSize) { + return this.item.transform(new ItemStackTransformer(stackSize)); + } - @Override - public Optional maybeStack( final int stackSize ) - { - return this.item.transform( new ItemStackTransformer( stackSize ) ); - } + @Override + public boolean isEnabled() { + return this.item.isPresent(); + } - @Override - public boolean isEnabled() - { - return this.item.isPresent(); - } + @Override + public final boolean isSameAs(final ItemStack comparableStack) { + return this.isEnabled() + && Platform.isSameItemType(comparableStack, this.maybeStack(1).get()); + } - @Override - public final boolean isSameAs( final ItemStack comparableStack ) - { - return this.isEnabled() && Platform.isSameItemType( comparableStack, this.maybeStack( 1 ).get() ); - } + @Override + public boolean + isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return false; + } - @Override - public boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return false; - } + private static class ItemStackTransformer implements Function { + private final int stackSize; - private static class ItemStackTransformer implements Function - { - private final int stackSize; + public ItemStackTransformer(final int stackSize) { + Preconditions.checkArgument(stackSize > 0); - public ItemStackTransformer( final int stackSize ) - { - Preconditions.checkArgument( stackSize > 0 ); + this.stackSize = stackSize; + } - this.stackSize = stackSize; - } - - @Override - public ItemStack apply( final Item input ) - { - return new ItemStack( input, this.stackSize ); - } - } + @Override + public ItemStack apply(final Item input) { + return new ItemStack(input, this.stackSize); + } + } } diff --git a/src/main/java/appeng/core/features/ItemFeatureHandler.java b/src/main/java/appeng/core/features/ItemFeatureHandler.java index 1bd820fe..a0e1c1c5 100644 --- a/src/main/java/appeng/core/features/ItemFeatureHandler.java +++ b/src/main/java/appeng/core/features/ItemFeatureHandler.java @@ -18,6 +18,7 @@ package appeng.core.features; +import java.util.EnumSet; import appeng.api.definitions.IItemDefinition; import appeng.core.CreativeTab; @@ -27,66 +28,57 @@ import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.Item; -import java.util.EnumSet; +public final class ItemFeatureHandler implements IFeatureHandler { + private final Item item; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final ItemDefinition definition; + public ItemFeatureHandler( + final EnumSet features, + final Item item, + final IAEFeature featured, + final Optional subName + ) { + final ActivityState state + = new FeaturedActiveChecker(features).getActivityState(); -public final class ItemFeatureHandler implements IFeatureHandler -{ - private final Item item; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final ItemDefinition definition; + this.item = item; + this.extractor = new FeatureNameExtractor(featured.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new ItemDefinition(item, state); + } - public ItemFeatureHandler( final EnumSet features, final Item item, final IAEFeature featured, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + @Override + public boolean isFeatureAvailable() { + return this.enabled; + } - this.item = item; - this.extractor = new FeatureNameExtractor( featured.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new ItemDefinition( item, state ); - } + @Override + public IItemDefinition getDefinition() { + return this.definition; + } - @Override - public boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public void register() { + if (this.enabled) { + String name = this.extractor.get(); + this.item.setTextureName("appliedenergistics2:" + name); + this.item.setUnlocalizedName(/* "item." */ "appliedenergistics2." + name); - @Override - public IItemDefinition getDefinition() - { - return this.definition; - } + if (this.item instanceof ItemFacade) { + this.item.setCreativeTab(CreativeTabFacade.instance); + } else { + this.item.setCreativeTab(CreativeTab.instance); + } - @Override - public void register() - { - if( this.enabled ) - { - String name = this.extractor.get(); - this.item.setTextureName( "appliedenergistics2:" + name ); - this.item.setUnlocalizedName( /* "item." */"appliedenergistics2." + name ); + if (name.equals("ItemMaterial")) { + name = "ItemMultiMaterial"; + } else if (name.equals("ItemPart")) { + name = "ItemMultiPart"; + } - if( this.item instanceof ItemFacade ) - { - this.item.setCreativeTab( CreativeTabFacade.instance ); - } - else - { - this.item.setCreativeTab( CreativeTab.instance ); - } - - if( name.equals( "ItemMaterial" ) ) - { - name = "ItemMultiMaterial"; - } - else if( name.equals( "ItemPart" ) ) - { - name = "ItemMultiPart"; - } - - GameRegistry.registerItem( this.item, "item." + name ); - } - } + GameRegistry.registerItem(this.item, "item." + name); + } + } } diff --git a/src/main/java/appeng/core/features/ItemStackSrc.java b/src/main/java/appeng/core/features/ItemStackSrc.java index 8ec4018e..74048a2b 100644 --- a/src/main/java/appeng/core/features/ItemStackSrc.java +++ b/src/main/java/appeng/core/features/ItemStackSrc.java @@ -18,55 +18,48 @@ package appeng.core.features; +import javax.annotation.Nullable; import com.google.common.base.Preconditions; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import javax.annotation.Nullable; +public class ItemStackSrc implements IStackSrc { + private final Item item; + private final int damage; + private final boolean enabled; + public ItemStackSrc(final Item item, final int damage, final ActivityState state) { + Preconditions.checkNotNull(item); + Preconditions.checkArgument(damage >= 0); + Preconditions.checkNotNull(state); + Preconditions.checkArgument( + state == ActivityState.Enabled || state == ActivityState.Disabled + ); -public class ItemStackSrc implements IStackSrc -{ + this.item = item; + this.damage = damage; + this.enabled = state == ActivityState.Enabled; + } - private final Item item; - private final int damage; - private final boolean enabled; + @Nullable + @Override + public ItemStack stack(final int i) { + return new ItemStack(this.item, i, this.damage); + } - public ItemStackSrc( final Item item, final int damage, final ActivityState state ) - { - Preconditions.checkNotNull( item ); - Preconditions.checkArgument( damage >= 0 ); - Preconditions.checkNotNull( state ); - Preconditions.checkArgument( state == ActivityState.Enabled || state == ActivityState.Disabled ); + @Override + public Item getItem() { + return this.item; + } - this.item = item; - this.damage = damage; - this.enabled = state == ActivityState.Enabled; - } + @Override + public int getDamage() { + return this.damage; + } - @Nullable - @Override - public ItemStack stack( final int i ) - { - return new ItemStack( this.item, i, this.damage ); - } - - @Override - public Item getItem() - { - return this.item; - } - - @Override - public int getDamage() - { - return this.damage; - } - - @Override - public boolean isEnabled() - { - return this.enabled; - } + @Override + public boolean isEnabled() { + return this.enabled; + } } diff --git a/src/main/java/appeng/core/features/MaterialStackSrc.java b/src/main/java/appeng/core/features/MaterialStackSrc.java index 6f38f452..32abb81c 100644 --- a/src/main/java/appeng/core/features/MaterialStackSrc.java +++ b/src/main/java/appeng/core/features/MaterialStackSrc.java @@ -18,45 +18,37 @@ package appeng.core.features; - import appeng.items.materials.MaterialType; import com.google.common.base.Preconditions; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +public class MaterialStackSrc implements IStackSrc { + private final MaterialType src; -public class MaterialStackSrc implements IStackSrc -{ - private final MaterialType src; + public MaterialStackSrc(final MaterialType src) { + Preconditions.checkNotNull(src); - public MaterialStackSrc( final MaterialType src ) - { - Preconditions.checkNotNull( src ); + this.src = src; + } - this.src = src; - } + @Override + public ItemStack stack(final int stackSize) { + return this.src.stack(stackSize); + } - @Override - public ItemStack stack( final int stackSize ) - { - return this.src.stack( stackSize ); - } + @Override + public Item getItem() { + return this.src.getItemInstance(); + } - @Override - public Item getItem() - { - return this.src.getItemInstance(); - } + @Override + public int getDamage() { + return this.src.getDamageValue(); + } - @Override - public int getDamage() - { - return this.src.getDamageValue(); - } - - @Override - public boolean isEnabled() - { - return true; - } + @Override + public boolean isEnabled() { + return true; + } } diff --git a/src/main/java/appeng/core/features/NameResolver.java b/src/main/java/appeng/core/features/NameResolver.java index a5969316..7816ecaf 100644 --- a/src/main/java/appeng/core/features/NameResolver.java +++ b/src/main/java/appeng/core/features/NameResolver.java @@ -18,11 +18,9 @@ package appeng.core.features; - -import appeng.items.AEBaseItem; - import java.util.regex.Pattern; +import appeng.items.AEBaseItem; /** * This class is used to rename items to match the persistent stored items. @@ -33,53 +31,45 @@ import java.util.regex.Pattern; * @deprecated only a temporary solution for a rename */ @Deprecated -public final class NameResolver -{ - private static final Pattern ITEM_MULTI_PART = Pattern.compile( "ItemMultiPart", Pattern.LITERAL ); - private static final Pattern ITEM_MULTI_MATERIAL = Pattern.compile( "ItemMultiMaterial", Pattern.LITERAL ); - private static final Pattern QUARTZ = Pattern.compile( "Quartz", Pattern.LITERAL ); +public final class NameResolver { + private static final Pattern ITEM_MULTI_PART + = Pattern.compile("ItemMultiPart", Pattern.LITERAL); + private static final Pattern ITEM_MULTI_MATERIAL + = Pattern.compile("ItemMultiMaterial", Pattern.LITERAL); + private static final Pattern QUARTZ = Pattern.compile("Quartz", Pattern.LITERAL); - private final Class withOriginalName; + private final Class withOriginalName; - public NameResolver( final Class withOriginalName ) - { - this.withOriginalName = withOriginalName; - } + public NameResolver(final Class withOriginalName) { + this.withOriginalName = withOriginalName; + } - public String getName( final String subName ) - { - String name = this.withOriginalName.getSimpleName(); + public String getName(final String subName) { + String name = this.withOriginalName.getSimpleName(); - if( name.startsWith( "ItemMultiPart" ) ) - { - name = ITEM_MULTI_PART.matcher( name ).replaceAll( "ItemPart" ); - } - else if( name.startsWith( "ItemMultiMaterial" ) ) - { - name = ITEM_MULTI_MATERIAL.matcher( name ).replaceAll( "ItemMaterial" ); - } + if (name.startsWith("ItemMultiPart")) { + name = ITEM_MULTI_PART.matcher(name).replaceAll("ItemPart"); + } else if (name.startsWith("ItemMultiMaterial")) { + name = ITEM_MULTI_MATERIAL.matcher(name).replaceAll("ItemMaterial"); + } - 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" ) ) - { - return "ItemPart.P2PTunnel"; - } + 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")) { + return "ItemPart.P2PTunnel"; + } - if( subName.equals( "CertusQuartzTools" ) ) - { - return QUARTZ.matcher( name ).replaceAll( "CertusQuartz" ); - } - if( subName.equals( "NetherQuartzTools" ) ) - { - return QUARTZ.matcher( name ).replaceAll( "NetherQuartz" ); - } + if (subName.equals("CertusQuartzTools")) { + return QUARTZ.matcher(name).replaceAll("CertusQuartz"); + } + if (subName.equals("NetherQuartzTools")) { + return QUARTZ.matcher(name).replaceAll("NetherQuartz"); + } - name += '.' + subName; - } + name += '.' + subName; + } - return name; - } + return name; + } } diff --git a/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java b/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java index 053fa3aa..6b730e53 100644 --- a/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/SlabBlockFeatureHandler.java @@ -18,6 +18,7 @@ package appeng.core.features; +import java.util.EnumSet; import appeng.api.definitions.IBlockDefinition; import appeng.block.AEBaseItemBlockSlab; @@ -26,45 +27,54 @@ import appeng.core.CreativeTab; import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; -import java.util.EnumSet; +public class SlabBlockFeatureHandler implements IFeatureHandler { + private final AEBaseSlabBlock slabs; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final BlockDefinition definition; + public SlabBlockFeatureHandler( + final EnumSet features, final AEBaseSlabBlock slabs + ) { + final ActivityState state + = new FeaturedActiveChecker(features).getActivityState(); + this.slabs = slabs; + this.extractor + = new FeatureNameExtractor(slabs.getClass(), Optional.absent()); + this.enabled = state == ActivityState.Enabled; + this.definition = new BlockDefinition(slabs, state); + } -public class SlabBlockFeatureHandler implements IFeatureHandler -{ - private final AEBaseSlabBlock slabs; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final BlockDefinition definition; + @Override + public final boolean isFeatureAvailable() { + return this.enabled; + } - public SlabBlockFeatureHandler( final EnumSet features, final AEBaseSlabBlock slabs ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); - this.slabs = slabs; - this.extractor = new FeatureNameExtractor( slabs.getClass(), Optional.absent() ); - this.enabled = state == ActivityState.Enabled; - this.definition = new BlockDefinition( slabs, state ); - } + @Override + public final IBlockDefinition getDefinition() { + return this.definition; + } - @Override - public final boolean isFeatureAvailable() - { - return this.enabled; - } - - @Override - public final IBlockDefinition getDefinition() - { - return this.definition; - } - - @Override - public final void register() - { - if( this.enabled ) - { - this.slabs.setCreativeTab( CreativeTab.instance ); - GameRegistry.registerBlock( this.slabs, AEBaseItemBlockSlab.class, "tile." + this.slabs.name(), this.slabs, this.slabs.doubleSlabs(), false ); - GameRegistry.registerBlock( this.slabs.doubleSlabs(), AEBaseItemBlockSlab.class, "tile." + this.slabs.name() + ".double", this.slabs, this.slabs.doubleSlabs(), true ); - } - } + @Override + public final void register() { + if (this.enabled) { + this.slabs.setCreativeTab(CreativeTab.instance); + GameRegistry.registerBlock( + this.slabs, + AEBaseItemBlockSlab.class, + "tile." + this.slabs.name(), + this.slabs, + this.slabs.doubleSlabs(), + false + ); + GameRegistry.registerBlock( + this.slabs.doubleSlabs(), + AEBaseItemBlockSlab.class, + "tile." + this.slabs.name() + ".double", + this.slabs, + this.slabs.doubleSlabs(), + true + ); + } + } } diff --git a/src/main/java/appeng/core/features/StairBlockFeatureHandler.java b/src/main/java/appeng/core/features/StairBlockFeatureHandler.java index 39c48273..5c19e55b 100644 --- a/src/main/java/appeng/core/features/StairBlockFeatureHandler.java +++ b/src/main/java/appeng/core/features/StairBlockFeatureHandler.java @@ -18,6 +18,7 @@ package appeng.core.features; +import java.util.EnumSet; import appeng.api.definitions.IBlockDefinition; import appeng.core.CreativeTab; @@ -25,49 +26,45 @@ import com.google.common.base.Optional; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.block.BlockStairs; -import java.util.EnumSet; +public class StairBlockFeatureHandler implements IFeatureHandler { + private final BlockStairs stairs; + private final FeatureNameExtractor extractor; + private final boolean enabled; + private final BlockDefinition definition; + public StairBlockFeatureHandler( + final EnumSet features, + final BlockStairs stairs, + final Optional subName + ) { + final ActivityState state + = new FeaturedActiveChecker(features).getActivityState(); -public class StairBlockFeatureHandler implements IFeatureHandler -{ - private final BlockStairs stairs; - private final FeatureNameExtractor extractor; - private final boolean enabled; - private final BlockDefinition definition; + this.stairs = stairs; + this.extractor = new FeatureNameExtractor(stairs.getClass(), subName); + this.enabled = state == ActivityState.Enabled; + this.definition = new BlockDefinition(stairs, state); + } - public StairBlockFeatureHandler( final EnumSet features, final BlockStairs stairs, final Optional subName ) - { - final ActivityState state = new FeaturedActiveChecker( features ).getActivityState(); + @Override + public final boolean isFeatureAvailable() { + return this.enabled; + } - this.stairs = stairs; - this.extractor = new FeatureNameExtractor( stairs.getClass(), subName ); - this.enabled = state == ActivityState.Enabled; - this.definition = new BlockDefinition( stairs, state ); - } + @Override + public final IBlockDefinition getDefinition() { + return this.definition; + } - @Override - public final boolean isFeatureAvailable() - { - return this.enabled; - } + @Override + public final void register() { + if (this.enabled) { + final String name = this.extractor.get(); + this.stairs.setCreativeTab(CreativeTab.instance); + this.stairs.setBlockName("appliedenergistics2." + name); + this.stairs.setBlockTextureName("appliedenergistics2:" + name); - @Override - public final IBlockDefinition getDefinition() - { - return this.definition; - } - - @Override - public final void register() - { - if( this.enabled ) - { - final String name = this.extractor.get(); - this.stairs.setCreativeTab( CreativeTab.instance ); - this.stairs.setBlockName( "appliedenergistics2." + name ); - this.stairs.setBlockTextureName( "appliedenergistics2:" + name ); - - GameRegistry.registerBlock( this.stairs, "tile." + name ); - } - } + GameRegistry.registerBlock(this.stairs, "tile." + name); + } + } } diff --git a/src/main/java/appeng/core/features/TileDefinition.java b/src/main/java/appeng/core/features/TileDefinition.java index 24b06988..2965d7cc 100644 --- a/src/main/java/appeng/core/features/TileDefinition.java +++ b/src/main/java/appeng/core/features/TileDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.ITileDefinition; import appeng.block.AEBaseTileBlock; import com.google.common.base.Function; @@ -26,44 +25,37 @@ import com.google.common.base.Optional; import com.google.common.base.Preconditions; import net.minecraft.tileentity.TileEntity; +public final class TileDefinition extends BlockDefinition implements ITileDefinition { + private static final TileEntityTransformer TILEENTITY_TRANSFORMER + = new TileEntityTransformer(); + private final Optional block; -public final class TileDefinition extends BlockDefinition implements ITileDefinition -{ - private static final TileEntityTransformer TILEENTITY_TRANSFORMER = new TileEntityTransformer(); - private final Optional block; + public TileDefinition(final AEBaseTileBlock block, final ActivityState state) { + super(block, state); - public TileDefinition( final AEBaseTileBlock block, final ActivityState state ) - { - super( block, state ); + Preconditions.checkNotNull(block); + Preconditions.checkNotNull(state); + Preconditions.checkNotNull(block.getTileEntityClass()); - Preconditions.checkNotNull( block ); - Preconditions.checkNotNull( state ); - Preconditions.checkNotNull( block.getTileEntityClass() ); + if (state == ActivityState.Enabled) { + this.block = Optional.of(block); + } else { + this.block = Optional.absent(); + } + } - if( state == ActivityState.Enabled ) - { - this.block = Optional.of( block ); - } - else - { - this.block = Optional.absent(); - } - } + @Override + public Optional> maybeEntity() { + return this.block.transform(TILEENTITY_TRANSFORMER); + } - @Override - public Optional> maybeEntity() - { - return this.block.transform( TILEENTITY_TRANSFORMER ); - } + private static class TileEntityTransformer + implements Function> { + @Override + public Class apply(final AEBaseTileBlock input) { + final Class entity = input.getTileEntityClass(); - private static class TileEntityTransformer implements Function> - { - @Override - public Class apply( final AEBaseTileBlock input ) - { - final Class entity = input.getTileEntityClass(); - - return entity; - } - } + return entity; + } + } } diff --git a/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java b/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java index c4a2dcf9..57c926e8 100644 --- a/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java +++ b/src/main/java/appeng/core/features/WrappedDamageItemDefinition.java @@ -18,7 +18,6 @@ package appeng.core.features; - import appeng.api.definitions.ITileDefinition; import com.google.common.base.Function; import com.google.common.base.Optional; @@ -30,97 +29,90 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; +public final class WrappedDamageItemDefinition implements ITileDefinition { + private final ITileDefinition definition; + private final int damage; -public final class WrappedDamageItemDefinition implements ITileDefinition -{ - private final ITileDefinition definition; - private final int damage; + public WrappedDamageItemDefinition( + final ITileDefinition definition, final int damage + ) { + Preconditions.checkNotNull(definition); + Preconditions.checkArgument(damage >= 0); - public WrappedDamageItemDefinition( final ITileDefinition definition, final int damage ) - { - Preconditions.checkNotNull( definition ); - Preconditions.checkArgument( damage >= 0 ); + this.definition = definition; + this.damage = damage; + } - this.definition = definition; - this.damage = damage; - } + @Override + public Optional> maybeEntity() { + return this.definition.maybeEntity(); + } - @Override - public Optional> maybeEntity() - { - return this.definition.maybeEntity(); - } + @Override + public Optional maybeBlock() { + return this.definition.maybeBlock(); + } - @Override - public Optional maybeBlock() - { - return this.definition.maybeBlock(); - } + @Override + public Optional maybeItemBlock() { + return this.definition.maybeItemBlock(); + } - @Override - public Optional maybeItemBlock() - { - return this.definition.maybeItemBlock(); - } + @Override + public Optional maybeItem() { + return this.definition.maybeItem(); + } - @Override - public Optional maybeItem() - { - return this.definition.maybeItem(); - } + @Override + public Optional maybeStack(final int stackSize) { + return this.definition.maybeBlock().transform( + new BlockTransformFunction(stackSize, this.damage) + ); + } - @Override - public Optional maybeStack( final int stackSize ) - { - return this.definition.maybeBlock().transform( new BlockTransformFunction( stackSize, this.damage ) ); - } + @Override + public boolean isEnabled() { + return this.definition.isEnabled(); + } - @Override - public boolean isEnabled() - { - return this.definition.isEnabled(); - } + @Override + public boolean isSameAs(final ItemStack comparableStack) { + if (comparableStack == null) { + return false; + } - @Override - public boolean isSameAs( final ItemStack comparableStack ) - { - if( comparableStack == null ) - { - return false; - } + final boolean sameItem + = this.definition.isSameAs(new ItemStack(comparableStack.getItem())); + final boolean sameDamage = comparableStack.getItemDamage() == this.damage; - final boolean sameItem = this.definition.isSameAs( new ItemStack( comparableStack.getItem() ) ); - final boolean sameDamage = comparableStack.getItemDamage() == this.damage; + return sameItem && sameDamage; + } - return sameItem && sameDamage; - } + @Override + public boolean + isSameAs(final IBlockAccess world, final int x, final int y, final int z) { + return this.definition.isSameAs(world, x, y, z) + && world.getBlockMetadata(x, y, z) == this.damage; + } - @Override - public boolean isSameAs( final IBlockAccess world, final int x, final int y, final int z ) - { - return this.definition.isSameAs( world, x, y, z ) && world.getBlockMetadata( x, y, z ) == this.damage; - } + private static final class BlockTransformFunction + implements Function { + private final int stackSize; + private final int damage; - private static final class BlockTransformFunction implements Function - { - private final int stackSize; - private final int damage; + public BlockTransformFunction(final int stackSize, final int damage) { + Preconditions.checkArgument(stackSize > 0); + Preconditions.checkArgument(damage >= 0); - public BlockTransformFunction( final int stackSize, final int damage ) - { - Preconditions.checkArgument( stackSize > 0 ); - Preconditions.checkArgument( damage >= 0 ); + this.stackSize = stackSize; + this.damage = damage; + } - this.stackSize = stackSize; - this.damage = damage; - } + @Override + public ItemStack apply(final Block input) { + Preconditions.checkNotNull(input); - @Override - public ItemStack apply( final Block input ) - { - Preconditions.checkNotNull( input ); - - return new ItemStack( input, this.stackSize, this.damage ); - } - } + return new ItemStack(input, this.stackSize, 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 5b8ae588..55f43e32 100644 --- a/src/main/java/appeng/core/features/registries/CellRegistry.java +++ b/src/main/java/appeng/core/features/registries/CellRegistry.java @@ -18,81 +18,64 @@ package appeng.core.features.registries; +import java.util.ArrayList; +import java.util.List; import appeng.api.storage.*; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.List; +public class CellRegistry implements ICellRegistry { + private final List handlers; + public CellRegistry() { + this.handlers = new ArrayList(); + } -public class CellRegistry implements ICellRegistry -{ + @Override + public void addCellHandler(final ICellHandler h) { + if (h != null) { + this.handlers.add(h); + } + } - private final List handlers; + @Override + public boolean isCellHandled(final ItemStack is) { + if (is == null) { + return false; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return true; + } + } + return false; + } - public CellRegistry() - { - this.handlers = new ArrayList(); - } + @Override + public ICellHandler getHandler(final ItemStack is) { + if (is == null) { + return null; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return ch; + } + } + return null; + } - @Override - public void addCellHandler( final ICellHandler h ) - { - if( h != null ) - { - this.handlers.add( h ); - } - } - - @Override - public boolean isCellHandled( final ItemStack is ) - { - if( is == null ) - { - return false; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return true; - } - } - return false; - } - - @Override - public ICellHandler getHandler( final ItemStack is ) - { - if( is == null ) - { - return null; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return ch; - } - } - return null; - } - - @Override - public IMEInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final StorageChannel chan ) - { - if( is == null ) - { - return null; - } - for( final ICellHandler ch : this.handlers ) - { - if( ch.isCell( is ) ) - { - return ch.getCellInventory( is, container, chan ); - } - } - return null; - } + @Override + public IMEInventoryHandler getCellInventory( + final ItemStack is, final ISaveProvider container, final StorageChannel chan + ) { + if (is == null) { + return null; + } + for (final ICellHandler ch : this.handlers) { + if (ch.isCell(is)) { + return ch.getCellInventory(is, container, chan); + } + } + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java b/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java index 585f271c..26f0ef04 100644 --- a/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java +++ b/src/main/java/appeng/core/features/registries/ExternalStorageRegistry.java @@ -18,6 +18,8 @@ package appeng.core.features.registries; +import java.util.ArrayList; +import java.util.List; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; @@ -27,43 +29,36 @@ import appeng.core.features.registries.entries.ExternalIInv; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.List; +public class ExternalStorageRegistry implements IExternalStorageRegistry { + private final List Handlers; + private final ExternalIInv lastHandler = new ExternalIInv(); + public ExternalStorageRegistry() { + this.Handlers = new ArrayList(); + } -public class ExternalStorageRegistry implements IExternalStorageRegistry -{ + @Override + public void addExternalStorageInterface(final IExternalStorageHandler ei) { + this.Handlers.add(ei); + } - private final List Handlers; - private final ExternalIInv lastHandler = new ExternalIInv(); + @Override + public IExternalStorageHandler getHandler( + final TileEntity te, + final ForgeDirection d, + final StorageChannel chan, + final BaseActionSource mySrc + ) { + for (final IExternalStorageHandler x : this.Handlers) { + if (x.canHandle(te, d, chan, mySrc)) { + return x; + } + } - public ExternalStorageRegistry() - { - this.Handlers = new ArrayList(); - } + if (this.lastHandler.canHandle(te, d, chan, mySrc)) { + return this.lastHandler; + } - @Override - public void addExternalStorageInterface( final IExternalStorageHandler ei ) - { - this.Handlers.add( ei ); - } - - @Override - public IExternalStorageHandler getHandler( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - for( final 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; - } + 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 58a2bf45..ad56eb33 100644 --- a/src/main/java/appeng/core/features/registries/GridCacheRegistry.java +++ b/src/main/java/appeng/core/features/registries/GridCacheRegistry.java @@ -18,69 +18,69 @@ package appeng.core.features.registries; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; import appeng.api.networking.IGrid; import appeng.api.networking.IGridCache; import appeng.api.networking.IGridCacheRegistry; import appeng.core.AELog; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; +public final class GridCacheRegistry implements IGridCacheRegistry { + private final Map, Class> caches + = new HashMap, Class>(); + @Override + public void registerGridCache( + final Class iface, + final Class implementation + ) { + if (iface.isAssignableFrom(implementation)) { + this.caches.put(iface, implementation); + } else { + throw new IllegalArgumentException( + "Invalid setup, grid cache must either be the same class, or an interface that the implementation implements. Gotten: " + + iface + " and " + implementation + ); + } + } -public final class GridCacheRegistry implements IGridCacheRegistry -{ - private final Map, Class> caches = new HashMap, Class>(); + @Override + public HashMap, IGridCache> + createCacheInstance(final IGrid g) { + final HashMap, IGridCache> map + = new HashMap, IGridCache>(); - @Override - public void registerGridCache( final Class iface, final Class implementation ) - { - if( iface.isAssignableFrom( implementation ) ) - { - this.caches.put( iface, implementation ); - } - else - { - throw new IllegalArgumentException( "Invalid setup, grid cache must either be the same class, or an interface that the implementation implements. Gotten: " + iface + " and " + implementation ); - } - } + for (final Class iface : this.caches.keySet()) { + try { + final Constructor c + = this.caches.get(iface).getConstructor(IGrid.class); + map.put(iface, c.newInstance(g)); + } catch (final NoSuchMethodException e) { + AELog.error( + "Grid Caches must have a constructor with IGrid as the single param." + ); + throw new IllegalArgumentException(e); + } catch (final InvocationTargetException e) { + AELog.error( + "Grid Caches must have a constructor with IGrid as the single param." + ); + throw new IllegalStateException(e); + } catch (final InstantiationException e) { + AELog.error( + "Grid Caches must have a constructor with IGrid as the single param." + ); + throw new IllegalStateException(e); + } catch (final IllegalAccessException e) { + AELog.error( + "Grid Caches must have a constructor with IGrid as the single param." + ); + throw new IllegalStateException(e); + } + } - @Override - public HashMap, IGridCache> createCacheInstance( final IGrid g ) - { - final HashMap, IGridCache> map = new HashMap, IGridCache>(); - - for( final Class iface : this.caches.keySet() ) - { - try - { - final Constructor c = this.caches.get( iface ).getConstructor( IGrid.class ); - map.put( iface, c.newInstance( g ) ); - } - catch( final NoSuchMethodException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalArgumentException( e ); - } - catch( final InvocationTargetException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - catch( final InstantiationException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - catch( final IllegalAccessException e ) - { - AELog.error( "Grid Caches must have a constructor with IGrid as the single param." ); - throw new IllegalStateException( e ); - } - } - - return map; - } + return map; + } } diff --git a/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java b/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java index 74819f32..19465c4a 100644 --- a/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java +++ b/src/main/java/appeng/core/features/registries/GrinderRecipeManager.java @@ -18,6 +18,11 @@ package appeng.core.features.registries; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import appeng.api.features.IGrinderEntry; import appeng.api.features.IGrinderRegistry; @@ -31,268 +36,266 @@ import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; +public final class GrinderRecipeManager implements IGrinderRegistry, IOreListener { + private final List recipes; + private final Map ores; + private final Map ingots; + private final Map dusts; + public GrinderRecipeManager() { + this.recipes = new ArrayList(); + this.ores = new HashMap(); + this.ingots = new HashMap(); + this.dusts = new HashMap(); -public final class GrinderRecipeManager implements IGrinderRegistry, IOreListener -{ - private final List recipes; - private final Map ores; - private final Map ingots; - private final Map dusts; + this.addOre("Coal", new ItemStack(Items.coal)); + this.addOre("Charcoal", new ItemStack(Items.coal, 1, 1)); - public GrinderRecipeManager() - { - this.recipes = new ArrayList(); - this.ores = new HashMap(); - this.ingots = new HashMap(); - this.dusts = new HashMap(); + this.addOre("NetherQuartz", new ItemStack(Blocks.quartz_ore)); + this.addIngot("NetherQuartz", new ItemStack(Items.quartz)); - this.addOre( "Coal", new ItemStack( Items.coal ) ); - this.addOre( "Charcoal", new ItemStack( Items.coal, 1, 1 ) ); + this.addOre("Gold", new ItemStack(Blocks.gold_ore)); + this.addIngot("Gold", new ItemStack(Items.gold_ingot)); - this.addOre( "NetherQuartz", new ItemStack( Blocks.quartz_ore ) ); - this.addIngot( "NetherQuartz", new ItemStack( Items.quartz ) ); + this.addOre("Iron", new ItemStack(Blocks.iron_ore)); + this.addIngot("Iron", new ItemStack(Items.iron_ingot)); - this.addOre( "Gold", new ItemStack( Blocks.gold_ore ) ); - this.addIngot( "Gold", new ItemStack( Items.gold_ingot ) ); + this.addOre("Obsidian", new ItemStack(Blocks.obsidian)); - this.addOre( "Iron", new ItemStack( Blocks.iron_ore ) ); - this.addIngot( "Iron", new ItemStack( Items.iron_ingot ) ); + this.addIngot("Ender", new ItemStack(Items.ender_pearl)); + this.addIngot("EnderPearl", new ItemStack(Items.ender_pearl)); - this.addOre( "Obsidian", new ItemStack( Blocks.obsidian ) ); + this.addIngot("Wheat", new ItemStack(Items.wheat)); - this.addIngot( "Ender", new ItemStack( Items.ender_pearl ) ); - this.addIngot( "EnderPearl", new ItemStack( Items.ender_pearl ) ); + OreDictionaryHandler.INSTANCE.observe(this); + } - this.addIngot( "Wheat", new ItemStack( Items.wheat ) ); + @Override + public List getRecipes() { + this.log("API - getRecipes"); + return this.recipes; + } - OreDictionaryHandler.INSTANCE.observe( this ); - } + @Override + public void addRecipe(final ItemStack in, final ItemStack out, final int cost) { + if (in == null || out == null) { + this.log("Invalid Grinder Recipe Specified."); + return; + } - @Override - public List getRecipes() - { - this.log( "API - getRecipes" ); - return this.recipes; - } + this.log( + "Allow Grinding of " + Platform.getItemDisplayName(in) + " to " + + Platform.getItemDisplayName(out) + " for " + cost + ); + this.injectRecipe(new AppEngGrinderRecipe(this.copy(in), this.copy(out), cost)); + } - @Override - public void addRecipe( final ItemStack in, final ItemStack out, final int cost ) - { - if( in == null || out == null ) - { - this.log( "Invalid Grinder Recipe Specified." ); - return; - } + @Override + public void addRecipe( + final ItemStack in, + final ItemStack out, + final ItemStack optional, + final float chance, + final int cost + ) { + if (in == null || (optional == null && out == null)) { + this.log("Invalid Grinder Recipe Specified."); + return; + } - this.log( "Allow Grinding of " + Platform.getItemDisplayName( in ) + " to " + Platform.getItemDisplayName( out ) + " for " + cost ); - this.injectRecipe( new AppEngGrinderRecipe( this.copy( in ), this.copy( out ), cost ) ); - } + this.log( + "Allow Grinding of " + Platform.getItemDisplayName(in) + " to " + + Platform.getItemDisplayName(out) + " with optional " + + Platform.getItemDisplayName(optional) + " for " + cost + ); + this.injectRecipe(new AppEngGrinderRecipe( + this.copy(in), this.copy(out), this.copy(optional), chance, cost + )); + } - @Override - public void addRecipe( final ItemStack in, final ItemStack out, final ItemStack optional, final float chance, final int cost ) - { - if( in == null || ( optional == null && out == null ) ) - { - this.log( "Invalid Grinder Recipe Specified." ); - return; - } + @Override + public void addRecipe( + final ItemStack in, + final ItemStack out, + final ItemStack optional, + final float chance, + final ItemStack optional2, + final float chance2, + final int cost + ) { + if (in == null || (optional == null && out == null && optional2 == null)) { + this.log("Invalid Grinder Recipe Specified."); + return; + } - this.log( "Allow Grinding of " + Platform.getItemDisplayName( in ) + " to " + Platform.getItemDisplayName( out ) + " with optional " + Platform.getItemDisplayName( optional ) + " for " + cost ); - this.injectRecipe( new AppEngGrinderRecipe( this.copy( in ), this.copy( out ), this.copy( optional ), chance, cost ) ); - } + this.log( + "Allow Grinding of " + Platform.getItemDisplayName(in) + " to " + + Platform.getItemDisplayName(out) + " with optional " + + Platform.getItemDisplayName(optional) + " for " + cost + ); + this.injectRecipe(new AppEngGrinderRecipe( + this.copy(in), + this.copy(out), + this.copy(optional), + this.copy(optional2), + chance, + chance2, + cost + )); + } - @Override - public void addRecipe( final ItemStack in, final ItemStack out, final ItemStack optional, final float chance, final ItemStack optional2, final float chance2, final int cost ) - { - if( in == null || ( optional == null && out == null && optional2 == null ) ) - { - this.log( "Invalid Grinder Recipe Specified." ); - return; - } + private void injectRecipe(final AppEngGrinderRecipe appEngGrinderRecipe) { + for (final IGrinderEntry gr : this.recipes) { + if (Platform.isSameItemPrecise( + gr.getInput(), appEngGrinderRecipe.getInput() + )) { + return; + } + } - this.log( "Allow Grinding of " + Platform.getItemDisplayName( in ) + " to " + Platform.getItemDisplayName( out ) + " with optional " + Platform.getItemDisplayName( optional ) + " for " + cost ); - this.injectRecipe( new AppEngGrinderRecipe( this.copy( in ), this.copy( out ), this.copy( optional ), this.copy( optional2 ), chance, chance2, cost ) ); - } + this.recipes.add(appEngGrinderRecipe); + } - private void injectRecipe( final AppEngGrinderRecipe appEngGrinderRecipe ) - { - for( final IGrinderEntry gr : this.recipes ) - { - if( Platform.isSameItemPrecise( gr.getInput(), appEngGrinderRecipe.getInput() ) ) - { - return; - } - } + private ItemStack copy(final ItemStack is) { + if (is != null) { + return is.copy(); + } + return null; + } - this.recipes.add( appEngGrinderRecipe ); - } + @Override + public IGrinderEntry getRecipeForInput(final ItemStack input) { + this.log("Looking up recipe for " + Platform.getItemDisplayName(input)); + if (input != null) { + for (final IGrinderEntry r : this.recipes) { + if (Platform.isSameItem(input, r.getInput())) { + this.log( + "Recipe for " + input.getUnlocalizedName() + " found " + + Platform.getItemDisplayName(r.getOutput()) + ); + return r; + } + } - private ItemStack copy( final ItemStack is ) - { - if( is != null ) - { - return is.copy(); - } - return null; - } + this.log("Could not find recipe for " + Platform.getItemDisplayName(input)); + } - @Override - public IGrinderEntry getRecipeForInput( final ItemStack input ) - { - this.log( "Looking up recipe for " + Platform.getItemDisplayName( input ) ); - if( input != null ) - { - for( final IGrinderEntry r : this.recipes ) - { - if( Platform.isSameItem( input, r.getInput() ) ) - { - this.log( "Recipe for " + input.getUnlocalizedName() + " found " + Platform.getItemDisplayName( r.getOutput() ) ); - return r; - } - } + return null; + } - this.log( "Could not find recipe for " + Platform.getItemDisplayName( input ) ); - } + private void log(final String o) { + AELog.grinder(o); + } - return null; - } + private int getDustToOreRatio(final String name) { + if (name.equals("Obsidian")) { + return 1; + } + if (name.equals("Charcoal")) { + return 1; + } + if (name.equals("Coal")) { + return 1; + } + return 2; + } - private void log( final String o ) - { - AELog.grinder( o ); - } + private void addOre(final String name, final ItemStack item) { + if (item == null) { + return; + } + this.log("Adding Ore - " + name + " : " + Platform.getItemDisplayName(item)); - private int getDustToOreRatio( final String name ) - { - if( name.equals( "Obsidian" ) ) - { - return 1; - } - if( name.equals( "Charcoal" ) ) - { - return 1; - } - if( name.equals( "Coal" ) ) - { - return 1; - } - return 2; - } + this.ores.put(item, name); - private void addOre( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - this.log( "Adding Ore - " + name + " : " + Platform.getItemDisplayName( item ) ); + if (this.dusts.containsKey(name)) { + final ItemStack is = this.dusts.get(name).copy(); + final int ratio = this.getDustToOreRatio(name); + if (ratio > 1) { + final ItemStack extra = is.copy(); + extra.stackSize = ratio - 1; + this.addRecipe( + item, + is, + extra, + (float) (AEConfig.instance.oreDoublePercentage / 100.0), + 8 + ); + } else { + this.addRecipe(item, is, 8); + } + } + } - this.ores.put( item, name ); + private void addIngot(final String name, final ItemStack item) { + if (item == null) { + return; + } + this.log("Adding Ingot - " + name + " : " + Platform.getItemDisplayName(item)); - if( this.dusts.containsKey( name ) ) - { - final ItemStack is = this.dusts.get( name ).copy(); - final int ratio = this.getDustToOreRatio( name ); - if( ratio > 1 ) - { - final ItemStack extra = is.copy(); - extra.stackSize = ratio - 1; - this.addRecipe( item, is, extra, (float) ( AEConfig.instance.oreDoublePercentage / 100.0 ), 8 ); - } - else - { - this.addRecipe( item, is, 8 ); - } - } - } + this.ingots.put(item, name); - private void addIngot( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - this.log( "Adding Ingot - " + name + " : " + Platform.getItemDisplayName( item ) ); + if (this.dusts.containsKey(name)) { + this.addRecipe(item, this.dusts.get(name), 4); + } + } - this.ingots.put( item, name ); + private void addDust(final String name, final ItemStack item) { + if (item == null) { + return; + } + if (this.dusts.containsKey(name)) { + this.log( + "Rejecting Dust - " + name + " : " + Platform.getItemDisplayName(item) + ); + return; + } - if( this.dusts.containsKey( name ) ) - { - this.addRecipe( item, this.dusts.get( name ), 4 ); - } - } + this.log("Adding Dust - " + name + " : " + Platform.getItemDisplayName(item)); - private void addDust( final String name, final ItemStack item ) - { - if( item == null ) - { - return; - } - if( this.dusts.containsKey( name ) ) - { - this.log( "Rejecting Dust - " + name + " : " + Platform.getItemDisplayName( item ) ); - return; - } + this.dusts.put(name, item); - this.log( "Adding Dust - " + name + " : " + Platform.getItemDisplayName( item ) ); + for (final Entry d : this.ores.entrySet()) { + if (name.equals(d.getValue())) { + final ItemStack is = item.copy(); + is.stackSize = 1; + final int ratio = this.getDustToOreRatio(name); + if (ratio > 1) { + final ItemStack extra = is.copy(); + extra.stackSize = ratio - 1; + this.addRecipe( + d.getKey(), + is, + extra, + (float) (AEConfig.instance.oreDoublePercentage / 100.0), + 8 + ); + } else { + this.addRecipe(d.getKey(), is, 8); + } + } + } - this.dusts.put( name, item ); + for (final Entry d : this.ingots.entrySet()) { + if (name.equals(d.getValue())) { + this.addRecipe(d.getKey(), item, 4); + } + } + } - for( final Entry d : this.ores.entrySet() ) - { - if( name.equals( d.getValue() ) ) - { - final ItemStack is = item.copy(); - is.stackSize = 1; - final int ratio = this.getDustToOreRatio( name ); - if( ratio > 1 ) - { - final ItemStack extra = is.copy(); - extra.stackSize = ratio - 1; - this.addRecipe( d.getKey(), is, extra, (float) ( AEConfig.instance.oreDoublePercentage / 100.0 ), 8 ); - } - else - { - this.addRecipe( d.getKey(), is, 8 ); - } - } - } - - for( final Entry d : this.ingots.entrySet() ) - { - if( name.equals( d.getValue() ) ) - { - this.addRecipe( d.getKey(), item, 4 ); - } - } - } - - @Override - public void oreRegistered( final String name, final ItemStack item ) - { - if( name.startsWith( "ore" ) || name.startsWith( "crystal" ) || name.startsWith( "gem" ) || name.startsWith( "ingot" ) || name.startsWith( "dust" ) ) - { - for( final String ore : AEConfig.instance.grinderOres ) - { - if( name.equals( "ore" + ore ) ) - { - this.addOre( ore, item ); - } - else if( name.equals( "crystal" + ore ) || name.equals( "ingot" + ore ) || name.equals( "gem" + ore ) ) - { - this.addIngot( ore, item ); - } - else if( name.equals( "dust" + ore ) ) - { - this.addDust( ore, item ); - } - } - } - } + @Override + public void oreRegistered(final String name, final ItemStack item) { + if (name.startsWith("ore") || name.startsWith("crystal") || name.startsWith("gem") + || name.startsWith("ingot") || name.startsWith("dust")) { + for (final String ore : AEConfig.instance.grinderOres) { + if (name.equals("ore" + ore)) { + this.addOre(ore, item); + } else if (name.equals("crystal" + ore) || name.equals("ingot" + ore) || name.equals("gem" + ore)) { + this.addIngot(ore, item); + } else if (name.equals("dust" + ore)) { + this.addDust(ore, item); + } + } + } + } } diff --git a/src/main/java/appeng/core/features/registries/InscriberRegistry.java b/src/main/java/appeng/core/features/registries/InscriberRegistry.java index ac2bbd84..72ecb274 100644 --- a/src/main/java/appeng/core/features/registries/InscriberRegistry.java +++ b/src/main/java/appeng/core/features/registries/InscriberRegistry.java @@ -18,6 +18,8 @@ package appeng.core.features.registries; +import java.util.*; +import javax.annotation.Nonnull; import appeng.api.features.IInscriberRecipe; import appeng.api.features.IInscriberRecipeBuilder; @@ -26,169 +28,147 @@ import appeng.api.features.InscriberProcessType; import appeng.core.features.registries.entries.InscriberRecipe; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import java.util.*; - - /** * @author thatsIch * @version rv3 * @since rv2 */ -public final class InscriberRegistry implements IInscriberRegistry -{ - private final Set recipes; - private final Set optionals; - private final Set inputs; +public final class InscriberRegistry implements IInscriberRegistry { + private final Set recipes; + private final Set optionals; + private final Set inputs; - public InscriberRegistry() - { - this.inputs = new HashSet(); - this.optionals = new HashSet(); - this.recipes = new HashSet(); - } + public InscriberRegistry() { + this.inputs = new HashSet(); + this.optionals = new HashSet(); + this.recipes = new HashSet(); + } - @Nonnull - @Override - public Collection getRecipes() - { - return Collections.unmodifiableCollection( this.recipes ); - } + @Nonnull + @Override + public Collection getRecipes() { + return Collections.unmodifiableCollection(this.recipes); + } - @Nonnull - @Override - public Set getOptionals() - { - return this.optionals; - } + @Nonnull + @Override + public Set getOptionals() { + return this.optionals; + } - @Nonnull - @Override - public Set getInputs() - { - return this.inputs; - } + @Nonnull + @Override + public Set getInputs() { + return this.inputs; + } - @Nonnull - @Override - public IInscriberRecipeBuilder builder() - { - return new Builder(); - } + @Nonnull + @Override + public IInscriberRecipeBuilder builder() { + return new Builder(); + } - @Override - public void addRecipe( final IInscriberRecipe recipe ) - { - if( recipe == null ) - { - throw new IllegalArgumentException( "Tried to add an invalid (null) inscriber recipe to the registry." ); - } + @Override + public void addRecipe(final IInscriberRecipe recipe) { + if (recipe == null) { + throw new IllegalArgumentException( + "Tried to add an invalid (null) inscriber recipe to the registry." + ); + } - this.recipes.add( recipe ); + this.recipes.add(recipe); - this.optionals.addAll( recipe.getTopOptional().asSet() ); - this.optionals.addAll( recipe.getBottomOptional().asSet() ); + this.optionals.addAll(recipe.getTopOptional().asSet()); + this.optionals.addAll(recipe.getBottomOptional().asSet()); - this.inputs.addAll( recipe.getInputs() ); - } + this.inputs.addAll(recipe.getInputs()); + } - @Override - public void removeRecipe( final IInscriberRecipe toBeRemovedRecipe ) - { - for( final Iterator iterator = this.recipes.iterator(); iterator.hasNext(); ) - { - final IInscriberRecipe recipe = iterator.next(); - if( recipe.equals( toBeRemovedRecipe ) ) - { - iterator.remove(); - } - } - } + @Override + public void removeRecipe(final IInscriberRecipe toBeRemovedRecipe) { + for (final Iterator iterator = this.recipes.iterator(); + iterator.hasNext();) { + final IInscriberRecipe recipe = iterator.next(); + if (recipe.equals(toBeRemovedRecipe)) { + iterator.remove(); + } + } + } - /** - * Internal {@link IInscriberRecipeBuilder} implementation. - * Needs to be adapted to represent a correct {@link IInscriberRecipe} - */ - private static final class Builder implements IInscriberRecipeBuilder - { - private List inputs; - private ItemStack output; - private ItemStack topOptional; - private ItemStack bottomOptional; - private InscriberProcessType type; + /** + * Internal {@link IInscriberRecipeBuilder} implementation. + * Needs to be adapted to represent a correct {@link IInscriberRecipe} + */ + private static final class Builder implements IInscriberRecipeBuilder { + private List inputs; + private ItemStack output; + private ItemStack topOptional; + private ItemStack bottomOptional; + private InscriberProcessType type; - @Nonnull - @Override - public Builder withInputs( @Nonnull final Collection inputs ) - { - this.inputs = new ArrayList( inputs.size() ); - this.inputs.addAll( inputs ); + @Nonnull + @Override + public Builder withInputs(@Nonnull final Collection inputs) { + this.inputs = new ArrayList(inputs.size()); + this.inputs.addAll(inputs); - return this; - } + return this; + } - @Nonnull - @Override - public Builder withOutput( @Nonnull final ItemStack output ) - { - this.output = output; + @Nonnull + @Override + public Builder withOutput(@Nonnull final ItemStack output) { + this.output = output; - return this; - } + return this; + } - @Nonnull - @Override - public Builder withTopOptional( @Nonnull final ItemStack topOptional ) - { - this.topOptional = topOptional; + @Nonnull + @Override + public Builder withTopOptional(@Nonnull final ItemStack topOptional) { + this.topOptional = topOptional; - return this; - } + return this; + } - @Nonnull - @Override - public Builder withBottomOptional( @Nonnull final ItemStack bottomOptional ) - { - this.bottomOptional = bottomOptional; + @Nonnull + @Override + public Builder withBottomOptional(@Nonnull final ItemStack bottomOptional) { + this.bottomOptional = bottomOptional; - return this; - } + return this; + } - @Nonnull - @Override - public Builder withProcessType( @Nonnull final InscriberProcessType type ) - { - this.type = type; + @Nonnull + @Override + public Builder withProcessType(@Nonnull final InscriberProcessType type) { + this.type = type; - return this; - } + return this; + } - @Nonnull - @Override - public IInscriberRecipe build() - { - if( this.inputs == null ) - { - throw new IllegalStateException( "Input must be defined." ); - } - if( this.inputs.isEmpty() ) - { - throw new IllegalStateException( "Input must have a size." ); - } - if( this.output == null ) - { - throw new IllegalStateException( "Output must be defined." ); - } - if( this.topOptional == null && this.bottomOptional == null ) - { - throw new IllegalStateException( "One optional must be defined." ); - } - if( this.type == null ) - { - throw new IllegalStateException( "Process type must be defined." ); - } + @Nonnull + @Override + public IInscriberRecipe build() { + if (this.inputs == null) { + throw new IllegalStateException("Input must be defined."); + } + if (this.inputs.isEmpty()) { + throw new IllegalStateException("Input must have a size."); + } + if (this.output == null) { + throw new IllegalStateException("Output must be defined."); + } + if (this.topOptional == null && this.bottomOptional == null) { + throw new IllegalStateException("One optional must be defined."); + } + if (this.type == null) { + throw new IllegalStateException("Process type must be defined."); + } - return new InscriberRecipe( this.inputs, this.output, this.topOptional, this.bottomOptional, this.type ); - } - } + return new InscriberRecipe( + this.inputs, this.output, this.topOptional, this.bottomOptional, this.type + ); + } + } } diff --git a/src/main/java/appeng/core/features/registries/LocatableRegistry.java b/src/main/java/appeng/core/features/registries/LocatableRegistry.java index d0e069e1..eae4aa45 100644 --- a/src/main/java/appeng/core/features/registries/LocatableRegistry.java +++ b/src/main/java/appeng/core/features/registries/LocatableRegistry.java @@ -18,6 +18,8 @@ package appeng.core.features.registries; +import java.util.HashMap; +import java.util.Map; import appeng.api.events.LocatableEventAnnounce; import appeng.api.events.LocatableEventAnnounce.LocatableEvent; @@ -27,51 +29,38 @@ import appeng.util.Platform; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.common.MinecraftForge; -import java.util.HashMap; -import java.util.Map; +public final class LocatableRegistry implements ILocatableRegistry { + private final Map set; + public LocatableRegistry() { + this.set = new HashMap(); + MinecraftForge.EVENT_BUS.register(this); + } -public final class LocatableRegistry implements ILocatableRegistry -{ - private final Map set; + @SubscribeEvent + public void updateLocatable(final LocatableEventAnnounce e) { + if (Platform.isClient()) { + return; // IGNORE! + } - public LocatableRegistry() - { - this.set = new HashMap(); - MinecraftForge.EVENT_BUS.register( this ); - } + if (e.change == LocatableEvent.Register) { + this.set.put(e.target.getLocatableSerial(), e.target); + } else if (e.change == LocatableEvent.Unregister) { + this.set.remove(e.target.getLocatableSerial()); + } + } - @SubscribeEvent - public void updateLocatable( final LocatableEventAnnounce e ) - { - if( Platform.isClient() ) - { - return; // IGNORE! - } + /** + * Find a locate-able object by its serial. + */ + @Override + @Deprecated + public Object findLocatableBySerial(final long ser) { + return this.set.get(ser); + } - if( e.change == LocatableEvent.Register ) - { - this.set.put( e.target.getLocatableSerial(), e.target ); - } - else if( e.change == LocatableEvent.Unregister ) - { - this.set.remove( e.target.getLocatableSerial() ); - } - } - - /** - * Find a locate-able object by its serial. - */ - @Override - @Deprecated - public Object findLocatableBySerial( final long ser ) - { - return this.set.get( ser ); - } - - @Override - public ILocatable getLocatableBy( final long serial ) - { - return this.set.get( serial ); - } + @Override + public ILocatable getLocatableBy(final long serial) { + return this.set.get(serial); + } } diff --git a/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java b/src/main/java/appeng/core/features/registries/MatterCannonAmmoRegistry.java index 9ff3af34..ea9ad4f7 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 appeng.api.features.IMatterCannonAmmoRegistry; import appeng.recipes.ores.IOreListener; @@ -26,125 +27,114 @@ import appeng.util.Platform; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import java.util.HashMap; +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); + } -public class MatterCannonAmmoRegistry implements IOreListener, IMatterCannonAmmoRegistry -{ + @Override + public void registerAmmo(final ItemStack ammo, final double weight) { + this.DamageModifiers.put(ammo, weight); + } - private final HashMap DamageModifiers = new HashMap(); + @Override + public float getPenetration(final ItemStack is) { + for (final ItemStack o : this.DamageModifiers.keySet()) { + if (Platform.isSameItem(o, is)) { + return this.DamageModifiers.get(o).floatValue(); + } + } + return 0; + } - public MatterCannonAmmoRegistry() - { - OreDictionaryHandler.INSTANCE.observe( this ); - this.registerAmmo( new ItemStack( Items.gold_nugget ), 196.96655 ); - } + @Override + public void oreRegistered(final String name, final ItemStack item) { + if (!(name.startsWith("berry") || name.startsWith("nugget"))) { + return; + } - @Override - public void registerAmmo( final ItemStack ammo, final double weight ) - { - this.DamageModifiers.put( ammo, weight ); - } + // addNugget( "Cobble", 18 ); // ? + this.considerItem(name, item, "MeatRaw", 32); + this.considerItem(name, item, "MeatCooked", 32); + this.considerItem(name, item, "Meat", 32); + this.considerItem(name, item, "Chicken", 32); + this.considerItem(name, item, "Beef", 32); + this.considerItem(name, item, "Sheep", 32); + this.considerItem(name, item, "Fish", 32); - @Override - public float getPenetration( final ItemStack is ) - { - for( final ItemStack o : this.DamageModifiers.keySet() ) - { - if( Platform.isSameItem( o, is ) ) - { - return this.DamageModifiers.get( o ).floatValue(); - } - } - return 0; - } + // real world... + this.considerItem(name, item, "Lithium", 6.941); + this.considerItem(name, item, "Beryllium", 9.0122); + this.considerItem(name, item, "Boron", 10.811); + this.considerItem(name, item, "Carbon", 12.0107); + this.considerItem(name, item, "Coal", 12.0107); + this.considerItem(name, item, "Charcoal", 12.0107); + this.considerItem(name, item, "Sodium", 22.9897); + this.considerItem(name, item, "Magnesium", 24.305); + this.considerItem(name, item, "Aluminum", 26.9815); + this.considerItem(name, item, "Silicon", 28.0855); + this.considerItem(name, item, "Phosphorus", 30.9738); + this.considerItem(name, item, "Sulfur", 32.065); + this.considerItem(name, item, "Potassium", 39.0983); + this.considerItem(name, item, "Calcium", 40.078); + this.considerItem(name, item, "Scandium", 44.9559); + this.considerItem(name, item, "Titanium", 47.867); + this.considerItem(name, item, "Vanadium", 50.9415); + this.considerItem(name, item, "Manganese", 54.938); + this.considerItem(name, item, "Iron", 55.845); + this.considerItem(name, item, "Nickel", 58.6934); + this.considerItem(name, item, "Cobalt", 58.9332); + this.considerItem(name, item, "Copper", 63.546); + this.considerItem(name, item, "Zinc", 65.39); + this.considerItem(name, item, "Gallium", 69.723); + this.considerItem(name, item, "Germanium", 72.64); + this.considerItem(name, item, "Bromine", 79.904); + this.considerItem(name, item, "Krypton", 83.8); + this.considerItem(name, item, "Rubidium", 85.4678); + this.considerItem(name, item, "Strontium", 87.62); + this.considerItem(name, item, "Yttrium", 88.9059); + this.considerItem(name, item, "Zirconiumm", 91.224); + this.considerItem(name, item, "Niobiumm", 92.9064); + this.considerItem(name, item, "Technetium", 98); + this.considerItem(name, item, "Ruthenium", 101.07); + this.considerItem(name, item, "Rhodium", 102.9055); + this.considerItem(name, item, "Palladium", 106.42); + this.considerItem(name, item, "Silver", 107.8682); + this.considerItem(name, item, "Cadmium", 112.411); + this.considerItem(name, item, "Indium", 114.818); + this.considerItem(name, item, "Tin", 118.71); + this.considerItem(name, item, "Antimony", 121.76); + this.considerItem(name, item, "Iodine", 126.9045); + this.considerItem(name, item, "Tellurium", 127.6); + this.considerItem(name, item, "Xenon", 131.293); + this.considerItem(name, item, "Cesium", 132.9055); + this.considerItem(name, item, "Barium", 137.327); + this.considerItem(name, item, "Lanthanum", 138.9055); + this.considerItem(name, item, "Cerium", 140.116); + this.considerItem(name, item, "Tantalum", 180.9479); + this.considerItem(name, item, "Tungsten", 183.84); + this.considerItem(name, item, "Osmium", 190.23); + this.considerItem(name, item, "Iridium", 192.217); + this.considerItem(name, item, "Platinum", 195.078); + this.considerItem(name, item, "Lead", 207.2); + this.considerItem(name, item, "Bismuth", 208.9804); + this.considerItem(name, item, "Uranium", 238.0289); + this.considerItem(name, item, "Plutonium", 244); - @Override - public void oreRegistered( final String name, final ItemStack item ) - { - if( !( name.startsWith( "berry" ) || name.startsWith( "nugget" ) ) ) - { - return; - } + // 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); + } - // addNugget( "Cobble", 18 ); // ? - this.considerItem( name, item, "MeatRaw", 32 ); - this.considerItem( name, item, "MeatCooked", 32 ); - this.considerItem( name, item, "Meat", 32 ); - this.considerItem( name, item, "Chicken", 32 ); - this.considerItem( name, item, "Beef", 32 ); - this.considerItem( name, item, "Sheep", 32 ); - this.considerItem( name, item, "Fish", 32 ); - - // real world... - this.considerItem( name, item, "Lithium", 6.941 ); - this.considerItem( name, item, "Beryllium", 9.0122 ); - this.considerItem( name, item, "Boron", 10.811 ); - this.considerItem( name, item, "Carbon", 12.0107 ); - this.considerItem( name, item, "Coal", 12.0107 ); - this.considerItem( name, item, "Charcoal", 12.0107 ); - this.considerItem( name, item, "Sodium", 22.9897 ); - this.considerItem( name, item, "Magnesium", 24.305 ); - this.considerItem( name, item, "Aluminum", 26.9815 ); - this.considerItem( name, item, "Silicon", 28.0855 ); - this.considerItem( name, item, "Phosphorus", 30.9738 ); - this.considerItem( name, item, "Sulfur", 32.065 ); - this.considerItem( name, item, "Potassium", 39.0983 ); - this.considerItem( name, item, "Calcium", 40.078 ); - this.considerItem( name, item, "Scandium", 44.9559 ); - this.considerItem( name, item, "Titanium", 47.867 ); - this.considerItem( name, item, "Vanadium", 50.9415 ); - this.considerItem( name, item, "Manganese", 54.938 ); - this.considerItem( name, item, "Iron", 55.845 ); - this.considerItem( name, item, "Nickel", 58.6934 ); - this.considerItem( name, item, "Cobalt", 58.9332 ); - this.considerItem( name, item, "Copper", 63.546 ); - this.considerItem( name, item, "Zinc", 65.39 ); - this.considerItem( name, item, "Gallium", 69.723 ); - this.considerItem( name, item, "Germanium", 72.64 ); - this.considerItem( name, item, "Bromine", 79.904 ); - this.considerItem( name, item, "Krypton", 83.8 ); - this.considerItem( name, item, "Rubidium", 85.4678 ); - this.considerItem( name, item, "Strontium", 87.62 ); - this.considerItem( name, item, "Yttrium", 88.9059 ); - this.considerItem( name, item, "Zirconiumm", 91.224 ); - this.considerItem( name, item, "Niobiumm", 92.9064 ); - this.considerItem( name, item, "Technetium", 98 ); - this.considerItem( name, item, "Ruthenium", 101.07 ); - this.considerItem( name, item, "Rhodium", 102.9055 ); - this.considerItem( name, item, "Palladium", 106.42 ); - this.considerItem( name, item, "Silver", 107.8682 ); - this.considerItem( name, item, "Cadmium", 112.411 ); - this.considerItem( name, item, "Indium", 114.818 ); - this.considerItem( name, item, "Tin", 118.71 ); - this.considerItem( name, item, "Antimony", 121.76 ); - this.considerItem( name, item, "Iodine", 126.9045 ); - this.considerItem( name, item, "Tellurium", 127.6 ); - this.considerItem( name, item, "Xenon", 131.293 ); - this.considerItem( name, item, "Cesium", 132.9055 ); - this.considerItem( name, item, "Barium", 137.327 ); - this.considerItem( name, item, "Lanthanum", 138.9055 ); - this.considerItem( name, item, "Cerium", 140.116 ); - this.considerItem( name, item, "Tantalum", 180.9479 ); - this.considerItem( name, item, "Tungsten", 183.84 ); - this.considerItem( name, item, "Osmium", 190.23 ); - this.considerItem( name, item, "Iridium", 192.217 ); - this.considerItem( name, item, "Platinum", 195.078 ); - this.considerItem( name, item, "Lead", 207.2 ); - this.considerItem( name, item, "Bismuth", 208.9804 ); - this.considerItem( name, item, "Uranium", 238.0289 ); - 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 ); - } - - private void considerItem( final String ore, final ItemStack item, final String name, final double weight ) - { - if( ore.equals( "berry" + name ) || ore.equals( "nugget" + name ) ) - { - this.registerAmmo( item, weight ); - } - } + private void considerItem( + final String ore, final ItemStack item, final String name, final double weight + ) { + if (ore.equals("berry" + name) || ore.equals("nugget" + name)) { + this.registerAmmo(item, weight); + } + } } diff --git a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java index 337415e6..aee8c6bb 100644 --- a/src/main/java/appeng/core/features/registries/MovableTileRegistry.java +++ b/src/main/java/appeng/core/features/registries/MovableTileRegistry.java @@ -18,6 +18,9 @@ package appeng.core.features.registries; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; import appeng.api.exceptions.AppEngException; import appeng.api.movable.IMovableHandler; @@ -27,140 +30,119 @@ import appeng.spatial.DefaultSpatialHandler; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; +public class MovableTileRegistry implements IMovableRegistry { + private final HashSet blacklisted = new HashSet(); + private final HashMap, IMovableHandler> Valid + = new HashMap, IMovableHandler>(); + private final LinkedList> test + = new LinkedList>(); + private final LinkedList handlers + = new LinkedList(); + private final DefaultSpatialHandler dsh = new DefaultSpatialHandler(); -public class MovableTileRegistry implements IMovableRegistry -{ + private final IMovableHandler nullHandler = new DefaultSpatialHandler(); - private final HashSet blacklisted = new HashSet(); + @Override + public void blacklistBlock(final Block blk) { + this.blacklisted.add(blk); + } - private final HashMap, IMovableHandler> Valid = new HashMap, IMovableHandler>(); - private final LinkedList> test = new LinkedList>(); - private final LinkedList handlers = new LinkedList(); - private final DefaultSpatialHandler dsh = new DefaultSpatialHandler(); + @Override + public void whiteListTileEntity(final Class c) { + if (c.getName().equals(TileEntity.class.getName())) { + throw new IllegalArgumentException(new AppEngException( + "Someone tried to make all tiles movable with " + c + + ", this is a clear violation of the purpose of the white list." + )); + } - private final IMovableHandler nullHandler = new DefaultSpatialHandler(); + this.test.add(c); + } - @Override - public void blacklistBlock( final Block blk ) - { - this.blacklisted.add( blk ); - } + @Override + public boolean askToMove(final TileEntity te) { + final Class myClass = te.getClass(); + IMovableHandler canMove = this.Valid.get(myClass); - @Override - public void whiteListTileEntity( final Class c ) - { - if( c.getName().equals( TileEntity.class.getName() ) ) - { - throw new IllegalArgumentException( new AppEngException( "Someone tried to make all tiles movable with " + c + ", this is a clear violation of the purpose of the white list." ) ); - } + if (canMove == null) { + canMove = this.testClass(myClass, te); + } - this.test.add( c ); - } + if (canMove != this.nullHandler) { + if (te instanceof IMovableTile) { + ((IMovableTile) te).prepareToMove(); + } - @Override - public boolean askToMove( final TileEntity te ) - { - final Class myClass = te.getClass(); - IMovableHandler canMove = this.Valid.get( myClass ); + te.invalidate(); + return true; + } - if( canMove == null ) - { - canMove = this.testClass( myClass, te ); - } + return false; + } - if( canMove != this.nullHandler ) - { - if( te instanceof IMovableTile ) - { - ( (IMovableTile) te ).prepareToMove(); - } + private IMovableHandler testClass(final Class myClass, final TileEntity te) { + IMovableHandler handler = null; - te.invalidate(); - return true; - } + // ask handlers... + for (final IMovableHandler han : this.handlers) { + if (han.canHandle(myClass, te)) { + handler = han; + break; + } + } - return false; - } + // if you have a handler your opted in + if (handler != null) { + this.Valid.put(myClass, handler); + return handler; + } - private IMovableHandler testClass( final Class myClass, final TileEntity te ) - { - IMovableHandler handler = null; + // if your movable our opted in + if (te instanceof IMovableTile) { + this.Valid.put(myClass, this.dsh); + return this.dsh; + } - // ask handlers... - for( final IMovableHandler han : this.handlers ) - { - if( han.canHandle( myClass, te ) ) - { - handler = han; - break; - } - } + // if you are on the white list your opted in. + for (final Class testClass : this.test) { + if (testClass.isAssignableFrom(myClass)) { + this.Valid.put(myClass, this.dsh); + return this.dsh; + } + } - // if you have a handler your opted in - if( handler != null ) - { - this.Valid.put( myClass, handler ); - return handler; - } + this.Valid.put(myClass, this.nullHandler); + return this.nullHandler; + } - // if your movable our opted in - if( te instanceof IMovableTile ) - { - this.Valid.put( myClass, this.dsh ); - return this.dsh; - } + @Override + public void doneMoving(final TileEntity te) { + if (te instanceof IMovableTile) { + final IMovableTile mt = (IMovableTile) te; + mt.doneMoving(); + } + } - // if you are on the white list your opted in. - for( final Class testClass : this.test ) - { - if( testClass.isAssignableFrom( myClass ) ) - { - this.Valid.put( myClass, this.dsh ); - return this.dsh; - } - } + @Override + public void addHandler(final IMovableHandler han) { + this.handlers.add(han); + } - this.Valid.put( myClass, this.nullHandler ); - return this.nullHandler; - } + @Override + public IMovableHandler getHandler(final TileEntity te) { + final Class myClass = te.getClass(); + final IMovableHandler h = this.Valid.get(myClass); + return h == null ? this.dsh : h; + } - @Override - public void doneMoving( final TileEntity te ) - { - if( te instanceof IMovableTile ) - { - final IMovableTile mt = (IMovableTile) te; - mt.doneMoving(); - } - } + @Override + public IMovableHandler getDefaultHandler() { + return this.dsh; + } - @Override - public void addHandler( final IMovableHandler han ) - { - this.handlers.add( han ); - } - - @Override - public IMovableHandler getHandler( final TileEntity te ) - { - final Class myClass = te.getClass(); - final IMovableHandler h = this.Valid.get( myClass ); - return h == null ? this.dsh : h; - } - - @Override - public IMovableHandler getDefaultHandler() - { - return this.dsh; - } - - @Override - public boolean isBlacklisted( final Block blk ) - { - return this.blacklisted.contains( blk ); - } + @Override + public boolean isBlacklisted(final 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 a6f2a0a4..dab23064 100644 --- a/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java +++ b/src/main/java/appeng/core/features/registries/P2PTunnelRegistry.java @@ -18,6 +18,9 @@ package appeng.core.features.registries; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.config.TunnelType; @@ -35,143 +38,165 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.oredict.OreDictionary; -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; +public final class P2PTunnelRegistry implements IP2PTunnelRegistry { + private static final int INITIAL_CAPACITY = 40; + private final Map tunnels + = new HashMap(INITIAL_CAPACITY); -public final class P2PTunnelRegistry implements IP2PTunnelRegistry -{ - private static final int INITIAL_CAPACITY = 40; + public void configure() { + /** + * light! + */ + this.addNewAttunement(new ItemStack(Blocks.torch), TunnelType.LIGHT); + this.addNewAttunement(new ItemStack(Blocks.glowstone), TunnelType.LIGHT); - private final Map tunnels = new HashMap( INITIAL_CAPACITY ); + /** + * attune based on most redstone base items. + */ + this.addNewAttunement(new ItemStack(Items.redstone), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Items.repeater), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.redstone_lamp), TunnelType.REDSTONE); + this.addNewAttunement( + new ItemStack(Blocks.unpowered_comparator), TunnelType.REDSTONE + ); + this.addNewAttunement( + new ItemStack(Blocks.powered_comparator), TunnelType.REDSTONE + ); + this.addNewAttunement( + new ItemStack(Blocks.powered_repeater), TunnelType.REDSTONE + ); + this.addNewAttunement( + new ItemStack(Blocks.unpowered_repeater), TunnelType.REDSTONE + ); + this.addNewAttunement( + new ItemStack(Blocks.daylight_detector), TunnelType.REDSTONE + ); + this.addNewAttunement(new ItemStack(Blocks.redstone_wire), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.redstone_block), TunnelType.REDSTONE); + this.addNewAttunement(new ItemStack(Blocks.lever), TunnelType.REDSTONE); + this.addNewAttunement( + this.getModItem( + "EnderIO", "itemRedstoneConduit", OreDictionary.WILDCARD_VALUE + ), + TunnelType.REDSTONE + ); - public void configure() - { - /** - * light! - */ - this.addNewAttunement( new ItemStack( Blocks.torch ), TunnelType.LIGHT ); - this.addNewAttunement( new ItemStack( Blocks.glowstone ), TunnelType.LIGHT ); + /** + * attune based on lots of random item related stuff + */ + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IParts parts = definitions.parts(); - /** - * attune based on most redstone base items. - */ - this.addNewAttunement( new ItemStack( Items.redstone ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Items.repeater ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.redstone_lamp ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.unpowered_comparator ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.powered_comparator ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.powered_repeater ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.unpowered_repeater ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.daylight_detector ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.redstone_wire ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.redstone_block ), TunnelType.REDSTONE ); - this.addNewAttunement( new ItemStack( Blocks.lever ), TunnelType.REDSTONE ); - this.addNewAttunement( this.getModItem( "EnderIO", "itemRedstoneConduit", OreDictionary.WILDCARD_VALUE ), TunnelType.REDSTONE ); + this.addNewAttunement(blocks.iface(), TunnelType.ITEM); + this.addNewAttunement(parts.iface(), TunnelType.ITEM); + this.addNewAttunement(parts.storageBus(), TunnelType.ITEM); + this.addNewAttunement(parts.importBus(), TunnelType.ITEM); + this.addNewAttunement(parts.exportBus(), TunnelType.ITEM); - /** - * attune based on lots of random item related stuff - */ - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IParts parts = definitions.parts(); + this.addNewAttunement(new ItemStack(Blocks.hopper), TunnelType.ITEM); + this.addNewAttunement(new ItemStack(Blocks.chest), TunnelType.ITEM); + this.addNewAttunement(new ItemStack(Blocks.trapped_chest), TunnelType.ITEM); + this.addNewAttunement( + this.getModItem("ExtraUtilities", "extractor_base", 0), TunnelType.ITEM + ); + this.addNewAttunement( + this.getModItem("Mekanism", "PartTransmitter", 9), TunnelType.ITEM + ); + this.addNewAttunement( + this.getModItem("EnderIO", "itemItemConduit", OreDictionary.WILDCARD_VALUE), + TunnelType.ITEM + ); + this.addNewAttunement( + this.getModItem("ThermalDynamics", "ThermalDynamics_32", 0), TunnelType.ITEM + ); - this.addNewAttunement( blocks.iface(), TunnelType.ITEM ); - this.addNewAttunement( parts.iface(), TunnelType.ITEM ); - this.addNewAttunement( parts.storageBus(), TunnelType.ITEM ); - this.addNewAttunement( parts.importBus(), TunnelType.ITEM ); - this.addNewAttunement( parts.exportBus(), TunnelType.ITEM ); + /** + * attune based on lots of random item related stuff + */ + this.addNewAttunement(new ItemStack(Items.bucket), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.lava_bucket), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.milk_bucket), TunnelType.FLUID); + this.addNewAttunement(new ItemStack(Items.water_bucket), TunnelType.FLUID); + this.addNewAttunement( + this.getModItem("Mekanism", "MachineBlock2", 11), TunnelType.FLUID + ); + this.addNewAttunement( + this.getModItem("Mekanism", "PartTransmitter", 4), TunnelType.FLUID + ); + this.addNewAttunement( + this.getModItem("ExtraUtilities", "extractor_base", 6), TunnelType.FLUID + ); + this.addNewAttunement( + this.getModItem("ExtraUtilities", "drum", OreDictionary.WILDCARD_VALUE), + TunnelType.FLUID + ); + this.addNewAttunement( + this.getModItem("EnderIO", "itemLiquidConduit", OreDictionary.WILDCARD_VALUE), + TunnelType.FLUID + ); + this.addNewAttunement( + this.getModItem("ThermalDynamics", "ThermalDynamics_16", 0), TunnelType.FLUID + ); - this.addNewAttunement( new ItemStack( Blocks.hopper ), TunnelType.ITEM ); - this.addNewAttunement( new ItemStack( Blocks.chest ), TunnelType.ITEM ); - this.addNewAttunement( new ItemStack( Blocks.trapped_chest ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "ExtraUtilities", "extractor_base", 0 ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "Mekanism", "PartTransmitter", 9 ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "EnderIO", "itemItemConduit", OreDictionary.WILDCARD_VALUE ), TunnelType.ITEM ); - this.addNewAttunement( this.getModItem( "ThermalDynamics", "ThermalDynamics_32", 0 ), TunnelType.ITEM ); + for (final AEColor c : AEColor.values()) { + this.addNewAttunement(parts.cableGlass().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableCovered().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableSmart().stack(c, 1), TunnelType.ME); + this.addNewAttunement(parts.cableDense().stack(c, 1), TunnelType.ME); + } + } - /** - * attune based on lots of random item related stuff - */ - this.addNewAttunement( new ItemStack( Items.bucket ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.lava_bucket ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.milk_bucket ), TunnelType.FLUID ); - this.addNewAttunement( new ItemStack( Items.water_bucket ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "Mekanism", "MachineBlock2", 11 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "Mekanism", "PartTransmitter", 4 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "ExtraUtilities", "extractor_base", 6 ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "ExtraUtilities", "drum", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "EnderIO", "itemLiquidConduit", OreDictionary.WILDCARD_VALUE ), TunnelType.FLUID ); - this.addNewAttunement( this.getModItem( "ThermalDynamics", "ThermalDynamics_16", 0 ), TunnelType.FLUID ); + @Override + public void + addNewAttunement(@Nullable final ItemStack trigger, @Nullable final TunnelType type) { + if (type == null || trigger == null) { + return; + } - for( final AEColor c : AEColor.values() ) - { - this.addNewAttunement( parts.cableGlass().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableCovered().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableSmart().stack( c, 1 ), TunnelType.ME ); - this.addNewAttunement( parts.cableDense().stack( c, 1 ), TunnelType.ME ); - } - } + this.tunnels.put(trigger, type); + } - @Override - public void addNewAttunement( @Nullable final ItemStack trigger, @Nullable final TunnelType type ) - { - if( type == null || trigger == null ) - { - return; - } + @Nullable + @Override + public TunnelType getTunnelTypeByItem(final ItemStack trigger) { + if (trigger != null) { + if (FluidContainerRegistry.isContainer(trigger)) { + return TunnelType.FLUID; + } - this.tunnels.put( trigger, type ); - } + for (final ItemStack is : this.tunnels.keySet()) { + if (is.getItem() == trigger.getItem() + && is.getItemDamage() == OreDictionary.WILDCARD_VALUE) { + return this.tunnels.get(is); + } - @Nullable - @Override - public TunnelType getTunnelTypeByItem( final ItemStack trigger ) - { - if( trigger != null ) - { - if( FluidContainerRegistry.isContainer( trigger ) ) - { - return TunnelType.FLUID; - } + if (Platform.isSameItem(is, trigger)) { + return this.tunnels.get(is); + } + } + } - for( final ItemStack is : this.tunnels.keySet() ) - { - if( is.getItem() == trigger.getItem() && is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) - { - return this.tunnels.get( is ); - } + return null; + } - if( Platform.isSameItem( is, trigger ) ) - { - return this.tunnels.get( is ); - } - } - } + @Nullable + private ItemStack getModItem(final String modID, final String name, final int meta) { + final ItemStack myItemStack = GameRegistry.findItemStack(modID, name, 1); - return null; - } + if (myItemStack == null) { + return null; + } - @Nullable - private ItemStack getModItem( final String modID, final String name, final int meta ) - { - final ItemStack myItemStack = GameRegistry.findItemStack( modID, name, 1 ); + myItemStack.setItemDamage(meta); + return myItemStack; + } - if( myItemStack == null ) - { - return null; - } - - myItemStack.setItemDamage( meta ); - return myItemStack; - } - - private void addNewAttunement( final IItemDefinition definition, final TunnelType type ) - { - for( final ItemStack definitionStack : definition.maybeStack( 1 ).asSet() ) - { - this.addNewAttunement( definitionStack, type ); - } - } + private void + addNewAttunement(final IItemDefinition definition, final TunnelType type) { + for (final ItemStack definitionStack : definition.maybeStack(1).asSet()) { + this.addNewAttunement(definitionStack, type); + } + } } diff --git a/src/main/java/appeng/core/features/registries/PlayerRegistry.java b/src/main/java/appeng/core/features/registries/PlayerRegistry.java index 16c2b0ed..f25cb89e 100644 --- a/src/main/java/appeng/core/features/registries/PlayerRegistry.java +++ b/src/main/java/appeng/core/features/registries/PlayerRegistry.java @@ -18,39 +18,31 @@ package appeng.core.features.registries; +import javax.annotation.Nullable; import appeng.api.features.IPlayerRegistry; import appeng.core.worlddata.WorldData; import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; -import javax.annotation.Nullable; +public class PlayerRegistry implements IPlayerRegistry { + @Override + public int getID(final GameProfile username) { + if (username == null || !username.isComplete()) { + return -1; + } + return WorldData.instance().playerData().getPlayerID(username); + } -public class PlayerRegistry implements IPlayerRegistry -{ + @Override + public int getID(final EntityPlayer player) { + return this.getID(player.getGameProfile()); + } - @Override - public int getID( final GameProfile username ) - { - if( username == null || !username.isComplete() ) - { - return -1; - } - - return WorldData.instance().playerData().getPlayerID( username ); - } - - @Override - public int getID( final EntityPlayer player ) - { - return this.getID( player.getGameProfile() ); - } - - @Nullable - @Override - public EntityPlayer findPlayer( final int playerID ) - { - return WorldData.instance().playerData().getPlayerFromID( playerID ); - } + @Nullable + @Override + public EntityPlayer findPlayer(final int playerID) { + return WorldData.instance().playerData().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 2a90128d..a82a10af 100644 --- a/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java +++ b/src/main/java/appeng/core/features/registries/RecipeHandlerRegistry.java @@ -18,6 +18,8 @@ package appeng.core.features.registries; +import java.util.*; +import javax.annotation.Nullable; import appeng.api.features.IRecipeHandlerRegistry; import appeng.api.recipes.ICraftHandler; @@ -26,86 +28,70 @@ import appeng.api.recipes.ISubItemResolver; import appeng.core.AELog; import appeng.recipes.RecipeHandler; -import javax.annotation.Nullable; -import java.util.*; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv3 - 10.08.2015 * @since rv0 */ -public class RecipeHandlerRegistry implements IRecipeHandlerRegistry -{ - private final Map> handlers = new HashMap>( 20 ); - private final Collection resolvers = new LinkedList(); +public class RecipeHandlerRegistry implements IRecipeHandlerRegistry { + private final Map> handlers + = new HashMap>(20); + private final Collection resolvers + = new LinkedList(); - @Override - public void addNewCraftHandler( final String name, final Class handler ) - { - this.handlers.put( name.toLowerCase( Locale.ENGLISH ), handler ); - } + @Override + public void + addNewCraftHandler(final String name, final Class handler) { + this.handlers.put(name.toLowerCase(Locale.ENGLISH), handler); + } - @Override - public void addNewSubItemResolver( final ISubItemResolver sir ) - { - this.resolvers.add( sir ); - } + @Override + public void addNewSubItemResolver(final ISubItemResolver sir) { + this.resolvers.add(sir); + } - @Nullable - @Override - public ICraftHandler getCraftHandlerFor( final String name ) - { - final Class clz = this.handlers.get( name ); - if( clz == null ) - { - return null; - } - try - { - return clz.newInstance(); - } - catch( final Throwable e ) - { - AELog.error( "Error Caused when trying to construct " + clz.getName() ); - AELog.debug( e ); + @Nullable + @Override + public ICraftHandler getCraftHandlerFor(final String name) { + final Class clz = this.handlers.get(name); + if (clz == null) { + return null; + } + try { + return clz.newInstance(); + } catch (final Throwable e) { + AELog.error("Error Caused when trying to construct " + clz.getName()); + AELog.debug(e); - this.handlers.put( name, null ); // clear it.. + this.handlers.put(name, null); // clear it.. - return null; - } - } + return null; + } + } - @Override - public IRecipeHandler createNewRecipehandler() - { - return new RecipeHandler(); - } + @Override + public IRecipeHandler createNewRecipehandler() { + return new RecipeHandler(); + } - @Nullable - @Override - public Object resolveItem( final String nameSpace, final String itemName ) - { - for( final ISubItemResolver sir : this.resolvers ) - { - Object rr = null; + @Nullable + @Override + public Object resolveItem(final String nameSpace, final String itemName) { + for (final ISubItemResolver sir : this.resolvers) { + Object rr = null; - try - { - rr = sir.resolveItemByName( nameSpace, itemName ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } + try { + rr = sir.resolveItemByName(nameSpace, itemName); + } catch (final Throwable t) { + AELog.debug(t); + } - if( rr != null ) - { - return rr; - } - } + if (rr != null) { + return rr; + } + } - return null; - } + 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 195c7263..8c1ed1d5 100644 --- a/src/main/java/appeng/core/features/registries/RegistryContainer.java +++ b/src/main/java/appeng/core/features/registries/RegistryContainer.java @@ -18,14 +18,12 @@ package appeng.core.features.registries; - import appeng.api.features.*; import appeng.api.movable.IMovableRegistry; import appeng.api.networking.IGridCacheRegistry; import appeng.api.storage.ICellRegistry; import appeng.api.storage.IExternalStorageRegistry; - /** * represents all registries * @@ -34,103 +32,89 @@ import appeng.api.storage.IExternalStorageRegistry; * @version rv2 * @since rv0 */ -public class RegistryContainer implements IRegistryContainer -{ - private final IGrinderRegistry grinder = new GrinderRecipeManager(); - private final IInscriberRegistry inscriber = new InscriberRegistry(); - private final IExternalStorageRegistry storage = new ExternalStorageRegistry(); - private final ICellRegistry cell = new CellRegistry(); - private final ILocatableRegistry locatable = new LocatableRegistry(); - private final ISpecialComparisonRegistry comparison = new SpecialComparisonRegistry(); - private final IWirelessTermRegistry wireless = new WirelessRegistry(); - private final IGridCacheRegistry gridCache = new GridCacheRegistry(); - private final IP2PTunnelRegistry p2pTunnel = new P2PTunnelRegistry(); - private final IMovableRegistry movable = new MovableTileRegistry(); - private final IMatterCannonAmmoRegistry matterCannonReg = new MatterCannonAmmoRegistry(); - private final IPlayerRegistry playerRegistry = new PlayerRegistry(); - private final IRecipeHandlerRegistry recipeReg = new RecipeHandlerRegistry(); +public class RegistryContainer implements IRegistryContainer { + private final IGrinderRegistry grinder = new GrinderRecipeManager(); + private final IInscriberRegistry inscriber = new InscriberRegistry(); + private final IExternalStorageRegistry storage = new ExternalStorageRegistry(); + private final ICellRegistry cell = new CellRegistry(); + private final ILocatableRegistry locatable = new LocatableRegistry(); + private final ISpecialComparisonRegistry comparison = new SpecialComparisonRegistry(); + private final IWirelessTermRegistry wireless = new WirelessRegistry(); + private final IGridCacheRegistry gridCache = new GridCacheRegistry(); + private final IP2PTunnelRegistry p2pTunnel = new P2PTunnelRegistry(); + private final IMovableRegistry movable = new MovableTileRegistry(); + private final IMatterCannonAmmoRegistry matterCannonReg + = new MatterCannonAmmoRegistry(); + private final IPlayerRegistry playerRegistry = new PlayerRegistry(); + private final IRecipeHandlerRegistry recipeReg = new RecipeHandlerRegistry(); - @Override - public IMovableRegistry movable() - { - return this.movable; - } + @Override + public IMovableRegistry movable() { + return this.movable; + } - @Override - public IGridCacheRegistry gridCache() - { - return this.gridCache; - } + @Override + public IGridCacheRegistry gridCache() { + return this.gridCache; + } - @Override - public IExternalStorageRegistry externalStorage() - { - return this.storage; - } + @Override + public IExternalStorageRegistry externalStorage() { + return this.storage; + } - @Override - public ISpecialComparisonRegistry specialComparison() - { - return this.comparison; - } + @Override + public ISpecialComparisonRegistry specialComparison() { + return this.comparison; + } - @Override - public IWirelessTermRegistry wireless() - { - return this.wireless; - } + @Override + public IWirelessTermRegistry wireless() { + return this.wireless; + } - @Override - public ICellRegistry cell() - { - return this.cell; - } + @Override + public ICellRegistry cell() { + return this.cell; + } - @Override - public IGrinderRegistry grinder() - { - return this.grinder; - } + @Override + public IGrinderRegistry grinder() { + return this.grinder; + } - @Override - public IInscriberRegistry inscriber() - { - return this.inscriber; - } + @Override + public IInscriberRegistry inscriber() { + return this.inscriber; + } - @Override - public ILocatableRegistry locatable() - { - return this.locatable; - } + @Override + public ILocatableRegistry locatable() { + return this.locatable; + } - @Override - public IP2PTunnelRegistry p2pTunnel() - { - return this.p2pTunnel; - } + @Override + public IP2PTunnelRegistry p2pTunnel() { + return this.p2pTunnel; + } - @Override - public IMatterCannonAmmoRegistry matterCannon() - { - return this.matterCannonReg; - } + @Override + public IMatterCannonAmmoRegistry matterCannon() { + return this.matterCannonReg; + } - @Override - public IPlayerRegistry players() - { - return this.playerRegistry; - } + @Override + public IPlayerRegistry players() { + return this.playerRegistry; + } - @Override - public IRecipeHandlerRegistry recipes() - { - return this.recipeReg; - } + @Override + public IRecipeHandlerRegistry recipes() { + return this.recipeReg; + } - @Override - public IWorldGen worldgen() - { - return WorldGenRegistry.INSTANCE; - } + @Override + public IWorldGen worldgen() { + 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 4563351b..0c29c58e 100644 --- a/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java +++ b/src/main/java/appeng/core/features/registries/SpecialComparisonRegistry.java @@ -18,44 +18,35 @@ package appeng.core.features.registries; +import java.util.ArrayList; +import java.util.List; import appeng.api.features.IItemComparison; import appeng.api.features.IItemComparisonProvider; import appeng.api.features.ISpecialComparisonRegistry; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.List; +public class SpecialComparisonRegistry implements ISpecialComparisonRegistry { + private final List CompRegistry; + public SpecialComparisonRegistry() { + this.CompRegistry = new ArrayList(); + } -public class SpecialComparisonRegistry implements ISpecialComparisonRegistry -{ + @Override + public IItemComparison getSpecialComparison(final ItemStack stack) { + for (final IItemComparisonProvider i : this.CompRegistry) { + final IItemComparison comp = i.getComparison(stack); + if (comp != null) { + return comp; + } + } - private final List CompRegistry; + return null; + } - public SpecialComparisonRegistry() - { - this.CompRegistry = new ArrayList(); - } - - @Override - public IItemComparison getSpecialComparison( final ItemStack stack ) - { - for( final IItemComparisonProvider i : this.CompRegistry ) - { - final IItemComparison comp = i.getComparison( stack ); - if( comp != null ) - { - return comp; - } - } - - return null; - } - - @Override - public void addComparisonProvider( final IItemComparisonProvider prov ) - { - this.CompRegistry.add( prov ); - } + @Override + public void addComparisonProvider(final IItemComparisonProvider prov) { + this.CompRegistry.add(prov); + } } diff --git a/src/main/java/appeng/core/features/registries/WirelessRegistry.java b/src/main/java/appeng/core/features/registries/WirelessRegistry.java index 4b93d2c8..4d7b62b0 100644 --- a/src/main/java/appeng/core/features/registries/WirelessRegistry.java +++ b/src/main/java/appeng/core/features/registries/WirelessRegistry.java @@ -18,6 +18,8 @@ package appeng.core.features.registries; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.api.features.ILocatable; @@ -30,91 +32,72 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -import java.util.ArrayList; -import java.util.List; +public final class WirelessRegistry implements IWirelessTermRegistry { + private final List handlers; + public WirelessRegistry() { + this.handlers = new ArrayList(); + } -public final class WirelessRegistry implements IWirelessTermRegistry -{ - private final List handlers; + @Override + public void registerWirelessHandler(final IWirelessTermHandler handler) { + if (handler != null) { + this.handlers.add(handler); + } + } - public WirelessRegistry() - { - this.handlers = new ArrayList(); - } + @Override + public boolean isWirelessTerminal(final ItemStack is) { + for (final IWirelessTermHandler h : this.handlers) { + if (h.canHandle(is)) { + return true; + } + } + return false; + } - @Override - public void registerWirelessHandler( final IWirelessTermHandler handler ) - { - if( handler != null ) - { - this.handlers.add( handler ); - } - } + @Override + public IWirelessTermHandler getWirelessTerminalHandler(final ItemStack is) { + for (final IWirelessTermHandler h : this.handlers) { + if (h.canHandle(is)) { + return h; + } + } + return null; + } - @Override - public boolean isWirelessTerminal( final ItemStack is ) - { - for( final IWirelessTermHandler h : this.handlers ) - { - if( h.canHandle( is ) ) - { - return true; - } - } - return false; - } + @Override + public void openWirelessTerminalGui( + final ItemStack item, final World w, final EntityPlayer player + ) { + if (Platform.isClient()) { + return; + } - @Override - public IWirelessTermHandler getWirelessTerminalHandler( final ItemStack is ) - { - for( final IWirelessTermHandler h : this.handlers ) - { - if( h.canHandle( is ) ) - { - return h; - } - } - return null; - } + if (!this.isWirelessTerminal(item)) { + player.addChatMessage(PlayerMessages.DeviceNotWirelessTerminal.get()); + return; + } - @Override - public void openWirelessTerminalGui( final ItemStack item, final World w, final EntityPlayer player ) - { - if( Platform.isClient() ) - { - return; - } + final IWirelessTermHandler handler = this.getWirelessTerminalHandler(item); + final String unparsedKey = handler.getEncryptionKey(item); + if (unparsedKey.isEmpty()) { + player.addChatMessage(PlayerMessages.DeviceNotLinked.get()); + return; + } - if( !this.isWirelessTerminal( item ) ) - { - player.addChatMessage( PlayerMessages.DeviceNotWirelessTerminal.get() ); - return; - } + final long parsedKey = Long.parseLong(unparsedKey); + final ILocatable securityStation + = AEApi.instance().registries().locatable().getLocatableBy(parsedKey); + if (securityStation == null) { + player.addChatMessage(PlayerMessages.StationCanNotBeLocated.get()); + return; + } - final IWirelessTermHandler handler = this.getWirelessTerminalHandler( item ); - final String unparsedKey = handler.getEncryptionKey( item ); - if( unparsedKey.isEmpty() ) - { - player.addChatMessage( PlayerMessages.DeviceNotLinked.get() ); - return; - } - - final long parsedKey = Long.parseLong( unparsedKey ); - final ILocatable securityStation = AEApi.instance().registries().locatable().getLocatableBy( parsedKey ); - if( securityStation == null ) - { - player.addChatMessage( PlayerMessages.StationCanNotBeLocated.get() ); - return; - } - - if( handler.hasPower( player, 0.5, item ) ) - { - Platform.openGUI( player, null, null, GuiBridge.GUI_WIRELESS_TERM ); - } - else - { - player.addChatMessage( PlayerMessages.DeviceNotPowered.get() ); - } - } + 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 a33859a9..c067ed61 100644 --- a/src/main/java/appeng/core/features/registries/WorldGenRegistry.java +++ b/src/main/java/appeng/core/features/registries/WorldGenRegistry.java @@ -18,99 +18,88 @@ package appeng.core.features.registries; +import java.util.HashSet; import appeng.api.features.IWorldGen; import net.minecraft.world.World; import net.minecraft.world.WorldProvider; -import java.util.HashSet; +public final class WorldGenRegistry implements IWorldGen { + public static final WorldGenRegistry INSTANCE = new WorldGenRegistry(); + private final TypeSet[] types; + private WorldGenRegistry() { + this.types = new TypeSet[WorldGenType.values().length]; -public final class WorldGenRegistry implements IWorldGen -{ + for (final WorldGenType type : WorldGenType.values()) { + this.types[type.ordinal()] = new TypeSet(); + } + } - public static final WorldGenRegistry INSTANCE = new WorldGenRegistry(); - private final TypeSet[] types; + @Override + public void disableWorldGenForProviderID( + final WorldGenType type, final Class provider + ) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } - private WorldGenRegistry() - { + if (provider == null) { + throw new IllegalArgumentException("Bad Provider Passed"); + } - this.types = new TypeSet[WorldGenType.values().length]; + this.types[type.ordinal()].badProviders.add(provider); + } - for( final WorldGenType type : WorldGenType.values() ) - { - this.types[type.ordinal()] = new TypeSet(); - } - } + @Override + public void + enableWorldGenForDimension(final WorldGenType type, final int dimensionID) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } - @Override - public void disableWorldGenForProviderID( final WorldGenType type, final Class provider ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + this.types[type.ordinal()].enabledDimensions.add(dimensionID); + } - if( provider == null ) - { - throw new IllegalArgumentException( "Bad Provider Passed" ); - } + @Override + public void + disableWorldGenForDimension(final WorldGenType type, final int dimensionID) { + if (type == null) { + throw new IllegalArgumentException("Bad Type Passed"); + } - this.types[type.ordinal()].badProviders.add( provider ); - } + this.types[type.ordinal()].badDimensions.add(dimensionID); + } - @Override - public void enableWorldGenForDimension( final WorldGenType type, final int dimensionID ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + @Override + public boolean isWorldGenEnabled(final WorldGenType type, final World w) { + 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"); + } - @Override - public void disableWorldGenForDimension( final WorldGenType type, final int dimensionID ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + final boolean isBadProvider + = this.types[type.ordinal()].badProviders.contains(w.provider.getClass()); + final boolean isBadDimension + = this.types[type.ordinal()].badDimensions.contains(w.provider.dimensionId); + final boolean isGoodDimension + = this.types[type.ordinal()].enabledDimensions.contains(w.provider.dimensionId + ); - this.types[type.ordinal()].badDimensions.add( dimensionID ); - } + if (isBadProvider || isBadDimension) { + return false; + } - @Override - public boolean isWorldGenEnabled( final WorldGenType type, final World w ) - { - if( type == null ) - { - throw new IllegalArgumentException( "Bad Type Passed" ); - } + return !(!isGoodDimension && type == WorldGenType.Meteorites); + } - if( w == null ) - { - throw new IllegalArgumentException( "Bad Provider Passed" ); - } - - final boolean isBadProvider = this.types[type.ordinal()].badProviders.contains( w.provider.getClass() ); - final boolean isBadDimension = this.types[type.ordinal()].badDimensions.contains( w.provider.dimensionId ); - final boolean isGoodDimension = this.types[type.ordinal()].enabledDimensions.contains( w.provider.dimensionId ); - - if( isBadProvider || isBadDimension ) - { - return false; - } - - return !( !isGoodDimension && type == WorldGenType.Meteorites ); - } - - private static class TypeSet - { - - final HashSet> badProviders = new HashSet>(); - final HashSet badDimensions = new HashSet(); - final HashSet enabledDimensions = new HashSet(); - } + 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 c4554457..5c72958d 100644 --- a/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java +++ b/src/main/java/appeng/core/features/registries/entries/AppEngGrinderRecipe.java @@ -18,128 +18,123 @@ package appeng.core.features.registries.entries; - import appeng.api.features.IGrinderEntry; import net.minecraft.item.ItemStack; +public class AppEngGrinderRecipe implements IGrinderEntry { + private ItemStack in; + private ItemStack out; -public class AppEngGrinderRecipe implements IGrinderEntry -{ + private float optionalChance; + private ItemStack optionalOutput; - private ItemStack in; - private ItemStack out; + private float optionalChance2; + private ItemStack optionalOutput2; - private float optionalChance; - private ItemStack optionalOutput; + private int energy; - private float optionalChance2; - private ItemStack optionalOutput2; + public AppEngGrinderRecipe(final ItemStack a, final ItemStack b, final int cost) { + this.in = a; + this.out = b; + this.energy = cost; + } - private int energy; + public AppEngGrinderRecipe( + final ItemStack a, + final ItemStack b, + final ItemStack c, + final float chance, + final int cost + ) { + this.in = a; + this.out = b; - public AppEngGrinderRecipe( final ItemStack a, final ItemStack b, final int cost ) - { - this.in = a; - this.out = b; - this.energy = cost; - } + this.optionalOutput = c; + this.optionalChance = chance; - public AppEngGrinderRecipe( final ItemStack a, final ItemStack b, final ItemStack c, final float chance, final int cost ) - { - this.in = a; - this.out = b; + this.energy = cost; + } - this.optionalOutput = c; - this.optionalChance = chance; + public AppEngGrinderRecipe( + final ItemStack a, + final ItemStack b, + final ItemStack c, + final ItemStack d, + final float chance, + final float chance2, + final int cost + ) { + this.in = a; + this.out = b; - this.energy = cost; - } + this.optionalOutput = c; + this.optionalChance = chance; - public AppEngGrinderRecipe( final ItemStack a, final ItemStack b, final ItemStack c, final ItemStack d, final float chance, final float chance2, final int cost ) - { - this.in = a; - this.out = b; + this.optionalOutput2 = d; + this.optionalChance2 = chance2; - this.optionalOutput = c; - this.optionalChance = chance; + this.energy = cost; + } - this.optionalOutput2 = d; - this.optionalChance2 = chance2; + @Override + public ItemStack getInput() { + return this.in; + } - this.energy = cost; - } + @Override + public void setInput(final ItemStack i) { + this.in = i.copy(); + } - @Override - public ItemStack getInput() - { - return this.in; - } + @Override + public ItemStack getOutput() { + return this.out; + } - @Override - public void setInput( final ItemStack i ) - { - this.in = i.copy(); - } + @Override + public void setOutput(final ItemStack o) { + this.out = o.copy(); + } - @Override - public ItemStack getOutput() - { - return this.out; - } + @Override + public ItemStack getOptionalOutput() { + return this.optionalOutput; + } - @Override - public void setOutput( final ItemStack o ) - { - this.out = o.copy(); - } + @Override + public ItemStack getSecondOptionalOutput() { + return this.optionalOutput2; + } - @Override - public ItemStack getOptionalOutput() - { - return this.optionalOutput; - } + @Override + public void setOptionalOutput(final ItemStack output, final float chance) { + this.optionalOutput = output.copy(); + this.optionalChance = chance; + } - @Override - public ItemStack getSecondOptionalOutput() - { - return this.optionalOutput2; - } + @Override + public float getOptionalChance() { + return this.optionalChance; + } - @Override - public void setOptionalOutput( final ItemStack output, final float chance ) - { - this.optionalOutput = output.copy(); - this.optionalChance = chance; - } + @Override + public void setSecondOptionalOutput(final ItemStack output, final float chance) { + this.optionalChance2 = chance; + this.optionalOutput2 = output.copy(); + } - @Override - public float getOptionalChance() - { - return this.optionalChance; - } + @Override + public float getSecondOptionalChance() { + return this.optionalChance2; + } - @Override - public void setSecondOptionalOutput( final ItemStack output, final float chance ) - { - this.optionalChance2 = chance; - this.optionalOutput2 = output.copy(); - } + @Override + public int getEnergyCost() { + return this.energy; + } - @Override - public float getSecondOptionalChance() - { - return this.optionalChance2; - } - - @Override - public int getEnergyCost() - { - return this.energy; - } - - @Override - public void setEnergyCost( final int c ) - { - this.energy = c; - } + @Override + public void setEnergyCost(final 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 096d043c..4abec421 100644 --- a/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java +++ b/src/main/java/appeng/core/features/registries/entries/BasicCellHandler.java @@ -18,7 +18,6 @@ package appeng.core.features.registries.entries; - import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.storage.*; import appeng.client.texture.ExtraBlockTextures; @@ -31,65 +30,61 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; +public class BasicCellHandler implements ICellHandler { + @Override + public boolean isCell(final ItemStack is) { + return CellInventory.isCell(is); + } -public class BasicCellHandler implements ICellHandler -{ + @Override + public IMEInventoryHandler getCellInventory( + final ItemStack is, final ISaveProvider container, final StorageChannel channel + ) { + if (channel == StorageChannel.ITEMS) { + return CellInventory.getCell(is, container); + } + return null; + } - @Override - public boolean isCell( final ItemStack is ) - { - return CellInventory.isCell( is ); - } + @Override + public IIcon getTopTexture_Light() { + return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); + } - @Override - public IMEInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final StorageChannel channel ) - { - if( channel == StorageChannel.ITEMS ) - { - return CellInventory.getCell( is, container ); - } - return null; - } + @Override + public IIcon getTopTexture_Medium() { + return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); + } - @Override - public IIcon getTopTexture_Light() - { - return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); - } + @Override + public IIcon getTopTexture_Dark() { + return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); + } - @Override - public IIcon getTopTexture_Medium() - { - return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); - } + @Override + public void openChestGui( + final EntityPlayer player, + final IChestOrDrive chest, + final ICellHandler cellHandler, + final IMEInventoryHandler inv, + final ItemStack is, + final StorageChannel chan + ) { + Platform.openGUI(player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME); + } - @Override - public IIcon getTopTexture_Dark() - { - return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); - } + @Override + public int getStatusForCell(final ItemStack is, final IMEInventory handler) { + if (handler instanceof CellInventoryHandler) { + final CellInventoryHandler ci = (CellInventoryHandler) handler; + return ci.getStatusForCell(); + } + return 0; + } - @Override - public void openChestGui( final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final StorageChannel chan ) - { - Platform.openGUI( player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME ); - } - - @Override - public int getStatusForCell( final ItemStack is, final IMEInventory handler ) - { - if( handler instanceof CellInventoryHandler ) - { - final CellInventoryHandler ci = (CellInventoryHandler) handler; - return ci.getStatusForCell(); - } - return 0; - } - - @Override - public double cellIdleDrain( final ItemStack is, final IMEInventory handler ) - { - final ICellInventory inv = ( (ICellInventoryHandler) handler ).getCellInv(); - return inv.getIdleDrain(); - } + @Override + public double cellIdleDrain(final ItemStack is, final IMEInventory handler) { + final 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 9e6e2ecf..d9b49a5b 100644 --- a/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java +++ b/src/main/java/appeng/core/features/registries/entries/CreativeCellHandler.java @@ -18,7 +18,6 @@ package appeng.core.features.registries.entries; - import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.storage.*; import appeng.client.texture.ExtraBlockTextures; @@ -31,59 +30,57 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; +public class CreativeCellHandler implements ICellHandler { + @Override + public boolean isCell(final ItemStack is) { + return is != null && is.getItem() instanceof ItemCreativeStorageCell; + } -public class CreativeCellHandler implements ICellHandler -{ + @Override + public IMEInventoryHandler getCellInventory( + final ItemStack is, final ISaveProvider container, final StorageChannel channel + ) { + if (channel == StorageChannel.ITEMS && is != null + && is.getItem() instanceof ItemCreativeStorageCell) { + return CreativeCellInventory.getCell(is); + } + return null; + } - @Override - public boolean isCell( final ItemStack is ) - { - return is != null && is.getItem() instanceof ItemCreativeStorageCell; - } + @Override + public IIcon getTopTexture_Light() { + return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); + } - @Override - public IMEInventoryHandler getCellInventory( final ItemStack is, final ISaveProvider container, final StorageChannel channel ) - { - if( channel == StorageChannel.ITEMS && is != null && is.getItem() instanceof ItemCreativeStorageCell ) - { - return CreativeCellInventory.getCell( is ); - } - return null; - } + @Override + public IIcon getTopTexture_Medium() { + return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); + } - @Override - public IIcon getTopTexture_Light() - { - return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); - } + @Override + public IIcon getTopTexture_Dark() { + return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); + } - @Override - public IIcon getTopTexture_Medium() - { - return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); - } + @Override + public void openChestGui( + final EntityPlayer player, + final IChestOrDrive chest, + final ICellHandler cellHandler, + final IMEInventoryHandler inv, + final ItemStack is, + final StorageChannel chan + ) { + Platform.openGUI(player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME); + } - @Override - public IIcon getTopTexture_Dark() - { - return ExtraBlockTextures.BlockMEChestItems_Dark.getIcon(); - } + @Override + public int getStatusForCell(final ItemStack is, final IMEInventory handler) { + return 2; + } - @Override - public void openChestGui( final EntityPlayer player, final IChestOrDrive chest, final ICellHandler cellHandler, final IMEInventoryHandler inv, final ItemStack is, final StorageChannel chan ) - { - Platform.openGUI( player, (TileEntity) chest, chest.getUp(), GuiBridge.GUI_ME ); - } - - @Override - public int getStatusForCell( final ItemStack is, final IMEInventory handler ) - { - return 2; - } - - @Override - public double cellIdleDrain( final ItemStack is, final IMEInventory handler ) - { - return 0; - } + @Override + public double cellIdleDrain(final ItemStack is, final 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 399b461d..4db9d84a 100644 --- a/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java +++ b/src/main/java/appeng/core/features/registries/entries/ExternalIInv.java @@ -18,7 +18,6 @@ package appeng.core.features.registries.entries; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,26 +28,30 @@ import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class ExternalIInv implements IExternalStorageHandler { + @Override + public boolean canHandle( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource mySrc + ) { + return channel == StorageChannel.ITEMS && te instanceof IInventory; + } -public class ExternalIInv implements IExternalStorageHandler -{ + @Override + public IMEInventory getInventory( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource src + ) { + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, d); - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc ) - { - return channel == StorageChannel.ITEMS && te instanceof IInventory; - } + if (channel == StorageChannel.ITEMS && ad != null) { + return new MEMonitorIInventory(ad); + } - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src ) - { - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, d ); - - if( channel == StorageChannel.ITEMS && ad != null ) - { - return new MEMonitorIInventory( ad ); - } - - return null; - } + return null; + } } diff --git a/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java b/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java index c3d4bc32..dacdfc4f 100644 --- a/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java +++ b/src/main/java/appeng/core/features/registries/entries/InscriberInscribeRecipe.java @@ -1,14 +1,12 @@ package appeng.core.features.registries.entries; +import java.util.Collection; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.features.InscriberProcessType; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.Collection; - - /** * inscribe recipes do not use up the provided optional upon craft * @@ -16,10 +14,13 @@ import java.util.Collection; * @version rv2 * @since rv2 */ -public class InscriberInscribeRecipe extends InscriberRecipe -{ - public InscriberInscribeRecipe( @Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot ) - { - super( inputs, output, top, bot, InscriberProcessType.Inscribe ); - } +public class InscriberInscribeRecipe extends InscriberRecipe { + public InscriberInscribeRecipe( + @Nonnull final Collection inputs, + @Nonnull final ItemStack output, + @Nullable final ItemStack top, + @Nullable final ItemStack bot + ) { + super(inputs, output, top, bot, InscriberProcessType.Inscribe); + } } diff --git a/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java b/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java index 8508d8c3..aa629c01 100644 --- a/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java +++ b/src/main/java/appeng/core/features/registries/entries/InscriberRecipe.java @@ -1,18 +1,16 @@ package appeng.core.features.registries.entries; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.features.IInscriberRecipe; import appeng.api.features.InscriberProcessType; import com.google.common.base.Optional; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - - /** * Basic inscriber recipe * @@ -20,111 +18,102 @@ import java.util.List; * @version rv2 * @since rv2 */ -public class InscriberRecipe implements IInscriberRecipe -{ - @Nonnull - private final List inputs; +public class InscriberRecipe implements IInscriberRecipe { + @Nonnull + private final List inputs; - @Nonnull - private final ItemStack output; + @Nonnull + private final ItemStack output; - @Nonnull - private final Optional maybeTop; + @Nonnull + private final Optional maybeTop; - @Nonnull - private final Optional maybeBot; + @Nonnull + private final Optional maybeBot; - @Nonnull - private final InscriberProcessType type; + @Nonnull + private final InscriberProcessType type; - public InscriberRecipe( @Nonnull final Collection inputs, @Nonnull final ItemStack output, @Nullable final ItemStack top, @Nullable final ItemStack bot, @Nonnull final InscriberProcessType type ) - { - this.inputs = new ArrayList( inputs.size() ); - this.inputs.addAll( inputs ); + public InscriberRecipe( + @Nonnull final Collection inputs, + @Nonnull final ItemStack output, + @Nullable final ItemStack top, + @Nullable final ItemStack bot, + @Nonnull final InscriberProcessType type + ) { + this.inputs = new ArrayList(inputs.size()); + this.inputs.addAll(inputs); - this.output = output; - this.maybeTop = Optional.fromNullable( top ); - this.maybeBot = Optional.fromNullable( bot ); + this.output = output; + this.maybeTop = Optional.fromNullable(top); + this.maybeBot = Optional.fromNullable(bot); - this.type = type; - } + this.type = type; + } - @Nonnull - @Override - public final List getInputs() - { - return this.inputs; - } + @Nonnull + @Override + public final List getInputs() { + return this.inputs; + } - @Nonnull - @Override - public final ItemStack getOutput() - { - return this.output; - } + @Nonnull + @Override + public final ItemStack getOutput() { + return this.output; + } - @Nonnull - @Override - public final Optional getTopOptional() - { - return this.maybeTop; - } + @Nonnull + @Override + public final Optional getTopOptional() { + return this.maybeTop; + } - @Nonnull - @Override - public final Optional getBottomOptional() - { - return this.maybeBot; - } + @Nonnull + @Override + public final Optional getBottomOptional() { + return this.maybeBot; + } - @Nonnull - @Override - public final InscriberProcessType getProcessType() - { - return this.type; - } + @Nonnull + @Override + public final InscriberProcessType getProcessType() { + return this.type; + } - @Override - public boolean equals( final Object o ) - { - if( this == o ) - { - return true; - } - if( !( o instanceof IInscriberRecipe ) ) - { - return false; - } + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof IInscriberRecipe)) { + return false; + } - final IInscriberRecipe that = (IInscriberRecipe) o; + final IInscriberRecipe that = (IInscriberRecipe) o; - if( !this.inputs.equals( that.getInputs() ) ) - { - return false; - } - if( !this.output.equals( that.getOutput() ) ) - { - return false; - } - if( !this.maybeTop.equals( that.getTopOptional() ) ) - { - return false; - } - if( !this.maybeBot.equals( that.getBottomOptional() ) ) - { - return false; - } - return this.type == that.getProcessType(); - } + if (!this.inputs.equals(that.getInputs())) { + return false; + } + if (!this.output.equals(that.getOutput())) { + return false; + } + if (!this.maybeTop.equals(that.getTopOptional())) { + return false; + } + if (!this.maybeBot.equals(that.getBottomOptional())) { + return false; + } + return this.type == that.getProcessType(); + } - @Override - public int hashCode() - { - int result = this.inputs.hashCode(); - result = 31 * result + this.output.hashCode(); - result = 31 * result + this.maybeTop.hashCode(); - result = 31 * result + this.maybeBot.hashCode(); - result = 31 * result + this.type.hashCode(); - return result; - } + @Override + public int hashCode() { + int result = this.inputs.hashCode(); + result = 31 * result + this.output.hashCode(); + result = 31 * result + this.maybeTop.hashCode(); + result = 31 * result + this.maybeBot.hashCode(); + result = 31 * result + this.type.hashCode(); + return result; + } } diff --git a/src/main/java/appeng/core/localization/ButtonToolTips.java b/src/main/java/appeng/core/localization/ButtonToolTips.java index ae20f6a4..30d912dc 100644 --- a/src/main/java/appeng/core/localization/ButtonToolTips.java +++ b/src/main/java/appeng/core/localization/ButtonToolTips.java @@ -18,74 +18,141 @@ package appeng.core.localization; - import appeng.api.config.SchedulingMode; import net.minecraft.util.StatCollector; +public enum ButtonToolTips { + PowerUnits, + IOMode, + CondenserOutput, + RedstoneMode, + MatchingFuzzy, -public enum ButtonToolTips -{ - PowerUnits, IOMode, CondenserOutput, RedstoneMode, MatchingFuzzy, + MatchingMode, + TransferDirection, + SortOrder, + SortBy, + View, - MatchingMode, TransferDirection, SortOrder, SortBy, View, + PartitionStorage, + Clear, + FuzzyMode, + OperationMode, + TrashController, - PartitionStorage, Clear, FuzzyMode, OperationMode, TrashController, + InterfaceBlockingMode, + InterfaceCraftingMode, + Trash, + MatterBalls, - InterfaceBlockingMode, InterfaceCraftingMode, Trash, MatterBalls, + Singularity, + Read, + Write, + ReadWrite, + AlwaysActive, - Singularity, Read, Write, ReadWrite, AlwaysActive, + ActiveWithoutSignal, + ActiveWithSignal, + ActiveOnPulse, - ActiveWithoutSignal, ActiveWithSignal, ActiveOnPulse, + EmitLevelsBelow, + EmitLevelAbove, + MatchingExact, + TransferToNetwork, - EmitLevelsBelow, EmitLevelAbove, MatchingExact, TransferToNetwork, + TransferToStorageCell, + ToggleSortDirection, + SearchMode_Auto, - TransferToStorageCell, ToggleSortDirection, SearchMode_Auto, + SearchMode_Standard, + SearchMode_NEIAuto, + SearchMode_NEIStandard, - SearchMode_Standard, SearchMode_NEIAuto, SearchMode_NEIStandard, + SearchMode, + ItemName, + NumberOfItems, + PartitionStorageHint, - SearchMode, ItemName, NumberOfItems, PartitionStorageHint, + ClearSettings, + StoredItems, + StoredCraftable, + Craftable, - ClearSettings, StoredItems, StoredCraftable, Craftable, + FZPercent_25, + FZPercent_50, + FZPercent_75, + FZPercent_99, + FZIgnoreAll, - FZPercent_25, FZPercent_50, FZPercent_75, FZPercent_99, FZIgnoreAll, + MoveWhenEmpty, + MoveWhenWorkIsDone, + MoveWhenFull, + Disabled, + Enable, - MoveWhenEmpty, MoveWhenWorkIsDone, MoveWhenFull, Disabled, Enable, + Blocking, + NonBlocking, - Blocking, NonBlocking, + LevelType, + LevelType_Energy, + LevelType_Item, + InventoryTweaks, + TerminalStyle, + TerminalStyle_Full, + TerminalStyle_Tall, + TerminalStyle_Small, - LevelType, LevelType_Energy, LevelType_Item, InventoryTweaks, TerminalStyle, TerminalStyle_Full, TerminalStyle_Tall, TerminalStyle_Small, + Stash, + StashDesc, + Encode, + EncodeDescription, + Substitutions, + SubstitutionsOn, + SubstitutionsOff, + SubstitutionsDescEnabled, + SubstitutionsDescDisabled, + CraftOnly, + CraftEither, - Stash, StashDesc, Encode, EncodeDescription, Substitutions, SubstitutionsOn, SubstitutionsOff, SubstitutionsDescEnabled, SubstitutionsDescDisabled, CraftOnly, CraftEither, + Craft, + Mod, + DoesntDespawn, + EmitterMode, + CraftViaRedstone, + EmitWhenCrafting, + ReportInaccessibleItems, + ReportInaccessibleItemsYes, + ReportInaccessibleItemsNo, - Craft, Mod, DoesntDespawn, EmitterMode, CraftViaRedstone, EmitWhenCrafting, ReportInaccessibleItems, ReportInaccessibleItemsYes, ReportInaccessibleItemsNo, + BlockPlacement, + BlockPlacementYes, + BlockPlacementNo, - BlockPlacement, BlockPlacementYes, BlockPlacementNo, + // Used in the tooltips of the items in the terminal, when moused over + ItemsStored, + ItemsRequestable, + P2PFrequency, - // Used in the tooltips of the items in the terminal, when moused over - ItemsStored, ItemsRequestable, P2PFrequency, + SchedulingMode, + SchedulingModeDefault, + SchedulingModeRoundRobin, + SchedulingModeRandom; - SchedulingMode, SchedulingModeDefault, SchedulingModeRoundRobin, SchedulingModeRandom; + private final String root; - private final String root; + ButtonToolTips() { + this.root = "gui.tooltips.appliedenergistics2"; + } - ButtonToolTips() - { - this.root = "gui.tooltips.appliedenergistics2"; - } + ButtonToolTips(final String r) { + this.root = r; + } - ButtonToolTips( final String r ) - { - this.root = r; - } - - public String getLocal() - { - return StatCollector.translateToLocal( this.getUnlocalized() ); - } - - 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 386c05c1..8282f258 100644 --- a/src/main/java/appeng/core/localization/GuiText.java +++ b/src/main/java/appeng/core/localization/GuiText.java @@ -18,102 +18,185 @@ package appeng.core.localization; - import net.minecraft.util.StatCollector; +public enum GuiText { + inventory("container"), // mc's default Inventory localization. -public enum GuiText -{ - inventory( "container" ), // mc's default Inventory localization. + Chest, + StoredEnergy, + Of, + Condenser, + Drive, + GrindStone, + SkyChest, - Chest, StoredEnergy, Of, Condenser, Drive, GrindStone, SkyChest, + VibrationChamber, + SpatialIOPort, + LevelEmitter, + Terminal, - VibrationChamber, SpatialIOPort, LevelEmitter, Terminal, + Interface, + Config, + StoredItems, + Patterns, + ImportBus, + ExportBus, - Interface, Config, StoredItems, Patterns, ImportBus, ExportBus, + CellWorkbench, + NetworkDetails, + StorageCells, + IOBuses, - CellWorkbench, NetworkDetails, StorageCells, IOBuses, + IOPort, + BytesUsed, + Types, + QuantumLinkChamber, + PortableCell, - IOPort, BytesUsed, Types, QuantumLinkChamber, PortableCell, + NetworkTool, + PowerUsageRate, + PowerInputRate, + Installed, + EnergyDrain, - NetworkTool, PowerUsageRate, PowerInputRate, Installed, EnergyDrain, + StorageBus, + Priority, + Security, + Encoded, + Blank, + Unlinked, + Linked, - StorageBus, Priority, Security, Encoded, Blank, Unlinked, Linked, + SecurityCardEditor, + NoPermissions, + WirelessTerminal, + Wireless, - SecurityCardEditor, NoPermissions, WirelessTerminal, Wireless, + CraftingTerminal, + FormationPlane, + Inscriber, + QuartzCuttingKnife, - CraftingTerminal, FormationPlane, Inscriber, QuartzCuttingKnife, + // tunnel names + METunnel, + ItemTunnel, + RedstoneTunnel, + EUTunnel, + FluidTunnel, + OCTunnel, + LightTunnel, + RFTunnel, + PressureTunnel, - // tunnel names - METunnel, ItemTunnel, RedstoneTunnel, EUTunnel, FluidTunnel, OCTunnel, LightTunnel, RFTunnel, PressureTunnel, + StoredSize, + CopyMode, + CopyModeDesc, + PatternTerminal, - StoredSize, CopyMode, CopyModeDesc, PatternTerminal, + // Pattern tooltips + CraftingPattern, + ProcessingPattern, + Crafts, + Creates, + And, + With, + Substitute, + Yes, + No, - // Pattern tooltips - CraftingPattern, - ProcessingPattern, - Crafts, - Creates, - And, - With, - Substitute, - Yes, - No, + MolecularAssembler, - MolecularAssembler, + StoredPower, + MaxPower, + RequiredPower, + Efficiency, + InWorldCrafting, - StoredPower, MaxPower, RequiredPower, Efficiency, InWorldCrafting, + inWorldFluix, + inWorldPurificationCertus, + inWorldPurificationNether, - inWorldFluix, inWorldPurificationCertus, inWorldPurificationNether, + inWorldPurificationFluix, + inWorldSingularity, + ChargedQuartz, - inWorldPurificationFluix, inWorldSingularity, ChargedQuartz, + NoSecondOutput, + OfSecondOutput, + MultipleOutputs, - NoSecondOutput, - OfSecondOutput, - MultipleOutputs, + Stores, + Next, + SelectAmount, + Lumen, + Empty, - Stores, Next, SelectAmount, Lumen, Empty, + ConfirmCrafting, + Stored, + Crafting, + Scheduled, + CraftingStatus, + Cancel, + ETA, + ETAFormat, - ConfirmCrafting, Stored, Crafting, Scheduled, CraftingStatus, Cancel, ETA, ETAFormat, + FromStorage, + ToCraft, + CraftingPlan, + CalculatingWait, + Start, + Bytes, - FromStorage, ToCraft, CraftingPlan, CalculatingWait, Start, Bytes, + CraftingCPU, + Automatic, + CoProcessors, + Simulation, + Missing, - CraftingCPU, Automatic, CoProcessors, Simulation, Missing, + InterfaceTerminal, + NoCraftingCPUs, + Clean, + InvalidPattern, - InterfaceTerminal, NoCraftingCPUs, Clean, InvalidPattern, + InterfaceTerminalHint, + Range, + TransparentFacades, + TransparentFacadesHint, - InterfaceTerminalHint, Range, TransparentFacades, TransparentFacadesHint, + NoCraftingJobs, + CPUs, + FacadeCrafting, + inWorldCraftingPresses, + ChargedQuartzFind, - NoCraftingJobs, CPUs, FacadeCrafting, inWorldCraftingPresses, ChargedQuartzFind, + Included, + Excluded, + Partitioned, + Precise, + Fuzzy, - Included, Excluded, Partitioned, Precise, Fuzzy, + // Used in a terminal to indicate that an item is craftable + SmallFontCraft, + LargeFontCraft, - // Used in a terminal to indicate that an item is craftable - SmallFontCraft, LargeFontCraft, + // Used in a ME Interface when no appropriate TileEntity was detected near it + Nothing; - // Used in a ME Interface when no appropriate TileEntity was detected near it - Nothing; + private final String root; - private final String root; + GuiText() { + this.root = "gui.appliedenergistics2"; + } - GuiText() - { - this.root = "gui.appliedenergistics2"; - } + GuiText(final String r) { + this.root = r; + } - GuiText( final String r ) - { - this.root = r; - } - - public String getLocal() - { - return StatCollector.translateToLocal( this.getUnlocalized() ); - } - - 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/PlayerMessages.java b/src/main/java/appeng/core/localization/PlayerMessages.java index 412a8e61..930986b5 100644 --- a/src/main/java/appeng/core/localization/PlayerMessages.java +++ b/src/main/java/appeng/core/localization/PlayerMessages.java @@ -18,28 +18,33 @@ package appeng.core.localization; - import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; +public enum PlayerMessages { + ChestCannotReadStorageCell, + InvalidMachine, + LoadedSettings, + SavedSettings, + MachineNotPowered, -public enum PlayerMessages -{ - ChestCannotReadStorageCell, InvalidMachine, LoadedSettings, SavedSettings, MachineNotPowered, + isNowLocked, + isNowUnlocked, + AmmoDepleted, + CommunicationError, + OutOfRange, + DeviceNotPowered, + DeviceNotWirelessTerminal, + DeviceNotLinked, + StationCanNotBeLocated, + SettingCleared, + ; - isNowLocked, isNowUnlocked, - AmmoDepleted, - CommunicationError, OutOfRange, DeviceNotPowered, DeviceNotWirelessTerminal, DeviceNotLinked, StationCanNotBeLocated, - SettingCleared,; - - public IChatComponent get() - { - return new ChatComponentTranslation( this.getName() ); - } - - 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 360fbee2..070bc149 100644 --- a/src/main/java/appeng/core/localization/WailaText.java +++ b/src/main/java/appeng/core/localization/WailaText.java @@ -18,42 +18,42 @@ package appeng.core.localization; - import net.minecraft.util.StatCollector; +public enum WailaText { + Crafting, -public enum WailaText -{ - Crafting, + DeviceOnline, + DeviceOffline, + DeviceMissingChannel, - DeviceOnline, DeviceOffline, DeviceMissingChannel, + P2PUnlinked, + P2PInputOneOutput, + P2PInputManyOutputs, + P2POutput, - P2PUnlinked, P2PInputOneOutput, P2PInputManyOutputs, P2POutput, + Locked, + Unlocked, + Showing, - Locked, Unlocked, Showing, + Contains, + Channels; - Contains, Channels; + private final String root; - private final String root; + WailaText() { + this.root = "waila.appliedenergistics2"; + } - WailaText() - { - this.root = "waila.appliedenergistics2"; - } + WailaText(final String r) { + this.root = r; + } - WailaText( final String r ) - { - this.root = r; - } - - public String getLocal() - { - return StatCollector.translateToLocal( this.getUnlocalized() ); - } - - 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/settings/TickRates.java b/src/main/java/appeng/core/settings/TickRates.java index bc440898..8a577fc4 100644 --- a/src/main/java/appeng/core/settings/TickRates.java +++ b/src/main/java/appeng/core/settings/TickRates.java @@ -18,73 +18,67 @@ package appeng.core.settings; - import appeng.core.AEConfig; +public enum TickRates { + Interface(5, 120), -public enum TickRates -{ + ImportBus(5, 40), - Interface( 5, 120 ), + ExportBus(5, 60), - ImportBus( 5, 40 ), + AnnihilationPlane(2, 120), - ExportBus( 5, 60 ), + METunnel(5, 20), - AnnihilationPlane( 2, 120 ), + Inscriber(1, 1), - METunnel( 5, 20 ), + IOPort(1, 5), - Inscriber( 1, 1 ), + VibrationChamber(10, 40), - IOPort( 1, 5 ), + StorageBus(5, 60), - VibrationChamber( 10, 40 ), + ItemTunnel(5, 60), - StorageBus( 5, 60 ), + LightTunnel(5, 120), - ItemTunnel( 5, 60 ), + OpenComputersTunnel(1, 5), - LightTunnel( 5, 120 ), + PressureTunnel(1, 120); - OpenComputersTunnel( 1, 5 ), + private int min; + private int max; - PressureTunnel( 1, 120 ); + TickRates(final int min, final int max) { + this.setMin(min); + this.setMax(max); + } - private int min; - private int max; + public void Load(final 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." + ); + this.setMin(config.get("TickRates", this.name() + ".min", this.getMin()) + .getInt(this.getMin())); + this.setMax(config.get("TickRates", this.name() + ".max", this.getMax()) + .getInt(this.getMax())); + } - TickRates( final int min, final int max ) - { - this.setMin( min ); - this.setMax( max ); - } + public int getMax() { + return this.max; + } - public void Load( final 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." ); - this.setMin( config.get( "TickRates", this.name() + ".min", this.getMin() ).getInt( this.getMin() ) ); - this.setMax( config.get( "TickRates", this.name() + ".max", this.getMax() ).getInt( this.getMax() ) ); - } + public void setMax(final int max) { + this.max = max; + } - public int getMax() - { - return this.max; - } - - public void setMax( final int max ) - { - this.max = max; - } - - public int getMin() - { - return this.min; - } - - public void setMin( final int min ) - { - this.min = min; - } + public int getMin() { + return this.min; + } + public void setMin(final int min) { + this.min = min; + } } diff --git a/src/main/java/appeng/core/stats/AchievementCraftingHandler.java b/src/main/java/appeng/core/stats/AchievementCraftingHandler.java index 650623e9..684df07e 100644 --- a/src/main/java/appeng/core/stats/AchievementCraftingHandler.java +++ b/src/main/java/appeng/core/stats/AchievementCraftingHandler.java @@ -18,55 +18,50 @@ package appeng.core.stats; - import appeng.util.Platform; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; - /** * handles the achievement when an {@link net.minecraft.item.Item} is crafted by a player. - * The achievement is only added if its a real {@link net.minecraft.entity.player.EntityPlayer}. + * The achievement is only added if its a real {@link + * net.minecraft.entity.player.EntityPlayer}. * * @author thatsIch * @since rv2 */ -public class AchievementCraftingHandler -{ - private final PlayerDifferentiator differentiator; +public class AchievementCraftingHandler { + private final PlayerDifferentiator differentiator; - public AchievementCraftingHandler( final PlayerDifferentiator differentiator ) - { - this.differentiator = differentiator; - } + public AchievementCraftingHandler(final PlayerDifferentiator differentiator) { + this.differentiator = differentiator; + } - @SubscribeEvent - public void onPlayerCraftingEvent( final PlayerEvent.ItemCraftedEvent event ) - { - if( this.differentiator.isNoPlayer( event.player ) || event.crafting == null ) - { - return; - } + @SubscribeEvent + public void onPlayerCraftingEvent(final PlayerEvent.ItemCraftedEvent event) { + if (this.differentiator.isNoPlayer(event.player) || event.crafting == null) { + return; + } - for( final Achievements achievement : Achievements.values() ) - { - switch( achievement.getType() ) - { - case Craft: - if( Platform.isSameItemPrecise( achievement.getStack(), event.crafting ) ) - { - achievement.addToPlayer( event.player ); - return; - } - break; - case CraftItem: - if( achievement.getStack() != null && achievement.getStack().getItem().getClass() == event.crafting.getItem().getClass() ) - { - achievement.addToPlayer( event.player ); - return; - } - default: - } - } - } + for (final Achievements achievement : Achievements.values()) { + switch (achievement.getType()) { + case Craft: + if (Platform.isSameItemPrecise( + achievement.getStack(), event.crafting + )) { + achievement.addToPlayer(event.player); + return; + } + break; + case CraftItem: + if (achievement.getStack() != null + && achievement.getStack().getItem().getClass() + == event.crafting.getItem().getClass()) { + achievement.addToPlayer(event.player); + return; + } + default: + } + } + } } diff --git a/src/main/java/appeng/core/stats/AchievementHierarchy.java b/src/main/java/appeng/core/stats/AchievementHierarchy.java index cb8df680..d99d42d8 100644 --- a/src/main/java/appeng/core/stats/AchievementHierarchy.java +++ b/src/main/java/appeng/core/stats/AchievementHierarchy.java @@ -18,44 +18,41 @@ package appeng.core.stats; - /** * Hierarchy of the AE2 achievements * * @author thatsIch * @since rv2 */ -public class AchievementHierarchy -{ - /** - * Setup hierarchy through assigning parents. - */ - void registerAchievementHierarchy() - { - Achievements.Presses.setParent( Achievements.Compass ); +public class AchievementHierarchy { + /** + * Setup hierarchy through assigning parents. + */ + void registerAchievementHierarchy() { + Achievements.Presses.setParent(Achievements.Compass); - Achievements.Fluix.setParent( Achievements.ChargedQuartz ); + Achievements.Fluix.setParent(Achievements.ChargedQuartz); - Achievements.Charger.setParent( Achievements.Fluix ); + Achievements.Charger.setParent(Achievements.Fluix); - Achievements.CrystalGrowthAccelerator.setParent( Achievements.Charger ); + Achievements.CrystalGrowthAccelerator.setParent(Achievements.Charger); - Achievements.GlassCable.setParent( Achievements.Charger ); + Achievements.GlassCable.setParent(Achievements.Charger); - Achievements.SpatialIOExplorer.setParent( Achievements.SpatialIO ); + Achievements.SpatialIOExplorer.setParent(Achievements.SpatialIO); - Achievements.IOPort.setParent( Achievements.StorageCell ); + Achievements.IOPort.setParent(Achievements.StorageCell); - Achievements.PatternTerminal.setParent( Achievements.CraftingTerminal ); + Achievements.PatternTerminal.setParent(Achievements.CraftingTerminal); - Achievements.Controller.setParent( Achievements.Networking1 ); + Achievements.Controller.setParent(Achievements.Networking1); - Achievements.Networking2.setParent( Achievements.Controller ); + Achievements.Networking2.setParent(Achievements.Controller); - Achievements.Networking3.setParent( Achievements.Networking2 ); + Achievements.Networking3.setParent(Achievements.Networking2); - Achievements.P2P.setParent( Achievements.Controller ); + Achievements.P2P.setParent(Achievements.Controller); - Achievements.Recursive.setParent( Achievements.Controller ); - } + Achievements.Recursive.setParent(Achievements.Controller); + } } diff --git a/src/main/java/appeng/core/stats/AchievementPickupHandler.java b/src/main/java/appeng/core/stats/AchievementPickupHandler.java index 3f60e1c6..aa4c73a0 100644 --- a/src/main/java/appeng/core/stats/AchievementPickupHandler.java +++ b/src/main/java/appeng/core/stats/AchievementPickupHandler.java @@ -18,46 +18,41 @@ package appeng.core.stats; - import appeng.util.Platform; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import net.minecraft.item.ItemStack; - /** - * handles the achievement when an {@link net.minecraft.item.Item} is picked up by a player. - * The achievement is only added if its a real {@link net.minecraft.entity.player.EntityPlayer}. + * handles the achievement when an {@link net.minecraft.item.Item} is picked up by a + * player. The achievement is only added if its a real {@link + * net.minecraft.entity.player.EntityPlayer}. * * @author thatsIch * @since rv2 */ -public class AchievementPickupHandler -{ - private final PlayerDifferentiator differentiator; +public class AchievementPickupHandler { + private final PlayerDifferentiator differentiator; - public AchievementPickupHandler( final PlayerDifferentiator differentiator ) - { - this.differentiator = differentiator; - } + public AchievementPickupHandler(final PlayerDifferentiator differentiator) { + this.differentiator = differentiator; + } - @SubscribeEvent - public void onItemPickUp( final PlayerEvent.ItemPickupEvent event ) - { - if( this.differentiator.isNoPlayer( event.player ) || event.pickedUp == null || event.pickedUp.getEntityItem() == null ) - { - return; - } + @SubscribeEvent + public void onItemPickUp(final PlayerEvent.ItemPickupEvent event) { + if (this.differentiator.isNoPlayer(event.player) || event.pickedUp == null + || event.pickedUp.getEntityItem() == null) { + return; + } - final ItemStack is = event.pickedUp.getEntityItem(); + final ItemStack is = event.pickedUp.getEntityItem(); - for( final Achievements achievement : Achievements.values() ) - { - if( achievement.getType() == AchievementType.Pickup && Platform.isSameItemPrecise( achievement.getStack(), is ) ) - { - achievement.addToPlayer( event.player ); - return; - } - } - } + for (final Achievements achievement : Achievements.values()) { + if (achievement.getType() == AchievementType.Pickup + && Platform.isSameItemPrecise(achievement.getStack(), 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 2e90ba9c..a4617cbf 100644 --- a/src/main/java/appeng/core/stats/AchievementType.java +++ b/src/main/java/appeng/core/stats/AchievementType.java @@ -18,10 +18,11 @@ package appeng.core.stats; +public enum AchievementType { -public enum AchievementType -{ - - Craft, CraftItem, Pickup, Custom + Craft, + CraftItem, + Pickup, + Custom } diff --git a/src/main/java/appeng/core/stats/Achievements.java b/src/main/java/appeng/core/stats/Achievements.java index 9d117599..e8ebf9e6 100644 --- a/src/main/java/appeng/core/stats/Achievements.java +++ b/src/main/java/appeng/core/stats/Achievements.java @@ -18,7 +18,6 @@ package appeng.core.stats; - import appeng.api.AEApi; import appeng.api.definitions.IItemDefinition; import appeng.api.util.AEColor; @@ -27,145 +26,235 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.stats.Achievement; +public enum Achievements { + // done + Compass( + -2, + -4, + AEApi.instance().definitions().blocks().skyCompass(), + AchievementType.Craft + ), -public enum Achievements -{ - // done - Compass( -2, -4, AEApi.instance().definitions().blocks().skyCompass(), AchievementType.Craft ), + // done + Presses( + -2, + -2, + AEApi.instance().definitions().materials().logicProcessorPress(), + AchievementType.Custom + ), - // done - Presses( -2, -2, AEApi.instance().definitions().materials().logicProcessorPress(), AchievementType.Custom ), + // done + SpatialIO( + -4, + -4, + AEApi.instance().definitions().blocks().spatialIOPort(), + AchievementType.Craft + ), - // done - SpatialIO( -4, -4, AEApi.instance().definitions().blocks().spatialIOPort(), AchievementType.Craft ), + // done + SpatialIOExplorer( + -4, + -2, + AEApi.instance().definitions().items().spatialCell128(), + AchievementType.Custom + ), - // done - SpatialIOExplorer( -4, -2, AEApi.instance().definitions().items().spatialCell128(), AchievementType.Custom ), + // done + StorageCell( + -6, + -4, + AEApi.instance().definitions().items().cell64k(), + AchievementType.CraftItem + ), - // done - StorageCell( -6, -4, AEApi.instance().definitions().items().cell64k(), AchievementType.CraftItem ), + // done + IOPort( + -6, -2, AEApi.instance().definitions().blocks().iOPort(), AchievementType.Craft + ), - // done - IOPort( -6, -2, AEApi.instance().definitions().blocks().iOPort(), AchievementType.Craft ), + // done + CraftingTerminal( + -8, + -4, + AEApi.instance().definitions().parts().craftingTerminal(), + AchievementType.Craft + ), - // done - CraftingTerminal( -8, -4, AEApi.instance().definitions().parts().craftingTerminal(), AchievementType.Craft ), + // done + PatternTerminal( + -8, + -2, + AEApi.instance().definitions().parts().patternTerminal(), + AchievementType.Craft + ), - // done - PatternTerminal( -8, -2, AEApi.instance().definitions().parts().patternTerminal(), AchievementType.Craft ), + // done + ChargedQuartz( + 0, + -4, + AEApi.instance().definitions().materials().certusQuartzCrystalCharged(), + AchievementType.Pickup + ), - // done - ChargedQuartz( 0, -4, AEApi.instance().definitions().materials().certusQuartzCrystalCharged(), AchievementType.Pickup ), + // done + Fluix( + 0, + -2, + AEApi.instance().definitions().materials().fluixCrystal(), + AchievementType.Pickup + ), - // done - Fluix( 0, -2, AEApi.instance().definitions().materials().fluixCrystal(), AchievementType.Pickup ), + // done + Charger( + 0, 0, AEApi.instance().definitions().blocks().charger(), AchievementType.Craft + ), - // done - Charger( 0, 0, AEApi.instance().definitions().blocks().charger(), AchievementType.Craft ), + // done + CrystalGrowthAccelerator( + -2, + 0, + AEApi.instance().definitions().blocks().quartzGrowthAccelerator(), + AchievementType.Craft + ), - // done - CrystalGrowthAccelerator( -2, 0, AEApi.instance().definitions().blocks().quartzGrowthAccelerator(), AchievementType.Craft ), + // done + GlassCable( + 2, 0, AEApi.instance().definitions().parts().cableGlass(), AchievementType.Craft + ), - // done - GlassCable( 2, 0, AEApi.instance().definitions().parts().cableGlass(), AchievementType.Craft ), + // done + Networking1( + 4, + -6, + AEApi.instance().definitions().parts().cableCovered(), + AchievementType.Custom + ), - // done - Networking1( 4, -6, AEApi.instance().definitions().parts().cableCovered(), AchievementType.Custom ), + // done + Controller( + 4, -4, AEApi.instance().definitions().blocks().controller(), AchievementType.Craft + ), - // done - Controller( 4, -4, AEApi.instance().definitions().blocks().controller(), AchievementType.Craft ), + // done + Networking2( + 4, 0, AEApi.instance().definitions().parts().cableSmart(), AchievementType.Custom + ), - // done - Networking2( 4, 0, AEApi.instance().definitions().parts().cableSmart(), AchievementType.Custom ), + // done + Networking3( + 4, 2, AEApi.instance().definitions().parts().cableDense(), AchievementType.Custom + ), - // done - Networking3( 4, 2, AEApi.instance().definitions().parts().cableDense(), AchievementType.Custom ), + // done + P2P(2, -2, AEApi.instance().definitions().parts().p2PTunnelME(), AchievementType.Craft + ), - // done - P2P( 2, -2, AEApi.instance().definitions().parts().p2PTunnelME(), AchievementType.Craft ), + // done + Recursive( + 6, -2, AEApi.instance().definitions().blocks().iface(), AchievementType.Craft + ), - // done - Recursive( 6, -2, AEApi.instance().definitions().blocks().iface(), AchievementType.Craft ), + // done + CraftingCPU( + 6, + 0, + AEApi.instance().definitions().blocks().craftingStorage64k(), + AchievementType.CraftItem + ), - // done - CraftingCPU( 6, 0, AEApi.instance().definitions().blocks().craftingStorage64k(), AchievementType.CraftItem ), + // done + Facade( + 6, 2, AEApi.instance().definitions().items().facade(), AchievementType.CraftItem + ), - // done - Facade( 6, 2, AEApi.instance().definitions().items().facade(), AchievementType.CraftItem ), + // done + NetworkTool( + 8, 0, AEApi.instance().definitions().items().networkTool(), AchievementType.Craft + ), - // done - NetworkTool( 8, 0, AEApi.instance().definitions().items().networkTool(), AchievementType.Craft ), + // done + PortableCell( + 8, 2, AEApi.instance().definitions().items().portableCell(), AchievementType.Craft + ), - // done - PortableCell( 8, 2, AEApi.instance().definitions().items().portableCell(), AchievementType.Craft ), + // done + StorageBus( + 10, 0, AEApi.instance().definitions().parts().storageBus(), AchievementType.Craft + ), - // done - StorageBus( 10, 0, AEApi.instance().definitions().parts().storageBus(), AchievementType.Craft ), + // done + QNB(10, + 2, + AEApi.instance().definitions().blocks().quantumLink(), + AchievementType.Craft); - // done - QNB( 10, 2, AEApi.instance().definitions().blocks().quantumLink(), AchievementType.Craft ); + private final ItemStack stack; + private final AchievementType type; + private final int x; + private final int y; - private final ItemStack stack; - private final AchievementType type; - private final int x; - private final int y; + private Achievement parent; + private Achievement stat; - private Achievement parent; - private Achievement stat; + Achievements( + final int x, + final int y, + final AEColoredItemDefinition which, + final AchievementType type + ) { + this.stack = (which != null) ? which.stack(AEColor.Transparent, 1) : null; + this.type = type; + this.x = x; + this.y = y; + } - Achievements( final int x, final int y, final AEColoredItemDefinition which, final AchievementType type ) - { - this.stack = ( which != null ) ? which.stack( AEColor.Transparent, 1 ) : null; - this.type = type; - this.x = x; - this.y = y; - } + Achievements( + final int x, final int y, final IItemDefinition which, final AchievementType type + ) { + this.stack = which.maybeStack(1).orNull(); + this.type = type; + this.x = x; + this.y = y; + } - Achievements( final int x, final int y, final IItemDefinition which, final AchievementType type ) - { - this.stack = which.maybeStack( 1 ).orNull(); - this.type = type; - this.x = x; - this.y = y; - } + Achievements( + final int x, final int y, final ItemStack which, final AchievementType type + ) { + this.stack = which; + this.type = type; + this.x = x; + this.y = y; + } - Achievements( final int x, final int y, final ItemStack which, final AchievementType type ) - { - this.stack = which; - this.type = type; - this.x = x; - this.y = y; - } + void setParent(final Achievements parent) { + this.parent = parent.getAchievement(); + } - void setParent( final Achievements parent ) - { - this.parent = parent.getAchievement(); - } + public Achievement getAchievement() { + if (this.stat == null && this.getStack() != null) { + this.stat = new Achievement( + "achievement.ae2." + this.name(), + "ae2." + this.name(), + this.x, + this.y, + this.getStack(), + this.parent + ); + this.stat.registerStat(); + } - public Achievement getAchievement() - { - if( this.stat == null && this.getStack() != null ) - { - this.stat = new Achievement( "achievement.ae2." + this.name(), "ae2." + this.name(), this.x, this.y, this.getStack(), this.parent ); - this.stat.registerStat(); - } + return this.stat; + } - return this.stat; - } + public void addToPlayer(final EntityPlayer player) { + player.addStat(this.getAchievement(), 1); + } - public void addToPlayer( final EntityPlayer player ) - { - player.addStat( this.getAchievement(), 1 ); - } - - AchievementType getType() - { - return this.type; - } - - ItemStack getStack() - { - return this.stack; - } + AchievementType getType() { + return this.type; + } + ItemStack getStack() { + return this.stack; + } } diff --git a/src/main/java/appeng/core/stats/PlayerDifferentiator.java b/src/main/java/appeng/core/stats/PlayerDifferentiator.java index 75d18bf6..693f5be2 100644 --- a/src/main/java/appeng/core/stats/PlayerDifferentiator.java +++ b/src/main/java/appeng/core/stats/PlayerDifferentiator.java @@ -18,31 +18,28 @@ package appeng.core.stats; - import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.util.FakePlayer; - /** - * Can differentiate if a {@link net.minecraft.entity.player.EntityPlayer} is a real player or not + * Can differentiate if a {@link net.minecraft.entity.player.EntityPlayer} is a real + * player or not * * @author thatsIch * @since rv2 */ -public class PlayerDifferentiator -{ - /** - * Can determine if an {@link net.minecraft.entity.player.EntityPlayer} is not a real player. - * This is based on if the {@param player} is: - * - null - * - dead - * - fake - * - * @param player to be checked player - * @return true if {@param player} is not a real player - */ - boolean isNoPlayer( final EntityPlayer player ) - { - return player == null || player.isDead || player instanceof FakePlayer; - } +public class PlayerDifferentiator { + /** + * Can determine if an {@link net.minecraft.entity.player.EntityPlayer} is not a real + * player. This is based on if the {@param player} is: + * - null + * - dead + * - fake + * + * @param player to be checked player + * @return true if {@param player} is not a real player + */ + boolean isNoPlayer(final EntityPlayer player) { + return player == null || player.isDead || player instanceof FakePlayer; + } } diff --git a/src/main/java/appeng/core/stats/PlayerStatsRegistration.java b/src/main/java/appeng/core/stats/PlayerStatsRegistration.java index eccedaa0..e0b27ae5 100644 --- a/src/main/java/appeng/core/stats/PlayerStatsRegistration.java +++ b/src/main/java/appeng/core/stats/PlayerStatsRegistration.java @@ -18,6 +18,7 @@ package appeng.core.stats; +import java.util.ArrayList; import appeng.core.AEConfig; import appeng.core.features.AEFeature; @@ -25,90 +26,86 @@ import cpw.mods.fml.common.eventhandler.EventBus; import net.minecraft.stats.Achievement; import net.minecraftforge.common.AchievementPage; -import java.util.ArrayList; - - /** * Registers any items a player is picking up or is crafting. * Registered items are added to the player stats. * This will only happen if the {@link AEFeature#Achievements} feature is enabled. */ -public class PlayerStatsRegistration -{ - /** - * {@link cpw.mods.fml.common.eventhandler.EventBus} to which the handlers might get posted to depending if the - * feature is enabled - */ - private final EventBus bus; +public class PlayerStatsRegistration { + /** + * {@link cpw.mods.fml.common.eventhandler.EventBus} to which the handlers might get + * posted to depending if the feature is enabled + */ + private final EventBus bus; - /** - * is true if the {@link appeng.core.features.AEFeature#Achievements} is enabled in the - */ - private final boolean isAchievementFeatureEnabled; + /** + * is true if the {@link appeng.core.features.AEFeature#Achievements} is enabled in + * the + */ + private final boolean isAchievementFeatureEnabled; - /** - * Constructs this with an {@link cpw.mods.fml.common.eventhandler.EventBus} and {@link appeng.core.AEConfig}. - * - * @param bus {@see #bus} - * @param config {@link appeng.core.AEConfig} which is used to determine if the - * {@link appeng.core.features.AEFeature#Achievements} is enabled - */ - public PlayerStatsRegistration( final EventBus bus, final AEConfig config ) - { - this.bus = bus; - this.isAchievementFeatureEnabled = config.isFeatureEnabled( AEFeature.Achievements ); - } + /** + * Constructs this with an {@link cpw.mods.fml.common.eventhandler.EventBus} and + * {@link appeng.core.AEConfig}. + * + * @param bus {@see #bus} + * @param config {@link appeng.core.AEConfig} which is used to determine if the + * {@link appeng.core.features.AEFeature#Achievements} is enabled + */ + public PlayerStatsRegistration(final EventBus bus, final AEConfig config) { + this.bus = bus; + this.isAchievementFeatureEnabled + = config.isFeatureEnabled(AEFeature.Achievements); + } - /** - * Registers the {@link appeng.core.stats.AchievementCraftingHandler} and - * {@link appeng.core.stats.AchievementPickupHandler} to the {@link #bus} if {@link #isAchievementFeatureEnabled} is - * true. - */ - public void registerAchievementHandlers() - { - if( this.isAchievementFeatureEnabled ) - { - final PlayerDifferentiator differentiator = new PlayerDifferentiator(); - final AchievementCraftingHandler craftingHandler = new AchievementCraftingHandler( differentiator ); - final AchievementPickupHandler pickupHandler = new AchievementPickupHandler( differentiator ); + /** + * Registers the {@link appeng.core.stats.AchievementCraftingHandler} and + * {@link appeng.core.stats.AchievementPickupHandler} to the {@link #bus} if {@link + * #isAchievementFeatureEnabled} is true. + */ + public void registerAchievementHandlers() { + if (this.isAchievementFeatureEnabled) { + final PlayerDifferentiator differentiator = new PlayerDifferentiator(); + final AchievementCraftingHandler craftingHandler + = new AchievementCraftingHandler(differentiator); + final AchievementPickupHandler pickupHandler + = new AchievementPickupHandler(differentiator); - this.bus.register( craftingHandler ); - this.bus.register( pickupHandler ); - } - } + this.bus.register(craftingHandler); + this.bus.register(pickupHandler); + } + } - /** - * Registers the {@link appeng.core.stats.AchievementHierarchy} and adds all {@link appeng.core.stats.Achievements} - * to a new {@link net.minecraftforge.common.AchievementPage}. - */ - public void registerAchievements() - { - if( this.isAchievementFeatureEnabled ) - { - final AchievementHierarchy hierarchy = new AchievementHierarchy(); - hierarchy.registerAchievementHierarchy(); + /** + * Registers the {@link appeng.core.stats.AchievementHierarchy} and adds all {@link + * appeng.core.stats.Achievements} to a new {@link + * net.minecraftforge.common.AchievementPage}. + */ + public void registerAchievements() { + if (this.isAchievementFeatureEnabled) { + final AchievementHierarchy hierarchy = new AchievementHierarchy(); + hierarchy.registerAchievementHierarchy(); - for( final Stats s : Stats.values() ) - { - s.getStat(); - } + for (final Stats s : Stats.values()) { + s.getStat(); + } - /** - * register - */ - final ArrayList list = new ArrayList(); + /** + * register + */ + final ArrayList list = new ArrayList(); - for( final Achievements a : Achievements.values() ) - { - final Achievement ach = a.getAchievement(); - if( ach != null ) - { - list.add( ach ); - } - } + for (final Achievements a : Achievements.values()) { + final Achievement ach = a.getAchievement(); + if (ach != null) { + list.add(ach); + } + } - final AchievementPage ae2AchievementPage = new AchievementPage( "Applied Energistics 2", list.toArray( new Achievement[list.size()] ) ); - AchievementPage.registerAchievementPage( ae2AchievementPage ); - } - } + final AchievementPage ae2AchievementPage = new AchievementPage( + "Applied Energistics 2", list.toArray(new Achievement[list.size()]) + ); + AchievementPage.registerAchievementPage(ae2AchievementPage); + } + } } diff --git a/src/main/java/appeng/core/stats/Stats.java b/src/main/java/appeng/core/stats/Stats.java index a3fd1546..f6303520 100644 --- a/src/main/java/appeng/core/stats/Stats.java +++ b/src/main/java/appeng/core/stats/Stats.java @@ -18,44 +18,37 @@ package appeng.core.stats; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.StatBasic; import net.minecraft.util.ChatComponentTranslation; +public enum Stats { + // done + ItemsInserted, -public enum Stats -{ + // done + ItemsExtracted, - // done - ItemsInserted, + // done + TurnedCranks; - // done - ItemsExtracted, + private StatBasic stat; - // done - TurnedCranks; + Stats() {} - private StatBasic stat; + public void addToPlayer(final EntityPlayer player, final int howMany) { + player.addStat(this.getStat(), howMany); + } - Stats() - { - } - - public void addToPlayer( final EntityPlayer player, final int howMany ) - { - player.addStat( this.getStat(), howMany ); - } - - StatBasic getStat() - { - if( this.stat == null ) - { - this.stat = new StatBasic( "stat.ae2." + this.name(), new ChatComponentTranslation( "stat.ae2." + this.name() ) ); - this.stat.registerStat(); - } - - return this.stat; - } + StatBasic getStat() { + if (this.stat == null) { + this.stat = new StatBasic( + "stat.ae2." + this.name(), + new ChatComponentTranslation("stat.ae2." + this.name()) + ); + this.stat.registerStat(); + } + return this.stat; + } } diff --git a/src/main/java/appeng/core/sync/AppEngPacket.java b/src/main/java/appeng/core/sync/AppEngPacket.java index 98d80941..efbf0a62 100644 --- a/src/main/java/appeng/core/sync/AppEngPacket.java +++ b/src/main/java/appeng/core/sync/AppEngPacket.java @@ -18,7 +18,6 @@ package appeng.core.sync; - import appeng.core.AEConfig; import appeng.core.AELog; import appeng.core.features.AEFeature; @@ -28,48 +27,52 @@ import cpw.mods.fml.common.network.internal.FMLProxyPacket; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; +public abstract class AppEngPacket { + private AppEngPacketHandlerBase.PacketTypes id; + private ByteBuf p; -public abstract class AppEngPacket -{ + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + throw new UnsupportedOperationException( + "This packet ( " + this.getPacketID() + + " does not implement a server side handler." + ); + } - private AppEngPacketHandlerBase.PacketTypes id; - private ByteBuf p; + public final int getPacketID() { + return AppEngPacketHandlerBase.PacketTypes.getID(this.getClass()).ordinal(); + } - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - throw new UnsupportedOperationException( "This packet ( " + this.getPacketID() + " does not implement a server side handler." ); - } + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + throw new UnsupportedOperationException( + "This packet ( " + this.getPacketID() + + " does not implement a client side handler." + ); + } - public final int getPacketID() - { - return AppEngPacketHandlerBase.PacketTypes.getID( this.getClass() ).ordinal(); - } + protected void configureWrite(final ByteBuf data) { + data.capacity(data.readableBytes()); + this.p = data; + } - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - throw new UnsupportedOperationException( "This packet ( " + this.getPacketID() + " does not implement a client side handler." ); - } + public FMLProxyPacket getProxy() { + 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!" + ); + } - protected void configureWrite( final ByteBuf data ) - { - data.capacity( data.readableBytes() ); - this.p = data; - } + final FMLProxyPacket pp + = new FMLProxyPacket(this.p, NetworkHandler.instance.getChannel()); - public FMLProxyPacket getProxy() - { - 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!" ); - } + if (AEConfig.instance.isFeatureEnabled(AEFeature.PacketLogging)) { + AELog.info(this.getClass().getName() + " : " + pp.payload().readableBytes()); + } - final FMLProxyPacket pp = new FMLProxyPacket( this.p, NetworkHandler.instance.getChannel() ); - - if( AEConfig.instance.isFeatureEnabled( AEFeature.PacketLogging ) ) - { - AELog.info( this.getClass().getName() + " : " + pp.payload().readableBytes() ); - } - - return pp; - } + return pp; + } } diff --git a/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java b/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java index 3757cbf8..a35d0f2d 100644 --- a/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java +++ b/src/main/java/appeng/core/sync/AppEngPacketHandlerBase.java @@ -18,113 +18,103 @@ package appeng.core.sync; - -import appeng.core.sync.packets.*; -import io.netty.buffer.ByteBuf; - import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; +import appeng.core.sync.packets.*; +import io.netty.buffer.ByteBuf; -public class AppEngPacketHandlerBase -{ - private static final Map, PacketTypes> REVERSE_LOOKUP = new HashMap, AppEngPacketHandlerBase.PacketTypes>(); +public class AppEngPacketHandlerBase { + private static final Map, PacketTypes> REVERSE_LOOKUP + = new HashMap, AppEngPacketHandlerBase.PacketTypes>( + ); + public enum PacketTypes { + PACKET_COMPASS_REQUEST(PacketCompassRequest.class), - public enum PacketTypes - { - PACKET_COMPASS_REQUEST( PacketCompassRequest.class ), + PACKET_COMPASS_RESPONSE(PacketCompassResponse.class), - PACKET_COMPASS_RESPONSE( PacketCompassResponse.class ), + PACKET_INVENTORY_ACTION(PacketInventoryAction.class), - PACKET_INVENTORY_ACTION( PacketInventoryAction.class ), + PACKET_ME_INVENTORY_UPDATE(PacketMEInventoryUpdate.class), - PACKET_ME_INVENTORY_UPDATE( PacketMEInventoryUpdate.class ), + PACKET_CONFIG_BUTTON(PacketConfigButton.class), - PACKET_CONFIG_BUTTON( PacketConfigButton.class ), + PACKET_MULTIPART(PacketMultiPart.class), - PACKET_MULTIPART( PacketMultiPart.class ), + PACKET_PART_PLACEMENT(PacketPartPlacement.class), - PACKET_PART_PLACEMENT( PacketPartPlacement.class ), + PACKET_LIGHTNING(PacketLightning.class), - PACKET_LIGHTNING( PacketLightning.class ), + PACKET_MATTER_CANNON(PacketMatterCannon.class), - PACKET_MATTER_CANNON( PacketMatterCannon.class ), + PACKET_MOCK_EXPLOSION(PacketMockExplosion.class), - PACKET_MOCK_EXPLOSION( PacketMockExplosion.class ), + PACKET_VALUE_CONFIG(PacketValueConfig.class), - PACKET_VALUE_CONFIG( PacketValueConfig.class ), + PACKET_TRANSITION_EFFECT(PacketTransitionEffect.class), - PACKET_TRANSITION_EFFECT( PacketTransitionEffect.class ), + PACKET_PROGRESS_VALUE(PacketProgressBar.class), - PACKET_PROGRESS_VALUE( PacketProgressBar.class ), + PACKET_CLICK(PacketClick.class), - PACKET_CLICK( PacketClick.class ), + PACKET_NEW_STORAGE_DIMENSION(PacketNewStorageDimension.class), - PACKET_NEW_STORAGE_DIMENSION( PacketNewStorageDimension.class ), + PACKET_SWITCH_GUIS(PacketSwitchGuis.class), - PACKET_SWITCH_GUIS( PacketSwitchGuis.class ), + PACKET_SWAP_SLOTS(PacketSwapSlots.class), - PACKET_SWAP_SLOTS( PacketSwapSlots.class ), + PACKET_PATTERN_SLOT(PacketPatternSlot.class), - PACKET_PATTERN_SLOT( PacketPatternSlot.class ), + PACKET_RECIPE_NEI(PacketNEIRecipe.class), - PACKET_RECIPE_NEI( PacketNEIRecipe.class ), + PACKET_PARTIAL_ITEM(PacketPartialItem.class), - PACKET_PARTIAL_ITEM( PacketPartialItem.class ), + PACKET_CRAFTING_REQUEST(PacketCraftRequest.class), - PACKET_CRAFTING_REQUEST( PacketCraftRequest.class ), + PACKET_ASSEMBLER_ANIMATION(PacketAssemblerAnimation.class), - PACKET_ASSEMBLER_ANIMATION( PacketAssemblerAnimation.class ), + PACKET_COMPRESSED_NBT(PacketCompressedNBT.class), - PACKET_COMPRESSED_NBT( PacketCompressedNBT.class ), + PACKET_PAINTED_ENTITY(PacketPaintedEntity.class); - PACKET_PAINTED_ENTITY( PacketPaintedEntity.class ); + private final Class packetClass; + private final Constructor packetConstructor; - private final Class packetClass; - private final Constructor packetConstructor; + PacketTypes(final Class c) { + this.packetClass = c; - PacketTypes( final Class c ) - { - this.packetClass = c; + Constructor x = null; + try { + x = this.packetClass.getConstructor(ByteBuf.class); + } catch (final NoSuchMethodException ignored) { + } catch (final SecurityException ignored) {} - Constructor x = null; - try - { - x = this.packetClass.getConstructor( ByteBuf.class ); - } - catch( final NoSuchMethodException ignored ) - { - } - catch( final SecurityException ignored ) - { - } + this.packetConstructor = x; + REVERSE_LOOKUP.put(this.packetClass, this); - this.packetConstructor = x; - REVERSE_LOOKUP.put( this.packetClass, this ); + if (this.packetConstructor == null) { + throw new IllegalStateException( + "Invalid Packet Class " + c + + ", must be constructable on DataInputStream" + ); + } + } - if( this.packetConstructor == null ) - { - throw new IllegalStateException( "Invalid Packet Class " + c + ", must be constructable on DataInputStream" ); - } - } + public static PacketTypes getPacket(final int id) { + return (values())[id]; + } - public static PacketTypes getPacket( final int id ) - { - return ( values() )[id]; - } + static PacketTypes getID(final Class c) { + return REVERSE_LOOKUP.get(c); + } - static PacketTypes getID( final Class c ) - { - return REVERSE_LOOKUP.get( c ); - } - - public AppEngPacket parsePacket( final ByteBuf in ) - throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException - { - return this.packetConstructor.newInstance( in ); - } - } + public AppEngPacket parsePacket(final ByteBuf in) + throws InstantiationException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException { + return this.packetConstructor.newInstance(in); + } + } } diff --git a/src/main/java/appeng/core/sync/GuiBridge.java b/src/main/java/appeng/core/sync/GuiBridge.java index 1508261a..b1cdd088 100644 --- a/src/main/java/appeng/core/sync/GuiBridge.java +++ b/src/main/java/appeng/core/sync/GuiBridge.java @@ -18,6 +18,8 @@ package appeng.core.sync; +import java.lang.reflect.Constructor; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; @@ -78,468 +80,595 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.lang.reflect.Constructor; -import java.util.List; - - -public enum GuiBridge implements IGuiHandler -{ - GUI_Handler(), - - GUI_GRINDER( ContainerGrinder.class, TileGrinder.class, GuiHostType.WORLD, null ), - - GUI_QNB( ContainerQNB.class, TileQuantumBridge.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_SKYCHEST( ContainerSkyChest.class, TileSkyChest.class, GuiHostType.WORLD, null ), - - GUI_CHEST( ContainerChest.class, TileChest.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_WIRELESS( ContainerWireless.class, TileWireless.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_ME( ContainerMEMonitorable.class, ITerminalHost.class, GuiHostType.WORLD, null ), - - GUI_PORTABLE_CELL( ContainerMEPortableCell.class, IPortableCell.class, GuiHostType.ITEM, null ), - - GUI_WIRELESS_TERM( ContainerWirelessTerm.class, WirelessTerminalGuiObject.class, GuiHostType.ITEM, null ), - - GUI_NETWORK_STATUS( ContainerNetworkStatus.class, INetworkTool.class, GuiHostType.ITEM, null ), - - GUI_NETWORK_STATUS_BLOCK( ContainerNetworkStatus.class, TileLegacyController.class, GuiHostType.WORLD, null ), - - GUI_CRAFTING_CPU( ContainerCraftingCPU.class, TileCraftingTile.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), - - GUI_NETWORK_TOOL( ContainerNetworkTool.class, INetworkTool.class, GuiHostType.ITEM, null ), - - GUI_QUARTZ_KNIFE( ContainerQuartzKnife.class, QuartzKnifeObj.class, GuiHostType.ITEM, null ), - - GUI_DRIVE( ContainerDrive.class, TileDrive.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_VIBRATION_CHAMBER( ContainerVibrationChamber.class, TileVibrationChamber.class, GuiHostType.WORLD, null ), - - GUI_CONDENSER( ContainerCondenser.class, TileCondenser.class, GuiHostType.WORLD, null ), - - GUI_INTERFACE( ContainerInterface.class, IInterfaceHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_BUS( ContainerUpgradeable.class, IUpgradeableHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_IOPORT( ContainerIOPort.class, TileIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_STORAGEBUS( ContainerStorageBus.class, PartStorageBus.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_FORMATION_PLANE( ContainerFormationPlane.class, PartFormationPlane.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_PRIORITY( ContainerPriority.class, IPriorityHost.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_SECURITY( ContainerSecurity.class, TileSecurity.class, GuiHostType.WORLD, SecurityPermissions.SECURITY ), - - GUI_CRAFTING_TERMINAL( ContainerCraftingTerm.class, ICraftingTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), - - GUI_PATTERN_TERMINAL( ContainerPatternTerm.class, PartPatternTerminal.class, GuiHostType.WORLD, SecurityPermissions.CRAFT ), - - // extends (Container/Gui) + Bus - GUI_LEVEL_EMITTER( ContainerLevelEmitter.class, PartLevelEmitter.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_SPATIAL_IO_PORT( ContainerSpatialIOPort.class, TileSpatialIOPort.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_INSCRIBER( ContainerInscriber.class, TileInscriber.class, GuiHostType.WORLD, null ), - - GUI_CELL_WORKBENCH( ContainerCellWorkbench.class, TileCellWorkbench.class, GuiHostType.WORLD, null ), - - GUI_MAC( ContainerMAC.class, TileMolecularAssembler.class, GuiHostType.WORLD, null ), - - GUI_CRAFTING_AMOUNT( ContainerCraftAmount.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), - - GUI_CRAFTING_CONFIRM( ContainerCraftConfirm.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ), - - GUI_INTERFACE_TERMINAL( ContainerInterfaceTerminal.class, PartInterfaceTerminal.class, GuiHostType.WORLD, SecurityPermissions.BUILD ), - - GUI_CRAFTING_STATUS( ContainerCraftingStatus.class, ITerminalHost.class, GuiHostType.ITEM_OR_WORLD, SecurityPermissions.CRAFT ); - - private final Class tileClass; - private final Class containerClass; - private Class guiClass; - private GuiHostType type; - private SecurityPermissions requiredPermission; - - GuiBridge() - { - this.tileClass = null; - this.guiClass = null; - this.containerClass = null; - } - - GuiBridge( final Class containerClass, final SecurityPermissions requiredPermission ) - { - this.requiredPermission = requiredPermission; - this.containerClass = containerClass; - this.tileClass = 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() ) - { - final String start = this.containerClass.getName(); - final String guiClass = start.replaceFirst( "container.", "client.gui." ).replace( ".Container", ".Gui" ); - - if( start.equals( guiClass ) ) - { - throw new IllegalStateException( "Unable to find gui class" ); - } - this.guiClass = ReflectionHelper.getClass( this.getClass().getClassLoader(), guiClass ); - if( this.guiClass == null ) - { - throw new IllegalStateException( "Cannot Load class: " + guiClass ); - } - } - } - - GuiBridge( final Class containerClass, final Class tileClass, final GuiHostType type, final SecurityPermissions requiredPermission ) - { - this.requiredPermission = requiredPermission; - this.containerClass = containerClass; - this.type = type; - this.tileClass = tileClass; - this.getGui(); - } - - @Override - public Object getServerGuiElement( final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - final ForgeDirection side = ForgeDirection.getOrientation( ordinal & 0x07 ); - final GuiBridge ID = values()[ordinal >> 4]; - final boolean stem = ( ( ordinal >> 3 ) & 1 ) == 1; - if( ID.type.isItem() ) - { - ItemStack it = null; - if( stem ) - { - it = player.inventory.getCurrentItem(); - } - else if( x >= 0 && x < player.inventory.mainInventory.length ) - { - it = player.inventory.getStackInSlot( x ); - } - final 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() ) - { - final TileEntity TE = w.getTileEntity( x, y, z ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final 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( final ItemStack it, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - if( it != null ) - { - if( it.getItem() instanceof IGuiItem ) - { - return ( (IGuiItem) it.getItem() ).getGuiObject( it, w, x, y, z ); - } - - final 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( final Object tE ) - { - if( this.tileClass == null ) - { - throw new IllegalArgumentException( "This Gui Cannot use the standard Handler." ); - } - - return this.tileClass.isInstance( tE ); - } - - private Object updateGui( final Object newContainer, final World w, final int x, final int y, final int z, final ForgeDirection side, final Object myItem ) - { - if( newContainer instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) newContainer; - bc.setOpenContext( new ContainerOpenContext( myItem ) ); - bc.getOpenContext().setWorld( w ); - bc.getOpenContext().setX( x ); - bc.getOpenContext().setY( y ); - bc.getOpenContext().setZ( z ); - bc.getOpenContext().setSide( side ); - } - - return newContainer; - } - - public Object ConstructContainer( final InventoryPlayer inventory, final ForgeDirection side, final Object tE ) - { - try - { - final Constructor[] c = this.containerClass.getConstructors(); - if( c.length == 0 ) - { - throw new AppEngException( "Invalid Gui Class" ); - } - - final Constructor target = this.findConstructor( c, inventory, tE ); - - if( target == null ) - { - throw new IllegalStateException( "Cannot find " + this.containerClass.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); - } - - final Object o = target.newInstance( inventory, tE ); - - /** - * triggers achievement when the player sees presses. - */ - if( o instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) o; - for( final Object so : bc.inventorySlots ) - { - if( so instanceof Slot ) - { - final ItemStack is = ( (Slot) so ).getStack(); - - final IMaterials materials = AEApi.instance().definitions().materials(); - this.addPressAchievementToPlayer( is, materials, inventory.player ); - } - } - } - - return o; - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } - - private Constructor findConstructor( final Constructor[] c, final InventoryPlayer inventory, final Object tE ) - { - for( final Constructor con : c ) - { - final Class[] types = con.getParameterTypes(); - if( types.length == 2 ) - { - if( types[0].isAssignableFrom( inventory.getClass() ) && types[1].isAssignableFrom( tE.getClass() ) ) - { - return con; - } - } - } - return null; - } - - private String typeName( final Object inventory ) - { - if( inventory == null ) - { - return "NULL"; - } - - return inventory.getClass().getName(); - } - - private void addPressAchievementToPlayer( final ItemStack newItem, final IMaterials possibleMaterials, final 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( final IComparableDefinition press : presses ) - { - if( press.isSameAs( newItem ) ) - { - Achievements.Presses.addToPlayer( player ); - - return; - } - } - } - - @Override - public Object getClientGuiElement( final int ordinal, final EntityPlayer player, final World w, final int x, final int y, final int z ) - { - final ForgeDirection side = ForgeDirection.getOrientation( ordinal & 0x07 ); - final GuiBridge ID = values()[ordinal >> 4]; - final boolean stem = ( ( ordinal >> 3 ) & 1 ) == 1; - if( ID.type.isItem() ) - { - ItemStack it = null; - if( stem ) - { - it = player.inventory.getCurrentItem(); - } - else if( x >= 0 && x < player.inventory.mainInventory.length ) - { - it = player.inventory.getStackInSlot( x ); - } - final Object myItem = this.getGuiObject( it, player, w, x, y, z ); - if( myItem != null && ID.CorrectTileOrPart( myItem ) ) - { - return ID.ConstructGui( player.inventory, side, myItem ); - } - } - if( ID.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( x, y, z ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( ID.CorrectTileOrPart( part ) ) - { - return ID.ConstructGui( player.inventory, side, part ); - } - } - else - { - if( ID.CorrectTileOrPart( TE ) ) - { - return ID.ConstructGui( player.inventory, side, TE ); - } - } - } - return new GuiNull( new ContainerNull() ); - } - - public Object ConstructGui( final InventoryPlayer inventory, final ForgeDirection side, final Object tE ) - { - try - { - final Constructor[] c = this.guiClass.getConstructors(); - if( c.length == 0 ) - { - throw new AppEngException( "Invalid Gui Class" ); - } - - final Constructor target = this.findConstructor( c, inventory, tE ); - - if( target == null ) - { - throw new IllegalStateException( "Cannot find " + this.containerClass.getName() + "( " + this.typeName( inventory ) + ", " + this.typeName( tE ) + " )" ); - } - - return target.newInstance( inventory, tE ); - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } - - public boolean hasPermissions( final TileEntity te, final int x, final int y, final int z, final ForgeDirection side, final EntityPlayer player ) - { - final World w = player.getEntityWorld(); - - if( Platform.hasPermissions( te != null ? new DimensionalCoord( te ) : new DimensionalCoord( player.worldObj, x, y, z ), player ) ) - { - if( this.type.isItem() ) - { - final ItemStack it = player.inventory.getCurrentItem(); - if( it != null && it.getItem() instanceof IGuiItem ) - { - final Object myItem = ( (IGuiItem) it.getItem() ).getGuiObject( it, w, x, y, z ); - if( this.CorrectTileOrPart( myItem ) ) - { - return true; - } - } - } - - if( this.type.isTile() ) - { - final TileEntity TE = w.getTileEntity( x, y, z ); - if( TE instanceof IPartHost ) - { - ( (IPartHost) TE ).getPart( side ); - final IPart part = ( (IPartHost) TE ).getPart( side ); - if( this.CorrectTileOrPart( part ) ) - { - return this.securityCheck( part, player ); - } - } - else - { - if( this.CorrectTileOrPart( TE ) ) - { - return this.securityCheck( TE, player ); - } - } - } - } - return false; - } - - private boolean securityCheck( final Object te, final EntityPlayer player ) - { - if( te instanceof IActionHost && this.requiredPermission != null ) - { - final IGridNode gn = ( (IActionHost) te ).getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - final boolean requirePower = false; - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( player, this.requiredPermission ) ) - { - return true; - } - } - } - - return false; - } - return true; - } - - public GuiHostType getType() - { - return this.type; - } - +public enum GuiBridge implements IGuiHandler { + GUI_Handler(), + + GUI_GRINDER(ContainerGrinder.class, TileGrinder.class, GuiHostType.WORLD, null), + + GUI_QNB( + ContainerQNB.class, + TileQuantumBridge.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_SKYCHEST(ContainerSkyChest.class, TileSkyChest.class, GuiHostType.WORLD, null), + + GUI_CHEST( + ContainerChest.class, + TileChest.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_WIRELESS( + ContainerWireless.class, + TileWireless.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_ME(ContainerMEMonitorable.class, ITerminalHost.class, GuiHostType.WORLD, null), + + GUI_PORTABLE_CELL( + ContainerMEPortableCell.class, IPortableCell.class, GuiHostType.ITEM, null + ), + + GUI_WIRELESS_TERM( + ContainerWirelessTerm.class, + WirelessTerminalGuiObject.class, + GuiHostType.ITEM, + null + ), + + GUI_NETWORK_STATUS( + ContainerNetworkStatus.class, INetworkTool.class, GuiHostType.ITEM, null + ), + + GUI_NETWORK_STATUS_BLOCK( + ContainerNetworkStatus.class, TileLegacyController.class, GuiHostType.WORLD, null + ), + + GUI_CRAFTING_CPU( + ContainerCraftingCPU.class, + TileCraftingTile.class, + GuiHostType.WORLD, + SecurityPermissions.CRAFT + ), + + GUI_NETWORK_TOOL( + ContainerNetworkTool.class, INetworkTool.class, GuiHostType.ITEM, null + ), + + GUI_QUARTZ_KNIFE( + ContainerQuartzKnife.class, QuartzKnifeObj.class, GuiHostType.ITEM, null + ), + + GUI_DRIVE( + ContainerDrive.class, + TileDrive.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_VIBRATION_CHAMBER( + ContainerVibrationChamber.class, + TileVibrationChamber.class, + GuiHostType.WORLD, + null + ), + + GUI_CONDENSER(ContainerCondenser.class, TileCondenser.class, GuiHostType.WORLD, null), + + GUI_INTERFACE( + ContainerInterface.class, + IInterfaceHost.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_BUS( + ContainerUpgradeable.class, + IUpgradeableHost.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_IOPORT( + ContainerIOPort.class, + TileIOPort.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_STORAGEBUS( + ContainerStorageBus.class, + PartStorageBus.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_FORMATION_PLANE( + ContainerFormationPlane.class, + PartFormationPlane.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_PRIORITY( + ContainerPriority.class, + IPriorityHost.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_SECURITY( + ContainerSecurity.class, + TileSecurity.class, + GuiHostType.WORLD, + SecurityPermissions.SECURITY + ), + + GUI_CRAFTING_TERMINAL( + ContainerCraftingTerm.class, + ICraftingTerminal.class, + GuiHostType.WORLD, + SecurityPermissions.CRAFT + ), + + GUI_PATTERN_TERMINAL( + ContainerPatternTerm.class, + PartPatternTerminal.class, + GuiHostType.WORLD, + SecurityPermissions.CRAFT + ), + + // extends (Container/Gui) + Bus + GUI_LEVEL_EMITTER( + ContainerLevelEmitter.class, + PartLevelEmitter.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_SPATIAL_IO_PORT( + ContainerSpatialIOPort.class, + TileSpatialIOPort.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_INSCRIBER(ContainerInscriber.class, TileInscriber.class, GuiHostType.WORLD, null), + + GUI_CELL_WORKBENCH( + ContainerCellWorkbench.class, TileCellWorkbench.class, GuiHostType.WORLD, null + ), + + GUI_MAC(ContainerMAC.class, TileMolecularAssembler.class, GuiHostType.WORLD, null), + + GUI_CRAFTING_AMOUNT( + ContainerCraftAmount.class, + ITerminalHost.class, + GuiHostType.ITEM_OR_WORLD, + SecurityPermissions.CRAFT + ), + + GUI_CRAFTING_CONFIRM( + ContainerCraftConfirm.class, + ITerminalHost.class, + GuiHostType.ITEM_OR_WORLD, + SecurityPermissions.CRAFT + ), + + GUI_INTERFACE_TERMINAL( + ContainerInterfaceTerminal.class, + PartInterfaceTerminal.class, + GuiHostType.WORLD, + SecurityPermissions.BUILD + ), + + GUI_CRAFTING_STATUS( + ContainerCraftingStatus.class, + ITerminalHost.class, + GuiHostType.ITEM_OR_WORLD, + SecurityPermissions.CRAFT + ); + + private final Class tileClass; + private final Class containerClass; + private Class guiClass; + private GuiHostType type; + private SecurityPermissions requiredPermission; + + GuiBridge() { + this.tileClass = null; + this.guiClass = null; + this.containerClass = null; + } + + GuiBridge(final Class containerClass, final SecurityPermissions requiredPermission) { + this.requiredPermission = requiredPermission; + this.containerClass = containerClass; + this.tileClass = 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()) { + final String start = this.containerClass.getName(); + final String guiClass = start.replaceFirst("container.", "client.gui.") + .replace(".Container", ".Gui"); + + if (start.equals(guiClass)) { + throw new IllegalStateException("Unable to find gui class"); + } + this.guiClass + = ReflectionHelper.getClass(this.getClass().getClassLoader(), guiClass); + if (this.guiClass == null) { + throw new IllegalStateException("Cannot Load class: " + guiClass); + } + } + } + + GuiBridge( + final Class containerClass, + final Class tileClass, + final GuiHostType type, + final SecurityPermissions requiredPermission + ) { + this.requiredPermission = requiredPermission; + this.containerClass = containerClass; + this.type = type; + this.tileClass = tileClass; + this.getGui(); + } + + @Override + public Object getServerGuiElement( + final int ordinal, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z + ) { + final ForgeDirection side = ForgeDirection.getOrientation(ordinal & 0x07); + final GuiBridge ID = values()[ordinal >> 4]; + final boolean stem = ((ordinal >> 3) & 1) == 1; + if (ID.type.isItem()) { + ItemStack it = null; + if (stem) { + it = player.inventory.getCurrentItem(); + } else if (x >= 0 && x < player.inventory.mainInventory.length) { + it = player.inventory.getStackInSlot(x); + } + final 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()) { + final TileEntity TE = w.getTileEntity(x, y, z); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final 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( + final ItemStack it, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z + ) { + if (it != null) { + if (it.getItem() instanceof IGuiItem) { + return ((IGuiItem) it.getItem()).getGuiObject(it, w, x, y, z); + } + + final 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(final Object tE) { + if (this.tileClass == null) { + throw new IllegalArgumentException("This Gui Cannot use the standard Handler." + ); + } + + return this.tileClass.isInstance(tE); + } + + private Object updateGui( + final Object newContainer, + final World w, + final int x, + final int y, + final int z, + final ForgeDirection side, + final Object myItem + ) { + if (newContainer instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) newContainer; + bc.setOpenContext(new ContainerOpenContext(myItem)); + bc.getOpenContext().setWorld(w); + bc.getOpenContext().setX(x); + bc.getOpenContext().setY(y); + bc.getOpenContext().setZ(z); + bc.getOpenContext().setSide(side); + } + + return newContainer; + } + + public Object ConstructContainer( + final InventoryPlayer inventory, final ForgeDirection side, final Object tE + ) { + try { + final Constructor[] c = this.containerClass.getConstructors(); + if (c.length == 0) { + throw new AppEngException("Invalid Gui Class"); + } + + final Constructor target = this.findConstructor(c, inventory, tE); + + if (target == null) { + throw new IllegalStateException( + "Cannot find " + this.containerClass.getName() + "( " + + this.typeName(inventory) + ", " + this.typeName(tE) + " )" + ); + } + + final Object o = target.newInstance(inventory, tE); + + /** + * triggers achievement when the player sees presses. + */ + if (o instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) o; + for (final Object so : bc.inventorySlots) { + if (so instanceof Slot) { + final ItemStack is = ((Slot) so).getStack(); + + final IMaterials materials + = AEApi.instance().definitions().materials(); + this.addPressAchievementToPlayer(is, materials, inventory.player); + } + } + } + + return o; + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } + + private Constructor findConstructor( + final Constructor[] c, final InventoryPlayer inventory, final Object tE + ) { + for (final Constructor con : c) { + final Class[] types = con.getParameterTypes(); + if (types.length == 2) { + if (types[0].isAssignableFrom(inventory.getClass()) + && types[1].isAssignableFrom(tE.getClass())) { + return con; + } + } + } + return null; + } + + private String typeName(final Object inventory) { + if (inventory == null) { + return "NULL"; + } + + return inventory.getClass().getName(); + } + + private void addPressAchievementToPlayer( + final ItemStack newItem, + final IMaterials possibleMaterials, + final 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 (final IComparableDefinition press : presses) { + if (press.isSameAs(newItem)) { + Achievements.Presses.addToPlayer(player); + + return; + } + } + } + + @Override + public Object getClientGuiElement( + final int ordinal, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z + ) { + final ForgeDirection side = ForgeDirection.getOrientation(ordinal & 0x07); + final GuiBridge ID = values()[ordinal >> 4]; + final boolean stem = ((ordinal >> 3) & 1) == 1; + if (ID.type.isItem()) { + ItemStack it = null; + if (stem) { + it = player.inventory.getCurrentItem(); + } else if (x >= 0 && x < player.inventory.mainInventory.length) { + it = player.inventory.getStackInSlot(x); + } + final Object myItem = this.getGuiObject(it, player, w, x, y, z); + if (myItem != null && ID.CorrectTileOrPart(myItem)) { + return ID.ConstructGui(player.inventory, side, myItem); + } + } + if (ID.type.isTile()) { + final TileEntity TE = w.getTileEntity(x, y, z); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (ID.CorrectTileOrPart(part)) { + return ID.ConstructGui(player.inventory, side, part); + } + } else { + if (ID.CorrectTileOrPart(TE)) { + return ID.ConstructGui(player.inventory, side, TE); + } + } + } + return new GuiNull(new ContainerNull()); + } + + public Object ConstructGui( + final InventoryPlayer inventory, final ForgeDirection side, final Object tE + ) { + try { + final Constructor[] c = this.guiClass.getConstructors(); + if (c.length == 0) { + throw new AppEngException("Invalid Gui Class"); + } + + final Constructor target = this.findConstructor(c, inventory, tE); + + if (target == null) { + throw new IllegalStateException( + "Cannot find " + this.containerClass.getName() + "( " + + this.typeName(inventory) + ", " + this.typeName(tE) + " )" + ); + } + + return target.newInstance(inventory, tE); + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } + + public boolean hasPermissions( + final TileEntity te, + final int x, + final int y, + final int z, + final ForgeDirection side, + final EntityPlayer player + ) { + final World w = player.getEntityWorld(); + + if (Platform.hasPermissions( + te != null ? new DimensionalCoord(te) + : new DimensionalCoord(player.worldObj, x, y, z), + player + )) { + if (this.type.isItem()) { + final ItemStack it = player.inventory.getCurrentItem(); + if (it != null && it.getItem() instanceof IGuiItem) { + final Object myItem + = ((IGuiItem) it.getItem()).getGuiObject(it, w, x, y, z); + if (this.CorrectTileOrPart(myItem)) { + return true; + } + } + } + + if (this.type.isTile()) { + final TileEntity TE = w.getTileEntity(x, y, z); + if (TE instanceof IPartHost) { + ((IPartHost) TE).getPart(side); + final IPart part = ((IPartHost) TE).getPart(side); + if (this.CorrectTileOrPart(part)) { + return this.securityCheck(part, player); + } + } else { + if (this.CorrectTileOrPart(TE)) { + return this.securityCheck(TE, player); + } + } + } + } + return false; + } + + private boolean securityCheck(final Object te, final EntityPlayer player) { + if (te instanceof IActionHost && this.requiredPermission != null) { + final IGridNode gn = ((IActionHost) te).getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + final boolean requirePower = false; + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(player, this.requiredPermission)) { + return true; + } + } + } + + return false; + } + return true; + } + + public GuiHostType getType() { + return this.type; + } } diff --git a/src/main/java/appeng/core/sync/GuiHostType.java b/src/main/java/appeng/core/sync/GuiHostType.java index ac780028..35041153 100644 --- a/src/main/java/appeng/core/sync/GuiHostType.java +++ b/src/main/java/appeng/core/sync/GuiHostType.java @@ -18,18 +18,16 @@ package appeng.core.sync; +public enum GuiHostType { + ITEM_OR_WORLD, + ITEM, + WORLD; -public enum GuiHostType -{ - ITEM_OR_WORLD, ITEM, WORLD; + public boolean isItem() { + return this != WORLD; + } - public boolean isItem() - { - return this != WORLD; - } - - boolean isTile() - { - return this != ITEM; - } + boolean isTile() { + return this != ITEM; + } } diff --git a/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngClientPacketHandler.java index 5aac2000..34ac2255 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 appeng.core.AELog; import appeng.core.sync.AppEngPacket; @@ -27,40 +28,29 @@ import io.netty.buffer.ByteBuf; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; -import java.lang.reflect.InvocationTargetException; +public class AppEngClientPacketHandler + extends AppEngPacketHandlerBase implements IPacketHandler { + @Override + public void onPacketData( + final INetworkInfo network, final FMLProxyPacket packet, EntityPlayer player + ) { + final ByteBuf stream = packet.payload(); + player = Minecraft.getMinecraft().thePlayer; -public class AppEngClientPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler -{ - - @Override - public void onPacketData( final INetworkInfo network, final FMLProxyPacket packet, EntityPlayer player ) - { - final ByteBuf stream = packet.payload(); - - player = Minecraft.getMinecraft().thePlayer; - - try - { - final int packetType = stream.readInt(); - final AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); - pack.clientPacketData( network, pack, player ); - } - catch( final InstantiationException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final InvocationTargetException e ) - { - AELog.debug( e ); - } - } + try { + final int packetType = stream.readInt(); + final AppEngPacket pack + = PacketTypes.getPacket(packetType).parsePacket(stream); + pack.clientPacketData(network, pack, player); + } catch (final InstantiationException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final InvocationTargetException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java b/src/main/java/appeng/core/sync/network/AppEngServerPacketHandler.java index 62e6b98d..11eed502 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 appeng.core.AELog; import appeng.core.sync.AppEngPacket; @@ -26,38 +27,27 @@ import cpw.mods.fml.common.network.internal.FMLProxyPacket; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; -import java.lang.reflect.InvocationTargetException; +public final class AppEngServerPacketHandler + extends AppEngPacketHandlerBase implements IPacketHandler { + @Override + public void onPacketData( + final INetworkInfo manager, final FMLProxyPacket packet, final EntityPlayer player + ) { + final ByteBuf stream = packet.payload(); - -public final class AppEngServerPacketHandler extends AppEngPacketHandlerBase implements IPacketHandler -{ - - @Override - public void onPacketData( final INetworkInfo manager, final FMLProxyPacket packet, final EntityPlayer player ) - { - final ByteBuf stream = packet.payload(); - - try - { - final int packetType = stream.readInt(); - final AppEngPacket pack = PacketTypes.getPacket( packetType ).parsePacket( stream ); - pack.serverPacketData( manager, pack, player ); - } - catch( final InstantiationException e ) - { - AELog.debug( e ); - } - catch( final IllegalAccessException e ) - { - AELog.debug( e ); - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - catch( final InvocationTargetException e ) - { - AELog.debug( e ); - } - } + try { + final int packetType = stream.readInt(); + final AppEngPacket pack + = PacketTypes.getPacket(packetType).parsePacket(stream); + pack.serverPacketData(manager, pack, player); + } catch (final InstantiationException e) { + AELog.debug(e); + } catch (final IllegalAccessException e) { + AELog.debug(e); + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } catch (final InvocationTargetException e) { + AELog.debug(e); + } + } } diff --git a/src/main/java/appeng/core/sync/network/INetworkInfo.java b/src/main/java/appeng/core/sync/network/INetworkInfo.java index 51766b76..c2f914b3 100644 --- a/src/main/java/appeng/core/sync/network/INetworkInfo.java +++ b/src/main/java/appeng/core/sync/network/INetworkInfo.java @@ -18,8 +18,4 @@ package appeng.core.sync.network; - -public interface INetworkInfo -{ - -} +public interface INetworkInfo {} diff --git a/src/main/java/appeng/core/sync/network/IPacketHandler.java b/src/main/java/appeng/core/sync/network/IPacketHandler.java index d1b2756d..d5e80f58 100644 --- a/src/main/java/appeng/core/sync/network/IPacketHandler.java +++ b/src/main/java/appeng/core/sync/network/IPacketHandler.java @@ -18,13 +18,9 @@ package appeng.core.sync.network; - import cpw.mods.fml.common.network.internal.FMLProxyPacket; import net.minecraft.entity.player.EntityPlayer; - -public interface IPacketHandler -{ - - void onPacketData( INetworkInfo manager, FMLProxyPacket packet, EntityPlayer player ); +public interface IPacketHandler { + 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 7f326985..84c504ea 100644 --- a/src/main/java/appeng/core/sync/network/NetworkHandler.java +++ b/src/main/java/appeng/core/sync/network/NetworkHandler.java @@ -18,7 +18,6 @@ package appeng.core.sync.network; - import appeng.core.sync.AppEngPacket; import appeng.core.worlddata.WorldData; import cpw.mods.fml.common.FMLCommonHandler; @@ -32,113 +31,91 @@ import cpw.mods.fml.common.network.NetworkRegistry; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetHandlerPlayServer; +public class NetworkHandler { + public static NetworkHandler instance; -public class NetworkHandler -{ + private final FMLEventChannel ec; + private final String myChannelName; - public static NetworkHandler instance; + private final IPacketHandler clientHandler; + private final IPacketHandler serveHandler; - private final FMLEventChannel ec; - private final String myChannelName; + public NetworkHandler(final String channelName) { + FMLCommonHandler.instance().bus().register(this); + this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel( + this.myChannelName = channelName + ); + this.ec.register(this); - private final IPacketHandler clientHandler; - private final IPacketHandler serveHandler; + this.clientHandler = this.createClientSide(); + this.serveHandler = this.createServerSide(); + } - public NetworkHandler( final String channelName ) - { - FMLCommonHandler.instance().bus().register( this ); - this.ec = NetworkRegistry.INSTANCE.newEventDrivenChannel( this.myChannelName = channelName ); - this.ec.register( this ); + private IPacketHandler createClientSide() { + try { + return new AppEngClientPacketHandler(); + } catch (final Throwable t) { + return null; + } + } - this.clientHandler = this.createClientSide(); - this.serveHandler = this.createServerSide(); - } + private IPacketHandler createServerSide() { + try { + return new AppEngServerPacketHandler(); + } catch (final Throwable t) { + return null; + } + } - private IPacketHandler createClientSide() - { - try - { - return new AppEngClientPacketHandler(); - } - catch( final Throwable t ) - { - return null; - } - } + @SubscribeEvent + public void newConnection(final ServerConnectionFromClientEvent ev) { + WorldData.instance().dimensionData().sendToPlayer(ev.manager); + } - private IPacketHandler createServerSide() - { - try - { - return new AppEngServerPacketHandler(); - } - catch( final Throwable t ) - { - return null; - } - } + @SubscribeEvent + public void newConnection(final PlayerLoggedInEvent loginEvent) { + if (loginEvent.player instanceof EntityPlayerMP) { + WorldData.instance().dimensionData().sendToPlayer(null); + } + } - @SubscribeEvent - public void newConnection( final ServerConnectionFromClientEvent ev ) - { - WorldData.instance().dimensionData().sendToPlayer( ev.manager ); - } + @SubscribeEvent + public void serverPacket(final ServerCustomPacketEvent ev) { + final NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.packet.handler(); + if (this.serveHandler != null) { + this.serveHandler.onPacketData(null, ev.packet, srv.playerEntity); + } + } - @SubscribeEvent - public void newConnection( final PlayerLoggedInEvent loginEvent ) - { - if( loginEvent.player instanceof EntityPlayerMP ) - { - WorldData.instance().dimensionData().sendToPlayer( null ); - } - } + @SubscribeEvent + public void clientPacket(final ClientCustomPacketEvent ev) { + if (this.clientHandler != null) { + this.clientHandler.onPacketData(null, ev.packet, null); + } + } - @SubscribeEvent - public void serverPacket( final ServerCustomPacketEvent ev ) - { - final NetHandlerPlayServer srv = (NetHandlerPlayServer) ev.packet.handler(); - if( this.serveHandler != null ) - { - this.serveHandler.onPacketData( null, ev.packet, srv.playerEntity ); - } - } + public String getChannel() { + return this.myChannelName; + } - @SubscribeEvent - public void clientPacket( final ClientCustomPacketEvent ev ) - { - if( this.clientHandler != null ) - { - this.clientHandler.onPacketData( null, ev.packet, null ); - } - } + public void sendToAll(final AppEngPacket message) { + this.ec.sendToAll(message.getProxy()); + } - public String getChannel() - { - return this.myChannelName; - } + public void sendTo(final AppEngPacket message, final EntityPlayerMP player) { + this.ec.sendTo(message.getProxy(), player); + } - public void sendToAll( final AppEngPacket message ) - { - this.ec.sendToAll( message.getProxy() ); - } + public void + sendToAllAround(final AppEngPacket message, final NetworkRegistry.TargetPoint point) { + this.ec.sendToAllAround(message.getProxy(), point); + } - public void sendTo( final AppEngPacket message, final EntityPlayerMP player ) - { - this.ec.sendTo( message.getProxy(), player ); - } + public void sendToDimension(final AppEngPacket message, final int dimensionId) { + this.ec.sendToDimension(message.getProxy(), dimensionId); + } - public void sendToAllAround( final AppEngPacket message, final NetworkRegistry.TargetPoint point ) - { - this.ec.sendToAllAround( message.getProxy(), point ); - } - - public void sendToDimension( final AppEngPacket message, final int dimensionId ) - { - this.ec.sendToDimension( message.getProxy(), dimensionId ); - } - - public void sendToServer( final AppEngPacket message ) - { - this.ec.sendToServer( message.getProxy() ); - } + public void sendToServer(final 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 f9123de7..83b7dd78 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 appeng.api.storage.data.IAEItemStack; import appeng.client.EffectType; @@ -31,53 +32,58 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; -import java.io.IOException; +public class PacketAssemblerAnimation extends AppEngPacket { + private final int x; + private final int y; + private final int z; + public final byte rate; + public final IAEItemStack is; + // automatic. + public PacketAssemblerAnimation(final ByteBuf stream) throws IOException { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.rate = stream.readByte(); + this.is = AEItemStack.loadItemStackFromPacket(stream); + } -public class PacketAssemblerAnimation extends AppEngPacket -{ + // api + public PacketAssemblerAnimation( + final int x, final int y, final int z, final byte rate, final IAEItemStack is + ) throws IOException { + final ByteBuf data = Unpooled.buffer(); - private final int x; - private final int y; - private final int z; - public final byte rate; - public final IAEItemStack is; + data.writeInt(this.getPacketID()); + data.writeInt(this.x = x); + data.writeInt(this.y = y); + data.writeInt(this.z = z); + data.writeByte(this.rate = rate); + is.writeToPacket(data); + this.is = is; - // automatic. - public PacketAssemblerAnimation( final ByteBuf stream ) throws IOException - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.rate = stream.readByte(); - this.is = AEItemStack.loadItemStackFromPacket( stream ); - } + this.configureWrite(data); + } - // api - public PacketAssemblerAnimation( final int x, final int y, final int z, final byte rate, final IAEItemStack is ) throws IOException - { + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final double d0 + = 0.5d; // + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + final double d1 + = 0.5d; // + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); + final double d2 + = 0.5d; // + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - final ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeInt( this.x = x ); - data.writeInt( this.y = y ); - data.writeInt( this.z = z ); - data.writeByte( this.rate = rate ); - is.writeToPacket( data ); - this.is = is; - - this.configureWrite( data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final double d0 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - final double d1 = 0.5d;// + ((double) (Platform.getRandomFloat() - 0.5F) * 0.26D); - final 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 ); - } + 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 02f24920..e8a0a163 100644 --- a/src/main/java/appeng/core/sync/packets/PacketClick.java +++ b/src/main/java/appeng/core/sync/packets/PacketClick.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.AEApi; import appeng.api.definitions.IComparableDefinition; import appeng.api.definitions.IItems; @@ -33,76 +32,86 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +public class PacketClick extends AppEngPacket { + private final int x; + private final int y; + private final int z; + private final int side; + private final float hitX; + private final float hitY; + private final float hitZ; -public class PacketClick extends AppEngPacket -{ + // automatic. + public PacketClick(final ByteBuf stream) { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.side = stream.readInt(); + this.hitX = stream.readFloat(); + this.hitY = stream.readFloat(); + this.hitZ = stream.readFloat(); + } - private final int x; - private final int y; - private final int z; - private final int side; - private final float hitX; - private final float hitY; - private final float hitZ; + // api + public PacketClick( + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketClick( final ByteBuf stream ) - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.side = stream.readInt(); - this.hitX = stream.readFloat(); - this.hitY = stream.readFloat(); - this.hitZ = stream.readFloat(); - } + data.writeInt(this.getPacketID()); + data.writeInt(this.x = x); + data.writeInt(this.y = y); + data.writeInt(this.z = z); + data.writeInt(this.side = side); + data.writeFloat(this.hitX = hitX); + data.writeFloat(this.hitY = hitY); + data.writeFloat(this.hitZ = hitZ); - // api - public PacketClick( final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final ItemStack is = player.inventory.getCurrentItem(); + final IItems items = AEApi.instance().definitions().items(); + final IComparableDefinition maybeMemoryCard = items.memoryCard(); + final IComparableDefinition maybeColorApplicator = items.colorApplicator(); - data.writeInt( this.getPacketID() ); - data.writeInt( this.x = x ); - data.writeInt( this.y = y ); - data.writeInt( this.z = z ); - data.writeInt( this.side = side ); - data.writeFloat( this.hitX = hitX ); - data.writeFloat( this.hitY = hitY ); - data.writeFloat( this.hitZ = hitZ ); + if (is != null) { + if (is.getItem() instanceof ToolNetworkTool) { + final 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 + ); + } - this.configureWrite( data ); - } + else if (maybeMemoryCard.isSameAs(is)) { + final IMemoryCard mem = (IMemoryCard) is.getItem(); + mem.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + is.setTagCompound(null); + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final 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 ) - { - final 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 ) ) - { - final IMemoryCard mem = (IMemoryCard) is.getItem(); - mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - is.setTagCompound( null ); - } - - else if( maybeColorApplicator.isSameAs( is ) ) - { - final ToolColorApplicator mem = (ToolColorApplicator) is.getItem(); - mem.cycleColors( is, mem.getColor( is ), 1 ); - } - } - } + else if (maybeColorApplicator.isSameAs(is)) { + final 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 a9e76ad8..3934253d 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassRequest.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.util.DimensionalCoord; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -30,53 +29,59 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +public class PacketCompassRequest extends AppEngPacket implements ICompassCallback { + final long attunement; + final int cx; + final int cz; + final int cdy; -public class PacketCompassRequest extends AppEngPacket implements ICompassCallback -{ + private EntityPlayer talkBackTo; - final long attunement; - final int cx; - final int cz; - final int cdy; + // automatic. + public PacketCompassRequest(final ByteBuf stream) { + this.attunement = stream.readLong(); + this.cx = stream.readInt(); + this.cz = stream.readInt(); + this.cdy = stream.readInt(); + } - private EntityPlayer talkBackTo; + // api + public PacketCompassRequest( + final long attunement, final int cx, final int cz, final int cdy + ) { + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketCompassRequest( final ByteBuf stream ) - { - this.attunement = stream.readLong(); - this.cx = stream.readInt(); - this.cz = stream.readInt(); - this.cdy = stream.readInt(); - } + data.writeInt(this.getPacketID()); + data.writeLong(this.attunement = attunement); + data.writeInt(this.cx = cx); + data.writeInt(this.cz = cz); + data.writeInt(this.cdy = cdy); - // api - public PacketCompassRequest( final long attunement, final int cx, final int cz, final int cdy ) - { + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); + @Override + public void calculatedDirection( + final boolean hasResult, + final boolean spin, + final double radians, + final double dist + ) { + NetworkHandler.instance.sendTo( + new PacketCompassResponse(this, hasResult, spin, radians), + (EntityPlayerMP) this.talkBackTo + ); + } - data.writeInt( this.getPacketID() ); - data.writeLong( this.attunement = attunement ); - data.writeInt( this.cx = cx ); - data.writeInt( this.cz = cz ); - data.writeInt( this.cdy = cdy ); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + this.talkBackTo = player; - this.configureWrite( data ); - } - - @Override - public void calculatedDirection( final boolean hasResult, final boolean spin, final double radians, final double dist ) - { - NetworkHandler.instance.sendTo( new PacketCompassResponse( this, hasResult, spin, radians ), (EntityPlayerMP) this.talkBackTo ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - this.talkBackTo = player; - - final DimensionalCoord loc = new DimensionalCoord( player.worldObj, this.cx << 4, this.cdy << 5, this.cz << 4 ); - WorldData.instance().compassData().service().getCompassDirection( loc, 174, this ); - } + final DimensionalCoord loc = new DimensionalCoord( + player.worldObj, this.cx << 4, this.cdy << 5, this.cz << 4 + ); + WorldData.instance().compassData().service().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 6daf805b..9056b61f 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompassResponse.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.hooks.CompassManager; @@ -27,50 +26,54 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketCompassResponse extends AppEngPacket { + private final long attunement; + private final int cx; + private final int cz; + private final int cdy; -public class PacketCompassResponse extends AppEngPacket -{ + private CompassResult cr; - private final long attunement; - private final int cx; - private final int cz; - private final int cdy; + // automatic. + public PacketCompassResponse(final ByteBuf stream) { + this.attunement = stream.readLong(); + this.cx = stream.readInt(); + this.cz = stream.readInt(); + this.cdy = stream.readInt(); - private CompassResult cr; + this.cr = new CompassResult( + stream.readBoolean(), stream.readBoolean(), stream.readDouble() + ); + } - // automatic. - public PacketCompassResponse( final ByteBuf stream ) - { - this.attunement = stream.readLong(); - this.cx = stream.readInt(); - this.cz = stream.readInt(); - this.cdy = stream.readInt(); + // api + public PacketCompassResponse( + final PacketCompassRequest req, + final boolean hasResult, + final boolean spin, + final double radians + ) { + final ByteBuf data = Unpooled.buffer(); - this.cr = new CompassResult( stream.readBoolean(), stream.readBoolean(), stream.readDouble() ); - } + data.writeInt(this.getPacketID()); + data.writeLong(this.attunement = req.attunement); + data.writeInt(this.cx = req.cx); + data.writeInt(this.cz = req.cz); + data.writeInt(this.cdy = req.cdy); - // api - public PacketCompassResponse( final PacketCompassRequest req, final boolean hasResult, final boolean spin, final double radians ) - { + data.writeBoolean(hasResult); + data.writeBoolean(spin); + data.writeDouble(radians); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeLong( this.attunement = req.attunement ); - data.writeInt( this.cx = req.cx ); - data.writeInt( this.cz = req.cz ); - data.writeInt( this.cdy = req.cdy ); - - data.writeBoolean( hasResult ); - data.writeBoolean( spin ); - data.writeDouble( radians ); - - this.configureWrite( data ); - } - - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - CompassManager.INSTANCE.postResult( this.attunement, this.cx << 4, this.cdy << 5, this.cz << 4, this.cr ); - } + @Override + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final 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 84e610cf..2dcb86ed 100644 --- a/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java +++ b/src/main/java/appeng/core/sync/packets/PacketCompressedNBT.java @@ -18,6 +18,9 @@ package appeng.core.sync.packets; +import java.io.*; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; import appeng.client.gui.implementations.GuiInterfaceTerminal; import appeng.core.sync.AppEngPacket; @@ -32,80 +35,63 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; -import java.io.*; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; +public class PacketCompressedNBT extends AppEngPacket { + // input. + private final NBTTagCompound in; + // output... + private final ByteBuf data; + private final GZIPOutputStream compressFrame; + // automatic. + public PacketCompressedNBT(final ByteBuf stream) throws IOException { + this.data = null; + this.compressFrame = null; -public class PacketCompressedNBT extends AppEngPacket -{ + final GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { + @Override + public int read() throws IOException { + if (stream.readableBytes() <= 0) { + return -1; + } - // input. - private final NBTTagCompound in; - // output... - private final ByteBuf data; - private final GZIPOutputStream compressFrame; + return stream.readByte() & 0xff; + } + }); - // automatic. - public PacketCompressedNBT( final ByteBuf stream ) throws IOException - { - this.data = null; - this.compressFrame = null; + final DataInputStream inStream = new DataInputStream(gzReader); + this.in = CompressedStreamTools.read(inStream); + inStream.close(); + } - final GZIPInputStream gzReader = new GZIPInputStream( new InputStream() - { + // api + public PacketCompressedNBT(final NBTTagCompound din) throws IOException { + this.data = Unpooled.buffer(2048); + this.data.writeInt(this.getPacketID()); - @Override - public int read() throws IOException - { - if( stream.readableBytes() <= 0 ) - { - return -1; - } + this.in = din; - return stream.readByte() & 0xff; - } - } ); + this.compressFrame = new GZIPOutputStream(new OutputStream() { + @Override + public void write(final int value) throws IOException { + PacketCompressedNBT.this.data.writeByte(value); + } + }); - final DataInputStream inStream = new DataInputStream( gzReader ); - this.in = CompressedStreamTools.read( inStream ); - inStream.close(); - } + CompressedStreamTools.write(din, new DataOutputStream(this.compressFrame)); + this.compressFrame.close(); - // api - public PacketCompressedNBT( final NBTTagCompound din ) throws IOException - { + this.configureWrite(this.data); + } - this.data = Unpooled.buffer( 2048 ); - this.data.writeInt( this.getPacketID() ); + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - this.in = din; - - this.compressFrame = new GZIPOutputStream( new OutputStream() - { - - @Override - public void write( final int value ) throws IOException - { - PacketCompressedNBT.this.data.writeByte( value ); - } - } ); - - CompressedStreamTools.write( din, new DataOutputStream( this.compressFrame ) ); - this.compressFrame.close(); - - this.configureWrite( this.data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - - if( gs instanceof GuiInterfaceTerminal ) - { - ( (GuiInterfaceTerminal) gs ).postUpdate( this.in ); - } - } + 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 db9e2bba..47406cd9 100644 --- a/src/main/java/appeng/core/sync/packets/PacketConfigButton.java +++ b/src/main/java/appeng/core/sync/packets/PacketConfigButton.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.config.Settings; import appeng.api.util.IConfigManager; import appeng.api.util.IConfigurableObject; @@ -32,48 +31,49 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +public final class PacketConfigButton extends AppEngPacket { + private final Settings option; + private final boolean rotationDirection; -public final class PacketConfigButton extends AppEngPacket -{ - private final Settings option; - private final boolean rotationDirection; + // automatic. + @Reflected + public PacketConfigButton(final ByteBuf stream) { + this.option = Settings.values()[stream.readInt()]; + this.rotationDirection = stream.readBoolean(); + } - // automatic. - @Reflected - public PacketConfigButton( final ByteBuf stream ) - { - this.option = Settings.values()[stream.readInt()]; - this.rotationDirection = stream.readBoolean(); - } + // api + public PacketConfigButton(final Settings option, final boolean rotationDirection) { + this.option = option; + this.rotationDirection = rotationDirection; - // api - public PacketConfigButton( final Settings option, final boolean rotationDirection ) - { - this.option = option; - this.rotationDirection = rotationDirection; + final ByteBuf data = Unpooled.buffer(); - final ByteBuf data = Unpooled.buffer(); + data.writeInt(this.getPacketID()); + data.writeInt(option.ordinal()); + data.writeBoolean(rotationDirection); - data.writeInt( this.getPacketID() ); - data.writeInt( option.ordinal() ); - data.writeBoolean( rotationDirection ); + this.configureWrite(data); + } - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof AEBaseContainer ) - { - final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if( baseContainer.getTarget() instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) baseContainer.getTarget() ).getConfigManager(); - final Enum newState = Platform.rotateEnum( cm.getSetting( this.option ), this.rotationDirection, this.option.getPossibleValues() ); - cm.putSetting( this.option, newState ); - } - } - } + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof AEBaseContainer) { + final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; + if (baseContainer.getTarget() instanceof IConfigurableObject) { + final IConfigManager cm + = ((IConfigurableObject) baseContainer.getTarget()) + .getConfigManager(); + final 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 56fc8542..bb567ce2 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 appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -38,90 +39,86 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.concurrent.Future; +public class PacketCraftRequest extends AppEngPacket { + private final long amount; + private final boolean heldShift; + // automatic. + public PacketCraftRequest(final ByteBuf stream) { + this.heldShift = stream.readBoolean(); + this.amount = stream.readLong(); + } -public class PacketCraftRequest extends AppEngPacket -{ + public PacketCraftRequest(final int craftAmt, final boolean shift) { + this.amount = craftAmt; + this.heldShift = shift; - private final long amount; - private final boolean heldShift; + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketCraftRequest( final ByteBuf stream ) - { - this.heldShift = stream.readBoolean(); - this.amount = stream.readLong(); - } + data.writeInt(this.getPacketID()); + data.writeBoolean(shift); + data.writeLong(this.amount); - public PacketCraftRequest( final int craftAmt, final boolean shift ) - { - this.amount = craftAmt; - this.heldShift = shift; + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + if (player.openContainer instanceof ContainerCraftAmount) { + final ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; + final Object target = cca.getTarget(); + if (target instanceof IGridHost) { + final IGridHost gh = (IGridHost) target; + final IGridNode gn = gh.getGridNode(ForgeDirection.UNKNOWN); + if (gn == null) { + return; + } - data.writeInt( this.getPacketID() ); - data.writeBoolean( shift ); - data.writeLong( this.amount ); + final IGrid g = gn.getGrid(); + if (g == null || cca.getItemToCraft() == null) { + return; + } - this.configureWrite( data ); - } + cca.getItemToCraft().setStackSize(this.amount); - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player.openContainer instanceof ContainerCraftAmount ) - { - final ContainerCraftAmount cca = (ContainerCraftAmount) player.openContainer; - final Object target = cca.getTarget(); - if( target instanceof IGridHost ) - { - final IGridHost gh = (IGridHost) target; - final IGridNode gn = gh.getGridNode( ForgeDirection.UNKNOWN ); - if( gn == null ) - { - return; - } + Future futureJob = null; + try { + final ICraftingGrid cg = g.getCache(ICraftingGrid.class); + futureJob = cg.beginCraftingJob( + cca.getWorld(), + cca.getGrid(), + cca.getActionSrc(), + cca.getItemToCraft(), + null + ); - final IGrid g = gn.getGrid(); - if( g == null || cca.getItemToCraft() == null ) - { - return; - } + final ContainerOpenContext context = cca.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI( + player, + te, + cca.getOpenContext().getSide(), + GuiBridge.GUI_CRAFTING_CONFIRM + ); - cca.getItemToCraft().setStackSize( this.amount ); - - Future futureJob = null; - try - { - final ICraftingGrid cg = g.getCache( ICraftingGrid.class ); - futureJob = cg.beginCraftingJob( cca.getWorld(), cca.getGrid(), cca.getActionSrc(), cca.getItemToCraft(), null ); - - final ContainerOpenContext context = cca.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( player, te, cca.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_CONFIRM ); - - if( player.openContainer instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer; - ccc.setAutoStart( this.heldShift ); - ccc.setJob( futureJob ); - cca.detectAndSendChanges(); - } - } - } - catch( final Throwable e ) - { - if( futureJob != null ) - { - futureJob.cancel( true ); - } - AELog.debug( e ); - } - } - } - } + if (player.openContainer instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm ccc + = (ContainerCraftConfirm) player.openContainer; + ccc.setAutoStart(this.heldShift); + ccc.setJob(futureJob); + cca.detectAndSendChanges(); + } + } + } catch (final Throwable e) { + if (futureJob != null) { + futureJob.cancel(true); + } + AELog.debug(e); + } + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java b/src/main/java/appeng/core/sync/packets/PacketInventoryAction.java index 5d80905f..ec52109c 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 appeng.api.storage.data.IAEItemStack; import appeng.client.ClientHelper; @@ -36,136 +37,127 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; -import java.io.IOException; +public class PacketInventoryAction extends AppEngPacket { + private final InventoryAction action; + private final int slot; + private final long id; + private final IAEItemStack slotItem; + // automatic. + public PacketInventoryAction(final ByteBuf stream) throws IOException { + this.action = InventoryAction.values()[stream.readInt()]; + this.slot = stream.readInt(); + this.id = stream.readLong(); + final boolean hasItem = stream.readBoolean(); + if (hasItem) { + this.slotItem = AEItemStack.loadItemStackFromPacket(stream); + } else { + this.slotItem = null; + } + } -public class PacketInventoryAction extends AppEngPacket -{ + // api + public PacketInventoryAction( + final InventoryAction action, final int slot, final IAEItemStack slotItem + ) throws IOException { + if (Platform.isClient()) { + throw new IllegalStateException( + "invalid packet, client cannot post inv actions with stacks." + ); + } - private final InventoryAction action; - private final int slot; - private final long id; - private final IAEItemStack slotItem; + this.action = action; + this.slot = slot; + this.id = 0; + this.slotItem = slotItem; - // automatic. - public PacketInventoryAction( final ByteBuf stream ) throws IOException - { - this.action = InventoryAction.values()[stream.readInt()]; - this.slot = stream.readInt(); - this.id = stream.readLong(); - final boolean hasItem = stream.readBoolean(); - if( hasItem ) - { - this.slotItem = AEItemStack.loadItemStackFromPacket( stream ); - } - else - { - this.slotItem = null; - } - } + final ByteBuf data = Unpooled.buffer(); - // api - public PacketInventoryAction( final InventoryAction action, final int slot, final IAEItemStack slotItem ) throws IOException - { + data.writeInt(this.getPacketID()); + data.writeInt(action.ordinal()); + data.writeInt(slot); + data.writeLong(this.id); - if( Platform.isClient() ) - { - throw new IllegalStateException( "invalid packet, client cannot post inv actions with stacks." ); - } + if (slotItem == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + slotItem.writeToPacket(data); + } - this.action = action; - this.slot = slot; - this.id = 0; - this.slotItem = slotItem; + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); + // api + public PacketInventoryAction( + final InventoryAction action, final int slot, final long id + ) { + this.action = action; + this.slot = slot; + this.id = id; + this.slotItem = null; - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( this.id ); + final ByteBuf data = Unpooled.buffer(); - if( slotItem == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } + data.writeInt(this.getPacketID()); + data.writeInt(action.ordinal()); + data.writeInt(slot); + data.writeLong(id); + data.writeBoolean(false); - this.configureWrite( data ); - } + this.configureWrite(data); + } - // api - public PacketInventoryAction( final InventoryAction action, final int slot, final long id ) - { - this.action = action; - this.slot = slot; - this.id = id; - this.slotItem = null; + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof AEBaseContainer) { + final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; + if (this.action == InventoryAction.AUTO_CRAFT) { + final ContainerOpenContext context = baseContainer.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI( + sender, + te, + baseContainer.getOpenContext().getSide(), + GuiBridge.GUI_CRAFTING_AMOUNT + ); - final ByteBuf data = Unpooled.buffer(); + if (sender.openContainer instanceof ContainerCraftAmount) { + final ContainerCraftAmount cca + = (ContainerCraftAmount) sender.openContainer; - data.writeInt( this.getPacketID() ); - data.writeInt( action.ordinal() ); - data.writeInt( slot ); - data.writeLong( id ); - data.writeBoolean( false ); + if (baseContainer.getTargetStack() != null) { + cca.getCraftingItem().putStack( + baseContainer.getTargetStack().getItemStack() + ); + cca.setItemToCraft(baseContainer.getTargetStack()); + } - this.configureWrite( data ); - } + cca.detectAndSendChanges(); + } + } + } else { + baseContainer.doAction(sender, this.action, this.slot, this.id); + } + } + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof AEBaseContainer ) - { - final AEBaseContainer baseContainer = (AEBaseContainer) sender.openContainer; - if( this.action == InventoryAction.AUTO_CRAFT ) - { - final ContainerOpenContext context = baseContainer.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( sender, te, baseContainer.getOpenContext().getSide(), GuiBridge.GUI_CRAFTING_AMOUNT ); - - if( sender.openContainer instanceof ContainerCraftAmount ) - { - final ContainerCraftAmount cca = (ContainerCraftAmount) sender.openContainer; - - if( baseContainer.getTargetStack() != null ) - { - cca.getCraftingItem().putStack( baseContainer.getTargetStack().getItemStack() ); - cca.setItemToCraft( baseContainer.getTargetStack() ); - } - - cca.detectAndSendChanges(); - } - } - } - else - { - baseContainer.doAction( sender, this.action, this.slot, this.id ); - } - } - } - - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - if( this.action == InventoryAction.UPDATE_HAND ) - { - if( this.slotItem == null ) - { - ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( null ); - } - else - { - ClientHelper.proxy.getPlayers().get( 0 ).inventory.setItemStack( this.slotItem.getItemStack() ); - } - } - } + @Override + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + if (this.action == InventoryAction.UPDATE_HAND) { + if (this.slotItem == null) { + ClientHelper.proxy.getPlayers().get(0).inventory.setItemStack(null); + } else { + ClientHelper.proxy.getPlayers().get(0).inventory.setItemStack( + this.slotItem.getItemStack() + ); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketLightning.java b/src/main/java/appeng/core/sync/packets/PacketLightning.java index e17414c0..9511bd2d 100644 --- a/src/main/java/appeng/core/sync/packets/PacketLightning.java +++ b/src/main/java/appeng/core/sync/packets/PacketLightning.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.ClientHelper; import appeng.client.render.effects.LightningFX; import appeng.core.AEConfig; @@ -32,53 +31,52 @@ import io.netty.buffer.Unpooled; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; +public class PacketLightning extends AppEngPacket { + private final double x; + private final double y; + private final double z; -public class PacketLightning extends AppEngPacket -{ + // automatic. + public PacketLightning(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + } - private final double x; - private final double y; - private final double z; + // api + public PacketLightning(final double x, final double y, final double z) { + this.x = x; + this.y = y; + this.z = z; - // automatic. - public PacketLightning( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - } + final ByteBuf data = Unpooled.buffer(); - // api - public PacketLightning( final double x, final double y, final double z ) - { - this.x = x; - this.y = y; - this.z = z; + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); - - this.configureWrite( data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { - if( Platform.isClient() && AEConfig.instance.enableEffects ) - { - final 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( final Exception ignored ) - { - } - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + try { + if (Platform.isClient() && AEConfig.instance.enableEffects) { + final 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 (final Exception ignored) {} + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java b/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java index df24cf19..69f3e044 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java +++ b/src/main/java/appeng/core/sync/packets/PacketMEInventoryUpdate.java @@ -18,6 +18,15 @@ package appeng.core.sync.packets; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.BufferOverflowException; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; +import javax.annotation.Nullable; import appeng.api.storage.data.IAEItemStack; import appeng.client.gui.implementations.GuiCraftConfirm; @@ -37,182 +46,147 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; -import javax.annotation.Nullable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.BufferOverflowException; -import java.util.LinkedList; -import java.util.List; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; +public class PacketMEInventoryUpdate extends AppEngPacket { + private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; + private static final int OPERATION_BYTE_LIMIT = 2 * 1024; + private static final int TEMP_BUFFER_SIZE = 1024; + private static final int STREAM_MASK = 0xff; + // input. + @Nullable + private final List list; + // output... + private final byte ref; -public class PacketMEInventoryUpdate extends AppEngPacket -{ - private static final int UNCOMPRESSED_PACKET_BYTE_LIMIT = 16 * 1024 * 1024; - private static final int OPERATION_BYTE_LIMIT = 2 * 1024; - private static final int TEMP_BUFFER_SIZE = 1024; - private static final int STREAM_MASK = 0xff; + @Nullable + private final ByteBuf data; + @Nullable + private final GZIPOutputStream compressFrame; - // input. - @Nullable - private final List list; - // output... - private final byte ref; + private int writtenBytes = 0; + private boolean empty = true; - @Nullable - private final ByteBuf data; - @Nullable - private final GZIPOutputStream compressFrame; + // automatic. + public PacketMEInventoryUpdate(final ByteBuf stream) throws IOException { + this.data = null; + this.compressFrame = null; + this.list = new LinkedList(); + this.ref = stream.readByte(); - private int writtenBytes = 0; - private boolean empty = true; + // int originalBytes = stream.readableBytes(); - // automatic. - public PacketMEInventoryUpdate( final ByteBuf stream ) throws IOException - { - this.data = null; - this.compressFrame = null; - this.list = new LinkedList(); - this.ref = stream.readByte(); + final GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { + @Override + public int read() throws IOException { + if (stream.readableBytes() <= 0) { + return -1; + } - // int originalBytes = stream.readableBytes(); + return stream.readByte() & STREAM_MASK; + } + }); - final GZIPInputStream gzReader = new GZIPInputStream( new InputStream() - { - @Override - public int read() throws IOException - { - if( stream.readableBytes() <= 0 ) - { - return -1; - } + final ByteBuf uncompressed = Unpooled.buffer(stream.readableBytes()); + final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; + while (gzReader.available() != 0) { + final int bytes = gzReader.read(tmp); + if (bytes > 0) { + uncompressed.writeBytes(tmp, 0, bytes); + } + } + gzReader.close(); - return stream.readByte() & STREAM_MASK; - } - } ); + // int uncompressedBytes = uncompressed.readableBytes(); + // AELog.info( "Receiver: " + originalBytes + " -> " + uncompressedBytes ); - final ByteBuf uncompressed = Unpooled.buffer( stream.readableBytes() ); - final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; - while( gzReader.available() != 0 ) - { - final int bytes = gzReader.read( tmp ); - if( bytes > 0 ) - { - uncompressed.writeBytes( tmp, 0, bytes ); - } - } - gzReader.close(); + while (uncompressed.readableBytes() > 0) { + this.list.add(AEItemStack.loadItemStackFromPacket(uncompressed)); + } - // int uncompressedBytes = uncompressed.readableBytes(); - // AELog.info( "Receiver: " + originalBytes + " -> " + uncompressedBytes ); + this.empty = this.list.isEmpty(); + } - while( uncompressed.readableBytes() > 0 ) - { - this.list.add( AEItemStack.loadItemStackFromPacket( uncompressed ) ); - } + // api + public PacketMEInventoryUpdate() throws IOException { + this((byte) 0); + } - this.empty = this.list.isEmpty(); - } + // api + public PacketMEInventoryUpdate(final byte ref) throws IOException { + this.ref = ref; + this.data = Unpooled.buffer(OPERATION_BYTE_LIMIT); + this.data.writeInt(this.getPacketID()); + this.data.writeByte(this.ref); - // api - public PacketMEInventoryUpdate() throws IOException - { - this( (byte) 0 ); - } + this.compressFrame = new GZIPOutputStream(new OutputStream() { + @Override + public void write(final int value) throws IOException { + PacketMEInventoryUpdate.this.data.writeByte(value); + } + }); - // api - public PacketMEInventoryUpdate( final byte ref ) throws IOException - { - this.ref = ref; - this.data = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - this.data.writeInt( this.getPacketID() ); - this.data.writeByte( this.ref ); + this.list = null; + } - this.compressFrame = new GZIPOutputStream( new OutputStream() - { - @Override - public void write( final int value ) throws IOException - { - PacketMEInventoryUpdate.this.data.writeByte( value ); - } - } ); + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - this.list = null; - } + if (gs instanceof GuiCraftConfirm) { + ((GuiCraftConfirm) gs).postUpdate(this.list, this.ref); + } - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + if (gs instanceof GuiCraftingCPU) { + ((GuiCraftingCPU) gs).postUpdate(this.list, this.ref); + } - if( gs instanceof GuiCraftConfirm ) - { - ( (GuiCraftConfirm) gs ).postUpdate( this.list, this.ref ); - } + if (gs instanceof GuiMEMonitorable) { + ((GuiMEMonitorable) gs).postUpdate(this.list); + } - if( gs instanceof GuiCraftingCPU ) - { - ( (GuiCraftingCPU) gs ).postUpdate( this.list, this.ref ); - } + if (gs instanceof GuiNetworkStatus) { + ((GuiNetworkStatus) gs).postUpdate(this.list); + } + } - if( gs instanceof GuiMEMonitorable ) - { - ( (GuiMEMonitorable) gs ).postUpdate( this.list ); - } + @Nullable + @Override + public FMLProxyPacket getProxy() { + try { + this.compressFrame.close(); - if( gs instanceof GuiNetworkStatus ) - { - ( (GuiNetworkStatus) gs ).postUpdate( this.list ); - } - } + this.configureWrite(this.data); + return super.getProxy(); + } catch (final IOException e) { + AELog.debug(e); + } - @Nullable - @Override - public FMLProxyPacket getProxy() - { - try - { - this.compressFrame.close(); + return null; + } - this.configureWrite( this.data ); - return super.getProxy(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } + public void appendItem(final IAEItemStack is) + throws IOException, BufferOverflowException { + final ByteBuf tmp = Unpooled.buffer(OPERATION_BYTE_LIMIT); + is.writeToPacket(tmp); - return null; - } + this.compressFrame.flush(); + if (this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT) { + throw new BufferOverflowException(); + } else { + this.writtenBytes += tmp.readableBytes(); + this.compressFrame.write(tmp.array(), 0, tmp.readableBytes()); + this.empty = false; + } + } - public void appendItem( final IAEItemStack is ) throws IOException, BufferOverflowException - { - final ByteBuf tmp = Unpooled.buffer( OPERATION_BYTE_LIMIT ); - is.writeToPacket( tmp ); + public int getLength() { + return this.data.readableBytes(); + } - this.compressFrame.flush(); - if( this.writtenBytes + tmp.readableBytes() > UNCOMPRESSED_PACKET_BYTE_LIMIT ) - { - throw new BufferOverflowException(); - } - else - { - this.writtenBytes += tmp.readableBytes(); - this.compressFrame.write( tmp.array(), 0, tmp.readableBytes() ); - this.empty = false; - } - } - - public int getLength() - { - return this.data.readableBytes(); - } - - public boolean isEmpty() - { - return this.empty; - } + public boolean isEmpty() { + return this.empty; + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java index 79e9ed3a..2d4f6d0d 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java +++ b/src/main/java/appeng/core/sync/packets/PacketMatterCannon.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.render.effects.MatterCannonFX; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -32,75 +31,79 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.world.World; +public class PacketMatterCannon extends AppEngPacket { + private final double x; + private final double y; + private final double z; + private final double dx; + private final double dy; + private final double dz; + private final byte len; -public class PacketMatterCannon extends AppEngPacket -{ + // automatic. + public PacketMatterCannon(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + this.dx = stream.readFloat(); + this.dy = stream.readFloat(); + this.dz = stream.readFloat(); + this.len = stream.readByte(); + } - private final double x; - private final double y; - private final double z; - private final double dx; - private final double dy; - private final double dz; - private final byte len; + // api + public PacketMatterCannon( + final double x, + final double y, + final double z, + final float dx, + final float dy, + final float dz, + final byte len + ) { + final float dl = dx * dx + dy * dy + dz * dz; + final float dlz = (float) Math.sqrt(dl); - // automatic. - public PacketMatterCannon( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - this.dx = stream.readFloat(); - this.dy = stream.readFloat(); - this.dz = stream.readFloat(); - this.len = stream.readByte(); - } + this.x = x; + this.y = y; + this.z = z; + this.dx = dx / dlz; + this.dy = dy / dlz; + this.dz = dz / dlz; + this.len = len; - // api - public PacketMatterCannon( final double x, final double y, final double z, final float dx, final float dy, final float dz, final byte len ) - { - final float dl = dx * dx + dy * dy + dz * dz; - final float dlz = (float) Math.sqrt( dl ); + final ByteBuf data = Unpooled.buffer(); - this.x = x; - this.y = y; - this.z = z; - this.dx = dx / dlz; - this.dy = dy / dlz; - this.dz = dz / dlz; - this.len = len; + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); + data.writeFloat((float) this.dx); + data.writeFloat((float) this.dy); + data.writeFloat((float) this.dz); + data.writeByte(len); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); - data.writeFloat( (float) this.dx ); - data.writeFloat( (float) this.dy ); - data.writeFloat( (float) this.dz ); - data.writeByte( len ); + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + try { + final World world = FMLClientHandler.instance().getClient().theWorld; + for (int a = 1; a < this.len; a++) { + final MatterCannonFX fx = new MatterCannonFX( + world, + this.x + this.dx * a, + this.y + this.dy * a, + this.z + this.dz * a, + Items.diamond + ); - this.configureWrite( data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { - - final World world = FMLClientHandler.instance().getClient().theWorld; - for( int a = 1; a < this.len; a++ ) - { - final 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( final Exception ignored ) - { - } - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } catch (final 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 f9e1893c..df20cc08 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java +++ b/src/main/java/appeng/core/sync/packets/PacketMockExplosion.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.CommonHelper; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -29,44 +28,40 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; +public class PacketMockExplosion extends AppEngPacket { + private final double x; + private final double y; + private final double z; -public class PacketMockExplosion extends AppEngPacket -{ + // automatic. + public PacketMockExplosion(final ByteBuf stream) { + this.x = stream.readDouble(); + this.y = stream.readDouble(); + this.z = stream.readDouble(); + } - private final double x; - private final double y; - private final double z; + // api + public PacketMockExplosion(final double x, final double y, final double z) { + this.x = x; + this.y = y; + this.z = z; - // automatic. - public PacketMockExplosion( final ByteBuf stream ) - { - this.x = stream.readDouble(); - this.y = stream.readDouble(); - this.z = stream.readDouble(); - } + final ByteBuf data = Unpooled.buffer(); - // api - public PacketMockExplosion( final double x, final double y, final double z ) - { - this.x = x; - this.y = y; - this.z = z; + data.writeInt(this.getPacketID()); + data.writeDouble(x); + data.writeDouble(y); + data.writeDouble(z); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeDouble( x ); - data.writeDouble( y ); - data.writeDouble( z ); - - this.configureWrite( data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final World world = CommonHelper.proxy.getWorld(); - world.spawnParticle( "largeexplode", this.x, this.y, this.z, 1.0D, 0.0D, 0.0D ); - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final 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 8bb90b26..48587c2c 100644 --- a/src/main/java/appeng/core/sync/packets/PacketMultiPart.java +++ b/src/main/java/appeng/core/sync/packets/PacketMultiPart.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; import appeng.integration.IntegrationRegistry; @@ -30,33 +29,29 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.common.MinecraftForge; +public class PacketMultiPart extends AppEngPacket { + // automatic. + public PacketMultiPart(final ByteBuf stream) {} -public class PacketMultiPart extends AppEngPacket -{ + // api + public PacketMultiPart() { + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketMultiPart( final ByteBuf stream ) - { - } + data.writeInt(this.getPacketID()); - // api - public PacketMultiPart() - { - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final IFMP fmp = (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ); - if( fmp != null ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - MinecraftForge.EVENT_BUS.post( fmp.newFMPPacketEvent( sender ) ); // when received it just posts this event. - } - } + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final IFMP fmp + = (IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP); + if (fmp != null) { + final 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 c3bf32d2..88171a27 100644 --- a/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java +++ b/src/main/java/appeng/core/sync/packets/PacketNEIRecipe.java @@ -18,6 +18,10 @@ package appeng.core.sync.packets; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; import appeng.api.config.Actionable; import appeng.api.config.FuzzyMode; @@ -54,219 +58,231 @@ import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; +public class PacketNEIRecipe extends AppEngPacket { + private ItemStack[][] recipe; + // automatic. + public PacketNEIRecipe(final ByteBuf stream) throws IOException { + final ByteArrayInputStream bytes = new ByteArrayInputStream(stream.array()); + bytes.skip(stream.readerIndex()); + final NBTTagCompound comp = CompressedStreamTools.readCompressed(bytes); + if (comp != null) { + this.recipe = new ItemStack[9][]; + for (int x = 0; x < this.recipe.length; x++) { + final NBTTagList list = comp.getTagList("#" + x, 10); + if (list.tagCount() > 0) { + this.recipe[x] = new ItemStack[list.tagCount()]; + for (int y = 0; y < list.tagCount(); y++) { + this.recipe[x][y] + = ItemStack.loadItemStackFromNBT(list.getCompoundTagAt(y)); + } + } + } + } + } -public class PacketNEIRecipe extends AppEngPacket -{ + // api + public PacketNEIRecipe(final NBTTagCompound recipe) throws IOException { + final ByteBuf data = Unpooled.buffer(); - private ItemStack[][] recipe; + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream outputStream = new DataOutputStream(bytes); - // automatic. - public PacketNEIRecipe( final ByteBuf stream ) throws IOException - { - final ByteArrayInputStream bytes = new ByteArrayInputStream( stream.array() ); - bytes.skip( stream.readerIndex() ); - final NBTTagCompound comp = CompressedStreamTools.readCompressed( bytes ); - if( comp != null ) - { - this.recipe = new ItemStack[9][]; - for( int x = 0; x < this.recipe.length; x++ ) - { - final NBTTagList list = comp.getTagList( "#" + x, 10 ); - if( list.tagCount() > 0 ) - { - this.recipe[x] = new ItemStack[list.tagCount()]; - for( int y = 0; y < list.tagCount(); y++ ) - { - this.recipe[x][y] = ItemStack.loadItemStackFromNBT( list.getCompoundTagAt( y ) ); - } - } - } - } - } + data.writeInt(this.getPacketID()); - // api - public PacketNEIRecipe( final NBTTagCompound recipe ) throws IOException - { - final ByteBuf data = Unpooled.buffer(); + CompressedStreamTools.writeCompressed(recipe, outputStream); + data.writeBytes(bytes.toByteArray()); - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream outputStream = new DataOutputStream( bytes ); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final EntityPlayerMP pmp = (EntityPlayerMP) player; + final Container con = pmp.openContainer; - CompressedStreamTools.writeCompressed( recipe, outputStream ); - data.writeBytes( bytes.toByteArray() ); + if (con instanceof IContainerCraftingPacket) { + final IContainerCraftingPacket cct = (IContainerCraftingPacket) con; + final IGridNode node = cct.getNetworkNode(); + if (node != null) { + final IGrid grid = node.getGrid(); + if (grid == null) { + return; + } - this.configureWrite( data ); - } + final IStorageGrid inv = grid.getCache(IStorageGrid.class); + final IEnergyGrid energy = grid.getCache(IEnergyGrid.class); + final ISecurityGrid security = grid.getCache(ISecurityGrid.class); + final IInventory craftMatrix = cct.getInventoryByName("crafting"); + final IInventory playerInventory = cct.getInventoryByName("player"); - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP pmp = (EntityPlayerMP) player; - final Container con = pmp.openContainer; + final Actionable realForFake + = cct.useRealItems() ? Actionable.MODULATE : Actionable.SIMULATE; - if( con instanceof IContainerCraftingPacket ) - { - final IContainerCraftingPacket cct = (IContainerCraftingPacket) con; - final IGridNode node = cct.getNetworkNode(); - if( node != null ) - { - final IGrid grid = node.getGrid(); - if( grid == null ) - { - return; - } + if (inv != null && this.recipe != null && security != null) { + final InventoryCrafting testInv + = new InventoryCrafting(new ContainerNull(), 3, 3); + for (int x = 0; x < 9; x++) { + if (this.recipe[x] != null && this.recipe[x].length > 0) { + testInv.setInventorySlotContents(x, this.recipe[x][0]); + } + } - final IStorageGrid inv = grid.getCache( IStorageGrid.class ); - final IEnergyGrid energy = grid.getCache( IEnergyGrid.class ); - final ISecurityGrid security = grid.getCache( ISecurityGrid.class ); - final IInventory craftMatrix = cct.getInventoryByName( "crafting" ); - final IInventory playerInventory = cct.getInventoryByName( "player" ); + final IRecipe r = Platform.findMatchingRecipe(testInv, pmp.worldObj); - final Actionable realForFake = cct.useRealItems() ? Actionable.MODULATE : Actionable.SIMULATE; + if (r != null + && security.hasPermission(player, SecurityPermissions.EXTRACT)) { + final ItemStack is = r.getCraftingResult(testInv); - if( inv != null && this.recipe != null && security != null ) - { - final InventoryCrafting testInv = new InventoryCrafting( new ContainerNull(), 3, 3 ); - for( int x = 0; x < 9; x++ ) - { - if( this.recipe[x] != null && this.recipe[x].length > 0 ) - { - testInv.setInventorySlotContents( x, this.recipe[x][0] ); - } - } + if (is != null) { + final IMEMonitor storage + = inv.getItemInventory(); + final IItemList all = storage.getStorageList(); + final IPartitionList filter + = ItemViewCell.createFilter(cct.getViewCells()); - final IRecipe r = Platform.findMatchingRecipe( testInv, pmp.worldObj ); + for (int x = 0; x < craftMatrix.getSizeInventory(); x++) { + final ItemStack patternItem = testInv.getStackInSlot(x); - if( r != null && security.hasPermission( player, SecurityPermissions.EXTRACT ) ) - { - final ItemStack is = r.getCraftingResult( testInv ); + ItemStack currentItem = craftMatrix.getStackInSlot(x); + if (currentItem != null) { + testInv.setInventorySlotContents(x, currentItem); + final ItemStack newItemStack + = r.matches(testInv, pmp.worldObj) + ? r.getCraftingResult(testInv) + : null; + testInv.setInventorySlotContents(x, patternItem); - if( is != null ) - { - final IMEMonitor storage = inv.getItemInventory(); - final IItemList all = storage.getStorageList(); - final IPartitionList filter = ItemViewCell.createFilter( cct.getViewCells() ); + if (newItemStack == null + || !Platform.isSameItemPrecise( + newItemStack, is + )) { + final IAEItemStack in + = AEItemStack.create(currentItem); + if (in != null) { + final IAEItemStack out + = realForFake == Actionable.SIMULATE + ? null + : Platform.poweredInsert( + energy, + storage, + in, + cct.getActionSource() + ); + if (out != null) { + craftMatrix.setInventorySlotContents( + x, out.getItemStack() + ); + } else { + craftMatrix.setInventorySlotContents( + x, null + ); + } - for( int x = 0; x < craftMatrix.getSizeInventory(); x++ ) - { - final ItemStack patternItem = testInv.getStackInSlot( x ); + currentItem = craftMatrix.getStackInSlot(x); + } + } + } - ItemStack currentItem = craftMatrix.getStackInSlot( x ); - if( currentItem != null ) - { - testInv.setInventorySlotContents( x, currentItem ); - final ItemStack newItemStack = r.matches( testInv, pmp.worldObj ) ? r.getCraftingResult( testInv ) : null; - testInv.setInventorySlotContents( x, patternItem ); + // True if we need to fetch an item for the recipe + if (patternItem != null && currentItem == null) { + // Grab from network by recipe + ItemStack whichItem = Platform.extractItemsByRecipe( + energy, + cct.getActionSource(), + storage, + player.worldObj, + r, + is, + testInv, + patternItem, + x, + all, + realForFake, + filter + ); - if( newItemStack == null || !Platform.isSameItemPrecise( newItemStack, is ) ) - { - final IAEItemStack in = AEItemStack.create( currentItem ); - if( in != null ) - { - final IAEItemStack out = realForFake == Actionable.SIMULATE ? null : Platform.poweredInsert( energy, storage, in, cct.getActionSource() ); - if( out != null ) - { - craftMatrix.setInventorySlotContents( x, out.getItemStack() ); - } - else - { - craftMatrix.setInventorySlotContents( x, null ); - } + // If that doesn't get it, grab exact items from + // network (?) + // TODO see if this code is necessary + if (whichItem == null) { + for (int y = 0; y < this.recipe[x].length; y++) { + final IAEItemStack request + = AEItemStack.create(this.recipe[x][y]); + if (request != null) { + if (filter == null + || filter.isListed(request)) { + request.setStackSize(1); + final IAEItemStack out + = Platform.poweredExtraction( + energy, + storage, + request, + cct.getActionSource() + ); + if (out != null) { + whichItem = out.getItemStack(); + break; + } + } + } + } + } - currentItem = craftMatrix.getStackInSlot( x ); - } - } - } + // If that doesn't work, grab from the player's + // inventory + if (whichItem == null && playerInventory != null) { + whichItem = this.extractItemFromPlayerInventory( + player, realForFake, patternItem + ); + } - // True if we need to fetch an item for the recipe - if( patternItem != null && currentItem == null ) - { - // Grab from network by recipe - ItemStack whichItem = Platform.extractItemsByRecipe( energy, cct.getActionSource(), storage, player.worldObj, r, is, testInv, patternItem, x, all, realForFake, filter ); + craftMatrix.setInventorySlotContents(x, whichItem); + } + } + con.onCraftMatrixChanged(craftMatrix); + } + } + } + } + } + } - // If that doesn't get it, grab exact items from network (?) - // TODO see if this code is necessary - if( whichItem == null ) - { - for( int y = 0; y < this.recipe[x].length; y++ ) - { - final IAEItemStack request = AEItemStack.create( this.recipe[x][y] ); - if( request != null ) - { - if( filter == null || filter.isListed( request ) ) - { - request.setStackSize( 1 ); - final IAEItemStack out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() ); - if( out != null ) - { - whichItem = out.getItemStack(); - break; - } - } - } - } - } + /** + * Tries to extract an item from the player inventory. Does account for fuzzy items. + * + * @param player the {@link EntityPlayer} to extract from + * @param mode the {@link Actionable} to simulate or modulate the operation + * @param patternItem which {@link ItemStack} to extract + * @return null or a found {@link ItemStack} + */ + private ItemStack extractItemFromPlayerInventory( + final EntityPlayer player, final Actionable mode, final ItemStack patternItem + ) { + final InventoryAdaptor ia + = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + final AEItemStack request = AEItemStack.create(patternItem); + final boolean isSimulated = mode == Actionable.SIMULATE; + final boolean checkFuzzy = request.isOre() + || patternItem.getItemDamage() == OreDictionary.WILDCARD_VALUE + || patternItem.hasTagCompound() || patternItem.isItemStackDamageable(); - // If that doesn't work, grab from the player's inventory - if( whichItem == null && playerInventory != null ) - { - whichItem = this.extractItemFromPlayerInventory( player, realForFake, patternItem ); - } - - craftMatrix.setInventorySlotContents( x, whichItem ); - } - } - con.onCraftMatrixChanged( craftMatrix ); - } - } - } - } - } - } - - /** - * Tries to extract an item from the player inventory. Does account for fuzzy items. - * - * @param player the {@link EntityPlayer} to extract from - * @param mode the {@link Actionable} to simulate or modulate the operation - * @param patternItem which {@link ItemStack} to extract - * @return null or a found {@link ItemStack} - */ - private ItemStack extractItemFromPlayerInventory( final EntityPlayer player, final Actionable mode, final ItemStack patternItem ) - { - final InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - final AEItemStack request = AEItemStack.create( patternItem ); - final boolean isSimulated = mode == Actionable.SIMULATE; - final boolean checkFuzzy = request.isOre() || patternItem.getItemDamage() == OreDictionary.WILDCARD_VALUE || patternItem.hasTagCompound() || patternItem.isItemStackDamageable(); - - if( !checkFuzzy ) - { - if( isSimulated ) - { - return ia.simulateRemove( 1, patternItem, null ); - } - else - { - return ia.removeItems( 1, patternItem, null ); - } - } - else - { - if( isSimulated ) - { - return ia.simulateSimilarRemove( 1, patternItem, FuzzyMode.IGNORE_ALL, null ); - } - else - { - return ia.removeSimilarItems( 1, patternItem, FuzzyMode.IGNORE_ALL, null ); - } - } - } + if (!checkFuzzy) { + if (isSimulated) { + return ia.simulateRemove(1, patternItem, null); + } else { + return ia.removeItems(1, patternItem, null); + } + } else { + if (isSimulated) { + return ia.simulateSimilarRemove( + 1, patternItem, FuzzyMode.IGNORE_ALL, null + ); + } else { + return ia.removeSimilarItems(1, patternItem, FuzzyMode.IGNORE_ALL, null); + } + } + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java b/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java index 29e911ba..b366e339 100644 --- a/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java +++ b/src/main/java/appeng/core/sync/packets/PacketNewStorageDimension.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.AEConfig; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -29,42 +28,37 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.common.DimensionManager; +public class PacketNewStorageDimension extends AppEngPacket { + private final int newDim; -public class PacketNewStorageDimension extends AppEngPacket -{ + // automatic. + public PacketNewStorageDimension(final ByteBuf stream) { + this.newDim = stream.readInt(); + } - private final int newDim; + // api + public PacketNewStorageDimension(final int newDim) { + this.newDim = newDim; - // automatic. - public PacketNewStorageDimension( final ByteBuf stream ) - { - this.newDim = stream.readInt(); - } + final ByteBuf data = Unpooled.buffer(); - // api - public PacketNewStorageDimension( final int newDim ) - { - this.newDim = newDim; + data.writeInt(this.getPacketID()); + data.writeInt(newDim); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeInt( newDim ); - - this.configureWrite( data ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - try - { - DimensionManager.registerDimension( this.newDim, AEConfig.instance.storageProviderID ); - } - catch( final IllegalArgumentException iae ) - { - // ok! - } - } + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + try { + DimensionManager.registerDimension( + this.newDim, AEConfig.instance.storageProviderID + ); + } catch (final 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 78ff4387..2f29a33f 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java +++ b/src/main/java/appeng/core/sync/packets/PacketPaintedEntity.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.api.util.AEColor; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -28,40 +27,37 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketPaintedEntity extends AppEngPacket { + private final AEColor myColor; + private final int entityId; + private int ticks; -public class PacketPaintedEntity extends AppEngPacket -{ + // automatic. + public PacketPaintedEntity(final ByteBuf stream) { + this.entityId = stream.readInt(); + this.myColor = AEColor.values()[stream.readByte()]; + this.ticks = stream.readInt(); + } - private final AEColor myColor; - private final int entityId; - private int ticks; + // api + public PacketPaintedEntity( + final int myEntity, final AEColor myColor, final int ticksLeft + ) { + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketPaintedEntity( final ByteBuf stream ) - { - this.entityId = stream.readInt(); - this.myColor = AEColor.values()[stream.readByte()]; - this.ticks = stream.readInt(); - } + data.writeInt(this.getPacketID()); + data.writeInt(this.entityId = myEntity); + data.writeByte((this.myColor = myColor).ordinal()); + data.writeInt(ticksLeft); - // api - public PacketPaintedEntity( final int myEntity, final AEColor myColor, final int ticksLeft ) - { + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); - - data.writeInt( this.getPacketID() ); - data.writeInt( this.entityId = myEntity ); - data.writeByte( ( this.myColor = myColor ).ordinal() ); - data.writeInt( ticksLeft ); - - this.configureWrite( data ); - } - - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final PlayerColor pc = new PlayerColor( this.entityId, this.myColor, this.ticks ); - TickHandler.INSTANCE.getPlayerColors().put( this.entityId, pc ); - } + @Override + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final 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 3a6f3557..f668f2b9 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java +++ b/src/main/java/appeng/core/sync/packets/PacketPartPlacement.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.core.CommonHelper; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -28,48 +27,56 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; +public class PacketPartPlacement extends AppEngPacket { + private int x; + private int y; + private int z; + private int face; + private float eyeHeight; -public class PacketPartPlacement extends AppEngPacket -{ + // automatic. + public PacketPartPlacement(final ByteBuf stream) { + this.x = stream.readInt(); + this.y = stream.readInt(); + this.z = stream.readInt(); + this.face = stream.readByte(); + this.eyeHeight = stream.readFloat(); + } - private int x; - private int y; - private int z; - private int face; - private float eyeHeight; + // api + public PacketPartPlacement( + final int x, final int y, final int z, final int face, final float eyeHeight + ) { + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketPartPlacement( final ByteBuf stream ) - { - this.x = stream.readInt(); - this.y = stream.readInt(); - this.z = stream.readInt(); - this.face = stream.readByte(); - this.eyeHeight = stream.readFloat(); - } + data.writeInt(this.getPacketID()); + data.writeInt(x); + data.writeInt(y); + data.writeInt(z); + data.writeByte(face); + data.writeFloat(eyeHeight); - // api - public PacketPartPlacement( final int x, final int y, final int z, final int face, final float eyeHeight ) - { - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeInt( x ); - data.writeInt( y ); - data.writeInt( z ); - data.writeByte( face ); - data.writeFloat( eyeHeight ); - - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - CommonHelper.proxy.updateRenderMode( sender ); - PartPlacement.setEyeHeight( 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 ); - } + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + CommonHelper.proxy.updateRenderMode(sender); + PartPlacement.setEyeHeight(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 1fd9e0fc..ef729f6a 100644 --- a/src/main/java/appeng/core/sync/packets/PacketPartialItem.java +++ b/src/main/java/appeng/core/sync/packets/PacketPartialItem.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -26,57 +25,48 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketPartialItem extends AppEngPacket { + private final short pageNum; + private final byte[] data; -public class PacketPartialItem extends AppEngPacket -{ + // automatic. + public PacketPartialItem(final ByteBuf stream) { + this.pageNum = stream.readShort(); + stream.readBytes(this.data = new byte[stream.readableBytes()]); + } - private final short pageNum; - private final byte[] data; + // api + public PacketPartialItem(final int page, final int maxPages, final byte[] buf) { + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketPartialItem( final ByteBuf stream ) - { - this.pageNum = stream.readShort(); - stream.readBytes( this.data = new byte[stream.readableBytes()] ); - } + this.pageNum = (short) (page | (maxPages << 8)); + this.data = buf; + data.writeInt(this.getPacketID()); + data.writeShort(this.pageNum); + data.writeBytes(buf); - // api - public PacketPartialItem( final int page, final int maxPages, final byte[] buf ) - { + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + if (player.openContainer instanceof AEBaseContainer) { + ((AEBaseContainer) player.openContainer).postPartial(this); + } + } - this.pageNum = (short) ( page | ( maxPages << 8 ) ); - this.data = buf; - data.writeInt( this.getPacketID() ); - data.writeShort( this.pageNum ); - data.writeBytes( buf ); + public int getPageCount() { + return this.pageNum >> 8; + } - this.configureWrite( data ); - } + public int getSize() { + return this.data.length; + } - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player.openContainer instanceof AEBaseContainer ) - { - ( (AEBaseContainer) player.openContainer ).postPartial( this ); - } - } - - public int getPageCount() - { - return this.pageNum >> 8; - } - - public int getSize() - { - return this.data.length; - } - - public int write( final byte[] buffer, final int cursor ) - { - System.arraycopy( this.data, 0, buffer, cursor, this.data.length ); - return cursor + this.data.length; - } + public int write(final byte[] buffer, final 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 02a2dfa6..403caa2d 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 appeng.api.AEApi; import appeng.api.storage.data.IAEItemStack; @@ -31,88 +32,76 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.IInventory; -import java.io.IOException; +public class PacketPatternSlot extends AppEngPacket { + public final IAEItemStack slotItem; + public final IAEItemStack[] pattern = new IAEItemStack[9]; -public class PacketPatternSlot extends AppEngPacket -{ + public final boolean shift; - public final IAEItemStack slotItem; + // automatic. + public PacketPatternSlot(final ByteBuf stream) throws IOException { + this.shift = stream.readBoolean(); - public final IAEItemStack[] pattern = new IAEItemStack[9]; + this.slotItem = this.readItem(stream); - public final boolean shift; + for (int x = 0; x < 9; x++) { + this.pattern[x] = this.readItem(stream); + } + } - // automatic. - public PacketPatternSlot( final ByteBuf stream ) throws IOException - { + private IAEItemStack readItem(final ByteBuf stream) throws IOException { + final boolean hasItem = stream.readBoolean(); - this.shift = stream.readBoolean(); + if (hasItem) { + return AEItemStack.loadItemStackFromPacket(stream); + } - this.slotItem = this.readItem( stream ); + return null; + } - for( int x = 0; x < 9; x++ ) - { - this.pattern[x] = this.readItem( stream ); - } - } + // api + public PacketPatternSlot( + final IInventory pat, final IAEItemStack slotItem, final boolean shift + ) throws IOException { + this.slotItem = slotItem; + this.shift = shift; - private IAEItemStack readItem( final ByteBuf stream ) throws IOException - { - final boolean hasItem = stream.readBoolean(); + final ByteBuf data = Unpooled.buffer(); - if( hasItem ) - { - return AEItemStack.loadItemStackFromPacket( stream ); - } + data.writeInt(this.getPacketID()); - return null; - } + data.writeBoolean(shift); - // api - public PacketPatternSlot( final IInventory pat, final IAEItemStack slotItem, final boolean shift ) throws IOException - { + this.writeItem(slotItem, data); + for (int x = 0; x < 9; x++) { + this.pattern[x] + = AEApi.instance().storage().createItemStack(pat.getStackInSlot(x)); + this.writeItem(this.pattern[x], data); + } - this.slotItem = slotItem; - this.shift = shift; + this.configureWrite(data); + } - final ByteBuf data = Unpooled.buffer(); + private void writeItem(final IAEItemStack slotItem, final ByteBuf data) + throws IOException { + if (slotItem == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + slotItem.writeToPacket(data); + } + } - data.writeInt( this.getPacketID() ); - - data.writeBoolean( shift ); - - this.writeItem( slotItem, data ); - for( int x = 0; x < 9; x++ ) - { - this.pattern[x] = AEApi.instance().storage().createItemStack( pat.getStackInSlot( x ) ); - this.writeItem( this.pattern[x], data ); - } - - this.configureWrite( data ); - } - - private void writeItem( final IAEItemStack slotItem, final ByteBuf data ) throws IOException - { - if( slotItem == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - slotItem.writeToPacket( data ); - } - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final EntityPlayerMP sender = (EntityPlayerMP) player; - if( sender.openContainer instanceof ContainerPatternTerm ) - { - final ContainerPatternTerm patternTerminal = (ContainerPatternTerm) sender.openContainer; - patternTerminal.craftOrGetItem( this ); - } - } + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final EntityPlayerMP sender = (EntityPlayerMP) player; + if (sender.openContainer instanceof ContainerPatternTerm) { + final 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 4c0ec163..3ed11f45 100644 --- a/src/main/java/appeng/core/sync/packets/PacketProgressBar.java +++ b/src/main/java/appeng/core/sync/packets/PacketProgressBar.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -27,52 +26,47 @@ import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; +public class PacketProgressBar extends AppEngPacket { + private final short id; + private final long value; -public class PacketProgressBar extends AppEngPacket -{ + // automatic. + public PacketProgressBar(final ByteBuf stream) { + this.id = stream.readShort(); + this.value = stream.readLong(); + } - private final short id; - private final long value; + // api + public PacketProgressBar(final int shortID, final long value) { + this.id = (short) shortID; + this.value = value; - // automatic. - public PacketProgressBar( final ByteBuf stream ) - { - this.id = stream.readShort(); - this.value = stream.readLong(); - } + final ByteBuf data = Unpooled.buffer(); - // api - public PacketProgressBar( final int shortID, final long value ) - { - this.id = (short) shortID; - this.value = value; + data.writeInt(this.getPacketID()); + data.writeShort(shortID); + data.writeLong(value); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeShort( shortID ); - data.writeLong( value ); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + ((AEBaseContainer) c).updateFullProgressBar(this.id, this.value); + } + } - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); - } - } - - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).updateFullProgressBar( this.id, this.value ); - } - } + @Override + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final 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 d8aff31a..297db403 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwapSlots.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.container.AEBaseContainer; import appeng.core.sync.AppEngPacket; import appeng.core.sync.network.INetworkInfo; @@ -26,38 +25,34 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; +public class PacketSwapSlots extends AppEngPacket { + private final int slotA; + private final int slotB; -public class PacketSwapSlots extends AppEngPacket -{ + // automatic. + public PacketSwapSlots(final ByteBuf stream) { + this.slotA = stream.readInt(); + this.slotB = stream.readInt(); + } - private final int slotA; - private final int slotB; + // api + public PacketSwapSlots(final int slotA, final int slotB) { + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketSwapSlots( final ByteBuf stream ) - { - this.slotA = stream.readInt(); - this.slotB = stream.readInt(); - } + data.writeInt(this.getPacketID()); + data.writeInt(this.slotA = slotA); + data.writeInt(this.slotB = slotB); - // api - public PacketSwapSlots( final int slotA, final int slotB ) - { - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeInt( this.slotA = slotA ); - data.writeInt( this.slotB = slotB ); - - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - if( player != null && player.openContainer instanceof AEBaseContainer ) - { - ( (AEBaseContainer) player.openContainer ).swapSlotContents( this.slotA, this.slotB ); - } - } + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final 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 388e9a3b..30046e76 100644 --- a/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java +++ b/src/main/java/appeng/core/sync/packets/PacketSwitchGuis.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.gui.AEBaseGui; import appeng.container.AEBaseContainer; import appeng.container.ContainerOpenContext; @@ -32,55 +31,49 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.tileentity.TileEntity; +public class PacketSwitchGuis extends AppEngPacket { + private final GuiBridge newGui; -public class PacketSwitchGuis extends AppEngPacket -{ + // automatic. + public PacketSwitchGuis(final ByteBuf stream) { + this.newGui = GuiBridge.values()[stream.readInt()]; + } - private final GuiBridge newGui; + // api + public PacketSwitchGuis(final GuiBridge newGui) { + this.newGui = newGui; - // automatic. - public PacketSwitchGuis( final ByteBuf stream ) - { - this.newGui = GuiBridge.values()[stream.readInt()]; - } + if (Platform.isClient()) { + AEBaseGui.setSwitchingGuis(true); + } - // api - public PacketSwitchGuis( final GuiBridge newGui ) - { - this.newGui = newGui; + final ByteBuf data = Unpooled.buffer(); - if( Platform.isClient() ) - { - AEBaseGui.setSwitchingGuis( true ); - } + data.writeInt(this.getPacketID()); + data.writeInt(newGui.ordinal()); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeInt( newGui.ordinal() ); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final Container c = player.openContainer; + if (c instanceof AEBaseContainer) { + final AEBaseContainer bc = (AEBaseContainer) c; + final ContainerOpenContext context = bc.getOpenContext(); + if (context != null) { + final TileEntity te = context.getTile(); + Platform.openGUI(player, te, context.getSide(), this.newGui); + } + } + } - this.configureWrite( data ); - } - - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; - if( c instanceof AEBaseContainer ) - { - final AEBaseContainer bc = (AEBaseContainer) c; - final ContainerOpenContext context = bc.getOpenContext(); - if( context != null ) - { - final TileEntity te = context.getTile(); - Platform.openGUI( player, te, context.getSide(), this.newGui ); - } - } - } - - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - AEBaseGui.setSwitchingGuis( true ); - } + @Override + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + AEBaseGui.setSwitchingGuis(true); + } } diff --git a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java index cfd56b85..c9242e79 100644 --- a/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java +++ b/src/main/java/appeng/core/sync/packets/PacketTransitionEffect.java @@ -18,7 +18,6 @@ package appeng.core.sync.packets; - import appeng.client.ClientHelper; import appeng.client.render.effects.EnergyFx; import appeng.core.CommonHelper; @@ -38,77 +37,96 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class PacketTransitionEffect extends AppEngPacket { + private final boolean mode; + private final double x; + private final double y; + private final double z; + private final ForgeDirection d; -public class PacketTransitionEffect extends AppEngPacket -{ + // automatic. + public PacketTransitionEffect(final ByteBuf stream) { + this.x = stream.readFloat(); + this.y = stream.readFloat(); + this.z = stream.readFloat(); + this.d = ForgeDirection.getOrientation(stream.readByte()); + this.mode = stream.readBoolean(); + } - private final boolean mode; - private final double x; - private final double y; - private final double z; - private final ForgeDirection d; + // api + public PacketTransitionEffect( + final double x, + final double y, + final double z, + final ForgeDirection dir, + final boolean wasBlock + ) { + this.x = x; + this.y = y; + this.z = z; + this.d = dir; + this.mode = wasBlock; - // automatic. - public PacketTransitionEffect( final ByteBuf stream ) - { - this.x = stream.readFloat(); - this.y = stream.readFloat(); - this.z = stream.readFloat(); - this.d = ForgeDirection.getOrientation( stream.readByte() ); - this.mode = stream.readBoolean(); - } + final ByteBuf data = Unpooled.buffer(); - // api - public PacketTransitionEffect( final double x, final double y, final double z, final ForgeDirection dir, final boolean wasBlock ) - { - this.x = x; - this.y = y; - this.z = z; - this.d = dir; - this.mode = wasBlock; + data.writeInt(this.getPacketID()); + data.writeFloat((float) x); + data.writeFloat((float) y); + data.writeFloat((float) z); + data.writeByte(this.d.ordinal()); + data.writeBoolean(wasBlock); - final ByteBuf data = Unpooled.buffer(); + this.configureWrite(data); + } - data.writeInt( this.getPacketID() ); - data.writeFloat( (float) x ); - data.writeFloat( (float) y ); - data.writeFloat( (float) z ); - data.writeByte( this.d.ordinal() ); - data.writeBoolean( wasBlock ); + @Override + @SideOnly(Side.CLIENT) + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final World world = ClientHelper.proxy.getWorld(); - this.configureWrite( data ); - } + for (int zz = 0; zz < (this.mode ? 32 : 8); zz++) { + if (CommonHelper.proxy.shouldAddParticles(Platform.getRandom())) { + final 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 + ); - @Override - @SideOnly( Side.CLIENT ) - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final World world = ClientHelper.proxy.getWorld(); + if (!this.mode) { + fx.fromItem(this.d); + } - for( int zz = 0; zz < ( this.mode ? 32 : 8 ); zz++ ) - { - if( CommonHelper.proxy.shouldAddParticles( Platform.getRandom() ) ) - { - final 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 ); + fx.motionX = -0.1 * this.d.offsetX; + fx.motionY = -0.1 * this.d.offsetY; + fx.motionZ = -0.1 * this.d.offsetZ; - if( !this.mode ) - { - fx.fromItem( this.d ); - } + Minecraft.getMinecraft().effectRenderer.addEffect(fx); + } + } - fx.motionX = -0.1 * this.d.offsetX; - fx.motionY = -0.1 * this.d.offsetY; - fx.motionZ = -0.1 * this.d.offsetZ; + if (this.mode) { + final Block block = world.getBlock((int) this.x, (int) this.y, (int) this.z); - Minecraft.getMinecraft().effectRenderer.addEffect( fx ); - } - } - - if( this.mode ) - { - final 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 ) ); - } - } + 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 9be46b60..1d67524d 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.*; import appeng.api.config.FuzzyMode; import appeng.api.config.Settings; @@ -37,229 +38,163 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; -import java.io.*; +public class PacketValueConfig extends AppEngPacket { + private final String Name; + private final String Value; + // automatic. + public PacketValueConfig(final ByteBuf stream) throws IOException { + final DataInputStream dis = new DataInputStream(new ByteArrayInputStream( + stream.array(), stream.readerIndex(), stream.readableBytes() + )); + this.Name = dis.readUTF(); + this.Value = dis.readUTF(); + // dis.close(); + } -public class PacketValueConfig extends AppEngPacket -{ + // api + public PacketValueConfig(final String name, final String value) throws IOException { + this.Name = name; + this.Value = value; - private final String Name; - private final String Value; + final ByteBuf data = Unpooled.buffer(); - // automatic. - public PacketValueConfig( final ByteBuf stream ) throws IOException - { - final DataInputStream dis = new DataInputStream( new ByteArrayInputStream( stream.array(), stream.readerIndex(), stream.readableBytes() ) ); - this.Name = dis.readUTF(); - this.Value = dis.readUTF(); - // dis.close(); - } + data.writeInt(this.getPacketID()); - // api - public PacketValueConfig( final String name, final String value ) throws IOException - { - this.Name = name; - this.Value = value; + final ByteArrayOutputStream bos = new ByteArrayOutputStream(); + final DataOutputStream dos = new DataOutputStream(bos); + dos.writeUTF(name); + dos.writeUTF(value); + // dos.close(); - final ByteBuf data = Unpooled.buffer(); + data.writeBytes(bos.toByteArray()); - data.writeInt( this.getPacketID() ); + this.configureWrite(data); + } - final ByteArrayOutputStream bos = new ByteArrayOutputStream(); - final DataOutputStream dos = new DataOutputStream( bos ); - dos.writeUTF( name ); - dos.writeUTF( value ); - // dos.close(); + @Override + public void serverPacketData( + final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player + ) { + final Container c = player.openContainer; - data.writeBytes( bos.toByteArray() ); + if (this.Name.equals("Item") && player.getHeldItem() != null + && player.getHeldItem().getItem() instanceof IMouseWheelItem) { + final ItemStack is = player.getHeldItem(); + final IMouseWheelItem si = (IMouseWheelItem) is.getItem(); + si.onWheel(is, this.Value.equals("WheelUp")); + } else if (this.Name.equals("Terminal.Cpu") && c instanceof ContainerCraftingStatus) { + final ContainerCraftingStatus qk = (ContainerCraftingStatus) c; + qk.cycleCpu(this.Value.equals("Next")); + } else if (this.Name.equals("Terminal.Cpu") && c instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.cycleCpu(this.Value.equals("Next")); + } else if (this.Name.equals("Terminal.Start") && c instanceof ContainerCraftConfirm) { + final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; + qk.startJob(); + } else if (this.Name.equals("TileCrafting.Cancel") && c instanceof ContainerCraftingCPU) { + final ContainerCraftingCPU qk = (ContainerCraftingCPU) c; + qk.cancelCrafting(); + } else if (this.Name.equals("QuartzKnife.Name") && c instanceof ContainerQuartzKnife) { + final ContainerQuartzKnife qk = (ContainerQuartzKnife) c; + qk.setName(this.Value); + } else if (this.Name.equals("TileSecurity.ToggleOption") && c instanceof ContainerSecurity) { + final ContainerSecurity sc = (ContainerSecurity) c; + sc.toggleSetting(this.Value, player); + } else if (this.Name.equals("PriorityHost.Priority") && c instanceof ContainerPriority) { + final ContainerPriority pc = (ContainerPriority) c; + pc.setPriority(Integer.parseInt(this.Value), player); + } else if (this.Name.equals("LevelEmitter.Value") && c instanceof ContainerLevelEmitter) { + final ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; + lvc.setLevel(Long.parseLong(this.Value), player); + } else if (this.Name.startsWith("PatternTerminal.") && c instanceof ContainerPatternTerm) { + final ContainerPatternTerm cpt = (ContainerPatternTerm) c; + if (this.Name.equals("PatternTerminal.CraftMode")) { + cpt.getPatternTerminal().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.equals("PatternTerminal.Substitute")) { + cpt.getPatternTerminal().setSubstitution(this.Value.equals("1")); + } + } else if (this.Name.startsWith("StorageBus.") && c instanceof ContainerStorageBus) { + final 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) { + final ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; + if (this.Name.equals("CellWorkbench.Action")) { + if (this.Value.equals("CopyMode")) { + ccw.nextWorkBenchCopyMode(); + } 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) { + final IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); - this.configureWrite( data ); - } + for (final Settings e : cm.getSettings()) { + if (e.name().equals(this.Name)) { + final Enum def = cm.getSetting(e); - @Override - public void serverPacketData( final INetworkInfo manager, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; + try { + cm.putSetting(e, Enum.valueOf(def.getClass(), this.Value)); + } catch (final IllegalArgumentException err) { + // :P + } - if( this.Name.equals( "Item" ) && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IMouseWheelItem ) - { - final ItemStack is = player.getHeldItem(); - final IMouseWheelItem si = (IMouseWheelItem) is.getItem(); - si.onWheel( is, this.Value.equals( "WheelUp" ) ); - } - else if( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftingStatus ) - { - final ContainerCraftingStatus qk = (ContainerCraftingStatus) c; - qk.cycleCpu( this.Value.equals( "Next" ) ); - } - else if( this.Name.equals( "Terminal.Cpu" ) && c instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; - qk.cycleCpu( this.Value.equals( "Next" ) ); - } - else if( this.Name.equals( "Terminal.Start" ) && c instanceof ContainerCraftConfirm ) - { - final ContainerCraftConfirm qk = (ContainerCraftConfirm) c; - qk.startJob(); - } - else if( this.Name.equals( "TileCrafting.Cancel" ) && c instanceof ContainerCraftingCPU ) - { - final ContainerCraftingCPU qk = (ContainerCraftingCPU) c; - qk.cancelCrafting(); - } - else if( this.Name.equals( "QuartzKnife.Name" ) && c instanceof ContainerQuartzKnife ) - { - final ContainerQuartzKnife qk = (ContainerQuartzKnife) c; - qk.setName( this.Value ); - } - else if( this.Name.equals( "TileSecurity.ToggleOption" ) && c instanceof ContainerSecurity ) - { - final ContainerSecurity sc = (ContainerSecurity) c; - sc.toggleSetting( this.Value, player ); - } - else if( this.Name.equals( "PriorityHost.Priority" ) && c instanceof ContainerPriority ) - { - final ContainerPriority pc = (ContainerPriority) c; - pc.setPriority( Integer.parseInt( this.Value ), player ); - } - else if( this.Name.equals( "LevelEmitter.Value" ) && c instanceof ContainerLevelEmitter ) - { - final ContainerLevelEmitter lvc = (ContainerLevelEmitter) c; - lvc.setLevel( Long.parseLong( this.Value ), player ); - } - else if( this.Name.startsWith( "PatternTerminal." ) && c instanceof ContainerPatternTerm ) - { - final ContainerPatternTerm cpt = (ContainerPatternTerm) c; - if( this.Name.equals( "PatternTerminal.CraftMode" ) ) - { - cpt.getPatternTerminal().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.equals( "PatternTerminal.Substitute" ) ) - { - cpt.getPatternTerminal().setSubstitution( this.Value.equals( "1" ) ); - } - } - else if( this.Name.startsWith( "StorageBus." ) && c instanceof ContainerStorageBus ) - { - final 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 ) - { - final ContainerCellWorkbench ccw = (ContainerCellWorkbench) c; - if( this.Name.equals( "CellWorkbench.Action" ) ) - { - if( this.Value.equals( "CopyMode" ) ) - { - ccw.nextWorkBenchCopyMode(); - } - 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 ) - { - final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); + break; + } + } + } + } - for( final Settings e : cm.getSettings() ) - { - if( e.name().equals( this.Name ) ) - { - final Enum def = cm.getSetting( e ); + @Override + public void clientPacketData( + final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player + ) { + final Container c = player.openContainer; - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch( final IllegalArgumentException err ) - { - // :P - } + if (this.Name.equals("CustomName") && c instanceof AEBaseContainer) { + ((AEBaseContainer) c).setCustomName(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")) { + final GuiScreen gs = Minecraft.getMinecraft().currentScreen; + if (gs instanceof GuiCraftingCPU) { + ((GuiCraftingCPU) gs).clearItems(); + } + } else if (c instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) c).getConfigManager(); - break; - } - } - } - } + for (final Settings e : cm.getSettings()) { + if (e.name().equals(this.Name)) { + final Enum def = cm.getSetting(e); - @Override - public void clientPacketData( final INetworkInfo network, final AppEngPacket packet, final EntityPlayer player ) - { - final Container c = player.openContainer; + try { + cm.putSetting(e, Enum.valueOf(def.getClass(), this.Value)); + } catch (final IllegalArgumentException err) { + // :P + } - if( this.Name.equals( "CustomName" ) && c instanceof AEBaseContainer ) - { - ( (AEBaseContainer) c ).setCustomName( 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" ) ) - { - final GuiScreen gs = Minecraft.getMinecraft().currentScreen; - if( gs instanceof GuiCraftingCPU ) - { - ( (GuiCraftingCPU) gs ).clearItems(); - } - } - else if( c instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) c ).getConfigManager(); - - for( final Settings e : cm.getSettings() ) - { - if( e.name().equals( this.Name ) ) - { - final Enum def = cm.getSetting( e ); - - try - { - cm.putSetting( e, Enum.valueOf( def.getClass(), this.Value ) ); - } - catch( final IllegalArgumentException err ) - { - // :P - } - - break; - } - } - } - } + break; + } + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/CompassData.java b/src/main/java/appeng/core/worlddata/CompassData.java index aaf7aaf1..9cba6176 100644 --- a/src/main/java/appeng/core/worlddata/CompassData.java +++ b/src/main/java/appeng/core/worlddata/CompassData.java @@ -18,41 +18,37 @@ package appeng.core.worlddata; +import java.io.File; +import javax.annotation.Nonnull; import appeng.services.CompassService; import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import java.io.File; - - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class CompassData implements IWorldCompassData, IOnWorldStoppable -{ - @Nonnull - private final CompassService service; +final class CompassData implements IWorldCompassData, IOnWorldStoppable { + @Nonnull + private final CompassService service; - public CompassData( @Nonnull final File compassDirectory, @Nonnull final CompassService service ) - { - Preconditions.checkNotNull( compassDirectory ); - Preconditions.checkNotNull( service ); + public CompassData( + @Nonnull final File compassDirectory, @Nonnull final CompassService service + ) { + Preconditions.checkNotNull(compassDirectory); + Preconditions.checkNotNull(service); - this.service = service; - } + this.service = service; + } - @Override - public CompassService service() - { - return this.service; - } + @Override + public CompassService service() { + return this.service; + } - @Override - public void onWorldStop() - { - this.service.kill(); - } + @Override + public void onWorldStop() { + this.service.kill(); + } } diff --git a/src/main/java/appeng/core/worlddata/DimensionData.java b/src/main/java/appeng/core/worlddata/DimensionData.java index 1b839647..1fb637f1 100644 --- a/src/main/java/appeng/core/worlddata/DimensionData.java +++ b/src/main/java/appeng/core/worlddata/DimensionData.java @@ -18,6 +18,9 @@ package appeng.core.worlddata; +import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.util.WorldCoord; import appeng.core.AEConfig; @@ -31,138 +34,131 @@ import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.List; - - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class DimensionData implements IWorldDimensionData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String CONFIG_CATEGORY = "DimensionManager"; - private static final String CONFIG_KEY = "StorageCells"; - private static final int[] STORAGE_CELLS_DEFAULT = new int[0]; +final class DimensionData + implements IWorldDimensionData, IOnWorldStartable, IOnWorldStoppable { + private static final String CONFIG_CATEGORY = "DimensionManager"; + private static final String CONFIG_KEY = "StorageCells"; + private static final int[] STORAGE_CELLS_DEFAULT = new int[0]; - private static final String STORAGE_CELL_CATEGORY = "StorageCell"; + private static final String STORAGE_CELL_CATEGORY = "StorageCell"; - private static final String STORAGE_CELL_SCALE_X_KEY = "scaleX"; - private static final String STORAGE_CELL_SCALE_Y_KEY = "scaleY"; - private static final String STORAGE_CELL_SCALE_Z_KEY = "scaleZ"; + private static final String STORAGE_CELL_SCALE_X_KEY = "scaleX"; + private static final String STORAGE_CELL_SCALE_Y_KEY = "scaleY"; + private static final String STORAGE_CELL_SCALE_Z_KEY = "scaleZ"; - private static final String PACKAGE_DEST_CATEGORY = "DimensionManager"; - private static final String PACKAGE_KEY_CATEGORY = "StorageCells"; - private static final int[] PACKAGE_DEF_CATEGORY = new int[0]; + private static final String PACKAGE_DEST_CATEGORY = "DimensionManager"; + private static final String PACKAGE_KEY_CATEGORY = "StorageCells"; + private static final int[] PACKAGE_DEF_CATEGORY = new int[0]; - private final Configuration config; - private final List storageCellDimensionIDs; + private final Configuration config; + private final List storageCellDimensionIDs; - DimensionData( @Nonnull final Configuration parentFile ) - { - Preconditions.checkNotNull( parentFile ); + DimensionData(@Nonnull final Configuration parentFile) { + Preconditions.checkNotNull(parentFile); - this.config = parentFile; + this.config = parentFile; - final int[] storageCellIDs = this.storageCellIDsProperty().getIntList(); + final int[] storageCellIDs = this.storageCellIDsProperty().getIntList(); - this.storageCellDimensionIDs = Lists.newArrayList(); - for( final int storageCellID : storageCellIDs ) - { - this.storageCellDimensionIDs.add( storageCellID ); - } - } + this.storageCellDimensionIDs = Lists.newArrayList(); + for (final int storageCellID : storageCellIDs) { + this.storageCellDimensionIDs.add(storageCellID); + } + } - private Property storageCellIDsProperty() - { - return this.config.get( CONFIG_CATEGORY, CONFIG_KEY, STORAGE_CELLS_DEFAULT ); - } + private Property storageCellIDsProperty() { + return this.config.get(CONFIG_CATEGORY, CONFIG_KEY, STORAGE_CELLS_DEFAULT); + } - @Override - public void onWorldStart() - { - for( final Integer storageCellDimID : this.storageCellDimensionIDs ) - { - DimensionManager.registerDimension( storageCellDimID, AEConfig.instance.storageProviderID ); - } + @Override + public void onWorldStart() { + for (final Integer storageCellDimID : this.storageCellDimensionIDs) { + DimensionManager.registerDimension( + storageCellDimID, AEConfig.instance.storageProviderID + ); + } - this.config.save(); - } + this.config.save(); + } - @Override - public void onWorldStop() - { - this.config.save(); + @Override + public void onWorldStop() { + this.config.save(); - for( final Integer storageCellDimID : this.storageCellDimensionIDs ) - { - DimensionManager.unregisterDimension( storageCellDimID ); - } + for (final Integer storageCellDimID : this.storageCellDimensionIDs) { + DimensionManager.unregisterDimension(storageCellDimID); + } - this.storageCellDimensionIDs.clear(); - } + this.storageCellDimensionIDs.clear(); + } - @Override - public void addStorageCell( final int newStorageCellID ) - { - this.storageCellDimensionIDs.add( newStorageCellID ); - DimensionManager.registerDimension( newStorageCellID, AEConfig.instance.storageProviderID ); + @Override + public void addStorageCell(final int newStorageCellID) { + this.storageCellDimensionIDs.add(newStorageCellID); + DimensionManager.registerDimension( + newStorageCellID, AEConfig.instance.storageProviderID + ); - NetworkHandler.instance.sendToAll( new PacketNewStorageDimension( newStorageCellID ) ); + NetworkHandler.instance.sendToAll(new PacketNewStorageDimension(newStorageCellID) + ); - final String[] values = new String[this.storageCellDimensionIDs.size()]; + final String[] values = new String[this.storageCellDimensionIDs.size()]; - for( int x = 0; x < values.length; x++ ) - { - values[x] = String.valueOf( this.storageCellDimensionIDs.get( x ) ); - } + for (int x = 0; x < values.length; x++) { + values[x] = String.valueOf(this.storageCellDimensionIDs.get(x)); + } - this.storageCellIDsProperty().set( values ); - this.config.save(); - } + this.storageCellIDsProperty().set(values); + this.config.save(); + } - @Override - public WorldCoord getStoredSize( final int dim ) - { - final String category = STORAGE_CELL_CATEGORY + dim; + @Override + public WorldCoord getStoredSize(final int dim) { + final String category = STORAGE_CELL_CATEGORY + dim; - final int x = this.config.get( category, STORAGE_CELL_SCALE_X_KEY, 0 ).getInt(); - final int y = this.config.get( category, STORAGE_CELL_SCALE_Y_KEY, 0 ).getInt(); - final int z = this.config.get( category, STORAGE_CELL_SCALE_Z_KEY, 0 ).getInt(); + final int x = this.config.get(category, STORAGE_CELL_SCALE_X_KEY, 0).getInt(); + final int y = this.config.get(category, STORAGE_CELL_SCALE_Y_KEY, 0).getInt(); + final int z = this.config.get(category, STORAGE_CELL_SCALE_Z_KEY, 0).getInt(); - return new WorldCoord( x, y, z ); - } + return new WorldCoord(x, y, z); + } - @Override - public void setStoredSize( final int dim, final int targetX, final int targetY, final int targetZ ) - { - final String category = STORAGE_CELL_CATEGORY + dim; + @Override + public void setStoredSize( + final int dim, final int targetX, final int targetY, final int targetZ + ) { + final String category = STORAGE_CELL_CATEGORY + dim; - this.config.get( category, STORAGE_CELL_SCALE_X_KEY, 0 ).set( targetX ); - this.config.get( category, STORAGE_CELL_SCALE_Y_KEY, 0 ).set( targetY ); - this.config.get( category, STORAGE_CELL_SCALE_Z_KEY, 0 ).set( targetZ ); + this.config.get(category, STORAGE_CELL_SCALE_X_KEY, 0).set(targetX); + this.config.get(category, STORAGE_CELL_SCALE_Y_KEY, 0).set(targetY); + this.config.get(category, STORAGE_CELL_SCALE_Z_KEY, 0).set(targetZ); - this.config.save(); - } + this.config.save(); + } - @Override - public void sendToPlayer( @Nullable final NetworkManager manager ) - { - if( manager != null ) - { - for( final int newDim : this.config.get( PACKAGE_DEST_CATEGORY, PACKAGE_KEY_CATEGORY, PACKAGE_DEF_CATEGORY ).getIntList() ) - { - manager.scheduleOutboundPacket( ( new PacketNewStorageDimension( newDim ) ).getProxy() ); - } - } - else - { - for( final TickHandler.PlayerColor pc : TickHandler.INSTANCE.getPlayerColors().values() ) - { - NetworkHandler.instance.sendToAll( pc.getPacket() ); - } - } - } + @Override + public void sendToPlayer(@Nullable final NetworkManager manager) { + if (manager != null) { + for (final int newDim : + this.config + .get( + PACKAGE_DEST_CATEGORY, PACKAGE_KEY_CATEGORY, PACKAGE_DEF_CATEGORY + ) + .getIntList()) { + manager.scheduleOutboundPacket( + (new PacketNewStorageDimension(newDim)).getProxy() + ); + } + } else { + for (final TickHandler.PlayerColor pc : + TickHandler.INSTANCE.getPlayerColors().values()) { + NetworkHandler.instance.sendToAll(pc.getPacket()); + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/IOnWorldStartable.java b/src/main/java/appeng/core/worlddata/IOnWorldStartable.java index b6c5c325..209076ae 100644 --- a/src/main/java/appeng/core/worlddata/IOnWorldStartable.java +++ b/src/main/java/appeng/core/worlddata/IOnWorldStartable.java @@ -18,13 +18,11 @@ package appeng.core.worlddata; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IOnWorldStartable -{ - void onWorldStart(); +public interface IOnWorldStartable { + void onWorldStart(); } diff --git a/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java b/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java index 7a36e771..c9e9d963 100644 --- a/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java +++ b/src/main/java/appeng/core/worlddata/IOnWorldStoppable.java @@ -18,13 +18,11 @@ package appeng.core.worlddata; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IOnWorldStoppable -{ - void onWorldStop(); +public interface IOnWorldStoppable { + void onWorldStop(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldCompassData.java b/src/main/java/appeng/core/worlddata/IWorldCompassData.java index c4b74b85..e9c4f14f 100644 --- a/src/main/java/appeng/core/worlddata/IWorldCompassData.java +++ b/src/main/java/appeng/core/worlddata/IWorldCompassData.java @@ -18,16 +18,13 @@ package appeng.core.worlddata; - import appeng.services.CompassService; - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldCompassData -{ - CompassService service(); +public interface IWorldCompassData { + CompassService service(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldData.java b/src/main/java/appeng/core/worlddata/IWorldData.java index bd24d3e3..b68020f6 100644 --- a/src/main/java/appeng/core/worlddata/IWorldData.java +++ b/src/main/java/appeng/core/worlddata/IWorldData.java @@ -18,33 +18,30 @@ package appeng.core.worlddata; - import javax.annotation.Nonnull; - /** * @author thatsIch * @version rv3 - 02.11.2015 * @since rv3 30.05.2015 */ -public interface IWorldData -{ - void onServerStopping(); +public interface IWorldData { + void onServerStopping(); - void onServerStoppped(); + void onServerStoppped(); - @Nonnull - IWorldGridStorageData storageData(); + @Nonnull + IWorldGridStorageData storageData(); - @Nonnull - IWorldPlayerData playerData(); + @Nonnull + IWorldPlayerData playerData(); - @Nonnull - IWorldDimensionData dimensionData(); + @Nonnull + IWorldDimensionData dimensionData(); - @Nonnull - IWorldCompassData compassData(); + @Nonnull + IWorldCompassData compassData(); - @Nonnull - IWorldSpawnData spawnData(); + @Nonnull + IWorldSpawnData spawnData(); } diff --git a/src/main/java/appeng/core/worlddata/IWorldDimensionData.java b/src/main/java/appeng/core/worlddata/IWorldDimensionData.java index ffbc1659..ac14496a 100644 --- a/src/main/java/appeng/core/worlddata/IWorldDimensionData.java +++ b/src/main/java/appeng/core/worlddata/IWorldDimensionData.java @@ -18,25 +18,22 @@ package appeng.core.worlddata; +import javax.annotation.Nullable; import appeng.api.util.WorldCoord; import net.minecraft.network.NetworkManager; -import javax.annotation.Nullable; - - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldDimensionData -{ - void addStorageCell( int newStorageCellID ); +public interface IWorldDimensionData { + void addStorageCell(int newStorageCellID); - WorldCoord getStoredSize( int dim ); + WorldCoord getStoredSize(int dim); - void setStoredSize( int dim, int targetX, int targetY, int targetZ ); + void setStoredSize(int dim, int targetX, int targetY, int targetZ); - void sendToPlayer( @Nullable NetworkManager manager ); + void sendToPlayer(@Nullable NetworkManager manager); } diff --git a/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java b/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java index 32767d10..85491b63 100644 --- a/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java +++ b/src/main/java/appeng/core/worlddata/IWorldGridStorageData.java @@ -18,29 +18,26 @@ package appeng.core.worlddata; - -import appeng.me.GridStorage; - import javax.annotation.Nonnull; import javax.annotation.Nullable; +import appeng.me.GridStorage; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldGridStorageData -{ - @Nullable - GridStorage getGridStorage( long storageID ); +public interface IWorldGridStorageData { + @Nullable + GridStorage getGridStorage(long storageID); - @Nonnull - GridStorage getNewGridStorage(); + @Nonnull + GridStorage getNewGridStorage(); - long nextGridStorage(); + long nextGridStorage(); - void destroyGridStorage( long id ); + void destroyGridStorage(long id); - int getNextOrderedValue( String name ); + int getNextOrderedValue(String name); } diff --git a/src/main/java/appeng/core/worlddata/IWorldPlayerData.java b/src/main/java/appeng/core/worlddata/IWorldPlayerData.java index 793a0d8a..baadffe4 100644 --- a/src/main/java/appeng/core/worlddata/IWorldPlayerData.java +++ b/src/main/java/appeng/core/worlddata/IWorldPlayerData.java @@ -18,22 +18,19 @@ package appeng.core.worlddata; +import javax.annotation.Nullable; import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; -import javax.annotation.Nullable; - - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldPlayerData -{ - @Nullable - EntityPlayer getPlayerFromID( int playerID ); +public interface IWorldPlayerData { + @Nullable + EntityPlayer getPlayerFromID(int playerID); - int getPlayerID( GameProfile profile ); + int getPlayerID(GameProfile profile); } diff --git a/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java b/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java index 7ae08fe9..79dd54ab 100644 --- a/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java +++ b/src/main/java/appeng/core/worlddata/IWorldPlayerMapping.java @@ -18,36 +18,33 @@ package appeng.core.worlddata; +import java.util.UUID; +import javax.annotation.Nonnull; import com.google.common.base.Optional; -import javax.annotation.Nonnull; -import java.util.UUID; - - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldPlayerMapping -{ - /** - * Tries to retrieve the UUID of a player. - * Might not be stored inside of the map. - * Should not happen though. - * - * @param id ID of the to be searched player - * @return maybe the UUID of the searched player - */ - @Nonnull - Optional get( int id ); +public interface IWorldPlayerMapping { + /** + * Tries to retrieve the UUID of a player. + * Might not be stored inside of the map. + * Should not happen though. + * + * @param id ID of the to be searched player + * @return maybe the UUID of the searched player + */ + @Nonnull + Optional get(int id); - /** - * Put in new players when they join the server - * - * @param id id of new player - * @param uuid UUID of new player - */ - void put( int id, @Nonnull UUID uuid ); + /** + * Put in new players when they join the server + * + * @param id id of new player + * @param uuid UUID of new player + */ + void put(int id, @Nonnull UUID uuid); } diff --git a/src/main/java/appeng/core/worlddata/IWorldSpawnData.java b/src/main/java/appeng/core/worlddata/IWorldSpawnData.java index cb945dde..8963c0b3 100644 --- a/src/main/java/appeng/core/worlddata/IWorldSpawnData.java +++ b/src/main/java/appeng/core/worlddata/IWorldSpawnData.java @@ -18,24 +18,21 @@ package appeng.core.worlddata; - -import net.minecraft.nbt.NBTTagCompound; - import java.util.Collection; +import net.minecraft.nbt.NBTTagCompound; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -public interface IWorldSpawnData -{ - void setGenerated( int dim, int chunkX, int chunkZ ); +public interface IWorldSpawnData { + void setGenerated(int dim, int chunkX, int chunkZ); - boolean hasGenerated( int dim, int chunkX, int chunkZ ); + boolean hasGenerated(int dim, int chunkX, int chunkZ); - boolean addNearByMeteorites( int dim, int chunkX, int chunkZ, NBTTagCompound newData ); + boolean addNearByMeteorites(int dim, int chunkX, int chunkZ, NBTTagCompound newData); - Collection getNearByMeteorites( int dim, int chunkX, int chunkZ ); + Collection getNearByMeteorites(int dim, int chunkX, int chunkZ); } diff --git a/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java b/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java index af20f029..bbf633a1 100644 --- a/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java +++ b/src/main/java/appeng/core/worlddata/MeteorDataNameEncoder.java @@ -18,11 +18,9 @@ package appeng.core.worlddata; - -import com.google.common.base.Preconditions; - import javax.annotation.Nonnull; +import com.google.common.base.Preconditions; /** * encodes data into a common name @@ -31,51 +29,63 @@ import javax.annotation.Nonnull; * @version rv3 - 05.06.2015 * @since rv3 05.06.2015 */ -public class MeteorDataNameEncoder -{ - private static final char DATA_SEPARATOR = '_'; - private static final char BASE_EXTENSION_SEPARATOR = '.'; - private static final String FILE_EXTENSION = "dat"; +public class MeteorDataNameEncoder { + private static final char DATA_SEPARATOR = '_'; + private static final char BASE_EXTENSION_SEPARATOR = '.'; + private static final String FILE_EXTENSION = "dat"; - private final char dataSeparator; - @Nonnull - private final String fileExtension; - private final char baseExtSeparator; - private final int bitScale; + private final char dataSeparator; + @Nonnull + private final String fileExtension; + private final char baseExtSeparator; + private final int bitScale; - /** - * @param bitScale how often the coordinates will be shifted right (will scale coordinates down) - */ - public MeteorDataNameEncoder( final int bitScale ) - { - this( DATA_SEPARATOR, BASE_EXTENSION_SEPARATOR, FILE_EXTENSION, bitScale ); - } + /** + * @param bitScale how often the coordinates will be shifted right (will scale + * coordinates down) + */ + public MeteorDataNameEncoder(final int bitScale) { + this(DATA_SEPARATOR, BASE_EXTENSION_SEPARATOR, FILE_EXTENSION, bitScale); + } - private MeteorDataNameEncoder( final char dataSeparator, final char baseExtSeparator, @Nonnull final String fileExtension, final int bitScale ) - { - Preconditions.checkNotNull( fileExtension ); - Preconditions.checkArgument( !fileExtension.isEmpty() ); - Preconditions.checkArgument( bitScale >= 0 ); + private MeteorDataNameEncoder( + final char dataSeparator, + final char baseExtSeparator, + @Nonnull final String fileExtension, + final int bitScale + ) { + Preconditions.checkNotNull(fileExtension); + Preconditions.checkArgument(!fileExtension.isEmpty()); + Preconditions.checkArgument(bitScale >= 0); - this.dataSeparator = dataSeparator; - this.baseExtSeparator = baseExtSeparator; - this.fileExtension = fileExtension; - this.bitScale = bitScale; - } + this.dataSeparator = dataSeparator; + this.baseExtSeparator = baseExtSeparator; + this.fileExtension = fileExtension; + this.bitScale = bitScale; + } - /** - * @param dimension ID of the processed dimension. Can be any integer - * @param chunkX X coordinate of the chunk. Can be any integer - * @param chunkZ Z coordinate of the chunk. Can be any integer - * @return encoded file name suggestion in form of dim_x_y.dat where x and y will be - * shifted to stay conform with the vanilla chunk system - * @since rv3 05.06.2015 - */ - public String encode( final int dimension, final int chunkX, final int chunkZ ) - { - final int shiftedX = chunkX >> this.bitScale; - final int shiftedZ = chunkZ >> this.bitScale; + /** + * @param dimension ID of the processed dimension. Can be any integer + * @param chunkX X coordinate of the chunk. Can be any integer + * @param chunkZ Z coordinate of the chunk. Can be any integer + * @return encoded file name suggestion in form of dim_x_y.dat where + * x and y will be + * shifted to stay conform with the vanilla chunk system + * @since rv3 05.06.2015 + */ + public String encode(final int dimension, final int chunkX, final int chunkZ) { + final int shiftedX = chunkX >> this.bitScale; + final int shiftedZ = chunkZ >> this.bitScale; - return String.format( "%d%c%d%c%d%c%s", dimension, this.dataSeparator, shiftedX, this.dataSeparator, shiftedZ, this.baseExtSeparator, this.fileExtension ); - } + return String.format( + "%d%c%d%c%d%c%s", + dimension, + this.dataSeparator, + shiftedX, + this.dataSeparator, + shiftedZ, + this.baseExtSeparator, + this.fileExtension + ); + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerData.java b/src/main/java/appeng/core/worlddata/PlayerData.java index f0be8d41..b0a8b9e8 100644 --- a/src/main/java/appeng/core/worlddata/PlayerData.java +++ b/src/main/java/appeng/core/worlddata/PlayerData.java @@ -18,6 +18,9 @@ package appeng.core.worlddata; +import java.util.UUID; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.core.CommonHelper; import com.google.common.base.Optional; @@ -28,11 +31,6 @@ import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.UUID; - - /** * Handles the matching between UUIDs and internal IDs for security systems. * This whole system could be replaced by storing directly the UUID, @@ -42,96 +40,87 @@ import java.util.UUID; * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class PlayerData implements IWorldPlayerData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String LAST_PLAYER_CATEGORY = "Counters"; - private static final String LAST_PLAYER_KEY = "lastPlayer"; - private static final int LAST_PLAYER_DEFAULT = 0; +final class PlayerData implements IWorldPlayerData, IOnWorldStartable, IOnWorldStoppable { + private static final String LAST_PLAYER_CATEGORY = "Counters"; + private static final String LAST_PLAYER_KEY = "lastPlayer"; + private static final int LAST_PLAYER_DEFAULT = 0; - private final Configuration config; - private final IWorldPlayerMapping playerMapping; + private final Configuration config; + private final IWorldPlayerMapping playerMapping; - private int lastPlayerID; + private int lastPlayerID; - public PlayerData( @Nonnull final Configuration configFile ) - { - Preconditions.checkNotNull( configFile ); + public PlayerData(@Nonnull final Configuration configFile) { + Preconditions.checkNotNull(configFile); - this.config = configFile; + this.config = configFile; - final ConfigCategory playerList = this.config.getCategory( "players" ); - this.playerMapping = new PlayerMapping( playerList ); - } + final ConfigCategory playerList = this.config.getCategory("players"); + this.playerMapping = new PlayerMapping(playerList); + } - @Nullable - @Override - public EntityPlayer getPlayerFromID( final int playerID ) - { - final Optional maybe = this.playerMapping.get( playerID ); + @Nullable + @Override + public EntityPlayer getPlayerFromID(final int playerID) { + final Optional maybe = this.playerMapping.get(playerID); - if( maybe.isPresent() ) - { - final UUID uuid = maybe.get(); - for( final EntityPlayer player : CommonHelper.proxy.getPlayers() ) - { - if( player.getUniqueID().equals( uuid ) ) - { - return player; - } - } - } + if (maybe.isPresent()) { + final UUID uuid = maybe.get(); + for (final EntityPlayer player : CommonHelper.proxy.getPlayers()) { + if (player.getUniqueID().equals(uuid)) { + return player; + } + } + } - return null; - } + return null; + } - @Override - public int getPlayerID( @Nonnull final GameProfile profile ) - { - Preconditions.checkNotNull( profile ); - Preconditions.checkNotNull( this.config.getCategory( "players" ) ); - Preconditions.checkState( profile.isComplete() ); + @Override + public int getPlayerID(@Nonnull final GameProfile profile) { + Preconditions.checkNotNull(profile); + Preconditions.checkNotNull(this.config.getCategory("players")); + Preconditions.checkState(profile.isComplete()); - final ConfigCategory players = this.config.getCategory( "players" ); - final String uuid = profile.getId().toString(); - final Property maybePlayerID = players.get( uuid ); + final ConfigCategory players = this.config.getCategory("players"); + final String uuid = profile.getId().toString(); + final Property maybePlayerID = players.get(uuid); - if( maybePlayerID != null && maybePlayerID.isIntValue() ) - { - return maybePlayerID.getInt(); - } - else - { - final int newPlayerID = this.nextPlayer(); - final Property newPlayer = new Property( uuid, String.valueOf( newPlayerID ), Property.Type.INTEGER ); - players.put( uuid, newPlayer ); - this.playerMapping.put( newPlayerID, profile.getId() ); // add to reverse map - this.config.save(); + if (maybePlayerID != null && maybePlayerID.isIntValue()) { + return maybePlayerID.getInt(); + } else { + final int newPlayerID = this.nextPlayer(); + final Property newPlayer + = new Property(uuid, String.valueOf(newPlayerID), Property.Type.INTEGER); + players.put(uuid, newPlayer); + this.playerMapping.put(newPlayerID, profile.getId()); // add to reverse map + this.config.save(); - return newPlayerID; - } - } + return newPlayerID; + } + } - private int nextPlayer() - { - final int r = this.lastPlayerID; - this.lastPlayerID++; - this.config.get( LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, this.lastPlayerID ).set( this.lastPlayerID ); - return r; - } + private int nextPlayer() { + final int r = this.lastPlayerID; + this.lastPlayerID++; + this.config.get(LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, this.lastPlayerID) + .set(this.lastPlayerID); + return r; + } - @Override - public void onWorldStart() - { - this.lastPlayerID = this.config.get( LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, LAST_PLAYER_DEFAULT ).getInt( LAST_PLAYER_DEFAULT ); + @Override + public void onWorldStart() { + this.lastPlayerID + = this.config.get(LAST_PLAYER_CATEGORY, LAST_PLAYER_KEY, LAST_PLAYER_DEFAULT) + .getInt(LAST_PLAYER_DEFAULT); - this.config.save(); - } + this.config.save(); + } - @Override - public void onWorldStop() - { - this.config.save(); + @Override + public void onWorldStop() { + this.config.save(); - this.lastPlayerID = 0; - } + this.lastPlayerID = 0; + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerMapping.java b/src/main/java/appeng/core/worlddata/PlayerMapping.java index 4455eb0c..473e60ee 100644 --- a/src/main/java/appeng/core/worlddata/PlayerMapping.java +++ b/src/main/java/appeng/core/worlddata/PlayerMapping.java @@ -18,51 +18,45 @@ package appeng.core.worlddata; +import java.util.Map; +import java.util.UUID; +import javax.annotation.Nonnull; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import net.minecraftforge.common.config.ConfigCategory; -import javax.annotation.Nonnull; -import java.util.Map; -import java.util.UUID; - - /** * Wrapper class for the player mappings. * Will grant access to a pre initialized player map * based on the "players" category in the settings.cfg */ -final class PlayerMapping implements IWorldPlayerMapping -{ - /** - * View of player mappings, is not immutable, - * since it needs to be edited upon runtime, - * cause new players can join - */ - private final Map mappings; +final class PlayerMapping implements IWorldPlayerMapping { + /** + * View of player mappings, is not immutable, + * since it needs to be edited upon runtime, + * cause new players can join + */ + private final Map mappings; - public PlayerMapping( final ConfigCategory category ) - { - final PlayerMappingsInitializer init = new PlayerMappingsInitializer( category ); + public PlayerMapping(final ConfigCategory category) { + final PlayerMappingsInitializer init = new PlayerMappingsInitializer(category); - this.mappings = init.getPlayerMappings(); - } + this.mappings = init.getPlayerMappings(); + } - @Nonnull - @Override - public Optional get( final int id ) - { - final UUID maybe = this.mappings.get( id ); + @Nonnull + @Override + public Optional get(final int id) { + final UUID maybe = this.mappings.get(id); - return Optional.fromNullable( maybe ); - } + return Optional.fromNullable(maybe); + } - @Override - public void put( final int id, @Nonnull final UUID uuid ) - { - Preconditions.checkNotNull( uuid ); + @Override + public void put(final int id, @Nonnull final UUID uuid) { + Preconditions.checkNotNull(uuid); - this.mappings.put( id, uuid ); - } + this.mappings.put(id, uuid); + } } diff --git a/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java b/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java index 00910d1d..54677402 100644 --- a/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java +++ b/src/main/java/appeng/core/worlddata/PlayerMappingsInitializer.java @@ -18,75 +18,71 @@ package appeng.core.worlddata; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; import appeng.core.AELog; import appeng.util.UUIDMatcher; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Property; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - - /** * Initializes a map of ID to UUID from the player list in the settings.cfg */ -class PlayerMappingsInitializer -{ - /** - * Internal immutable mapping - */ - private final Map playerMappings; +class PlayerMappingsInitializer { + /** + * Internal immutable mapping + */ + private final Map playerMappings; - /** - * Creates the initializer for the player mappings. - * The map will be filled upon construction - * and will only be filled with valid entries. - * If an invalid entry is found, an warning is printed, - * mostly due to migration problems from 1.7.2 to 1.7.10 - * where the UUIDs were introduced. - * - * @param playerList the category for the player list, generally extracted using the "players" tag - * @param log the logger used to warn the server or user of faulty entries - */ - PlayerMappingsInitializer( final ConfigCategory playerList ) - { - // Matcher for UUIDs - final UUIDMatcher matcher = new UUIDMatcher(); + /** + * Creates the initializer for the player mappings. + * The map will be filled upon construction + * and will only be filled with valid entries. + * If an invalid entry is found, an warning is printed, + * mostly due to migration problems from 1.7.2 to 1.7.10 + * where the UUIDs were introduced. + * + * @param playerList the category for the player list, generally extracted using the + * "players" tag + * @param log the logger used to warn the server or user of faulty entries + */ + PlayerMappingsInitializer(final ConfigCategory playerList) { + // Matcher for UUIDs + final UUIDMatcher matcher = new UUIDMatcher(); - // Initial capacity for mappings - final int capacity = playerList.size(); + // Initial capacity for mappings + final int capacity = playerList.size(); - // Mappings for the IDs is a regular HashMap - this.playerMappings = new HashMap( capacity ); + // Mappings for the IDs is a regular HashMap + this.playerMappings = new HashMap(capacity); - // Iterates through every pair of UUID to ID - for( final Map.Entry entry : playerList.getValues().entrySet() ) - { - final String maybeUUID = entry.getKey(); - final int id = entry.getValue().getInt(); + // Iterates through every pair of UUID to ID + for (final Map.Entry entry : + playerList.getValues().entrySet()) { + final String maybeUUID = entry.getKey(); + final int id = entry.getValue().getInt(); - if( matcher.isUUID( maybeUUID ) ) - { - final UUID uuidString = UUID.fromString( maybeUUID ); + if (matcher.isUUID(maybeUUID)) { + final UUID uuidString = UUID.fromString(maybeUUID); - this.playerMappings.put( id, uuidString ); - } - else - { - AELog.warn( "The configuration for players contained an outdated entry instead an expected UUID " + maybeUUID + " for the player " + id + ". Please clean this up." ); - } - } - } + this.playerMappings.put(id, uuidString); + } else { + AELog.warn( + "The configuration for players contained an outdated entry instead an expected UUID " + + maybeUUID + " for the player " + id + ". Please clean this up." + ); + } + } + } - /** - * Getter - * - * @return Immutable map of the players mappings of their ID to their UUID - */ - public Map getPlayerMappings() - { - return this.playerMappings; - } + /** + * Getter + * + * @return Immutable map of the players mappings of their ID to their UUID + */ + public Map getPlayerMappings() { + return this.playerMappings; + } } diff --git a/src/main/java/appeng/core/worlddata/SpawnData.java b/src/main/java/appeng/core/worlddata/SpawnData.java index 06d6d7b6..4204dfec 100644 --- a/src/main/java/appeng/core/worlddata/SpawnData.java +++ b/src/main/java/appeng/core/worlddata/SpawnData.java @@ -18,196 +18,161 @@ package appeng.core.worlddata; - -import appeng.core.AELog; -import com.google.common.base.Preconditions; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - -import javax.annotation.Nonnull; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collection; import java.util.LinkedList; +import javax.annotation.Nonnull; +import appeng.core.AELog; +import com.google.common.base.Preconditions; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class SpawnData implements IWorldSpawnData -{ - @Nonnull - private final File spawnDirectory; - @Nonnull - private final MeteorDataNameEncoder encoder; +final class SpawnData implements IWorldSpawnData { + @Nonnull + private final File spawnDirectory; + @Nonnull + private final MeteorDataNameEncoder encoder; - public SpawnData( @Nonnull final File spawnDirectory ) - { - Preconditions.checkNotNull( spawnDirectory ); + public SpawnData(@Nonnull final File spawnDirectory) { + Preconditions.checkNotNull(spawnDirectory); - this.spawnDirectory = spawnDirectory; - this.encoder = new MeteorDataNameEncoder( 4 ); - } + this.spawnDirectory = spawnDirectory; + this.encoder = new MeteorDataNameEncoder(4); + } - @Override - public void setGenerated( final int dim, final int chunkX, final int chunkZ ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); + @Override + public void setGenerated(final int dim, final int chunkX, final int chunkZ) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); - // edit. - data.setBoolean( chunkX + "," + chunkZ, true ); + // edit. + data.setBoolean(chunkX + "," + chunkZ, true); - this.writeSpawnData( dim, chunkX, chunkZ, data ); - } - } + this.writeSpawnData(dim, chunkX, chunkZ, data); + } + } - @Override - public boolean hasGenerated( final int dim, final int chunkX, final int chunkZ ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); - return data.getBoolean( chunkX + "," + chunkZ ); - } - } + @Override + public boolean hasGenerated(final int dim, final int chunkX, final int chunkZ) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); + return data.getBoolean(chunkX + "," + chunkZ); + } + } - @Override - public boolean addNearByMeteorites( final int dim, final int chunkX, final int chunkZ, final NBTTagCompound newData ) - { - synchronized( SpawnData.class ) - { - final NBTTagCompound data = this.loadSpawnData( dim, chunkX, chunkZ ); + @Override + public boolean addNearByMeteorites( + final int dim, final int chunkX, final int chunkZ, final NBTTagCompound newData + ) { + synchronized (SpawnData.class) { + final NBTTagCompound data = this.loadSpawnData(dim, chunkX, chunkZ); - // edit. - final int size = data.getInteger( "num" ); - data.setTag( String.valueOf( size ), newData ); - data.setInteger( "num", size + 1 ); + // edit. + final int size = data.getInteger("num"); + data.setTag(String.valueOf(size), newData); + data.setInteger("num", size + 1); - this.writeSpawnData( dim, chunkX, chunkZ, data ); + this.writeSpawnData(dim, chunkX, chunkZ, data); - return true; - } - } + return true; + } + } - @Override - public Collection getNearByMeteorites( final int dim, final int chunkX, final int chunkZ ) - { - final Collection ll = new LinkedList(); + @Override + public Collection + getNearByMeteorites(final int dim, final int chunkX, final int chunkZ) { + final Collection ll = new LinkedList(); - synchronized( SpawnData.class ) - { - for( int x = -1; x <= 1; x++ ) - { - for( int z = -1; z <= 1; z++ ) - { - final int cx = x + ( chunkX >> 4 ); - final int cz = z + ( chunkZ >> 4 ); + synchronized (SpawnData.class) { + for (int x = -1; x <= 1; x++) { + for (int z = -1; z <= 1; z++) { + final int cx = x + (chunkX >> 4); + final int cz = z + (chunkZ >> 4); - final NBTTagCompound data = this.loadSpawnData( dim, cx << 4, cz << 4 ); + final NBTTagCompound data = this.loadSpawnData(dim, cx << 4, cz << 4); - if( data != null ) - { - // edit. - final int size = data.getInteger( "num" ); - for( int s = 0; s < size; s++ ) - { - ll.add( data.getCompoundTag( String.valueOf( s ) ) ); - } - } - } - } - } + if (data != null) { + // edit. + final int size = data.getInteger("num"); + for (int s = 0; s < size; s++) { + ll.add(data.getCompoundTag(String.valueOf(s))); + } + } + } + } + } - return ll; - } + return ll; + } - private NBTTagCompound loadSpawnData( final int dim, final int chunkX, final int chunkZ ) - { - if( !Thread.holdsLock( SpawnData.class ) ) - { - throw new IllegalStateException( "Invalid Request" ); - } + private NBTTagCompound + loadSpawnData(final int dim, final int chunkX, final int chunkZ) { + if (!Thread.holdsLock(SpawnData.class)) { + throw new IllegalStateException("Invalid Request"); + } - NBTTagCompound data = null; - final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); - final File file = new File( this.spawnDirectory, fileName ); + NBTTagCompound data = null; + final String fileName = this.encoder.encode(dim, chunkX, chunkZ); + final File file = new File(this.spawnDirectory, fileName); - if( file.isFile() ) - { - FileInputStream fileInputStream = null; + if (file.isFile()) { + FileInputStream fileInputStream = null; - try - { - fileInputStream = new FileInputStream( file ); - data = CompressedStreamTools.readCompressed( fileInputStream ); - } - catch( final Throwable e ) - { - data = new NBTTagCompound(); - AELog.debug( e ); - } - finally - { - if( fileInputStream != null ) - { - try - { - fileInputStream.close(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } - else - { - data = new NBTTagCompound(); - } + try { + fileInputStream = new FileInputStream(file); + data = CompressedStreamTools.readCompressed(fileInputStream); + } catch (final Throwable e) { + data = new NBTTagCompound(); + AELog.debug(e); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } else { + data = new NBTTagCompound(); + } - return data; - } + return data; + } - private void writeSpawnData( final int dim, final int chunkX, final int chunkZ, final NBTTagCompound data ) - { - if( !Thread.holdsLock( SpawnData.class ) ) - { - throw new IllegalStateException( "Invalid Request" ); - } + private void writeSpawnData( + final int dim, final int chunkX, final int chunkZ, final NBTTagCompound data + ) { + if (!Thread.holdsLock(SpawnData.class)) { + throw new IllegalStateException("Invalid Request"); + } - final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); - final File file = new File( this.spawnDirectory, fileName ); - FileOutputStream fileOutputStream = null; + final String fileName = this.encoder.encode(dim, chunkX, chunkZ); + final File file = new File(this.spawnDirectory, fileName); + FileOutputStream fileOutputStream = null; - try - { - fileOutputStream = new FileOutputStream( file ); - CompressedStreamTools.writeCompressed( data, fileOutputStream ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - finally - { - if( fileOutputStream != null ) - { - try - { - fileOutputStream.close(); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - } - } + try { + fileOutputStream = new FileOutputStream(file); + CompressedStreamTools.writeCompressed(data, fileOutputStream); + } catch (final Throwable e) { + AELog.debug(e); + } finally { + if (fileOutputStream != null) { + try { + fileOutputStream.close(); + } catch (final IOException e) { + AELog.debug(e); + } + } + } + } } diff --git a/src/main/java/appeng/core/worlddata/StorageData.java b/src/main/java/appeng/core/worlddata/StorageData.java index ce0f91b4..a2429164 100644 --- a/src/main/java/appeng/core/worlddata/StorageData.java +++ b/src/main/java/appeng/core/worlddata/StorageData.java @@ -18,6 +18,11 @@ package appeng.core.worlddata; +import java.lang.ref.WeakReference; +import java.util.Map; +import java.util.WeakHashMap; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.core.AELog; import appeng.me.GridStorage; @@ -26,136 +31,131 @@ import com.google.common.base.Preconditions; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.lang.ref.WeakReference; -import java.util.Map; -import java.util.WeakHashMap; - - /** * @author thatsIch * @version rv3 - 30.05.2015 * @since rv3 30.05.2015 */ -final class StorageData implements IWorldGridStorageData, IOnWorldStartable, IOnWorldStoppable -{ - private static final String LAST_GRID_STORAGE_CATEGORY = "Counters"; - private static final String LAST_GRID_STORAGE_KEY = "lastGridStorage"; - private static final int LAST_GRID_STORAGE_DEFAULT = 0; +final class StorageData + implements IWorldGridStorageData, IOnWorldStartable, IOnWorldStoppable { + private static final String LAST_GRID_STORAGE_CATEGORY = "Counters"; + private static final String LAST_GRID_STORAGE_KEY = "lastGridStorage"; + private static final int LAST_GRID_STORAGE_DEFAULT = 0; - private static final String GRID_STORAGE_CATEGORY = "gridstorage"; + private static final String GRID_STORAGE_CATEGORY = "gridstorage"; - private final Map> loadedStorage = new WeakHashMap>( 10 ); - private final Configuration config; + private final Map> loadedStorage + = new WeakHashMap>(10); + private final Configuration config; - private long lastGridStorage; + private long lastGridStorage; - public StorageData( @Nonnull final Configuration settingsFile ) - { - Preconditions.checkNotNull( settingsFile ); + public StorageData(@Nonnull final Configuration settingsFile) { + Preconditions.checkNotNull(settingsFile); - this.config = settingsFile; - } + this.config = settingsFile; + } - /** - * lazy loading, can load any id, even ones that don't exist anymore. - * - * @param storageID ID of grid storage - * @return corresponding grid storage - */ - @Nullable - @Override - public GridStorage getGridStorage( final long storageID ) - { - final GridStorageSearch gss = new GridStorageSearch( storageID ); - final WeakReference result = this.loadedStorage.get( gss ); + /** + * lazy loading, can load any id, even ones that don't exist anymore. + * + * @param storageID ID of grid storage + * @return corresponding grid storage + */ + @Nullable + @Override + public GridStorage getGridStorage(final long storageID) { + final GridStorageSearch gss = new GridStorageSearch(storageID); + final WeakReference result = this.loadedStorage.get(gss); - if( result == null || result.get() == null ) - { - final String id = String.valueOf( storageID ); - final String data = this.config.get( "gridstorage", id, "" ).getString(); - final GridStorage thisStorage = new GridStorage( data, storageID, gss ); - gss.setGridStorage( new WeakReference( thisStorage ) ); - this.loadedStorage.put( gss, new WeakReference( gss ) ); - return thisStorage; - } + if (result == null || result.get() == null) { + final String id = String.valueOf(storageID); + final String data = this.config.get("gridstorage", id, "").getString(); + final GridStorage thisStorage = new GridStorage(data, storageID, gss); + gss.setGridStorage(new WeakReference(thisStorage)); + this.loadedStorage.put(gss, new WeakReference(gss)); + return thisStorage; + } - return result.get().getGridStorage().get(); - } + return result.get().getGridStorage().get(); + } - /** - * create a new storage - */ - @Nonnull - @Override - public GridStorage getNewGridStorage() - { - final long storageID = this.nextGridStorage(); - final GridStorageSearch gss = new GridStorageSearch( storageID ); - final GridStorage newStorage = new GridStorage( storageID, gss ); - gss.setGridStorage( new WeakReference( newStorage ) ); - this.loadedStorage.put( gss, new WeakReference( gss ) ); + /** + * create a new storage + */ + @Nonnull + @Override + public GridStorage getNewGridStorage() { + final long storageID = this.nextGridStorage(); + final GridStorageSearch gss = new GridStorageSearch(storageID); + final GridStorage newStorage = new GridStorage(storageID, gss); + gss.setGridStorage(new WeakReference(newStorage)); + this.loadedStorage.put(gss, new WeakReference(gss)); - return newStorage; - } + return newStorage; + } - @Override - public long nextGridStorage() - { - final long r = this.lastGridStorage; - this.lastGridStorage++; - this.config.get( "Counters", "lastGridStorage", this.lastGridStorage ).set( Long.toString( this.lastGridStorage ) ); - return r; - } + @Override + public long nextGridStorage() { + final long r = this.lastGridStorage; + this.lastGridStorage++; + this.config.get("Counters", "lastGridStorage", this.lastGridStorage) + .set(Long.toString(this.lastGridStorage)); + return r; + } - @Override - public void destroyGridStorage( final long id ) - { - final String stringID = String.valueOf( id ); - this.config.getCategory( "gridstorage" ).remove( stringID ); - } + @Override + public void destroyGridStorage(final long id) { + final String stringID = String.valueOf(id); + this.config.getCategory("gridstorage").remove(stringID); + } - @Override - public int getNextOrderedValue( final String name ) - { - final Property p = this.config.get( "orderedValues", name, 0 ); - final int myValue = p.getInt(); - p.set( myValue + 1 ); - return myValue; - } + @Override + public int getNextOrderedValue(final String name) { + final Property p = this.config.get("orderedValues", name, 0); + final int myValue = p.getInt(); + p.set(myValue + 1); + return myValue; + } - @Override - public void onWorldStart() - { - final String lastString = this.config.get( LAST_GRID_STORAGE_CATEGORY, LAST_GRID_STORAGE_KEY, LAST_GRID_STORAGE_DEFAULT ).getString(); + @Override + public void onWorldStart() { + final String lastString = this.config + .get( + LAST_GRID_STORAGE_CATEGORY, + LAST_GRID_STORAGE_KEY, + LAST_GRID_STORAGE_DEFAULT + ) + .getString(); - try - { - this.lastGridStorage = Long.parseLong( lastString ); - } - catch( final NumberFormatException err ) - { - AELog.warn( "The config contained a value which was not represented as a Long: %s", lastString ); + try { + this.lastGridStorage = Long.parseLong(lastString); + } catch (final NumberFormatException err) { + AELog.warn( + "The config contained a value which was not represented as a Long: %s", + lastString + ); - this.lastGridStorage = 0; - } - } + this.lastGridStorage = 0; + } + } - @Override - public void onWorldStop() - { - // populate new data - for( final GridStorageSearch gs : this.loadedStorage.keySet() ) - { - final GridStorage thisStorage = gs.getGridStorage().get(); - if( thisStorage != null && thisStorage.getGrid() != null && !thisStorage.getGrid().isEmpty() ) - { - final String value = thisStorage.getValue(); - this.config.get( GRID_STORAGE_CATEGORY, String.valueOf( thisStorage.getID() ), value ).set( value ); - } - } + @Override + public void onWorldStop() { + // populate new data + for (final GridStorageSearch gs : this.loadedStorage.keySet()) { + final GridStorage thisStorage = gs.getGridStorage().get(); + if (thisStorage != null && thisStorage.getGrid() != null + && !thisStorage.getGrid().isEmpty()) { + final String value = thisStorage.getValue(); + this.config + .get( + GRID_STORAGE_CATEGORY, String.valueOf(thisStorage.getID()), value + ) + .set(value); + } + } - this.config.save(); - } + this.config.save(); + } } diff --git a/src/main/java/appeng/core/worlddata/WorldData.java b/src/main/java/appeng/core/worlddata/WorldData.java index 3ead1880..85ccfcf3 100644 --- a/src/main/java/appeng/core/worlddata/WorldData.java +++ b/src/main/java/appeng/core/worlddata/WorldData.java @@ -18,6 +18,11 @@ package appeng.core.worlddata; +import java.io.File; +import java.util.List; +import java.util.concurrent.ThreadFactory; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.core.AEConfig; import appeng.services.CompassService; @@ -27,184 +32,170 @@ import com.google.common.collect.Lists; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.config.Configuration; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.File; -import java.util.List; -import java.util.concurrent.ThreadFactory; - - /** * Singleton access to anything related to world-based data. *

- * Data will change depending which world is loaded. Will probably not affect SMP at all since only one world is loaded, - * but SSP more, cause they play on - * different worlds. + * Data will change depending which world is loaded. Will probably not affect SMP at all + * since only one world is loaded, but SSP more, cause they play on different worlds. * * @author thatsIch * @version rv3 - 02.11.2015 * @since rv3 30.05.2015 */ -public final class WorldData implements IWorldData -{ - private static final String AE2_DIRECTORY_NAME = "AE2"; - private static final String SETTING_FILE_NAME = "settings.cfg"; - private static final String SPAWNDATA_DIR_NAME = "spawndata"; - private static final String COMPASS_DIR_NAME = "compass"; +public final class WorldData implements IWorldData { + private static final String AE2_DIRECTORY_NAME = "AE2"; + private static final String SETTING_FILE_NAME = "settings.cfg"; + private static final String SPAWNDATA_DIR_NAME = "spawndata"; + private static final String COMPASS_DIR_NAME = "compass"; - @Nullable - private static IWorldData instance; + @Nullable + private static IWorldData instance; - private final IWorldPlayerData playerData; - private final IWorldDimensionData dimensionData; - private final IWorldGridStorageData storageData; - private final IWorldCompassData compassData; - private final IWorldSpawnData spawnData; + private final IWorldPlayerData playerData; + private final IWorldDimensionData dimensionData; + private final IWorldGridStorageData storageData; + private final IWorldCompassData compassData; + private final IWorldSpawnData spawnData; - private final List startables; - private final List stoppables; + private final List startables; + private final List stoppables; - private final File ae2directory; - private final File spawnDirectory; - private final File compassDirectory; + private final File ae2directory; + private final File spawnDirectory; + private final File compassDirectory; - private final Configuration sharedConfig; + private final Configuration sharedConfig; - private WorldData( @Nonnull final File worldDirectory ) - { - Preconditions.checkNotNull( worldDirectory ); - Preconditions.checkArgument( worldDirectory.isDirectory() ); + private WorldData(@Nonnull final File worldDirectory) { + Preconditions.checkNotNull(worldDirectory); + Preconditions.checkArgument(worldDirectory.isDirectory()); - this.ae2directory = new File( worldDirectory, AE2_DIRECTORY_NAME ); - this.spawnDirectory = new File( this.ae2directory, SPAWNDATA_DIR_NAME ); - this.compassDirectory = new File( this.ae2directory, COMPASS_DIR_NAME ); + this.ae2directory = new File(worldDirectory, AE2_DIRECTORY_NAME); + this.spawnDirectory = new File(this.ae2directory, SPAWNDATA_DIR_NAME); + this.compassDirectory = new File(this.ae2directory, COMPASS_DIR_NAME); - final File settingsFile = new File( this.ae2directory, SETTING_FILE_NAME ); - this.sharedConfig = new Configuration( settingsFile, AEConfig.VERSION ); + final File settingsFile = new File(this.ae2directory, SETTING_FILE_NAME); + this.sharedConfig = new Configuration(settingsFile, AEConfig.VERSION); - final PlayerData playerData = new PlayerData( this.sharedConfig ); - final DimensionData dimensionData = new DimensionData( this.sharedConfig ); - final StorageData storageData = new StorageData( this.sharedConfig ); + final PlayerData playerData = new PlayerData(this.sharedConfig); + final DimensionData dimensionData = new DimensionData(this.sharedConfig); + final StorageData storageData = new StorageData(this.sharedConfig); - final ThreadFactory compassThreadFactory = new CompassThreadFactory(); - final CompassService compassService = new CompassService( this.compassDirectory, compassThreadFactory ); - final CompassData compassData = new CompassData( this.compassDirectory, compassService ); + final ThreadFactory compassThreadFactory = new CompassThreadFactory(); + final CompassService compassService + = new CompassService(this.compassDirectory, compassThreadFactory); + final CompassData compassData + = new CompassData(this.compassDirectory, compassService); - final IWorldSpawnData spawnData = new SpawnData( this.spawnDirectory ); + final IWorldSpawnData spawnData = new SpawnData(this.spawnDirectory); - this.playerData = playerData; - this.dimensionData = dimensionData; - this.storageData = storageData; - this.compassData = compassData; - this.spawnData = spawnData; + this.playerData = playerData; + this.dimensionData = dimensionData; + this.storageData = storageData; + this.compassData = compassData; + this.spawnData = spawnData; - this.startables = Lists.newArrayList( playerData, dimensionData, storageData ); - this.stoppables = Lists.newArrayList( playerData, dimensionData, storageData, compassData ); - } + this.startables = Lists.newArrayList( + playerData, dimensionData, storageData + ); + this.stoppables + = Lists.newArrayList(playerData, dimensionData, storageData, compassData); + } - /** - * @return ae2 data related to a specific world - * @deprecated do not use singletons which are dependent on specific world state - */ - @Deprecated - @Nonnull - public static IWorldData instance() - { - return instance; - } + /** + * @return ae2 data related to a specific world + * @deprecated do not use singletons which are dependent on specific world state + */ + @Deprecated + @Nonnull + public static IWorldData instance() { + return instance; + } - /** - * Requires to start up from external from here - *

- * drawback of the singleton build style - */ - public static void onServerAboutToStart() - { - final File worldDirectory = DimensionManager.getCurrentSaveRootDirectory(); - final WorldData newInstance = new WorldData( worldDirectory ); + /** + * Requires to start up from external from here + *

+ * drawback of the singleton build style + */ + public static void onServerAboutToStart() { + final File worldDirectory = DimensionManager.getCurrentSaveRootDirectory(); + final WorldData newInstance = new WorldData(worldDirectory); - instance = newInstance; - newInstance.onServerStarting(); - } + instance = newInstance; + newInstance.onServerStarting(); + } - private void onServerStarting() - { - // check if ae2 folder already exists, else create - if( !this.ae2directory.isDirectory() && !this.ae2directory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.ae2directory.getAbsolutePath() ); - } + private void onServerStarting() { + // check if ae2 folder already exists, else create + if (!this.ae2directory.isDirectory() && !this.ae2directory.mkdir()) { + throw new IllegalStateException( + "Failed to create " + this.ae2directory.getAbsolutePath() + ); + } - // check if compass folder already exists, else create - if( !this.compassDirectory.isDirectory() && !this.compassDirectory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.compassDirectory.getAbsolutePath() ); - } + // check if compass folder already exists, else create + if (!this.compassDirectory.isDirectory() && !this.compassDirectory.mkdir()) { + throw new IllegalStateException( + "Failed to create " + this.compassDirectory.getAbsolutePath() + ); + } - // check if spawn data dir already exists, else create - if( !this.spawnDirectory.isDirectory() && !this.spawnDirectory.mkdir() ) - { - throw new IllegalStateException( "Failed to create " + this.spawnDirectory.getAbsolutePath() ); - } + // check if spawn data dir already exists, else create + if (!this.spawnDirectory.isDirectory() && !this.spawnDirectory.mkdir()) { + throw new IllegalStateException( + "Failed to create " + this.spawnDirectory.getAbsolutePath() + ); + } - for( final IOnWorldStartable startable : this.startables ) - { - startable.onWorldStart(); - } + for (final IOnWorldStartable startable : this.startables) { + startable.onWorldStart(); + } - this.startables.clear(); - } + this.startables.clear(); + } - @Override - public void onServerStopping() - { - for( final IOnWorldStoppable stoppable : this.stoppables ) - { - stoppable.onWorldStop(); - } - } + @Override + public void onServerStopping() { + for (final IOnWorldStoppable stoppable : this.stoppables) { + stoppable.onWorldStop(); + } + } - @Override - public void onServerStoppped() - { - Preconditions.checkNotNull( instance ); + @Override + public void onServerStoppped() { + Preconditions.checkNotNull(instance); - this.stoppables.clear(); - instance = null; - } + this.stoppables.clear(); + instance = null; + } - @Nonnull - @Override - public IWorldGridStorageData storageData() - { - return this.storageData; - } + @Nonnull + @Override + public IWorldGridStorageData storageData() { + return this.storageData; + } - @Nonnull - @Override - public IWorldPlayerData playerData() - { - return this.playerData; - } + @Nonnull + @Override + public IWorldPlayerData playerData() { + return this.playerData; + } - @Nonnull - @Override - public IWorldDimensionData dimensionData() - { - return this.dimensionData; - } + @Nonnull + @Override + public IWorldDimensionData dimensionData() { + return this.dimensionData; + } - @Nonnull - @Override - public IWorldCompassData compassData() - { - return this.compassData; - } + @Nonnull + @Override + public IWorldCompassData compassData() { + return this.compassData; + } - @Nonnull - @Override - public IWorldSpawnData spawnData() - { - return this.spawnData; - } + @Nonnull + @Override + public IWorldSpawnData spawnData() { + return this.spawnData; + } } diff --git a/src/main/java/appeng/crafting/CraftBranchFailure.java b/src/main/java/appeng/crafting/CraftBranchFailure.java index c0491678..c698ce27 100644 --- a/src/main/java/appeng/crafting/CraftBranchFailure.java +++ b/src/main/java/appeng/crafting/CraftBranchFailure.java @@ -18,21 +18,16 @@ package appeng.crafting; - import appeng.api.storage.data.IAEItemStack; +public class CraftBranchFailure extends Exception { + private static final long serialVersionUID = 654603652836724823L; -public class CraftBranchFailure extends Exception -{ + private final IAEItemStack missing; - private static final long serialVersionUID = 654603652836724823L; - - private final IAEItemStack missing; - - public CraftBranchFailure( final IAEItemStack what, final long howMany ) - { - super( "Failed: " + what.getItem().getUnlocalizedName() + " x " + howMany ); - this.missing = what.copy(); - this.missing.setStackSize( howMany ); - } + public CraftBranchFailure(final IAEItemStack what, final 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 bfaa7ece..d11bcdf4 100644 --- a/src/main/java/appeng/crafting/CraftingCalculationFailure.java +++ b/src/main/java/appeng/crafting/CraftingCalculationFailure.java @@ -18,21 +18,16 @@ package appeng.crafting; - import appeng.api.storage.data.IAEItemStack; +public class CraftingCalculationFailure extends RuntimeException { + private static final long serialVersionUID = 654603652836724823L; -public class CraftingCalculationFailure extends RuntimeException -{ + private final IAEItemStack missing; - private static final long serialVersionUID = 654603652836724823L; - - private final IAEItemStack missing; - - public CraftingCalculationFailure( final IAEItemStack what, final long howMany ) - { - super( "this should have been caught!" ); - this.missing = what.copy(); - this.missing.setStackSize( howMany ); - } + public CraftingCalculationFailure(final IAEItemStack what, final 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 9d847099..9ba9cfe8 100644 --- a/src/main/java/appeng/crafting/CraftingJob.java +++ b/src/main/java/appeng/crafting/CraftingJob.java @@ -18,6 +18,8 @@ package appeng.crafting; +import java.util.HashMap; +import java.util.concurrent.TimeUnit; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -43,363 +45,330 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; +public class CraftingJob implements Runnable, ICraftingJob { + private static final String LOG_CRAFTING_JOB + = "CraftingJob (%s) issued by %s requesting [%s] using %s bytes took %s ms"; + private static final String LOG_MACHINE_SOURCE_DETAILS = "Machine[object=%s, %s]"; + private final MECraftingInventory original; + private final World world; + private final IItemList crafting + = AEApi.instance().storage().createItemList(); + private final IItemList missing + = AEApi.instance().storage().createItemList(); + private final HashMap opsAndMultiplier + = new HashMap(); + private final Object monitor = new Object(); + private final Stopwatch watch = Stopwatch.createUnstarted(); + private CraftingTreeNode tree; + private final IAEItemStack output; + private boolean simulate = false; + private MECraftingInventory availableCheck; + private long bytes = 0; + private final BaseActionSource actionSrc; + private final ICraftingCallback callback; + private boolean running = false; + private boolean done = false; + private int time = 5; + private int incTime = Integer.MAX_VALUE; -public class CraftingJob implements Runnable, ICraftingJob -{ - private static final String LOG_CRAFTING_JOB = "CraftingJob (%s) issued by %s requesting [%s] using %s bytes took %s ms"; - private static final String LOG_MACHINE_SOURCE_DETAILS = "Machine[object=%s, %s]"; + private World wrapWorld(final World w) { + return w; + } - private final MECraftingInventory original; - private final World world; - private final IItemList crafting = AEApi.instance().storage().createItemList(); - private final IItemList missing = AEApi.instance().storage().createItemList(); - private final HashMap opsAndMultiplier = new HashMap(); - private final Object monitor = new Object(); - private final Stopwatch watch = Stopwatch.createUnstarted(); - private CraftingTreeNode tree; - private final IAEItemStack output; - private boolean simulate = false; - private MECraftingInventory availableCheck; - private long bytes = 0; - private final BaseActionSource actionSrc; - private final ICraftingCallback callback; - private boolean running = false; - private boolean done = false; - private int time = 5; - private int incTime = Integer.MAX_VALUE; + public CraftingJob( + final World w, + final IGrid grid, + final BaseActionSource actionSrc, + final IAEItemStack what, + final ICraftingCallback callback + ) { + this.world = this.wrapWorld(w); + this.output = what.copy(); + this.actionSrc = actionSrc; - private World wrapWorld( final World w ) - { - return w; - } + this.callback = callback; + final ICraftingGrid cc = grid.getCache(ICraftingGrid.class); + final IStorageGrid sg = grid.getCache(IStorageGrid.class); + this.original = new MECraftingInventory( + sg.getItemInventory(), actionSrc, false, false, false + ); - public CraftingJob( final World w, final IGrid grid, final BaseActionSource actionSrc, final IAEItemStack what, final ICraftingCallback callback ) - { - this.world = this.wrapWorld( w ); - this.output = what.copy(); - this.actionSrc = actionSrc; + this.setTree(this.getCraftingTree(cc, what)); + this.availableCheck = null; + } - this.callback = callback; - final ICraftingGrid cc = grid.getCache( ICraftingGrid.class ); - final IStorageGrid sg = grid.getCache( IStorageGrid.class ); - this.original = new MECraftingInventory( sg.getItemInventory(), actionSrc, false, false, false ); + private CraftingTreeNode + getCraftingTree(final ICraftingGrid cc, final IAEItemStack what) { + return new CraftingTreeNode(cc, this, what, null, -1, 0); + } - this.setTree( this.getCraftingTree( cc, what ) ); - this.availableCheck = null; - } + void refund(final IAEItemStack o) { + this.availableCheck.injectItems(o, Actionable.MODULATE, this.actionSrc); + } - private CraftingTreeNode getCraftingTree( final ICraftingGrid cc, final IAEItemStack what ) - { - return new CraftingTreeNode( cc, this, what, null, -1, 0 ); - } + IAEItemStack checkUse(final IAEItemStack available) { + return this.availableCheck.extractItems( + available, Actionable.MODULATE, this.actionSrc + ); + } - void refund( final IAEItemStack o ) - { - this.availableCheck.injectItems( o, Actionable.MODULATE, this.actionSrc ); - } + public void writeToNBT(final NBTTagCompound out) {} - IAEItemStack checkUse( final IAEItemStack available ) - { - return this.availableCheck.extractItems( available, Actionable.MODULATE, this.actionSrc ); - } + void addTask( + IAEItemStack what, + final long crafts, + final ICraftingPatternDetails details, + final int depth + ) { + if (crafts > 0) { + what = what.copy(); + what.setStackSize(what.getStackSize() * crafts); + this.crafting.add(what); + } + } - public void writeToNBT( final NBTTagCompound out ) - { + void addMissing(IAEItemStack what) { + what = what.copy(); + this.missing.add(what); + } - } + @Override + public void run() { + try { + try { + TickHandler.INSTANCE.registerCraftingSimulation(this.world, this); + this.handlePausing(); - void addTask( IAEItemStack what, final long crafts, final ICraftingPatternDetails details, final int depth ) - { - if( crafts > 0 ) - { - what = what.copy(); - what.setStackSize( what.getStackSize() * crafts ); - this.crafting.add( what ); - } - } + final Stopwatch timer = Stopwatch.createStarted(); - void addMissing( IAEItemStack what ) - { - what = what.copy(); - this.missing.add( what ); - } + final MECraftingInventory craftingInventory + = new MECraftingInventory(this.original, true, false, true); + craftingInventory.ignore(this.output); - @Override - public void run() - { - try - { - try - { - TickHandler.INSTANCE.registerCraftingSimulation( this.world, this ); - this.handlePausing(); + this.availableCheck + = new MECraftingInventory(this.original, false, false, false); + this.getTree().request( + craftingInventory, this.output.getStackSize(), this.actionSrc + ); + this.getTree().dive(this); - final Stopwatch timer = Stopwatch.createStarted(); + for (final String s : this.opsAndMultiplier.keySet()) { + final TwoIntegers ti = this.opsAndMultiplier.get(s); + AELog.crafting(s + " * " + ti.times + " = " + (ti.perOp * ti.times)); + } - final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true ); - craftingInventory.ignore( this.output ); + this.logCraftingJob("real", timer); + // if ( mode == Actionable.MODULATE ) + // craftingInventory.moveItemsToStorage( storage ); + } catch (final CraftBranchFailure e) { + this.simulate = true; - this.availableCheck = new MECraftingInventory( this.original, false, false, false ); - this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc ); - this.getTree().dive( this ); + try { + final Stopwatch timer = Stopwatch.createStarted(); + final MECraftingInventory craftingInventory + = new MECraftingInventory(this.original, true, false, true); + craftingInventory.ignore(this.output); - for( final String s : this.opsAndMultiplier.keySet() ) - { - final TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); - } + this.availableCheck + = new MECraftingInventory(this.original, false, false, false); - this.logCraftingJob( "real", timer ); - // if ( mode == Actionable.MODULATE ) - // craftingInventory.moveItemsToStorage( storage ); - } - catch( final CraftBranchFailure e ) - { - this.simulate = true; + this.getTree().setSimulate(); + this.getTree().request( + craftingInventory, this.output.getStackSize(), this.actionSrc + ); + this.getTree().dive(this); - try - { - final Stopwatch timer = Stopwatch.createStarted(); - final MECraftingInventory craftingInventory = new MECraftingInventory( this.original, true, false, true ); - craftingInventory.ignore( this.output ); + for (final String s : this.opsAndMultiplier.keySet()) { + final TwoIntegers ti = this.opsAndMultiplier.get(s); + AELog.crafting( + s + " * " + ti.times + " = " + (ti.perOp * ti.times) + ); + } - this.availableCheck = new MECraftingInventory( this.original, false, false, false ); + this.logCraftingJob("simulate", timer); + } catch (final CraftBranchFailure e1) { + AELog.debug(e1); + } catch (final CraftingCalculationFailure f) { + AELog.debug(f); + } catch (final InterruptedException e1) { + AELog.crafting("Crafting calculation canceled."); + this.finish(); + return; + } + } catch (final CraftingCalculationFailure f) { + AELog.debug(f); + } catch (final InterruptedException e1) { + AELog.crafting("Crafting calculation canceled."); + this.finish(); + return; + } - this.getTree().setSimulate(); - this.getTree().request( craftingInventory, this.output.getStackSize(), this.actionSrc ); - this.getTree().dive( this ); + AELog.craftingDebug("crafting job now done"); + } catch (final Throwable t) { + this.finish(); + throw new IllegalStateException(t); + } - for( final String s : this.opsAndMultiplier.keySet() ) - { - final TwoIntegers ti = this.opsAndMultiplier.get( s ); - AELog.crafting( s + " * " + ti.times + " = " + ( ti.perOp * ti.times ) ); - } + this.finish(); + } - this.logCraftingJob( "simulate", timer ); - } - catch( final CraftBranchFailure e1 ) - { - AELog.debug( e1 ); - } - catch( final CraftingCalculationFailure f ) - { - AELog.debug( f ); - } - catch( final InterruptedException e1 ) - { - AELog.crafting( "Crafting calculation canceled." ); - this.finish(); - return; - } - } - catch( final CraftingCalculationFailure f ) - { - AELog.debug( f ); - } - catch( final InterruptedException e1 ) - { - AELog.crafting( "Crafting calculation canceled." ); - this.finish(); - return; - } + void handlePausing() throws InterruptedException { + if (this.incTime > 100) { + this.incTime = 0; - AELog.craftingDebug( "crafting job now done" ); - } - catch( final Throwable t ) - { - this.finish(); - throw new IllegalStateException( t ); - } + synchronized (this.monitor) { + if (this.watch.elapsed(TimeUnit.MICROSECONDS) > this.time) { + this.running = false; + this.watch.stop(); + this.monitor.notify(); + } - this.finish(); - } + if (!this.running) { + AELog.craftingDebug("crafting job will now sleep"); - void handlePausing() throws InterruptedException - { - if( this.incTime > 100 ) - { - this.incTime = 0; + while (!this.running) { + this.monitor.wait(); + } - synchronized( this.monitor ) - { - if( this.watch.elapsed( TimeUnit.MICROSECONDS ) > this.time ) - { - this.running = false; - this.watch.stop(); - this.monitor.notify(); - } + AELog.craftingDebug("crafting job now active"); + } + } - if( !this.running ) - { - AELog.craftingDebug( "crafting job will now sleep" ); + if (Thread.interrupted()) { + throw new InterruptedException(); + } + } + this.incTime++; + } - while( !this.running ) - { - this.monitor.wait(); - } + private void finish() { + if (this.callback != null) { + this.callback.calculationComplete(this); + } - AELog.craftingDebug( "crafting job now active" ); - } - } + this.availableCheck = null; - if( Thread.interrupted() ) - { - throw new InterruptedException(); - } - } - this.incTime++; - } + synchronized (this.monitor) { + this.running = false; + this.done = true; + this.monitor.notify(); + } + } - private void finish() - { - if( this.callback != null ) - { - this.callback.calculationComplete( this ); - } + @Override + public boolean isSimulation() { + return this.simulate; + } - this.availableCheck = null; + @Override + public long getByteTotal() { + return this.bytes; + } - synchronized( this.monitor ) - { - this.running = false; - this.done = true; - this.monitor.notify(); - } - } + @Override + public void populatePlan(final IItemList plan) { + if (this.getTree() != null) { + this.getTree().getPlan(plan); + } + } - @Override - public boolean isSimulation() - { - return this.simulate; - } + @Override + public IAEItemStack getOutput() { + return this.output; + } - @Override - public long getByteTotal() - { - return this.bytes; - } + public boolean isDone() { + return this.done; + } - @Override - public void populatePlan( final IItemList plan ) - { - if( this.getTree() != null ) - { - this.getTree().getPlan( plan ); - } - } + World getWorld() { + return this.world; + } - @Override - public IAEItemStack getOutput() - { - return this.output; - } + /** + * returns true if this needs more simulation. + * + * @param milli milliseconds of simulation + * @return true if this needs more simulation + */ + public boolean simulateFor(final int milli) { + this.time = milli; - public boolean isDone() - { - return this.done; - } + synchronized (this.monitor) { + if (this.done) { + return false; + } - World getWorld() - { - return this.world; - } + this.watch.reset(); + this.watch.start(); + this.running = true; - /** - * returns true if this needs more simulation. - * - * @param milli milliseconds of simulation - * @return true if this needs more simulation - */ - public boolean simulateFor( final int milli ) - { - this.time = milli; + AELog.craftingDebug("main thread is now going to sleep"); - synchronized( this.monitor ) - { - if( this.done ) - { - return false; - } + this.monitor.notify(); - this.watch.reset(); - this.watch.start(); - this.running = true; + while (this.running) { + try { + this.monitor.wait(); + } catch (final InterruptedException ignored) {} + } - AELog.craftingDebug( "main thread is now going to sleep" ); + AELog.craftingDebug("main thread is now active"); + } - this.monitor.notify(); + return true; + } - while( this.running ) - { - try - { - this.monitor.wait(); - } - catch( final InterruptedException ignored ) - { - } - } + void addBytes(final long crafts) { + this.bytes += crafts; + } - AELog.craftingDebug( "main thread is now active" ); - } + public CraftingTreeNode getTree() { + return this.tree; + } - return true; - } + private void setTree(final CraftingTreeNode tree) { + this.tree = tree; + } - void addBytes( final long crafts ) - { - this.bytes += crafts; - } + private void logCraftingJob(String type, Stopwatch timer) { + if (AELog.isCraftingLogEnabled()) { + final String itemToOutput = this.output.toString(); + final long elapsedTime = timer.elapsed(TimeUnit.MILLISECONDS); + final String actionSource; - public CraftingTreeNode getTree() - { - return this.tree; - } + if (this.actionSrc instanceof MachineSource) { + final IActionHost machineSource = ((MachineSource) this.actionSrc).via; + final IGridNode actionableNode = machineSource.getActionableNode(); + final IGridHost machine = actionableNode.getMachine(); + final DimensionalCoord location + = actionableNode.getGridBlock().getLocation(); - private void setTree( final CraftingTreeNode tree ) - { - this.tree = tree; - } + actionSource + = String.format(LOG_MACHINE_SOURCE_DETAILS, machine, location); + } else if (this.actionSrc instanceof PlayerSource) { + final PlayerSource source = (PlayerSource) this.actionSrc; + final EntityPlayer player = source.player; - private void logCraftingJob( String type, Stopwatch timer ) - { - if( AELog.isCraftingLogEnabled() ) - { - final String itemToOutput = this.output.toString(); - final long elapsedTime = timer.elapsed( TimeUnit.MILLISECONDS ); - final String actionSource; + actionSource = player.toString(); + } else { + actionSource = "[unknown source]"; + } - if( this.actionSrc instanceof MachineSource ) - { - final IActionHost machineSource = ( (MachineSource) this.actionSrc ).via; - final IGridNode actionableNode = machineSource.getActionableNode(); - final IGridHost machine = actionableNode.getMachine(); - final DimensionalCoord location = actionableNode.getGridBlock().getLocation(); + AELog.crafting( + LOG_CRAFTING_JOB, + type, + actionSource, + itemToOutput, + this.bytes, + elapsedTime + ); + } + } - actionSource = String.format( LOG_MACHINE_SOURCE_DETAILS, machine, location ); - } - else if( this.actionSrc instanceof PlayerSource ) - { - final PlayerSource source = (PlayerSource) this.actionSrc; - final EntityPlayer player = source.player; - - actionSource = player.toString(); - } - else - { - actionSource = "[unknown source]"; - } - - AELog.crafting( LOG_CRAFTING_JOB, type, actionSource, itemToOutput, this.bytes, elapsedTime ); - } - } - - private static class TwoIntegers - { - private final long perOp = 0; - private final long times = 0; - } + private static class TwoIntegers { + private final long perOp = 0; + private final long times = 0; + } } diff --git a/src/main/java/appeng/crafting/CraftingLink.java b/src/main/java/appeng/crafting/CraftingLink.java index 1ea6e6ec..e6ff78ff 100644 --- a/src/main/java/appeng/crafting/CraftingLink.java +++ b/src/main/java/appeng/crafting/CraftingLink.java @@ -18,7 +18,6 @@ package appeng.crafting; - import appeng.api.config.Actionable; import appeng.api.networking.crafting.ICraftingCPU; import appeng.api.networking.crafting.ICraftingLink; @@ -26,189 +25,159 @@ import appeng.api.networking.crafting.ICraftingRequester; import appeng.api.storage.data.IAEItemStack; import net.minecraft.nbt.NBTTagCompound; +public class CraftingLink implements ICraftingLink { + private final ICraftingRequester req; + private final ICraftingCPU cpu; + private final String CraftID; + private final boolean standalone; + private boolean canceled = false; + private boolean done = false; + private CraftingLinkNexus tie; -public class CraftingLink implements ICraftingLink -{ + public CraftingLink(final NBTTagCompound data, final ICraftingRequester req) { + this.CraftID = data.getString("CraftID"); + this.setCanceled(data.getBoolean("canceled")); + this.setDone(data.getBoolean("done")); + this.standalone = data.getBoolean("standalone"); - private final ICraftingRequester req; - private final ICraftingCPU cpu; - private final String CraftID; - private final boolean standalone; - private boolean canceled = false; - private boolean done = false; - private CraftingLinkNexus tie; + if (!data.hasKey("req") || !data.getBoolean("req")) { + throw new IllegalStateException("Invalid Crafting Link for Object"); + } - public CraftingLink( final NBTTagCompound data, final ICraftingRequester req ) - { - this.CraftID = data.getString( "CraftID" ); - this.setCanceled( data.getBoolean( "canceled" ) ); - this.setDone( data.getBoolean( "done" ) ); - this.standalone = data.getBoolean( "standalone" ); + this.req = req; + this.cpu = null; + } - if( !data.hasKey( "req" ) || !data.getBoolean( "req" ) ) - { - throw new IllegalStateException( "Invalid Crafting Link for Object" ); - } + public CraftingLink(final NBTTagCompound data, final ICraftingCPU cpu) { + this.CraftID = data.getString("CraftID"); + this.setCanceled(data.getBoolean("canceled")); + this.setDone(data.getBoolean("done")); + this.standalone = data.getBoolean("standalone"); - this.req = req; - this.cpu = null; - } + if (!data.hasKey("req") || data.getBoolean("req")) { + throw new IllegalStateException("Invalid Crafting Link for Object"); + } - public CraftingLink( final NBTTagCompound data, final ICraftingCPU cpu ) - { - this.CraftID = data.getString( "CraftID" ); - this.setCanceled( data.getBoolean( "canceled" ) ); - this.setDone( data.getBoolean( "done" ) ); - this.standalone = data.getBoolean( "standalone" ); + this.cpu = cpu; + this.req = null; + } - if( !data.hasKey( "req" ) || data.getBoolean( "req" ) ) - { - throw new IllegalStateException( "Invalid Crafting Link for Object" ); - } + @Override + public boolean isCanceled() { + if (this.canceled) { + return true; + } - this.cpu = cpu; - this.req = null; - } + if (this.done) { + return false; + } - @Override - public boolean isCanceled() - { - if( this.canceled ) - { - return true; - } + if (this.tie == null) { + return false; + } - if( this.done ) - { - return false; - } + return this.tie.isCanceled(); + } - if( this.tie == null ) - { - return false; - } + @Override + public boolean isDone() { + if (this.done) { + return true; + } - return this.tie.isCanceled(); - } + if (this.canceled) { + return false; + } - @Override - public boolean isDone() - { - if( this.done ) - { - return true; - } + if (this.tie == null) { + return false; + } - if( this.canceled ) - { - return false; - } + return this.tie.isDone(); + } - if( this.tie == null ) - { - return false; - } + @Override + public void cancel() { + if (this.done) { + return; + } - return this.tie.isDone(); - } + this.setCanceled(true); - @Override - public void cancel() - { - if( this.done ) - { - return; - } + if (this.tie != null) { + this.tie.cancel(); + } - this.setCanceled( true ); + this.tie = null; + } - if( this.tie != null ) - { - this.tie.cancel(); - } + @Override + public boolean isStandalone() { + return this.standalone; + } - this.tie = null; - } + @Override + public void writeToNBT(final NBTTagCompound tag) { + tag.setString("CraftID", this.CraftID); + tag.setBoolean("canceled", this.isCanceled()); + tag.setBoolean("done", this.isDone()); + tag.setBoolean("standalone", this.standalone); + tag.setBoolean("req", this.getRequester() != null); + } - @Override - public boolean isStandalone() - { - return this.standalone; - } + @Override + public String getCraftingID() { + return this.CraftID; + } - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - tag.setString( "CraftID", this.CraftID ); - tag.setBoolean( "canceled", this.isCanceled() ); - tag.setBoolean( "done", this.isDone() ); - tag.setBoolean( "standalone", this.standalone ); - tag.setBoolean( "req", this.getRequester() != null ); - } + public void setNexus(final CraftingLinkNexus n) { + if (this.tie != null) { + this.tie.remove(this); + } - @Override - public String getCraftingID() - { - return this.CraftID; - } + if (this.isCanceled() && n != null) { + n.cancel(); + this.tie = null; + return; + } - public void setNexus( final CraftingLinkNexus n ) - { - if( this.tie != null ) - { - this.tie.remove( this ); - } + this.tie = n; - if( this.isCanceled() && n != null ) - { - n.cancel(); - this.tie = null; - return; - } + if (n != null) { + n.add(this); + } + } - this.tie = n; + public IAEItemStack injectItems(final IAEItemStack input, final Actionable mode) { + if (this.tie == null || this.tie.getRequest() == null + || this.tie.getRequest().getRequester() == null) { + return input; + } - if( n != null ) - { - n.add( this ); - } - } + return this.tie.getRequest().getRequester().injectCraftedItems( + this.tie.getRequest(), input, mode + ); + } - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode ) - { - if( this.tie == null || this.tie.getRequest() == null || this.tie.getRequest().getRequester() == null ) - { - return input; - } + public void markDone() { + if (this.tie != null) { + this.tie.markDone(); + } + } - return this.tie.getRequest().getRequester().injectCraftedItems( this.tie.getRequest(), input, mode ); - } + void setCanceled(final boolean canceled) { + this.canceled = canceled; + } - public void markDone() - { - if( this.tie != null ) - { - this.tie.markDone(); - } - } + ICraftingRequester getRequester() { + return this.req; + } - void setCanceled( final boolean canceled ) - { - this.canceled = canceled; - } + ICraftingCPU getCpu() { + return this.cpu; + } - ICraftingRequester getRequester() - { - return this.req; - } - - ICraftingCPU getCpu() - { - return this.cpu; - } - - void setDone( final boolean done ) - { - this.done = done; - } + void setDone(final boolean done) { + this.done = done; + } } diff --git a/src/main/java/appeng/crafting/CraftingLinkNexus.java b/src/main/java/appeng/crafting/CraftingLinkNexus.java index 7a30dcf6..d3371455 100644 --- a/src/main/java/appeng/crafting/CraftingLinkNexus.java +++ b/src/main/java/appeng/crafting/CraftingLinkNexus.java @@ -18,157 +18,121 @@ package appeng.crafting; - import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.me.cache.CraftingGridCache; +public class CraftingLinkNexus { + private final String craftID; + private boolean canceled = false; + private boolean done = false; + private int tickOfDeath = 0; + private CraftingLink req; + private CraftingLink cpu; -public class CraftingLinkNexus -{ + public CraftingLinkNexus(final String craftID) { + this.craftID = craftID; + } - private final String craftID; - private boolean canceled = false; - private boolean done = false; - private int tickOfDeath = 0; - private CraftingLink req; - private CraftingLink cpu; + public boolean isDead(final IGrid g, final CraftingGridCache craftingGridCache) { + if (this.canceled || this.done) { + return true; + } - public CraftingLinkNexus( final String craftID ) - { - this.craftID = craftID; - } + if (this.getRequest() == null || this.cpu == null) { + this.tickOfDeath++; + } else { + final boolean hasCpu = craftingGridCache.hasCpu(this.cpu.getCpu()); + final boolean hasMachine + = this.getRequest().getRequester().getActionableNode().getGrid() == g; - public boolean isDead( final IGrid g, final CraftingGridCache craftingGridCache ) - { - if( this.canceled || this.done ) - { - return true; - } + if (hasCpu && hasMachine) { + this.tickOfDeath = 0; + } else { + this.tickOfDeath += 60; + } + } - if( this.getRequest() == null || this.cpu == null ) - { - this.tickOfDeath++; - } - else - { - final boolean hasCpu = craftingGridCache.hasCpu( this.cpu.getCpu() ); - final boolean hasMachine = this.getRequest().getRequester().getActionableNode().getGrid() == g; + if (this.tickOfDeath > 60) { + this.cancel(); + return true; + } - if( hasCpu && hasMachine ) - { - this.tickOfDeath = 0; - } - else - { - this.tickOfDeath += 60; - } - } + return false; + } - if( this.tickOfDeath > 60 ) - { - this.cancel(); - return true; - } + void cancel() { + this.canceled = true; - return false; - } + if (this.getRequest() != null) { + this.getRequest().setCanceled(true); + if (this.getRequest().getRequester() != null) { + this.getRequest().getRequester().jobStateChange(this.getRequest()); + } + } - void cancel() - { - this.canceled = true; + if (this.cpu != null) { + this.cpu.setCanceled(true); + } + } - if( this.getRequest() != null ) - { - this.getRequest().setCanceled( true ); - if( this.getRequest().getRequester() != null ) - { - this.getRequest().getRequester().jobStateChange( this.getRequest() ); - } - } + void remove(final CraftingLink craftingLink) { + if (this.getRequest() == craftingLink) { + this.setRequest(null); + } else if (this.cpu == craftingLink) { + this.cpu = null; + } + } - if( this.cpu != null ) - { - this.cpu.setCanceled( true ); - } - } + void add(final CraftingLink craftingLink) { + if (craftingLink.getCpu() != null) { + this.cpu = craftingLink; + } else if (craftingLink.getRequester() != null) { + this.setRequest(craftingLink); + } + } - void remove( final CraftingLink craftingLink ) - { - if( this.getRequest() == craftingLink ) - { - this.setRequest( null ); - } - else if( this.cpu == craftingLink ) - { - this.cpu = null; - } - } + boolean isCanceled() { + return this.canceled; + } - void add( final CraftingLink craftingLink ) - { - if( craftingLink.getCpu() != null ) - { - this.cpu = craftingLink; - } - else if( craftingLink.getRequester() != null ) - { - this.setRequest( craftingLink ); - } - } + boolean isDone() { + return this.done; + } - boolean isCanceled() - { - return this.canceled; - } + void markDone() { + this.done = true; - boolean isDone() - { - return this.done; - } + if (this.getRequest() != null) { + this.getRequest().setDone(true); + if (this.getRequest().getRequester() != null) { + this.getRequest().getRequester().jobStateChange(this.getRequest()); + } + } - void markDone() - { - this.done = true; + if (this.cpu != null) { + this.cpu.setDone(true); + } + } - if( this.getRequest() != null ) - { - this.getRequest().setDone( true ); - if( this.getRequest().getRequester() != null ) - { - this.getRequest().getRequester().jobStateChange( this.getRequest() ); - } - } + public boolean isMachine(final IGridHost machine) { + return this.getRequest() == machine; + } - if( this.cpu != null ) - { - this.cpu.setDone( true ); - } - } + public void removeNode() { + if (this.getRequest() != null) { + this.getRequest().setNexus(null); + } - public boolean isMachine( final IGridHost machine ) - { - return this.getRequest() == machine; - } + this.setRequest(null); + this.tickOfDeath = 0; + } - public void removeNode() - { - if( this.getRequest() != null ) - { - this.getRequest().setNexus( null ); - } + public CraftingLink getRequest() { + return req; + } - this.setRequest( null ); - this.tickOfDeath = 0; - } - - public CraftingLink getRequest() - { - return req; - } - - public void setRequest( CraftingLink req ) - { - this.req = req; - } + public void setRequest(CraftingLink req) { + this.req = req; + } } diff --git a/src/main/java/appeng/crafting/CraftingTreeNode.java b/src/main/java/appeng/crafting/CraftingTreeNode.java index 583218a1..af0ba2f4 100644 --- a/src/main/java/appeng/crafting/CraftingTreeNode.java +++ b/src/main/java/appeng/crafting/CraftingTreeNode.java @@ -18,6 +18,10 @@ package appeng.crafting; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -31,375 +35,331 @@ import appeng.me.cluster.implementations.CraftingCPUCluster; import com.google.common.collect.Lists; import net.minecraft.world.World; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; +public class CraftingTreeNode { + // what slot! + private final int slot; + private final CraftingJob job; + private final IItemList used + = AEApi.instance().storage().createItemList(); + // parent node. + private final CraftingTreeProcess parent; + private final World world; + // what item is this? + private final IAEItemStack what; + // what are the crafting patterns for this? + private final ArrayList nodes + = new ArrayList(); + private int bytes = 0; + private boolean canEmit = false; + private long missing = 0; + private long howManyEmitted = 0; + private boolean exhausted = false; + private boolean sim; -public class CraftingTreeNode -{ + public CraftingTreeNode( + final ICraftingGrid cc, + final CraftingJob job, + final IAEItemStack wat, + final CraftingTreeProcess par, + final int slot, + final int depth + ) { + this.what = wat; + this.parent = par; + this.slot = slot; + this.world = job.getWorld(); + this.job = job; + this.sim = false; - // what slot! - private final int slot; - private final CraftingJob job; - private final IItemList used = AEApi.instance().storage().createItemList(); - // parent node. - private final CraftingTreeProcess parent; - private final World world; - // what item is this? - private final IAEItemStack what; - // what are the crafting patterns for this? - private final ArrayList nodes = new ArrayList(); - private int bytes = 0; - private boolean canEmit = false; - private long missing = 0; - private long howManyEmitted = 0; - private boolean exhausted = false; + this.canEmit = cc.canEmitFor(this.what); - private boolean sim; + if (this.canEmit) { + return; // if you can emit for something, you can't make it with patterns. + } - public CraftingTreeNode( final ICraftingGrid cc, final CraftingJob job, final IAEItemStack wat, final CraftingTreeProcess par, final int slot, final int depth ) - { - this.what = wat; - this.parent = par; - this.slot = slot; - this.world = job.getWorld(); - this.job = job; - this.sim = false; + for (final 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)) { + this.nodes.add(new CraftingTreeProcess(cc, job, details, this, depth + 1) + ); + } + } + } - this.canEmit = cc.canEmitFor( this.what ); + boolean notRecursive(final ICraftingPatternDetails details) { + IAEItemStack[] o = details.getCondensedOutputs(); - if( this.canEmit ) - { - return; // if you can emit for something, you can't make it with patterns. - } + for (final IAEItemStack i : o) { + if (i.equals(this.what)) { + return false; + } + } - for( final 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 ) ) - { - this.nodes.add( new CraftingTreeProcess( cc, job, details, this, depth + 1 ) ); - } - } - } + o = details.getCondensedInputs(); - boolean notRecursive( final ICraftingPatternDetails details ) - { - IAEItemStack[] o = details.getCondensedOutputs(); + for (final IAEItemStack i : o) { + if (i.equals(this.what)) { + return false; + } + } - for( final IAEItemStack i : o ) - { - if( i.equals( this.what ) ) - { - return false; - } - } + if (this.parent == null) { + return true; + } - o = details.getCondensedInputs(); + return this.parent.notRecursive(details); + } - for( final IAEItemStack i : o ) - { - if( i.equals( this.what ) ) - { - return false; - } - } + IAEItemStack + request(final MECraftingInventory inv, long l, final BaseActionSource src) + throws CraftBranchFailure, InterruptedException { + this.job.handlePausing(); - if( this.parent == null ) - { - return true; - } + final List thingsUsed = new LinkedList(); - return this.parent.notRecursive( details ); - } + this.what.setStackSize(l); + if (this.getSlot() >= 0 && this.parent != null + && this.parent.details.isCraftable()) { + final Collection itemList; + final IItemList inventoryList = inv.getItemList(); - IAEItemStack request( final MECraftingInventory inv, long l, final BaseActionSource src ) throws CraftBranchFailure, InterruptedException - { - this.job.handlePausing(); + if (this.parent.details.canSubstitute()) { + itemList = inventoryList.findFuzzy(this.what, FuzzyMode.IGNORE_ALL); + } else { + itemList = Lists.newArrayList(); - final List thingsUsed = new LinkedList(); + final IAEItemStack item = inventoryList.findPrecise(this.what); - this.what.setStackSize( l ); - if( this.getSlot() >= 0 && this.parent != null && this.parent.details.isCraftable() ) - { - final Collection itemList; - final IItemList inventoryList = inv.getItemList(); + if (item != null) { + itemList.add(item); + } + } - if( this.parent.details.canSubstitute() ) - { - itemList = inventoryList.findFuzzy( this.what, FuzzyMode.IGNORE_ALL ); - } - else - { - itemList = Lists.newArrayList(); + for (IAEItemStack fuzz : itemList) { + if (this.parent.details.isValidItemForSlot( + this.getSlot(), fuzz.getItemStack(), this.world + )) { + fuzz = fuzz.copy(); + fuzz.setStackSize(l); - final IAEItemStack item = inventoryList.findPrecise( this.what ); + final IAEItemStack available + = inv.extractItems(fuzz, Actionable.MODULATE, src); - if( item != null ) - { - itemList.add( item ); - } - } + if (available != null) { + if (!this.exhausted) { + final IAEItemStack is = this.job.checkUse(available); - for( IAEItemStack fuzz : itemList ) - { - if( this.parent.details.isValidItemForSlot( this.getSlot(), fuzz.getItemStack(), this.world ) ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( l ); + if (is != null) { + thingsUsed.add(is.copy()); + this.used.add(is); + } + } - final IAEItemStack available = inv.extractItems( fuzz, Actionable.MODULATE, src ); + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - if( available != null ) - { - if( !this.exhausted ) - { - final IAEItemStack is = this.job.checkUse( available ); + if (l == 0) { + return available; + } + } + } + } + } else { + final IAEItemStack available + = inv.extractItems(this.what, Actionable.MODULATE, src); - if( is != null ) - { - thingsUsed.add( is.copy() ); - this.used.add( is ); - } - } + if (available != null) { + if (!this.exhausted) { + final IAEItemStack is = this.job.checkUse(available); - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + if (is != null) { + thingsUsed.add(is.copy()); + this.used.add(is); + } + } - if( l == 0 ) - { - return available; - } - } - } - } - } - else - { - final IAEItemStack available = inv.extractItems( this.what, Actionable.MODULATE, src ); + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - if( available != null ) - { - if( !this.exhausted ) - { - final IAEItemStack is = this.job.checkUse( available ); + if (l == 0) { + return available; + } + } + } - if( is != null ) - { - thingsUsed.add( is.copy() ); - this.used.add( is ); - } - } + if (this.canEmit) { + final IAEItemStack wat = this.what.copy(); + wat.setStackSize(l); - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + this.howManyEmitted = wat.getStackSize(); + this.bytes += wat.getStackSize(); - if( l == 0 ) - { - return available; - } - } - } + return wat; + } - if( this.canEmit ) - { - final IAEItemStack wat = this.what.copy(); - wat.setStackSize( l ); + this.exhausted = true; - this.howManyEmitted = wat.getStackSize(); - this.bytes += wat.getStackSize(); + if (this.nodes.size() == 1) { + final CraftingTreeProcess pro = this.nodes.get(0); - return wat; - } + while (pro.possible && l > 0) { + final IAEItemStack madeWhat = pro.getAmountCrafted(this.what); - this.exhausted = true; + pro.request(inv, pro.getTimes(l, madeWhat.getStackSize()), src); - if( this.nodes.size() == 1 ) - { - final CraftingTreeProcess pro = this.nodes.get( 0 ); + madeWhat.setStackSize(l); - while( pro.possible && l > 0 ) - { - final IAEItemStack madeWhat = pro.getAmountCrafted( this.what ); + final IAEItemStack available + = inv.extractItems(madeWhat, Actionable.MODULATE, src); - pro.request( inv, pro.getTimes( l, madeWhat.getStackSize() ), src ); + if (available != null) { + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - madeWhat.setStackSize( l ); + if (l <= 0) { + return available; + } + } else { + pro.possible = false; // ;P + } + } + } else if (this.nodes.size() > 1) { + for (final CraftingTreeProcess pro : this.nodes) { + try { + while (pro.possible && l > 0) { + final MECraftingInventory subInv + = new MECraftingInventory(inv, true, true, true); + pro.request(subInv, 1, src); - final IAEItemStack available = inv.extractItems( madeWhat, Actionable.MODULATE, src ); + this.what.setStackSize(l); + final IAEItemStack available + = subInv.extractItems(this.what, Actionable.MODULATE, src); - if( available != null ) - { - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + if (available != null) { + if (!subInv.commit(src)) { + throw new CraftBranchFailure(this.what, l); + } - if( l <= 0 ) - { - return available; - } - } - else - { - pro.possible = false; // ;P - } - } - } - else if( this.nodes.size() > 1 ) - { - for( final CraftingTreeProcess pro : this.nodes ) - { - try - { - while( pro.possible && l > 0 ) - { - final MECraftingInventory subInv = new MECraftingInventory( inv, true, true, true ); - pro.request( subInv, 1, src ); + this.bytes += available.getStackSize(); + l -= available.getStackSize(); - this.what.setStackSize( l ); - final IAEItemStack available = subInv.extractItems( this.what, Actionable.MODULATE, src ); + if (l <= 0) { + return available; + } + } else { + pro.possible = false; // ;P + } + } + } catch (final CraftBranchFailure fail) { + pro.possible = true; + } + } + } - if( available != null ) - { - if( !subInv.commit( src ) ) - { - throw new CraftBranchFailure( this.what, l ); - } + if (this.sim) { + this.missing += l; + this.bytes += l; + final IAEItemStack rv = this.what.copy(); + rv.setStackSize(l); + return rv; + } - this.bytes += available.getStackSize(); - l -= available.getStackSize(); + for (final IAEItemStack o : thingsUsed) { + this.job.refund(o.copy()); + o.setStackSize(-o.getStackSize()); + this.used.add(o); + } - if( l <= 0 ) - { - return available; - } - } - else - { - pro.possible = false; // ;P - } - } - } - catch( final CraftBranchFailure fail ) - { - pro.possible = true; - } - } - } + throw new CraftBranchFailure(this.what, l); + } - if( this.sim ) - { - this.missing += l; - this.bytes += l; - final IAEItemStack rv = this.what.copy(); - rv.setStackSize( l ); - return rv; - } + void dive(final CraftingJob job) { + if (this.missing > 0) { + job.addMissing(this.getStack(this.missing)); + } + // missing = 0; - for( final IAEItemStack o : thingsUsed ) - { - this.job.refund( o.copy() ); - o.setStackSize( -o.getStackSize() ); - this.used.add( o ); - } + job.addBytes(8 + this.bytes); - throw new CraftBranchFailure( this.what, l ); - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.dive(job); + } + } - void dive( final CraftingJob job ) - { - if( this.missing > 0 ) - { - job.addMissing( this.getStack( this.missing ) ); - } - // missing = 0; + IAEItemStack getStack(final long size) { + final IAEItemStack is = this.what.copy(); + is.setStackSize(size); + return is; + } - job.addBytes( 8 + this.bytes ); + void setSimulate() { + this.sim = true; + this.missing = 0; + this.bytes = 0; + this.used.resetStatus(); + this.exhausted = false; - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.dive( job ); - } - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.setSimulate(); + } + } - IAEItemStack getStack( final long size ) - { - final IAEItemStack is = this.what.copy(); - is.setStackSize( size ); - return is; - } + public void setJob( + final MECraftingInventory storage, + final CraftingCPUCluster craftingCPUCluster, + final BaseActionSource src + ) throws CraftBranchFailure { + for (final IAEItemStack i : this.used) { + final IAEItemStack ex = storage.extractItems(i, Actionable.MODULATE, src); - void setSimulate() - { - this.sim = true; - this.missing = 0; - this.bytes = 0; - this.used.resetStatus(); - this.exhausted = false; + if (ex == null || ex.getStackSize() != i.getStackSize()) { + throw new CraftBranchFailure(i, i.getStackSize()); + } - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.setSimulate(); - } - } + craftingCPUCluster.addStorage(ex); + } - public void setJob( final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final BaseActionSource src ) throws CraftBranchFailure - { - for( final IAEItemStack i : this.used ) - { - final IAEItemStack ex = storage.extractItems( i, Actionable.MODULATE, src ); + if (this.howManyEmitted > 0) { + final IAEItemStack i = this.what.copy(); + i.setStackSize(this.howManyEmitted); + craftingCPUCluster.addEmitable(i); + } - if( ex == null || ex.getStackSize() != i.getStackSize() ) - { - throw new CraftBranchFailure( i, i.getStackSize() ); - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.setJob(storage, craftingCPUCluster, src); + } + } - craftingCPUCluster.addStorage( ex ); - } + void getPlan(final IItemList plan) { + if (this.missing > 0) { + final IAEItemStack o = this.what.copy(); + o.setStackSize(this.missing); + plan.add(o); + } - if( this.howManyEmitted > 0 ) - { - final IAEItemStack i = this.what.copy(); - i.setStackSize( this.howManyEmitted ); - craftingCPUCluster.addEmitable( i ); - } + if (this.howManyEmitted > 0) { + final IAEItemStack i = this.what.copy(); + i.setCountRequestable(this.howManyEmitted); + plan.addRequestable(i); + } - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.setJob( storage, craftingCPUCluster, src ); - } - } + for (final IAEItemStack i : this.used) { + plan.add(i.copy()); + } - void getPlan( final IItemList plan ) - { - if( this.missing > 0 ) - { - final IAEItemStack o = this.what.copy(); - o.setStackSize( this.missing ); - plan.add( o ); - } + for (final CraftingTreeProcess pro : this.nodes) { + pro.getPlan(plan); + } + } - if( this.howManyEmitted > 0 ) - { - final IAEItemStack i = this.what.copy(); - i.setCountRequestable( this.howManyEmitted ); - plan.addRequestable( i ); - } - - for( final IAEItemStack i : this.used ) - { - plan.add( i.copy() ); - } - - for( final CraftingTreeProcess pro : this.nodes ) - { - pro.getPlan( plan ); - } - } - - int getSlot() - { - return this.slot; - } + int getSlot() { + return this.slot; + } } diff --git a/src/main/java/appeng/crafting/CraftingTreeProcess.java b/src/main/java/appeng/crafting/CraftingTreeProcess.java index c5d86e8e..6fc62308 100644 --- a/src/main/java/appeng/crafting/CraftingTreeProcess.java +++ b/src/main/java/appeng/crafting/CraftingTreeProcess.java @@ -18,6 +18,9 @@ package appeng.crafting; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -35,289 +38,274 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; +public class CraftingTreeProcess { + private final CraftingTreeNode parent; + final ICraftingPatternDetails details; + private final CraftingJob job; + private final Map nodes + = new HashMap(); + private final int depth; + boolean possible = true; + private World world; + private long crafts = 0; + private boolean containerItems; + private boolean limitQty; + private boolean fullSimulation; + private long bytes = 0; + public CraftingTreeProcess( + final ICraftingGrid cc, + final CraftingJob job, + final ICraftingPatternDetails details, + final CraftingTreeNode craftingTreeNode, + final int depth + ) { + this.parent = craftingTreeNode; + this.details = details; + this.job = job; + this.depth = depth; + final World world = job.getWorld(); -public class CraftingTreeProcess -{ + if (details.isCraftable()) { + final IAEItemStack[] list = details.getInputs(); - private final CraftingTreeNode parent; - final ICraftingPatternDetails details; - private final CraftingJob job; - private final Map nodes = new HashMap(); - private final int depth; - boolean possible = true; - private World world; - private long crafts = 0; - private boolean containerItems; - private boolean limitQty; - private boolean fullSimulation; - private long bytes = 0; + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); + final IAEItemStack[] is = details.getInputs(); + for (int x = 0; x < ic.getSizeInventory(); x++) { + ic.setInventorySlotContents( + x, is[x] == null ? null : is[x].getItemStack() + ); + } - public CraftingTreeProcess( final ICraftingGrid cc, final CraftingJob job, final ICraftingPatternDetails details, final CraftingTreeNode craftingTreeNode, final int depth ) - { - this.parent = craftingTreeNode; - this.details = details; - this.job = job; - this.depth = depth; - final World world = job.getWorld(); + FMLCommonHandler.instance().firePlayerCraftingEvent( + Platform.getPlayer((WorldServer) world), details.getOutput(ic, world), ic + ); - if( details.isCraftable() ) - { - final IAEItemStack[] list = details.getInputs(); + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack g = ic.getStackInSlot(x); + if (g != null && g.stackSize > 1) { + this.fullSimulation = true; + } + } - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); - final IAEItemStack[] is = details.getInputs(); - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - ic.setInventorySlotContents( x, is[x] == null ? null : is[x].getItemStack() ); - } + for (final IAEItemStack part : details.getCondensedInputs()) { + final ItemStack g = part.getItemStack(); - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) world ), details.getOutput( ic, world ), ic ); + boolean isAnInput = false; + for (final IAEItemStack a : details.getCondensedOutputs()) { + if (g != null && a != null && a.equals(g)) { + isAnInput = true; + } + } - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack g = ic.getStackInSlot( x ); - if( g != null && g.stackSize > 1 ) - { - this.fullSimulation = true; - } - } + if (isAnInput) { + this.limitQty = true; + } - for( final IAEItemStack part : details.getCondensedInputs() ) - { - final ItemStack g = part.getItemStack(); + if (g.getItem().hasContainerItem(g)) { + this.limitQty = this.containerItems = true; + } + } - boolean isAnInput = false; - for( final IAEItemStack a : details.getCondensedOutputs() ) - { - if( g != null && a != null && a.equals( g ) ) - { - isAnInput = true; - } - } + final boolean complicated = false; - if( isAnInput ) - { - this.limitQty = true; - } + if (this.containerItems || complicated) { + for (int x = 0; x < list.length; x++) { + final IAEItemStack part = list[x]; + 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 (final IAEItemStack part : details.getCondensedInputs()) { + for (int x = 0; x < list.length; x++) { + final IAEItemStack comparePart = list[x]; + 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() + ); + break; + } + } + } + } + } else { + for (final IAEItemStack part : details.getCondensedInputs()) { + final ItemStack g = part.getItemStack(); - if( g.getItem().hasContainerItem( g ) ) - { - this.limitQty = this.containerItems = true; - } - } + boolean isAnInput = false; + for (final IAEItemStack a : details.getCondensedOutputs()) { + if (g != null && a != null && a.equals(g)) { + isAnInput = true; + } + } - final boolean complicated = false; + if (isAnInput) { + this.limitQty = true; + } + } - if( this.containerItems || complicated ) - { - for( int x = 0; x < list.length; x++ ) - { - final IAEItemStack part = list[x]; - 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( final IAEItemStack part : details.getCondensedInputs() ) - { - for( int x = 0; x < list.length; x++ ) - { - final IAEItemStack comparePart = list[x]; - 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() ); - break; - } - } - } - } - } - else - { - for( final IAEItemStack part : details.getCondensedInputs() ) - { - final ItemStack g = part.getItemStack(); + for (final IAEItemStack part : details.getCondensedInputs()) { + this.nodes.put( + new CraftingTreeNode(cc, job, part.copy(), this, -1, depth + 1), + part.getStackSize() + ); + } + } + } - boolean isAnInput = false; - for( final IAEItemStack a : details.getCondensedOutputs() ) - { - if( g != null && a != null && a.equals( g ) ) - { - isAnInput = true; - } - } + boolean notRecursive(final ICraftingPatternDetails details) { + return this.parent == null || this.parent.notRecursive(details); + } - if( isAnInput ) - { - this.limitQty = true; - } - } + long getTimes(final long remaining, final long stackSize) { + if (this.limitQty || this.fullSimulation) { + return 1; + } + return (remaining / stackSize) + (remaining % stackSize != 0 ? 1 : 0); + } - for( final IAEItemStack part : details.getCondensedInputs() ) - { - this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, -1, depth + 1 ), part.getStackSize() ); - } - } - } + void request(final MECraftingInventory inv, final long i, final BaseActionSource src) + throws CraftBranchFailure, InterruptedException { + this.job.handlePausing(); - boolean notRecursive( final ICraftingPatternDetails details ) - { - return this.parent == null || this.parent.notRecursive( details ); - } + if (this.fullSimulation) { + final InventoryCrafting ic = new InventoryCrafting(new ContainerNull(), 3, 3); - long getTimes( final long remaining, final long stackSize ) - { - if( this.limitQty || this.fullSimulation ) - { - return 1; - } - return ( remaining / stackSize ) + ( remaining % stackSize != 0 ? 1 : 0 ); - } + for (final Entry entry : this.nodes.entrySet()) { + final IAEItemStack item = entry.getKey().getStack(entry.getValue()); + final IAEItemStack stack + = entry.getKey().request(inv, item.getStackSize(), src); - void request( final MECraftingInventory inv, final long i, final BaseActionSource src ) throws CraftBranchFailure, InterruptedException - { - this.job.handlePausing(); + ic.setInventorySlotContents( + entry.getKey().getSlot(), stack.getItemStack() + ); + } - if( this.fullSimulation ) - { - final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 ); + FMLCommonHandler.instance().firePlayerCraftingEvent( + Platform.getPlayer((WorldServer) this.world), + this.details.getOutput(ic, this.world), + ic + ); - for( final Entry entry : this.nodes.entrySet() ) - { - final IAEItemStack item = entry.getKey().getStack( entry.getValue() ); - final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize(), src ); + for (int x = 0; x < ic.getSizeInventory(); x++) { + ItemStack is = ic.getStackInSlot(x); + is = Platform.getContainerItem(is); - ic.setInventorySlotContents( entry.getKey().getSlot(), stack.getItemStack() ); - } + final IAEItemStack o = AEApi.instance().storage().createItemStack(is); + if (o != null) { + this.bytes++; + inv.injectItems(o, Actionable.MODULATE, src); + } + } + } else { + // request and remove inputs... + for (final Entry entry : this.nodes.entrySet()) { + final IAEItemStack item = entry.getKey().getStack(entry.getValue()); + final IAEItemStack stack + = entry.getKey().request(inv, item.getStackSize() * i, src); - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.world ), this.details.getOutput( ic, this.world ), ic ); + if (this.containerItems) { + final ItemStack is = Platform.getContainerItem(stack.getItemStack()); + final IAEItemStack o = AEApi.instance().storage().createItemStack(is); + if (o != null) { + this.bytes++; + inv.injectItems(o, Actionable.MODULATE, src); + } + } + } + } - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - ItemStack is = ic.getStackInSlot( x ); - is = Platform.getContainerItem( is ); + // assume its possible. - final IAEItemStack o = AEApi.instance().storage().createItemStack( is ); - if( o != null ) - { - this.bytes++; - inv.injectItems( o, Actionable.MODULATE, src ); - } - } - } - else - { - // request and remove inputs... - for( final Entry entry : this.nodes.entrySet() ) - { - final IAEItemStack item = entry.getKey().getStack( entry.getValue() ); - final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize() * i, src ); + // add crafting results.. + for (final IAEItemStack out : this.details.getCondensedOutputs()) { + final IAEItemStack o = out.copy(); + o.setStackSize(o.getStackSize() * i); + inv.injectItems(o, Actionable.MODULATE, src); + } - if( this.containerItems ) - { - final ItemStack is = Platform.getContainerItem( stack.getItemStack() ); - final IAEItemStack o = AEApi.instance().storage().createItemStack( is ); - if( o != null ) - { - this.bytes++; - inv.injectItems( o, Actionable.MODULATE, src ); - } - } - } - } + this.crafts += i; + } - // assume its possible. + void dive(final CraftingJob job) { + job.addTask( + this.getAmountCrafted(this.parent.getStack(1)), + this.crafts, + this.details, + this.depth + ); + for (final CraftingTreeNode pro : this.nodes.keySet()) { + pro.dive(job); + } - // add crafting results.. - for( final IAEItemStack out : this.details.getCondensedOutputs() ) - { - final IAEItemStack o = out.copy(); - o.setStackSize( o.getStackSize() * i ); - inv.injectItems( o, Actionable.MODULATE, src ); - } + job.addBytes(8 + this.crafts + this.bytes); + } - this.crafts += i; - } + IAEItemStack getAmountCrafted(IAEItemStack what2) { + for (final IAEItemStack is : this.details.getCondensedOutputs()) { + if (is.equals(what2)) { + what2 = what2.copy(); + what2.setStackSize(is.getStackSize()); + return what2; + } + } - void dive( final CraftingJob job ) - { - job.addTask( this.getAmountCrafted( this.parent.getStack( 1 ) ), this.crafts, this.details, this.depth ); - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.dive( job ); - } + // more fuzzy! + for (final 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; + } + } - job.addBytes( 8 + this.crafts + this.bytes ); - } + throw new IllegalStateException("Crafting Tree construction failed."); + } - IAEItemStack getAmountCrafted( IAEItemStack what2 ) - { - for( final IAEItemStack is : this.details.getCondensedOutputs() ) - { - if( is.equals( what2 ) ) - { - what2 = what2.copy(); - what2.setStackSize( is.getStackSize() ); - return what2; - } - } + void setSimulate() { + this.crafts = 0; + this.bytes = 0; - // more fuzzy! - for( final 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; - } - } + for (final CraftingTreeNode pro : this.nodes.keySet()) { + pro.setSimulate(); + } + } - throw new IllegalStateException( "Crafting Tree construction failed." ); - } + void setJob( + final MECraftingInventory storage, + final CraftingCPUCluster craftingCPUCluster, + final BaseActionSource src + ) throws CraftBranchFailure { + craftingCPUCluster.addCrafting(this.details, this.crafts); - void setSimulate() - { - this.crafts = 0; - this.bytes = 0; + for (final CraftingTreeNode pro : this.nodes.keySet()) { + pro.setJob(storage, craftingCPUCluster, src); + } + } - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.setSimulate(); - } - } + void getPlan(final IItemList plan) { + for (IAEItemStack i : this.details.getOutputs()) { + i = i.copy(); + i.setCountRequestable(i.getStackSize() * this.crafts); + plan.addRequestable(i); + } - void setJob( final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final BaseActionSource src ) throws CraftBranchFailure - { - craftingCPUCluster.addCrafting( this.details, this.crafts ); - - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.setJob( storage, craftingCPUCluster, src ); - } - } - - void getPlan( final IItemList plan ) - { - for( IAEItemStack i : this.details.getOutputs() ) - { - i = i.copy(); - i.setCountRequestable( i.getStackSize() * this.crafts ); - plan.addRequestable( i ); - } - - for( final CraftingTreeNode pro : this.nodes.keySet() ) - { - pro.getPlan( plan ); - } - } + for (final 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 8dfe57c3..fc97cea0 100644 --- a/src/main/java/appeng/crafting/CraftingWatcher.java +++ b/src/main/java/appeng/crafting/CraftingWatcher.java @@ -18,184 +18,162 @@ package appeng.crafting; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import javax.annotation.Nonnull; import appeng.api.networking.crafting.ICraftingWatcher; import appeng.api.networking.crafting.ICraftingWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.CraftingGridCache; -import javax.annotation.Nonnull; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; - - /** - * Maintain my interests, and a global watch list, they should always be fully synchronized. + * Maintain my interests, and a global watch list, they should always be fully + * synchronized. */ -public class CraftingWatcher implements ICraftingWatcher -{ +public class CraftingWatcher implements ICraftingWatcher { + private final CraftingGridCache gsc; + private final ICraftingWatcherHost host; + private final HashSet myInterests = new HashSet(); - private final CraftingGridCache gsc; - private final ICraftingWatcherHost host; - private final HashSet myInterests = new HashSet(); + public CraftingWatcher( + final CraftingGridCache cache, final ICraftingWatcherHost host + ) { + this.gsc = cache; + this.host = host; + } - public CraftingWatcher( final CraftingGridCache cache, final ICraftingWatcherHost host ) - { - this.gsc = cache; - this.host = host; - } + public ICraftingWatcherHost getHost() { + return this.host; + } - public ICraftingWatcherHost getHost() - { - return this.host; - } + @Override + public int size() { + return this.myInterests.size(); + } - @Override - public int size() - { - return this.myInterests.size(); - } + @Override + public boolean isEmpty() { + return this.myInterests.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } + @Override + public boolean contains(final Object o) { + return this.myInterests.contains(o); + } - @Override - public boolean contains( final Object o ) - { - return this.myInterests.contains( o ); - } + @Nonnull + @Override + public Iterator iterator() { + return new ItemWatcherIterator(this, this.myInterests.iterator()); + } - @Nonnull - @Override - public Iterator iterator() - { - return new ItemWatcherIterator( this, this.myInterests.iterator() ); - } + @Nonnull + @Override + public Object[] toArray() { + return this.myInterests.toArray(); + } - @Nonnull - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } + @Nonnull + @Override + public T[] toArray(@Nonnull final T[] a) { + return this.myInterests.toArray(a); + } - @Nonnull - @Override - public T[] toArray( @Nonnull final T[] a ) - { - return this.myInterests.toArray( a ); - } + @Override + public boolean add(final IAEStack e) { + if (this.myInterests.contains(e)) { + return false; + } - @Override - public boolean add( final IAEStack e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } + return this.myInterests.add(e.copy()) + && this.gsc.getInterestManager().put(e, this); + } - return this.myInterests.add( e.copy() ) && this.gsc.getInterestManager().put( e, this ); - } + @Override + public boolean remove(final Object o) { + return this.myInterests.remove(o) + && this.gsc.getInterestManager().remove((IAEStack) o, this); + } - @Override - public boolean remove( final Object o ) - { - return this.myInterests.remove( o ) && this.gsc.getInterestManager().remove( (IAEStack) o, this ); - } + @Override + public boolean containsAll(@Nonnull final Collection c) { + return this.myInterests.containsAll(c); + } - @Override - public boolean containsAll( @Nonnull final Collection c ) - { - return this.myInterests.containsAll( c ); - } + @Override + public boolean addAll(@Nonnull final Collection c) { + boolean didChange = false; - @Override - public boolean addAll( @Nonnull final Collection c ) - { - boolean didChange = false; + for (final IAEStack o : c) { + didChange = this.add(o) || didChange; + } - for( final IAEStack o : c ) - { - didChange = this.add( o ) || didChange; - } + return didChange; + } - return didChange; - } + @Override + public boolean removeAll(@Nonnull final Collection c) { + boolean didSomething = false; + for (final Object o : c) { + didSomething = this.remove(o) || didSomething; + } + return didSomething; + } - @Override - public boolean removeAll( @Nonnull final Collection c ) - { - boolean didSomething = false; - for( final Object o : c ) - { - didSomething = this.remove( o ) || didSomething; - } - return didSomething; - } + @Override + public boolean retainAll(@Nonnull final Collection c) { + boolean changed = false; + final Iterator i = this.iterator(); - @Override - public boolean retainAll( @Nonnull final Collection c ) - { - boolean changed = false; - final Iterator i = this.iterator(); + while (i.hasNext()) { + if (!c.contains(i.next())) { + i.remove(); + changed = true; + } + } - while( i.hasNext() ) - { - if( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } + return changed; + } - return changed; - } + @Override + public void clear() { + final Iterator i = this.myInterests.iterator(); + while (i.hasNext()) { + this.gsc.getInterestManager().remove(i.next(), this); + i.remove(); + } + } - @Override - public void clear() - { - final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterestManager().remove( i.next(), this ); - i.remove(); - } - } + private class ItemWatcherIterator implements Iterator { + private final CraftingWatcher watcher; + private final Iterator interestIterator; + private IAEStack myLast; - private class ItemWatcherIterator implements Iterator - { + public ItemWatcherIterator( + final CraftingWatcher parent, final Iterator i + ) { + this.watcher = parent; + this.interestIterator = i; + } - private final CraftingWatcher watcher; - private final Iterator interestIterator; - private IAEStack myLast; + @Override + public boolean hasNext() { + return this.interestIterator.hasNext(); + } - public ItemWatcherIterator( final CraftingWatcher parent, final Iterator i ) - { - this.watcher = parent; - this.interestIterator = i; - } + @Override + public IAEStack next() { + return this.myLast = this.interestIterator.next(); + } - @Override - public boolean hasNext() - { - return this.interestIterator.hasNext(); - } - - @Override - public IAEStack next() - { - return this.myLast = this.interestIterator.next(); - } - - @Override - public void remove() - { - CraftingWatcher.this.gsc.getInterestManager().remove( this.myLast, this.watcher ); - this.interestIterator.remove(); - } - } + @Override + public void remove() { + CraftingWatcher.this.gsc.getInterestManager().remove( + this.myLast, this.watcher + ); + this.interestIterator.remove(); + } + } } diff --git a/src/main/java/appeng/crafting/MECraftingInventory.java b/src/main/java/appeng/crafting/MECraftingInventory.java index ff0c6771..b84b047f 100644 --- a/src/main/java/appeng/crafting/MECraftingInventory.java +++ b/src/main/java/appeng/crafting/MECraftingInventory.java @@ -18,7 +18,6 @@ package appeng.crafting; - import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -29,325 +28,282 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.util.inv.ItemListIgnoreCrafting; +public class MECraftingInventory implements IMEInventory { + private final MECraftingInventory par; -public class MECraftingInventory implements IMEInventory -{ + private final IMEInventory target; + private final IItemList localCache; - private final MECraftingInventory par; + private final boolean logExtracted; + private final IItemList extractedCache; - private final IMEInventory target; - private final IItemList localCache; + private final boolean logInjections; + private final IItemList injectedCache; - private final boolean logExtracted; - private final IItemList extractedCache; + private final boolean logMissing; + private final IItemList missingCache; - private final boolean logInjections; - private final IItemList injectedCache; + public MECraftingInventory() { + this.localCache + = new ItemListIgnoreCrafting<>(AEApi.instance().storage().createItemList()); + this.extractedCache = null; + this.injectedCache = null; + this.missingCache = null; + this.logExtracted = false; + this.logInjections = false; + this.logMissing = false; + this.target = null; + this.par = null; + } - private final boolean logMissing; - private final IItemList missingCache; + public MECraftingInventory(final MECraftingInventory parent) { + this.target = parent; + this.logExtracted = parent.logExtracted; + this.logInjections = parent.logInjections; + this.logMissing = parent.logMissing; - public MECraftingInventory() - { - this.localCache = new ItemListIgnoreCrafting<>( AEApi.instance().storage().createItemList() ); - this.extractedCache = null; - this.injectedCache = null; - this.missingCache = null; - this.logExtracted = false; - this.logInjections = false; - this.logMissing = false; - this.target = null; - this.par = null; - } + if (this.logMissing) { + this.missingCache = AEApi.instance().storage().createItemList(); + } else { + this.missingCache = null; + } - public MECraftingInventory( final MECraftingInventory parent ) - { - this.target = parent; - this.logExtracted = parent.logExtracted; - this.logInjections = parent.logInjections; - this.logMissing = parent.logMissing; + if (this.logExtracted) { + this.extractedCache = AEApi.instance().storage().createItemList(); + } else { + this.extractedCache = null; + } - if( this.logMissing ) - { - this.missingCache = AEApi.instance().storage().createItemList(); - } - else - { - this.missingCache = null; - } + if (this.logInjections) { + this.injectedCache = AEApi.instance().storage().createItemList(); + } else { + this.injectedCache = null; + } - if( this.logExtracted ) - { - this.extractedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.extractedCache = null; - } + this.localCache = this.target.getAvailableItems( + new ItemListIgnoreCrafting<>(AEApi.instance().storage().createItemList()) + ); - if( this.logInjections ) - { - this.injectedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.injectedCache = null; - } + this.par = parent; + } - this.localCache = this.target.getAvailableItems( new ItemListIgnoreCrafting<>( AEApi.instance().storage().createItemList() ) ); + public MECraftingInventory( + final IMEMonitor target, + final BaseActionSource src, + final boolean logExtracted, + final boolean logInjections, + final boolean logMissing + ) { + this.target = target; + this.logExtracted = logExtracted; + this.logInjections = logInjections; + this.logMissing = logMissing; - this.par = parent; - } + if (logMissing) { + this.missingCache = AEApi.instance().storage().createItemList(); + } else { + this.missingCache = null; + } - public MECraftingInventory( final IMEMonitor target, final BaseActionSource src, final boolean logExtracted, final boolean logInjections, final boolean logMissing ) - { - this.target = target; - this.logExtracted = logExtracted; - this.logInjections = logInjections; - this.logMissing = logMissing; + if (logExtracted) { + this.extractedCache = AEApi.instance().storage().createItemList(); + } else { + this.extractedCache = null; + } - if( logMissing ) - { - this.missingCache = AEApi.instance().storage().createItemList(); - } - else - { - this.missingCache = null; - } + if (logInjections) { + this.injectedCache = AEApi.instance().storage().createItemList(); + } else { + this.injectedCache = null; + } - if( logExtracted ) - { - this.extractedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.extractedCache = null; - } + this.localCache + = new ItemListIgnoreCrafting<>(AEApi.instance().storage().createItemList()); + for (final IAEItemStack is : target.getStorageList()) { + this.localCache.add(target.extractItems(is, Actionable.SIMULATE, src)); + } - if( logInjections ) - { - this.injectedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.injectedCache = null; - } + this.par = null; + } - this.localCache = new ItemListIgnoreCrafting<>( AEApi.instance().storage().createItemList() ); - for( final IAEItemStack is : target.getStorageList() ) - { - this.localCache.add( target.extractItems( is, Actionable.SIMULATE, src ) ); - } + public MECraftingInventory( + final IMEInventory target, + final boolean logExtracted, + final boolean logInjections, + final boolean logMissing + ) { + this.target = target; + this.logExtracted = logExtracted; + this.logInjections = logInjections; + this.logMissing = logMissing; - this.par = null; - } + if (logMissing) { + this.missingCache = AEApi.instance().storage().createItemList(); + } else { + this.missingCache = null; + } - public MECraftingInventory( final IMEInventory target, final boolean logExtracted, final boolean logInjections, final boolean logMissing ) - { - this.target = target; - this.logExtracted = logExtracted; - this.logInjections = logInjections; - this.logMissing = logMissing; + if (logExtracted) { + this.extractedCache = AEApi.instance().storage().createItemList(); + } else { + this.extractedCache = null; + } - if( logMissing ) - { - this.missingCache = AEApi.instance().storage().createItemList(); - } - else - { - this.missingCache = null; - } + if (logInjections) { + this.injectedCache = AEApi.instance().storage().createItemList(); + } else { + this.injectedCache = null; + } - if( logExtracted ) - { - this.extractedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.extractedCache = null; - } + this.localCache + = target.getAvailableItems(AEApi.instance().storage().createItemList()); + this.par = null; + } - if( logInjections ) - { - this.injectedCache = AEApi.instance().storage().createItemList(); - } - else - { - this.injectedCache = null; - } + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + if (input == null) { + return null; + } - this.localCache = target.getAvailableItems( AEApi.instance().storage().createItemList() ); - this.par = null; - } + if (mode == Actionable.MODULATE) { + if (this.logInjections) { + this.injectedCache.add(input); + } + this.localCache.add(input); + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( input == null ) - { - return null; - } + return null; + } - if( mode == Actionable.MODULATE ) - { - if( this.logInjections ) - { - this.injectedCache.add( input ); - } - this.localCache.add( input ); - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + if (request == null) { + return null; + } - return null; - } + final IAEItemStack list = this.localCache.findPrecise(request); + if (list == null || list.getStackSize() == 0) { + return null; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( request == null ) - { - return null; - } + if (list.getStackSize() >= request.getStackSize()) { + if (mode == Actionable.MODULATE) { + list.decStackSize(request.getStackSize()); + if (this.logExtracted) { + this.extractedCache.add(request); + } + } - final IAEItemStack list = this.localCache.findPrecise( request ); - if( list == null || list.getStackSize() == 0 ) - { - return null; - } + return request; + } - if( list.getStackSize() >= request.getStackSize() ) - { - if( mode == Actionable.MODULATE ) - { - list.decStackSize( request.getStackSize() ); - if( this.logExtracted ) - { - this.extractedCache.add( request ); - } - } + final IAEItemStack ret = request.copy(); + ret.setStackSize(list.getStackSize()); - return request; - } + if (mode == Actionable.MODULATE) { + list.reset(); + if (this.logExtracted) { + this.extractedCache.add(ret); + } + } - final IAEItemStack ret = request.copy(); - ret.setStackSize( list.getStackSize() ); + return ret; + } - if( mode == Actionable.MODULATE ) - { - list.reset(); - if( this.logExtracted ) - { - this.extractedCache.add( ret ); - } - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack is : this.localCache) { + out.add(is); + } - return ret; - } + return out; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack is : this.localCache ) - { - out.add( is ); - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } - return out; - } + public IItemList getItemList() { + return this.localCache; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + public boolean commit(final BaseActionSource src) { + final IItemList added = AEApi.instance().storage().createItemList(); + final IItemList pulled + = AEApi.instance().storage().createItemList(); + boolean failed = false; - public IItemList getItemList() - { - return this.localCache; - } + if (this.logInjections) { + for (final IAEItemStack inject : this.injectedCache) { + IAEItemStack result = null; + added.add( + result = this.target.injectItems(inject, Actionable.MODULATE, src) + ); - public boolean commit( final BaseActionSource src ) - { - final IItemList added = AEApi.instance().storage().createItemList(); - final IItemList pulled = AEApi.instance().storage().createItemList(); - boolean failed = false; + if (result != null) { + failed = true; + break; + } + } + } - if( this.logInjections ) - { - for( final IAEItemStack inject : this.injectedCache ) - { - IAEItemStack result = null; - added.add( result = this.target.injectItems( inject, Actionable.MODULATE, src ) ); + if (failed) { + for (final IAEItemStack is : added) { + this.target.extractItems(is, Actionable.MODULATE, src); + } - if( result != null ) - { - failed = true; - break; - } - } - } + return false; + } - if( failed ) - { - for( final IAEItemStack is : added ) - { - this.target.extractItems( is, Actionable.MODULATE, src ); - } + if (this.logExtracted) { + for (final IAEItemStack extra : this.extractedCache) { + IAEItemStack result = null; + pulled.add( + result = this.target.extractItems(extra, Actionable.MODULATE, src) + ); - return false; - } + if (result == null || result.getStackSize() != extra.getStackSize()) { + failed = true; + break; + } + } + } - if( this.logExtracted ) - { - for( final IAEItemStack extra : this.extractedCache ) - { - IAEItemStack result = null; - pulled.add( result = this.target.extractItems( extra, Actionable.MODULATE, src ) ); + if (failed) { + for (final IAEItemStack is : added) { + this.target.extractItems(is, Actionable.MODULATE, src); + } - if( result == null || result.getStackSize() != extra.getStackSize() ) - { - failed = true; - break; - } - } - } + for (final IAEItemStack is : pulled) { + this.target.injectItems(is, Actionable.MODULATE, src); + } - if( failed ) - { - for( final IAEItemStack is : added ) - { - this.target.extractItems( is, Actionable.MODULATE, src ); - } + return false; + } - for( final IAEItemStack is : pulled ) - { - this.target.injectItems( is, Actionable.MODULATE, src ); - } + if (this.logMissing && this.par != null) { + for (final IAEItemStack extra : this.missingCache) { + this.par.addMissing(extra); + } + } - return false; - } + return true; + } - if( this.logMissing && this.par != null ) - { - for( final IAEItemStack extra : this.missingCache ) - { - this.par.addMissing( extra ); - } - } + private void addMissing(final IAEItemStack extra) { + this.missingCache.add(extra); + } - return true; - } - - private void addMissing( final IAEItemStack extra ) - { - this.missingCache.add( extra ); - } - - void ignore( final IAEItemStack what ) - { - final IAEItemStack list = this.localCache.findPrecise( what ); - if( list != null ) - { - list.setStackSize( 0 ); - } - } + void ignore(final IAEItemStack what) { + final IAEItemStack list = this.localCache.findPrecise(what); + 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 20237049..bcfdc15e 100644 --- a/src/main/java/appeng/debug/BlockChunkloader.java +++ b/src/main/java/appeng/debug/BlockChunkloader.java @@ -18,6 +18,8 @@ package appeng.debug; +import java.util.EnumSet; +import java.util.List; import appeng.block.AEBaseTileBlock; import appeng.core.AppEng; @@ -29,30 +31,21 @@ import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.ForgeChunkManager.LoadingCallback; import net.minecraftforge.common.ForgeChunkManager.Ticket; -import java.util.EnumSet; -import java.util.List; +public class BlockChunkloader extends AEBaseTileBlock implements LoadingCallback { + public BlockChunkloader() { + super(Material.iron); + this.setTileEntity(TileChunkLoader.class); + ForgeChunkManager.setForcedChunkLoadingCallback(AppEng.instance(), this); + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } + @Override + public void ticketsLoaded(final List tickets, final World world) {} -public class BlockChunkloader extends AEBaseTileBlock implements LoadingCallback -{ - - public BlockChunkloader() - { - super( Material.iron ); - this.setTileEntity( TileChunkLoader.class ); - ForgeChunkManager.setForcedChunkLoadingCallback( AppEng.instance(), this ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public void ticketsLoaded( final List tickets, final World world ) - { - - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/BlockCubeGenerator.java b/src/main/java/appeng/debug/BlockCubeGenerator.java index e7a185b1..681c9d8b 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 appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; @@ -26,34 +27,37 @@ import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -import java.util.EnumSet; +public class BlockCubeGenerator extends AEBaseTileBlock { + public BlockCubeGenerator() { + super(Material.iron); + this.setTileEntity(TileCubeGenerator.class); + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final TileCubeGenerator tcg = this.getTileEntity(w, x, y, z); + if (tcg != null) { + tcg.click(player); + } -public class BlockCubeGenerator extends AEBaseTileBlock -{ + return true; + } - public BlockCubeGenerator() - { - super( Material.iron ); - this.setTileEntity( TileCubeGenerator.class ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TileCubeGenerator tcg = this.getTileEntity( w, x, y, z ); - if( tcg != null ) - { - tcg.click( player ); - } - - return true; - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/BlockItemGen.java b/src/main/java/appeng/debug/BlockItemGen.java index 05edc755..06be9d1d 100644 --- a/src/main/java/appeng/debug/BlockItemGen.java +++ b/src/main/java/appeng/debug/BlockItemGen.java @@ -18,28 +18,24 @@ package appeng.debug; +import java.util.EnumSet; import appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; -import java.util.EnumSet; +public class BlockItemGen extends AEBaseTileBlock { + public BlockItemGen() { + super(Material.iron); + this.setTileEntity(TileItemGen.class); + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } - -public class BlockItemGen extends AEBaseTileBlock -{ - - public BlockItemGen() - { - super( Material.iron ); - this.setTileEntity( TileItemGen.class ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/BlockPhantomNode.java b/src/main/java/appeng/debug/BlockPhantomNode.java index 26b4b1d3..936ed94e 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 appeng.block.AEBaseTileBlock; import appeng.core.features.AEFeature; @@ -26,30 +27,34 @@ import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -import java.util.EnumSet; +public class BlockPhantomNode extends AEBaseTileBlock { + public BlockPhantomNode() { + super(Material.iron); + this.setTileEntity(TilePhantomNode.class); + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } + @Override + public boolean onActivated( + final World w, + final int x, + final int y, + final int z, + final EntityPlayer player, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final TilePhantomNode tpn = this.getTileEntity(w, x, y, z); + tpn.triggerCrashMode(); + return true; + } -public class BlockPhantomNode extends AEBaseTileBlock -{ - - public BlockPhantomNode() - { - super( Material.iron ); - this.setTileEntity( TilePhantomNode.class ); - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } - - @Override - public boolean onActivated( final World w, final int x, final int y, final int z, final EntityPlayer player, final int side, final float hitX, final float hitY, final float hitZ ) - { - final TilePhantomNode tpn = this.getTileEntity( w, x, y, z ); - tpn.triggerCrashMode(); - return true; - } - - @Override - public void registerBlockIcons( final IIconRegister iconRegistry ) - { - this.registerNoIcons(); - } + @Override + public void registerBlockIcons(final IIconRegister iconRegistry) { + this.registerNoIcons(); + } } diff --git a/src/main/java/appeng/debug/TileChunkLoader.java b/src/main/java/appeng/debug/TileChunkLoader.java index 0b7254b4..0c3cca70 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 appeng.core.AELog; import appeng.core.AppEng; @@ -34,61 +35,53 @@ import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.ForgeChunkManager.Ticket; import net.minecraftforge.common.ForgeChunkManager.Type; -import java.util.List; +public class TileChunkLoader extends AEBaseTile { + private boolean requestTicket = true; + private Ticket ct = null; + @TileEvent(TileEventType.TICK) + public void onTickEvent() { + if (this.requestTicket) { + this.requestTicket = false; + this.initTicket(); + } + } -public class TileChunkLoader extends AEBaseTile -{ + private void initTicket() { + if (Platform.isClient()) { + return; + } - private boolean requestTicket = true; - private Ticket ct = null; + this.ct = ForgeChunkManager.requestTicket( + AppEng.instance(), this.worldObj, Type.NORMAL + ); - @TileEvent( TileEventType.TICK ) - public void onTickEvent() - { - if( this.requestTicket ) - { - this.requestTicket = false; - this.initTicket(); - } - } + if (this.ct == null) { + final MinecraftServer server + = FMLCommonHandler.instance().getMinecraftServerInstance(); + if (server != null) { + final List pl + = server.getConfigurationManager().playerEntityList; + for (final EntityPlayerMP p : pl) { + p.addChatMessage(new ChatComponentText("Can't chunk load..")); + } + } + return; + } - private void initTicket() - { - if( Platform.isClient() ) - { - return; - } + AELog.info("New Ticket " + this.ct.toString()); + ForgeChunkManager.forceChunk( + this.ct, new ChunkCoordIntPair(this.xCoord >> 4, this.zCoord >> 4) + ); + } - this.ct = ForgeChunkManager.requestTicket( AppEng.instance(), this.worldObj, Type.NORMAL ); + @Override + public void invalidate() { + if (Platform.isClient()) { + return; + } - if( this.ct == null ) - { - final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); - if( server != null ) - { - final List pl = server.getConfigurationManager().playerEntityList; - for( final EntityPlayerMP p : pl ) - { - p.addChatMessage( new ChatComponentText( "Can't chunk load.." ) ); - } - } - return; - } - - AELog.info( "New Ticket " + this.ct.toString() ); - ForgeChunkManager.forceChunk( this.ct, new ChunkCoordIntPair( this.xCoord >> 4, this.zCoord >> 4 ) ); - } - - @Override - public void invalidate() - { - if( Platform.isClient() ) - { - return; - } - - AELog.info( "Released Ticket " + this.ct.toString() ); - ForgeChunkManager.releaseTicket( this.ct ); - } + AELog.info("Released Ticket " + this.ct.toString()); + ForgeChunkManager.releaseTicket(this.ct); + } } diff --git a/src/main/java/appeng/debug/TileCubeGenerator.java b/src/main/java/appeng/debug/TileCubeGenerator.java index 6dcb29ae..c9ce7081 100644 --- a/src/main/java/appeng/debug/TileCubeGenerator.java +++ b/src/main/java/appeng/debug/TileCubeGenerator.java @@ -18,7 +18,6 @@ package appeng.debug; - import appeng.core.CommonHelper; import appeng.tile.AEBaseTile; import appeng.tile.TileEvent; @@ -30,94 +29,87 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ChatComponentText; import net.minecraftforge.common.util.ForgeDirection; +public class TileCubeGenerator extends AEBaseTile { + private int size = 3; + private ItemStack is = null; + private int countdown = 20 * 10; + private EntityPlayer who = null; -public class TileCubeGenerator extends AEBaseTile -{ + @TileEvent(TileEventType.TICK) + public void onTickEvent() { + if (this.is != null && Platform.isServer()) { + this.countdown--; - private int size = 3; - private ItemStack is = null; - private int countdown = 20 * 10; - private EntityPlayer who = null; + if (this.countdown % 20 == 0) { + for (final EntityPlayer e : CommonHelper.proxy.getPlayers()) { + e.addChatMessage( + new ChatComponentText("Spawning in... " + (this.countdown / 20)) + ); + } + } - @TileEvent( TileEventType.TICK ) - public void onTickEvent() - { - if( this.is != null && Platform.isServer() ) - { - this.countdown--; + if (this.countdown <= 0) { + this.spawn(); + } + } + } - if( this.countdown % 20 == 0 ) - { - for( final EntityPlayer e : CommonHelper.proxy.getPlayers() ) - { - e.addChatMessage( new ChatComponentText( "Spawning in... " + ( this.countdown / 20 ) ) ); - } - } + private void spawn() { + this.worldObj.setBlock( + this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK, 0, 3 + ); - if( this.countdown <= 0 ) - { - this.spawn(); - } - } - } + final Item i = this.is.getItem(); + final int side = ForgeDirection.UP.ordinal(); - private void spawn() - { - this.worldObj.setBlock( this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK, 0, 3 ); + final int half = (int) Math.floor(this.size / 2); - final Item i = this.is.getItem(); - final int side = ForgeDirection.UP.ordinal(); + for (int y = 0; y < this.size; y++) { + for (int x = -half; x < half; x++) { + 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 + ); + } + } + } + } - final int half = (int) Math.floor( this.size / 2 ); + void click(final EntityPlayer player) { + if (Platform.isServer()) { + final ItemStack hand = player.inventory.getCurrentItem(); + this.who = player; - for( int y = 0; y < this.size; y++ ) - { - for( int x = -half; x < half; x++ ) - { - 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 ); - } - } - } - } + if (hand == null) { + this.is = null; - void click( final EntityPlayer player ) - { - if( Platform.isServer() ) - { - final ItemStack hand = player.inventory.getCurrentItem(); - this.who = player; + if (player.isSneaking()) { + this.size--; + } else { + this.size++; + } - if( hand == null ) - { - this.is = null; + if (this.size < 3) { + this.size = 3; + } + if (this.size > 64) { + this.size = 64; + } - if( player.isSneaking() ) - { - this.size--; - } - else - { - this.size++; - } - - if( this.size < 3 ) - { - this.size = 3; - } - if( this.size > 64 ) - { - this.size = 64; - } - - player.addChatMessage( new ChatComponentText( "Size: " + this.size ) ); - } - else - { - this.countdown = 20 * 10; - this.is = hand; - } - } - } + player.addChatMessage(new ChatComponentText("Size: " + this.size)); + } else { + this.countdown = 20 * 10; + this.is = hand; + } + } + } } diff --git a/src/main/java/appeng/debug/TileItemGen.java b/src/main/java/appeng/debug/TileItemGen.java index 5eff7e25..8a3402a7 100644 --- a/src/main/java/appeng/debug/TileItemGen.java +++ b/src/main/java/appeng/debug/TileItemGen.java @@ -18,6 +18,10 @@ package appeng.debug; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; import appeng.tile.AEBaseTile; import net.minecraft.entity.player.EntityPlayer; @@ -25,122 +29,89 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; +public class TileItemGen extends AEBaseTile implements IInventory { + private static final Queue POSSIBLE_ITEMS = new LinkedList(); + public TileItemGen() { + if (POSSIBLE_ITEMS.isEmpty()) { + for (final Object obj : Item.itemRegistry) { + final Item mi = (Item) obj; + if (mi != null) { + if (mi.isDamageable()) { + for (int dmg = 0; dmg < mi.getMaxDamage(); dmg++) { + POSSIBLE_ITEMS.add(new ItemStack(mi, 1, dmg)); + } + } else { + final List list = new ArrayList(); + mi.getSubItems(mi, mi.getCreativeTab(), list); + POSSIBLE_ITEMS.addAll(list); + } + } + } + } + } -public class TileItemGen extends AEBaseTile implements IInventory -{ + @Override + public int getSizeInventory() { + return 1; + } - private static final Queue POSSIBLE_ITEMS = new LinkedList(); + @Override + public ItemStack getStackInSlot(final int i) { + return this.getRandomItem(); + } - public TileItemGen() - { - if( POSSIBLE_ITEMS.isEmpty() ) - { - for( final Object obj : Item.itemRegistry ) - { - final Item mi = (Item) obj; - if( mi != null ) - { - if( mi.isDamageable() ) - { - for( int dmg = 0; dmg < mi.getMaxDamage(); dmg++ ) - { - POSSIBLE_ITEMS.add( new ItemStack( mi, 1, dmg ) ); - } - } - else - { - final List list = new ArrayList(); - mi.getSubItems( mi, mi.getCreativeTab(), list ); - POSSIBLE_ITEMS.addAll( list ); - } - } - } - } - } + private ItemStack getRandomItem() { + return POSSIBLE_ITEMS.peek(); + } - @Override - public int getSizeInventory() - { - return 1; - } + @Override + public ItemStack decrStackSize(final int i, final int j) { + final ItemStack a = POSSIBLE_ITEMS.poll(); + final ItemStack out = a.copy(); + POSSIBLE_ITEMS.add(a); + return out; + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.getRandomItem(); - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } - private ItemStack getRandomItem() - { - return POSSIBLE_ITEMS.peek(); - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + final ItemStack a = POSSIBLE_ITEMS.poll(); + POSSIBLE_ITEMS.add(a); + } - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - final ItemStack a = POSSIBLE_ITEMS.poll(); - final ItemStack out = a.copy(); - POSSIBLE_ITEMS.add( a ); - return out; - } + @Override + public String getInventoryName() { + return null; + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - final ItemStack a = POSSIBLE_ITEMS.poll(); - POSSIBLE_ITEMS.add( a ); - } + @Override + public int getInventoryStackLimit() { + return 1; + } - @Override - public String getInventoryName() - { - return null; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public void openInventory() {} - @Override - public int getInventoryStackLimit() - { - return 1; - } + @Override + public void closeInventory() {} - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - - } - - @Override - public void closeInventory() - { - - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return false; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return false; + } } diff --git a/src/main/java/appeng/debug/TilePhantomNode.java b/src/main/java/appeng/debug/TilePhantomNode.java index 746b6230..f990815b 100644 --- a/src/main/java/appeng/debug/TilePhantomNode.java +++ b/src/main/java/appeng/debug/TilePhantomNode.java @@ -18,47 +18,38 @@ package appeng.debug; +import java.util.EnumSet; import appeng.api.networking.IGridNode; import appeng.me.helpers.AENetworkProxy; import appeng.tile.grid.AENetworkTile; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class TilePhantomNode extends AENetworkTile { + private AENetworkProxy proxy = null; + private boolean crashMode = false; + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + if (!this.crashMode) { + return super.getGridNode(dir); + } -public class TilePhantomNode extends AENetworkTile -{ + return this.proxy.getNode(); + } - private AENetworkProxy proxy = null; - private boolean crashMode = false; + @Override + public void onReady() { + super.onReady(); + this.proxy = this.createProxy(); + this.proxy.onReady(); + this.crashMode = true; + } - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - if( !this.crashMode ) - { - return super.getGridNode( dir ); - } - - return this.proxy.getNode(); - } - - @Override - public void onReady() - { - super.onReady(); - this.proxy = this.createProxy(); - this.proxy.onReady(); - this.crashMode = true; - } - - void triggerCrashMode() - { - if( this.proxy != null ) - { - this.crashMode = true; - this.proxy.setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - } + void triggerCrashMode() { + 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 27a7c6fe..d324fc2f 100644 --- a/src/main/java/appeng/debug/ToolDebugCard.java +++ b/src/main/java/appeng/debug/ToolDebugCard.java @@ -18,6 +18,9 @@ package appeng.debug; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.Set; import appeng.api.networking.IGridConnection; import appeng.api.networking.IGridHost; @@ -47,183 +50,175 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.Set; +public class ToolDebugCard extends AEBaseItem { + public ToolDebugCard() { + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) + return true; -public class ToolDebugCard extends AEBaseItem -{ - public ToolDebugCard() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } + if (Platform.isClient()) { + return false; + } - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; + if (player.isSneaking()) { + int grids = 0; + int totalNodes = 0; - if( Platform.isClient() ) - { - return false; - } + for (final Grid g : TickHandler.INSTANCE.getGridList()) { + grids++; + totalNodes += g.getNodes().size(); + } - if( player.isSneaking() ) - { - int grids = 0; - int totalNodes = 0; + this.outputMsg(player, "Grids: " + grids); + this.outputMsg(player, "Total Nodes: " + totalNodes); + } else { + final TileEntity te = world.getTileEntity(x, y, z); - for( final Grid g : TickHandler.INSTANCE.getGridList() ) - { - grids++; - totalNodes += g.getNodes().size(); - } + if (te instanceof IGridHost) { + final GridNode node + = (GridNode) ((IGridHost) te) + .getGridNode(ForgeDirection.getOrientation(side)); + if (node != null) { + final Grid g = node.getInternalGrid(); + final IGridNode center = g.getPivot(); + this.outputMsg(player, "This Node: " + node.toString()); + this.outputMsg(player, "Center Node: " + center.toString()); - this.outputMsg( player, "Grids: " + grids ); - this.outputMsg( player, "Total Nodes: " + totalNodes ); - } - else - { - final TileEntity te = world.getTileEntity( x, y, z ); + final IPathingGrid pg = g.getCache(IPathingGrid.class); + if (pg.getControllerState() == ControllerState.CONTROLLER_ONLINE) { + Set next = new HashSet(); + next.add(node); - if( te instanceof IGridHost ) - { - final GridNode node = (GridNode) ( (IGridHost) te ).getGridNode( ForgeDirection.getOrientation( side ) ); - if( node != null ) - { - final Grid g = node.getInternalGrid(); - final IGridNode center = g.getPivot(); - this.outputMsg( player, "This Node: " + node.toString() ); - this.outputMsg( player, "Center Node: " + center.toString() ); + final int maxLength = 10000; - final IPathingGrid pg = g.getCache( IPathingGrid.class ); - if( pg.getControllerState() == ControllerState.CONTROLLER_ONLINE ) - { + int length = 0; + outer: + while (!next.isEmpty()) { + final Iterable current = next; + next = new HashSet(); - Set next = new HashSet(); - next.add( node ); + for (final IGridNode n : current) { + if (n.getMachine() instanceof TileController) { + break outer; + } - final int maxLength = 10000; + for (final IGridConnection c : n.getConnections()) { + next.add(c.getOtherSide(n)); + } + } - int length = 0; - outer: - while( !next.isEmpty() ) - { - final Iterable current = next; - next = new HashSet(); + length++; - for( final IGridNode n : current ) - { - if( n.getMachine() instanceof TileController ) - { - break outer; - } + if (length > maxLength) { + break; + } + } - for( final IGridConnection c : n.getConnections() ) - { - next.add( c.getOtherSide( n ) ); - } - } + this.outputMsg(player, "Cable Distance: " + length); + } - length++; + if (center.getMachine() instanceof PartP2PTunnel) { + this.outputMsg( + player, + "Freq: " + + ((PartP2PTunnel) center.getMachine()).getFrequency() + ); + } - if( length > maxLength ) - { - break; - } - } + final TickManagerCache tmc = g.getCache(ITickManager.class); + for (final Class c : g.getMachineClasses()) { + int o = 0; + long nanos = 0; + for (final IGridNode oj : g.getMachines(c)) { + o++; + nanos += tmc.getAvgNanoTime(oj); + } - this.outputMsg( player, "Cable Distance: " + length ); - } + if (nanos < 0) { + this.outputMsg(player, c.getSimpleName() + " - " + o); + } else { + this.outputMsg( + player, + c.getSimpleName() + " - " + o + "; " + + this.timeMeasurement(nanos) + ); + } + } + } else { + this.outputMsg(player, "No Node Available."); + } + } else { + this.outputMsg(player, "Not Networked Block"); + } - if( center.getMachine() instanceof PartP2PTunnel ) - { - this.outputMsg( player, "Freq: " + ( (PartP2PTunnel) center.getMachine() ).getFrequency() ); - } + if (te instanceof IPartHost) { + final IPart center = ((IPartHost) te).getPart(ForgeDirection.UNKNOWN); + ((IPartHost) te).markForUpdate(); + if (center != null) { + final GridNode n = (GridNode) center.getGridNode(); + this.outputMsg(player, "Node Channels: " + n.usedChannels()); + for (final IGridConnection gc : n.getConnections()) { + final ForgeDirection fd = gc.getDirection(n); + if (fd != ForgeDirection.UNKNOWN) { + this.outputMsg( + player, fd.toString() + ": " + gc.getUsedChannels() + ); + } + } + } + } - final TickManagerCache tmc = g.getCache( ITickManager.class ); - for( final Class c : g.getMachineClasses() ) - { - int o = 0; - long nanos = 0; - for( final IGridNode oj : g.getMachines( c ) ) - { - o++; - nanos += tmc.getAvgNanoTime( oj ); - } + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) te; + this.outputMsg( + player, + "Energy: " + ps.getAECurrentPower() + " / " + ps.getAEMaxPower() + ); - if( nanos < 0 ) - { - this.outputMsg( player, c.getSimpleName() + " - " + o ); - } - else - { - this.outputMsg( player, c.getSimpleName() + " - " + o + "; " + this.timeMeasurement( nanos ) ); - } - } - } - else - { - this.outputMsg( player, "No Node Available." ); - } - } - else - { - this.outputMsg( player, "Not Networked Block" ); - } + if (te instanceof IGridHost) { + final IGridNode node + = ((IGridHost) te) + .getGridNode(ForgeDirection.getOrientation(side)); + if (node != null && node.getGrid() != null) { + final IEnergyGrid eg = node.getGrid().getCache(IEnergyGrid.class); + this.outputMsg( + player, + "GridEnergy: " + eg.getStoredPower() + " : " + + eg.getEnergyDemand(Double.MAX_VALUE) + ); + } + } + } + } + return true; + } - if( te instanceof IPartHost ) - { - final IPart center = ( (IPartHost) te ).getPart( ForgeDirection.UNKNOWN ); - ( (IPartHost) te ).markForUpdate(); - if( center != null ) - { - final GridNode n = (GridNode) center.getGridNode(); - this.outputMsg( player, "Node Channels: " + n.usedChannels() ); - for( final IGridConnection gc : n.getConnections() ) - { - final ForgeDirection fd = gc.getDirection( n ); - if( fd != ForgeDirection.UNKNOWN ) - { - this.outputMsg( player, fd.toString() + ": " + gc.getUsedChannels() ); - } - } - } - } + private void outputMsg(final ICommandSender player, final String string) { + player.addChatMessage(new ChatComponentText(string)); + } - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) te; - this.outputMsg( player, "Energy: " + ps.getAECurrentPower() + " / " + ps.getAEMaxPower() ); - - if( te instanceof IGridHost ) - { - final IGridNode node = ( (IGridHost) te ).getGridNode( ForgeDirection.getOrientation( side ) ); - if( node != null && node.getGrid() != null ) - { - final IEnergyGrid eg = node.getGrid().getCache( IEnergyGrid.class ); - this.outputMsg( player, "GridEnergy: " + eg.getStoredPower() + " : " + eg.getEnergyDemand( Double.MAX_VALUE ) ); - } - } - } - } - return true; - } - - private void outputMsg( final ICommandSender player, final String string ) - { - player.addChatMessage( new ChatComponentText( string ) ); - } - - private String timeMeasurement( final long nanos ) - { - final long ms = nanos / 100000; - if( nanos <= 100000 ) - { - return nanos + "ns"; - } - return ( ms / 10.0f ) + "ms"; - } + private String timeMeasurement(final long nanos) { + final long ms = 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 c105674e..23199beb 100644 --- a/src/main/java/appeng/debug/ToolEraser.java +++ b/src/main/java/appeng/debug/ToolEraser.java @@ -18,6 +18,10 @@ package appeng.debug; +import java.util.Collection; +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.List; import appeng.api.util.WorldCoord; import appeng.client.texture.MissingIcon; @@ -33,81 +37,95 @@ import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.util.Collection; -import java.util.EnumSet; -import java.util.LinkedList; -import java.util.List; +public class ToolEraser extends AEBaseItem { + private static final int BLOCK_ERASE_LIMIT = 90000; + public ToolEraser() { + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } -public class ToolEraser extends AEBaseItem -{ + @Override + public void registerIcons(final IIconRegister par1IconRegister) { + this.itemIcon = new MissingIcon(this); + } - private static final int BLOCK_ERASE_LIMIT = 90000; + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) + return true; - public ToolEraser() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } + if (Platform.isClient()) { + return false; + } - @Override - public void registerIcons( final IIconRegister par1IconRegister ) - { - this.itemIcon = new MissingIcon( this ); - } + final Block blk = world.getBlock(x, y, z); + final int meta = world.getBlockMetadata(x, y, z); - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; + if (blk != null + && ForgeEventFactory + .onPlayerInteract( + player, + PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + world + ) + .isCanceled()) + return true; - if( Platform.isClient() ) - { - return false; - } + List next = new LinkedList(); + next.add(new WorldCoord(x, y, z)); - final Block blk = world.getBlock( x, y, z ); - final int meta = world.getBlockMetadata( x, y, z ); + int blocks = 0; + while (blocks < BLOCK_ERASE_LIMIT && !next.isEmpty()) { + final List c = next; + next = new LinkedList(); - if( blk != null && ForgeEventFactory.onPlayerInteract( player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, side, world ).isCanceled() ) - return true; + for (final WorldCoord wc : c) { + final Block c_blk = world.getBlock(wc.x, wc.y, wc.z); + final int c_meta = world.getBlockMetadata(wc.x, wc.y, wc.z); - List next = new LinkedList(); - next.add( new WorldCoord( x, y, z ) ); + if (c_blk == blk && c_meta == meta) { + blocks++; + world.setBlock(wc.x, wc.y, wc.z, Platform.AIR_BLOCK); - int blocks = 0; - while( blocks < BLOCK_ERASE_LIMIT && !next.isEmpty() ) - { - final List c = next; - next = new LinkedList(); + this.wrappedAdd(world, wc.x + 1, wc.y, wc.z, next); + this.wrappedAdd(world, wc.x - 1, wc.y, wc.z, next); + this.wrappedAdd(world, wc.x, wc.y + 1, wc.z, next); + this.wrappedAdd(world, wc.x, wc.y - 1, wc.z, next); + this.wrappedAdd(world, wc.x, wc.y, wc.z + 1, next); + this.wrappedAdd(world, wc.x, wc.y, wc.z - 1, next); + } + } + } - for( final WorldCoord wc : c ) - { - final Block c_blk = world.getBlock( wc.x, wc.y, wc.z ); - final int c_meta = world.getBlockMetadata( wc.x, wc.y, wc.z ); + AELog.info("Delete " + blocks + " blocks"); - if( c_blk == blk && c_meta == meta ) - { - blocks++; - world.setBlock( wc.x, wc.y, wc.z, Platform.AIR_BLOCK ); + return true; + } - this.wrappedAdd( world, wc.x + 1, wc.y, wc.z, next ); - this.wrappedAdd( world, wc.x - 1, wc.y, wc.z, next ); - this.wrappedAdd( world, wc.x, wc.y + 1, wc.z, next ); - this.wrappedAdd( world, wc.x, wc.y - 1, wc.z, next ); - this.wrappedAdd( world, wc.x, wc.y, wc.z + 1, next ); - this.wrappedAdd( world, wc.x, wc.y, wc.z - 1, next ); - } - } - } - - AELog.info( "Delete " + blocks + " blocks" ); - - return true; - } - - private void wrappedAdd( final World world, final int i, final int y, final int z, final Collection next ) - { - next.add( new WorldCoord( i, y, z ) ); - } + private void wrappedAdd( + final World world, + final int i, + final int y, + final int z, + final Collection next + ) { + next.add(new WorldCoord(i, y, z)); + } } diff --git a/src/main/java/appeng/debug/ToolMeteoritePlacer.java b/src/main/java/appeng/debug/ToolMeteoritePlacer.java index 1a210bef..cb335381 100644 --- a/src/main/java/appeng/debug/ToolMeteoritePlacer.java +++ b/src/main/java/appeng/debug/ToolMeteoritePlacer.java @@ -18,6 +18,7 @@ package appeng.debug; +import java.util.EnumSet; import appeng.client.texture.MissingIcon; import appeng.core.features.AEFeature; @@ -32,41 +33,45 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; +public class ToolMeteoritePlacer extends AEBaseItem { + public ToolMeteoritePlacer() { + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } + @Override + public void registerIcons(final IIconRegister par1IconRegister) { + this.itemIcon = new MissingIcon(this); + } -public class ToolMeteoritePlacer extends AEBaseItem -{ - public ToolMeteoritePlacer() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) + return true; - @Override - public void registerIcons( final IIconRegister par1IconRegister ) - { - this.itemIcon = new MissingIcon( this ); - } + if (Platform.isClient()) { + return false; + } - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; + final MeteoritePlacer mp = new MeteoritePlacer(); + final boolean worked = mp.spawnMeteorite(new StandardWorld(world), x, y, z); - if( Platform.isClient() ) - { - return false; - } + if (!worked) { + player.addChatMessage(new ChatComponentText("Un-suitable Location.")); + } - final MeteoritePlacer mp = new MeteoritePlacer(); - final boolean worked = mp.spawnMeteorite( new StandardWorld( world ), x, y, z ); - - if( !worked ) - { - player.addChatMessage( new ChatComponentText( "Un-suitable Location." ) ); - } - - return true; - } + return true; + } } diff --git a/src/main/java/appeng/debug/ToolReplicatorCard.java b/src/main/java/appeng/debug/ToolReplicatorCard.java index 15657522..e84e9308 100644 --- a/src/main/java/appeng/debug/ToolReplicatorCard.java +++ b/src/main/java/appeng/debug/ToolReplicatorCard.java @@ -18,6 +18,7 @@ package appeng.debug; +import java.util.EnumSet; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -39,144 +40,149 @@ import net.minecraftforge.common.DimensionManager; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; +public class ToolReplicatorCard extends AEBaseItem { + public ToolReplicatorCard() { + this.setFeature( + EnumSet.of(AEFeature.UnsupportedDeveloperTools, AEFeature.Creative) + ); + } + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + int x, + int y, + int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) + return true; -public class ToolReplicatorCard extends AEBaseItem -{ - public ToolReplicatorCard() - { - this.setFeature( EnumSet.of( AEFeature.UnsupportedDeveloperTools, AEFeature.Creative ) ); - } + if (Platform.isClient()) { + return false; + } - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, int x, int y, int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; + if (player.isSneaking()) { + if (world.getTileEntity(x, y, z) instanceof IGridHost) { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("x", x); + tag.setInteger("y", y); + tag.setInteger("z", z); + tag.setInteger("side", side); + tag.setInteger("dimid", world.provider.dimensionId); + stack.setTagCompound(tag); + } else { + this.outputMsg(player, "This is not a Grid Tile."); + } + } else { + final NBTTagCompound ish = stack.getTagCompound(); + if (ish != null) { + final int src_x = ish.getInteger("x"); + final int src_y = ish.getInteger("y"); + final int src_z = ish.getInteger("z"); + final int src_side = ish.getInteger("side"); + final int dimid = ish.getInteger("dimid"); + final World src_w = DimensionManager.getWorld(dimid); - if( Platform.isClient() ) - { - return false; - } + final TileEntity te = src_w.getTileEntity(src_x, src_y, src_z); + if (te instanceof IGridHost) { + final IGridHost gh = (IGridHost) te; + final ForgeDirection sideOff + = ForgeDirection.getOrientation(src_side); + final ForgeDirection currentSideOff + = ForgeDirection.getOrientation(side); + final IGridNode n = gh.getGridNode(sideOff); + if (n != null) { + final IGrid g = n.getGrid(); + if (g != null) { + final ISpatialCache sc = g.getCache(ISpatialCache.class); + if (sc.isValidRegion()) { + final DimensionalCoord min = sc.getMin(); + final DimensionalCoord max = sc.getMax(); - if( player.isSneaking() ) - { - if( world.getTileEntity( x, y, z ) instanceof IGridHost ) - { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setInteger( "x", x ); - tag.setInteger( "y", y ); - tag.setInteger( "z", z ); - tag.setInteger( "side", side ); - tag.setInteger( "dimid", world.provider.dimensionId ); - stack.setTagCompound( tag ); - } - else - { - this.outputMsg( player, "This is not a Grid Tile." ); - } - } - else - { - final NBTTagCompound ish = stack.getTagCompound(); - if( ish != null ) - { - final int src_x = ish.getInteger( "x" ); - final int src_y = ish.getInteger( "y" ); - final int src_z = ish.getInteger( "z" ); - final int src_side = ish.getInteger( "side" ); - final int dimid = ish.getInteger( "dimid" ); - final World src_w = DimensionManager.getWorld( dimid ); + x += currentSideOff.offsetX; + y += currentSideOff.offsetY; + z += currentSideOff.offsetZ; - final TileEntity te = src_w.getTileEntity( src_x, src_y, src_z ); - if( te instanceof IGridHost ) - { - final IGridHost gh = (IGridHost) te; - final ForgeDirection sideOff = ForgeDirection.getOrientation( src_side ); - final ForgeDirection currentSideOff = ForgeDirection.getOrientation( side ); - final IGridNode n = gh.getGridNode( sideOff ); - if( n != null ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - final ISpatialCache sc = g.getCache( ISpatialCache.class ); - if( sc.isValidRegion() ) - { - final DimensionalCoord min = sc.getMin(); - final DimensionalCoord max = sc.getMax(); + final int min_x = min.x; + final int min_y = min.y; + final int min_z = min.z; - x += currentSideOff.offsetX; - y += currentSideOff.offsetY; - z += currentSideOff.offsetZ; + final int rel_x = min.x - src_x + x; + final int rel_y = min.y - src_y + y; + final int rel_z = min.z - src_z + z; - final int min_x = min.x; - final int min_y = min.y; - final int min_z = min.z; + final int scale_x = max.x - min.x; + final int scale_y = max.y - min.y; + final int scale_z = max.z - min.z; - final int rel_x = min.x - src_x + x; - final int rel_y = min.y - src_y + y; - final int rel_z = min.z - src_z + 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++) { + final Block blk = src_w.getBlock( + min_x + i, min_y + j, min_z + k + ); + final 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 + ); - final int scale_x = max.x - min.x; - final int scale_y = max.y - min.y; - final int scale_z = max.z - min.z; + if (blk != null && blk.hasTileEntity(meta)) { + final TileEntity ote + = src_w.getTileEntity( + min_x + i, min_y + j, min_z + k + ); + final TileEntity nte + = blk.createTileEntity(world, meta); + final NBTTagCompound data + = new NBTTagCompound(); + ote.writeToNBT(data); + nte.readFromNBT((NBTTagCompound + ) data.copy()); + world.setTileEntity( + i + rel_x, j + rel_y, k + rel_z, nte + ); + } + world.markBlockForUpdate( + i + rel_x, j + rel_y, k + rel_z + ); + } + } + } + } else { + this.outputMsg( + player, "requires valid spatial pylon setup." + ); + } + } else { + this.outputMsg(player, "no grid?"); + } + } else { + this.outputMsg(player, "No grid node?"); + } + } else { + this.outputMsg(player, "Src is no longer a grid block?"); + } + } else { + this.outputMsg(player, "No Source Defined"); + } + } + return true; + } - for( int i = 1; i < scale_x; i++ ) - { - for( int j = 1; j < scale_y; j++ ) - { - for( int k = 1; k < scale_z; k++ ) - { - final Block blk = src_w.getBlock( min_x + i, min_y + j, min_z + k ); - final 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 ) ) - { - final TileEntity ote = src_w.getTileEntity( min_x + i, min_y + j, min_z + k ); - final TileEntity nte = blk.createTileEntity( world, meta ); - final NBTTagCompound data = new NBTTagCompound(); - ote.writeToNBT( data ); - nte.readFromNBT( (NBTTagCompound) data.copy() ); - world.setTileEntity( i + rel_x, j + rel_y, k + rel_z, nte ); - } - world.markBlockForUpdate( i + rel_x, j + rel_y, k + rel_z ); - } - } - } - } - else - { - this.outputMsg( player, "requires valid spatial pylon setup." ); - } - } - else - { - this.outputMsg( player, "no grid?" ); - } - } - else - { - this.outputMsg( player, "No grid node?" ); - } - } - else - { - this.outputMsg( player, "Src is no longer a grid block?" ); - } - } - else - { - this.outputMsg( player, "No Source Defined" ); - } - } - return true; - } - - private void outputMsg( final ICommandSender player, final String string ) - { - player.addChatMessage( new ChatComponentText( string ) ); - } + private void outputMsg(final ICommandSender player, final String string) { + player.addChatMessage(new ChatComponentText(string)); + } } diff --git a/src/main/java/appeng/entity/AEBaseEntityItem.java b/src/main/java/appeng/entity/AEBaseEntityItem.java index 375916b7..030a93ef 100644 --- a/src/main/java/appeng/entity/AEBaseEntityItem.java +++ b/src/main/java/appeng/entity/AEBaseEntityItem.java @@ -18,6 +18,7 @@ package appeng.entity; +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; @@ -25,24 +26,24 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import java.util.List; +public abstract class AEBaseEntityItem extends EntityItem { + public AEBaseEntityItem(final World world) { + super(world); + } + public AEBaseEntityItem( + final World world, + final double x, + final double y, + final double z, + final ItemStack stack + ) { + super(world, x, y, z, stack); + } -public abstract class AEBaseEntityItem extends EntityItem -{ - public AEBaseEntityItem( final World world ) - { - super( world ); - } - - public AEBaseEntityItem( final World world, final double x, final double y, final double z, final ItemStack stack ) - { - super( world, x, y, z, stack ); - } - - @SuppressWarnings( "unchecked" ) - protected List getCheckedEntitiesWithinAABBExcludingEntity( final AxisAlignedBB region ) - { - return this.worldObj.getEntitiesWithinAABBExcludingEntity( this, region ); - } + @SuppressWarnings("unchecked") + protected List + getCheckedEntitiesWithinAABBExcludingEntity(final AxisAlignedBB region) { + return this.worldObj.getEntitiesWithinAABBExcludingEntity(this, region); + } } diff --git a/src/main/java/appeng/entity/EntityChargedQuartz.java b/src/main/java/appeng/entity/EntityChargedQuartz.java index ec560fa2..fe72bf9a 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 appeng.api.AEApi; import appeng.api.definitions.IMaterials; @@ -36,130 +37,120 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -import java.util.List; +public final class EntityChargedQuartz extends AEBaseEntityItem { + private int delay = 0; + private int transformTime = 0; + @Reflected + public EntityChargedQuartz(final World w) { + super(w); + } -public final class EntityChargedQuartz extends AEBaseEntityItem -{ + public EntityChargedQuartz( + final World w, final double x, final double y, final double z, final ItemStack is + ) { + super(w, x, y, z, is); + } - private int delay = 0; - private int transformTime = 0; + @Override + public void onUpdate() { + super.onUpdate(); - @Reflected - public EntityChargedQuartz( final World w ) - { - super( w ); - } + if (!AEConfig.instance.isFeatureEnabled(AEFeature.InWorldFluix)) { + return; + } - public EntityChargedQuartz( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } + 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; + } + this.delay++; - @Override - public void onUpdate() - { - super.onUpdate(); + final int j = MathHelper.floor_double(this.posX); + final int i = MathHelper.floor_double( + (this.boundingBox.minY + this.boundingBox.maxY) / 2.0D + ); + final int k = MathHelper.floor_double(this.posZ); - if( !AEConfig.instance.isFeatureEnabled( AEFeature.InWorldFluix ) ) - { - return; - } + final Material mat = this.worldObj.getBlock(j, i, k).getMaterial(); + if (Platform.isServer() && mat.isLiquid()) { + this.transformTime++; + if (this.transformTime > 60) { + if (!this.transform()) { + this.transformTime = 0; + } + } + } else { + this.transformTime = 0; + } + } - 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; - } - this.delay++; + private boolean transform() { + final ItemStack item = this.getEntityItem(); + final IMaterials materials = AEApi.instance().definitions().materials(); - final int j = MathHelper.floor_double( this.posX ); - final int i = MathHelper.floor_double( (this.boundingBox.minY + this.boundingBox.maxY) / 2.0D ); - final int k = MathHelper.floor_double( this.posZ ); + if (materials.certusQuartzCrystalCharged().isSameAs(item)) { + final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( + this.posX - 1, + this.posY - 1, + this.posZ - 1, + this.posX + 1, + this.posY + 1, + this.posZ + 1 + ); + final List l + = this.getCheckedEntitiesWithinAABBExcludingEntity(region); - final Material mat = this.worldObj.getBlock( j, i, k ).getMaterial(); - if( Platform.isServer() && mat.isLiquid() ) - { - this.transformTime++; - if( this.transformTime > 60 ) - { - if( !this.transform() ) - { - this.transformTime = 0; - } - } - } - else - { - this.transformTime = 0; - } - } + EntityItem redstone = null; + EntityItem netherQuartz = null; - private boolean transform() - { - final ItemStack item = this.getEntityItem(); - final IMaterials materials = AEApi.instance().definitions().materials(); + for (final Entity e : l) { + if (e instanceof EntityItem && !e.isDead) { + final ItemStack other = ((EntityItem) e).getEntityItem(); + if (other != null && other.stackSize > 0) { + if (Platform.isSameItem(other, new ItemStack(Items.redstone))) { + redstone = (EntityItem) e; + } - if( materials.certusQuartzCrystalCharged().isSameAs( item ) ) - { - final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( this.posX - 1, this.posY - 1, this.posZ - 1, this.posX + 1, this.posY + 1, this.posZ + 1 ); - final List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); + if (Platform.isSameItem(other, new ItemStack(Items.quartz))) { + netherQuartz = (EntityItem) e; + } + } + } + } - EntityItem redstone = null; - EntityItem netherQuartz = null; + if (redstone != null && netherQuartz != null) { + this.getEntityItem().stackSize--; + redstone.getEntityItem().stackSize--; + netherQuartz.getEntityItem().stackSize--; - for( final Entity e : l ) - { - if( e instanceof EntityItem && !e.isDead ) - { - final ItemStack other = ( (EntityItem) e ).getEntityItem(); - if( other != null && other.stackSize > 0 ) - { - if( Platform.isSameItem( other, new ItemStack( Items.redstone ) ) ) - { - redstone = (EntityItem) e; - } + if (this.getEntityItem().stackSize <= 0) { + this.setDead(); + } - if( Platform.isSameItem( other, new ItemStack( Items.quartz ) ) ) - { - netherQuartz = (EntityItem) e; - } - } - } - } + if (redstone.getEntityItem().stackSize <= 0) { + redstone.setDead(); + } - if( redstone != null && netherQuartz != null ) - { - this.getEntityItem().stackSize--; - redstone.getEntityItem().stackSize--; - netherQuartz.getEntityItem().stackSize--; + if (netherQuartz.getEntityItem().stackSize <= 0) { + netherQuartz.setDead(); + } - if( this.getEntityItem().stackSize <= 0 ) - { - this.setDead(); - } + for (final ItemStack fluixCrystalStack : + materials.fluixCrystal().maybeStack(2).asSet()) { + final EntityItem entity = new EntityItem( + this.worldObj, this.posX, this.posY, this.posZ, fluixCrystalStack + ); - if( redstone.getEntityItem().stackSize <= 0 ) - { - redstone.setDead(); - } + this.worldObj.spawnEntityInWorld(entity); + } - if( netherQuartz.getEntityItem().stackSize <= 0 ) - { - netherQuartz.setDead(); - } + return true; + } + } - for( final ItemStack fluixCrystalStack : materials.fluixCrystal().maybeStack( 2 ).asSet() ) - { - final EntityItem entity = new EntityItem( this.worldObj, this.posX, this.posY, this.posZ, fluixCrystalStack ); - - this.worldObj.spawnEntityInWorld( entity ); - } - - return true; - } - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/entity/EntityFloatingItem.java b/src/main/java/appeng/entity/EntityFloatingItem.java index 57e930ad..e5677f9c 100644 --- a/src/main/java/appeng/entity/EntityFloatingItem.java +++ b/src/main/java/appeng/entity/EntityFloatingItem.java @@ -18,60 +18,56 @@ package appeng.entity; - import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraft.world.World; +public final class EntityFloatingItem extends EntityItem { + public static int ageStatic = 0; + private final Entity parent; + private int superDeath = 0; + private float progress = 0; -public final class EntityFloatingItem extends EntityItem -{ + public EntityFloatingItem( + final Entity parent, + final World world, + final double x, + final double y, + final double z, + final ItemStack stack + ) { + super(world, x, y, z, stack); + this.motionX = this.motionY = this.motionZ = 0.0d; + this.hoverStart = 0.5f; + this.rotationYaw = 0; + this.parent = parent; + } - public static int ageStatic = 0; - private final Entity parent; - private int superDeath = 0; - private float progress = 0; + // public boolean isEntityAlive() - public EntityFloatingItem( final Entity parent, final World world, final double x, final double y, final double z, final ItemStack stack ) - { - super( world, x, y, z, stack ); - this.motionX = this.motionY = this.motionZ = 0.0d; - this.hoverStart = 0.5f; - this.rotationYaw = 0; - this.parent = parent; - } + @Override + public void onUpdate() { + if (!this.isDead && this.parent.isDead) { + this.setDead(); + } - // public boolean isEntityAlive() + if (this.superDeath > 100) { + this.setDead(); + } + this.superDeath++; - @Override - public void onUpdate() - { - if( !this.isDead && this.parent.isDead ) - { - this.setDead(); - } + this.age = ageStatic; + } - if( this.superDeath > 100 ) - { - this.setDead(); - } - this.superDeath++; + public void setProgress(final float progress) { + this.progress = progress; + if (this.progress > 0.99) { + this.setDead(); + } + } - this.age = ageStatic; - } - - public void setProgress( final float progress ) - { - this.progress = progress; - if( this.progress > 0.99 ) - { - this.setDead(); - } - } - - float getProgress() - { - return this.progress; - } + float getProgress() { + return this.progress; + } } diff --git a/src/main/java/appeng/entity/EntityGrowingCrystal.java b/src/main/java/appeng/entity/EntityGrowingCrystal.java index 92b23e16..82651246 100644 --- a/src/main/java/appeng/entity/EntityGrowingCrystal.java +++ b/src/main/java/appeng/entity/EntityGrowingCrystal.java @@ -18,7 +18,6 @@ package appeng.entity; - import appeng.api.implementations.items.IGrowableCrystal; import appeng.api.implementations.tiles.ICrystalGrowthAccelerator; import appeng.client.EffectType; @@ -35,166 +34,146 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; +public final class EntityGrowingCrystal extends EntityItem { + private int progress_1000 = 0; -public final class EntityGrowingCrystal extends EntityItem -{ + public EntityGrowingCrystal(final World w) { + super(w); + } - private int progress_1000 = 0; + public EntityGrowingCrystal( + final World w, final double x, final double y, final double z, final ItemStack is + ) { + super(w, x, y, z, is); + } - public EntityGrowingCrystal( final World w ) - { - super( w ); - } + @Override + public void onUpdate() { + super.onUpdate(); - public EntityGrowingCrystal( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } + if (!AEConfig.instance.isFeatureEnabled(AEFeature.InWorldPurification)) { + return; + } - @Override - public void onUpdate() - { - super.onUpdate(); + if (this.age > 600) { + this.age = 100; + } - if( !AEConfig.instance.isFeatureEnabled( AEFeature.InWorldPurification ) ) - { - return; - } + final ItemStack is = this.getEntityItem(); + final Item gc = is.getItem(); - if( this.age > 600 ) - { - this.age = 100; - } + if (gc instanceof IGrowableCrystal) // if it changes this just stops being an + // issue... + { + final int j = MathHelper.floor_double(this.posX); + final int i = MathHelper.floor_double( + (this.boundingBox.minY + this.boundingBox.maxY) / 2.0D + ); + final int k = MathHelper.floor_double(this.posZ); - final ItemStack is = this.getEntityItem(); - final Item gc = is.getItem(); + final Block blk = this.worldObj.getBlock(j, i, k); + final Material mat = blk.getMaterial(); + final IGrowableCrystal cry = (IGrowableCrystal) is.getItem(); - if( gc instanceof IGrowableCrystal ) // if it changes this just stops being an issue... - { - final int j = MathHelper.floor_double( this.posX ); - final int i = MathHelper.floor_double( (this.boundingBox.minY + this.boundingBox.maxY) / 2.0D ); - final int k = MathHelper.floor_double( this.posZ ); + final float multiplier = cry.getMultiplier(blk, mat); + final int speed = (int) Math.max(1, this.getSpeed(j, i, k) * multiplier); - final Block blk = this.worldObj.getBlock( j, i, k ); - final Material mat = blk.getMaterial(); - final IGrowableCrystal cry = (IGrowableCrystal) is.getItem(); + final boolean isClient = Platform.isClient(); - final float multiplier = cry.getMultiplier( blk, mat ); - final int speed = (int) Math.max( 1, this.getSpeed( j, i, k ) * multiplier ); + if (mat.isLiquid()) { + if (isClient) { + this.progress_1000++; + } else { + this.progress_1000 += speed; + } + } else { + this.progress_1000 = 0; + } - final boolean isClient = Platform.isClient(); + if (isClient) { + int len = 40; - if( mat.isLiquid() ) - { - if( isClient ) - { - this.progress_1000++; - } - else - { - this.progress_1000 += speed; - } - } - else - { - this.progress_1000 = 0; - } + if (speed > 2) { + len = 20; + } - if( isClient ) - { - int len = 40; + if (speed > 90) { + len = 15; + } - if( speed > 2 ) - { - len = 20; - } + if (speed > 150) { + len = 10; + } - if( speed > 90 ) - { - len = 15; - } + if (speed > 240) { + len = 7; + } - if( speed > 150 ) - { - len = 10; - } + if (speed > 360) { + len = 3; + } - if( speed > 240 ) - { - len = 7; - } + if (speed > 500) { + len = 1; + } - if( speed > 360 ) - { - len = 3; - } + 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 + ); + } + } else { + if (this.progress_1000 > 1000) { + this.progress_1000 -= 1000; + this.setEntityItemStack(cry.triggerGrowth(is)); + } + } + } + } - if( speed > 500 ) - { - len = 1; - } + private int getSpeed(final int x, final int y, final int z) { + final int per = 80; + final float mul = 0.3f; - 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 ); - } - } - else - { - if( this.progress_1000 > 1000 ) - { - this.progress_1000 -= 1000; - this.setEntityItemStack( cry.triggerGrowth( is ) ); - } - } - } - } + int qty = 0; - private int getSpeed( final int x, final int y, final int z ) - { - final int per = 80; - final float mul = 0.3f; + if (this.isAccelerated(x + 1, y, z)) { + qty += per + qty * mul; + } - int qty = 0; + if (this.isAccelerated(x, y + 1, z)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x + 1, y, z ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x, y, z + 1)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x, y + 1, z ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x - 1, y, z)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x, y, z + 1 ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x, y - 1, z)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x - 1, y, z ) ) - { - qty += per + qty * mul; - } + if (this.isAccelerated(x, y, z - 1)) { + qty += per + qty * mul; + } - if( this.isAccelerated( x, y - 1, z ) ) - { - qty += per + qty * mul; - } + return qty; + } - if( this.isAccelerated( x, y, z - 1 ) ) - { - qty += per + qty * mul; - } + private boolean isAccelerated(final int x, final int y, final int z) { + final TileEntity te = this.worldObj.getTileEntity(x, y, z); - return qty; - } - - private boolean isAccelerated( final int x, final int y, final int z ) - { - final 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/EntityIds.java b/src/main/java/appeng/entity/EntityIds.java index a79ac012..d232a606 100644 --- a/src/main/java/appeng/entity/EntityIds.java +++ b/src/main/java/appeng/entity/EntityIds.java @@ -18,40 +18,30 @@ package appeng.entity; - import net.minecraft.entity.Entity; +public final class EntityIds { + private static final int TINY_TNT = 10; + private static final int SINGULARITY = 11; + private static final int CHARGED_QUARTZ = 12; + private static final int GROWING_CRYSTAL = 13; -public final class EntityIds -{ - private static final int TINY_TNT = 10; - private static final int SINGULARITY = 11; - private static final int CHARGED_QUARTZ = 12; - private static final int GROWING_CRYSTAL = 13; + private EntityIds() {} - private EntityIds() - { - } + public static int get(final Class droppedEntity) { + if (droppedEntity == EntityTinyTNTPrimed.class) { + return TINY_TNT; + } + if (droppedEntity == EntitySingularity.class) { + return SINGULARITY; + } + if (droppedEntity == EntityChargedQuartz.class) { + return CHARGED_QUARTZ; + } + if (droppedEntity == EntityGrowingCrystal.class) { + return GROWING_CRYSTAL; + } - public static int get( final Class droppedEntity ) - { - if( droppedEntity == EntityTinyTNTPrimed.class ) - { - return TINY_TNT; - } - if( droppedEntity == EntitySingularity.class ) - { - return SINGULARITY; - } - if( droppedEntity == EntityChargedQuartz.class ) - { - return CHARGED_QUARTZ; - } - if( droppedEntity == EntityGrowingCrystal.class ) - { - return GROWING_CRYSTAL; - } - - throw new IllegalStateException( "Missing entity id: " + droppedEntity.getName() ); - } + throw new IllegalStateException("Missing entity id: " + droppedEntity.getName()); + } } diff --git a/src/main/java/appeng/entity/EntitySingularity.java b/src/main/java/appeng/entity/EntitySingularity.java index a91de0b8..8bb566a8 100644 --- a/src/main/java/appeng/entity/EntitySingularity.java +++ b/src/main/java/appeng/entity/EntitySingularity.java @@ -18,6 +18,8 @@ package appeng.entity; +import java.util.Date; +import java.util.List; import appeng.api.AEApi; import appeng.api.definitions.IMaterials; @@ -34,119 +36,116 @@ import net.minecraft.util.DamageSource; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import java.util.Date; -import java.util.List; +public final class EntitySingularity extends AEBaseEntityItem { + private static int randTickSeed = 0; + @Reflected + public EntitySingularity(final World w) { + super(w); + } -public final class EntitySingularity extends AEBaseEntityItem -{ + public EntitySingularity( + final World w, final double x, final double y, final double z, final ItemStack is + ) { + super(w, x, y, z, is); + } - private static int randTickSeed = 0; + @Override + public boolean attackEntityFrom(final DamageSource src, final float dmg) { + if (src.isExplosion()) { + this.doExplosion(); + return false; + } - @Reflected - public EntitySingularity( final World w ) - { - super( w ); - } + return super.attackEntityFrom(src, dmg); + } - public EntitySingularity( final World w, final double x, final double y, final double z, final ItemStack is ) - { - super( w, x, y, z, is ); - } + private void doExplosion() { + if (Platform.isClient()) { + return; + } - @Override - public boolean attackEntityFrom( final DamageSource src, final float dmg ) - { - if( src.isExplosion() ) - { - this.doExplosion(); - return false; - } + if (!AEConfig.instance.isFeatureEnabled(AEFeature.InWorldSingularity)) { + return; + } - return super.attackEntityFrom( src, dmg ); - } + final ItemStack item = this.getEntityItem(); - private void doExplosion() - { - if( Platform.isClient() ) - { - return; - } + final IMaterials materials = AEApi.instance().definitions().materials(); - if( !AEConfig.instance.isFeatureEnabled( AEFeature.InWorldSingularity ) ) - { - return; - } + if (materials.singularity().isSameAs(item)) { + final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( + this.posX - 4, + this.posY - 4, + this.posZ - 4, + this.posX + 4, + this.posY + 4, + this.posZ + 4 + ); + final List l + = this.getCheckedEntitiesWithinAABBExcludingEntity(region); - final ItemStack item = this.getEntityItem(); + for (final Entity e : l) { + if (e instanceof EntityItem) { + final ItemStack other = ((EntityItem) e).getEntityItem(); + if (other != null) { + boolean matches = false; + for (final ItemStack is : OreDictionary.getOres("dustEnder")) { + if (OreDictionary.itemMatches(other, is, false)) { + matches = true; + break; + } + } - final IMaterials materials = AEApi.instance().definitions().materials(); + // check... other name. + if (!matches) { + for (final ItemStack is : + OreDictionary.getOres("dustEnderPearl")) { + if (OreDictionary.itemMatches(other, is, false)) { + matches = true; + break; + } + } + } - if( materials.singularity().isSameAs( item ) ) - { - final AxisAlignedBB region = AxisAlignedBB.getBoundingBox( this.posX - 4, this.posY - 4, this.posZ - 4, this.posX + 4, this.posY + 4, this.posZ + 4 ); - final List l = this.getCheckedEntitiesWithinAABBExcludingEntity( region ); + if (matches) { + while (item.stackSize > 0 && other.stackSize > 0) { + other.stackSize--; + if (other.stackSize == 0) { + e.setDead(); + } - for( final Entity e : l ) - { - if( e instanceof EntityItem ) - { - final ItemStack other = ( (EntityItem) e ).getEntityItem(); - if( other != null ) - { - boolean matches = false; - for( final ItemStack is : OreDictionary.getOres( "dustEnder" ) ) - { - if( OreDictionary.itemMatches( other, is, false ) ) - { - matches = true; - break; - } - } + for (final ItemStack singularityStack : + materials.qESingularity().maybeStack(2).asSet()) { + final NBTTagCompound cmp + = Platform.openNbtData(singularityStack); + cmp.setLong( + "freq", + (new Date()).getTime() * 100 + + (randTickSeed) % 100 + ); + randTickSeed++; + item.stackSize--; - // check... other name. - if( !matches ) - { - for( final ItemStack is : OreDictionary.getOres( "dustEnderPearl" ) ) - { - if( OreDictionary.itemMatches( other, is, false ) ) - { - matches = true; - break; - } - } - } + final EntitySingularity entity + = new EntitySingularity( + this.worldObj, + this.posX, + this.posY, + this.posZ, + singularityStack + ); + this.worldObj.spawnEntityInWorld(entity); + } + } - if( matches ) - { - while( item.stackSize > 0 && other.stackSize > 0 ) - { - other.stackSize--; - if( other.stackSize == 0 ) - { - e.setDead(); - } - - for( final ItemStack singularityStack : materials.qESingularity().maybeStack( 2 ).asSet() ) - { - final NBTTagCompound cmp = Platform.openNbtData( singularityStack ); - cmp.setLong( "freq", ( new Date() ).getTime() * 100 + ( randTickSeed ) % 100 ); - randTickSeed++; - item.stackSize--; - - final EntitySingularity entity = new EntitySingularity( this.worldObj, this.posX, this.posY, this.posZ, singularityStack ); - this.worldObj.spawnEntityInWorld( entity ); - } - } - - if( item.stackSize <= 0 ) - { - this.setDead(); - } - } - } - } - } - } - } + 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 2c6fc5ee..681d2d67 100644 --- a/src/main/java/appeng/entity/EntityTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/EntityTinyTNTPrimed.java @@ -18,7 +18,6 @@ package appeng.entity; - import appeng.api.AEApi; import appeng.core.AEConfig; import appeng.core.CommonHelper; @@ -40,148 +39,186 @@ import net.minecraft.util.DamageSource; import net.minecraft.world.Explosion; import net.minecraft.world.World; +public final class EntityTinyTNTPrimed + extends EntityTNTPrimed implements IEntityAdditionalSpawnData { + @Reflected + public EntityTinyTNTPrimed(final World w) { + super(w); + this.setSize(0.35F, 0.35F); + } -public final class EntityTinyTNTPrimed extends EntityTNTPrimed implements IEntityAdditionalSpawnData -{ - @Reflected - public EntityTinyTNTPrimed( final World w ) - { - super( w ); - this.setSize( 0.35F, 0.35F ); - } + public EntityTinyTNTPrimed( + final World w, + final double x, + final double y, + final double z, + final EntityLivingBase igniter + ) { + super(w, x, y, z, igniter); + this.setSize(0.55F, 0.55F); + this.yOffset = this.height / 2.0F; + } - public EntityTinyTNTPrimed( final World w, final double x, final double y, final double z, final EntityLivingBase igniter ) - { - super( w, x, y, z, igniter ); - this.setSize( 0.55F, 0.55F ); - this.yOffset = this.height / 2.0F; - } + /** + * Called to update the entity's position/logic. + */ + @Override + public void onUpdate() { + this.handleWaterMovement(); - /** - * Called to update the entity's position/logic. - */ - @Override - public void onUpdate() - { - this.handleWaterMovement(); + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.motionY -= 0.03999999910593033D; + this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.9800000190734863D; + this.motionY *= 0.9800000190734863D; + this.motionZ *= 0.9800000190734863D; - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.motionY -= 0.03999999910593033D; - this.moveEntity( this.motionX, this.motionY, this.motionZ ); - this.motionX *= 0.9800000190734863D; - this.motionY *= 0.9800000190734863D; - this.motionZ *= 0.9800000190734863D; + if (this.onGround) { + this.motionX *= 0.699999988079071D; + this.motionZ *= 0.699999988079071D; + this.motionY *= -0.5D; + } - if( this.onGround ) - { - this.motionX *= 0.699999988079071D; - this.motionZ *= 0.699999988079071D; - this.motionY *= -0.5D; - } + if (this.isInWater() && Platform.isServer()) // put out the fuse. + { + for (final ItemStack tntStack : + AEApi.instance().definitions().blocks().tinyTNT().maybeStack(1).asSet( + )) { + final EntityItem item = new EntityItem( + this.worldObj, this.posX, this.posY, this.posZ, tntStack + ); - if( this.isInWater() && Platform.isServer() ) // put out the fuse. - { - for( final ItemStack tntStack : AEApi.instance().definitions().blocks().tinyTNT().maybeStack( 1 ).asSet() ) - { - final EntityItem item = new EntityItem( this.worldObj, this.posX, this.posY, this.posZ, tntStack ); + item.motionX = this.motionX; + item.motionY = this.motionY; + item.motionZ = this.motionZ; + item.prevPosX = this.prevPosX; + item.prevPosY = this.prevPosY; + item.prevPosZ = this.prevPosZ; - item.motionX = this.motionX; - item.motionY = this.motionY; - item.motionZ = this.motionZ; - item.prevPosX = this.prevPosX; - item.prevPosY = this.prevPosY; - item.prevPosZ = this.prevPosZ; + this.worldObj.spawnEntityInWorld(item); + this.setDead(); + } + } - this.worldObj.spawnEntityInWorld( item ); - this.setDead(); - } - } + if (this.fuse <= 0) { + this.setDead(); - if( this.fuse <= 0 ) - { - this.setDead(); + if (!this.worldObj.isRemote) { + this.explode(); + } + } else { + this.worldObj.spawnParticle( + "smoke", this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D + ); + } + this.fuse--; + } - if( !this.worldObj.isRemote ) - { - this.explode(); - } - } - else - { - this.worldObj.spawnParticle( "smoke", this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D ); - } - this.fuse--; - } + // 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 + ); - // 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 ); + if (this.isInWater()) { + return; + } - if( this.isInWater() ) - { - return; - } + for (final 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) { + ((Entity) e).attackEntityFrom(DamageSource.setExplosionSource(null), 6); + } + } - for( final 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 ) - { - ( (Entity) e ).attackEntityFrom( DamageSource.setExplosionSource( null ), 6 ); - } - } + if (AEConfig.instance.isFeatureEnabled(AEFeature.TinyTNTBlockDamage)) { + this.posY -= 0.25; + final Explosion ex = new Explosion( + this.worldObj, this, this.posX, this.posY, this.posZ, 0.2f + ); - if( AEConfig.instance.isFeatureEnabled( AEFeature.TinyTNTBlockDamage ) ) - { - this.posY -= 0.25; - final 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 y = (int) (this.posY - 2); y <= this.posY + 2; y++) { + for (int z = (int) (this.posZ - 2); z <= this.posZ + 2; z++) { + final Block block = this.worldObj.getBlock(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))); - 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 z = (int) ( this.posZ - 2 ); z <= this.posZ + 2; z++ ) - { - final Block block = this.worldObj.getBlock( 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 ) ) ); + final float resistance = block.getExplosionResistance( + this, + this.worldObj, + x, + y, + z, + this.posX, + this.posY, + this.posZ + ); + strength -= (resistance + 0.3F) * 0.11f; - final float resistance = block.getExplosionResistance( this, this.worldObj, x, y, z, this.posX, this.posY, this.posZ ); - strength -= ( resistance + 0.3F ) * 0.11f; + if (strength > 0.01) { + if (block.getMaterial() != Material.air) { + if (block.canDropFromExplosion(ex)) { + block.dropBlockAsItemWithChance( + this.worldObj, + x, + y, + z, + this.worldObj.getBlockMetadata(x, y, z), + 1.0F / 1.0f, + 0 + ); + } - if( strength > 0.01 ) - { - if( block.getMaterial() != Material.air ) - { - if( block.canDropFromExplosion( ex ) ) - { - block.dropBlockAsItemWithChance( this.worldObj, x, y, z, this.worldObj.getBlockMetadata( x, y, z ), 1.0F / 1.0f, 0 ); - } + block.onBlockExploded(this.worldObj, x, y, z, ex); + } + } + } + } + } + } + } - block.onBlockExploded( this.worldObj, x, y, z, ex ); - } - } - } - } - } - } - } + CommonHelper.proxy.sendToAllNearExcept( + null, + this.posX, + this.posY, + this.posZ, + 64, + this.worldObj, + new PacketMockExplosion(this.posX, this.posY, this.posZ) + ); + } - CommonHelper.proxy.sendToAllNearExcept( null, this.posX, this.posY, this.posZ, 64, this.worldObj, new PacketMockExplosion( this.posX, this.posY, this.posZ ) ); - } + @Override + public void writeSpawnData(final ByteBuf data) { + data.writeByte(this.fuse); + } - @Override - public void writeSpawnData( final ByteBuf data ) - { - data.writeByte( this.fuse ); - } - - @Override - public void readSpawnData( final ByteBuf data ) - { - this.fuse = data.readByte(); - } + @Override + public void readSpawnData(final 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 93e7c960..146c58d7 100644 --- a/src/main/java/appeng/entity/RenderFloatingItem.java +++ b/src/main/java/appeng/entity/RenderFloatingItem.java @@ -18,7 +18,6 @@ package appeng.entity; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.entity.RenderItem; @@ -27,41 +26,39 @@ import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemBlock; import org.lwjgl.opengl.GL11; +@SideOnly(Side.CLIENT) +public class RenderFloatingItem extends RenderItem { + public RenderFloatingItem() { + this.shadowOpaque = 0.0F; + this.renderManager = RenderManager.instance; + } -@SideOnly( Side.CLIENT ) -public class RenderFloatingItem extends RenderItem -{ + @Override + public void doRender( + final EntityItem entityItem, + final double x, + final double y, + final double z, + final float yaw, + final float partialTick + ) { + if (entityItem instanceof EntityFloatingItem) { + final EntityFloatingItem efi = (EntityFloatingItem) entityItem; + if (efi.getProgress() > 0.0) { + GL11.glPushMatrix(); - public RenderFloatingItem() - { - this.shadowOpaque = 0.0F; - this.renderManager = RenderManager.instance; - } + if (!(efi.getEntityItem().getItem() instanceof ItemBlock)) { + GL11.glTranslatef(0, -0.15f, 0); + } - @Override - public void doRender( final EntityItem entityItem, final double x, final double y, final double z, final float yaw, final float partialTick ) - { - if( entityItem instanceof EntityFloatingItem ) - { - final EntityFloatingItem efi = (EntityFloatingItem) entityItem; - if( efi.getProgress() > 0.0 ) - { - GL11.glPushMatrix(); + super.doRender(efi, x, y, z, yaw, partialTick); + GL11.glPopMatrix(); + } + } + } - if( !( efi.getEntityItem().getItem() instanceof ItemBlock ) ) - { - GL11.glTranslatef( 0, -0.15f, 0 ); - } - - super.doRender( efi, x, y, z, yaw, partialTick ); - GL11.glPopMatrix(); - } - } - } - - @Override - public boolean shouldBob() - { - return false; - } + @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 665a43fb..727b3cfb 100644 --- a/src/main/java/appeng/entity/RenderTinyTNTPrimed.java +++ b/src/main/java/appeng/entity/RenderTinyTNTPrimed.java @@ -18,7 +18,6 @@ package appeng.entity; - import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.RenderBlocks; @@ -30,76 +29,78 @@ import net.minecraft.init.Blocks; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; +@SideOnly(Side.CLIENT) +public class RenderTinyTNTPrimed extends Render { + private final RenderBlocks blockRenderer = new RenderBlocks(); -@SideOnly( Side.CLIENT ) -public class RenderTinyTNTPrimed extends Render -{ + public RenderTinyTNTPrimed() { + this.shadowSize = 0.5F; + this.renderManager = RenderManager.instance; + } - private final RenderBlocks blockRenderer = new RenderBlocks(); + @Override + public void doRender( + final Entity tnt, + final double x, + final double y, + final double z, + final float unused, + final float life + ) { + this.renderPrimedTNT((EntityTinyTNTPrimed) tnt, x, y, z, life); + } - public RenderTinyTNTPrimed() - { - this.shadowSize = 0.5F; - this.renderManager = RenderManager.instance; - } + private void renderPrimedTNT( + final EntityTinyTNTPrimed tnt, + final double x, + final double y, + final double z, + final float life + ) { + GL11.glPushMatrix(); + GL11.glTranslatef((float) x, (float) y - 0.25f, (float) z); + float f2; - @Override - public void doRender( final Entity tnt, final double x, final double y, final double z, final float unused, final float life ) - { - this.renderPrimedTNT( (EntityTinyTNTPrimed) tnt, x, y, z, life ); - } + if (tnt.fuse - life + 1.0F < 10.0F) { + f2 = 1.0F - (tnt.fuse - life + 1.0F) / 10.0F; - private void renderPrimedTNT( final EntityTinyTNTPrimed tnt, final double x, final double y, final double z, final float life ) - { - GL11.glPushMatrix(); - GL11.glTranslatef( (float) x, (float) y - 0.25f, (float) z ); - float f2; + if (f2 < 0.0F) { + f2 = 0.0F; + } - if( tnt.fuse - life + 1.0F < 10.0F ) - { - f2 = 1.0F - ( tnt.fuse - life + 1.0F ) / 10.0F; + if (f2 > 1.0F) { + f2 = 1.0F; + } - if( f2 < 0.0F ) - { - f2 = 0.0F; - } + f2 *= f2; + f2 *= f2; + final float f3 = 1.0F + f2 * 0.3F; + GL11.glScalef(f3, f3, f3); + } - if( f2 > 1.0F ) - { - f2 = 1.0F; - } + GL11.glScalef(0.5f, 0.5f, 0.5f); + f2 = (1.0F - (tnt.fuse - life + 1.0F) / 100.0F) * 0.8F; + this.bindEntityTexture(tnt); + this.blockRenderer.renderBlockAsItem(Blocks.tnt, 0, tnt.getBrightness(life)); - f2 *= f2; - f2 *= f2; - final float f3 = 1.0F + f2 * 0.3F; - GL11.glScalef( f3, f3, f3 ); - } + if (tnt.fuse / 5 % 2 == 0) { + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_DST_ALPHA); + GL11.glColor4f(1.0F, 1.0F, 1.0F, f2); + this.blockRenderer.renderBlockAsItem(Blocks.tnt, 0, 1.0F); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } - GL11.glScalef( 0.5f, 0.5f, 0.5f ); - f2 = ( 1.0F - ( tnt.fuse - life + 1.0F ) / 100.0F ) * 0.8F; - this.bindEntityTexture( tnt ); - this.blockRenderer.renderBlockAsItem( Blocks.tnt, 0, tnt.getBrightness( life ) ); + GL11.glPopMatrix(); + } - if( tnt.fuse / 5 % 2 == 0 ) - { - GL11.glDisable( GL11.GL_TEXTURE_2D ); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_BLEND ); - GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_DST_ALPHA ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, f2 ); - this.blockRenderer.renderBlockAsItem( Blocks.tnt, 0, 1.0F ); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); - GL11.glDisable( GL11.GL_BLEND ); - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL11.GL_TEXTURE_2D ); - } - - GL11.glPopMatrix(); - } - - @Override - protected ResourceLocation getEntityTexture( final Entity entity ) - { - return TextureMap.locationBlocksTexture; - } + @Override + protected ResourceLocation getEntityTexture(final Entity entity) { + return TextureMap.locationBlocksTexture; + } } diff --git a/src/main/java/appeng/facade/FacadeContainer.java b/src/main/java/appeng/facade/FacadeContainer.java index 4c6bc590..3fe25205 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 appeng.api.AEApi; import appeng.api.parts.IFacadeContainer; @@ -35,208 +36,199 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; +public class FacadeContainer implements IFacadeContainer { + private final int facades = 6; + private final CableBusStorage storage; + public FacadeContainer(final CableBusStorage cbs) { + this.storage = cbs; + } -public class FacadeContainer implements IFacadeContainer -{ + @Override + public boolean addFacade(final IFacadePart a) { + if (this.getFacade(a.getSide()) == null) { + this.storage.setFacade(a.getSide().ordinal(), a); + return true; + } + return false; + } - private final int facades = 6; - private final CableBusStorage storage; + @Override + public void removeFacade(final IPartHost host, final 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(); + } + } + } + } - public FacadeContainer( final CableBusStorage cbs ) - { - this.storage = cbs; - } + @Override + public IFacadePart getFacade(final ForgeDirection s) { + return this.storage.getFacade(s.ordinal()); + } - @Override - public boolean addFacade( final IFacadePart a ) - { - if( this.getFacade( a.getSide() ) == null ) - { - this.storage.setFacade( a.getSide().ordinal(), a ); - return true; - } - return false; - } + @Override + public void rotateLeft() { + final IFacadePart[] newFacades = new FacadePart[6]; - @Override - public void removeFacade( final IPartHost host, final 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(); - } - } - } - } + newFacades[ForgeDirection.UP.ordinal()] + = this.storage.getFacade(ForgeDirection.UP.ordinal()); + newFacades[ForgeDirection.DOWN.ordinal()] + = this.storage.getFacade(ForgeDirection.DOWN.ordinal()); - @Override - public IFacadePart getFacade( final ForgeDirection s ) - { - return this.storage.getFacade( s.ordinal() ); - } + newFacades[ForgeDirection.EAST.ordinal()] + = this.storage.getFacade(ForgeDirection.NORTH.ordinal()); + newFacades[ForgeDirection.SOUTH.ordinal()] + = this.storage.getFacade(ForgeDirection.EAST.ordinal()); - @Override - public void rotateLeft() - { - final IFacadePart[] newFacades = new FacadePart[6]; + newFacades[ForgeDirection.WEST.ordinal()] + = this.storage.getFacade(ForgeDirection.SOUTH.ordinal()); + newFacades[ForgeDirection.NORTH.ordinal()] + = this.storage.getFacade(ForgeDirection.WEST.ordinal()); - newFacades[ForgeDirection.UP.ordinal()] = this.storage.getFacade( ForgeDirection.UP.ordinal() ); - newFacades[ForgeDirection.DOWN.ordinal()] = this.storage.getFacade( ForgeDirection.DOWN.ordinal() ); + for (int x = 0; x < this.facades; x++) { + this.storage.setFacade(x, newFacades[x]); + } + } - newFacades[ForgeDirection.EAST.ordinal()] = this.storage.getFacade( ForgeDirection.NORTH.ordinal() ); - newFacades[ForgeDirection.SOUTH.ordinal()] = this.storage.getFacade( ForgeDirection.EAST.ordinal() ); + @Override + public void writeToNBT(final NBTTagCompound c) { + for (int x = 0; x < this.facades; x++) { + if (this.storage.getFacade(x) != null) { + final NBTTagCompound data = new NBTTagCompound(); + this.storage.getFacade(x).getItemStack().writeToNBT(data); + c.setTag("facade:" + x, data); + } + } + } - newFacades[ForgeDirection.WEST.ordinal()] = this.storage.getFacade( ForgeDirection.SOUTH.ordinal() ); - newFacades[ForgeDirection.NORTH.ordinal()] = this.storage.getFacade( ForgeDirection.WEST.ordinal() ); + @Override + public boolean readFromStream(final ByteBuf out) throws IOException { + final int facadeSides = out.readByte(); - for( int x = 0; x < this.facades; x++ ) - { - this.storage.setFacade( x, newFacades[x] ); - } - } + boolean changed = false; - @Override - public void writeToNBT( final NBTTagCompound c ) - { - for( int x = 0; x < this.facades; x++ ) - { - if( this.storage.getFacade( x ) != null ) - { - final NBTTagCompound data = new NBTTagCompound(); - this.storage.getFacade( x ).getItemStack().writeToNBT( data ); - c.setTag( "facade:" + x, data ); - } - } - } + final int[] ids = new int[2]; + for (int x = 0; x < this.facades; x++) { + final ForgeDirection side = ForgeDirection.getOrientation(x); + final int ix = (1 << x); + if ((facadeSides & ix) == ix) { + ids[0] = out.readInt(); + ids[1] = out.readInt(); + final boolean isBC = ids[0] < 0; + ids[0] = Math.abs(ids[0]); - @Override - public boolean readFromStream( final ByteBuf out ) throws IOException - { - final int facadeSides = out.readByte(); + if (isBC + && IntegrationRegistry.INSTANCE.isEnabled( + IntegrationType.BuildCraftTransport + )) { + final IBuildCraftTransport bc + = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( + IntegrationType.BuildCraftTransport + ); + final IFacadePart created = bc.createFacadePart( + (Block) Block.blockRegistry.getObjectById(ids[0]), ids[1], side + ); + changed = changed || this.storage.getFacade(x) == null; - boolean changed = false; + this.storage.setFacade(x, created); + } else if (!isBC) { + for (final Item facadeItem : AEApi.instance() + .definitions() + .items() + .facade() + .maybeItem() + .asSet()) { + final ItemFacade ifa = (ItemFacade) facadeItem; + final ItemStack facade = ifa.createFromIDs(ids); + if (facade != null) { + changed = changed || this.storage.getFacade(x) == null; + this.storage.setFacade( + x, ifa.createPartFromItemStack(facade, side) + ); + } + } + } + } else { + changed = changed || this.storage.getFacade(x) != null; + this.storage.setFacade(x, null); + } + } - final int[] ids = new int[2]; - for( int x = 0; x < this.facades; x++ ) - { - final ForgeDirection side = ForgeDirection.getOrientation( x ); - final int ix = ( 1 << x ); - if( ( facadeSides & ix ) == ix ) - { - ids[0] = out.readInt(); - ids[1] = out.readInt(); - final boolean isBC = ids[0] < 0; - ids[0] = Math.abs( ids[0] ); + return changed; + } - if( isBC && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - final IFacadePart created = bc.createFacadePart( (Block) Block.blockRegistry.getObjectById( ids[0] ), ids[1], side ); - changed = changed || this.storage.getFacade( x ) == null; + @Override + public void readFromNBT(final NBTTagCompound c) { + for (int x = 0; x < this.facades; x++) { + this.storage.setFacade(x, null); - this.storage.setFacade( x, created ); - } - else if( !isBC ) - { - for( final Item facadeItem : AEApi.instance().definitions().items().facade().maybeItem().asSet() ) - { - final ItemFacade ifa = (ItemFacade) facadeItem; - final ItemStack facade = ifa.createFromIDs( ids ); - if( facade != null ) - { - changed = changed || this.storage.getFacade( x ) == null; - this.storage.setFacade( x, ifa.createPartFromItemStack( facade, side ) ); - } - } - } - } - else - { - changed = changed || this.storage.getFacade( x ) != null; - this.storage.setFacade( x, null ); - } - } + final NBTTagCompound t = c.getCompoundTag("facade:" + x); + if (t != null) { + final ItemStack is = ItemStack.loadItemStackFromNBT(t); + if (is != null) { + final Item i = is.getItem(); + if (i instanceof IFacadeItem) { + this.storage.setFacade( + x, + ((IFacadeItem) i) + .createPartFromItemStack( + is, ForgeDirection.getOrientation(x) + ) + ); + } else { + if (IntegrationRegistry.INSTANCE.isEnabled( + IntegrationType.BuildCraftTransport + )) { + final IBuildCraftTransport bc + = (IBuildCraftTransport) IntegrationRegistry.INSTANCE + .getInstance(IntegrationType.BuildCraftTransport); + if (bc.isFacade(is)) { + this.storage.setFacade( + x, + bc.createFacadePart( + is, ForgeDirection.getOrientation(x) + ) + ); + } + } + } + } + } + } + } - return changed; - } + @Override + public void writeToStream(final ByteBuf out) throws IOException { + int facadeSides = 0; + for (int x = 0; x < this.facades; x++) { + if (this.getFacade(ForgeDirection.getOrientation(x)) != null) { + facadeSides |= (1 << x); + } + } + out.writeByte((byte) facadeSides); - @Override - public void readFromNBT( final NBTTagCompound c ) - { - for( int x = 0; x < this.facades; x++ ) - { - this.storage.setFacade( x, null ); + for (int x = 0; x < this.facades; x++) { + final IFacadePart part = this.getFacade(ForgeDirection.getOrientation(x)); + if (part != null) { + final int itemID = Item.getIdFromItem(part.getItem()); + final int dmgValue = part.getItemDamage(); + out.writeInt(itemID * (part.notAEFacade() ? -1 : 1)); + out.writeInt(dmgValue); + } + } + } - final NBTTagCompound t = c.getCompoundTag( "facade:" + x ); - if( t != null ) - { - final ItemStack is = ItemStack.loadItemStackFromNBT( t ); - if( is != null ) - { - final Item i = is.getItem(); - if( i instanceof IFacadeItem ) - { - this.storage.setFacade( x, ( (IFacadeItem) i ).createPartFromItemStack( is, ForgeDirection.getOrientation( x ) ) ); - } - else - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( bc.isFacade( is ) ) - { - this.storage.setFacade( x, bc.createFacadePart( is, ForgeDirection.getOrientation( x ) ) ); - } - } - } - } - } - } - } - - @Override - public void writeToStream( final ByteBuf out ) throws IOException - { - int facadeSides = 0; - for( int x = 0; x < this.facades; x++ ) - { - if( this.getFacade( ForgeDirection.getOrientation( x ) ) != null ) - { - facadeSides |= ( 1 << x ); - } - } - out.writeByte( (byte) facadeSides ); - - for( int x = 0; x < this.facades; x++ ) - { - final IFacadePart part = this.getFacade( ForgeDirection.getOrientation( x ) ); - if( part != null ) - { - final int itemID = Item.getIdFromItem( part.getItem() ); - final int dmgValue = part.getItemDamage(); - out.writeInt( itemID * ( part.notAEFacade() ? -1 : 1 ) ); - out.writeInt( dmgValue ); - } - } - } - - @Override - public boolean isEmpty() - { - for( int x = 0; x < this.facades; x++ ) - { - if( this.storage.getFacade( x ) != null ) - { - return false; - } - } - return true; - } + @Override + public boolean isEmpty() { + for (int x = 0; x < this.facades; x++) { + if (this.storage.getFacade(x) != null) { + return false; + } + } + return true; + } } diff --git a/src/main/java/appeng/facade/FacadePart.java b/src/main/java/appeng/facade/FacadePart.java index b98ded0d..aec2fdf2 100644 --- a/src/main/java/appeng/facade/FacadePart.java +++ b/src/main/java/appeng/facade/FacadePart.java @@ -18,6 +18,8 @@ package appeng.facade; +import java.util.EnumSet; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.parts.*; @@ -45,553 +47,710 @@ import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import javax.annotation.Nullable; -import java.util.EnumSet; +public class FacadePart implements IFacadePart, IBoxProvider { + private final ItemStack facade; + private final ForgeDirection side; + private int thickness = 2; + @SideOnly(Side.CLIENT) + private ISimplifiedBundle prevLight; -public class FacadePart implements IFacadePart, IBoxProvider -{ + public FacadePart(final ItemStack facade, final ForgeDirection side) { + if (facade == null) { + throw new IllegalArgumentException("Facade Part constructed on null item."); + } + this.facade = facade.copy(); + this.facade.stackSize = 1; + this.side = side; + } - private final ItemStack facade; - private final ForgeDirection side; - private int thickness = 2; + public static boolean isFacade(final ItemStack is) { + return is.getItem() instanceof IFacadeItem; + } - @SideOnly( Side.CLIENT ) - private ISimplifiedBundle prevLight; + @Override + public ItemStack getItemStack() { + return this.facade; + } - public FacadePart( final ItemStack facade, final ForgeDirection side ) - { - if( facade == null ) - { - throw new IllegalArgumentException( "Facade Part constructed on null item." ); - } - this.facade = facade.copy(); - this.facade.stackSize = 1; - this.side = side; - } + @Override + public void getBoxes(final IPartCollisionHelper ch, final Entity e) { + if (e instanceof EntityLivingBase) { + // prevent weird snag behavior + ch.addBox(0.0, 0.0, 14, 16.0, 16.0, 16.0); + } else { + // the box is 15.9 for transition planes to pick up collision events. + ch.addBox(0.0, 0.0, 14, 16.0, 16.0, 15.9); + } + } - public static boolean isFacade( final ItemStack is ) - { - return is.getItem() instanceof IFacadeItem; - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper instance2, + final RenderBlocks renderer, + final IFacadeContainer fc, + final AxisAlignedBB busBounds, + final boolean renderStilt + ) { + if (this.facade != null) { + final BusRenderHelper instance = (BusRenderHelper) instance2; - @Override - public ItemStack getItemStack() - { - return this.facade; - } + try { + final ItemStack randomItem = this.getTexture(); - @Override - public void getBoxes( final IPartCollisionHelper ch, final Entity e ) - { - if( e instanceof EntityLivingBase ) - { - // prevent weird snag behavior - ch.addBox( 0.0, 0.0, 14, 16.0, 16.0, 16.0 ); - } - else - { - // the box is 15.9 for transition planes to pick up collision events. - ch.addBox( 0.0, 0.0, 14, 16.0, 16.0, 15.9 ); - } - } + RenderBlocksWorkaround rbw = null; + if (renderer instanceof RenderBlocksWorkaround) { + rbw = (RenderBlocksWorkaround) renderer; + } - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper instance2, final RenderBlocks renderer, final IFacadeContainer fc, final AxisAlignedBB busBounds, final boolean renderStilt ) - { - if( this.facade != null ) - { - final BusRenderHelper instance = (BusRenderHelper) instance2; + if (renderStilt && busBounds == null) { + if (rbw != null) { + rbw.setFacade(false); + rbw.setCalculations(true); + } - try - { - final ItemStack randomItem = this.getTexture(); + IIcon myIcon = null; + if (this.notAEFacade() + && IntegrationRegistry.INSTANCE.isEnabled( + IntegrationType.BuildCraftTransport + )) { + final IBuildCraftTransport bc + = (IBuildCraftTransport) IntegrationRegistry.INSTANCE + .getInstance(IntegrationType.BuildCraftTransport); + myIcon = bc.getCobbleStructurePipeTexture(); + } - RenderBlocksWorkaround rbw = null; - if( renderer instanceof RenderBlocksWorkaround ) - { - rbw = (RenderBlocksWorkaround) renderer; - } + if (myIcon == null) { + myIcon = this.facade.getIconIndex(); + } - if( renderStilt && busBounds == null ) - { - if( rbw != null ) - { - rbw.setFacade( false ); - rbw.setCalculations( true ); - } + instance.setTexture(myIcon); - IIcon myIcon = null; - if( this.notAEFacade() && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - myIcon = bc.getCobbleStructurePipeTexture(); - } + if (this.notAEFacade()) { + instance.setBounds(6, 6, 10, 10, 10, 15); + } else { + instance.setBounds(7, 7, 10, 9, 9, 15); + } - if( myIcon == null ) - { - myIcon = this.facade.getIconIndex(); - } + instance.renderBlock(x, y, z, renderer); + instance.setTexture(null); + } - instance.setTexture( myIcon ); + if (randomItem != null) { + if (randomItem.getItem() instanceof ItemBlock) { + final ItemBlock ib = (ItemBlock) randomItem.getItem(); + final Block blk = Block.getBlockFromItem(ib); - if( this.notAEFacade() ) - { - instance.setBounds( 6, 6, 10, 10, 10, 15 ); - } - else - { - instance.setBounds( 7, 7, 10, 9, 9, 15 ); - } + if (AEApi.instance() + .partHelper() + .getCableRenderMode() + .transparentFacades) { + if (rbw != null) { + rbw.setOpacity(0.3f); + } + instance.renderForPass(1); + } else { + if (blk.canRenderInPass(1)) { + instance.renderForPass(1); + } + } - instance.renderBlock( x, y, z, renderer ); - instance.setTexture( null ); - } + int color = 0xffffff; - if( randomItem != null ) - { - if( randomItem.getItem() instanceof ItemBlock ) - { - final ItemBlock ib = (ItemBlock) randomItem.getItem(); - final Block blk = Block.getBlockFromItem( ib ); + try { + color = ib.getColorFromItemStack(randomItem, 0); + } catch (final Throwable ignored) {} - if( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) - { - if( rbw != null ) - { - rbw.setOpacity( 0.3f ); - } - instance.renderForPass( 1 ); - } - else - { - if( blk.canRenderInPass( 1 ) ) - { - instance.renderForPass( 1 ); - } - } + renderer.uvRotateBottom = renderer.uvRotateEast + = renderer.uvRotateNorth = renderer.uvRotateSouth + = renderer.uvRotateTop = renderer.uvRotateWest = 0; + instance.setBounds(0, 0, 16 - this.thickness, 16, 16, 16); + instance.prepareBounds(renderer); - int color = 0xffffff; + if (rbw != null) { + rbw.setFacade(true); - try - { - color = ib.getColorFromItemStack( randomItem, 0 ); - } - catch( final Throwable ignored ) - { - } + rbw.setCalculations(true); + rbw.setFaces(EnumSet.noneOf(ForgeDirection.class)); - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - instance.setBounds( 0, 0, 16 - this.thickness, 16, 16, 16 ); - instance.prepareBounds( renderer ); + if (this.prevLight != null + && rbw.similarLighting( + blk, rbw.blockAccess, x, y, z, this.prevLight + )) { + rbw.populate(this.prevLight); + } else { + instance.setRenderColor(color); + rbw.renderStandardBlock(instance.getBlock(), x, y, z); + instance.setRenderColor(0xffffff); + this.prevLight = rbw.getLightingCache(); + } - if( rbw != null ) - { - rbw.setFacade( true ); + rbw.setCalculations(false); + rbw.setFaces(this.calculateFaceOpenFaces( + rbw.blockAccess, fc, x, y, z, this.side + )); - rbw.setCalculations( true ); - rbw.setFaces( EnumSet.noneOf( ForgeDirection.class ) ); + ((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()) + ) + ); + } - if( this.prevLight != null && rbw.similarLighting( blk, rbw.blockAccess, x, y, z, this.prevLight ) ) - { - rbw.populate( this.prevLight ); - } - else - { - instance.setRenderColor( color ); - rbw.renderStandardBlock( instance.getBlock(), x, y, z ); - instance.setRenderColor( 0xffffff ); - this.prevLight = rbw.getLightingCache(); - } - - rbw.setCalculations( false ); - rbw.setFaces( 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() ) ) ); - } - 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() ) ) ); - } - - if( busBounds == null ) - { - if( this.side == ForgeDirection.UP || this.side == ForgeDirection.DOWN ) - { - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } + if (busBounds == null) { + 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 ) { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } - else - { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } + instance.renderBlockCurrentBounds(x, y, z, renderer); + } else { + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.SOUTH ) != null ) - { - renderer.renderMaxZ -= this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.SOUTH) != null) { + renderer.renderMaxZ -= this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.NORTH ) != null ) - { - renderer.renderMinZ += this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.NORTH) != null) { + renderer.renderMinZ += this.thickness / 16.0; + } - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } - } - else - { - 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 ); - } + instance.renderBlockCurrentBounds(x, y, z, renderer); + } + } else { + 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 ) { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.maxX, 0.0, 0.0, 1.0, 1.0, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, 0.0, 0.0, busBounds.minX, 1.0, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.minX, 0.0, 0.0, busBounds.maxX, busBounds.minY, 1.0 ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, busBounds.minX, busBounds.maxY, 0.0, busBounds.maxX, 1.0, 1.0 ); - } - else - { - if( fc.getFacade( ForgeDirection.UP ) != null ) - { - renderer.renderMaxY -= this.thickness / 16.0; - } + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + busBounds.maxX, + 0.0, + 0.0, + 1.0, + 1.0, + 1.0 + ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + 0.0, + 0.0, + 0.0, + busBounds.minX, + 1.0, + 1.0 + ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + busBounds.minX, + 0.0, + 0.0, + busBounds.maxX, + busBounds.minY, + 1.0 + ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + busBounds.minX, + busBounds.maxY, + 0.0, + busBounds.maxX, + 1.0, + 1.0 + ); + } else { + if (fc.getFacade(ForgeDirection.UP) != null) { + renderer.renderMaxY -= this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.DOWN ) != null ) - { - renderer.renderMinY += this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.DOWN) != null) { + renderer.renderMinY += this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.SOUTH ) != null ) - { - renderer.renderMaxZ -= this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.SOUTH) != null) { + renderer.renderMaxZ -= this.thickness / 16.0; + } - if( fc.getFacade( ForgeDirection.NORTH ) != null ) - { - renderer.renderMinZ += this.thickness / 16.0; - } + if (fc.getFacade(ForgeDirection.NORTH) != null) { + renderer.renderMinZ += this.thickness / 16.0; + } - 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, 1.0, busBounds.minY, busBounds.maxZ ); - this.renderSegmentBlockCurrentBounds( instance, x, y, z, renderer, 0.0, busBounds.maxY, busBounds.minZ, 1.0, 1.0, busBounds.maxZ ); - } - } + 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, + 1.0, + busBounds.minY, + busBounds.maxZ + ); + this.renderSegmentBlockCurrentBounds( + instance, + x, + y, + z, + renderer, + 0.0, + busBounds.maxY, + busBounds.minZ, + 1.0, + 1.0, + busBounds.maxZ + ); + } + } - if( rbw != null ) - { - rbw.setOpacity( 1.0f ); - rbw.setFaces( EnumSet.allOf( ForgeDirection.class ) ); - } + if (rbw != null) { + rbw.setOpacity(1.0f); + rbw.setFaces(EnumSet.allOf(ForgeDirection.class)); + } - instance.renderForPass( 0 ); - instance.setTexture( null ); - Tessellator.instance.setColorOpaque_F( 1, 1, 1 ); - } - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - } + instance.renderForPass(0); + instance.setTexture(null); + Tessellator.instance.setColorOpaque_F(1, 1, 1); + } + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + } - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper instance, final RenderBlocks renderer ) - { - if( this.facade != null ) - { - final IFacadeItem fi = (IFacadeItem) this.facade.getItem(); + @Override + @SideOnly(Side.CLIENT) + public void + renderInventory(final IPartRenderHelper instance, final RenderBlocks renderer) { + if (this.facade != null) { + final IFacadeItem fi = (IFacadeItem) this.facade.getItem(); - try - { - if( fi != null ) - { - final ItemStack randomItem = fi.getTextureItem( this.facade ); + try { + if (fi != null) { + final ItemStack randomItem = fi.getTextureItem(this.facade); - instance.setTexture( this.facade.getIconIndex() ); - instance.setBounds( 7, 7, 4, 9, 9, 14 ); - instance.renderInventoryBox( renderer ); - instance.setTexture( null ); + instance.setTexture(this.facade.getIconIndex()); + instance.setBounds(7, 7, 4, 9, 9, 14); + instance.renderInventoryBox(renderer); + instance.setTexture(null); - if( randomItem != null ) - { - if( randomItem.getItem() instanceof ItemBlock ) - { - final ItemBlock ib = (ItemBlock) randomItem.getItem(); - final Block blk = Block.getBlockFromItem( ib ); + if (randomItem != null) { + if (randomItem.getItem() instanceof ItemBlock) { + final ItemBlock ib = (ItemBlock) randomItem.getItem(); + final Block blk = Block.getBlockFromItem(ib); - try - { - final int color = ib.getColorFromItemStack( randomItem, 0 ); - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0F ); - instance.setInvColor( color ); - } - catch( final Throwable error ) - { - GL11.glColor4f( 1.0f, 1.0f, 1.0f, 1.0F ); - instance.setInvColor( 0xffffff ); - } + try { + final int color = ib.getColorFromItemStack(randomItem, 0); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + instance.setInvColor(color); + } catch (final Throwable error) { + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); + instance.setInvColor(0xffffff); + } - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_F( 1, 1, 1 ); - instance.setTexture( blk.getIcon( this.side.ordinal(), ib.getMetadata( randomItem.getItemDamage() ) ) ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + Tessellator.instance.setColorOpaque_F(1, 1, 1); + instance.setTexture(blk.getIcon( + this.side.ordinal(), + ib.getMetadata(randomItem.getItemDamage()) + )); - instance.setBounds( 0, 0, 14, 16, 16, 16 ); - instance.renderInventoryBox( renderer ); + instance.setBounds(0, 0, 14, 16, 16, 16); + instance.renderInventoryBox(renderer); - instance.setTexture( null ); - } - } - } - } - catch( final Exception ignored ) - { + instance.setTexture(null); + } + } + } + } catch (final Exception ignored) {} + } + } - } - } - } + @Override + public ForgeDirection getSide() { + return this.side; + } - @Override - public ForgeDirection getSide() - { - return this.side; - } + @Override + public AxisAlignedBB getPrimaryBox() { + return Platform.getPrimaryBox(this.side, this.thickness); + } - @Override - public AxisAlignedBB getPrimaryBox() - { - return Platform.getPrimaryBox( this.side, this.thickness ); - } + @Override + public Item getItem() { + final ItemStack is = this.getTexture(); + if (is == null) { + return null; + } + return is.getItem(); + } - @Override - public Item getItem() - { - final ItemStack is = this.getTexture(); - if( is == null ) - { - return null; - } - return is.getItem(); - } + @Override + public int getItemDamage() { + final ItemStack is = this.getTexture(); + if (is == null) { + return 0; + } + return is.getItemDamage(); + } - @Override - public int getItemDamage() - { - final ItemStack is = this.getTexture(); - if( is == null ) - { - return 0; - } - return is.getItemDamage(); - } + @Override + public boolean notAEFacade() { + return !(this.facade.getItem() instanceof IFacadeItem); + } - @Override - public boolean notAEFacade() - { - return !( this.facade.getItem() instanceof IFacadeItem ); - } + @Override + public void setThinFacades(final boolean useThinFacades) { + this.thickness = useThinFacades ? 1 : 2; + } - @Override - public void setThinFacades( final boolean useThinFacades ) - { - this.thickness = useThinFacades ? 1 : 2; - } + @Override + public boolean isTransparent() { + if (AEApi.instance().partHelper().getCableRenderMode().transparentFacades) { + return true; + } - @Override - public boolean isTransparent() - { - if( AEApi.instance().partHelper().getCableRenderMode().transparentFacades ) - { - return true; - } + final ItemStack is = this.getTexture(); + final Block blk = Block.getBlockFromItem(is.getItem()); - final ItemStack is = this.getTexture(); - final Block blk = Block.getBlockFromItem( is.getItem() ); + return !blk.isOpaqueCube(); + } - return !blk.isOpaqueCube(); - } + @Nullable + private ItemStack getTexture() { + final Item maybeFacade = this.facade.getItem(); - @Nullable - private ItemStack getTexture() - { - final Item maybeFacade = this.facade.getItem(); + // AE Facade + if (maybeFacade instanceof IFacadeItem) { + final IFacadeItem facade = (IFacadeItem) maybeFacade; - // AE Facade - if( maybeFacade instanceof IFacadeItem ) - { - final IFacadeItem facade = (IFacadeItem) maybeFacade; + return facade.getTextureItem(this.facade); + } else if (IntegrationRegistry.INSTANCE.isEnabled( + IntegrationType.BuildCraftTransport + )) { + final IBuildCraftTransport bc = (IBuildCraftTransport + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport + ); - return facade.getTextureItem( this.facade ); - } - else if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); + return bc.getTextureForFacade(this.facade); + } - return bc.getTextureForFacade( this.facade ); - } + return null; + } - return null; - } + private EnumSet calculateFaceOpenFaces( + final IBlockAccess blockAccess, + final IFacadeContainer fc, + final int x, + final int y, + final int z, + final ForgeDirection side + ) { + final EnumSet out = EnumSet.of(side, side.getOpposite()); + final IFacadePart facade = fc.getFacade(side); - private EnumSet calculateFaceOpenFaces( final IBlockAccess blockAccess, final IFacadeContainer fc, final int x, final int y, final int z, final ForgeDirection side ) - { - final EnumSet out = EnumSet.of( side, side.getOpposite() ); - final IFacadePart facade = fc.getFacade( side ); + for (final ForgeDirection it : ForgeDirection.VALID_DIRECTIONS) { + if (!out.contains(it) + && this.hasAlphaDiff( + blockAccess.getTileEntity( + x + it.offsetX, y + it.offsetY, z + it.offsetZ + ), + side, + facade + )) { + out.add(it); + } + } - for( final ForgeDirection it : ForgeDirection.VALID_DIRECTIONS ) - { - 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)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.UP); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.UP); + } + } - if( out.contains( ForgeDirection.UP ) && ( side.offsetX != 0 || side.offsetZ != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.UP ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.UP ); - } - } + if (out.contains(ForgeDirection.DOWN) + && (side.offsetX != 0 || side.offsetZ != 0)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.DOWN); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.DOWN); + } + } - if( out.contains( ForgeDirection.DOWN ) && ( side.offsetX != 0 || side.offsetZ != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.DOWN ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.DOWN ); - } - } + if (out.contains(ForgeDirection.SOUTH) && (side.offsetX != 0)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.SOUTH); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.SOUTH); + } + } - if( out.contains( ForgeDirection.SOUTH ) && ( side.offsetX != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.SOUTH ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.SOUTH ); - } - } + if (out.contains(ForgeDirection.NORTH) && (side.offsetX != 0)) { + final IFacadePart fp = fc.getFacade(ForgeDirection.NORTH); + if (fp != null && (fp.isTransparent() == facade.isTransparent())) { + out.remove(ForgeDirection.NORTH); + } + } - if( out.contains( ForgeDirection.NORTH ) && ( side.offsetX != 0 ) ) - { - final IFacadePart fp = fc.getFacade( ForgeDirection.NORTH ); - if( fp != null && ( fp.isTransparent() == facade.isTransparent() ) ) - { - out.remove( ForgeDirection.NORTH ); - } - } + /* + * if ( out.contains( ForgeDirection.EAST ) && (side.offsetZ != 0) ) { IFacadePart + * fp = fc.getFacade( ForgeDirection.EAST ); if ( fp != null && + * (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.EAST ); } + * if ( out.contains( ForgeDirection.WEST ) && (side.offsetZ != 0) ) { IFacadePart + * fp = fc.getFacade( ForgeDirection.WEST ); if ( fp != null && + * (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.WEST ); } + * if ( out.contains( ForgeDirection.NORTH ) && (side.offsetY != 0) ) { + * IFacadePart fp = fc.getFacade( ForgeDirection.NORTH ); if ( fp != null && + * (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.NORTH ); } + * if ( out.contains( ForgeDirection.SOUTH ) && (side.offsetY != 0) ) { + * IFacadePart fp = fc.getFacade( ForgeDirection.SOUTH ); if ( fp != null && + * (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.SOUTH ); } + * if ( out.contains( ForgeDirection.EAST ) && (side.offsetY != 0) ) { IFacadePart + * fp = fc.getFacade( ForgeDirection.EAST ); if ( fp != null && + * (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.EAST ); } + * if ( out.contains( ForgeDirection.WEST ) && (side.offsetY != 0) ) { IFacadePart + * fp = fc.getFacade( ForgeDirection.WEST ); if ( fp != null && + * (fp.isTransparent() == facade.isTransparent()) ) out.remove( + * ForgeDirection.WEST ); } + */ + return out; + } - /* - * if ( out.contains( ForgeDirection.EAST ) && (side.offsetZ != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.EAST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.EAST ); } - * if ( out.contains( ForgeDirection.WEST ) && (side.offsetZ != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.WEST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.WEST ); } - * if ( out.contains( ForgeDirection.NORTH ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.NORTH ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.NORTH ); } - * if ( out.contains( ForgeDirection.SOUTH ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.SOUTH ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.SOUTH ); } - * if ( out.contains( ForgeDirection.EAST ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.EAST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.EAST ); } - * if ( out.contains( ForgeDirection.WEST ) && (side.offsetY != 0) ) { IFacadePart fp = fc.getFacade( - * ForgeDirection.WEST ); if ( fp != null && (fp.isTransparent() == facade.isTransparent()) ) out.remove( - * ForgeDirection.WEST ); } - */ - return out; - } + @SideOnly(Side.CLIENT) + private void renderSegmentBlockCurrentBounds( + final IPartRenderHelper instance, + final int x, + final int y, + final int z, + final RenderBlocks renderer, + final double minX, + final double minY, + final double minZ, + final double maxX, + final double maxY, + final double maxZ + ) { + final double oldMinX = renderer.renderMinX; + final double oldMinY = renderer.renderMinY; + final double oldMinZ = renderer.renderMinZ; + final double oldMaxX = renderer.renderMaxX; + final double oldMaxY = renderer.renderMaxY; + final double oldMaxZ = renderer.renderMaxZ; - @SideOnly( Side.CLIENT ) - private void renderSegmentBlockCurrentBounds( final IPartRenderHelper instance, final int x, final int y, final int z, final RenderBlocks renderer, final double minX, final double minY, final double minZ, final double maxX, final double maxY, final double maxZ ) - { - final double oldMinX = renderer.renderMinX; - final double oldMinY = renderer.renderMinY; - final double oldMinZ = renderer.renderMinZ; - final double oldMaxX = renderer.renderMaxX; - final double oldMaxY = renderer.renderMaxY; - final double oldMaxZ = renderer.renderMaxZ; + renderer.renderMinX = Math.max(renderer.renderMinX, minX); + renderer.renderMinY = Math.max(renderer.renderMinY, minY); + renderer.renderMinZ = Math.max(renderer.renderMinZ, minZ); + renderer.renderMaxX = Math.min(renderer.renderMaxX, maxX); + renderer.renderMaxY = Math.min(renderer.renderMaxY, maxY); + renderer.renderMaxZ = Math.min(renderer.renderMaxZ, maxZ); - renderer.renderMinX = Math.max( renderer.renderMinX, minX ); - renderer.renderMinY = Math.max( renderer.renderMinY, minY ); - renderer.renderMinZ = Math.max( renderer.renderMinZ, minZ ); - renderer.renderMaxX = Math.min( renderer.renderMaxX, maxX ); - renderer.renderMaxY = Math.min( renderer.renderMaxY, maxY ); - 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) { + instance.renderBlockCurrentBounds(x, y, z, renderer); + } - // 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 ) - { - instance.renderBlockCurrentBounds( x, y, z, renderer ); - } + renderer.renderMinX = oldMinX; + renderer.renderMinY = oldMinY; + renderer.renderMinZ = oldMinZ; + renderer.renderMaxX = oldMaxX; + renderer.renderMaxY = oldMaxY; + renderer.renderMaxZ = oldMaxZ; + } - renderer.renderMinX = oldMinX; - renderer.renderMinY = oldMinY; - renderer.renderMinZ = oldMinZ; - renderer.renderMaxX = oldMaxX; - renderer.renderMaxY = oldMaxY; - renderer.renderMaxZ = oldMaxZ; - } + private boolean hasAlphaDiff( + final TileEntity tileEntity, final ForgeDirection side, final IFacadePart facade + ) { + if (tileEntity instanceof IPartHost) { + final IPartHost ph = (IPartHost) tileEntity; + final IFacadePart fp = ph.getFacadeContainer().getFacade(side); - private boolean hasAlphaDiff( final TileEntity tileEntity, final ForgeDirection side, final IFacadePart facade ) - { - if( tileEntity instanceof IPartHost ) - { - final IPartHost ph = (IPartHost) tileEntity; - final IFacadePart fp = ph.getFacadeContainer().getFacade( side ); + return fp == null || (fp.isTransparent() != facade.isTransparent()); + } - return fp == null || ( fp.isTransparent() != facade.isTransparent() ); - } + return true; + } - return true; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - this.getBoxes( bch, null ); - } + @Override + public void getBoxes(final 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 39c4baed..422a46cb 100644 --- a/src/main/java/appeng/facade/IFacadeItem.java +++ b/src/main/java/appeng/facade/IFacadeItem.java @@ -18,20 +18,16 @@ 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); -public interface IFacadeItem -{ + ItemStack getTextureItem(ItemStack is); - FacadePart createPartFromItemStack( ItemStack is, ForgeDirection side ); + int getMeta(ItemStack is); - ItemStack getTextureItem( ItemStack is ); - - int getMeta( ItemStack is ); - - Block getBlock( 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 9d670555..f793c233 100644 --- a/src/main/java/appeng/fmp/CableBusPart.java +++ b/src/main/java/appeng/fmp/CableBusPart.java @@ -18,6 +18,8 @@ package appeng.fmp; +import java.io.IOException; +import java.util.*; import appeng.api.implementations.parts.IPartCable; import appeng.api.networking.IGridNode; @@ -55,636 +57,564 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.*; - - /** * Implementing these might help improve visuals for hollow covers *

* TSlottedPart,ISidedHollowConnect */ -public class CableBusPart extends JCuboidPart implements JNormalOcclusion, IMaskedRedstonePart, AEMultiTile -{ - private static final ThreadLocal DISABLE_FACADE_OCCLUSION = new ThreadLocal(); - private static final double SHORTER = 6.0 / 16.0; - private static final double LONGER = 10.0 / 16.0; - private static final double MIN_DIRECTION = 0; - private static final double MAX_DIRECTION = 1.0; - private static final Cuboid6[] SIDE_TESTS = { - - // DOWN(0, -1, 0), - new Cuboid6( SHORTER, MIN_DIRECTION, SHORTER, LONGER, SHORTER, LONGER ), - - // UP(0, 1, 0), - new Cuboid6( SHORTER, LONGER, SHORTER, LONGER, MAX_DIRECTION, LONGER ), - - // NORTH(0, 0, -1), - new Cuboid6( SHORTER, SHORTER, MIN_DIRECTION, LONGER, LONGER, SHORTER ), - - // SOUTH(0, 0, 1), - new Cuboid6( SHORTER, SHORTER, LONGER, LONGER, LONGER, MAX_DIRECTION ), - - // WEST(-1, 0, 0), - new Cuboid6( MIN_DIRECTION, SHORTER, SHORTER, SHORTER, LONGER, LONGER ), - - // EAST(1, 0, 0), - new Cuboid6( LONGER, SHORTER, SHORTER, MAX_DIRECTION, LONGER, LONGER ), - }; - - /** - * Mask for {@link IMaskedRedstonePart#getConnectionMask(int)} - *

- * the bits are derived from the rotation, where 4 is the center - */ - private static final int CONNECTION_MASK = 0x000010; - private CableBusContainer cb = new CableBusContainer( this ); - private boolean canUpdate = false; - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - return this.getCableBus().recolourBlock( side, colour, who ); - } - - @Override - public Cuboid6 getBounds() - { - AxisAlignedBB b = null; - - for( final AxisAlignedBB bx : this.getCableBus().getSelectedBoundingBoxesFromPool( false, true, null, true ) ) - { - if( b == null ) - { - b = bx; - } - else - { - final double minX = Math.min( b.minX, bx.minX ); - final double minY = Math.min( b.minY, bx.minY ); - final double minZ = Math.min( b.minZ, bx.minZ ); - final double maxX = Math.max( b.maxX, bx.maxX ); - final double maxY = Math.max( b.maxY, bx.maxY ); - final double maxZ = Math.max( b.maxZ, bx.maxZ ); - b.setBounds( minX, minY, minZ, maxX, maxY, maxZ ); - } - } - - 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 ); - } - - @Override - public String getType() - { - return PartRegistry.CableBusPart.getName(); - } - - @Override - public int getLightValue() - { - return this.getCableBus().getLightValue(); - } - - @Override - public void onWorldJoin() - { - this.canUpdate = true; - this.getCableBus().updateConnections(); - this.getCableBus().addToWorld(); - } - - @Override - public boolean occlusionTest( final TMultiPart part ) - { - return NormalOcclusionTest.apply( this, part ); - } - - @Override - public boolean renderStatic( final Vector3 pos, final int pass ) - { - if( pass == 0 || ( pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) ) - { - BusRenderHelper.INSTANCE.setPass( pass ); - BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; - BusRenderer.INSTANCE.getRenderer().blockAccess = this.world(); - BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; - this.getCableBus().renderStatic( pos.x, pos.y, pos.z ); - return BusRenderHelper.INSTANCE.getItemsRendered() > 0; - } - return false; - } - - @Override - public void renderDynamic( final Vector3 pos, final float frame, final int pass ) - { - if( pass == 0 || ( pass == 1 && AEConfig.instance.isFeatureEnabled( AEFeature.AlphaPass ) ) ) - { - BusRenderHelper.INSTANCE.setPass( pass ); - this.getCableBus().renderDynamic( pos.x, pos.y, pos.z ); - } - } - - @Override - public void onPartChanged( final TMultiPart part ) - { - this.getCableBus().updateConnections(); - } - - @Override - public void onEntityCollision( final Entity entity ) - { - this.getCableBus().onEntityCollision( entity ); - } - - @Override - public boolean activate( final EntityPlayer player, final MovingObjectPosition hit, final ItemStack item ) - { - return this.getCableBus().activate( player, hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ) ); - } - - @Override - public void load( final NBTTagCompound tag ) - { - this.getCableBus().readFromNBT( tag ); - } - - @Override - public void onWorldSeparate() - { - this.canUpdate = false; - this.getCableBus().removeFromWorld(); - } - - @Override - public void save( final NBTTagCompound tag ) - { - this.getCableBus().writeToNBT( tag ); - } - - @Override - public void writeDesc( final MCDataOutput packet ) - { - final ByteBuf stream = Unpooled.buffer(); - - try - { - this.getCableBus().writeToStream( stream ); - packet.writeInt( stream.readableBytes() ); - stream.capacity( stream.readableBytes() ); - packet.writeByteArray( stream.array() ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - @Override - public ItemStack pickItem( final MovingObjectPosition hit ) - { - final Vec3 v3 = hit.hitVec.addVector( -hit.blockX, -hit.blockY, -hit.blockZ ); - final SelectedPart sp = this.getCableBus().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.getCableBus().getDrops( new ArrayList() ); - } - - @Override - public void onNeighborChanged() - { - this.getCableBus().onNeighborChanged(); - } - - @Override - public boolean doesTick() - { - return false; - } - - @Override - public void invalidateConvertedTile() - { - this.getCableBus().setHost( this ); - } - - @Override - public void readDesc( final MCDataInput packet ) - { - final int len = packet.readInt(); - final byte[] data = packet.readByteArray( len ); - - try - { - if( len > 0 ) - { - final ByteBuf byteBuffer = Unpooled.wrappedBuffer( data ); - this.getCableBus().readFromStream( byteBuffer ); - } - } - catch( final IOException e ) - { - AELog.debug( e ); - } - } - - @Override - public boolean canConnectRedstone( final int side ) - { - return this.getCableBus().canConnectRedstone( EnumSet.of( ForgeDirection.getOrientation( side ) ) ); - } - - @Override - public int weakPowerLevel( final int side ) - { - return this.getCableBus().isProvidingWeakPower( ForgeDirection.getOrientation( side ) ); - } - - @Override - public int strongPowerLevel( final int side ) - { - return this.getCableBus().isProvidingStrongPower( ForgeDirection.getOrientation( side ) ); - } - - public void convertFromTile( final TileEntity blockTileEntity ) - { - final TileCableBus tcb = (TileCableBus) blockTileEntity; - this.setCableBus( tcb.getCableBus() ); - } - - @Override - public Iterable getOcclusionBoxes() - { - final LinkedList l = new LinkedList(); - for( final AxisAlignedBB b : this.getCableBus().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 ) ); - } - return l; - } - - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getCableBus().getGridNode( dir ); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return this.getCableBus().getCableConnectionType( dir ); - } - - @Override - public void securityBreak() - { - this.getCableBus().securityBreak(); - } - - // @Override - public int getHollowSize( final int side ) - { - final IPartCable cable = (IPartCable) this.getPart( ForgeDirection.UNKNOWN ); - - final ForgeDirection dir = ForgeDirection.getOrientation( side ); - if( cable != null && cable.isConnected( dir ) ) - { - final List boxes = new ArrayList(); - - final BusCollisionHelper bch = new BusCollisionHelper( boxes, ForgeDirection.EAST, ForgeDirection.UP, ForgeDirection.SOUTH, null, true ); - - for( final ForgeDirection whichSide : ForgeDirection.values() ) - { - final IPart fPart = this.getPart( whichSide ); - - if( fPart != null ) - { - fPart.getBoxes( bch ); - } - } - - AxisAlignedBB b = null; - final AxisAlignedBB pb = Platform.getPrimaryBox( dir, 2 ); - - for( final AxisAlignedBB bb : boxes ) - { - if( bb.intersectsWith( pb ) ) - { - if( b == null ) - { - b = bb; - } - else - { - b.maxX = Math.max( b.maxX, bb.maxX ); - b.maxY = Math.max( b.maxY, bb.maxY ); - b.maxZ = Math.max( b.maxZ, bb.maxZ ); - b.minX = Math.min( b.minX, bb.minX ); - b.minY = Math.min( b.minY, bb.minY ); - b.minZ = Math.min( b.minZ, bb.minZ ); - } - } - } - - if( b == null ) - { - return 0; - } - - 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: - } - } - - return 12; - } - - private int getSize( final double a, final double b, final double c, final 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 ) ); - } - - // @Override - public int getSlotMask() - { - int mask = 0; - - for( final ForgeDirection side : ForgeDirection.values() ) - { - if( this.getPart( side ) != null ) - { - mask |= 1 << side.ordinal(); - } - else if( side != ForgeDirection.UNKNOWN && this.getFacadeContainer().getFacade( side ) != null ) - { - mask |= 1 << side.ordinal(); - } - } - - return mask; - } - - @Override - public IFacadeContainer getFacadeContainer() - { - return this.getCableBus().getFacadeContainer(); - } - - @Override - public boolean canAddPart( ItemStack is, final ForgeDirection side ) - { - final IFacadePart fp = PartPlacement.isFacade( is, side ); - if( fp != null ) - { - if( !( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) ) - { - final List boxes = new ArrayList(); - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - fp.getBoxes( bch, null ); - for( final AxisAlignedBB bb : boxes ) - { - DISABLE_FACADE_OCCLUSION.set( true ); - final 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 ) - { - final IPartItem bi = (IPartItem) is.getItem(); - - is = is.copy(); - is.stackSize = 1; - - final IPart bp = bi.createPartFromItemStack( is ); - if( !( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) ) - { - final List boxes = new ArrayList(); - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - if( bp != null ) - { - bp.getBoxes( bch ); - } - for( final AxisAlignedBB bb : boxes ) - { - if( !this.tile().canAddPart( new NormallyOccludedPart( new Cuboid6( bb ) ) ) ) - { - return false; - } - } - } - } - - return this.getCableBus().canAddPart( is, side ); - } - - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer owner ) - { - return this.getCableBus().addPart( is, side, owner ); - } - - @Override - public IPart getPart( final ForgeDirection side ) - { - return this.getCableBus().getPart( side ); - } - - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - this.getCableBus().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.getCableBus().getColor(); - } - - @Override - public void clearContainer() - { - this.setCableBus( new CableBusContainer( this ) ); - } - - @Override - public boolean isBlocked( final ForgeDirection side ) - { - if( side == null || side == ForgeDirection.UNKNOWN || this.tile() == null ) - { - return false; - } - - DISABLE_FACADE_OCCLUSION.set( true ); - - final int ordinal = side.ordinal(); - final Cuboid6 sideTest = SIDE_TESTS[ordinal]; - final NormallyOccludedPart occludedPart = new NormallyOccludedPart( sideTest ); - final boolean blocked = !this.tile().canAddPart( occludedPart ); - DISABLE_FACADE_OCCLUSION.remove(); - - return blocked; - } - - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - return this.getCableBus().selectPart( pos ); - } - - @Override - public void markForSave() - { - // mark the chunk for save... - final 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( final ForgeDirection side ) - { - return this.getCableBus().hasRedstone( side ); - } - - @Override - public boolean isEmpty() - { - return this.getCableBus().isEmpty(); - } - - @Override - public Set getLayerFlags() - { - return this.getCableBus().getLayerFlags(); - } - - @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.getCableBus().isInWorld(); - } - - @Override - public Iterable getCollisionBoxes() - { - final LinkedList l = new LinkedList(); - for( final AxisAlignedBB b : this.getCableBus().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() - { - final LinkedList l = new LinkedList(); - for( final Cuboid6 c : this.getCollisionBoxes() ) - { - l.add( new IndexedCuboid6( 0, c ) ); - } - return l; - } - - @Override - public int getConnectionMask( final int side ) - { - return CONNECTION_MASK; - } - - public CableBusContainer getCableBus() - { - return this.cb; - } - - private void setCableBus( final CableBusContainer cb ) - { - this.cb = cb; - } +public class CableBusPart + extends JCuboidPart implements JNormalOcclusion, IMaskedRedstonePart, AEMultiTile { + private static final ThreadLocal DISABLE_FACADE_OCCLUSION + = new ThreadLocal(); + private static final double SHORTER = 6.0 / 16.0; + private static final double LONGER = 10.0 / 16.0; + private static final double MIN_DIRECTION = 0; + private static final double MAX_DIRECTION = 1.0; + private static final Cuboid6[] SIDE_TESTS = { + + // DOWN(0, -1, 0), + new Cuboid6(SHORTER, MIN_DIRECTION, SHORTER, LONGER, SHORTER, LONGER), + + // UP(0, 1, 0), + new Cuboid6(SHORTER, LONGER, SHORTER, LONGER, MAX_DIRECTION, LONGER), + + // NORTH(0, 0, -1), + new Cuboid6(SHORTER, SHORTER, MIN_DIRECTION, LONGER, LONGER, SHORTER), + + // SOUTH(0, 0, 1), + new Cuboid6(SHORTER, SHORTER, LONGER, LONGER, LONGER, MAX_DIRECTION), + + // WEST(-1, 0, 0), + new Cuboid6(MIN_DIRECTION, SHORTER, SHORTER, SHORTER, LONGER, LONGER), + + // EAST(1, 0, 0), + new Cuboid6(LONGER, SHORTER, SHORTER, MAX_DIRECTION, LONGER, LONGER), + }; + + /** + * Mask for {@link IMaskedRedstonePart#getConnectionMask(int)} + *

+ * the bits are derived from the rotation, where 4 is the center + */ + private static final int CONNECTION_MASK = 0x000010; + private CableBusContainer cb = new CableBusContainer(this); + private boolean canUpdate = false; + + @Override + public boolean recolourBlock( + final ForgeDirection side, final AEColor colour, final EntityPlayer who + ) { + return this.getCableBus().recolourBlock(side, colour, who); + } + + @Override + public Cuboid6 getBounds() { + AxisAlignedBB b = null; + + for (final AxisAlignedBB bx : this.getCableBus().getSelectedBoundingBoxesFromPool( + false, true, null, true + )) { + if (b == null) { + b = bx; + } else { + final double minX = Math.min(b.minX, bx.minX); + final double minY = Math.min(b.minY, bx.minY); + final double minZ = Math.min(b.minZ, bx.minZ); + final double maxX = Math.max(b.maxX, bx.maxX); + final double maxY = Math.max(b.maxY, bx.maxY); + final double maxZ = Math.max(b.maxZ, bx.maxZ); + b.setBounds(minX, minY, minZ, maxX, maxY, maxZ); + } + } + + 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); + } + + @Override + public String getType() { + return PartRegistry.CableBusPart.getName(); + } + + @Override + public int getLightValue() { + return this.getCableBus().getLightValue(); + } + + @Override + public void onWorldJoin() { + this.canUpdate = true; + this.getCableBus().updateConnections(); + this.getCableBus().addToWorld(); + } + + @Override + public boolean occlusionTest(final TMultiPart part) { + return NormalOcclusionTest.apply(this, part); + } + + @Override + public boolean renderStatic(final Vector3 pos, final int pass) { + if (pass == 0 + || (pass == 1 && AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass))) { + BusRenderHelper.INSTANCE.setPass(pass); + BusRenderer.INSTANCE.getRenderer().renderAllFaces = true; + BusRenderer.INSTANCE.getRenderer().blockAccess = this.world(); + BusRenderer.INSTANCE.getRenderer().overrideBlockTexture = null; + this.getCableBus().renderStatic(pos.x, pos.y, pos.z); + return BusRenderHelper.INSTANCE.getItemsRendered() > 0; + } + return false; + } + + @Override + public void renderDynamic(final Vector3 pos, final float frame, final int pass) { + if (pass == 0 + || (pass == 1 && AEConfig.instance.isFeatureEnabled(AEFeature.AlphaPass))) { + BusRenderHelper.INSTANCE.setPass(pass); + this.getCableBus().renderDynamic(pos.x, pos.y, pos.z); + } + } + + @Override + public void onPartChanged(final TMultiPart part) { + this.getCableBus().updateConnections(); + } + + @Override + public void onEntityCollision(final Entity entity) { + this.getCableBus().onEntityCollision(entity); + } + + @Override + public boolean activate( + final EntityPlayer player, final MovingObjectPosition hit, final ItemStack item + ) { + return this.getCableBus().activate( + player, hit.hitVec.addVector(-hit.blockX, -hit.blockY, -hit.blockZ) + ); + } + + @Override + public void load(final NBTTagCompound tag) { + this.getCableBus().readFromNBT(tag); + } + + @Override + public void onWorldSeparate() { + this.canUpdate = false; + this.getCableBus().removeFromWorld(); + } + + @Override + public void save(final NBTTagCompound tag) { + this.getCableBus().writeToNBT(tag); + } + + @Override + public void writeDesc(final MCDataOutput packet) { + final ByteBuf stream = Unpooled.buffer(); + + try { + this.getCableBus().writeToStream(stream); + packet.writeInt(stream.readableBytes()); + stream.capacity(stream.readableBytes()); + packet.writeByteArray(stream.array()); + } catch (final IOException e) { + AELog.debug(e); + } + } + + @Override + public ItemStack pickItem(final MovingObjectPosition hit) { + final Vec3 v3 = hit.hitVec.addVector(-hit.blockX, -hit.blockY, -hit.blockZ); + final SelectedPart sp = this.getCableBus().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.getCableBus().getDrops(new ArrayList()); + } + + @Override + public void onNeighborChanged() { + this.getCableBus().onNeighborChanged(); + } + + @Override + public boolean doesTick() { + return false; + } + + @Override + public void invalidateConvertedTile() { + this.getCableBus().setHost(this); + } + + @Override + public void readDesc(final MCDataInput packet) { + final int len = packet.readInt(); + final byte[] data = packet.readByteArray(len); + + try { + if (len > 0) { + final ByteBuf byteBuffer = Unpooled.wrappedBuffer(data); + this.getCableBus().readFromStream(byteBuffer); + } + } catch (final IOException e) { + AELog.debug(e); + } + } + + @Override + public boolean canConnectRedstone(final int side) { + return this.getCableBus().canConnectRedstone( + EnumSet.of(ForgeDirection.getOrientation(side)) + ); + } + + @Override + public int weakPowerLevel(final int side) { + return this.getCableBus().isProvidingWeakPower(ForgeDirection.getOrientation(side) + ); + } + + @Override + public int strongPowerLevel(final int side) { + return this.getCableBus().isProvidingStrongPower( + ForgeDirection.getOrientation(side) + ); + } + + public void convertFromTile(final TileEntity blockTileEntity) { + final TileCableBus tcb = (TileCableBus) blockTileEntity; + this.setCableBus(tcb.getCableBus()); + } + + @Override + public Iterable getOcclusionBoxes() { + final LinkedList l = new LinkedList(); + for (final AxisAlignedBB b : this.getCableBus().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)); + } + return l; + } + + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getCableBus().getGridNode(dir); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return this.getCableBus().getCableConnectionType(dir); + } + + @Override + public void securityBreak() { + this.getCableBus().securityBreak(); + } + + // @Override + public int getHollowSize(final int side) { + final IPartCable cable = (IPartCable) this.getPart(ForgeDirection.UNKNOWN); + + final ForgeDirection dir = ForgeDirection.getOrientation(side); + if (cable != null && cable.isConnected(dir)) { + final List boxes = new ArrayList(); + + final BusCollisionHelper bch = new BusCollisionHelper( + boxes, + ForgeDirection.EAST, + ForgeDirection.UP, + ForgeDirection.SOUTH, + null, + true + ); + + for (final ForgeDirection whichSide : ForgeDirection.values()) { + final IPart fPart = this.getPart(whichSide); + + if (fPart != null) { + fPart.getBoxes(bch); + } + } + + AxisAlignedBB b = null; + final AxisAlignedBB pb = Platform.getPrimaryBox(dir, 2); + + for (final AxisAlignedBB bb : boxes) { + if (bb.intersectsWith(pb)) { + if (b == null) { + b = bb; + } else { + b.maxX = Math.max(b.maxX, bb.maxX); + b.maxY = Math.max(b.maxY, bb.maxY); + b.maxZ = Math.max(b.maxZ, bb.maxZ); + b.minX = Math.min(b.minX, bb.minX); + b.minY = Math.min(b.minY, bb.minY); + b.minZ = Math.min(b.minZ, bb.minZ); + } + } + } + + if (b == null) { + return 0; + } + + 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: + } + } + + return 12; + } + + private int getSize(final double a, final double b, final double c, final 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)); + } + + // @Override + public int getSlotMask() { + int mask = 0; + + for (final ForgeDirection side : ForgeDirection.values()) { + if (this.getPart(side) != null) { + mask |= 1 << side.ordinal(); + } else if (side != ForgeDirection.UNKNOWN && this.getFacadeContainer().getFacade(side) != null) { + mask |= 1 << side.ordinal(); + } + } + + return mask; + } + + @Override + public IFacadeContainer getFacadeContainer() { + return this.getCableBus().getFacadeContainer(); + } + + @Override + public boolean canAddPart(ItemStack is, final ForgeDirection side) { + final IFacadePart fp = PartPlacement.isFacade(is, side); + if (fp != null) { + if (!(side == null || side == ForgeDirection.UNKNOWN || this.tile() == null + )) { + final List boxes = new ArrayList(); + final IPartCollisionHelper bch + = new BusCollisionHelper(boxes, side, null, true); + fp.getBoxes(bch, null); + for (final AxisAlignedBB bb : boxes) { + DISABLE_FACADE_OCCLUSION.set(true); + final 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) { + final IPartItem bi = (IPartItem) is.getItem(); + + is = is.copy(); + is.stackSize = 1; + + final IPart bp = bi.createPartFromItemStack(is); + if (!(side == null || side == ForgeDirection.UNKNOWN || this.tile() == null + )) { + final List boxes = new ArrayList(); + final IPartCollisionHelper bch + = new BusCollisionHelper(boxes, side, null, true); + if (bp != null) { + bp.getBoxes(bch); + } + for (final AxisAlignedBB bb : boxes) { + if (!this.tile().canAddPart(new NormallyOccludedPart(new Cuboid6(bb)) + )) { + return false; + } + } + } + } + + return this.getCableBus().canAddPart(is, side); + } + + @Override + public ForgeDirection + addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer owner) { + return this.getCableBus().addPart(is, side, owner); + } + + @Override + public IPart getPart(final ForgeDirection side) { + return this.getCableBus().getPart(side); + } + + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + this.getCableBus().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.getCableBus().getColor(); + } + + @Override + public void clearContainer() { + this.setCableBus(new CableBusContainer(this)); + } + + @Override + public boolean isBlocked(final ForgeDirection side) { + if (side == null || side == ForgeDirection.UNKNOWN || this.tile() == null) { + return false; + } + + DISABLE_FACADE_OCCLUSION.set(true); + + final int ordinal = side.ordinal(); + final Cuboid6 sideTest = SIDE_TESTS[ordinal]; + final NormallyOccludedPart occludedPart = new NormallyOccludedPart(sideTest); + final boolean blocked = !this.tile().canAddPart(occludedPart); + DISABLE_FACADE_OCCLUSION.remove(); + + return blocked; + } + + @Override + public SelectedPart selectPart(final Vec3 pos) { + return this.getCableBus().selectPart(pos); + } + + @Override + public void markForSave() { + // mark the chunk for save... + final 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(final ForgeDirection side) { + return this.getCableBus().hasRedstone(side); + } + + @Override + public boolean isEmpty() { + return this.getCableBus().isEmpty(); + } + + @Override + public Set getLayerFlags() { + return this.getCableBus().getLayerFlags(); + } + + @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.getCableBus().isInWorld(); + } + + @Override + public Iterable getCollisionBoxes() { + final LinkedList l = new LinkedList(); + for (final AxisAlignedBB b : this.getCableBus().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() { + final LinkedList l = new LinkedList(); + for (final Cuboid6 c : this.getCollisionBoxes()) { + l.add(new IndexedCuboid6(0, c)); + } + return l; + } + + @Override + public int getConnectionMask(final int side) { + return CONNECTION_MASK; + } + + public CableBusContainer getCableBus() { + return this.cb; + } + + private void setCableBus(final CableBusContainer cb) { + this.cb = cb; + } } diff --git a/src/main/java/appeng/fmp/FMPEvent.java b/src/main/java/appeng/fmp/FMPEvent.java index 002c3c1e..b04638ee 100644 --- a/src/main/java/appeng/fmp/FMPEvent.java +++ b/src/main/java/appeng/fmp/FMPEvent.java @@ -18,7 +18,6 @@ package appeng.fmp; - import appeng.block.AEBaseItemBlock; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketMultiPart; @@ -42,115 +41,127 @@ import net.minecraftforge.event.entity.player.PlayerDestroyItemEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; - /** * Basically a total rip of of the FMP version for vanilla, seemed to work well enough... */ -public class FMPEvent -{ +public class FMPEvent { + private final ThreadLocal placing = new ThreadLocal(); - private final ThreadLocal placing = new ThreadLocal(); + @SubscribeEvent + public void ServerFMPEvent(final FMPPacketEvent event) { + FMPEvent.place(event.getSender(), event.getSender().worldObj); + } - @SubscribeEvent - public void ServerFMPEvent( final FMPPacketEvent event ) - { - FMPEvent.place( event.getSender(), event.getSender().worldObj ); - } + private static boolean place(final EntityPlayer player, final World world) { + final MovingObjectPosition hit = RayTracer.reTrace(world, player); + if (hit == null) { + return false; + } - private static boolean place( final EntityPlayer player, final World world ) - { - final MovingObjectPosition hit = RayTracer.reTrace( world, player ); - if( hit == null ) - { - return false; - } + final BlockCoord pos + = new BlockCoord(hit.blockX, hit.blockY, hit.blockZ).offset(hit.sideHit); + final ItemStack held = player.getHeldItem(); - final BlockCoord pos = new BlockCoord( hit.blockX, hit.blockY, hit.blockZ ).offset( hit.sideHit ); - final ItemStack held = player.getHeldItem(); + if (held == null) { + return false; + } - if( held == null ) - { - return false; - } + Block blk = null; + TMultiPart part = null; + if (held.getItem() instanceof AEBaseItemBlock) { + final AEBaseItemBlock ib = (AEBaseItemBlock) held.getItem(); + blk = Block.getBlockFromItem(ib); + part = PartRegistry.getPartByBlock(blk, hit.sideHit); + } - Block blk = null; - TMultiPart part = null; - if( held.getItem() instanceof AEBaseItemBlock ) - { - final AEBaseItemBlock ib = (AEBaseItemBlock) held.getItem(); - blk = Block.getBlockFromItem( ib ); - part = PartRegistry.getPartByBlock( blk, hit.sideHit ); - } + if (part == null) { + return false; + } - if( part == null ) - { - return false; - } + if (world.isRemote + && !player.isSneaking( + )) // attempt to use block activated like normal and tell the server + // the right stuff + { + final Vector3 f + = new Vector3(hit.hitVec).add(-hit.blockX, -hit.blockY, -hit.blockZ); + final 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 + )) { + 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 + )); + return true; + } + } - if( world.isRemote && !player.isSneaking() )// attempt to use block activated like normal and tell the server - // the right stuff - { - final Vector3 f = new Vector3( hit.hitVec ).add( -hit.blockX, -hit.blockY, -hit.blockZ ); - final 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 ) ) - { - 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 ) ); - return true; - } - } + final TileMultipart tile = TileMultipart.getOrConvertTile(world, pos); + if (tile == null || !tile.canAddPart(part)) { + return false; + } - final TileMultipart tile = TileMultipart.getOrConvertTile( world, pos ); - if( tile == null || !tile.canAddPart( part ) ) - { - return false; - } + 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) { + held.stackSize--; + if (held.stackSize == 0) { + player.inventory.mainInventory[player.inventory.currentItem] = null; + MinecraftForge.EVENT_BUS.post(new PlayerDestroyItemEvent(player, held) + ); + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer(new PacketMultiPart()); + } + return true; + } - 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 ) - { - held.stackSize--; - if( held.stackSize == 0 ) - { - player.inventory.mainInventory[player.inventory.currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketMultiPart() ); - } - return true; - } + /** + * Because vanilla is weird. + */ + private static boolean ignoreActivate(final Block block) { + return block instanceof BlockFence; + } - /** - * Because vanilla is weird. - */ - private static boolean ignoreActivate( final Block block ) - { - return block instanceof BlockFence; - } - - @SubscribeEvent - public void playerInteract( final 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 ); - } - } + @SubscribeEvent + public void playerInteract(final 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 89639d3d..2a03ba71 100644 --- a/src/main/java/appeng/fmp/FMPPlacementHelper.java +++ b/src/main/java/appeng/fmp/FMPPlacementHelper.java @@ -18,6 +18,8 @@ package appeng.fmp; +import java.util.EnumSet; +import java.util.Set; import appeng.api.parts.*; import appeng.api.util.AEColor; @@ -34,285 +36,231 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Set; +public class FMPPlacementHelper implements IPartHost { + private static final CableBusStorage NULL_STORAGE = new NullStorage(); + private boolean hasPart = false; + private TileMultipart myMP; + private CableBusPart myPart; + public FMPPlacementHelper(final TileMultipart mp) { + this.myMP = mp; + } -public class FMPPlacementHelper implements IPartHost -{ + @Override + public IFacadeContainer getFacadeContainer() { + if (this.myPart == null) { + return new FacadeContainer(NULL_STORAGE); + } + return this.myPart.getFacadeContainer(); + } - private static final CableBusStorage NULL_STORAGE = new NullStorage(); - private boolean hasPart = false; - private TileMultipart myMP; - private CableBusPart myPart; + @Override + public boolean canAddPart(final ItemStack part, final ForgeDirection side) { + final CableBusPart myPart = this.getPart(); - public FMPPlacementHelper( final TileMultipart mp ) - { - this.myMP = mp; - } + final boolean returnValue = this.hasPart && myPart.canAddPart(part, side); - @Override - public IFacadeContainer getFacadeContainer() - { - if( this.myPart == null ) - { - return new FacadeContainer( NULL_STORAGE ); - } - return this.myPart.getFacadeContainer(); - } + this.removePart(); - @Override - public boolean canAddPart( final ItemStack part, final ForgeDirection side ) - { - final CableBusPart myPart = this.getPart(); + return returnValue; + } - final boolean returnValue = this.hasPart && myPart.canAddPart( part, side ); + private CableBusPart getPart() { + final scala.collection.Iterator i = this.myMP.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p instanceof CableBusPart) { + this.myPart = (CableBusPart) p; + } + } - this.removePart(); + if (this.myPart == null) { + this.myPart = (CableBusPart) PartRegistry.CableBusPart.construct(0); + } - return returnValue; - } + final BlockCoord loc + = new BlockCoord(this.myMP.xCoord, this.myMP.yCoord, this.myMP.zCoord); - private CableBusPart getPart() - { - final scala.collection.Iterator i = this.myMP.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p instanceof CableBusPart ) - { - this.myPart = (CableBusPart) p; - } - } + if (this.myMP.canAddPart(this.myPart) && Platform.isServer()) { + this.myMP = TileMultipart.addPart(this.myMP.getWorldObj(), loc, this.myPart); + this.hasPart = true; + } - if( this.myPart == null ) - { - this.myPart = (CableBusPart) PartRegistry.CableBusPart.construct( 0 ); - } + return this.myPart; + } - final BlockCoord loc = new BlockCoord( this.myMP.xCoord, this.myMP.yCoord, this.myMP.zCoord ); + private void removePart() { + if (this.myPart.isEmpty()) { + final scala.collection.Iterator i + = this.myMP.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p == this.myPart) { + this.myMP = this.myMP.remPart(this.myPart); + break; + } + } + this.hasPart = false; + this.myPart = null; + } + } - if( this.myMP.canAddPart( this.myPart ) && Platform.isServer() ) - { - this.myMP = TileMultipart.addPart( this.myMP.getWorldObj(), loc, this.myPart ); - this.hasPart = true; - } + @Override + public ForgeDirection + addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer owner) { + final CableBusPart myPart = this.getPart(); - return this.myPart; - } + final ForgeDirection returnValue + = this.hasPart ? myPart.addPart(is, side, owner) : null; - private void removePart() - { - if( this.myPart.isEmpty() ) - { - final scala.collection.Iterator i = this.myMP.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p == this.myPart ) - { - this.myMP = this.myMP.remPart( this.myPart ); - break; - } - } - this.hasPart = false; - this.myPart = null; - } - } + this.removePart(); - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer owner ) - { - final CableBusPart myPart = this.getPart(); + return returnValue; + } - final ForgeDirection returnValue = this.hasPart ? myPart.addPart( is, side, owner ) : null; + @Override + public IPart getPart(final ForgeDirection side) { + if (this.myPart == null) { + return null; + } + return this.myPart.getPart(side); + } - this.removePart(); + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + if (this.myPart == null) { + return; + } + this.myPart.removePart(side, suppressUpdate); + } - return returnValue; - } + @Override + public void markForUpdate() { + if (this.myPart == null) { + return; + } + this.myPart.markForUpdate(); + } - @Override - public IPart getPart( final ForgeDirection side ) - { - if( this.myPart == null ) - { - return null; - } - return this.myPart.getPart( side ); - } + @Override + public DimensionalCoord getLocation() { + if (this.myPart == null) { + return new DimensionalCoord(this.myMP); + } + return this.myPart.getLocation(); + } - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - if( this.myPart == null ) - { - return; - } - this.myPart.removePart( side, suppressUpdate ); - } + @Override + public TileEntity getTile() { + return this.myMP; + } - @Override - public void markForUpdate() - { - if( this.myPart == null ) - { - return; - } - this.myPart.markForUpdate(); - } + @Override + public AEColor getColor() { + if (this.myPart == null) { + return AEColor.Transparent; + } + return this.myPart.getColor(); + } - @Override - public DimensionalCoord getLocation() - { - if( this.myPart == null ) - { - return new DimensionalCoord( this.myMP ); - } - return this.myPart.getLocation(); - } + @Override + public void clearContainer() { + if (this.myPart == null) { + return; + } + this.myPart.clearContainer(); + } - @Override - public TileEntity getTile() - { - return this.myMP; - } + @Override + public boolean isBlocked(final ForgeDirection side) { + this.getPart(); - @Override - public AEColor getColor() - { - if( this.myPart == null ) - { - return AEColor.Transparent; - } - return this.myPart.getColor(); - } + final boolean returnValue = this.myPart.isBlocked(side); - @Override - public void clearContainer() - { - if( this.myPart == null ) - { - return; - } - this.myPart.clearContainer(); - } + this.removePart(); - @Override - public boolean isBlocked( final ForgeDirection side ) - { - this.getPart(); + return returnValue; + } - final boolean returnValue = this.myPart.isBlocked( side ); + @Override + public SelectedPart selectPart(final Vec3 pos) { + if (this.myPart == null) { + return new SelectedPart(); + } + return this.myPart.selectPart(pos); + } - this.removePart(); + @Override + public void markForSave() { + if (this.myPart == null) { + return; + } + this.myPart.markForSave(); + } - return returnValue; - } + @Override + public void partChanged() { + if (this.myPart == null) { + return; + } + this.myPart.partChanged(); + } - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - if( this.myPart == null ) - { - return new SelectedPart(); - } - return this.myPart.selectPart( pos ); - } + @Override + public boolean hasRedstone(final ForgeDirection side) { + if (this.myPart == null) { + return false; + } + return this.myPart.hasRedstone(side); + } - @Override - public void markForSave() - { - if( this.myPart == null ) - { - return; - } - this.myPart.markForSave(); - } + @Override + public boolean isEmpty() { + if (this.myPart == null) { + return true; + } + return this.myPart.isEmpty(); + } - @Override - public void partChanged() - { - if( this.myPart == null ) - { - return; - } - this.myPart.partChanged(); - } + @Override + public Set getLayerFlags() { + if (this.myPart == null) { + return EnumSet.noneOf(LayerFlags.class); + } + return this.myPart.getLayerFlags(); + } - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - if( this.myPart == null ) - { - return false; - } - return this.myPart.hasRedstone( side ); - } + @Override + public void cleanup() { + if (this.myPart == null) { + return; + } + this.myPart.cleanup(); + } - @Override - public boolean isEmpty() - { - if( this.myPart == null ) - { - return true; - } - return this.myPart.isEmpty(); - } + @Override + public void notifyNeighbors() { + if (this.myPart == null) { + return; + } + this.myPart.notifyNeighbors(); + } - @Override - public Set getLayerFlags() - { - if( this.myPart == null ) - { - return EnumSet.noneOf( LayerFlags.class ); - } - return this.myPart.getLayerFlags(); - } + @Override + public boolean isInWorld() { + if (this.myPart == null) { + return this.myMP.getWorldObj() != null; + } + return this.myPart.isInWorld(); + } - @Override - public void cleanup() - { - if( this.myPart == null ) - { - return; - } - this.myPart.cleanup(); - } + private static class NullStorage extends CableBusStorage { + @Override + public IFacadePart getFacade(final int x) { + return null; + } - @Override - public void notifyNeighbors() - { - if( this.myPart == null ) - { - return; - } - this.myPart.notifyNeighbors(); - } - - @Override - public boolean isInWorld() - { - if( this.myPart == null ) - { - return this.myMP.getWorldObj() != null; - } - return this.myPart.isInWorld(); - } - - private static class NullStorage extends CableBusStorage - { - - @Override - public IFacadePart getFacade( final int x ) - { - return null; - } - - @Override - public void setFacade( final int x, final IFacadePart facade ) - { - - } - } + @Override + public void setFacade(final int x, final IFacadePart facade) {} + } } diff --git a/src/main/java/appeng/fmp/PartRegistry.java b/src/main/java/appeng/fmp/PartRegistry.java index 5ecdd1c8..ee04f68e 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 javax.annotation.Nullable; import appeng.block.AEBaseBlock; import appeng.block.misc.BlockQuartzTorch; @@ -26,59 +27,49 @@ import appeng.core.Api; import codechicken.multipart.TMultiPart; import net.minecraft.block.Block; -import javax.annotation.Nullable; +public enum PartRegistry { + QuartzTorchPart("ae2_torch", BlockQuartzTorch.class, QuartzTorchPart.class), + CableBusPart("ae2_cablebus", BlockCableBus.class, CableBusPart.class); + private final String name; + private final Class blk; + private final Class part; -public enum PartRegistry -{ - QuartzTorchPart( "ae2_torch", BlockQuartzTorch.class, QuartzTorchPart.class ), - CableBusPart( "ae2_cablebus", BlockCableBus.class, CableBusPart.class ); + PartRegistry( + final String name, + final Class blk, + final Class part + ) { + this.name = name; + this.blk = blk; + this.part = part; + } - private final String name; - private final Class blk; - private final Class part; + @Nullable + public static TMultiPart getPartByBlock(final Block block, final int meta) { + for (final PartRegistry pr : values()) { + if (pr.blk.isInstance(block)) { + return pr.construct(meta); + } + } + return null; + } - PartRegistry( final String name, final Class blk, final Class part ) - { - this.name = name; - this.blk = blk; - this.part = part; - } + public TMultiPart construct(final int meta) { + try { + if (this == CableBusPart) { + return (TMultiPart) Api.INSTANCE.partHelper() + .getCombinedInstance(this.part.getName()) + .newInstance(); + } else { + return this.part.getConstructor(int.class).newInstance(meta); + } + } catch (final Throwable t) { + throw new IllegalStateException(t); + } + } - @Nullable - public static TMultiPart getPartByBlock( final Block block, final int meta ) - { - for( final PartRegistry pr : values() ) - { - if( pr.blk.isInstance( block ) ) - { - return pr.construct( meta ); - } - } - return null; - } - - public TMultiPart construct( final int meta ) - { - try - { - if( this == CableBusPart ) - { - return (TMultiPart) Api.INSTANCE.partHelper().getCombinedInstance( this.part.getName() ).newInstance(); - } - else - { - return this.part.getConstructor( int.class ).newInstance( meta ); - } - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } - } - - public String getName() - { - return this.name; - } + 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 2d021980..16e531f8 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 appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; @@ -30,80 +31,71 @@ import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Random; +public class QuartzTorchPart extends McSidedMetaPart implements IRandomDisplayTick { + public QuartzTorchPart() { + this(ForgeDirection.DOWN.ordinal()); + } + public QuartzTorchPart(final int meta) { + super(meta); + } -public class QuartzTorchPart extends McSidedMetaPart implements IRandomDisplayTick -{ + public static McBlockPart + placement(final World world, BlockCoord pos, final int side) { + pos = pos.copy().offset(side); + if (!world.isSideSolid( + pos.x, pos.y, pos.z, ForgeDirection.getOrientation(side) + )) { + return null; + } - public QuartzTorchPart() - { - this( ForgeDirection.DOWN.ordinal() ); - } + return new QuartzTorchPart(side); + } - public QuartzTorchPart( final int meta ) - { - super( meta ); - } + @Override + public boolean doesTick() { + return false; + } - public static McBlockPart placement( final World world, BlockCoord pos, final int side ) - { - pos = pos.copy().offset( side ); - if( !world.isSideSolid( pos.x, pos.y, pos.z, ForgeDirection.getOrientation( side ) ) ) - { - return null; - } + @Override + public String getType() { + return PartRegistry.QuartzTorchPart.getName(); + } - return new QuartzTorchPart( side ); - } + @Override + public Cuboid6 getBounds() { + return this.getBounds(this.meta); + } - @Override - public boolean doesTick() - { - return false; - } + private Cuboid6 getBounds(final int meta) { + final ForgeDirection up = ForgeDirection.getOrientation(meta); + final double xOff = -0.3 * up.offsetX; + final double yOff = -0.3 * up.offsetY; + final double zOff = -0.3 * up.offsetZ; + return new Cuboid6( + xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 + ); + } - @Override - public String getType() - { - return PartRegistry.QuartzTorchPart.getName(); - } + @Override + public int sideForMeta(final int meta) { + return ForgeDirection.getOrientation(meta).getOpposite().ordinal(); + } - @Override - public Cuboid6 getBounds() - { - return this.getBounds( this.meta ); - } + @Override + public void randomDisplayTick(final Random r) { + this.getBlock().randomDisplayTick(this.world(), this.x(), this.y(), this.z(), r); + } - private Cuboid6 getBounds( final int meta ) - { - final ForgeDirection up = ForgeDirection.getOrientation( meta ); - final double xOff = -0.3 * up.offsetX; - final double yOff = -0.3 * up.offsetY; - final double zOff = -0.3 * up.offsetZ; - return new Cuboid6( xOff + 0.3, yOff + 0.3, zOff + 0.3, xOff + 0.7, yOff + 0.7, zOff + 0.7 ); - } + @Override + public Block getBlock() { + for (final Block torchBlock : + AEApi.instance().definitions().blocks().quartzTorch().maybeBlock().asSet()) { + return torchBlock; + } - @Override - public int sideForMeta( final int meta ) - { - return ForgeDirection.getOrientation( meta ).getOpposite().ordinal(); - } - - @Override - public void randomDisplayTick( final Random r ) - { - this.getBlock().randomDisplayTick( this.world(), this.x(), this.y(), this.z(), r ); - } - - @Override - public Block getBlock() - { - for( final 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." ); - } + 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 478883b4..0f03df7d 100644 --- a/src/main/java/appeng/helpers/AEGlassMaterial.java +++ b/src/main/java/appeng/helpers/AEGlassMaterial.java @@ -18,24 +18,19 @@ package appeng.helpers; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; +public class AEGlassMaterial extends Material { + public static final AEGlassMaterial INSTANCE + = (new AEGlassMaterial(MapColor.airColor)); -public class AEGlassMaterial extends Material -{ + public AEGlassMaterial(final MapColor color) { + super(color); + } - public static final AEGlassMaterial INSTANCE = ( new AEGlassMaterial( MapColor.airColor ) ); - - public AEGlassMaterial( final MapColor color ) - { - super( color ); - } - - @Override - public boolean isOpaque() - { - return false; - } + @Override + public boolean isOpaque() { + return false; + } } diff --git a/src/main/java/appeng/helpers/AEMultiTile.java b/src/main/java/appeng/helpers/AEMultiTile.java index de816532..b27bbc42 100644 --- a/src/main/java/appeng/helpers/AEMultiTile.java +++ b/src/main/java/appeng/helpers/AEMultiTile.java @@ -18,13 +18,8 @@ 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 -{ - -} +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 02ae0b16..99a947cd 100644 --- a/src/main/java/appeng/helpers/DualityInterface.java +++ b/src/main/java/appeng/helpers/DualityInterface.java @@ -18,6 +18,7 @@ package appeng.helpers; +import java.util.*; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -87,1213 +88,1082 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.*; - - -public class DualityInterface - implements IGridTickable, IStorageMonitorable, IInventoryDestination, IAEAppEngInventory, IConfigManagerHost, ICraftingProvider, IUpgradeableHost, IPriorityHost -{ - - public static final int NUMBER_OF_STORAGE_SLOTS = 9; - public static final int NUMBER_OF_CONFIG_SLOTS = 9; - public static final int NUMBER_OF_PATTERN_SLOTS = 9; - - private static final Collection BAD_BLOCKS = new HashSet( 100 ); - private final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; - private final IAEItemStack[] requireWork = { null, null, null, null, null, null, null, null, null }; - private final MultiCraftingTracker craftingTracker; - private final AENetworkProxy gridProxy; - private final IInterfaceHost iHost; - private final BaseActionSource mySource; - private final BaseActionSource interfaceRequestSource; - private final ConfigManager cm = new ConfigManager( this ); - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, NUMBER_OF_CONFIG_SLOTS ); - private final AppEngInternalInventory storage = new AppEngInternalInventory( this, NUMBER_OF_STORAGE_SLOTS ); - private final AppEngInternalInventory patterns = new AppEngInternalInventory( this, NUMBER_OF_PATTERN_SLOTS ); - private final WrapperInvSlot slotInv = new WrapperInvSlot( this.storage ); - private final MEMonitorPassThrough items = new MEMonitorPassThrough( new NullInventory(), StorageChannel.ITEMS ); - private final MEMonitorPassThrough fluids = new MEMonitorPassThrough( new NullInventory(), StorageChannel.FLUIDS ); - private final UpgradeInventory upgrades; - private boolean hasConfig = false; - private int priority; - private List craftingList = null; - private List waitingToSend = null; - private IMEInventory destination; - private boolean isWorking = false; - - public DualityInterface( final AENetworkProxy networkProxy, final IInterfaceHost ih ) - { - this.gridProxy = networkProxy; - this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL ); - - this.upgrades = new StackUpgradeInventory( this.gridProxy.getMachineRepresentation(), this, 1 ); - this.cm.registerSetting( Settings.BLOCK, YesNo.NO ); - this.cm.registerSetting( Settings.INTERFACE_TERMINAL, YesNo.YES ); - - this.iHost = ih; - this.craftingTracker = new MultiCraftingTracker( this.iHost, 9 ); - - final MachineSource actionSource = new MachineSource( this.iHost ); - this.mySource = actionSource; - this.fluids.setChangeSource( actionSource ); - this.items.setChangeSource( actionSource ); - - this.interfaceRequestSource = new InterfaceRequestSource( this.iHost ); - } - - @Override - public void saveChanges() - { - this.iHost.saveChanges(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - 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 ) - { - final boolean had = this.hasWorkToDo(); - - this.updatePlan( slot ); - - final 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( final GridAccessException e ) - { - // :P - } - } - } - } - - public void writeToNBT( final NBTTagCompound data ) - { - this.config.writeToNBT( data, "config" ); - this.patterns.writeToNBT( data, "patterns" ); - this.storage.writeToNBT( data, "storage" ); - this.upgrades.writeToNBT( data, "upgrades" ); - this.cm.writeToNBT( data ); - this.craftingTracker.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - - final NBTTagList waitingToSend = new NBTTagList(); - if( this.waitingToSend != null ) - { - for( final ItemStack is : this.waitingToSend ) - { - final NBTTagCompound item = new NBTTagCompound(); - is.writeToNBT( item ); - waitingToSend.appendTag( item ); - } - } - data.setTag( "waitingToSend", waitingToSend ); - } - - public void readFromNBT( final NBTTagCompound data ) - { - this.waitingToSend = null; - final NBTTagList waitingList = data.getTagList( "waitingToSend", 10 ); - if( waitingList != null ) - { - for( int x = 0; x < waitingList.tagCount(); x++ ) - { - final NBTTagCompound c = waitingList.getCompoundTagAt( x ); - if( c != null ) - { - final ItemStack is = ItemStack.loadItemStackFromNBT( c ); - this.addToSendList( is ); - } - } - } - - this.craftingTracker.readFromNBT( data ); - this.upgrades.readFromNBT( data, "upgrades" ); - this.config.readFromNBT( data, "config" ); - this.patterns.readFromNBT( data, "patterns" ); - this.storage.readFromNBT( data, "storage" ); - this.priority = data.getInteger( "priority" ); - this.cm.readFromNBT( data ); - this.readConfig(); - this.updateCraftingList(); - } - - private void addToSendList( final 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( final GridAccessException e ) - { - // :P - } - } - - private void readConfig() - { - this.hasConfig = false; - - for( final ItemStack p : this.config ) - { - if( p != null ) - { - this.hasConfig = true; - break; - } - } - - final boolean had = this.hasWorkToDo(); - - for( int x = 0; x < NUMBER_OF_CONFIG_SLOTS; x++ ) - { - this.updatePlan( x ); - } - - final 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( final GridAccessException e ) - { - // :P - } - } - - this.notifyNeighbors(); - } - - private void updateCraftingList() - { - final Boolean[] accountedFor = { 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 ) - { - final Iterator i = this.craftingList.iterator(); - while( i.hasNext() ) - { - final ICraftingPatternDetails details = i.next(); - boolean found = false; - - for( int x = 0; x < accountedFor.length; x++ ) - { - final 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( final GridAccessException e ) - { - // :P - } - } - - private boolean hasWorkToDo() - { - if( this.hasItemsToSend() ) - { - return true; - } - else - { - for( final IAEItemStack requiredWork : this.requireWork ) - { - if( requiredWork != null ) - { - return true; - } - } - - return false; - } - } - - private void updatePlan( final int slot ) - { - IAEItemStack req = this.config.getAEStackInSlot( slot ); - if( req != null && req.getStackSize() <= 0 ) - { - this.config.setInventorySlotContents( slot, null ); - req = null; - } - - final ItemStack Stored = this.storage.getStackInSlot( slot ); - - if( req == null && Stored != null ) - { - final IAEItemStack work = AEApi.instance().storage().createItemStack( Stored ); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - else if( req != null ) - { - if( Stored == null ) // need to add stuff! - { - this.requireWork[slot] = req.copy(); - return; - } - else if( req.isSameType( Stored ) ) // same type ( qty different? )! - { - if( req.getStackSize() != Stored.stackSize ) - { - this.requireWork[slot] = req.copy(); - this.requireWork[slot].setStackSize( req.getStackSize() - Stored.stackSize ); - return; - } - } - else - // Stored != null; dispose! - { - final IAEItemStack work = AEApi.instance().storage().createItemStack( Stored ); - this.requireWork[slot] = work.setStackSize( -work.getStackSize() ); - return; - } - } - - // else - - this.requireWork[slot] = null; - } - - 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( final GridAccessException e ) - { - // :P - } - } - - final TileEntity te = this.iHost.getTileEntity(); - if( te != null && te.getWorldObj() != null ) - { - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - } - } - - private void addToCraftingList( final ItemStack is ) - { - if( is == null ) - { - return; - } - - if( is.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); - final ICraftingPatternDetails details = cpi.getPatternForItem( is, this.iHost.getTileEntity().getWorldObj() ); - - if( details != null ) - { - if( this.craftingList == null ) - { - this.craftingList = new LinkedList(); - } - - this.craftingList.add( details ); - } - } - } - - private boolean hasItemsToSend() - { - return this.waitingToSend != null && !this.waitingToSend.isEmpty(); - } - - @Override - public boolean canInsert( final ItemStack stack ) - { - final 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() - { - return this.config; - } - - public IInventory getPatterns() - { - return this.patterns; - } - - public void gridChanged() - { - try - { - this.items.setInternal( this.gridProxy.getStorage().getItemInventory() ); - this.fluids.setInternal( this.gridProxy.getStorage().getFluidInventory() ); - } - catch( final GridAccessException gae ) - { - this.items.setInternal( new NullInventory() ); - this.fluids.setInternal( new NullInventory() ); - } - - this.notifyNeighbors(); - } - - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this.iHost.getTileEntity() ); - } - - public IInventory getInternalInventory() - { - return this.storage; - } - - public void markDirty() - { - for( int slot = 0; slot < this.storage.getSizeInventory(); slot++ ) - { - this.onChangeInventory( this.storage, slot, InvOperation.markDirty, null, null ); - } - } - - public int[] getAccessibleSlotsFromSide( final int side ) - { - return this.sides; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.Interface.getMin(), TickRates.Interface.getMax(), !this.hasWorkToDo(), true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( !this.gridProxy.isActive() ) - { - return TickRateModulation.SLEEP; - } - - if( this.hasItemsToSend() ) - { - this.pushItemsOut( this.iHost.getTargets() ); - } - - final boolean couldDoWork = this.updateStorage(); - return this.hasWorkToDo() ? ( couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER ) : TickRateModulation.SLEEP; - } - - private void pushItemsOut( final EnumSet possibleDirections ) - { - if( !this.hasItemsToSend() ) - { - return; - } - - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorldObj(); - - final Iterator i = this.waitingToSend.iterator(); - while( i.hasNext() ) - { - ItemStack whatToSend = i.next(); - - for( final ForgeDirection s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if( te == null ) - { - continue; - } - - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if( ad != null ) - { - final 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 < NUMBER_OF_STORAGE_SLOTS; x++ ) - { - if( this.requireWork[x] != null ) - { - didSomething = this.usePlan( x, this.requireWork[x] ) || didSomething; - } - } - - return didSomething; - } - - private boolean usePlan( final int x, final IAEItemStack itemStack ) - { - final InventoryAdaptor adaptor = this.getAdaptor( x ); - this.isWorking = true; - - boolean changed = false; - try - { - this.destination = this.gridProxy.getStorage().getItemInventory(); - final 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(); - } - - final IAEItemStack acquired = Platform.poweredExtraction( src, this.destination, itemStack, this.interfaceRequestSource ); - if( acquired != null ) - { - changed = true; - final ItemStack issue = adaptor.addItems( acquired.getItemStack() ); - if( issue != null ) - { - throw new IllegalStateException( "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... - final 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.interfaceRequestSource ); - - if( toStore != null ) - { - diff -= toStore.getStackSize(); - } - - if( diff != 0 ) - { - // extract items! - changed = true; - final ItemStack removed = adaptor.removeItems( (int) diff, null, null ); - if( removed == null ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( removeItems )" ); - } - else if( removed.stackSize != diff ) - { - throw new IllegalStateException( "bad attempt at managing inventory. ( removeItems )" ); - } - } - } - // else wtf? - } - catch( final GridAccessException e ) - { - // :P - } - - if( changed ) - { - this.updatePlan( x ); - } - - this.isWorking = false; - return changed; - } - - private InventoryAdaptor getAdaptor( final int slot ) - { - return new AdaptorIInventory( this.slotInv.getWrapper( slot ) ); - } - - private boolean handleCrafting( final int x, final InventoryAdaptor d, final 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.mySource ); - } - } - catch( final GridAccessException e ) - { - // :P - } - - return false; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - if( this.upgrades == null ) - { - return 0; - } - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public TileEntity getTile() - { - return (TileEntity) ( this.iHost instanceof TileEntity ? this.iHost : null ); - } - - @Override - public IMEMonitor getItemInventory() - { - if( this.hasConfig() ) - { - return new InterfaceInventory( this ); - } - - return this.items; - } - - private boolean hasConfig() - { - return this.hasConfig; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "storage" ) ) - { - return this.storage; - } - - if( name.equals( "patterns" ) ) - { - return this.patterns; - } - - if( name.equals( "config" ) ) - { - return this.config; - } - - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - public IInventory getStorage() - { - return this.storage; - } - - @Override - public appeng.api.util.IConfigManager getConfigManager() - { - return this.cm; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - 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() - { - this.craftingTracker.cancel(); - } - - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src, final IStorageMonitorable myInterface ) - { - if( Platform.canAccess( this.gridProxy, src ) ) - { - return myInterface; - } - - final DualityInterface di = this; - - return new IStorageMonitorable() - { - - @Override - public IMEMonitor getItemInventory() - { - return new InterfaceInventory( di ); - } - - @Override - public IMEMonitor getFluidInventory() - { - return null; - } - }; - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - if( this.hasItemsToSend() || !this.gridProxy.isActive() || !this.craftingList.contains( patternDetails ) ) - { - return false; - } - - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorldObj(); - - final EnumSet possibleDirections = this.iHost.getTargets(); - for( final ForgeDirection s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - if( te instanceof IInterfaceHost ) - { - try - { - if( ( (IInterfaceHost) te ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - continue; - } - } - catch( final GridAccessException e ) - { - continue; - } - } - - if( te instanceof ICraftingMachine ) - { - final ICraftingMachine cm = (ICraftingMachine) te; - if( cm.acceptsPlans() ) - { - if( cm.pushPattern( patternDetails, table, s.getOpposite() ) ) - { - return true; - } - continue; - } - } - - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); - if( ad != null ) - { - if( this.isBlocking() ) - { - if( ad.simulateRemove( 1, null, null ) != null ) - { - continue; - } - } - - if( this.acceptsItems( ad, table ) ) - { - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( is != null ) - { - final ItemStack added = ad.addItems( is ); - this.addToSendList( added ); - } - } - this.pushItemsOut( possibleDirections ); - return true; - } - } - } - - return false; - } - - @Override - public boolean isBusy() - { - if( this.hasItemsToSend() ) - { - return true; - } - - boolean busy = false; - - if( this.isBlocking() ) - { - final EnumSet possibleDirections = this.iHost.getTargets(); - final TileEntity tile = this.iHost.getTileEntity(); - final World w = tile.getWorldObj(); - - boolean allAreBusy = true; - - for( final ForgeDirection s : possibleDirections ) - { - final TileEntity te = w.getTileEntity( tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ ); - - final 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( final IGrid grid ) throws GridAccessException - { - return grid == this.gridProxy.getGrid(); - } - - private boolean isBlocking() - { - return this.cm.getSetting( Settings.BLOCK ) == YesNo.YES; - } - - private boolean acceptsItems( final InventoryAdaptor ad, final InventoryCrafting table ) - { - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - final ItemStack is = table.getStackInSlot( x ); - if( is == null ) - { - continue; - } - - if( ad.simulateAdd( is.copy() ) != null ) - { - return false; - } - } - - return true; - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - if( this.gridProxy.isActive() && this.craftingList != null ) - { - for( final ICraftingPatternDetails details : this.craftingList ) - { - details.setPriority( this.priority ); - craftingTracker.addCraftingOption( this, details ); - } - } - } - - public void addDrops( final List drops ) - { - if( this.waitingToSend != null ) - { - for( final ItemStack is : this.waitingToSend ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - for( final ItemStack is : this.upgrades ) - { - if( is != null ) - { - drops.add( is ); - } - } - - for( final ItemStack is : this.storage ) - { - if( is != null ) - { - drops.add( is ); - } - } - - for( final ItemStack is : this.patterns ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - public IUpgradeableHost getHost() - { - if( this.getPart() instanceof IUpgradeableHost ) - { - return (IUpgradeableHost) this.getPart(); - } - if( this.getTile() instanceof IUpgradeableHost ) - { - return (IUpgradeableHost) this.getTile(); - } - return null; - } - - private IPart getPart() - { - return (IPart) ( this.iHost instanceof IPart ? this.iHost : null ); - } - - public ImmutableSet getRequestedJobs() - { - return this.craftingTracker.getRequestedJobs(); - } - - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack acquired, final Actionable mode ) - { - final int slot = this.craftingTracker.getSlot( link ); - - if( acquired != null && slot >= 0 && slot <= this.requireWork.length ) - { - final InventoryAdaptor adaptor = this.getAdaptor( slot ); - - if( mode == Actionable.SIMULATE ) - { - return AEItemStack.create( adaptor.simulateAdd( acquired.getItemStack() ) ); - } - else - { - final IAEItemStack is = AEItemStack.create( adaptor.addItems( acquired.getItemStack() ) ); - this.updatePlan( slot ); - return is; - } - } - - return acquired; - } - - public void jobStateChange( final ICraftingLink link ) - { - this.craftingTracker.jobStateChange( link ); - } - - public String getTermName() - { - final TileEntity hostTile = this.iHost.getTileEntity(); - final World hostWorld = hostTile.getWorldObj(); - - if( ( (ICustomNameObject) this.iHost ).hasCustomName() ) - { - return ( (ICustomNameObject) this.iHost ).getCustomName(); - } - - final EnumSet possibleDirections = this.iHost.getTargets(); - for( final ForgeDirection direction : possibleDirections ) - { - final int xPos = hostTile.xCoord + direction.offsetX; - final int yPos = hostTile.yCoord + direction.offsetY; - final int zPos = hostTile.zCoord + direction.offsetZ; - final TileEntity directedTile = hostWorld.getTileEntity( xPos, yPos, zPos ); - - if( directedTile == null ) - { - continue; - } - - if( directedTile instanceof IInterfaceHost ) - { - try - { - if( ( (IInterfaceHost) directedTile ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) - { - continue; - } - } - catch( final GridAccessException e ) - { - continue; - } - } - - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( directedTile, direction.getOpposite() ); - if( directedTile instanceof ICraftingMachine || adaptor != null ) - { - if( directedTile instanceof IInventory && ( (IInventory) directedTile ).getSizeInventory() == 0 ) - { - continue; - } - - if( directedTile instanceof ISidedInventory ) - { - final int[] sides = ( (ISidedInventory) directedTile ).getAccessibleSlotsFromSide( direction.getOpposite().ordinal() ); - - if( sides == null || sides.length == 0 ) - { - continue; - } - } - - final Block directedBlock = hostWorld.getBlock( xPos, yPos, zPos ); - ItemStack what = new ItemStack( directedBlock, 1, directedBlock.getDamageValue( hostWorld, xPos, yPos, zPos ) ); - try - { - Vec3 from = Vec3.createVectorHelper( hostTile.xCoord + 0.5, hostTile.yCoord + 0.5, hostTile.zCoord + 0.5 ); - from = from.addVector( direction.offsetX * 0.501, direction.offsetY * 0.501, direction.offsetZ * 0.501 ); - final Vec3 to = from.addVector( direction.offsetX, direction.offsetY, direction.offsetZ ); - final MovingObjectPosition mop = hostWorld.rayTraceBlocks( from, to, true ); - if( mop != null && !BAD_BLOCKS.contains( directedBlock ) ) - { - if( mop.blockX == directedTile.xCoord && mop.blockY == directedTile.yCoord && mop.blockZ == directedTile.zCoord ) - { - final ItemStack g = directedBlock.getPickBlock( mop, hostWorld, directedTile.xCoord, directedTile.yCoord, directedTile.zCoord, null ); - if( g != null ) - { - what = g; - } - } - } - } - catch( final Throwable t ) - { - BAD_BLOCKS.add( directedBlock ); // nope! - } - - if( what.getItem() != null ) - { - return what.getUnlocalizedName(); - } - - final Item item = Item.getItemFromBlock( directedBlock ); - if( item == null ) - { - return directedBlock.getUnlocalizedName(); - } - } - } - - return "Nothing"; - } - - public long getSortValue() - { - final TileEntity te = this.iHost.getTileEntity(); - return ( te.zCoord << 24 ) ^ ( te.xCoord << 8 ) ^ te.yCoord; - } - - public void initialize() - { - this.updateCraftingList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.markDirty(); - - try - { - this.gridProxy.getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.gridProxy.getNode() ) ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - private class InterfaceRequestSource extends MachineSource - { - - public InterfaceRequestSource( final IActionHost v ) - { - super( v ); - } - } - - - private class InterfaceInventory extends MEMonitorIInventory - { - - public InterfaceInventory( final DualityInterface tileInterface ) - { - super( new AdaptorIInventory( tileInterface.storage ) ); - this.setActionSource( new MachineSource( DualityInterface.this.iHost ) ); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( src instanceof InterfaceRequestSource ) - { - return input; - } - - return super.injectItems( input, type, src ); - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable type, final BaseActionSource src ) - { - if( src instanceof InterfaceRequestSource ) - { - return null; - } - - return super.extractItems( request, type, src ); - } - } +public class DualityInterface implements IGridTickable, IStorageMonitorable, + IInventoryDestination, IAEAppEngInventory, + IConfigManagerHost, ICraftingProvider, + IUpgradeableHost, IPriorityHost { + public static final int NUMBER_OF_STORAGE_SLOTS = 9; + public static final int NUMBER_OF_CONFIG_SLOTS = 9; + public static final int NUMBER_OF_PATTERN_SLOTS = 9; + + private static final Collection BAD_BLOCKS = new HashSet(100); + private final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; + private final IAEItemStack[] requireWork + = { null, null, null, null, null, null, null, null, null }; + private final MultiCraftingTracker craftingTracker; + private final AENetworkProxy gridProxy; + private final IInterfaceHost iHost; + private final BaseActionSource mySource; + private final BaseActionSource interfaceRequestSource; + private final ConfigManager cm = new ConfigManager(this); + private final AppEngInternalAEInventory config + = new AppEngInternalAEInventory(this, NUMBER_OF_CONFIG_SLOTS); + private final AppEngInternalInventory storage + = new AppEngInternalInventory(this, NUMBER_OF_STORAGE_SLOTS); + private final AppEngInternalInventory patterns + = new AppEngInternalInventory(this, NUMBER_OF_PATTERN_SLOTS); + private final WrapperInvSlot slotInv = new WrapperInvSlot(this.storage); + private final MEMonitorPassThrough items + = new MEMonitorPassThrough( + new NullInventory(), StorageChannel.ITEMS + ); + private final MEMonitorPassThrough fluids + = new MEMonitorPassThrough( + new NullInventory(), StorageChannel.FLUIDS + ); + private final UpgradeInventory upgrades; + private boolean hasConfig = false; + private int priority; + private List craftingList = null; + private List waitingToSend = null; + private IMEInventory destination; + private boolean isWorking = false; + + public DualityInterface(final AENetworkProxy networkProxy, final IInterfaceHost ih) { + this.gridProxy = networkProxy; + this.gridProxy.setFlags(GridFlags.REQUIRE_CHANNEL); + + this.upgrades = new StackUpgradeInventory( + this.gridProxy.getMachineRepresentation(), this, 1 + ); + this.cm.registerSetting(Settings.BLOCK, YesNo.NO); + this.cm.registerSetting(Settings.INTERFACE_TERMINAL, YesNo.YES); + + this.iHost = ih; + this.craftingTracker = new MultiCraftingTracker(this.iHost, 9); + + final MachineSource actionSource = new MachineSource(this.iHost); + this.mySource = actionSource; + this.fluids.setChangeSource(actionSource); + this.items.setChangeSource(actionSource); + + this.interfaceRequestSource = new InterfaceRequestSource(this.iHost); + } + + @Override + public void saveChanges() { + this.iHost.saveChanges(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + 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) { + final boolean had = this.hasWorkToDo(); + + this.updatePlan(slot); + + final 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 (final GridAccessException e) { + // :P + } + } + } + } + + public void writeToNBT(final NBTTagCompound data) { + this.config.writeToNBT(data, "config"); + this.patterns.writeToNBT(data, "patterns"); + this.storage.writeToNBT(data, "storage"); + this.upgrades.writeToNBT(data, "upgrades"); + this.cm.writeToNBT(data); + this.craftingTracker.writeToNBT(data); + data.setInteger("priority", this.priority); + + final NBTTagList waitingToSend = new NBTTagList(); + if (this.waitingToSend != null) { + for (final ItemStack is : this.waitingToSend) { + final NBTTagCompound item = new NBTTagCompound(); + is.writeToNBT(item); + waitingToSend.appendTag(item); + } + } + data.setTag("waitingToSend", waitingToSend); + } + + public void readFromNBT(final NBTTagCompound data) { + this.waitingToSend = null; + final NBTTagList waitingList = data.getTagList("waitingToSend", 10); + if (waitingList != null) { + for (int x = 0; x < waitingList.tagCount(); x++) { + final NBTTagCompound c = waitingList.getCompoundTagAt(x); + if (c != null) { + final ItemStack is = ItemStack.loadItemStackFromNBT(c); + this.addToSendList(is); + } + } + } + + this.craftingTracker.readFromNBT(data); + this.upgrades.readFromNBT(data, "upgrades"); + this.config.readFromNBT(data, "config"); + this.patterns.readFromNBT(data, "patterns"); + this.storage.readFromNBT(data, "storage"); + this.priority = data.getInteger("priority"); + this.cm.readFromNBT(data); + this.readConfig(); + this.updateCraftingList(); + } + + private void addToSendList(final 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 (final GridAccessException e) { + // :P + } + } + + private void readConfig() { + this.hasConfig = false; + + for (final ItemStack p : this.config) { + if (p != null) { + this.hasConfig = true; + break; + } + } + + final boolean had = this.hasWorkToDo(); + + for (int x = 0; x < NUMBER_OF_CONFIG_SLOTS; x++) { + this.updatePlan(x); + } + + final 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 (final GridAccessException e) { + // :P + } + } + + this.notifyNeighbors(); + } + + private void updateCraftingList() { + final Boolean[] accountedFor + = { 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) { + final Iterator i = this.craftingList.iterator(); + while (i.hasNext()) { + final ICraftingPatternDetails details = i.next(); + boolean found = false; + + for (int x = 0; x < accountedFor.length; x++) { + final 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 (final GridAccessException e) { + // :P + } + } + + private boolean hasWorkToDo() { + if (this.hasItemsToSend()) { + return true; + } else { + for (final IAEItemStack requiredWork : this.requireWork) { + if (requiredWork != null) { + return true; + } + } + + return false; + } + } + + private void updatePlan(final int slot) { + IAEItemStack req = this.config.getAEStackInSlot(slot); + if (req != null && req.getStackSize() <= 0) { + this.config.setInventorySlotContents(slot, null); + req = null; + } + + final ItemStack Stored = this.storage.getStackInSlot(slot); + + if (req == null && Stored != null) { + final IAEItemStack work = AEApi.instance().storage().createItemStack(Stored); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } else if (req != null) { + if (Stored == null) // need to add stuff! + { + this.requireWork[slot] = req.copy(); + return; + } else if (req.isSameType(Stored)) // same type ( qty different? )! + { + if (req.getStackSize() != Stored.stackSize) { + this.requireWork[slot] = req.copy(); + this.requireWork[slot].setStackSize( + req.getStackSize() - Stored.stackSize + ); + return; + } + } else + // Stored != null; dispose! + { + final IAEItemStack work + = AEApi.instance().storage().createItemStack(Stored); + this.requireWork[slot] = work.setStackSize(-work.getStackSize()); + return; + } + } + + // else + + this.requireWork[slot] = null; + } + + 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 (final GridAccessException e) { + // :P + } + } + + final TileEntity te = this.iHost.getTileEntity(); + if (te != null && te.getWorldObj() != null) { + Platform.notifyBlocksOfNeighbors( + te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord + ); + } + } + + private void addToCraftingList(final ItemStack is) { + if (is == null) { + return; + } + + if (is.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem cpi = (ICraftingPatternItem) is.getItem(); + final ICraftingPatternDetails details + = cpi.getPatternForItem(is, this.iHost.getTileEntity().getWorldObj()); + + if (details != null) { + if (this.craftingList == null) { + this.craftingList = new LinkedList(); + } + + this.craftingList.add(details); + } + } + } + + private boolean hasItemsToSend() { + return this.waitingToSend != null && !this.waitingToSend.isEmpty(); + } + + @Override + public boolean canInsert(final ItemStack stack) { + final 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() { + return this.config; + } + + public IInventory getPatterns() { + return this.patterns; + } + + public void gridChanged() { + try { + this.items.setInternal(this.gridProxy.getStorage().getItemInventory()); + this.fluids.setInternal(this.gridProxy.getStorage().getFluidInventory()); + } catch (final GridAccessException gae) { + this.items.setInternal(new NullInventory()); + this.fluids.setInternal(new NullInventory()); + } + + this.notifyNeighbors(); + } + + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + public DimensionalCoord getLocation() { + return new DimensionalCoord(this.iHost.getTileEntity()); + } + + public IInventory getInternalInventory() { + return this.storage; + } + + public void markDirty() { + for (int slot = 0; slot < this.storage.getSizeInventory(); slot++) { + this.onChangeInventory( + this.storage, slot, InvOperation.markDirty, null, null + ); + } + } + + public int[] getAccessibleSlotsFromSide(final int side) { + return this.sides; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.Interface.getMin(), + TickRates.Interface.getMax(), + !this.hasWorkToDo(), + true + ); + } + + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (!this.gridProxy.isActive()) { + return TickRateModulation.SLEEP; + } + + if (this.hasItemsToSend()) { + this.pushItemsOut(this.iHost.getTargets()); + } + + final boolean couldDoWork = this.updateStorage(); + return this.hasWorkToDo() + ? (couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER) + : TickRateModulation.SLEEP; + } + + private void pushItemsOut(final EnumSet possibleDirections) { + if (!this.hasItemsToSend()) { + return; + } + + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorldObj(); + + final Iterator i = this.waitingToSend.iterator(); + while (i.hasNext()) { + ItemStack whatToSend = i.next(); + + for (final ForgeDirection s : possibleDirections) { + final TileEntity te = w.getTileEntity( + tile.xCoord + s.offsetX, + tile.yCoord + s.offsetY, + tile.zCoord + s.offsetZ + ); + if (te == null) { + continue; + } + + final InventoryAdaptor ad + = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + if (ad != null) { + final 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 < NUMBER_OF_STORAGE_SLOTS; x++) { + if (this.requireWork[x] != null) { + didSomething = this.usePlan(x, this.requireWork[x]) || didSomething; + } + } + + return didSomething; + } + + private boolean usePlan(final int x, final IAEItemStack itemStack) { + final InventoryAdaptor adaptor = this.getAdaptor(x); + this.isWorking = true; + + boolean changed = false; + try { + this.destination = this.gridProxy.getStorage().getItemInventory(); + final 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(); + } + + final IAEItemStack acquired = Platform.poweredExtraction( + src, this.destination, itemStack, this.interfaceRequestSource + ); + if (acquired != null) { + changed = true; + final ItemStack issue = adaptor.addItems(acquired.getItemStack()); + if (issue != null) { + throw new IllegalStateException( + "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... + final 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.interfaceRequestSource + ); + + if (toStore != null) { + diff -= toStore.getStackSize(); + } + + if (diff != 0) { + // extract items! + changed = true; + final ItemStack removed = adaptor.removeItems((int) diff, null, null); + if (removed == null) { + throw new IllegalStateException( + "bad attempt at managing inventory. ( removeItems )" + ); + } else if (removed.stackSize != diff) { + throw new IllegalStateException( + "bad attempt at managing inventory. ( removeItems )" + ); + } + } + } + // else wtf? + } catch (final GridAccessException e) { + // :P + } + + if (changed) { + this.updatePlan(x); + } + + this.isWorking = false; + return changed; + } + + private InventoryAdaptor getAdaptor(final int slot) { + return new AdaptorIInventory(this.slotInv.getWrapper(slot)); + } + + private boolean + handleCrafting(final int x, final InventoryAdaptor d, final 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.mySource + ); + } + } catch (final GridAccessException e) { + // :P + } + + return false; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + if (this.upgrades == null) { + return 0; + } + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + public TileEntity getTile() { + return (TileEntity) (this.iHost instanceof TileEntity ? this.iHost : null); + } + + @Override + public IMEMonitor getItemInventory() { + if (this.hasConfig()) { + return new InterfaceInventory(this); + } + + return this.items; + } + + private boolean hasConfig() { + return this.hasConfig; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("storage")) { + return this.storage; + } + + if (name.equals("patterns")) { + return this.patterns; + } + + if (name.equals("config")) { + return this.config; + } + + if (name.equals("upgrades")) { + return this.upgrades; + } + + return null; + } + + public IInventory getStorage() { + return this.storage; + } + + @Override + public appeng.api.util.IConfigManager getConfigManager() { + return this.cm; + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + 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() { + this.craftingTracker.cancel(); + } + + public IStorageMonitorable getMonitorable( + final ForgeDirection side, + final BaseActionSource src, + final IStorageMonitorable myInterface + ) { + if (Platform.canAccess(this.gridProxy, src)) { + return myInterface; + } + + final DualityInterface di = this; + + return new IStorageMonitorable() { + @Override + public IMEMonitor getItemInventory() { + return new InterfaceInventory(di); + } + + @Override + public IMEMonitor getFluidInventory() { + return null; + } + }; + } + + @Override + public boolean pushPattern( + final ICraftingPatternDetails patternDetails, final InventoryCrafting table + ) { + if (this.hasItemsToSend() || !this.gridProxy.isActive() + || !this.craftingList.contains(patternDetails)) { + return false; + } + + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorldObj(); + + final EnumSet possibleDirections = this.iHost.getTargets(); + for (final ForgeDirection s : possibleDirections) { + final TileEntity te = w.getTileEntity( + tile.xCoord + s.offsetX, tile.yCoord + s.offsetY, tile.zCoord + s.offsetZ + ); + if (te instanceof IInterfaceHost) { + try { + if (((IInterfaceHost) te) + .getInterfaceDuality() + .sameGrid(this.gridProxy.getGrid())) { + continue; + } + } catch (final GridAccessException e) { + continue; + } + } + + if (te instanceof ICraftingMachine) { + final ICraftingMachine cm = (ICraftingMachine) te; + if (cm.acceptsPlans()) { + if (cm.pushPattern(patternDetails, table, s.getOpposite())) { + return true; + } + continue; + } + } + + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor(te, s.getOpposite()); + if (ad != null) { + if (this.isBlocking()) { + if (ad.simulateRemove(1, null, null) != null) { + continue; + } + } + + if (this.acceptsItems(ad, table)) { + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (is != null) { + final ItemStack added = ad.addItems(is); + this.addToSendList(added); + } + } + this.pushItemsOut(possibleDirections); + return true; + } + } + } + + return false; + } + + @Override + public boolean isBusy() { + if (this.hasItemsToSend()) { + return true; + } + + boolean busy = false; + + if (this.isBlocking()) { + final EnumSet possibleDirections = this.iHost.getTargets(); + final TileEntity tile = this.iHost.getTileEntity(); + final World w = tile.getWorldObj(); + + boolean allAreBusy = true; + + for (final ForgeDirection s : possibleDirections) { + final TileEntity te = w.getTileEntity( + tile.xCoord + s.offsetX, + tile.yCoord + s.offsetY, + tile.zCoord + s.offsetZ + ); + + final 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(final IGrid grid) throws GridAccessException { + return grid == this.gridProxy.getGrid(); + } + + private boolean isBlocking() { + return this.cm.getSetting(Settings.BLOCK) == YesNo.YES; + } + + private boolean + acceptsItems(final InventoryAdaptor ad, final InventoryCrafting table) { + for (int x = 0; x < table.getSizeInventory(); x++) { + final ItemStack is = table.getStackInSlot(x); + if (is == null) { + continue; + } + + if (ad.simulateAdd(is.copy()) != null) { + return false; + } + } + + return true; + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + if (this.gridProxy.isActive() && this.craftingList != null) { + for (final ICraftingPatternDetails details : this.craftingList) { + details.setPriority(this.priority); + craftingTracker.addCraftingOption(this, details); + } + } + } + + public void addDrops(final List drops) { + if (this.waitingToSend != null) { + for (final ItemStack is : this.waitingToSend) { + if (is != null) { + drops.add(is); + } + } + } + + for (final ItemStack is : this.upgrades) { + if (is != null) { + drops.add(is); + } + } + + for (final ItemStack is : this.storage) { + if (is != null) { + drops.add(is); + } + } + + for (final ItemStack is : this.patterns) { + if (is != null) { + drops.add(is); + } + } + } + + public IUpgradeableHost getHost() { + if (this.getPart() instanceof IUpgradeableHost) { + return (IUpgradeableHost) this.getPart(); + } + if (this.getTile() instanceof IUpgradeableHost) { + return (IUpgradeableHost) this.getTile(); + } + return null; + } + + private IPart getPart() { + return (IPart) (this.iHost instanceof IPart ? this.iHost : null); + } + + public ImmutableSet getRequestedJobs() { + return this.craftingTracker.getRequestedJobs(); + } + + public IAEItemStack injectCraftedItems( + final ICraftingLink link, final IAEItemStack acquired, final Actionable mode + ) { + final int slot = this.craftingTracker.getSlot(link); + + if (acquired != null && slot >= 0 && slot <= this.requireWork.length) { + final InventoryAdaptor adaptor = this.getAdaptor(slot); + + if (mode == Actionable.SIMULATE) { + return AEItemStack.create(adaptor.simulateAdd(acquired.getItemStack())); + } else { + final IAEItemStack is + = AEItemStack.create(adaptor.addItems(acquired.getItemStack())); + this.updatePlan(slot); + return is; + } + } + + return acquired; + } + + public void jobStateChange(final ICraftingLink link) { + this.craftingTracker.jobStateChange(link); + } + + public String getTermName() { + final TileEntity hostTile = this.iHost.getTileEntity(); + final World hostWorld = hostTile.getWorldObj(); + + if (((ICustomNameObject) this.iHost).hasCustomName()) { + return ((ICustomNameObject) this.iHost).getCustomName(); + } + + final EnumSet possibleDirections = this.iHost.getTargets(); + for (final ForgeDirection direction : possibleDirections) { + final int xPos = hostTile.xCoord + direction.offsetX; + final int yPos = hostTile.yCoord + direction.offsetY; + final int zPos = hostTile.zCoord + direction.offsetZ; + final TileEntity directedTile = hostWorld.getTileEntity(xPos, yPos, zPos); + + if (directedTile == null) { + continue; + } + + if (directedTile instanceof IInterfaceHost) { + try { + if (((IInterfaceHost) directedTile) + .getInterfaceDuality() + .sameGrid(this.gridProxy.getGrid())) { + continue; + } + } catch (final GridAccessException e) { + continue; + } + } + + final InventoryAdaptor adaptor + = InventoryAdaptor.getAdaptor(directedTile, direction.getOpposite()); + if (directedTile instanceof ICraftingMachine || adaptor != null) { + if (directedTile instanceof IInventory + && ((IInventory) directedTile).getSizeInventory() == 0) { + continue; + } + + if (directedTile instanceof ISidedInventory) { + final int[] sides = ((ISidedInventory) directedTile) + .getAccessibleSlotsFromSide( + direction.getOpposite().ordinal() + ); + + if (sides == null || sides.length == 0) { + continue; + } + } + + final Block directedBlock = hostWorld.getBlock(xPos, yPos, zPos); + ItemStack what = new ItemStack( + directedBlock, + 1, + directedBlock.getDamageValue(hostWorld, xPos, yPos, zPos) + ); + try { + Vec3 from = Vec3.createVectorHelper( + hostTile.xCoord + 0.5, + hostTile.yCoord + 0.5, + hostTile.zCoord + 0.5 + ); + from = from.addVector( + direction.offsetX * 0.501, + direction.offsetY * 0.501, + direction.offsetZ * 0.501 + ); + final Vec3 to = from.addVector( + direction.offsetX, direction.offsetY, direction.offsetZ + ); + final MovingObjectPosition mop + = hostWorld.rayTraceBlocks(from, to, true); + if (mop != null && !BAD_BLOCKS.contains(directedBlock)) { + if (mop.blockX == directedTile.xCoord + && mop.blockY == directedTile.yCoord + && mop.blockZ == directedTile.zCoord) { + final ItemStack g = directedBlock.getPickBlock( + mop, + hostWorld, + directedTile.xCoord, + directedTile.yCoord, + directedTile.zCoord, + null + ); + if (g != null) { + what = g; + } + } + } + } catch (final Throwable t) { + BAD_BLOCKS.add(directedBlock); // nope! + } + + if (what.getItem() != null) { + return what.getUnlocalizedName(); + } + + final Item item = Item.getItemFromBlock(directedBlock); + if (item == null) { + return directedBlock.getUnlocalizedName(); + } + } + } + + return "Nothing"; + } + + public long getSortValue() { + final TileEntity te = this.iHost.getTileEntity(); + return (te.zCoord << 24) ^ (te.xCoord << 8) ^ te.yCoord; + } + + public void initialize() { + this.updateCraftingList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.markDirty(); + + try { + this.gridProxy.getGrid().postEvent( + new MENetworkCraftingPatternChange(this, this.gridProxy.getNode()) + ); + } catch (final GridAccessException e) { + // :P + } + } + + private class InterfaceRequestSource extends MachineSource { + public InterfaceRequestSource(final IActionHost v) { + super(v); + } + } + + private class InterfaceInventory extends MEMonitorIInventory { + public InterfaceInventory(final DualityInterface tileInterface) { + super(new AdaptorIInventory(tileInterface.storage)); + this.setActionSource(new MachineSource(DualityInterface.this.iHost)); + } + + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable type, final BaseActionSource src + ) { + if (src instanceof InterfaceRequestSource) { + return input; + } + + return super.injectItems(input, type, src); + } + + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable type, final BaseActionSource src + ) { + if (src instanceof InterfaceRequestSource) { + 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 4a7a52a7..18e6eb22 100644 --- a/src/main/java/appeng/helpers/IContainerCraftingPacket.java +++ b/src/main/java/appeng/helpers/IContainerCraftingPacket.java @@ -18,39 +18,35 @@ package appeng.helpers; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.BaseActionSource; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public interface IContainerCraftingPacket { + /** + * @return gain access to network infrastructure. + */ + IGridNode getNetworkNode(); -public interface IContainerCraftingPacket -{ + /** + * @param string name of inventory + * @return the inventory of the part/tile by name. + */ + IInventory getInventoryByName(String string); - /** - * @return gain access to network infrastructure. - */ - IGridNode getNetworkNode(); + /** + * @return who are we? + */ + BaseActionSource getActionSource(); - /** - * @param string name of inventory - * @return the inventory of the part/tile by name. - */ - IInventory getInventoryByName( String string ); + /** + * @return consume items? + */ + boolean useRealItems(); - /** - * @return who are we? - */ - BaseActionSource getActionSource(); - - /** - * @return consume items? - */ - boolean useRealItems(); - - /** - * @return array of view cells - */ - ItemStack[] getViewCells(); + /** + * @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 79059c5e..4370154c 100644 --- a/src/main/java/appeng/helpers/ICustomCollision.java +++ b/src/main/java/appeng/helpers/ICustomCollision.java @@ -18,17 +18,18 @@ package appeng.helpers; +import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; -import java.util.List; +public interface ICustomCollision { + Iterable getSelectedBoundingBoxesFromPool( + World w, int x, int y, int z, Entity thePlayer, boolean b + ); - -public interface ICustomCollision -{ - 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 c499e18b..6d544353 100644 --- a/src/main/java/appeng/helpers/ICustomNameObject.java +++ b/src/main/java/appeng/helpers/ICustomNameObject.java @@ -18,11 +18,8 @@ package appeng.helpers; +public interface ICustomNameObject { + String getCustomName(); -public interface ICustomNameObject -{ - - String getCustomName(); - - boolean hasCustomName(); + boolean hasCustomName(); } diff --git a/src/main/java/appeng/helpers/IInterfaceHost.java b/src/main/java/appeng/helpers/IInterfaceHost.java index e08813c1..1a2fecca 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 appeng.api.implementations.IUpgradeableHost; import appeng.api.networking.crafting.ICraftingProvider; @@ -25,17 +26,13 @@ import appeng.api.networking.crafting.ICraftingRequester; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public interface IInterfaceHost + extends ICraftingProvider, IUpgradeableHost, ICraftingRequester { + DualityInterface getInterfaceDuality(); + EnumSet getTargets(); -public interface IInterfaceHost extends ICraftingProvider, IUpgradeableHost, ICraftingRequester -{ + TileEntity getTileEntity(); - DualityInterface getInterfaceDuality(); - - EnumSet getTargets(); - - TileEntity getTileEntity(); - - void saveChanges(); + void saveChanges(); } diff --git a/src/main/java/appeng/helpers/IMouseWheelItem.java b/src/main/java/appeng/helpers/IMouseWheelItem.java index cc223005..04dc486a 100644 --- a/src/main/java/appeng/helpers/IMouseWheelItem.java +++ b/src/main/java/appeng/helpers/IMouseWheelItem.java @@ -18,12 +18,8 @@ package appeng.helpers; - import net.minecraft.item.ItemStack; - -public interface IMouseWheelItem -{ - - void onWheel( ItemStack is, boolean up ); +public interface IMouseWheelItem { + 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 083fd8ca..b0d2dbcc 100644 --- a/src/main/java/appeng/helpers/IPriorityHost.java +++ b/src/main/java/appeng/helpers/IPriorityHost.java @@ -18,17 +18,14 @@ package appeng.helpers; +public interface IPriorityHost { + /** + * get current priority. + */ + int getPriority(); -public interface IPriorityHost -{ - - /** - * get current priority. - */ - int getPriority(); - - /** - * set new priority - */ - void setPriority( int newValue ); + /** + * set new priority + */ + void setPriority(int newValue); } diff --git a/src/main/java/appeng/helpers/InventoryAction.java b/src/main/java/appeng/helpers/InventoryAction.java index 5076b85e..37ce7459 100644 --- a/src/main/java/appeng/helpers/InventoryAction.java +++ b/src/main/java/appeng/helpers/InventoryAction.java @@ -18,15 +18,24 @@ package appeng.helpers; +public enum InventoryAction { + // standard vanilla mechanics. + PICKUP_OR_SET_DOWN, + SPLIT_OR_PLACE_SINGLE, + CREATIVE_DUPLICATE, + SHIFT_CLICK, -public enum InventoryAction -{ - // standard vanilla mechanics. - PICKUP_OR_SET_DOWN, SPLIT_OR_PLACE_SINGLE, CREATIVE_DUPLICATE, SHIFT_CLICK, + // crafting term + CRAFT_STACK, + CRAFT_ITEM, + CRAFT_SHIFT, - // crafting term - CRAFT_STACK, CRAFT_ITEM, CRAFT_SHIFT, - - // extra... - MOVE_REGION, PICKUP_SINGLE, UPDATE_HAND, ROLL_UP, ROLL_DOWN, AUTO_CRAFT, PLACE_SINGLE + // extra... + MOVE_REGION, + PICKUP_SINGLE, + UPDATE_HAND, + ROLL_UP, + ROLL_DOWN, + AUTO_CRAFT, + PLACE_SINGLE } diff --git a/src/main/java/appeng/helpers/LocationRotation.java b/src/main/java/appeng/helpers/LocationRotation.java index a077ab5d..711dbeb9 100644 --- a/src/main/java/appeng/helpers/LocationRotation.java +++ b/src/main/java/appeng/helpers/LocationRotation.java @@ -18,54 +18,44 @@ package appeng.helpers; - import appeng.api.util.IOrientable; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.util.ForgeDirection; +public class LocationRotation implements IOrientable { + private final IBlockAccess w; + private final int x; + private final int y; + private final int z; -public class LocationRotation implements IOrientable -{ + public LocationRotation( + final IBlockAccess world, final int x, final int y, final int z + ) { + this.w = world; + this.x = x; + this.y = y; + this.z = z; + } - private final IBlockAccess w; - private final int x; - private final int y; - private final int z; + @Override + public boolean canBeRotated() { + return false; + } - public LocationRotation( final IBlockAccess world, final int x, final int y, final int z ) - { - this.w = world; - this.x = x; - this.y = y; - this.z = z; - } + @Override + public ForgeDirection getForward() { + if (this.getUp().offsetY == 0) { + return ForgeDirection.UP; + } + return ForgeDirection.SOUTH; + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public ForgeDirection getUp() { + final int num = Math.abs(this.x + this.y + this.z) % 6; + return ForgeDirection.getOrientation(num); + } - @Override - public ForgeDirection getForward() - { - if( this.getUp().offsetY == 0 ) - { - return ForgeDirection.UP; - } - return ForgeDirection.SOUTH; - } - - @Override - public ForgeDirection getUp() - { - final int num = Math.abs( this.x + this.y + this.z ) % 6; - return ForgeDirection.getOrientation( num ); - } - - @Override - public void setOrientation( final ForgeDirection forward, final ForgeDirection up ) - { - - } + @Override + public void setOrientation(final ForgeDirection forward, final ForgeDirection up) {} } diff --git a/src/main/java/appeng/helpers/MetaRotation.java b/src/main/java/appeng/helpers/MetaRotation.java index 9db4bca3..2eb351d9 100644 --- a/src/main/java/appeng/helpers/MetaRotation.java +++ b/src/main/java/appeng/helpers/MetaRotation.java @@ -18,61 +18,53 @@ package appeng.helpers; - import appeng.api.util.IOrientable; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class MetaRotation implements IOrientable { + private final IBlockAccess w; + private final int x; + private final int y; + private final int z; -public class MetaRotation implements IOrientable -{ + public MetaRotation(final IBlockAccess world, final int x, final int y, final int z) { + this.w = world; + this.x = x; + this.y = y; + this.z = z; + } - private final IBlockAccess w; - private final int x; - private final int y; - private final int z; + @Override + public boolean canBeRotated() { + return true; + } - public MetaRotation( final IBlockAccess world, final int x, final int y, final int z ) - { - this.w = world; - this.x = x; - this.y = y; - this.z = z; - } + @Override + public ForgeDirection getForward() { + if (this.getUp().offsetY == 0) { + return ForgeDirection.UP; + } + return ForgeDirection.SOUTH; + } - @Override - public boolean canBeRotated() - { - return true; - } + @Override + public ForgeDirection getUp() { + return ForgeDirection.getOrientation( + this.w.getBlockMetadata(this.x, this.y, this.z) + ); + } - @Override - public ForgeDirection getForward() - { - if( this.getUp().offsetY == 0 ) - { - return ForgeDirection.UP; - } - return ForgeDirection.SOUTH; - } - - @Override - public ForgeDirection getUp() - { - return ForgeDirection.getOrientation( this.w.getBlockMetadata( this.x, this.y, this.z ) ); - } - - @Override - public void setOrientation( final ForgeDirection forward, final ForgeDirection up ) - { - if( this.w instanceof World ) - { - ( (World) this.w ).setBlockMetadataWithNotify( this.x, this.y, this.z, up.ordinal(), 1 + 2 ); - } - else - { - throw new IllegalStateException( this.w.getClass().getName() + " received, expected World" ); - } - } + @Override + public void setOrientation(final ForgeDirection forward, final ForgeDirection up) { + if (this.w instanceof World) { + ((World) this.w) + .setBlockMetadataWithNotify(this.x, this.y, this.z, up.ordinal(), 1 + 2); + } else { + throw new IllegalStateException( + 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 014fa61d..50157c97 100644 --- a/src/main/java/appeng/helpers/MultiCraftingTracker.java +++ b/src/main/java/appeng/helpers/MultiCraftingTracker.java @@ -18,6 +18,8 @@ package appeng.helpers; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; import appeng.api.AEApi; import appeng.api.networking.IGrid; @@ -32,257 +34,206 @@ import com.google.common.collect.ImmutableSet; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; +public class MultiCraftingTracker { + private final int size; + private final ICraftingRequester owner; + private Future[] jobs = null; + private ICraftingLink[] links = null; -public class MultiCraftingTracker -{ + public MultiCraftingTracker(final ICraftingRequester o, final int size) { + this.owner = o; + this.size = size; + } - private final int size; - private final ICraftingRequester owner; + public void readFromNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final NBTTagCompound link = extra.getCompoundTag("links-" + x); - private Future[] jobs = null; - private ICraftingLink[] links = null; + if (link != null && !link.hasNoTags()) { + this.setLink( + x, AEApi.instance().storage().loadCraftingLink(link, this.owner) + ); + } + } + } - public MultiCraftingTracker( final ICraftingRequester o, final int size ) - { - this.owner = o; - this.size = size; - } + public void writeToNBT(final NBTTagCompound extra) { + for (int x = 0; x < this.size; x++) { + final ICraftingLink link = this.getLink(x); - public void readFromNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final NBTTagCompound link = extra.getCompoundTag( "links-" + x ); + if (link != null) { + final NBTTagCompound ln = new NBTTagCompound(); + link.writeToNBT(ln); + extra.setTag("links-" + x, ln); + } + } + } - if( link != null && !link.hasNoTags() ) - { - this.setLink( x, AEApi.instance().storage().loadCraftingLink( link, this.owner ) ); - } - } - } + public boolean handleCrafting( + final int x, + final long itemToCraft, + final IAEItemStack ais, + final InventoryAdaptor d, + final World w, + final IGrid g, + final ICraftingGrid cg, + final BaseActionSource mySrc + ) { + if (ais != null && d.simulateAdd(ais.getItemStack()) == null) { + final Future craftingJob = this.getJob(x); - public void writeToNBT( final NBTTagCompound extra ) - { - for( int x = 0; x < this.size; x++ ) - { - final ICraftingLink link = this.getLink( x ); + if (this.getLink(x) != null) { + return false; + } else if (craftingJob != null) { + try { + ICraftingJob job = null; + if (craftingJob.isDone()) { + job = craftingJob.get(); + } - if( link != null ) - { - final NBTTagCompound ln = new NBTTagCompound(); - link.writeToNBT( ln ); - extra.setTag( "links-" + x, ln ); - } - } - } + if (job != null) { + final ICraftingLink link + = cg.submitJob(job, this.owner, null, false, mySrc); - public boolean handleCrafting( final int x, final long itemToCraft, final IAEItemStack ais, final InventoryAdaptor d, final World w, final IGrid g, final ICraftingGrid cg, final BaseActionSource mySrc ) - { - if( ais != null && d.simulateAdd( ais.getItemStack() ) == null ) - { - final Future craftingJob = this.getJob( x ); + this.setJob(x, null); - if( this.getLink( x ) != null ) - { - return false; - } - else if( craftingJob != null ) - { - try - { - ICraftingJob job = null; - if( craftingJob.isDone() ) - { - job = craftingJob.get(); - } + if (link != null) { + this.setLink(x, link); - if( job != null ) - { - final ICraftingLink link = cg.submitJob( job, this.owner, null, false, mySrc ); + return true; + } + } + } catch (final InterruptedException e) { + // :P + } catch (final ExecutionException e) { + // :P + } + } else { + if (this.getLink(x) == null) { + final IAEItemStack aisC = ais.copy(); + aisC.setStackSize(itemToCraft); - this.setJob( x, null ); + this.setJob(x, cg.beginCraftingJob(w, g, mySrc, aisC, null)); + } + } + } + return false; + } - if( link != null ) - { - this.setLink( x, link ); + public ImmutableSet getRequestedJobs() { + if (this.links == null) { + return ImmutableSet.of(); + } - return true; - } - } - } - catch( final InterruptedException e ) - { - // :P - } - catch( final ExecutionException e ) - { - // :P - } - } - else - { - if( this.getLink( x ) == null ) - { - final IAEItemStack aisC = ais.copy(); - aisC.setStackSize( itemToCraft ); + return ImmutableSet.copyOf(new NonNullArrayIterator(this.links)); + } - this.setJob( x, cg.beginCraftingJob( w, g, mySrc, aisC, null ) ); - } - } - } - return false; - } + public void jobStateChange(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { + this.setLink(x, null); + return; + } + } + } + } - public ImmutableSet getRequestedJobs() - { - if( this.links == null ) - { - return ImmutableSet.of(); - } + int getSlot(final ICraftingLink link) { + if (this.links != null) { + for (int x = 0; x < this.links.length; x++) { + if (this.links[x] == link) { + return x; + } + } + } - return ImmutableSet.copyOf( new NonNullArrayIterator( this.links ) ); - } + return -1; + } - public void jobStateChange( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { - this.setLink( x, null ); - return; - } - } - } - } + void cancel() { + if (this.links != null) { + for (final ICraftingLink l : this.links) { + if (l != null) { + l.cancel(); + } + } - int getSlot( final ICraftingLink link ) - { - if( this.links != null ) - { - for( int x = 0; x < this.links.length; x++ ) - { - if( this.links[x] == link ) - { - return x; - } - } - } + this.links = null; + } - return -1; - } + if (this.jobs != null) { + for (final Future l : this.jobs) { + if (l != null) { + l.cancel(true); + } + } - void cancel() - { - if( this.links != null ) - { - for( final ICraftingLink l : this.links ) - { - if( l != null ) - { - l.cancel(); - } - } + this.jobs = null; + } + } - this.links = null; - } + boolean isBusy(final int slot) { + return this.getLink(slot) != null || this.getJob(slot) != null; + } - if( this.jobs != null ) - { - for( final Future l : this.jobs ) - { - if( l != null ) - { - l.cancel( true ); - } - } + private ICraftingLink getLink(final int slot) { + if (this.links == null) { + return null; + } - this.jobs = null; - } - } + return this.links[slot]; + } - boolean isBusy( final int slot ) - { - return this.getLink( slot ) != null || this.getJob( slot ) != null; - } + private void setLink(final int slot, final ICraftingLink l) { + if (this.links == null) { + this.links = new ICraftingLink[this.size]; + } - private ICraftingLink getLink( final int slot ) - { - if( this.links == null ) - { - return null; - } + this.links[slot] = l; - return this.links[slot]; - } + boolean hasStuff = false; + for (int x = 0; x < this.links.length; x++) { + final ICraftingLink g = this.links[x]; - private void setLink( final int slot, final ICraftingLink l ) - { - if( this.links == null ) - { - this.links = new ICraftingLink[this.size]; - } + if (g == null || g.isCanceled() || g.isDone()) { + this.links[x] = null; + } else { + hasStuff = true; + } + } - this.links[slot] = l; + if (!hasStuff) { + this.links = null; + } + } - boolean hasStuff = false; - for( int x = 0; x < this.links.length; x++ ) - { - final ICraftingLink g = this.links[x]; + private Future getJob(final int slot) { + if (this.jobs == null) { + return null; + } - if( g == null || g.isCanceled() || g.isDone() ) - { - this.links[x] = null; - } - else - { - hasStuff = true; - } - } + return this.jobs[slot]; + } - if( !hasStuff ) - { - this.links = null; - } - } + private void setJob(final int slot, final Future l) { + if (this.jobs == null) { + this.jobs = new Future[this.size]; + } - private Future getJob( final int slot ) - { - if( this.jobs == null ) - { - return null; - } + this.jobs[slot] = l; - return this.jobs[slot]; - } + boolean hasStuff = false; - private void setJob( final int slot, final Future l ) - { - if( this.jobs == null ) - { - this.jobs = new Future[this.size]; - } + for (final Future job : this.jobs) { + if (job != null) { + hasStuff = true; + } + } - this.jobs[slot] = l; - - boolean hasStuff = false; - - for( final Future job : this.jobs ) - { - if( job != null ) - { - hasStuff = true; - } - } - - if( !hasStuff ) - { - this.jobs = null; - } - } + if (!hasStuff) { + this.jobs = null; + } + } } diff --git a/src/main/java/appeng/helpers/NonNullArrayIterator.java b/src/main/java/appeng/helpers/NonNullArrayIterator.java index 7c964168..b3f9b326 100644 --- a/src/main/java/appeng/helpers/NonNullArrayIterator.java +++ b/src/main/java/appeng/helpers/NonNullArrayIterator.java @@ -18,44 +18,35 @@ package appeng.helpers; - import java.util.Iterator; +public class NonNullArrayIterator implements Iterator { + private final E[] g; + private int offset = 0; -public class NonNullArrayIterator implements Iterator -{ + public NonNullArrayIterator(final E[] o) { + this.g = o; + } - private final E[] g; - private int offset = 0; + @Override + public boolean hasNext() { + while (this.offset < this.g.length && this.g[this.offset] == null) { + this.offset++; + } - public NonNullArrayIterator( final E[] o ) - { - this.g = o; - } + return this.offset != this.g.length; + } - @Override - public boolean hasNext() - { - while( this.offset < this.g.length && this.g[this.offset] == null ) - { - this.offset++; - } + @Override + public E next() { + final E result = this.g[this.offset]; + this.offset++; - return this.offset != this.g.length; - } + return result; + } - @Override - public E next() - { - final E result = this.g[this.offset]; - this.offset++; - - return result; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/helpers/NullRotation.java b/src/main/java/appeng/helpers/NullRotation.java index 342191de..d2e76e85 100644 --- a/src/main/java/appeng/helpers/NullRotation.java +++ b/src/main/java/appeng/helpers/NullRotation.java @@ -18,40 +18,27 @@ package appeng.helpers; - import appeng.api.util.IOrientable; import net.minecraftforge.common.util.ForgeDirection; +public class NullRotation implements IOrientable { + public NullRotation() {} -public class NullRotation implements IOrientable -{ + @Override + public boolean canBeRotated() { + return false; + } - public NullRotation() - { + @Override + public ForgeDirection getForward() { + return ForgeDirection.SOUTH; + } - } + @Override + public ForgeDirection getUp() { + return ForgeDirection.UP; + } - @Override - public boolean canBeRotated() - { - return false; - } - - @Override - public ForgeDirection getForward() - { - return ForgeDirection.SOUTH; - } - - @Override - public ForgeDirection getUp() - { - return ForgeDirection.UP; - } - - @Override - public void setOrientation( final ForgeDirection forward, final ForgeDirection up ) - { - - } + @Override + public void setOrientation(final ForgeDirection forward, final ForgeDirection up) {} } diff --git a/src/main/java/appeng/helpers/PatternHelper.java b/src/main/java/appeng/helpers/PatternHelper.java index 9972e43f..ad272bb0 100644 --- a/src/main/java/appeng/helpers/PatternHelper.java +++ b/src/main/java/appeng/helpers/PatternHelper.java @@ -18,6 +18,7 @@ package appeng.helpers; +import java.util.*; import appeng.api.AEApi; import appeng.api.networking.crafting.ICraftingPatternDetails; @@ -35,417 +36,351 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; -import java.util.*; - - -public class PatternHelper implements ICraftingPatternDetails, Comparable -{ - - private final ItemStack patternItem; - private final InventoryCrafting crafting = new InventoryCrafting( new ContainerNull(), 3, 3 ); - private final InventoryCrafting testFrame = new InventoryCrafting( new ContainerNull(), 3, 3 ); - private final ItemStack correctOutput; - private final IRecipe standardRecipe; - private final IAEItemStack[] condensedInputs; - private final IAEItemStack[] condensedOutputs; - private final IAEItemStack[] inputs; - private final IAEItemStack[] outputs; - private final boolean isCrafting; - private final boolean canSubstitute; - private final Set failCache = new HashSet(); - private final Set passCache = new HashSet(); - private final IAEItemStack pattern; - private int priority = 0; - - public PatternHelper( final ItemStack is, final World w ) - { - final NBTTagCompound encodedValue = is.getTagCompound(); - - if( encodedValue == null ) - { - throw new IllegalArgumentException( "No pattern here!" ); - } - - final NBTTagList inTag = encodedValue.getTagList( "in", 10 ); - final NBTTagList outTag = encodedValue.getTagList( "out", 10 ); - this.isCrafting = encodedValue.getBoolean( "crafting" ); - - this.canSubstitute = encodedValue.getBoolean( "substitute" ); - this.patternItem = is; - this.pattern = AEItemStack.create( is ); - - final List in = new ArrayList(); - final List out = new ArrayList(); - - for( int x = 0; x < inTag.tagCount(); x++ ) - { - final ItemStack gs = ItemStack.loadItemStackFromNBT( inTag.getCompoundTagAt( x ) ); - - this.crafting.setInventorySlotContents( x, gs ); - - if( gs != null && ( !this.isCrafting || !gs.hasTagCompound() ) ) - { - this.markItemAs( x, gs, TestStatus.ACCEPT ); - } - - in.add( AEApi.instance().storage().createItemStack( gs ) ); - this.testFrame.setInventorySlotContents( x, gs ); - } - - if( this.isCrafting ) - { - this.standardRecipe = Platform.findMatchingRecipe( this.crafting, w ); - - if( this.standardRecipe != null ) - { - this.correctOutput = this.standardRecipe.getCraftingResult( this.crafting ); - out.add( AEApi.instance().storage().createItemStack( this.correctOutput ) ); - } - else - { - throw new IllegalStateException( "No pattern here!" ); - } - } - else - { - this.standardRecipe = null; - this.correctOutput = null; - - for( int x = 0; x < outTag.tagCount(); x++ ) - { - final ItemStack gs = ItemStack.loadItemStackFromNBT( outTag.getCompoundTagAt( x ) ); - - if( gs != null ) - { - out.add( AEApi.instance().storage().createItemStack( gs ) ); - } - } - } - - this.outputs = out.toArray( new IAEItemStack[out.size()] ); - this.inputs = in.toArray( new IAEItemStack[in.size()] ); - - final Map tmpOutputs = new HashMap(); - - for( final IAEItemStack io : this.outputs ) - { - if( io == null ) - { - continue; - } - - final IAEItemStack g = tmpOutputs.get( io ); - - if( g == null ) - { - tmpOutputs.put( io, io.copy() ); - } - else - { - g.add( io ); - } - } - - final Map tmpInputs = new HashMap(); - - for( final IAEItemStack io : this.inputs ) - { - if( io == null ) - { - continue; - } - - final IAEItemStack g = tmpInputs.get( io ); - - if( g == null ) - { - tmpInputs.put( io, io.copy() ); - } - else - { - g.add( io ); - } - } - - if( tmpOutputs.isEmpty() || tmpInputs.isEmpty() ) - { - throw new IllegalStateException( "No pattern here!" ); - } - - this.condensedInputs = new IAEItemStack[tmpInputs.size()]; - int offset = 0; - - for( final IAEItemStack io : tmpInputs.values() ) - { - this.condensedInputs[offset] = io; - offset++; - } - - offset = 0; - this.condensedOutputs = new IAEItemStack[tmpOutputs.size()]; - - for( final IAEItemStack io : tmpOutputs.values() ) - { - this.condensedOutputs[offset] = io; - offset++; - } - } - - private void markItemAs( final int slotIndex, final ItemStack i, final TestStatus b ) - { - if( b == TestStatus.TEST || i.hasTagCompound() ) - { - return; - } - - ( b == TestStatus.ACCEPT ? this.passCache : this.failCache ).add( new TestLookup( slotIndex, i ) ); - } - - @Override - public ItemStack getPattern() - { - return this.patternItem; - } - - @Override - public synchronized boolean isValidItemForSlot( final int slotIndex, final ItemStack i, final World w ) - { - if( !this.isCrafting ) - { - throw new IllegalStateException( "Only crafting recipes supported." ); - } - - final TestStatus result = this.getStatus( slotIndex, i ); - - switch( result ) - { - case ACCEPT: - return true; - case DECLINE: - return false; - case TEST: - default: - break; - } - - for( int x = 0; x < this.crafting.getSizeInventory(); x++ ) - { - this.testFrame.setInventorySlotContents( x, this.crafting.getStackInSlot( x ) ); - } - - this.testFrame.setInventorySlotContents( slotIndex, i ); - - if( this.standardRecipe.matches( this.testFrame, w ) ) - { - final ItemStack testOutput = this.standardRecipe.getCraftingResult( this.testFrame ); - - if( Platform.isSameItemPrecise( this.correctOutput, testOutput ) ) - { - this.testFrame.setInventorySlotContents( slotIndex, this.crafting.getStackInSlot( slotIndex ) ); - this.markItemAs( slotIndex, i, TestStatus.ACCEPT ); - return true; - } - } - else - { - final ItemStack testOutput = CraftingManager.getInstance().findMatchingRecipe( this.testFrame, w ); - - if( Platform.isSameItemPrecise( this.correctOutput, testOutput ) ) - { - this.testFrame.setInventorySlotContents( slotIndex, this.crafting.getStackInSlot( slotIndex ) ); - this.markItemAs( slotIndex, i, TestStatus.ACCEPT ); - return true; - } - } - - this.markItemAs( slotIndex, i, TestStatus.DECLINE ); - return false; - } - - @Override - public boolean isCraftable() - { - return this.isCrafting; - } - - @Override - public IAEItemStack[] getInputs() - { - return this.inputs; - } - - @Override - public IAEItemStack[] getCondensedInputs() - { - return this.condensedInputs; - } - - @Override - public IAEItemStack[] getCondensedOutputs() - { - return this.condensedOutputs; - } - - @Override - public IAEItemStack[] getOutputs() - { - return this.outputs; - } - - @Override - public boolean canSubstitute() - { - return this.canSubstitute; - } - - @Override - public ItemStack getOutput( final InventoryCrafting craftingInv, final World w ) - { - if( !this.isCrafting ) - { - throw new IllegalStateException( "Only crafting recipes supported." ); - } - - for( int x = 0; x < craftingInv.getSizeInventory(); x++ ) - { - if( !this.isValidItemForSlot( x, craftingInv.getStackInSlot( x ), w ) ) - { - return null; - } - } - - if( this.outputs != null && this.outputs.length > 0 ) - { - return this.outputs[0].getItemStack(); - } - - return null; - } - - private TestStatus getStatus( final int slotIndex, final 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( final int priority ) - { - this.priority = priority; - } - - @Override - public int compareTo( final PatternHelper o ) - { - return ItemSorters.compareInt( o.priority, this.priority ); - } - - @Override - public int hashCode() - { - return this.pattern.hashCode(); - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - - final PatternHelper other = (PatternHelper) obj; - - if( this.pattern != null && other.pattern != null ) - { - return this.pattern.equals( other.pattern ); - } - return false; - } - - private enum TestStatus - { - ACCEPT, DECLINE, TEST - } - - - private static final class TestLookup - { - - private final int slot; - private final int ref; - private final int hash; - - public TestLookup( final int slot, final ItemStack i ) - { - this( slot, i.getItem(), i.getItemDamage() ); - } - - public TestLookup( final int slot, final Item item, final int dmg ) - { - this.slot = slot; - this.ref = ( dmg << Platform.DEF_OFFSET ) | ( Item.getIdFromItem( item ) & 0xffff ); - final int offset = 3 * slot; - this.hash = ( this.ref << offset ) | ( this.ref >> ( offset + 32 ) ); - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals( final Object obj ) - { - final boolean equality; - - if( obj instanceof TestLookup ) - { - final TestLookup b = (TestLookup) obj; - - equality = b.slot == this.slot && b.ref == this.ref; - } - else - { - equality = false; - } - - return equality; - } - } +public class PatternHelper implements ICraftingPatternDetails, Comparable { + private final ItemStack patternItem; + private final InventoryCrafting crafting + = new InventoryCrafting(new ContainerNull(), 3, 3); + private final InventoryCrafting testFrame + = new InventoryCrafting(new ContainerNull(), 3, 3); + private final ItemStack correctOutput; + private final IRecipe standardRecipe; + private final IAEItemStack[] condensedInputs; + private final IAEItemStack[] condensedOutputs; + private final IAEItemStack[] inputs; + private final IAEItemStack[] outputs; + private final boolean isCrafting; + private final boolean canSubstitute; + private final Set failCache = new HashSet(); + private final Set passCache = new HashSet(); + private final IAEItemStack pattern; + private int priority = 0; + + public PatternHelper(final ItemStack is, final World w) { + final NBTTagCompound encodedValue = is.getTagCompound(); + + if (encodedValue == null) { + throw new IllegalArgumentException("No pattern here!"); + } + + final NBTTagList inTag = encodedValue.getTagList("in", 10); + final NBTTagList outTag = encodedValue.getTagList("out", 10); + this.isCrafting = encodedValue.getBoolean("crafting"); + + this.canSubstitute = encodedValue.getBoolean("substitute"); + this.patternItem = is; + this.pattern = AEItemStack.create(is); + + final List in = new ArrayList(); + final List out = new ArrayList(); + + for (int x = 0; x < inTag.tagCount(); x++) { + final ItemStack gs + = ItemStack.loadItemStackFromNBT(inTag.getCompoundTagAt(x)); + + this.crafting.setInventorySlotContents(x, gs); + + if (gs != null && (!this.isCrafting || !gs.hasTagCompound())) { + this.markItemAs(x, gs, TestStatus.ACCEPT); + } + + in.add(AEApi.instance().storage().createItemStack(gs)); + this.testFrame.setInventorySlotContents(x, gs); + } + + if (this.isCrafting) { + this.standardRecipe = Platform.findMatchingRecipe(this.crafting, w); + + if (this.standardRecipe != null) { + this.correctOutput = this.standardRecipe.getCraftingResult(this.crafting); + out.add(AEApi.instance().storage().createItemStack(this.correctOutput)); + } else { + throw new IllegalStateException("No pattern here!"); + } + } else { + this.standardRecipe = null; + this.correctOutput = null; + + for (int x = 0; x < outTag.tagCount(); x++) { + final ItemStack gs + = ItemStack.loadItemStackFromNBT(outTag.getCompoundTagAt(x)); + + if (gs != null) { + out.add(AEApi.instance().storage().createItemStack(gs)); + } + } + } + + this.outputs = out.toArray(new IAEItemStack[out.size()]); + this.inputs = in.toArray(new IAEItemStack[in.size()]); + + final Map tmpOutputs + = new HashMap(); + + for (final IAEItemStack io : this.outputs) { + if (io == null) { + continue; + } + + final IAEItemStack g = tmpOutputs.get(io); + + if (g == null) { + tmpOutputs.put(io, io.copy()); + } else { + g.add(io); + } + } + + final Map tmpInputs + = new HashMap(); + + for (final IAEItemStack io : this.inputs) { + if (io == null) { + continue; + } + + final IAEItemStack g = tmpInputs.get(io); + + if (g == null) { + tmpInputs.put(io, io.copy()); + } else { + g.add(io); + } + } + + if (tmpOutputs.isEmpty() || tmpInputs.isEmpty()) { + throw new IllegalStateException("No pattern here!"); + } + + this.condensedInputs = new IAEItemStack[tmpInputs.size()]; + int offset = 0; + + for (final IAEItemStack io : tmpInputs.values()) { + this.condensedInputs[offset] = io; + offset++; + } + + offset = 0; + this.condensedOutputs = new IAEItemStack[tmpOutputs.size()]; + + for (final IAEItemStack io : tmpOutputs.values()) { + this.condensedOutputs[offset] = io; + offset++; + } + } + + private void markItemAs(final int slotIndex, final ItemStack i, final TestStatus b) { + if (b == TestStatus.TEST || i.hasTagCompound()) { + return; + } + + (b == TestStatus.ACCEPT ? this.passCache : this.failCache) + .add(new TestLookup(slotIndex, i)); + } + + @Override + public ItemStack getPattern() { + return this.patternItem; + } + + @Override + public synchronized boolean + isValidItemForSlot(final int slotIndex, final ItemStack i, final World w) { + if (!this.isCrafting) { + throw new IllegalStateException("Only crafting recipes supported."); + } + + final TestStatus result = this.getStatus(slotIndex, i); + + switch (result) { + case ACCEPT: + return true; + case DECLINE: + return false; + case TEST: + default: + break; + } + + for (int x = 0; x < this.crafting.getSizeInventory(); x++) { + this.testFrame.setInventorySlotContents(x, this.crafting.getStackInSlot(x)); + } + + this.testFrame.setInventorySlotContents(slotIndex, i); + + if (this.standardRecipe.matches(this.testFrame, w)) { + final ItemStack testOutput + = this.standardRecipe.getCraftingResult(this.testFrame); + + if (Platform.isSameItemPrecise(this.correctOutput, testOutput)) { + this.testFrame.setInventorySlotContents( + slotIndex, this.crafting.getStackInSlot(slotIndex) + ); + this.markItemAs(slotIndex, i, TestStatus.ACCEPT); + return true; + } + } else { + final ItemStack testOutput + = CraftingManager.getInstance().findMatchingRecipe(this.testFrame, w); + + if (Platform.isSameItemPrecise(this.correctOutput, testOutput)) { + this.testFrame.setInventorySlotContents( + slotIndex, this.crafting.getStackInSlot(slotIndex) + ); + this.markItemAs(slotIndex, i, TestStatus.ACCEPT); + return true; + } + } + + this.markItemAs(slotIndex, i, TestStatus.DECLINE); + return false; + } + + @Override + public boolean isCraftable() { + return this.isCrafting; + } + + @Override + public IAEItemStack[] getInputs() { + return this.inputs; + } + + @Override + public IAEItemStack[] getCondensedInputs() { + return this.condensedInputs; + } + + @Override + public IAEItemStack[] getCondensedOutputs() { + return this.condensedOutputs; + } + + @Override + public IAEItemStack[] getOutputs() { + return this.outputs; + } + + @Override + public boolean canSubstitute() { + return this.canSubstitute; + } + + @Override + public ItemStack getOutput(final InventoryCrafting craftingInv, final World w) { + if (!this.isCrafting) { + throw new IllegalStateException("Only crafting recipes supported."); + } + + for (int x = 0; x < craftingInv.getSizeInventory(); x++) { + if (!this.isValidItemForSlot(x, craftingInv.getStackInSlot(x), w)) { + return null; + } + } + + if (this.outputs != null && this.outputs.length > 0) { + return this.outputs[0].getItemStack(); + } + + return null; + } + + private TestStatus getStatus(final int slotIndex, final 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(final int priority) { + this.priority = priority; + } + + @Override + public int compareTo(final PatternHelper o) { + return ItemSorters.compareInt(o.priority, this.priority); + } + + @Override + public int hashCode() { + return this.pattern.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + + final PatternHelper other = (PatternHelper) obj; + + if (this.pattern != null && other.pattern != null) { + return this.pattern.equals(other.pattern); + } + return false; + } + + private enum TestStatus { ACCEPT, DECLINE, TEST } + + private static final class TestLookup { + private final int slot; + private final int ref; + private final int hash; + + public TestLookup(final int slot, final ItemStack i) { + this(slot, i.getItem(), i.getItemDamage()); + } + + public TestLookup(final int slot, final Item item, final int dmg) { + this.slot = slot; + this.ref = (dmg << Platform.DEF_OFFSET) | (Item.getIdFromItem(item) & 0xffff); + final int offset = 3 * slot; + this.hash = (this.ref << offset) | (this.ref >> (offset + 32)); + } + + @Override + public int hashCode() { + return this.hash; + } + + @Override + public boolean equals(final Object obj) { + final boolean equality; + + if (obj instanceof TestLookup) { + final TestLookup b = (TestLookup) obj; + + equality = b.slot == this.slot && b.ref == this.ref; + } else { + equality = false; + } + + return equality; + } + } } diff --git a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java index 0ac15515..1d09ca38 100644 --- a/src/main/java/appeng/helpers/PlayerSecurityWrapper.java +++ b/src/main/java/appeng/helpers/PlayerSecurityWrapper.java @@ -18,28 +18,25 @@ package appeng.helpers; - -import appeng.api.config.SecurityPermissions; -import appeng.api.networking.security.ISecurityRegistry; - import java.util.EnumSet; import java.util.HashMap; import java.util.Map; +import appeng.api.config.SecurityPermissions; +import appeng.api.networking.security.ISecurityRegistry; -public class PlayerSecurityWrapper implements ISecurityRegistry -{ +public class PlayerSecurityWrapper implements ISecurityRegistry { + private final Map> target; - private final Map> target; + public PlayerSecurityWrapper( + final HashMap> playerPerms + ) { + this.target = playerPerms; + } - public PlayerSecurityWrapper( final HashMap> playerPerms ) - { - this.target = playerPerms; - } - - @Override - public void addPlayer( final int playerID, final EnumSet permissions ) - { - this.target.put( playerID, permissions ); - } + @Override + public void + addPlayer(final int playerID, final EnumSet permissions) { + this.target.put(playerID, permissions); + } } diff --git a/src/main/java/appeng/helpers/Reflected.java b/src/main/java/appeng/helpers/Reflected.java index 6e0c84da..d04cb166 100644 --- a/src/main/java/appeng/helpers/Reflected.java +++ b/src/main/java/appeng/helpers/Reflected.java @@ -1,18 +1,15 @@ package appeng.helpers; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * Marker interface to help identify invocation of reflection */ -@Retention( RetentionPolicy.SOURCE ) -@Target( { ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD } ) -public @interface Reflected -{ - -} +@Retention(RetentionPolicy.SOURCE) +@Target( + { ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE, ElementType.METHOD } +) +public @interface Reflected {} diff --git a/src/main/java/appeng/helpers/Splotch.java b/src/main/java/appeng/helpers/Splotch.java index faddd5aa..db2481cc 100644 --- a/src/main/java/appeng/helpers/Splotch.java +++ b/src/main/java/appeng/helpers/Splotch.java @@ -18,100 +18,90 @@ package appeng.helpers; - import appeng.api.util.AEColor; import io.netty.buffer.ByteBuf; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; +public class Splotch { + private final ForgeDirection side; + private final boolean lumen; + private final AEColor color; + private final int pos; -public class Splotch -{ + public Splotch( + final AEColor col, + final boolean lit, + final ForgeDirection side, + final Vec3 position + ) { + this.color = col; + this.lumen = lit; - private final ForgeDirection side; - private final boolean lumen; - private final AEColor color; - private final int pos; + final double x; + final double y; - public Splotch( final AEColor col, final boolean lit, final ForgeDirection side, final Vec3 position ) - { - this.color = col; - this.lumen = lit; + if (side == ForgeDirection.SOUTH || side == ForgeDirection.NORTH) { + x = position.xCoord; + y = position.yCoord; + } - final double x; - final double y; + else if (side == ForgeDirection.UP || side == ForgeDirection.DOWN) { + x = position.xCoord; + y = position.zCoord; + } - if( side == ForgeDirection.SOUTH || side == ForgeDirection.NORTH ) - { - x = position.xCoord; - y = position.yCoord; - } + else { + x = position.yCoord; + y = position.zCoord; + } - else if( side == ForgeDirection.UP || side == ForgeDirection.DOWN ) - { - x = position.xCoord; - y = position.zCoord; - } + final int a = (int) (x * 0xF); + final int b = (int) (y * 0xF); + this.pos = a | (b << 4); - else - { - x = position.yCoord; - y = position.zCoord; - } + this.side = side; + } - final int a = (int) ( x * 0xF ); - final int b = (int) ( y * 0xF ); - this.pos = a | ( b << 4 ); + public Splotch(final ByteBuf data) { + this.pos = data.readByte(); + final int val = data.readByte(); - this.side = side; - } + this.side = ForgeDirection.getOrientation(val & 0x07); + this.color = AEColor.values()[(val >> 3) & 0x0F]; + this.lumen = ((val >> 7) & 0x01) > 0; + } - public Splotch( final ByteBuf data ) - { + public void writeToStream(final ByteBuf stream) { + stream.writeByte(this.pos); + final int val = this.getSide().ordinal() | (this.getColor().ordinal() << 3) + | (this.isLumen() ? 0x80 : 0x00); + stream.writeByte(val); + } - this.pos = data.readByte(); - final int val = data.readByte(); + public float x() { + return (this.pos & 0x0f) / 15.0f; + } - this.side = ForgeDirection.getOrientation( val & 0x07 ); - this.color = AEColor.values()[( val >> 3 ) & 0x0F]; - this.lumen = ( ( val >> 7 ) & 0x01 ) > 0; - } + public float y() { + return ((this.pos >> 4) & 0x0f) / 15.0f; + } - public void writeToStream( final ByteBuf stream ) - { - stream.writeByte( this.pos ); - final int val = this.getSide().ordinal() | ( this.getColor().ordinal() << 3 ) | ( this.isLumen() ? 0x80 : 0x00 ); - stream.writeByte( val ); - } + public int getSeed() { + final int val = this.getSide().ordinal() | (this.getColor().ordinal() << 3) + | (this.isLumen() ? 0x80 : 0x00); + return Math.abs(this.pos + val); + } - public float x() - { - return ( this.pos & 0x0f ) / 15.0f; - } + public ForgeDirection getSide() { + return this.side; + } - public float y() - { - return ( ( this.pos >> 4 ) & 0x0f ) / 15.0f; - } + public AEColor getColor() { + return this.color; + } - public int getSeed() - { - final int val = this.getSide().ordinal() | ( this.getColor().ordinal() << 3 ) | ( this.isLumen() ? 0x80 : 0x00 ); - return Math.abs( this.pos + val ); - } - - public ForgeDirection getSide() - { - return this.side; - } - - public AEColor getColor() - { - return this.color; - } - - public boolean isLumen() - { - return this.lumen; - } + public boolean isLumen() { + return this.lumen; + } } diff --git a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java index 644fb5cf..700e6768 100644 --- a/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java +++ b/src/main/java/appeng/helpers/WirelessTerminalGuiObject.java @@ -18,7 +18,6 @@ package appeng.helpers; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -50,331 +49,283 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class WirelessTerminalGuiObject + implements IPortableCell, IActionHost, IInventorySlotAware { + private final ItemStack effectiveItem; + private final IWirelessTermHandler wth; + private final String encryptionKey; + private final EntityPlayer myPlayer; + private IGrid targetGrid; + private IStorageGrid sg; + private IMEMonitor itemStorage; + private IWirelessAccessPoint myWap; + private double sqRange = Double.MAX_VALUE; + private double myRange = Double.MAX_VALUE; + private final int inventorySlot; -public class WirelessTerminalGuiObject implements IPortableCell, IActionHost, IInventorySlotAware -{ + public WirelessTerminalGuiObject( + final IWirelessTermHandler wh, + final ItemStack is, + final EntityPlayer ep, + final World w, + final int x, + final int y, + final int z + ) { + this.encryptionKey = wh.getEncryptionKey(is); + this.effectiveItem = is; + this.myPlayer = ep; + this.wth = wh; + this.inventorySlot = x; - private final ItemStack effectiveItem; - private final IWirelessTermHandler wth; - private final String encryptionKey; - private final EntityPlayer myPlayer; - private IGrid targetGrid; - private IStorageGrid sg; - private IMEMonitor itemStorage; - private IWirelessAccessPoint myWap; - private double sqRange = Double.MAX_VALUE; - private double myRange = Double.MAX_VALUE; - private final int inventorySlot; + ILocatable obj = null; - public WirelessTerminalGuiObject( final IWirelessTermHandler wh, final ItemStack is, final EntityPlayer ep, final World w, final int x, final int y, final int z ) - { - this.encryptionKey = wh.getEncryptionKey( is ); - this.effectiveItem = is; - this.myPlayer = ep; - this.wth = wh; - this.inventorySlot = x; + try { + final long encKey = Long.parseLong(this.encryptionKey); + obj = AEApi.instance().registries().locatable().getLocatableBy(encKey); + } catch (final NumberFormatException err) { + // :P + } - ILocatable obj = null; + if (obj instanceof IGridHost) { + final IGridNode n = ((IGridHost) obj).getGridNode(ForgeDirection.UNKNOWN); + if (n != null) { + this.targetGrid = n.getGrid(); + if (this.targetGrid != null) { + this.sg = this.targetGrid.getCache(IStorageGrid.class); + if (this.sg != null) { + this.itemStorage = this.sg.getItemInventory(); + } + } + } + } + } - try - { - final long encKey = Long.parseLong( this.encryptionKey ); - obj = AEApi.instance().registries().locatable().getLocatableBy( encKey ); - } - catch( final NumberFormatException err ) - { - // :P - } + public double getRange() { + return this.myRange; + } - if( obj instanceof IGridHost ) - { - final IGridNode n = ( (IGridHost) obj ).getGridNode( ForgeDirection.UNKNOWN ); - if( n != null ) - { - this.targetGrid = n.getGrid(); - if( this.targetGrid != null ) - { - this.sg = this.targetGrid.getCache( IStorageGrid.class ); - if( this.sg != null ) - { - this.itemStorage = this.sg.getItemInventory(); - } - } - } - } - } + @Override + public IMEMonitor getItemInventory() { + if (this.sg == null) { + return null; + } + return this.sg.getItemInventory(); + } - public double getRange() - { - return this.myRange; - } + @Override + public IMEMonitor getFluidInventory() { + if (this.sg == null) { + return null; + } + return this.sg.getFluidInventory(); + } - @Override - public IMEMonitor getItemInventory() - { - if( this.sg == null ) - { - return null; - } - return this.sg.getItemInventory(); - } + @Override + public void addListener( + final IMEMonitorHandlerReceiver l, final Object verificationToken + ) { + if (this.itemStorage != null) { + this.itemStorage.addListener(l, verificationToken); + } + } - @Override - public IMEMonitor getFluidInventory() - { - if( this.sg == null ) - { - return null; - } - return this.sg.getFluidInventory(); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + if (this.itemStorage != null) { + this.itemStorage.removeListener(l); + } + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - if( this.itemStorage != null ) - { - this.itemStorage.addListener( l, verificationToken ); - } - } + @Override + public IItemList getAvailableItems(final IItemList out) { + if (this.itemStorage != null) { + return this.itemStorage.getAvailableItems(out); + } + return out; + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - if( this.itemStorage != null ) - { - this.itemStorage.removeListener( l ); - } - } + @Override + public IItemList getStorageList() { + if (this.itemStorage != null) { + return this.itemStorage.getStorageList(); + } + return null; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.getAvailableItems( out ); - } - return out; - } + @Override + public AccessRestriction getAccess() { + if (this.itemStorage != null) { + return this.itemStorage.getAccess(); + } + return AccessRestriction.NO_ACCESS; + } - @Override - public IItemList getStorageList() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getStorageList(); - } - return null; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + if (this.itemStorage != null) { + return this.itemStorage.isPrioritized(input); + } + return false; + } - @Override - public AccessRestriction getAccess() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getAccess(); - } - return AccessRestriction.NO_ACCESS; - } + @Override + public boolean canAccept(final IAEItemStack input) { + if (this.itemStorage != null) { + return this.itemStorage.canAccept(input); + } + return false; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.isPrioritized( input ); - } - return false; - } + @Override + public int getPriority() { + if (this.itemStorage != null) { + return this.itemStorage.getPriority(); + } + return 0; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.canAccept( input ); - } - return false; - } + @Override + public int getSlot() { + if (this.itemStorage != null) { + return this.itemStorage.getSlot(); + } + return 0; + } - @Override - public int getPriority() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getPriority(); - } - return 0; - } + @Override + public boolean validForPass(final int i) { + return this.itemStorage.validForPass(i); + } - @Override - public int getSlot() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getSlot(); - } - return 0; - } + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable type, final BaseActionSource src + ) { + if (this.itemStorage != null) { + return this.itemStorage.injectItems(input, type, src); + } + return input; + } - @Override - public boolean validForPass( final int i ) - { - return this.itemStorage.validForPass( i ); - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + if (this.itemStorage != null) { + return this.itemStorage.extractItems(request, mode, src); + } + return null; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.injectItems( input, type, src ); - } - return input; - } + @Override + public StorageChannel getChannel() { + if (this.itemStorage != null) { + return this.itemStorage.getChannel(); + } + return StorageChannel.ITEMS; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( this.itemStorage != null ) - { - return this.itemStorage.extractItems( request, mode, src ); - } - return null; - } + @Override + public double extractAEPower( + final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier + ) { + if (this.wth != null && this.effectiveItem != null) { + if (mode == Actionable.SIMULATE) { + return this.wth.hasPower(this.myPlayer, amt, this.effectiveItem) ? amt + : 0; + } + return this.wth.usePower(this.myPlayer, amt, this.effectiveItem) ? amt : 0; + } + return 0.0; + } - @Override - public StorageChannel getChannel() - { - if( this.itemStorage != null ) - { - return this.itemStorage.getChannel(); - } - return StorageChannel.ITEMS; - } + @Override + public ItemStack getItemStack() { + return this.effectiveItem; + } - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - if( this.wth != null && this.effectiveItem != null ) - { - if( mode == Actionable.SIMULATE ) - { - return this.wth.hasPower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; - } - return this.wth.usePower( this.myPlayer, amt, this.effectiveItem ) ? amt : 0; - } - return 0.0; - } + @Override + public IConfigManager getConfigManager() { + return this.wth.getConfigManager(this.effectiveItem); + } - @Override - public ItemStack getItemStack() - { - return this.effectiveItem; - } + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getActionableNode(); + } - @Override - public IConfigManager getConfigManager() - { - return this.wth.getConfigManager( this.effectiveItem ); - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.NONE; + } - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getActionableNode(); - } + @Override + public void securityBreak() {} - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.NONE; - } + @Override + public IGridNode getActionableNode() { + this.rangeCheck(); + if (this.myWap != null) { + return this.myWap.getActionableNode(); + } + return null; + } - @Override - public void securityBreak() - { + public boolean rangeCheck() { + 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; + } - @Override - public IGridNode getActionableNode() - { - this.rangeCheck(); - if( this.myWap != null ) - { - return this.myWap.getActionableNode(); - } - return null; - } + final IMachineSet tw = this.targetGrid.getMachines(TileWireless.class); - public boolean rangeCheck() - { - this.sqRange = this.myRange = Double.MAX_VALUE; + this.myWap = null; - 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; - } + for (final IGridNode n : tw) { + final IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); + if (this.testWap(wap)) { + this.myWap = wap; + } + } - final IMachineSet tw = this.targetGrid.getMachines( TileWireless.class ); + return this.myWap != null; + } + return false; + } - this.myWap = null; + private boolean testWap(final IWirelessAccessPoint wap) { + double rangeLimit = wap.getRange(); + rangeLimit *= rangeLimit; - for( final IGridNode n : tw ) - { - final IWirelessAccessPoint wap = (IWirelessAccessPoint) n.getMachine(); - if( this.testWap( wap ) ) - { - this.myWap = wap; - } - } + final DimensionalCoord dc = wap.getLocation(); - return this.myWap != null; - } - return false; - } + if (dc.getWorld() == this.myPlayer.worldObj) { + final double offX = dc.x - this.myPlayer.posX; + final double offY = dc.y - this.myPlayer.posY; + final double offZ = dc.z - this.myPlayer.posZ; - private boolean testWap( final IWirelessAccessPoint wap ) - { - double rangeLimit = wap.getRange(); - rangeLimit *= rangeLimit; - - final DimensionalCoord dc = wap.getLocation(); - - if( dc.getWorld() == this.myPlayer.worldObj ) - { - final double offX = dc.x - this.myPlayer.posX; - final double offY = dc.y - this.myPlayer.posY; - final double offZ = dc.z - this.myPlayer.posZ; - - final 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; - } - - @Override - public int getInventorySlot() - { - return this.inventorySlot; - } + final double r = offX * offX + offY * offY + offZ * offZ; + if (r r) { + if (wap.isActive()) { + this.sqRange = r; + this.myRange = Math.sqrt(r); + return true; + } + } + } + return false; + } + @Override + public int getInventorySlot() { + return this.inventorySlot; + } } diff --git a/src/main/java/appeng/hooks/AETrading.java b/src/main/java/appeng/hooks/AETrading.java index bc569031..4abb6d8b 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 appeng.api.AEApi; import appeng.api.definitions.IItemDefinition; @@ -30,95 +31,104 @@ import net.minecraft.item.ItemStack; import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; -import java.util.Random; +public class AETrading implements IVillageTradeHandler { + @Override + public void manipulateTradesForVillager( + final EntityVillager villager, + final MerchantRecipeList recipeList, + final Random random + ) { + final IMaterials materials = AEApi.instance().definitions().materials(); + this.addMerchant(recipeList, materials.silicon(), 1, random, 2); + this.addMerchant(recipeList, materials.certusQuartzCrystal(), 2, random, 4); + this.addMerchant(recipeList, materials.certusQuartzDust(), 1, random, 3); -public class AETrading implements IVillageTradeHandler -{ + this.addTrade( + recipeList, + materials.certusQuartzDust(), + materials.certusQuartzCrystal(), + random, + 2 + ); + } - @Override - public void manipulateTradesForVillager( final EntityVillager villager, final MerchantRecipeList recipeList, final Random random ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); + private void addMerchant( + final MerchantRecipeList list, + final IItemDefinition item, + final int emera, + final Random rand, + final int greed + ) { + for (final ItemStack itemStack : item.maybeStack(1).asSet()) { + // Sell + final ItemStack from = itemStack.copy(); + final ItemStack to = new ItemStack(Items.emerald); - this.addMerchant( recipeList, materials.silicon(), 1, random, 2 ); - this.addMerchant( recipeList, materials.certusQuartzCrystal(), 2, random, 4 ); - this.addMerchant( recipeList, materials.certusQuartzDust(), 1, random, 3 ); + final int multiplier = (Math.abs(rand.nextInt()) % 6); + final int emeraldCost + = emera + (Math.abs(rand.nextInt()) % greed) - multiplier; + final int mood = rand.nextInt() % 2; - this.addTrade( recipeList, materials.certusQuartzDust(), materials.certusQuartzCrystal(), random, 2 ); - } + from.stackSize = multiplier + mood; + to.stackSize = multiplier * emeraldCost - mood; - private void addMerchant( final MerchantRecipeList list, final IItemDefinition item, final int emera, final Random rand, final int greed ) - { - for( final ItemStack itemStack : item.maybeStack( 1 ).asSet() ) - { - // Sell - final ItemStack from = itemStack.copy(); - final ItemStack to = new ItemStack( Items.emerald ); + if (to.stackSize < 0) { + from.stackSize -= to.stackSize; + to.stackSize -= to.stackSize; + } - final int multiplier = ( Math.abs( rand.nextInt() ) % 6 ); - final int emeraldCost = emera + ( Math.abs( rand.nextInt() ) % greed ) - multiplier; - final int mood = rand.nextInt() % 2; + this.addToList(list, from, to); - from.stackSize = multiplier + mood; - to.stackSize = multiplier * emeraldCost - mood; + // Buy + final ItemStack reverseTo = from.copy(); + final ItemStack reverseFrom = to.copy(); - if( to.stackSize < 0 ) - { - from.stackSize -= to.stackSize; - to.stackSize -= to.stackSize; - } + reverseFrom.stackSize *= rand.nextFloat() * 3.0f + 1.0f; - this.addToList( list, from, to ); + this.addToList(list, reverseFrom, reverseTo); + } + } - // Buy - final ItemStack reverseTo = from.copy(); - final ItemStack reverseFrom = to.copy(); + private void addTrade( + final MerchantRecipeList list, + final IItemDefinition inputDefinition, + final IItemDefinition outputDefinition, + final Random rand, + final int conversionVariance + ) { + final Optional maybeInputStack = inputDefinition.maybeStack(1); + final Optional maybeOutputStack = outputDefinition.maybeStack(1); - reverseFrom.stackSize *= rand.nextFloat() * 3.0f + 1.0f; + if (maybeInputStack.isPresent() && maybeOutputStack.isPresent()) { + // Sell + final ItemStack inputStack = maybeInputStack.get().copy(); + final ItemStack outputStack = maybeOutputStack.get().copy(); - this.addToList( list, reverseFrom, reverseTo ); - } - } + inputStack.stackSize + = 1 + (Math.abs(rand.nextInt()) % (1 + conversionVariance)); + outputStack.stackSize = 1; - private void addTrade( final MerchantRecipeList list, final IItemDefinition inputDefinition, final IItemDefinition outputDefinition, final Random rand, final int conversionVariance ) - { - final Optional maybeInputStack = inputDefinition.maybeStack( 1 ); - final Optional maybeOutputStack = outputDefinition.maybeStack( 1 ); + this.addToList(list, inputStack, outputStack); + } + } - if( maybeInputStack.isPresent() && maybeOutputStack.isPresent() ) - { - // Sell - final ItemStack inputStack = maybeInputStack.get().copy(); - final ItemStack outputStack = maybeOutputStack.get().copy(); + private void + addToList(final MerchantRecipeList l, final ItemStack a, final ItemStack b) { + if (a.stackSize < 1) { + a.stackSize = 1; + } + if (b.stackSize < 1) { + b.stackSize = 1; + } - inputStack.stackSize = 1 + ( Math.abs( rand.nextInt() ) % ( 1 + conversionVariance ) ); - outputStack.stackSize = 1; + if (a.stackSize > a.getMaxStackSize()) { + a.stackSize = a.getMaxStackSize(); + } + if (b.stackSize > b.getMaxStackSize()) { + b.stackSize = b.getMaxStackSize(); + } - this.addToList( list, inputStack, outputStack ); - } - } - - private void addToList( final MerchantRecipeList l, final ItemStack a, final 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 ) ); - } + 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 4c49cdf7..1c8d04d6 100644 --- a/src/main/java/appeng/hooks/CompassManager.java +++ b/src/main/java/appeng/hooks/CompassManager.java @@ -18,104 +18,98 @@ package appeng.hooks; +import java.util.HashMap; +import java.util.Iterator; import appeng.core.sync.network.NetworkHandler; import appeng.core.sync.packets.PacketCompassRequest; -import java.util.HashMap; -import java.util.Iterator; +public class CompassManager { + public static final CompassManager INSTANCE = new CompassManager(); + private final HashMap requests + = new HashMap(); + public void postResult( + final long attunement, + final int x, + final int y, + final int z, + final CompassResult result + ) { + final CompassRequest r = new CompassRequest(attunement, x, y, z); + this.requests.put(r, result); + } -public class CompassManager -{ + public CompassResult + getCompassDirection(final long attunement, final int x, final int y, final int z) { + final long now = System.currentTimeMillis(); - public static final CompassManager INSTANCE = new CompassManager(); - private final HashMap requests = new HashMap(); + final Iterator i = this.requests.values().iterator(); + while (i.hasNext()) { + final CompassResult res = i.next(); + final long diff = now - res.getTime(); + if (diff > 20000) { + i.remove(); + } + } - public void postResult( final long attunement, final int x, final int y, final int z, final CompassResult result ) - { - final CompassRequest r = new CompassRequest( attunement, x, y, z ); - this.requests.put( r, result ); - } + final CompassRequest r = new CompassRequest(attunement, x, y, z); + CompassResult res = this.requests.get(r); - public CompassResult getCompassDirection( final long attunement, final int x, final int y, final int z ) - { - final long now = System.currentTimeMillis(); + if (res == null) { + res = new CompassResult(false, true, 0); + this.requests.put(r, res); + this.requestUpdate(r); + } else if (now - res.getTime() > 1000 * 3) { + if (!res.isRequested()) { + res.setRequested(true); + this.requestUpdate(r); + } + } - final Iterator i = this.requests.values().iterator(); - while( i.hasNext() ) - { - final CompassResult res = i.next(); - final long diff = now - res.getTime(); - if( diff > 20000 ) - { - i.remove(); - } - } + return res; + } - final CompassRequest r = new CompassRequest( attunement, x, y, z ); - CompassResult res = this.requests.get( r ); + private void requestUpdate(final CompassRequest r) { + NetworkHandler.instance.sendToServer( + new PacketCompassRequest(r.attunement, r.cx, r.cz, r.cdy) + ); + } - if( res == null ) - { - res = new CompassResult( false, true, 0 ); - this.requests.put( r, res ); - this.requestUpdate( r ); - } - else if( now - res.getTime() > 1000 * 3 ) - { - if( !res.isRequested() ) - { - res.setRequested( true ); - this.requestUpdate( r ); - } - } + private static class CompassRequest { + private final int hash; + private final long attunement; + private final int cx; + private final int cdy; + private final int cz; - return res; - } + public CompassRequest( + final long attunement, final int x, final int y, final 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(); + } - private void requestUpdate( final CompassRequest r ) - { - NetworkHandler.instance.sendToServer( new PacketCompassRequest( r.attunement, r.cx, r.cz, r.cdy ) ); - } + @Override + public int hashCode() { + return this.hash; + } - private static class CompassRequest - { - - private final int hash; - private final long attunement; - private final int cx; - private final int cdy; - private final int cz; - - public CompassRequest( final long attunement, final int x, final int y, final 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(); - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final CompassRequest other = (CompassRequest) obj; - return this.attunement == other.attunement && this.cx == other.cx && this.cdy == other.cdy && this.cz == other.cz; - } - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final CompassRequest other = (CompassRequest) obj; + return this.attunement == other.attunement && this.cx == other.cx + && this.cdy == other.cdy && this.cz == other.cz; + } + } } diff --git a/src/main/java/appeng/hooks/CompassResult.java b/src/main/java/appeng/hooks/CompassResult.java index 53c0982c..ab65ec0b 100644 --- a/src/main/java/appeng/hooks/CompassResult.java +++ b/src/main/java/appeng/hooks/CompassResult.java @@ -18,51 +18,41 @@ package appeng.hooks; +public class CompassResult { + private final boolean hasResult; + private final boolean spin; + private final double rad; + private final long time; + private boolean requested = false; -public class CompassResult -{ + public CompassResult(final boolean hasResult, final boolean spin, final double rad) { + this.hasResult = hasResult; + this.spin = spin; + this.rad = rad; + this.time = System.currentTimeMillis(); + } - private final boolean hasResult; - private final boolean spin; - private final double rad; - private final long time; - private boolean requested = false; + public boolean isValidResult() { + return this.hasResult; + } - public CompassResult( final boolean hasResult, final boolean spin, final double rad ) - { - this.hasResult = hasResult; - this.spin = spin; - this.rad = rad; - this.time = System.currentTimeMillis(); - } + public boolean isSpin() { + return this.spin; + } - public boolean isValidResult() - { - return this.hasResult; - } + public double getRad() { + return this.rad; + } - public boolean isSpin() - { - return this.spin; - } + boolean isRequested() { + return this.requested; + } - public double getRad() - { - return this.rad; - } + void setRequested(final boolean requested) { + this.requested = requested; + } - boolean isRequested() - { - return this.requested; - } - - void setRequested( final boolean requested ) - { - this.requested = requested; - } - - long getTime() - { - return this.time; - } + long getTime() { + return this.time; + } } diff --git a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java index 8ce43c64..6511a295 100644 --- a/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java +++ b/src/main/java/appeng/hooks/DispenserBehaviorTinyTNT.java @@ -18,7 +18,6 @@ package appeng.hooks; - import appeng.entity.EntityTinyTNTPrimed; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; @@ -27,21 +26,20 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; - -public final class DispenserBehaviorTinyTNT extends BehaviorDefaultDispenseItem -{ - - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, final ItemStack dispensedItem ) - { - final EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); - final World world = dispenser.getWorld(); - final int i = dispenser.getXInt() + enumfacing.getFrontOffsetX(); - final int j = dispenser.getYInt() + enumfacing.getFrontOffsetY(); - final int k = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); - final EntityTinyTNTPrimed primedTinyTNTEntity = new EntityTinyTNTPrimed( world, i + 0.5F, j + 0.5F, k + 0.5F, null ); - world.spawnEntityInWorld( primedTinyTNTEntity ); - --dispensedItem.stackSize; - return dispensedItem; - } +public final class DispenserBehaviorTinyTNT extends BehaviorDefaultDispenseItem { + @Override + protected ItemStack + dispenseStack(final IBlockSource dispenser, final ItemStack dispensedItem) { + final EnumFacing enumfacing + = BlockDispenser.func_149937_b(dispenser.getBlockMetadata()); + final World world = dispenser.getWorld(); + final int i = dispenser.getXInt() + enumfacing.getFrontOffsetX(); + final int j = dispenser.getYInt() + enumfacing.getFrontOffsetY(); + final int k = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); + final 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 45fbc6d4..12130a2b 100644 --- a/src/main/java/appeng/hooks/DispenserBlockTool.java +++ b/src/main/java/appeng/hooks/DispenserBlockTool.java @@ -18,7 +18,6 @@ package appeng.hooks; - import appeng.util.Platform; import net.minecraft.block.BlockDispenser; import net.minecraft.dispenser.BehaviorDefaultDispenseItem; @@ -29,29 +28,36 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraft.world.WorldServer; +public final class DispenserBlockTool extends BehaviorDefaultDispenseItem { + @Override + protected ItemStack + dispenseStack(final IBlockSource dispenser, final ItemStack dispensedItem) { + final Item i = dispensedItem.getItem(); + if (i instanceof IBlockTool) { + final EnumFacing enumfacing + = BlockDispenser.func_149937_b(dispenser.getBlockMetadata()); + final IBlockTool tm = (IBlockTool) i; -public final class DispenserBlockTool extends BehaviorDefaultDispenseItem -{ + final World w = dispenser.getWorld(); + if (w instanceof WorldServer) { + final int x = dispenser.getXInt() + enumfacing.getFrontOffsetX(); + final int y = dispenser.getYInt() + enumfacing.getFrontOffsetY(); + final int z = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, final ItemStack dispensedItem ) - { - final Item i = dispensedItem.getItem(); - if( i instanceof IBlockTool ) - { - final EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); - final IBlockTool tm = (IBlockTool) i; - - final World w = dispenser.getWorld(); - if( w instanceof WorldServer ) - { - final int x = dispenser.getXInt() + enumfacing.getFrontOffsetX(); - final int y = dispenser.getYInt() + enumfacing.getFrontOffsetY(); - final int z = dispenser.getZInt() + enumfacing.getFrontOffsetZ(); - - tm.onItemUse( dispensedItem, Platform.getPlayer( (WorldServer) w ), w, x, y, z, enumfacing.ordinal(), 0.5f, 0.5f, 0.5f ); - } - } - return dispensedItem; - } + tm.onItemUse( + dispensedItem, + Platform.getPlayer((WorldServer) w), + w, + x, + y, + z, + enumfacing.ordinal(), + 0.5f, + 0.5f, + 0.5f + ); + } + } + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/DispenserMatterCannon.java b/src/main/java/appeng/hooks/DispenserMatterCannon.java index 187d51e8..2ec75152 100644 --- a/src/main/java/appeng/hooks/DispenserMatterCannon.java +++ b/src/main/java/appeng/hooks/DispenserMatterCannon.java @@ -18,7 +18,6 @@ package appeng.hooks; - import appeng.items.tools.powered.ToolMassCannon; import appeng.util.Platform; import net.minecraft.block.BlockDispenser; @@ -32,41 +31,37 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ForgeDirection; +public final class DispenserMatterCannon extends BehaviorDefaultDispenseItem { + @Override + protected ItemStack + dispenseStack(final IBlockSource dispenser, ItemStack dispensedItem) { + final Item i = dispensedItem.getItem(); + if (i instanceof ToolMassCannon) { + final EnumFacing enumfacing + = BlockDispenser.func_149937_b(dispenser.getBlockMetadata()); + ForgeDirection dir = ForgeDirection.UNKNOWN; + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + if (enumfacing.getFrontOffsetX() == d.offsetX + && enumfacing.getFrontOffsetY() == d.offsetY + && enumfacing.getFrontOffsetZ() == d.offsetZ) { + dir = d; + } + } -public final class DispenserMatterCannon extends BehaviorDefaultDispenseItem -{ + final ToolMassCannon tm = (ToolMassCannon) i; - @Override - protected ItemStack dispenseStack( final IBlockSource dispenser, ItemStack dispensedItem ) - { - final Item i = dispensedItem.getItem(); - if( i instanceof ToolMassCannon ) - { - final EnumFacing enumfacing = BlockDispenser.func_149937_b( dispenser.getBlockMetadata() ); - ForgeDirection dir = ForgeDirection.UNKNOWN; - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - if( enumfacing.getFrontOffsetX() == d.offsetX && enumfacing.getFrontOffsetY() == d.offsetY && enumfacing.getFrontOffsetZ() == d.offsetZ ) - { - dir = d; - } - } + final World w = dispenser.getWorld(); + if (w instanceof WorldServer) { + final EntityPlayer p = Platform.getPlayer((WorldServer) w); + Platform.configurePlayer(p, dir, dispenser.getBlockTileEntity()); - final ToolMassCannon tm = (ToolMassCannon) i; + p.posX += dir.offsetX; + p.posY += dir.offsetY; + p.posZ += dir.offsetZ; - final World w = dispenser.getWorld(); - if( w instanceof WorldServer ) - { - final EntityPlayer p = Platform.getPlayer( (WorldServer) w ); - Platform.configurePlayer( p, dir, dispenser.getBlockTileEntity() ); - - p.posX += dir.offsetX; - p.posY += dir.offsetY; - p.posZ += dir.offsetZ; - - dispensedItem = tm.onItemRightClick( dispensedItem, w, p ); - } - } - return dispensedItem; - } + dispensedItem = tm.onItemRightClick(dispensedItem, w, p); + } + } + return dispensedItem; + } } diff --git a/src/main/java/appeng/hooks/IBlockTool.java b/src/main/java/appeng/hooks/IBlockTool.java index 9bff76a9..50ac6ef6 100644 --- a/src/main/java/appeng/hooks/IBlockTool.java +++ b/src/main/java/appeng/hooks/IBlockTool.java @@ -18,14 +18,21 @@ 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 ); +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 + ); } diff --git a/src/main/java/appeng/hooks/TickHandler.java b/src/main/java/appeng/hooks/TickHandler.java index 75fc92f0..f1550045 100644 --- a/src/main/java/appeng/hooks/TickHandler.java +++ b/src/main/java/appeng/hooks/TickHandler.java @@ -18,6 +18,8 @@ package appeng.hooks; +import java.util.*; +import java.util.concurrent.TimeUnit; import appeng.api.AEApi; import appeng.api.networking.IGridNode; @@ -46,290 +48,241 @@ import net.minecraft.world.World; import net.minecraftforge.event.world.ChunkEvent; import net.minecraftforge.event.world.WorldEvent; -import java.util.*; -import java.util.concurrent.TimeUnit; +public class TickHandler { + public static final TickHandler INSTANCE = new TickHandler(); + private final Queue> serverQueue + = new LinkedList>(); + private final Multimap craftingJobs = LinkedListMultimap.create(); + private final WeakHashMap>> callQueue + = new WeakHashMap>>(); + private final HandlerRep server = new HandlerRep(); + private final HandlerRep client = new HandlerRep(); + private final HashMap cliPlayerColors + = new HashMap(); + private final HashMap srvPlayerColors + = new HashMap(); + private CableRenderMode crm = CableRenderMode.Standard; + public HashMap getPlayerColors() { + if (Platform.isServer()) { + return this.srvPlayerColors; + } + return this.cliPlayerColors; + } -public class TickHandler -{ + public void addCallable(final World w, final IWorldCallable c) { + if (w == null) { + this.serverQueue.add(c); + } else { + Queue> queue = this.callQueue.get(w); - public static final TickHandler INSTANCE = new TickHandler(); - private final Queue> serverQueue = new LinkedList>(); - private final Multimap craftingJobs = LinkedListMultimap.create(); - private final WeakHashMap>> callQueue = new WeakHashMap>>(); - private final HandlerRep server = new HandlerRep(); - private final HandlerRep client = new HandlerRep(); - private final HashMap cliPlayerColors = new HashMap(); - private final HashMap srvPlayerColors = new HashMap(); - private CableRenderMode crm = CableRenderMode.Standard; + if (queue == null) { + queue = new LinkedList>(); + this.callQueue.put(w, queue); + } - public HashMap getPlayerColors() - { - if( Platform.isServer() ) - { - return this.srvPlayerColors; - } - return this.cliPlayerColors; - } + queue.add(c); + } + } - public void addCallable( final World w, final IWorldCallable c ) - { - if( w == null ) - { - this.serverQueue.add( c ); - } - else - { - Queue> queue = this.callQueue.get( w ); + public void addInit(final AEBaseTile tile) { + if (Platform.isServer( + )) // for no there is no reason to care about this on the client... + { + this.getRepo().tiles.add(tile); + } + } - if( queue == null ) - { - queue = new LinkedList>(); - this.callQueue.put( w, queue ); - } + private HandlerRep getRepo() { + if (Platform.isServer()) { + return this.server; + } + return this.client; + } - queue.add( c ); - } - } + public void addNetwork(final 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 addInit( final AEBaseTile tile ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().tiles.add( tile ); - } - } + public void removeNetwork(final Grid grid) { + if (Platform.isServer( + )) // for no there is no reason to care about this on the client... + { + this.getRepo().networks.remove(grid); + } + } - private HandlerRep getRepo() - { - if( Platform.isServer() ) - { - return this.server; - } - return this.client; - } + public Iterable getGridList() { + return this.getRepo().networks; + } - public void addNetwork( final 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 shutdown() { + this.getRepo().clear(); + } - public void removeNetwork( final Grid grid ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - this.getRepo().networks.remove( grid ); - } - } + @SubscribeEvent + public void unloadWorld(final WorldEvent.Unload ev) { + if (Platform.isServer( + )) // for no there is no reason to care about this on the client... + { + final LinkedList toDestroy = new LinkedList(); - public Iterable getGridList() - { - return this.getRepo().networks; - } + for (final Grid g : this.getRepo().networks) { + for (final IGridNode n : g.getNodes()) { + if (n.getWorld() == ev.world) { + toDestroy.add(n); + } + } + } - public void shutdown() - { - this.getRepo().clear(); - } + for (final IGridNode n : toDestroy) { + n.destroy(); + } + } + } - @SubscribeEvent - public void unloadWorld( final WorldEvent.Unload ev ) - { - if( Platform.isServer() ) // for no there is no reason to care about this on the client... - { - final LinkedList toDestroy = new LinkedList(); + @SubscribeEvent + public void onChunkLoad(final ChunkEvent.Load load) { + for (final Object te : load.getChunk().chunkTileEntityMap.values()) { + if (te instanceof AEBaseTile) { + ((AEBaseTile) te).onChunkLoad(); + } + } + } - for( final Grid g : this.getRepo().networks ) - { - for( final IGridNode n : g.getNodes() ) - { - if( n.getWorld() == ev.world ) - { - toDestroy.add( n ); - } - } - } + @SubscribeEvent + public void onTick(final TickEvent ev) { + if (ev.type == Type.CLIENT && ev.phase == Phase.START) { + this.tickColors(this.cliPlayerColors); + EntityFloatingItem.ageStatic = (EntityFloatingItem.ageStatic + 1) % 60000; + final CableRenderMode currentMode + = AEApi.instance().partHelper().getCableRenderMode(); + if (currentMode != this.crm) { + this.crm = currentMode; + CommonHelper.proxy.triggerUpdates(); + } + } - for( final IGridNode n : toDestroy ) - { - n.destroy(); - } - } - } + if (ev.type == Type.WORLD && ev.phase == Phase.END) { + final WorldTickEvent wte = (WorldTickEvent) ev; + synchronized (this.craftingJobs) { + final Collection jobSet = this.craftingJobs.get(wte.world); + if (!jobSet.isEmpty()) { + final int simTime = Math.max( + 1, + AEConfig.instance.craftingCalculationTimePerTick / jobSet.size() + ); + final Iterator i = jobSet.iterator(); + while (i.hasNext()) { + final CraftingJob cj = i.next(); + if (!cj.simulateFor(simTime)) { + i.remove(); + } + } + } + } + } - @SubscribeEvent - public void onChunkLoad( final ChunkEvent.Load load ) - { - for( final Object te : load.getChunk().chunkTileEntityMap.values() ) - { - if( te instanceof AEBaseTile ) - { - ( (AEBaseTile) te ).onChunkLoad(); - } - } - } + // for no there is no reason to care about this on the client... + else if (ev.type == Type.SERVER && ev.phase == Phase.END) { + this.tickColors(this.srvPlayerColors); + // ready tiles. + final HandlerRep repo = this.getRepo(); + while (!repo.tiles.isEmpty()) { + final AEBaseTile bt = repo.tiles.poll(); + if (!bt.isInvalid()) { + bt.onReady(); + } + } - @SubscribeEvent - public void onTick( final TickEvent ev ) - { + // tick networks. + for (final Grid g : this.getRepo().networks) { + g.update(); + } - if( ev.type == Type.CLIENT && ev.phase == Phase.START ) - { - this.tickColors( this.cliPlayerColors ); - EntityFloatingItem.ageStatic = ( EntityFloatingItem.ageStatic + 1 ) % 60000; - final CableRenderMode currentMode = AEApi.instance().partHelper().getCableRenderMode(); - if( currentMode != this.crm ) - { - this.crm = currentMode; - CommonHelper.proxy.triggerUpdates(); - } - } + // cross world queue. + this.processQueue(this.serverQueue, null); + } - if( ev.type == Type.WORLD && ev.phase == Phase.END ) - { - final WorldTickEvent wte = (WorldTickEvent) ev; - synchronized( this.craftingJobs ) - { - final Collection jobSet = this.craftingJobs.get( wte.world ); - if( !jobSet.isEmpty() ) - { - final int simTime = Math.max( 1, AEConfig.instance.craftingCalculationTimePerTick / jobSet.size() ); - final Iterator i = jobSet.iterator(); - while( i.hasNext() ) - { - final CraftingJob cj = i.next(); - if( !cj.simulateFor( simTime ) ) - { - i.remove(); - } - } - } - } - } + // world synced queue(s) + if (ev.type == Type.WORLD && ev.phase == Phase.START) { + final World world = ((WorldTickEvent) ev).world; + final Queue> queue = this.callQueue.get(world); + this.processQueue(queue, world); + } + } - // for no there is no reason to care about this on the client... - else if( ev.type == Type.SERVER && ev.phase == Phase.END ) - { - this.tickColors( this.srvPlayerColors ); - // ready tiles. - final HandlerRep repo = this.getRepo(); - while( !repo.tiles.isEmpty() ) - { - final AEBaseTile bt = repo.tiles.poll(); - if( !bt.isInvalid() ) - { - bt.onReady(); - } - } + private void tickColors(final HashMap playerSet) { + final Iterator i = playerSet.values().iterator(); + while (i.hasNext()) { + final PlayerColor pc = i.next(); + if (pc.ticksLeft <= 0) { + i.remove(); + } + pc.ticksLeft--; + } + } - // tick networks. - for( final Grid g : this.getRepo().networks ) - { - g.update(); - } + private void processQueue(final Queue> queue, final World world) { + if (queue == null) { + return; + } - // cross world queue. - this.processQueue( this.serverQueue, null ); - } + final Stopwatch sw = Stopwatch.createStarted(); - // world synced queue(s) - if( ev.type == Type.WORLD && ev.phase == Phase.START ) - { - final World world = ( (WorldTickEvent) ev ).world; - final Queue> queue = this.callQueue.get( world ); - this.processQueue( queue, world ); - } - } + IWorldCallable c = null; + while ((c = queue.poll()) != null) { + try { + c.call(world); - private void tickColors( final HashMap playerSet ) - { - final Iterator i = playerSet.values().iterator(); - while( i.hasNext() ) - { - final PlayerColor pc = i.next(); - if( pc.ticksLeft <= 0 ) - { - i.remove(); - } - pc.ticksLeft--; - } - } + if (sw.elapsed(TimeUnit.MILLISECONDS) > 50) { + break; + } + } catch (final Exception e) { + AELog.debug(e); + } + } - private void processQueue( final Queue> queue, final World world ) - { - if( queue == null ) - { - return; - } + // long time = sw.elapsed( TimeUnit.MILLISECONDS ); + // if ( time > 0 ) + // AELog.info( "processQueue Time: " + time + "ms" ); + } - final Stopwatch sw = Stopwatch.createStarted(); + public void + registerCraftingSimulation(final World world, final CraftingJob craftingJob) { + synchronized (this.craftingJobs) { + this.craftingJobs.put(world, craftingJob); + } + } - IWorldCallable c = null; - while( ( c = queue.poll() ) != null ) - { - try - { - c.call( world ); + private static class HandlerRep { + private Queue tiles = new LinkedList(); - if( sw.elapsed( TimeUnit.MILLISECONDS ) > 50 ) - { - break; - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } + private Collection networks = new NetworkList(); - // long time = sw.elapsed( TimeUnit.MILLISECONDS ); - // if ( time > 0 ) - // AELog.info( "processQueue Time: " + time + "ms" ); - } + private void clear() { + this.tiles = new LinkedList(); + this.networks = new NetworkList(); + } + } - public void registerCraftingSimulation( final World world, final CraftingJob craftingJob ) - { - synchronized( this.craftingJobs ) - { - this.craftingJobs.put( world, craftingJob ); - } - } + public static class PlayerColor { + public final AEColor myColor; + private final int myEntity; + private int ticksLeft; - private static class HandlerRep - { + public PlayerColor(final int id, final AEColor col, final int ticks) { + this.myEntity = id; + this.myColor = col; + this.ticksLeft = ticks; + } - private Queue tiles = new LinkedList(); - - private Collection networks = new NetworkList(); - - private void clear() - { - this.tiles = new LinkedList(); - this.networks = new NetworkList(); - } - } - - - public static class PlayerColor - { - - public final AEColor myColor; - private final int myEntity; - private int ticksLeft; - - public PlayerColor( final int id, final AEColor col, final int ticks ) - { - this.myEntity = id; - this.myColor = col; - this.ticksLeft = ticks; - } - - public PacketPaintedEntity getPacket() - { - return new PacketPaintedEntity( this.myEntity, this.myColor, this.ticksLeft ); - } - } + public PacketPaintedEntity getPacket() { + return new PacketPaintedEntity(this.myEntity, this.myColor, this.ticksLeft); + } + } } diff --git a/src/main/java/appeng/integration/IIntegrationModule.java b/src/main/java/appeng/integration/IIntegrationModule.java index 64a7a8ae..37a554c8 100644 --- a/src/main/java/appeng/integration/IIntegrationModule.java +++ b/src/main/java/appeng/integration/IIntegrationModule.java @@ -18,10 +18,8 @@ package appeng.integration; +public interface IIntegrationModule { + void init() throws Throwable; -public interface IIntegrationModule -{ - void init() throws Throwable; - - void postInit(); + void postInit(); } diff --git a/src/main/java/appeng/integration/IntegrationHelper.java b/src/main/java/appeng/integration/IntegrationHelper.java index 783bbd48..e0c88818 100644 --- a/src/main/java/appeng/integration/IntegrationHelper.java +++ b/src/main/java/appeng/integration/IntegrationHelper.java @@ -18,12 +18,8 @@ package appeng.integration; - -public class IntegrationHelper -{ - - public static void testClassExistence( final Object o, final Class clz ) - { - clz.isInstance( o ); - } +public class IntegrationHelper { + public static void testClassExistence(final Object o, final Class clz) { + clz.isInstance(o); + } } diff --git a/src/main/java/appeng/integration/IntegrationNode.java b/src/main/java/appeng/integration/IntegrationNode.java index cd01e1b8..939afe4e 100644 --- a/src/main/java/appeng/integration/IntegrationNode.java +++ b/src/main/java/appeng/integration/IntegrationNode.java @@ -18,6 +18,7 @@ package appeng.integration; +import java.lang.reflect.Field; import appeng.api.exceptions.ModNotInstalled; import appeng.core.AEConfig; @@ -25,154 +26,142 @@ import appeng.core.AELog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModAPIManager; -import java.lang.reflect.Field; +public final class IntegrationNode { + private final String displayName; + private final String modID; + private final IntegrationType shortName; + private IntegrationStage state = IntegrationStage.PRE_INIT; + private IntegrationStage failedStage = IntegrationStage.PRE_INIT; + private Throwable exception = null; + private String name = null; + private Class classValue = null; + private Object instance; + private IIntegrationModule mod = null; + public IntegrationNode( + final String displayName, + final String modID, + final IntegrationType shortName, + final String name + ) { + this.displayName = displayName; + this.shortName = shortName; + this.modID = modID; + this.name = name; + } -public final class IntegrationNode -{ + @Override + public String toString() { + return this.getShortName().name() + ':' + this.getState().name(); + } - private final String displayName; - private final String modID; - private final IntegrationType shortName; - private IntegrationStage state = IntegrationStage.PRE_INIT; - private IntegrationStage failedStage = IntegrationStage.PRE_INIT; - private Throwable exception = null; - private String name = null; - private Class classValue = null; - private Object instance; - private IIntegrationModule mod = null; + boolean isActive() { + if (this.getState() == IntegrationStage.PRE_INIT) { + this.call(IntegrationStage.PRE_INIT); + } - public IntegrationNode( final String displayName, final String modID, final IntegrationType shortName, final String name ) - { - this.displayName = displayName; - this.shortName = shortName; - this.modID = modID; - this.name = name; - } + return this.getState() != IntegrationStage.FAILED; + } - @Override - public String toString() - { - return this.getShortName().name() + ':' + this.getState().name(); - } + void call(final IntegrationStage stage) { + if (this.getState() != IntegrationStage.FAILED) { + if (this.getState().ordinal() > stage.ordinal()) { + return; + } - boolean isActive() - { - if( this.getState() == IntegrationStage.PRE_INIT ) - { - this.call( IntegrationStage.PRE_INIT ); - } + try { + switch (stage) { + case PRE_INIT: + final ModAPIManager apiManager = ModAPIManager.INSTANCE; + boolean enabled = this.modID == null + || Loader.isModLoaded(this.modID) + || apiManager.hasAPI(this.modID); - return this.getState() != IntegrationStage.FAILED; - } + 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." + ); + final String mode = AEConfig.instance + .get( + "ModIntegration", + this.displayName.replace(" ", ""), + "AUTO" + ) + .getString(); - void call( final IntegrationStage stage ) - { - if( this.getState() != IntegrationStage.FAILED ) - { - if( this.getState().ordinal() > stage.ordinal() ) - { - return; - } + if (mode.toUpperCase().equals("ON")) { + enabled = true; + } + if (mode.toUpperCase().equals("OFF")) { + enabled = false; + } - try - { - switch( stage ) - { - case PRE_INIT: - final ModAPIManager apiManager = ModAPIManager.INSTANCE; - boolean enabled = this.modID == null || Loader.isModLoaded( this.modID ) || apiManager.hasAPI( this.modID ); + if (enabled) { + this.classValue + = this.getClass().getClassLoader().loadClass(this.name); + this.mod + = (IIntegrationModule) this.classValue.getConstructor() + .newInstance(); + final Field f = this.classValue.getField("instance"); + f.set(this.classValue, this.setInstance(this.mod)); + } else { + throw new ModNotInstalled(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." ); - final String mode = AEConfig.instance.get( "ModIntegration", this.displayName.replace( " ", "" ), "AUTO" ).getString(); + this.setState(IntegrationStage.INIT); - if( mode.toUpperCase().equals( "ON" ) ) - { - enabled = true; - } - if( mode.toUpperCase().equals( "OFF" ) ) - { - enabled = false; - } + break; + case INIT: + this.mod.init(); + this.setState(IntegrationStage.POST_INIT); - if( enabled ) - { - this.classValue = this.getClass().getClassLoader().loadClass( this.name ); - this.mod = (IIntegrationModule) this.classValue.getConstructor().newInstance(); - final Field f = this.classValue.getField( "instance" ); - f.set( this.classValue, this.setInstance( this.mod ) ); - } - else - { - throw new ModNotInstalled( this.modID ); - } + break; + case POST_INIT: + this.mod.postInit(); + this.setState(IntegrationStage.READY); - this.setState( IntegrationStage.INIT ); + break; + case FAILED: + default: + break; + } + } catch (final Throwable t) { + this.failedStage = stage; + this.exception = t; + this.setState(IntegrationStage.FAILED); + } + } - break; - case INIT: - this.mod.init(); - this.setState( IntegrationStage.POST_INIT ); + if (stage == IntegrationStage.POST_INIT) { + if (this.getState() == IntegrationStage.FAILED) { + AELog.info(this.displayName + " - Integration Disabled"); + if (!(this.exception instanceof ModNotInstalled)) { + AELog.integration(this.exception); + } + } else { + AELog.info(this.displayName + " - Integration Enable"); + } + } + } - break; - case POST_INIT: - this.mod.postInit(); - this.setState( IntegrationStage.READY ); + Object getInstance() { + return this.instance; + } - break; - case FAILED: - default: - break; - } - } - catch( final Throwable t ) - { - this.failedStage = stage; - this.exception = t; - this.setState( IntegrationStage.FAILED ); - } - } + private Object setInstance(final Object instance) { + this.instance = instance; + return instance; + } - if( stage == IntegrationStage.POST_INIT ) - { - if( this.getState() == IntegrationStage.FAILED ) - { - AELog.info( this.displayName + " - Integration Disabled" ); - if( !( this.exception instanceof ModNotInstalled ) ) - { - AELog.integration( this.exception ); - } - } - else - { - AELog.info( this.displayName + " - Integration Enable" ); - } - } - } + IntegrationType getShortName() { + return this.shortName; + } - Object getInstance() - { - return this.instance; - } + IntegrationStage getState() { + return this.state; + } - private Object setInstance( final Object instance ) - { - this.instance = instance; - return instance; - } - - IntegrationType getShortName() - { - return this.shortName; - } - - IntegrationStage getState() - { - return this.state; - } - - private void setState( final IntegrationStage state ) - { - this.state = state; - } + private void setState(final IntegrationStage state) { + this.state = state; + } } diff --git a/src/main/java/appeng/integration/IntegrationRegistry.java b/src/main/java/appeng/integration/IntegrationRegistry.java index 4e89feff..53c804cf 100644 --- a/src/main/java/appeng/integration/IntegrationRegistry.java +++ b/src/main/java/appeng/integration/IntegrationRegistry.java @@ -18,101 +18,87 @@ package appeng.integration; +import java.util.Collection; +import java.util.LinkedList; +import javax.annotation.Nonnull; import cpw.mods.fml.relauncher.FMLLaunchHandler; import cpw.mods.fml.relauncher.Side; -import javax.annotation.Nonnull; -import java.util.Collection; -import java.util.LinkedList; +public enum IntegrationRegistry { + INSTANCE; + private static final String PACKAGE_PREFIX = "appeng.integration.modules."; -public enum IntegrationRegistry -{ - INSTANCE; + private final Collection modules = new LinkedList(); - private static final String PACKAGE_PREFIX = "appeng.integration.modules."; + public void add(final IntegrationType type) { + if (type.side == IntegrationSide.CLIENT + && FMLLaunchHandler.side() == Side.SERVER) { + return; + } - private final Collection modules = new LinkedList(); + if (type.side == IntegrationSide.SERVER + && FMLLaunchHandler.side() == Side.CLIENT) { + return; + } - public void add( final IntegrationType type ) - { - if( type.side == IntegrationSide.CLIENT && FMLLaunchHandler.side() == Side.SERVER ) - { - return; - } + this.modules.add(new IntegrationNode( + type.dspName, type.modID, type, PACKAGE_PREFIX + type.name() + )); + } - if( type.side == IntegrationSide.SERVER && FMLLaunchHandler.side() == Side.CLIENT ) - { - return; - } + public void init() { + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.PRE_INIT); + } - this.modules.add( new IntegrationNode( type.dspName, type.modID, type, PACKAGE_PREFIX + type.name() ) ); - } + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.INIT); + } + } - public void init() - { - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.PRE_INIT ); - } + public void postInit() { + for (final IntegrationNode node : this.modules) { + node.call(IntegrationStage.POST_INIT); + } + } - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.INIT ); - } - } + public String getStatus() { + final StringBuilder builder = new StringBuilder(this.modules.size() * 3); - public void postInit() - { - for( final IntegrationNode node : this.modules ) - { - node.call( IntegrationStage.POST_INIT ); - } - } + for (final IntegrationNode node : this.modules) { + if (builder.length() != 0) { + builder.append(", "); + } - public String getStatus() - { - final StringBuilder builder = new StringBuilder( this.modules.size() * 3 ); + final String integrationState = node.getShortName() + ":" + + (node.getState() == IntegrationStage.FAILED ? "OFF" : "ON"); + builder.append(integrationState); + } - for( final IntegrationNode node : this.modules ) - { - if( builder.length() != 0 ) - { - builder.append( ", " ); - } + return builder.toString(); + } - final String integrationState = node.getShortName() + ":" + ( node.getState() == IntegrationStage.FAILED ? "OFF" : "ON" ); - builder.append( integrationState ); - } + public boolean isEnabled(final IntegrationType name) { + for (final IntegrationNode node : this.modules) { + if (node.getShortName() == name) { + return node.isActive(); + } + } + return false; + } - return builder.toString(); - } - - public boolean isEnabled( final IntegrationType name ) - { - for( final IntegrationNode node : this.modules ) - { - if( node.getShortName() == name ) - { - return node.isActive(); - } - } - return false; - } - - @Nonnull - public Object getInstance( final IntegrationType name ) - { - for( final IntegrationNode node : this.modules ) - { - if( node.getShortName() == name && node.isActive() ) - { - return node.getInstance(); - } - } - - throw new IllegalStateException( "integration with " + name.name() + " is disabled." ); - } + @Nonnull + public Object getInstance(final IntegrationType name) { + for (final IntegrationNode node : this.modules) { + if (node.getShortName() == name && node.isActive()) { + return node.getInstance(); + } + } + throw new IllegalStateException( + "integration with " + name.name() + " is disabled." + ); + } } diff --git a/src/main/java/appeng/integration/IntegrationSide.java b/src/main/java/appeng/integration/IntegrationSide.java index 25fd40a4..a632332b 100644 --- a/src/main/java/appeng/integration/IntegrationSide.java +++ b/src/main/java/appeng/integration/IntegrationSide.java @@ -18,8 +18,4 @@ package appeng.integration; - -public enum IntegrationSide -{ - CLIENT, SERVER, BOTH -} +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 628cf5d4..828a42d7 100644 --- a/src/main/java/appeng/integration/IntegrationStage.java +++ b/src/main/java/appeng/integration/IntegrationStage.java @@ -18,12 +18,13 @@ package appeng.integration; +public enum IntegrationStage { -public enum IntegrationStage -{ + PRE_INIT, + INIT, + POST_INIT, - PRE_INIT, INIT, POST_INIT, - - FAILED, READY + FAILED, + READY } diff --git a/src/main/java/appeng/integration/IntegrationType.java b/src/main/java/appeng/integration/IntegrationType.java index 413d0b0f..0c94984e 100644 --- a/src/main/java/appeng/integration/IntegrationType.java +++ b/src/main/java/appeng/integration/IntegrationType.java @@ -18,66 +18,64 @@ package appeng.integration; +public enum IntegrationType { + IC2(IntegrationSide.BOTH, "Industrial Craft 2", "IC2"), -public enum IntegrationType -{ - 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" ), + BuildCraftCore(IntegrationSide.BOTH, "BuildCraft Core", "BuildCraft|Core"), - BuildCraftCore( IntegrationSide.BOTH, "BuildCraft Core", "BuildCraft|Core" ), + BuildCraftTransport( + IntegrationSide.BOTH, "BuildCraft Transport", "BuildCraft|Transport" + ), - BuildCraftTransport( IntegrationSide.BOTH, "BuildCraft Transport", "BuildCraft|Transport" ), + BuildCraftBuilder(IntegrationSide.BOTH, "BuildCraft Builders", "BuildCraft|Builders"), - BuildCraftBuilder( IntegrationSide.BOTH, "BuildCraft Builders", "BuildCraft|Builders" ), + LogisticsPipes(IntegrationSide.BOTH, "Logistics Pipes", "LogisticsPipes"), - LogisticsPipes( IntegrationSide.BOTH, "Logistics Pipes", "LogisticsPipes" ), + RF(IntegrationSide.BOTH, "RedstoneFlux Power - Tiles", "CoFHAPI"), - RF( IntegrationSide.BOTH, "RedstoneFlux Power - Tiles", "CoFHAPI" ), + RFItem(IntegrationSide.BOTH, "RedstoneFlux Power - Items", "CoFHAPI"), - RFItem( IntegrationSide.BOTH, "RedstoneFlux Power - Items", "CoFHAPI" ), + 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" ), + OpenComputers(IntegrationSide.BOTH, "OpenComputers", "OpenComputers"), - OpenComputers( IntegrationSide.BOTH, "OpenComputers", "OpenComputers" ), + PneumaticCraft(IntegrationSide.BOTH, "PneumaticCraft", "PneumaticCraft"); - PneumaticCraft( IntegrationSide.BOTH, "PneumaticCraft", "PneumaticCraft" ); - - public final IntegrationSide side; - public final String dspName; - public final String modID; - - IntegrationType( final IntegrationSide side, final String name, final String modid ) - { - this.side = side; - this.dspName = name; - this.modID = modid; - } + public final IntegrationSide side; + public final String dspName; + public final String modID; + IntegrationType(final IntegrationSide side, final String name, final 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 3f467c58..f85a233e 100644 --- a/src/main/java/appeng/integration/abstraction/IBetterStorage.java +++ b/src/main/java/appeng/integration/abstraction/IBetterStorage.java @@ -18,15 +18,11 @@ package appeng.integration.abstraction; - import appeng.util.InventoryAdaptor; import net.minecraftforge.common.util.ForgeDirection; +public interface IBetterStorage { + boolean isStorageCrate(Object te); -public interface IBetterStorage -{ - - boolean isStorageCrate( Object te ); - - InventoryAdaptor getAdaptor( Object te, ForgeDirection d ); + InventoryAdaptor getAdaptor(Object te, ForgeDirection d); } diff --git a/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java b/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java index 1c2f8a46..7fa7faf1 100644 --- a/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java +++ b/src/main/java/appeng/integration/abstraction/IBuildCraftCore.java @@ -18,13 +18,11 @@ package appeng.integration.abstraction; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; - import javax.annotation.Nonnull; import javax.annotation.Nullable; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; /** * Contains wrench behaviour @@ -38,34 +36,37 @@ import javax.annotation.Nullable; * @version rv3 * @since rv0 */ -public interface IBuildCraftCore -{ - /** - * @param eq to be checked item, can be {@code null} - * @return {@code true} if it is an {@link buildcraft.api.tools.IToolWrench} - */ - boolean isWrench( @Nullable Item eq ); +public interface IBuildCraftCore { + /** + * @param eq to be checked item, can be {@code null} + * @return {@code true} if it is an {@link buildcraft.api.tools.IToolWrench} + */ + boolean isWrench(@Nullable Item eq); - /** - * @param wrench to be checked item, must be an {@link buildcraft.api.tools.IToolWrench} - * @param wrencher wrenching player, can be probably {@code null}, but not sure - * @param x x pos - * @param y y pos - * @param z z pos - * @return {@code true} if player can wrench with that {@code wrench} - * @throws NullPointerException if {@code wrench} is {@code null} - * @throws ClassCastException if {@code wrench} is not an {@link buildcraft.api.tools.IToolWrench} - */ - boolean canWrench( @Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z ); + /** + * @param wrench to be checked item, must be an {@link + * buildcraft.api.tools.IToolWrench} + * @param wrencher wrenching player, can be probably {@code null}, but not sure + * @param x x pos + * @param y y pos + * @param z z pos + * @return {@code true} if player can wrench with that {@code wrench} + * @throws NullPointerException if {@code wrench} is {@code null} + * @throws ClassCastException if {@code wrench} is not an {@link + * buildcraft.api.tools.IToolWrench} + */ + boolean canWrench(@Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z); - /** - * @param wrench to be checked item, must be an {@link buildcraft.api.tools.IToolWrench} - * @param wrencher wrenching player, can be probably {@code null}, but not sure - * @param x x pos - * @param y y pos - * @param z z pos - * @throws NullPointerException if {@code wrench} is {@code null} - * @throws ClassCastException if {@code wrench} is not an {@link buildcraft.api.tools.IToolWrench} - */ - void wrenchUsed( @Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z ); + /** + * @param wrench to be checked item, must be an {@link + * buildcraft.api.tools.IToolWrench} + * @param wrencher wrenching player, can be probably {@code null}, but not sure + * @param x x pos + * @param y y pos + * @param z z pos + * @throws NullPointerException if {@code wrench} is {@code null} + * @throws ClassCastException if {@code wrench} is not an {@link + * buildcraft.api.tools.IToolWrench} + */ + void wrenchUsed(@Nonnull Item wrench, EntityPlayer wrencher, int x, int y, int z); } diff --git a/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java b/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java index f54014df..dff33808 100644 --- a/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java +++ b/src/main/java/appeng/integration/abstraction/IBuildCraftTransport.java @@ -18,6 +18,8 @@ package appeng.integration.abstraction; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.parts.IFacadePart; import net.minecraft.block.Block; @@ -26,10 +28,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - - /** * Contains facade logic to interchange BC facades with AE facades, *

@@ -43,70 +41,80 @@ import javax.annotation.Nullable; * @version rv3 - 12.06.2015 * @since rv3 12.06.2015 */ -public interface IBuildCraftTransport -{ - /** - * @param is to be checked item - * @return {@code true} if the checked item is a {@link buildcraft.api.facades.IFacadeItem} - */ - boolean isFacade( @Nullable ItemStack is ); +public interface IBuildCraftTransport { + /** + * @param is to be checked item + * @return {@code true} if the checked item is a {@link + * buildcraft.api.facades.IFacadeItem} + */ + boolean isFacade(@Nullable ItemStack is); - /** - * @param blk block used for the ae facade - * @param meta meta of the block - * @param side side of the ae facade - * @return ae facade through bc facade system - */ - @Nullable - IFacadePart createFacadePart( @Nullable Block blk, int meta, @Nonnull ForgeDirection side ); + /** + * @param blk block used for the ae facade + * @param meta meta of the block + * @param side side of the ae facade + * @return ae facade through bc facade system + */ + @Nullable + IFacadePart + createFacadePart(@Nullable Block blk, int meta, @Nonnull ForgeDirection side); - /** - * @param held create facade for that item - * @param side on which side should the part be rendered, should rather be not {@code null} - * @return new instance using the {@code held} and side as direct argument, no logic in between - * @throws IllegalArgumentException if {@code held} is {@code null} - */ - IFacadePart createFacadePart( @Nonnull ItemStack held, @Nonnull ForgeDirection side ); + /** + * @param held create facade for that item + * @param side on which side should the part be rendered, should rather be not {@code + * null} + * @return new instance using the {@code held} and side as direct argument, no logic + * in between + * @throws IllegalArgumentException if {@code held} is {@code null} + */ + IFacadePart createFacadePart(@Nonnull ItemStack held, @Nonnull ForgeDirection side); - /** - * @param facade buildcraft facade - * @return item with the block and metadata based on the facade or {@code null} if {@code facade} was not a facade - * @throws NullPointerException if {@code facade} is {@code null} - */ - @Nullable - ItemStack getTextureForFacade( @Nonnull ItemStack facade ); + /** + * @param facade buildcraft facade + * @return item with the block and metadata based on the facade or {@code null} if + * {@code facade} was not a facade + * @throws NullPointerException if {@code facade} is {@code null} + */ + @Nullable + ItemStack getTextureForFacade(@Nonnull ItemStack facade); - /** - * @return texture of buildcraft cobblestone structure pipe or null if something bad happens - */ - @Nullable - IIcon getCobbleStructurePipeTexture(); + /** + * @return texture of buildcraft cobblestone structure pipe or null if something bad + * happens + */ + @Nullable + IIcon getCobbleStructurePipeTexture(); - /** - * @param te the to be checked {@link TileEntity} - * @param dir direction of the {@link TileEntity} - * @return {@code true} if {@code te} is a buildcraft pipe, but not plugged - * @throws NullPointerException if {@code dir} is {@code null} - */ - boolean isPipe( @Nullable TileEntity te, @Nonnull ForgeDirection dir ); + /** + * @param te the to be checked {@link TileEntity} + * @param dir direction of the {@link TileEntity} + * @return {@code true} if {@code te} is a buildcraft pipe, but not plugged + * @throws NullPointerException if {@code dir} is {@code null} + */ + boolean isPipe(@Nullable TileEntity te, @Nonnull ForgeDirection dir); - /** - * checks weather if the {@code te} is injectable and simulates to inject the item - * - * @param te preferred something like a buildcraft injectable, can handle anything, just fails that way - * @param is to be injected item - * @param dir direction of the pipe - * @return {@code true} if items were simulated successfully being added - */ - boolean canAddItemsToPipe( TileEntity te, ItemStack is, ForgeDirection dir ); + /** + * checks weather if the {@code te} is injectable and simulates to inject the item + * + * @param te preferred something like a buildcraft injectable, can handle anything, + * just fails that way + * @param is to be injected item + * @param dir direction of the pipe + * @return {@code true} if items were simulated successfully being added + */ + boolean canAddItemsToPipe(TileEntity te, ItemStack is, ForgeDirection dir); - /** - * checks weather if the {@code te} is injectable, simulates the inject and tries to inject the item - * - * @param te preferred something like a buildcraft injectable, can handle anything, just fails that way - * @param is to be injected item - * @param dir direction of the pipe - * @return {@code true} if items were added to the buildcraft pipe - */ - boolean addItemsToPipe( @Nullable TileEntity te, @Nullable ItemStack is, @Nonnull ForgeDirection dir ); + /** + * checks weather if the {@code te} is injectable, simulates the inject and tries to + * inject the item + * + * @param te preferred something like a buildcraft injectable, can handle anything, + * just fails that way + * @param is to be injected item + * @param dir direction of the pipe + * @return {@code true} if items were added to the buildcraft pipe + */ + boolean addItemsToPipe( + @Nullable TileEntity te, @Nullable ItemStack is, @Nonnull ForgeDirection dir + ); } diff --git a/src/main/java/appeng/integration/abstraction/ICLApi.java b/src/main/java/appeng/integration/abstraction/ICLApi.java index d3184ecc..e1918649 100644 --- a/src/main/java/appeng/integration/abstraction/ICLApi.java +++ b/src/main/java/appeng/integration/abstraction/ICLApi.java @@ -18,12 +18,8 @@ package appeng.integration.abstraction; - import appeng.api.util.AEColor; - -public interface ICLApi -{ - - int colorLight( AEColor color, int light ); +public interface ICLApi { + 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 67ff00ec..77c0c827 100644 --- a/src/main/java/appeng/integration/abstraction/IDSU.java +++ b/src/main/java/appeng/integration/abstraction/IDSU.java @@ -18,15 +18,11 @@ package appeng.integration.abstraction; - import appeng.api.storage.IMEInventory; import net.minecraft.tileentity.TileEntity; +public interface IDSU { + IMEInventory getDSU(TileEntity te); -public interface IDSU -{ - - IMEInventory getDSU( TileEntity te ); - - boolean isDSU( 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 24b51c63..9a5b0fb2 100644 --- a/src/main/java/appeng/integration/abstraction/IFMP.java +++ b/src/main/java/appeng/integration/abstraction/IFMP.java @@ -18,22 +18,18 @@ package appeng.integration.abstraction; - import appeng.api.parts.IPartHost; import appeng.parts.CableBusContainer; import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; +public interface IFMP { + IPartHost getOrCreateHost(TileEntity tile); -public interface IFMP -{ + CableBusContainer getCableContainer(TileEntity te); - IPartHost getOrCreateHost( TileEntity tile ); + void registerPassThrough(Class layerInterface); - CableBusContainer getCableContainer( TileEntity te ); - - void registerPassThrough( Class layerInterface ); - - Event newFMPPacketEvent( EntityPlayerMP sender ); + 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 a6f68eaf..a6247dff 100644 --- a/src/main/java/appeng/integration/abstraction/IFZ.java +++ b/src/main/java/appeng/integration/abstraction/IFZ.java @@ -18,28 +18,24 @@ package appeng.integration.abstraction; - import appeng.api.storage.IMEInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public interface IFZ { + ItemStack barrelGetItem(TileEntity te); -public interface IFZ -{ + int barrelGetMaxItemCount(TileEntity te); - ItemStack barrelGetItem( TileEntity te ); + int barrelGetItemCount(TileEntity te); - int barrelGetMaxItemCount( TileEntity te ); + void setItemType(TileEntity te, ItemStack input); - int barrelGetItemCount( TileEntity te ); + void barrelSetCount(TileEntity te, int max); - void setItemType( TileEntity te, ItemStack input ); + IMEInventory getFactorizationBarrel(TileEntity te); - void barrelSetCount( TileEntity te, int max ); + boolean isBarrel(TileEntity te); - IMEInventory getFactorizationBarrel( TileEntity te ); - - boolean isBarrel( TileEntity te ); - - void grinderRecipe( ItemStack is, ItemStack itemStack ); + 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 816583c0..f19a18f6 100644 --- a/src/main/java/appeng/integration/abstraction/IForestry.java +++ b/src/main/java/appeng/integration/abstraction/IForestry.java @@ -18,12 +18,8 @@ package appeng.integration.abstraction; - import appeng.api.features.IItemComparisonProvider; - -public interface IForestry -{ - - IItemComparisonProvider getGeneticsComparisonProvider(); +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 7cc990bb..2b22d2b5 100644 --- a/src/main/java/appeng/integration/abstraction/IGT.java +++ b/src/main/java/appeng/integration/abstraction/IGT.java @@ -18,15 +18,11 @@ package appeng.integration.abstraction; - import appeng.api.storage.IMEInventory; import net.minecraft.tileentity.TileEntity; +public interface IGT { + boolean isQuantumChest(TileEntity te); -public interface IGT -{ - - boolean isQuantumChest( TileEntity te ); - - IMEInventory getQuantumChest( 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 655bc109..d5b342b2 100644 --- a/src/main/java/appeng/integration/abstraction/IIC2.java +++ b/src/main/java/appeng/integration/abstraction/IIC2.java @@ -18,19 +18,15 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public interface IIC2 { + void addToEnergyNet(TileEntity appEngTile); -public interface IIC2 -{ + void removeFromEnergyNet(TileEntity appEngTile); - void addToEnergyNet( TileEntity appEngTile ); + ItemStack getItem(String string); - void removeFromEnergyNet( TileEntity appEngTile ); - - ItemStack getItem( String string ); - - void maceratorRecipe( ItemStack in, ItemStack out ); + 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 77059ee2..0f16edcb 100644 --- a/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java +++ b/src/main/java/appeng/integration/abstraction/IImmibisMicroblocks.java @@ -18,20 +18,16 @@ package appeng.integration.abstraction; - import appeng.api.parts.IPartHost; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; +public interface IImmibisMicroblocks { + IPartHost getOrCreateHost(EntityPlayer player, int side, TileEntity te); -public interface IImmibisMicroblocks -{ - - IPartHost getOrCreateHost( EntityPlayer player, int side, TileEntity te ); - - /** - * @param te to be left tile entity - * @return true if this worked.. - */ - boolean leaveParts( TileEntity te ); + /** + * @param te to be left tile entity + * @return true if this worked.. + */ + 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 e493123f..3a8511c8 100644 --- a/src/main/java/appeng/integration/abstraction/IInvTweaks.java +++ b/src/main/java/appeng/integration/abstraction/IInvTweaks.java @@ -18,12 +18,8 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; - -public interface IInvTweaks -{ - - int compareItems( ItemStack i, ItemStack j ); +public interface IInvTweaks { + 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 fc26e804..9823bd0e 100644 --- a/src/main/java/appeng/integration/abstraction/ILP.java +++ b/src/main/java/appeng/integration/abstraction/ILP.java @@ -18,32 +18,28 @@ package appeng.integration.abstraction; +import java.util.List; import appeng.api.storage.IMEInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; +public interface ILP { + List getCraftedItems(TileEntity te); + List getProvidedItems(TileEntity te); -public interface ILP -{ + boolean isRequestPipe(TileEntity te); - List getCraftedItems( TileEntity te ); + List performRequest(TileEntity te, ItemStack wanted); - List getProvidedItems( TileEntity te ); + IMEInventory getInv(TileEntity te); - boolean isRequestPipe( TileEntity te ); + Object getGetPowerPipe(TileEntity te); - List performRequest( TileEntity te, ItemStack wanted ); + boolean isPowerSource(TileEntity tt); - IMEInventory getInv( TileEntity te ); + boolean canUseEnergy(Object pp, int ceil, List providersToIgnore); - Object getGetPowerPipe( TileEntity te ); - - boolean isPowerSource( TileEntity tt ); - - boolean canUseEnergy( Object pp, int ceil, List providersToIgnore ); - - boolean useEnergy( Object pp, int ceil, List providersToIgnore ); + boolean useEnergy(Object pp, int ceil, List providersToIgnore); } diff --git a/src/main/java/appeng/integration/abstraction/ILogisticsPipes.java b/src/main/java/appeng/integration/abstraction/ILogisticsPipes.java index 0bee3708..983ad387 100644 --- a/src/main/java/appeng/integration/abstraction/ILogisticsPipes.java +++ b/src/main/java/appeng/integration/abstraction/ILogisticsPipes.java @@ -18,15 +18,13 @@ package appeng.integration.abstraction; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - - /** * Contains pipe logic to interact between storage buses and pipes * @@ -34,9 +32,7 @@ import javax.annotation.Nullable; * @version rv3 01.01.2017 * @since rv3 01.01.2017 */ -public interface ILogisticsPipes -{ - +public interface ILogisticsPipes { /** * checks weather if the {@code te} is injectable and simulates to inject the item * @@ -45,15 +41,18 @@ public interface ILogisticsPipes * @param dir direction of the pipe * @return {@code true} if items were simulated successfully being added */ - boolean canAddItemsToPipe( TileEntity te, ItemStack is, ForgeDirection dir ); + boolean canAddItemsToPipe(TileEntity te, ItemStack is, ForgeDirection dir); /** - * checks weather if the {@code te} is injectable, simulates the inject and tries to inject the item + * checks weather if the {@code te} is injectable, simulates the inject and tries to + * inject the item * * @param te instanceof ILPPipe * @param is to be injected item * @param dir direction of the pipe * @return {@code true} if items were added to the buildcraft pipe */ - boolean addItemsToPipe( @Nullable TileEntity te, @Nullable ItemStack is, @Nonnull ForgeDirection dir ); + boolean addItemsToPipe( + @Nullable TileEntity te, @Nullable ItemStack is, @Nonnull ForgeDirection dir + ); } \ No newline at end of file diff --git a/src/main/java/appeng/integration/abstraction/IMekanism.java b/src/main/java/appeng/integration/abstraction/IMekanism.java index 8f56d415..1517c77b 100644 --- a/src/main/java/appeng/integration/abstraction/IMekanism.java +++ b/src/main/java/appeng/integration/abstraction/IMekanism.java @@ -18,14 +18,10 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; +public interface IMekanism { + void addCrusherRecipe(ItemStack in, ItemStack out); -public interface IMekanism -{ - - void addCrusherRecipe( ItemStack in, ItemStack out ); - - void addEnrichmentChamberRecipe( 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 817ef8b4..9d417436 100644 --- a/src/main/java/appeng/integration/abstraction/INEI.java +++ b/src/main/java/appeng/integration/abstraction/INEI.java @@ -18,15 +18,11 @@ package appeng.integration.abstraction; - import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.inventory.Slot; +public interface INEI { + void drawSlot(Slot s); -public interface INEI -{ - - void drawSlot( Slot s ); - - RenderItem setItemRender( RenderItem renderItem ); + RenderItem setItemRender(RenderItem renderItem); } diff --git a/src/main/java/appeng/integration/abstraction/IRC.java b/src/main/java/appeng/integration/abstraction/IRC.java index 857a5cc0..145499b7 100644 --- a/src/main/java/appeng/integration/abstraction/IRC.java +++ b/src/main/java/appeng/integration/abstraction/IRC.java @@ -18,12 +18,8 @@ package appeng.integration.abstraction; - import net.minecraft.item.ItemStack; - -public interface IRC -{ - - void rockCrusher( ItemStack input, ItemStack output ); +public interface IRC { + 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 7aca71e7..512c9779 100644 --- a/src/main/java/appeng/integration/abstraction/ITE.java +++ b/src/main/java/appeng/integration/abstraction/ITE.java @@ -18,20 +18,18 @@ 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); -public interface ITE -{ + void addPulverizerRecipe( + int i, ItemStack blkQuartzOre, ItemStack matQuartz, ItemStack matQuartzDust + ); - void addPulverizerRecipe( int i, ItemStack blkQuartz, ItemStack blockDust ); + boolean isPipe(TileEntity te, ForgeDirection opposite); - void addPulverizerRecipe( int i, ItemStack blkQuartzOre, ItemStack matQuartz, ItemStack matQuartzDust ); - - boolean isPipe( TileEntity te, ForgeDirection opposite ); - - ItemStack addItemsToPipe( TileEntity ad, ItemStack itemstack, ForgeDirection dir ); + ItemStack addItemsToPipe(TileEntity ad, ItemStack itemstack, ForgeDirection dir); } diff --git a/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java b/src/main/java/appeng/integration/modules/BCHelpers/AECableSchematicTile.java index 456cd85f..590596c8 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 appeng.api.parts.*; import appeng.api.util.AEColor; @@ -31,141 +32,102 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Set; +public class AECableSchematicTile extends AEGenericSchematicTile implements IPartHost { + @Override + public void rotateLeft(final IBuilderContext context) { + final CableBusContainer cbc = new CableBusContainer(this); + cbc.readFromNBT(this.tileNBT); + cbc.rotateLeft(); -public class AECableSchematicTile extends AEGenericSchematicTile implements IPartHost -{ + this.tileNBT = new NBTTagCompound(); + cbc.writeToNBT(this.tileNBT); + } - @Override - public void rotateLeft( final IBuilderContext context ) - { - final CableBusContainer cbc = new CableBusContainer( this ); - cbc.readFromNBT( this.tileNBT ); + @Override + public IFacadeContainer getFacadeContainer() { + return null; + } - cbc.rotateLeft(); + @Override + public boolean canAddPart(final ItemStack part, final ForgeDirection side) { + return false; + } - this.tileNBT = new NBTTagCompound(); - cbc.writeToNBT( this.tileNBT ); - } + @Override + public ForgeDirection + addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer owner) { + return null; + } - @Override - public IFacadeContainer getFacadeContainer() - { - return null; - } + @Override + public IPart getPart(final ForgeDirection side) { + return null; + } - @Override - public boolean canAddPart( final ItemStack part, final ForgeDirection side ) - { - return false; - } + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) {} - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer owner ) - { - return null; - } + @Override + public void markForUpdate() {} - @Override - public IPart getPart( final ForgeDirection side ) - { - return null; - } + @Override + public DimensionalCoord getLocation() { + return null; + } - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { + @Override + public TileEntity getTile() { + return null; + } - } + @Override + public AEColor getColor() { + return null; + } - @Override - public void markForUpdate() - { + @Override + public void clearContainer() {} - } + @Override + public boolean isBlocked(final ForgeDirection side) { + return false; + } - @Override - public DimensionalCoord getLocation() - { - return null; - } + @Override + public SelectedPart selectPart(final Vec3 pos) { + return null; + } - @Override - public TileEntity getTile() - { - return null; - } + @Override + public void markForSave() {} - @Override - public AEColor getColor() - { - return null; - } + @Override + public void partChanged() {} - @Override - public void clearContainer() - { + @Override + public boolean hasRedstone(final ForgeDirection side) { + return false; + } - } + @Override + public boolean isEmpty() { + return false; + } - @Override - public boolean isBlocked( final ForgeDirection side ) - { - return false; - } + @Override + public Set getLayerFlags() { + return null; + } - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - return null; - } + @Override + public void cleanup() {} - @Override - public void markForSave() - { + @Override + public void notifyNeighbors() {} - } - - @Override - public void partChanged() - { - - } - - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - return false; - } - - @Override - public boolean isEmpty() - { - return false; - } - - @Override - public Set getLayerFlags() - { - return null; - } - - @Override - public void cleanup() - { - - } - - @Override - public void notifyNeighbors() - { - - } - - @Override - public boolean isInWorld() - { - return false; - } + @Override + public boolean isInWorld() { + 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 b856b53f..06d5430c 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AEGenericSchematicTile.java @@ -18,6 +18,7 @@ package appeng.integration.modules.BCHelpers; +import java.util.ArrayList; import appeng.api.util.ICommonTile; import appeng.tile.AEBaseTile; @@ -28,52 +29,40 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; +public class AEGenericSchematicTile extends SchematicTile { + @Override + public void storeRequirements( + final IBuilderContext context, final int x, final int y, final int z + ) { + final TileEntity tile = context.world().getTileEntity(x, y, z); + final ArrayList list = new ArrayList(); + if (tile instanceof AEBaseTile) { + final ICommonTile tcb = (ICommonTile) tile; + tcb.getDrops(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, list); + } + this.storedRequirements = list.toArray(new ItemStack[list.size()]); + } -public class AEGenericSchematicTile extends SchematicTile -{ + @Override + public void rotateLeft(final IBuilderContext context) { + if (this.tileNBT.hasKey("orientation_forward") + && this.tileNBT.hasKey("orientation_up")) { + final String forward = this.tileNBT.getString("orientation_forward"); + final String up = this.tileNBT.getString("orientation_up"); - @Override - public void storeRequirements( final IBuilderContext context, final int x, final int y, final int z ) - { - final TileEntity tile = context.world().getTileEntity( x, y, z ); - final ArrayList list = new ArrayList(); - if( tile instanceof AEBaseTile ) - { - final ICommonTile tcb = (ICommonTile) tile; - tcb.getDrops( tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, list ); - } + if (forward != null && up != null) { + try { + ForgeDirection fdForward = ForgeDirection.valueOf(forward); + ForgeDirection fdUp = ForgeDirection.valueOf(up); - this.storedRequirements = list.toArray( new ItemStack[list.size()] ); - } + fdForward = Platform.rotateAround(fdForward, ForgeDirection.DOWN); + fdUp = Platform.rotateAround(fdUp, ForgeDirection.DOWN); - @Override - public void rotateLeft( final IBuilderContext context ) - { - if( this.tileNBT.hasKey( "orientation_forward" ) && this.tileNBT.hasKey( "orientation_up" ) ) - { - final String forward = this.tileNBT.getString( "orientation_forward" ); - final String up = this.tileNBT.getString( "orientation_up" ); - - if( forward != null && up != null ) - { - try - { - ForgeDirection fdForward = ForgeDirection.valueOf( forward ); - ForgeDirection fdUp = ForgeDirection.valueOf( up ); - - fdForward = Platform.rotateAround( fdForward, ForgeDirection.DOWN ); - fdUp = Platform.rotateAround( fdUp, ForgeDirection.DOWN ); - - this.tileNBT.setString( "orientation_forward", fdForward.name() ); - this.tileNBT.setString( "orientation_up", fdUp.name() ); - } - catch( final Throwable ignored ) - { - - } - } - } - } + this.tileNBT.setString("orientation_forward", fdForward.name()); + this.tileNBT.setString("orientation_up", fdUp.name()); + } catch (final 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 7697cf79..e211f106 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/AERotatableBlockSchematic.java @@ -18,23 +18,19 @@ package appeng.integration.modules.BCHelpers; - import appeng.util.Platform; import buildcraft.api.blueprints.IBuilderContext; import buildcraft.api.blueprints.SchematicBlock; import net.minecraftforge.common.util.ForgeDirection; - -public class AERotatableBlockSchematic extends SchematicBlock -{ - - @Override - public void rotateLeft( final IBuilderContext context ) - { - if( this.meta < 6 ) - { - final ForgeDirection d = Platform.rotateAround( ForgeDirection.values()[this.meta], ForgeDirection.DOWN ); - this.meta = d.ordinal(); - } - } +public class AERotatableBlockSchematic extends SchematicBlock { + @Override + public void rotateLeft(final IBuilderContext context) { + if (this.meta < 6) { + final 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 c067ca33..f0acaaaa 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.BCHelpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,30 +28,35 @@ import appeng.integration.abstraction.IBuildCraftTransport; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class BCPipeHandler implements IExternalStorageHandler { + @Override + public boolean canHandle( + final TileEntity te, + final ForgeDirection d, + final StorageChannel chan, + final BaseActionSource mySrc + ) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport + ); -public class BCPipeHandler implements IExternalStorageHandler -{ + return chan == StorageChannel.ITEMS && bc.isPipe(te, d); + } - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); + return false; + } - return chan == StorageChannel.ITEMS && bc.isPipe( te, d ); - } - - return false; - } - - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - return new BCPipeInventory( te, d ); - } - return null; - } + @Override + public IMEInventory getInventory( + final TileEntity te, + final ForgeDirection d, + final StorageChannel chan, + final BaseActionSource src + ) { + 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 f4bcec50..73af7110 100644 --- a/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java +++ b/src/main/java/appeng/integration/modules/BCHelpers/BCPipeInventory.java @@ -18,7 +18,6 @@ package appeng.integration.modules.BCHelpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -31,59 +30,55 @@ import appeng.integration.abstraction.IBuildCraftTransport; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class BCPipeInventory implements IMEInventory { + private final TileEntity te; + private final ForgeDirection direction; -public class BCPipeInventory implements IMEInventory -{ + public BCPipeInventory(final TileEntity te, final ForgeDirection direction) { + this.te = te; + this.direction = direction; + } - private final TileEntity te; - private final ForgeDirection direction; + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport registry = (IBuildCraftTransport + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport + ); - public BCPipeInventory( final TileEntity te, final ForgeDirection direction ) - { - this.te = te; - this.direction = direction; - } + if (mode == Actionable.SIMULATE) { + if (registry.canAddItemsToPipe( + this.te, input.getItemStack(), this.direction + )) { + return null; + } + return input; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport registry = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); + if (registry.addItemsToPipe(this.te, input.getItemStack(), this.direction)) { + return null; + } + } - if( mode == Actionable.SIMULATE ) - { - if( registry.canAddItemsToPipe( this.te, input.getItemStack(), this.direction ) ) - { - return null; - } - return input; - } + return input; + } - if( registry.addItemsToPipe( this.te, input.getItemStack(), this.direction ) ) - { - return null; - } - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + return null; + } - return input; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/integration/modules/BetterStorage.java b/src/main/java/appeng/integration/modules/BetterStorage.java index dd6e8219..c9076a72 100644 --- a/src/main/java/appeng/integration/modules/BetterStorage.java +++ b/src/main/java/appeng/integration/modules/BetterStorage.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; @@ -30,42 +29,37 @@ import appeng.util.InventoryAdaptor; import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraftforge.common.util.ForgeDirection; +public class BetterStorage implements IIntegrationModule, IBetterStorage { + @Reflected + public static BetterStorage instance; -public class BetterStorage implements IIntegrationModule, IBetterStorage -{ - @Reflected - public static BetterStorage instance; + @Reflected + public BetterStorage() { + IntegrationHelper.testClassExistence( + this, net.mcft.copy.betterstorage.api.crate.ICrateStorage.class + ); + } - @Reflected - public BetterStorage() - { - IntegrationHelper.testClassExistence( this, net.mcft.copy.betterstorage.api.crate.ICrateStorage.class ); - } + @Override + public boolean isStorageCrate(final Object te) { + return te instanceof ICrateStorage; + } - @Override - public boolean isStorageCrate( final Object te ) - { - return te instanceof ICrateStorage; - } + @Override + public InventoryAdaptor getAdaptor(final Object te, final ForgeDirection d) { + if (te instanceof ICrateStorage) { + return new BSCrateStorageAdaptor(te); + } + return null; + } - @Override - public InventoryAdaptor getAdaptor( final Object te, final ForgeDirection d ) - { - if( te instanceof ICrateStorage ) - { - return new BSCrateStorageAdaptor( te ); - } - return null; - } + @Override + public void init() {} - @Override - public void init() - { - } - - @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new BSCrateHandler() ); - } + @Override + public void postInit() { + AEApi.instance().registries().externalStorage().addExternalStorageInterface( + new BSCrateHandler() + ); + } } diff --git a/src/main/java/appeng/integration/modules/BuildCraftBuilder.java b/src/main/java/appeng/integration/modules/BuildCraftBuilder.java index d8f997dd..e260e145 100644 --- a/src/main/java/appeng/integration/modules/BuildCraftBuilder.java +++ b/src/main/java/appeng/integration/modules/BuildCraftBuilder.java @@ -18,6 +18,8 @@ package appeng.integration.modules; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -37,10 +39,6 @@ import com.google.common.base.Optional; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - - /** * The builder has no interface, because it provides no functionality * @@ -49,79 +47,75 @@ import java.lang.reflect.Method; * @since rv3 12.06.2015 */ @Reflected -public class BuildCraftBuilder implements IIntegrationModule -{ - @Reflected - public static BuildCraftBuilder instance; +public class BuildCraftBuilder implements IIntegrationModule { + @Reflected + public static BuildCraftBuilder instance; - @Reflected - public BuildCraftBuilder() - { - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.BuilderAPI.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.IBuilderContext.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.ISchematicRegistry.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.SchematicTile.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.blueprints.SchematicBlock.class ); - } + @Reflected + public BuildCraftBuilder() { + IntegrationHelper + .testClassExistence(this, buildcraft.api.blueprints.BuilderAPI.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.blueprints.IBuilderContext.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.blueprints.ISchematicRegistry.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.blueprints.SchematicTile.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.blueprints.SchematicBlock.class); + } - @Override - public void init() throws Throwable - { - try - { - this.initBuilderSupport(); - } - catch( final Exception builderSupport ) - { - // not supported? - } - } + @Override + public void init() throws Throwable { + try { + this.initBuilderSupport(); + } catch (final Exception builderSupport) { + // not supported? + } + } - @Override - public void postInit() - { - } + @Override + public void postInit() {} - private void initBuilderSupport() - { - final ISchematicRegistry schematicRegistry = BuilderAPI.schematicRegistry; + private void initBuilderSupport() { + final ISchematicRegistry schematicRegistry = BuilderAPI.schematicRegistry; - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final IBlockDefinition maybeMultiPart = blocks.multiPart(); + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final IBlockDefinition maybeMultiPart = blocks.multiPart(); - for( final Method blockDefinition : blocks.getClass().getMethods() ) - { - try - { - final IBlockDefinition def = (IBlockDefinition) blockDefinition.invoke( blocks ); - final Optional maybeBlock = def.maybeBlock(); - if( !maybeBlock.isPresent() ) - { - continue; - } + for (final Method blockDefinition : blocks.getClass().getMethods()) { + try { + final IBlockDefinition def + = (IBlockDefinition) blockDefinition.invoke(blocks); + final Optional maybeBlock = def.maybeBlock(); + if (!maybeBlock.isPresent()) { + continue; + } - final Block block = maybeBlock.get(); - if( block instanceof IOrientableBlock && ( (IOrientableBlock) block ).usesMetadata() && !( def instanceof ITileDefinition ) ) - { - schematicRegistry.registerSchematicBlock( block, AERotatableBlockSchematic.class ); - } - else if( maybeMultiPart.isSameAs( new ItemStack( block ) ) ) - { - schematicRegistry.registerSchematicBlock( block, AECableSchematicTile.class ); - } - else if( def instanceof ITileDefinition ) - { - schematicRegistry.registerSchematicBlock( block, AEGenericSchematicTile.class ); - } - } - catch( final InvocationTargetException ignore ) - { - AELog.warn( "Encountered problems while initializing the BuildCraft Builder support. Can not invoke the method %s", blockDefinition ); - } - catch( final IllegalAccessException ignore ) - { - AELog.warn( "Encountered problems while initializing the BuildCraft Builder support. Can not access the method %s", blockDefinition ); - } - } - } + final Block block = maybeBlock.get(); + if (block instanceof IOrientableBlock + && ((IOrientableBlock) block).usesMetadata() + && !(def instanceof ITileDefinition)) { + schematicRegistry + .registerSchematicBlock(block, AERotatableBlockSchematic.class); + } else if (maybeMultiPart.isSameAs(new ItemStack(block))) { + schematicRegistry + .registerSchematicBlock(block, AECableSchematicTile.class); + } else if (def instanceof ITileDefinition) { + schematicRegistry + .registerSchematicBlock(block, AEGenericSchematicTile.class); + } + } catch (final InvocationTargetException ignore) { + AELog.warn( + "Encountered problems while initializing the BuildCraft Builder support. Can not invoke the method %s", + blockDefinition + ); + } catch (final IllegalAccessException ignore) { + AELog.warn( + "Encountered problems while initializing the BuildCraft Builder support. Can not access the method %s", + blockDefinition + ); + } + } + } } diff --git a/src/main/java/appeng/integration/modules/BuildCraftCore.java b/src/main/java/appeng/integration/modules/BuildCraftCore.java index 9dd6d26e..19dce62e 100644 --- a/src/main/java/appeng/integration/modules/BuildCraftCore.java +++ b/src/main/java/appeng/integration/modules/BuildCraftCore.java @@ -18,6 +18,7 @@ package appeng.integration.modules; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.config.TunnelType; @@ -31,58 +32,68 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; - - @Reflected -public final class BuildCraftCore implements IBuildCraftCore, IIntegrationModule -{ - @Reflected - public static BuildCraftCore instance; +public final class BuildCraftCore implements IBuildCraftCore, IIntegrationModule { + @Reflected + public static BuildCraftCore instance; - @Reflected - public BuildCraftCore() - { - IntegrationHelper.testClassExistence( this, buildcraft.BuildCraftCore.class ); - IntegrationHelper.testClassExistence( this, buildcraft.BuildCraftTransport.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.tools.IToolWrench.class ); - } + @Reflected + public BuildCraftCore() { + IntegrationHelper.testClassExistence(this, buildcraft.BuildCraftCore.class); + IntegrationHelper.testClassExistence(this, buildcraft.BuildCraftTransport.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.tools.IToolWrench.class); + } - @Override - public boolean isWrench( final Item eq ) - { - return eq instanceof IToolWrench; - } + @Override + public boolean isWrench(final Item eq) { + return eq instanceof IToolWrench; + } - @Override - public boolean canWrench( @Nonnull final Item wrench, final EntityPlayer wrencher, final int x, final int y, final int z ) - { - return ( (IToolWrench) wrench ).canWrench( wrencher, x, y, z ); - } + @Override + public boolean canWrench( + @Nonnull final Item wrench, + final EntityPlayer wrencher, + final int x, + final int y, + final int z + ) { + return ((IToolWrench) wrench).canWrench(wrencher, x, y, z); + } - @Override - public void wrenchUsed( @Nonnull final Item wrench, final EntityPlayer wrencher, final int x, final int y, final int z ) - { - ( (IToolWrench) wrench ).wrenchUsed( wrencher, x, y, z ); - } + @Override + public void wrenchUsed( + @Nonnull final Item wrench, + final EntityPlayer wrencher, + final int x, + final int y, + final int z + ) { + ((IToolWrench) wrench).wrenchUsed(wrencher, x, y, z); + } - @Override - public void init() - { - } + @Override + public void init() {} - @Override - public void postInit() - { - this.registerPowerP2P(); - } + @Override + public void postInit() { + this.registerPowerP2P(); + } - private void registerPowerP2P() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + private void registerPowerP2P() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftCore.engineBlock, 1, 0 ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftCore.engineBlock, 1, 1 ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftCore.engineBlock, 1, 2 ), TunnelType.RF_POWER ); - } + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftCore.engineBlock, 1, 0), + TunnelType.RF_POWER + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftCore.engineBlock, 1, 1), + TunnelType.RF_POWER + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftCore.engineBlock, 1, 2), + TunnelType.RF_POWER + ); + } } diff --git a/src/main/java/appeng/integration/modules/BuildCraftTransport.java b/src/main/java/appeng/integration/modules/BuildCraftTransport.java index 5c011dc5..3dd12c7f 100644 --- a/src/main/java/appeng/integration/modules/BuildCraftTransport.java +++ b/src/main/java/appeng/integration/modules/BuildCraftTransport.java @@ -18,6 +18,8 @@ package appeng.integration.modules; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.IAppEngApi; @@ -45,255 +47,295 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - - /** * @author thatsIch * @version rv3 - 12.06.2015 * @since rv3 12.06.2015 */ @Reflected -public class BuildCraftTransport implements IBuildCraftTransport, IIntegrationModule -{ - @Reflected - public static BuildCraftTransport instance; +public class BuildCraftTransport implements IBuildCraftTransport, IIntegrationModule { + @Reflected + public static BuildCraftTransport instance; - @Reflected - public BuildCraftTransport() - { - IntegrationHelper.testClassExistence( this, buildcraft.BuildCraftTransport.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.facades.IFacadeItem.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IInjectable.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IPipeConnection.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IPipeTile.class ); - IntegrationHelper.testClassExistence( this, buildcraft.api.transport.IPipeTile.PipeType.class ); - IntegrationHelper.testClassExistence( this, buildcraft.transport.ItemFacade.class ); - IntegrationHelper.testClassExistence( this, buildcraft.transport.PipeIconProvider.class ); - } + @Reflected + public BuildCraftTransport() { + IntegrationHelper.testClassExistence(this, buildcraft.BuildCraftTransport.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.facades.IFacadeItem.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.transport.IInjectable.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.transport.IPipeConnection.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.transport.IPipeTile.class); + IntegrationHelper + .testClassExistence(this, buildcraft.api.transport.IPipeTile.PipeType.class); + IntegrationHelper.testClassExistence(this, buildcraft.transport.ItemFacade.class); + IntegrationHelper + .testClassExistence(this, buildcraft.transport.PipeIconProvider.class); + } - @Override - public boolean isFacade( final ItemStack is ) - { - if( is == null ) - { - return false; - } + @Override + public boolean isFacade(final ItemStack is) { + if (is == null) { + return false; + } - return is.getItem() instanceof IFacadeItem; - } + return is.getItem() instanceof IFacadeItem; + } - @Nullable - @Override - public IFacadePart createFacadePart( final Block blk, final int meta, @Nonnull final ForgeDirection side ) - { - try - { - final ItemFacade.FacadeState state = ItemFacade.FacadeState.create( blk, meta ); - final ItemStack facade = ItemFacade.getFacade( state ); + @Nullable + @Override + public IFacadePart createFacadePart( + final Block blk, final int meta, @Nonnull final ForgeDirection side + ) { + try { + final ItemFacade.FacadeState state = ItemFacade.FacadeState.create(blk, meta); + final ItemStack facade = ItemFacade.getFacade(state); - return new FacadePart( facade, side ); - } - catch( final Exception ignored ) - { + return new FacadePart(facade, side); + } catch (final Exception ignored) {} - } + return null; + } - return null; - } + @Override + public IFacadePart + createFacadePart(@Nonnull final ItemStack fs, @Nonnull final ForgeDirection side) { + return new FacadePart(fs, side); + } - @Override - public IFacadePart createFacadePart( @Nonnull final ItemStack fs, @Nonnull final ForgeDirection side ) - { - return new FacadePart( fs, side ); - } + @Nullable + @Override + public ItemStack getTextureForFacade(@Nonnull final ItemStack facade) { + final Item maybeFacadeItem = facade.getItem(); - @Nullable - @Override - public ItemStack getTextureForFacade( @Nonnull final ItemStack facade ) - { - final Item maybeFacadeItem = facade.getItem(); + if (maybeFacadeItem instanceof IFacadeItem) { + final IFacadeItem facadeItem = (IFacadeItem) maybeFacadeItem; - if( maybeFacadeItem instanceof IFacadeItem ) - { - final IFacadeItem facadeItem = (IFacadeItem) maybeFacadeItem; + final Block[] blocks = facadeItem.getBlocksForFacade(facade); + final int[] metas = facadeItem.getMetaValuesForFacade(facade); - final Block[] blocks = facadeItem.getBlocksForFacade( facade ); - final int[] metas = facadeItem.getMetaValuesForFacade( facade ); + if (blocks.length > 0 && metas.length > 0) { + return new ItemStack(blocks[0], 1, metas[0]); + } + } - if( blocks.length > 0 && metas.length > 0 ) - { - return new ItemStack( blocks[0], 1, metas[0] ); - } - } + return null; + } - return null; - } + @Nullable + @Override + public IIcon getCobbleStructurePipeTexture() { + try { + return buildcraft.BuildCraftTransport.instance.pipeIconProvider.getIcon( + PipeIconProvider.TYPE.PipeStructureCobblestone.ordinal() + ); // Structure + } catch (final Exception ignored) {} + return null; + // Pipe + } - @Nullable - @Override - public IIcon getCobbleStructurePipeTexture() - { - try - { - return buildcraft.BuildCraftTransport.instance.pipeIconProvider.getIcon( PipeIconProvider.TYPE.PipeStructureCobblestone.ordinal() ); // Structure - } - catch( final Exception ignored ) - { - } - return null; - // Pipe - } + @Override + public boolean isPipe(final TileEntity te, @Nonnull final ForgeDirection dir) { + if (te instanceof IPipeTile) { + final IPipeTile pipeTile = (IPipeTile) te; + return !pipeTile.hasPipePluggable(dir.getOpposite()); + } - @Override - public boolean isPipe( final TileEntity te, @Nonnull final ForgeDirection dir ) - { - if( te instanceof IPipeTile ) - { - final IPipeTile pipeTile = (IPipeTile) te; - return !pipeTile.hasPipePluggable( dir.getOpposite() ); - } + return false; + } - return false; - } + @Override + public boolean + canAddItemsToPipe(final TileEntity te, final ItemStack is, final ForgeDirection dir) { + if (is != null && te != null && te instanceof IInjectable) { + final IInjectable pt = (IInjectable) te; + if (pt.canInjectItems(dir)) { + final int amt = pt.injectItem(is, false, dir, null); + if (amt == is.stackSize) { + return true; + } + } + } - @Override - public boolean canAddItemsToPipe( final TileEntity te, final ItemStack is, final ForgeDirection dir ) - { - if( is != null && te != null && te instanceof IInjectable ) - { - final IInjectable pt = (IInjectable) te; - if( pt.canInjectItems( dir ) ) - { - final int amt = pt.injectItem( is, false, dir, null ); - if( amt == is.stackSize ) - { - return true; - } - } - } + return false; + } - return false; - } + @Override + public boolean addItemsToPipe( + @Nullable final TileEntity te, + @Nullable final ItemStack is, + @Nonnull final ForgeDirection dir + ) { + if (is != null && te != null && te instanceof IInjectable) { + final IInjectable pt = (IInjectable) te; + if (pt.canInjectItems(dir)) { + final int amt = pt.injectItem(is, false, dir, null); + if (amt == is.stackSize) { + pt.injectItem(is, true, dir, null); + return true; + } + } + } - @Override - public boolean addItemsToPipe( @Nullable final TileEntity te, @Nullable final ItemStack is, @Nonnull final ForgeDirection dir ) - { - if( is != null && te != null && te instanceof IInjectable ) - { - final IInjectable pt = (IInjectable) te; - if( pt.canInjectItems( dir ) ) - { - final int amt = pt.injectItem( is, false, dir, null ); - if( amt == is.stackSize ) - { - pt.injectItem( is, true, dir, null ); - return true; - } - } - } + return false; + } - return false; - } + private void addFacade(final ItemStack item) { + if (item != null) { + FMLInterModComms.sendMessage("BuildCraft|Transport", "add-facade", item); + } + } - private void addFacade( final ItemStack item ) - { - if( item != null ) - { - FMLInterModComms.sendMessage( "BuildCraft|Transport", "add-facade", item ); - } - } + private void registerPowerP2P() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - private void registerPowerP2P() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipePowerCobblestone), + TunnelType.RF_POWER + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipePowerDiamond), + TunnelType.RF_POWER + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipePowerGold), + TunnelType.RF_POWER + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipePowerQuartz), + TunnelType.RF_POWER + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipePowerStone), + TunnelType.RF_POWER + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipePowerWood), + TunnelType.RF_POWER + ); + } - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerCobblestone ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerDiamond ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerGold ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerQuartz ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerStone ), TunnelType.RF_POWER ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipePowerWood ), TunnelType.RF_POWER ); - } + private void registerItemP2P() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - private void registerItemP2P() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsWood), TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsVoid), TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsSandstone), + TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsQuartz), TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsObsidian), + TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsIron), TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsGold), TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsEmerald), + TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsDiamond), + TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsStone), TunnelType.ITEM + ); + registry.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeItemsCobblestone), + TunnelType.ITEM + ); + } - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsWood ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsVoid ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsSandstone ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsQuartz ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsObsidian ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsIron ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsGold ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsEmerald ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsDiamond ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsStone ), TunnelType.ITEM ); - registry.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeItemsCobblestone ), TunnelType.ITEM ); - } + private void registerLiquidsP2P() { + final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsCobblestone), + TunnelType.FLUID + ); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsEmerald), + TunnelType.FLUID + ); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsGold), TunnelType.FLUID + ); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsIron), TunnelType.FLUID + ); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsSandstone), + TunnelType.FLUID + ); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsStone), + TunnelType.FLUID + ); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsVoid), TunnelType.FLUID + ); + reg.addNewAttunement( + new ItemStack(buildcraft.BuildCraftTransport.pipeFluidsWood), TunnelType.FLUID + ); + } - private void registerLiquidsP2P() - { - final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsCobblestone ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsEmerald ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsGold ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsIron ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsSandstone ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsStone ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsVoid ), TunnelType.FLUID ); - reg.addNewAttunement( new ItemStack( buildcraft.BuildCraftTransport.pipeFluidsWood ), TunnelType.FLUID ); - } + @Override + public void init() throws Throwable { + this.initPipeConnection(); + this.initFacades(); + } - @Override - public void init() throws Throwable - { - this.initPipeConnection(); - this.initFacades(); - } + @Override + public void postInit() { + this.registerPowerP2P(); + this.registerItemP2P(); + this.registerLiquidsP2P(); + } - @Override - public void postInit() - { - this.registerPowerP2P(); - this.registerItemP2P(); - this.registerLiquidsP2P(); - } + private void initPipeConnection() { + final IAppEngApi api = AEApi.instance(); - private void initPipeConnection() - { - final IAppEngApi api = AEApi.instance(); + api.partHelper().registerNewLayer( + "appeng.parts.layers.LayerIPipeConnection", + "buildcraft.api.transport.IPipeConnection" + ); + api.registries().externalStorage().addExternalStorageInterface(new BCPipeHandler() + ); + } - api.partHelper().registerNewLayer( "appeng.parts.layers.LayerIPipeConnection", "buildcraft.api.transport.IPipeConnection" ); - api.registries().externalStorage().addExternalStorageInterface( new BCPipeHandler() ); - } + private void initFacades() { + final IAppEngApi api = AEApi.instance(); + final IBlocks blocks = api.definitions().blocks(); - private void initFacades() - { - final IAppEngApi api = AEApi.instance(); - final IBlocks blocks = api.definitions().blocks(); + this.addFacadeStack(blocks.fluix()); + this.addFacadeStack(blocks.quartz()); + this.addFacadeStack(blocks.quartzChiseled()); + this.addFacadeStack(blocks.quartzPillar()); - this.addFacadeStack( blocks.fluix() ); - this.addFacadeStack( blocks.quartz() ); - this.addFacadeStack( blocks.quartzChiseled() ); - this.addFacadeStack( blocks.quartzPillar() ); + for (final Block skyStoneBlock : blocks.skyStone().maybeBlock().asSet()) { + this.addFacade(new ItemStack(skyStoneBlock, 1, 0)); + this.addFacade(new ItemStack(skyStoneBlock, 1, 1)); + this.addFacade(new ItemStack(skyStoneBlock, 1, 2)); + this.addFacade(new ItemStack(skyStoneBlock, 1, 3)); + } + } - for( final Block skyStoneBlock : blocks.skyStone().maybeBlock().asSet() ) - { - this.addFacade( new ItemStack( skyStoneBlock, 1, 0 ) ); - this.addFacade( new ItemStack( skyStoneBlock, 1, 1 ) ); - this.addFacade( new ItemStack( skyStoneBlock, 1, 2 ) ); - this.addFacade( new ItemStack( skyStoneBlock, 1, 3 ) ); - } - } - - private void addFacadeStack( final IItemDefinition definition ) - { - for( final ItemStack facadeStack : definition.maybeStack( 1 ).asSet() ) - { - this.addFacade( facadeStack ); - } - } + private void addFacadeStack(final IItemDefinition definition) { + for (final ItemStack facadeStack : definition.maybeStack(1).asSet()) { + this.addFacade(facadeStack); + } + } } diff --git a/src/main/java/appeng/integration/modules/CLApi.java b/src/main/java/appeng/integration/modules/CLApi.java index 8659c124..d9a0756b 100644 --- a/src/main/java/appeng/integration/modules/CLApi.java +++ b/src/main/java/appeng/integration/modules/CLApi.java @@ -18,45 +18,39 @@ package appeng.integration.modules; - import appeng.api.util.AEColor; import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; import appeng.integration.abstraction.ICLApi; +public class CLApi implements ICLApi, IIntegrationModule { + @Reflected + public static CLApi instance; -public class CLApi implements ICLApi, IIntegrationModule -{ - @Reflected - public static CLApi instance; + @Reflected + public CLApi() { + IntegrationHelper.testClassExistence(this, coloredlightscore.src.api.CLApi.class); + } - @Reflected - public CLApi() - { - IntegrationHelper.testClassExistence( this, coloredlightscore.src.api.CLApi.class ); - } + @Override + public void init() throws Throwable {} - @Override - public void init() throws Throwable - { - } + @Override + public void postInit() { + // :P + } - @Override - public void postInit() - { - // :P - } + @Override + public int colorLight(final AEColor color, final int light) { + final int mv = color.mediumVariant; - @Override - public int colorLight( final AEColor color, final int light ) - { - final int mv = color.mediumVariant; + final float r = (mv >> 16) & 0xff; + final float g = (mv >> 8) & 0xff; + final float b = (mv) &0xff; - final float r = ( mv >> 16 ) & 0xff; - final float g = ( mv >> 8 ) & 0xff; - final float b = ( mv ) & 0xff; - - return coloredlightscore.src.api.CLApi.makeRGBLightValue( r / 255.0f, g / 255.0f, b / 255.0f, light / 15.0f ); - } + 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 c0eb79e2..829ef75e 100644 --- a/src/main/java/appeng/integration/modules/CraftGuide.java +++ b/src/main/java/appeng/integration/modules/CraftGuide.java @@ -18,6 +18,9 @@ package appeng.integration.modules; +import java.util.Arrays; +import java.util.List; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.IAppEngApi; @@ -44,404 +47,453 @@ import uristqwerty.CraftGuide.api.*; import uristqwerty.gui_craftguide.texture.DynamicTexture; import uristqwerty.gui_craftguide.texture.TextureClip; -import javax.annotation.Nullable; -import java.util.Arrays; -import java.util.List; +public final class CraftGuide + extends CraftGuideAPIObject implements IIntegrationModule, RecipeProvider { + private static final int SLOT_SIZE = 16; + private static final int TEXTURE_WIDTH = 79; + private static final int TEXTURE_HEIGHT = 58; + private static final int GRINDER_RATIO = 10000; + private static final Slot[] GRINDER_SLOTS = { + new ItemSlot(3, 21, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(41, 21, SLOT_SIZE, SLOT_SIZE, true) + .drawOwnBackground() + .setSlotType(SlotType.OUTPUT_SLOT), + new ChanceSlot(59, 12, SLOT_SIZE, SLOT_SIZE, true) + .setRatio(GRINDER_RATIO) + .setFormatString(" (%1$.2f%% chance)") + .drawOwnBackground() + .setSlotType(SlotType.OUTPUT_SLOT), + new ChanceSlot(59, 30, SLOT_SIZE, SLOT_SIZE, true) + .setRatio(GRINDER_RATIO) + .setFormatString(" (%1$.2f%% chance)") + .drawOwnBackground() + .setSlotType(SlotType.OUTPUT_SLOT), + new ItemSlot(22, 12, SLOT_SIZE, SLOT_SIZE).setSlotType(SlotType.MACHINE_SLOT), + new ItemSlot(22, 30, SLOT_SIZE, SLOT_SIZE).setSlotType(SlotType.MACHINE_SLOT) + }; + private static final Slot[] INSCRIBER_SLOTS = { + new ItemSlot(12, 21, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(21, 3, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(21, 39, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(50, 21, SLOT_SIZE, SLOT_SIZE, true) + .drawOwnBackground() + .setSlotType(SlotType.OUTPUT_SLOT), + new ItemSlot(31, 21, SLOT_SIZE, SLOT_SIZE).setSlotType(SlotType.MACHINE_SLOT) + }; + private static final Slot[] SHAPELESS_CRAFTING_SLOTS = { + new ItemSlot(3, 3, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(21, 3, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(39, 3, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(3, 21, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(21, 21, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(39, 21, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(3, 39, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(21, 39, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(39, 39, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(59, 21, SLOT_SIZE, SLOT_SIZE, true) + .setSlotType(SlotType.OUTPUT_SLOT), + }; + private static final Slot[] CRAFTING_SLOTS_OWN_BG = { + new ItemSlot(3, 3, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(21, 3, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(39, 3, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(3, 21, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(21, 21, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(39, 21, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(3, 39, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(21, 39, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(39, 39, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(59, 21, SLOT_SIZE, SLOT_SIZE, true) + .setSlotType(SlotType.OUTPUT_SLOT) + .drawOwnBackground(), + }; + private static final Slot[] SMALL_CRAFTING_SLOTS_OWN_BG = { + new ItemSlot(12, 12, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(30, 12, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(12, 30, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(30, 30, SLOT_SIZE, SLOT_SIZE).drawOwnBackground(), + new ItemSlot(59, 21, SLOT_SIZE, SLOT_SIZE, true) + .setSlotType(SlotType.OUTPUT_SLOT) + .drawOwnBackground(), + }; + private static final Slot[] CRTAFTING_SLOTS = { + new ItemSlot(3, 3, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(21, 3, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(39, 3, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(3, 21, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(21, 21, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(39, 21, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(3, 39, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(21, 39, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(39, 39, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(59, 21, SLOT_SIZE, SLOT_SIZE, true) + .setSlotType(SlotType.OUTPUT_SLOT), + }; + private static final Slot[] SMALL_CRAFTING_SLOTS = { + new ItemSlot(12, 12, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(30, 12, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(12, 30, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(30, 30, SLOT_SIZE, SLOT_SIZE), + new ItemSlot(59, 21, SLOT_SIZE, SLOT_SIZE, true) + .setSlotType(SlotType.OUTPUT_SLOT), + }; -public final class CraftGuide extends CraftGuideAPIObject implements IIntegrationModule, RecipeProvider -{ - private static final int SLOT_SIZE = 16; - private static final int TEXTURE_WIDTH = 79; - private static final int TEXTURE_HEIGHT = 58; - private static final int GRINDER_RATIO = 10000; + @Reflected + public static CraftGuide instance; - private static final Slot[] GRINDER_SLOTS = { - new ItemSlot( 3, 21, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 41, 21, SLOT_SIZE, SLOT_SIZE, true ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), - new ChanceSlot( 59, 12, SLOT_SIZE, SLOT_SIZE, true ).setRatio( GRINDER_RATIO ).setFormatString( " (%1$.2f%% chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), - new ChanceSlot( 59, 30, SLOT_SIZE, SLOT_SIZE, true ).setRatio( GRINDER_RATIO ).setFormatString( " (%1$.2f%% chance)" ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), - new ItemSlot( 22, 12, SLOT_SIZE, SLOT_SIZE ).setSlotType( SlotType.MACHINE_SLOT ), - new ItemSlot( 22, 30, SLOT_SIZE, SLOT_SIZE ).setSlotType( SlotType.MACHINE_SLOT ) - }; - private static final Slot[] INSCRIBER_SLOTS = { - new ItemSlot( 12, 21, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 21, 3, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 21, 39, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 50, 21, SLOT_SIZE, SLOT_SIZE, true ).drawOwnBackground().setSlotType( SlotType.OUTPUT_SLOT ), - new ItemSlot( 31, 21, SLOT_SIZE, SLOT_SIZE ).setSlotType( SlotType.MACHINE_SLOT ) - }; - private static final Slot[] SHAPELESS_CRAFTING_SLOTS = { - new ItemSlot( 3, 3, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 21, 3, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 39, 3, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 3, 21, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 21, 21, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 39, 21, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 3, 39, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 21, 39, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 39, 39, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 59, 21, SLOT_SIZE, SLOT_SIZE, true ).setSlotType( SlotType.OUTPUT_SLOT ), - }; - private static final Slot[] CRAFTING_SLOTS_OWN_BG = { - new ItemSlot( 3, 3, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 21, 3, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 39, 3, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 3, 21, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 21, 21, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 39, 21, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 3, 39, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 21, 39, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 39, 39, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 59, 21, SLOT_SIZE, SLOT_SIZE, true ).setSlotType( SlotType.OUTPUT_SLOT ).drawOwnBackground(), - }; - private static final Slot[] SMALL_CRAFTING_SLOTS_OWN_BG = { - new ItemSlot( 12, 12, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 30, 12, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 12, 30, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 30, 30, SLOT_SIZE, SLOT_SIZE ).drawOwnBackground(), - new ItemSlot( 59, 21, SLOT_SIZE, SLOT_SIZE, true ).setSlotType( SlotType.OUTPUT_SLOT ).drawOwnBackground(), - }; - private static final Slot[] CRTAFTING_SLOTS = { - new ItemSlot( 3, 3, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 21, 3, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 39, 3, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 3, 21, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 21, 21, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 39, 21, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 3, 39, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 21, 39, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 39, 39, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 59, 21, SLOT_SIZE, SLOT_SIZE, true ).setSlotType( SlotType.OUTPUT_SLOT ), - }; - private static final Slot[] SMALL_CRAFTING_SLOTS = { - new ItemSlot( 12, 12, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 30, 12, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 12, 30, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 30, 30, SLOT_SIZE, SLOT_SIZE ), - new ItemSlot( 59, 21, SLOT_SIZE, SLOT_SIZE, true ).setSlotType( SlotType.OUTPUT_SLOT ), - }; + public CraftGuide() { + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.CraftGuideLog.class); + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.DefaultRecipeTemplate.class); + IntegrationHelper.testClassExistence( + this, uristqwerty.CraftGuide.RecipeGeneratorImplementation.class + ); + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.api.ChanceSlot.class); + IntegrationHelper.testClassExistence( + this, uristqwerty.CraftGuide.api.CraftGuideAPIObject.class + ); + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.api.ItemSlot.class); + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.api.RecipeGenerator.class); + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.api.RecipeProvider.class); + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.api.RecipeTemplate.class); + IntegrationHelper.testClassExistence(this, uristqwerty.CraftGuide.api.Slot.class); + IntegrationHelper + .testClassExistence(this, uristqwerty.CraftGuide.api.SlotType.class); + IntegrationHelper.testClassExistence( + this, uristqwerty.gui_craftguide.texture.DynamicTexture.class + ); + IntegrationHelper.testClassExistence( + this, uristqwerty.gui_craftguide.texture.TextureClip.class + ); + } - @Reflected - public static CraftGuide instance; + @Override + public void init() throws Throwable {} - public CraftGuide() - { - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.CraftGuideLog.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.DefaultRecipeTemplate.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.RecipeGeneratorImplementation.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.ChanceSlot.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.CraftGuideAPIObject.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.ItemSlot.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.RecipeGenerator.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.RecipeProvider.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.RecipeTemplate.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.Slot.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.CraftGuide.api.SlotType.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.gui_craftguide.texture.DynamicTexture.class ); - IntegrationHelper.testClassExistence( this, uristqwerty.gui_craftguide.texture.TextureClip.class ); - } + @Override + public void postInit() {} - @Override - public void init() throws Throwable - { - } + @Override + public void generateRecipes(final RecipeGenerator generator) { + final RecipeTemplate craftingTemplate; + final RecipeTemplate smallTemplate; - @Override - public void postInit() - { - } + if (uristqwerty.CraftGuide.CraftGuide.newerBackgroundStyle) { + craftingTemplate + = generator.createRecipeTemplate(CRAFTING_SLOTS_OWN_BG, null); + smallTemplate + = generator.createRecipeTemplate(SMALL_CRAFTING_SLOTS_OWN_BG, null); + } else { + final TextureClip craftingBG = new TextureClip( + DynamicTexture.instance("recipe_backgrounds"), + 1, + 1, + TEXTURE_WIDTH, + TEXTURE_HEIGHT + ); + final TextureClip craftingSelected = new TextureClip( + DynamicTexture.instance("recipe_backgrounds"), + 82, + 1, + TEXTURE_WIDTH, + TEXTURE_HEIGHT + ); + craftingTemplate = new DefaultRecipeTemplate( + CRTAFTING_SLOTS, + RecipeGeneratorImplementation.workbench, + craftingBG, + craftingSelected + ); - @Override - public void generateRecipes( final RecipeGenerator generator ) - { - final RecipeTemplate craftingTemplate; - final RecipeTemplate smallTemplate; + final TextureClip smallBG = new TextureClip( + DynamicTexture.instance("recipe_backgrounds"), + 1, + 61, + TEXTURE_WIDTH, + TEXTURE_HEIGHT + ); + final TextureClip smallSelected = new TextureClip( + DynamicTexture.instance("recipe_backgrounds"), + 82, + 61, + TEXTURE_WIDTH, + TEXTURE_HEIGHT + ); + smallTemplate = new DefaultRecipeTemplate( + SMALL_CRAFTING_SLOTS, + RecipeGeneratorImplementation.workbench, + smallBG, + smallSelected + ); + } - if( uristqwerty.CraftGuide.CraftGuide.newerBackgroundStyle ) - { - craftingTemplate = generator.createRecipeTemplate( CRAFTING_SLOTS_OWN_BG, null ); - smallTemplate = generator.createRecipeTemplate( SMALL_CRAFTING_SLOTS_OWN_BG, null ); - } - else - { - final TextureClip craftingBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 1, TEXTURE_WIDTH, TEXTURE_HEIGHT ); - final TextureClip craftingSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 1, TEXTURE_WIDTH, TEXTURE_HEIGHT ); - craftingTemplate = new DefaultRecipeTemplate( CRTAFTING_SLOTS, RecipeGeneratorImplementation.workbench, craftingBG, craftingSelected ); + final TextureClip shapelessBG = new TextureClip( + DynamicTexture.instance("recipe_backgrounds"), + 1, + 121, + TEXTURE_WIDTH, + TEXTURE_HEIGHT + ); + final TextureClip shapelessSelected = new TextureClip( + DynamicTexture.instance("recipe_backgrounds"), + 82, + 121, + TEXTURE_WIDTH, + TEXTURE_HEIGHT + ); + final RecipeTemplate shapelessTemplate = new DefaultRecipeTemplate( + SHAPELESS_CRAFTING_SLOTS, + RecipeGeneratorImplementation.workbench, + shapelessBG, + shapelessSelected + ); - final TextureClip smallBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 61, TEXTURE_WIDTH, TEXTURE_HEIGHT ); - final TextureClip smallSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 61, TEXTURE_WIDTH, TEXTURE_HEIGHT ); - smallTemplate = new DefaultRecipeTemplate( SMALL_CRAFTING_SLOTS, RecipeGeneratorImplementation.workbench, smallBG, smallSelected ); - } + this.addCraftingRecipes( + craftingTemplate, smallTemplate, shapelessTemplate, generator + ); - final TextureClip shapelessBG = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 1, 121, TEXTURE_WIDTH, TEXTURE_HEIGHT ); - final TextureClip shapelessSelected = new TextureClip( DynamicTexture.instance( "recipe_backgrounds" ), 82, 121, TEXTURE_WIDTH, TEXTURE_HEIGHT ); - final RecipeTemplate shapelessTemplate = new DefaultRecipeTemplate( SHAPELESS_CRAFTING_SLOTS, RecipeGeneratorImplementation.workbench, shapelessBG, shapelessSelected ); + final IAppEngApi api = AEApi.instance(); + final IBlocks aeBlocks = api.definitions().blocks(); + final Optional grindstone = aeBlocks.grindStone().maybeStack(1); + final Optional inscriber = aeBlocks.inscriber().maybeStack(1); - this.addCraftingRecipes( craftingTemplate, smallTemplate, shapelessTemplate, generator ); + if (grindstone.isPresent()) { + this.addGrinderRecipes(api, grindstone.get(), generator); + } - final IAppEngApi api = AEApi.instance(); - final IBlocks aeBlocks = api.definitions().blocks(); - final Optional grindstone = aeBlocks.grindStone().maybeStack( 1 ); - final Optional inscriber = aeBlocks.inscriber().maybeStack( 1 ); + if (inscriber.isPresent()) { + this.addInscriberRecipes(api, inscriber.get(), generator); + } + } - if( grindstone.isPresent() ) - { - this.addGrinderRecipes( api, grindstone.get(), generator ); - } + @SuppressWarnings("unchecked") + private List getUncheckedRecipes() { + return (List) CraftingManager.getInstance().getRecipeList(); + } - if( inscriber.isPresent() ) - { - this.addInscriberRecipes( api, inscriber.get(), generator ); - } - } + private void addCraftingRecipes( + final RecipeTemplate template, + final RecipeTemplate templateSmall, + final RecipeTemplate templateShapeless, + final RecipeGenerator generator + ) { + final List recipes = this.getUncheckedRecipes(); - @SuppressWarnings( "unchecked" ) - private List getUncheckedRecipes() - { - return (List) CraftingManager.getInstance().getRecipeList(); - } + int errCount = 0; - private void addCraftingRecipes( final RecipeTemplate template, final RecipeTemplate templateSmall, final RecipeTemplate templateShapeless, final RecipeGenerator generator ) - { - final List recipes = this.getUncheckedRecipes(); + for (final IRecipe recipe : recipes) { + try { + final Object[] items = this.getCraftingRecipe(recipe, true); - int errCount = 0; + if (items == null) { + continue; + } + if (items.length == 5) { + generator.addRecipe(templateSmall, items); + } else if (recipe instanceof ShapelessRecipe) { + generator.addRecipe(templateShapeless, items); + } else { + generator.addRecipe(template, items); + } + } catch (final Exception e) { + if (errCount >= 5) { + CraftGuideLog.log( + "AppEng CraftGuide integration: 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 + ); + } else { + e.printStackTrace(); + } + errCount++; - for( final IRecipe recipe : recipes ) - { - try - { - final Object[] items = this.getCraftingRecipe( recipe, true ); + CraftGuideLog.log(e); + } + } + } - if( items == null ) - { - continue; - } - if( items.length == 5 ) - { - generator.addRecipe( templateSmall, items ); - } - else if( recipe instanceof ShapelessRecipe ) - { - generator.addRecipe( templateShapeless, items ); - } - else - { - generator.addRecipe( template, items ); - } - } - catch( final Exception e ) - { - if( errCount >= 5 ) - { - CraftGuideLog.log( "AppEng CraftGuide integration: 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 ); - } - else - { - e.printStackTrace(); - } - errCount++; + private void addGrinderRecipes( + final IAppEngApi api, final ItemStack grindstone, final RecipeGenerator generator + ) { + final ItemStack handle + = api.definitions().blocks().crankHandle().maybeStack(1).orNull(); + final RecipeTemplate grinderTemplate + = generator.createRecipeTemplate(GRINDER_SLOTS, grindstone); - CraftGuideLog.log( e ); - } - } - } + for (final IGrinderEntry recipe : api.registries().grinder().getRecipes()) { + generator.addRecipe( + grinderTemplate, + new Object[] { + recipe.getInput(), + recipe.getOutput(), + new Object[] { recipe.getOptionalOutput(), + (int) (recipe.getOptionalChance() * GRINDER_RATIO) }, + new Object[] { recipe.getSecondOptionalOutput(), + (int) (recipe.getOptionalChance() * GRINDER_RATIO) }, + handle, + grindstone } + ); + } + } - private void addGrinderRecipes( final IAppEngApi api, final ItemStack grindstone, final RecipeGenerator generator ) - { - final ItemStack handle = api.definitions().blocks().crankHandle().maybeStack( 1 ).orNull(); - final RecipeTemplate grinderTemplate = generator.createRecipeTemplate( GRINDER_SLOTS, grindstone ); + private void addInscriberRecipes( + final IAppEngApi api, final ItemStack inscriber, final RecipeGenerator generator + ) { + final RecipeTemplate inscriberTemplate + = generator.createRecipeTemplate(INSCRIBER_SLOTS, inscriber); - for( final IGrinderEntry recipe : api.registries().grinder().getRecipes() ) - { - generator.addRecipe( grinderTemplate, new Object[] { - recipe.getInput(), - recipe.getOutput(), - new Object[] { - recipe.getOptionalOutput(), - (int) ( recipe.getOptionalChance() * GRINDER_RATIO ) - }, - new Object[] { - recipe.getSecondOptionalOutput(), - (int) ( recipe.getOptionalChance() * GRINDER_RATIO ) - }, - handle, - grindstone - } ); - } - } + for (final IInscriberRecipe recipe : api.registries().inscriber().getRecipes()) { + generator.addRecipe( + inscriberTemplate, + new Object[] { recipe.getInputs(), + recipe.getTopOptional().orNull(), + recipe.getBottomOptional().orNull(), + recipe.getOutput(), + inscriber } + ); + } + } - private void addInscriberRecipes( final IAppEngApi api, final ItemStack inscriber, final RecipeGenerator generator ) - { - final RecipeTemplate inscriberTemplate = generator.createRecipeTemplate( INSCRIBER_SLOTS, inscriber ); + private Object[] getCraftingShapelessRecipe( + final List items, final ItemStack recipeOutput + ) { + final Object[] output = new Object[10]; - for( final IInscriberRecipe recipe : api.registries().inscriber().getRecipes() ) - { - generator.addRecipe( inscriberTemplate, new Object[] { - recipe.getInputs(), - recipe.getTopOptional().orNull(), - recipe.getBottomOptional().orNull(), - recipe.getOutput(), - inscriber - } ); - } - } + for (int i = 0; i < items.size(); i++) { + output[i] = items.get(i); - private Object[] getCraftingShapelessRecipe( final List items, final ItemStack recipeOutput ) - { - final Object[] output = new Object[10]; + if (output[i] instanceof ItemStack[]) { + output[i] = Arrays.asList((ItemStack[]) output[i]); + } - for( int i = 0; i < items.size(); i++ ) - { - output[i] = items.get( i ); + if (output[i] instanceof IIngredient) { + try { + output[i] = this.toCG(((IIngredient) output[i]).getItemStackSet()); + } catch (final RegistrationError ignored) { + } catch (final MissingIngredientError ignored) {} + } + } - if( output[i] instanceof ItemStack[] ) - { - output[i] = Arrays.asList( (ItemStack[]) output[i] ); - } + output[9] = recipeOutput; - if( output[i] instanceof IIngredient ) - { - try - { - output[i] = this.toCG( ( (IIngredient) output[i] ).getItemStackSet() ); - } - catch( final RegistrationError ignored ) - { + return output; + } - } - catch( final MissingIngredientError ignored ) - { + private Object[] getSmallShapedRecipe( + final int width, + final int height, + final Object[] items, + final ItemStack recipeOutput + ) { + final Object[] output = new Object[5]; - } - } - } + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + final int i = y * 2 + x; + output[i] = items[y * width + x]; - output[9] = recipeOutput; + if (output[i] instanceof ItemStack[]) { + output[i] = Arrays.asList((ItemStack[]) output[i]); + } - return output; - } + if (output[i] instanceof IIngredient) { + try { + output[i] + = this.toCG(((IIngredient) output[i]).getItemStackSet()); + } catch (final RegistrationError ignored) { + } catch (final MissingIngredientError ignored) {} + } + } + } - private Object[] getSmallShapedRecipe( final int width, final int height, final Object[] items, final ItemStack recipeOutput ) - { - final Object[] output = new Object[5]; + output[4] = recipeOutput; - for( int y = 0; y < height; y++ ) - { - for( int x = 0; x < width; x++ ) - { - final int i = y * 2 + x; - output[i] = items[y * width + x]; + return output; + } - if( output[i] instanceof ItemStack[] ) - { - output[i] = Arrays.asList( (ItemStack[]) output[i] ); - } + private Object[] getCraftingShapedRecipe( + final int width, + final int height, + final Object[] items, + final ItemStack recipeOutput + ) { + final Object[] output = new Object[10]; - if( output[i] instanceof IIngredient ) - { - try - { - output[i] = this.toCG( ( (IIngredient) output[i] ).getItemStackSet() ); - } - catch( final RegistrationError ignored ) - { + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + final int i = y * 3 + x; + output[i] = items[y * width + x]; - } - catch( final MissingIngredientError ignored ) - { + 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 (final RegistrationError ignored) { + } catch (final MissingIngredientError ignored) {} + } + } + } - output[4] = recipeOutput; + output[9] = recipeOutput; - return output; - } + return output; + } - private Object[] getCraftingShapedRecipe( final int width, final int height, final Object[] items, final ItemStack recipeOutput ) - { - final Object[] output = new Object[10]; + private Object toCG(final ItemStack[] itemStackSet) { + final List list = Arrays.asList(itemStackSet); - for( int y = 0; y < height; y++ ) - { - for( int x = 0; x < width; x++ ) - { - final int i = y * 3 + x; - output[i] = items[y * width + x]; + for (int x = 0; x < list.size(); x++) { + list.set(x, list.get(x).copy()); + if (list.get(x).stackSize == 0) { + list.get(x).stackSize = 1; + } + } - if( output[i] instanceof ItemStack[] ) - { - output[i] = Arrays.asList( (ItemStack[]) output[i] ); - } + return list; + } - if( output[i] instanceof IIngredient ) - { - try - { - output[i] = this.toCG( ( (IIngredient) output[i] ).getItemStackSet() ); - } - catch( final RegistrationError ignored ) - { + @Nullable + private Object[] getCraftingRecipe( + final IRecipe recipe, final boolean allowSmallGrid + ) { + if (recipe instanceof ShapelessRecipe) { + final List items = ReflectionHelper.getPrivateValue( + ShapelessRecipe.class, (ShapelessRecipe) recipe, "input" + ); - } - catch( final MissingIngredientError ignored ) - { + return this.getCraftingShapelessRecipe(items, recipe.getRecipeOutput()); + } else if (recipe instanceof ShapedRecipe) { + final int width = ReflectionHelper.getPrivateValue( + ShapedRecipe.class, (ShapedRecipe) recipe, "width" + ); + final int height = ReflectionHelper.getPrivateValue( + ShapedRecipe.class, (ShapedRecipe) recipe, "height" + ); + final Object[] items = ReflectionHelper.getPrivateValue( + ShapedRecipe.class, (ShapedRecipe) recipe, "input" + ); - } - } - } - } + if (allowSmallGrid && width < 3 && height < 3) { + return this.getSmallShapedRecipe( + width, height, items, recipe.getRecipeOutput() + ); + } else { + return this.getCraftingShapedRecipe( + width, height, items, recipe.getRecipeOutput() + ); + } + } - output[9] = recipeOutput; - - return output; - } - - private Object toCG( final ItemStack[] itemStackSet ) - { - final List list = Arrays.asList( itemStackSet ); - - for( int x = 0; x < list.size(); x++ ) - { - list.set( x, list.get( x ).copy() ); - if( list.get( x ).stackSize == 0 ) - { - list.get( x ).stackSize = 1; - } - } - - return list; - } - - @Nullable - private Object[] getCraftingRecipe( final IRecipe recipe, final boolean allowSmallGrid ) - { - if( recipe instanceof ShapelessRecipe ) - { - final List items = ReflectionHelper.getPrivateValue( ShapelessRecipe.class, (ShapelessRecipe) recipe, "input" ); - - return this.getCraftingShapelessRecipe( items, recipe.getRecipeOutput() ); - } - else if( recipe instanceof ShapedRecipe ) - { - final int width = ReflectionHelper.getPrivateValue( ShapedRecipe.class, (ShapedRecipe) recipe, "width" ); - final int height = ReflectionHelper.getPrivateValue( ShapedRecipe.class, (ShapedRecipe) recipe, "height" ); - final Object[] items = ReflectionHelper.getPrivateValue( ShapedRecipe.class, (ShapedRecipe) recipe, "input" ); - - if( allowSmallGrid && width < 3 && height < 3 ) - { - return this.getSmallShapedRecipe( width, height, items, recipe.getRecipeOutput() ); - } - else - { - return this.getCraftingShapedRecipe( width, height, items, recipe.getRecipeOutput() ); - } - } - - return null; - } + return null; + } } diff --git a/src/main/java/appeng/integration/modules/DSU.java b/src/main/java/appeng/integration/modules/DSU.java index bc8ed1ef..66478771 100644 --- a/src/main/java/appeng/integration/modules/DSU.java +++ b/src/main/java/appeng/integration/modules/DSU.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.storage.IMEInventory; import appeng.helpers.Reflected; @@ -30,38 +29,34 @@ import appeng.integration.modules.helpers.MinefactoryReloadedDeepStorageUnit; import net.minecraft.tileentity.TileEntity; import powercrystals.minefactoryreloaded.api.IDeepStorageUnit; +public class DSU implements IDSU, IIntegrationModule { + @Reflected + public static DSU instance; -public class DSU implements IDSU, IIntegrationModule -{ - @Reflected - public static DSU instance; + @Reflected + public DSU() { + IntegrationHelper.testClassExistence( + this, powercrystals.minefactoryreloaded.api.IDeepStorageUnit.class + ); + } - @Reflected - public DSU() - { - IntegrationHelper.testClassExistence( this, powercrystals.minefactoryreloaded.api.IDeepStorageUnit.class ); - } + @Override + public IMEInventory getDSU(final TileEntity te) { + return new MinefactoryReloadedDeepStorageUnit(te); + } - @Override - public IMEInventory getDSU( final TileEntity te ) - { - return new MinefactoryReloadedDeepStorageUnit( te ); - } + @Override + public boolean isDSU(final TileEntity te) { + return te instanceof IDeepStorageUnit; + } - @Override - public boolean isDSU( final TileEntity te ) - { - return te instanceof IDeepStorageUnit; - } + @Override + public void init() {} - @Override - public void init() - { - } - - @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new MFRDSUHandler() ); - } + @Override + public void postInit() { + 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 9af4b9a7..bc42f1ad 100644 --- a/src/main/java/appeng/integration/modules/FMP.java +++ b/src/main/java/appeng/integration/modules/FMP.java @@ -18,6 +18,8 @@ package appeng.integration.modules; +import java.util.Collection; +import java.util.List; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -49,172 +51,143 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; -import java.util.Collection; -import java.util.List; +public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IFMP { + @Reflected + public static FMP instance; + @Override + public TMultiPart createPart(final String name, final boolean client) { + for (final PartRegistry pr : PartRegistry.values()) { + if (pr.getName().equals(name)) { + return pr.construct(0); + } + } -public class FMP implements IIntegrationModule, IPartFactory, IPartConverter, IFMP -{ - @Reflected - public static FMP instance; + return null; + } - @Override - public TMultiPart createPart( final String name, final boolean client ) - { - for( final PartRegistry pr : PartRegistry.values() ) - { - if( pr.getName().equals( name ) ) - { - return pr.construct( 0 ); - } - } + @Override + public TMultiPart convert(final World world, final BlockCoord pos) { + final Block blk = world.getBlock(pos.x, pos.y, pos.z); + final int meta = world.getBlockMetadata(pos.x, pos.y, pos.z); - return null; - } + final TMultiPart part = PartRegistry.getPartByBlock(blk, meta); + if (part instanceof CableBusPart) { + final CableBusPart cbp = (CableBusPart) part; + cbp.convertFromTile(world.getTileEntity(pos.x, pos.y, pos.z)); + } - @Override - public TMultiPart convert( final World world, final BlockCoord pos ) - { - final Block blk = world.getBlock( pos.x, pos.y, pos.z ); - final int meta = world.getBlockMetadata( pos.x, pos.y, pos.z ); + return part; + } - final TMultiPart part = PartRegistry.getPartByBlock( blk, meta ); - if( part instanceof CableBusPart ) - { - final CableBusPart cbp = (CableBusPart) part; - cbp.convertFromTile( world.getTileEntity( pos.x, pos.y, pos.z ) ); - } + @Override + public Iterable blockTypes() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final List blockTypes = Lists.newArrayListWithCapacity(2); - return part; - } + this.addBlockTypes(blockTypes, blocks.multiPart()); + this.addBlockTypes(blockTypes, blocks.quartzTorch()); - @Override - public Iterable blockTypes() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final List blockTypes = Lists.newArrayListWithCapacity( 2 ); + return blockTypes; + } - this.addBlockTypes( blockTypes, blocks.multiPart() ); - this.addBlockTypes( blockTypes, blocks.quartzTorch() ); + private void + addBlockTypes(final Collection blockTypes, final IBlockDefinition definition) { + for (final Block block : definition.maybeBlock().asSet()) { + blockTypes.add(block); + } + } - return blockTypes; - } + @Override + public void init() throws Throwable { + final IBlocks blocks = AEApi.instance().definitions().blocks(); - private void addBlockTypes( final Collection blockTypes, final IBlockDefinition definition ) - { - for( final Block block : definition.maybeBlock().asSet() ) - { - blockTypes.add( block ); - } - } + this.createAndRegister(blocks.quartz(), 0); + this.createAndRegister(blocks.quartzPillar(), 0); + this.createAndRegister(blocks.quartzChiseled(), 0); + this.createAndRegister(blocks.skyStone(), 0); + this.createAndRegister(blocks.skyStone(), 1); + this.createAndRegister(blocks.skyStone(), 2); + this.createAndRegister(blocks.skyStone(), 3); - @Override - public void init() throws Throwable - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); + final PartRegistry[] reg = PartRegistry.values(); - this.createAndRegister( blocks.quartz(), 0 ); - this.createAndRegister( blocks.quartzPillar(), 0 ); - this.createAndRegister( blocks.quartzChiseled(), 0 ); - this.createAndRegister( blocks.skyStone(), 0 ); - this.createAndRegister( blocks.skyStone(), 1 ); - this.createAndRegister( blocks.skyStone(), 2 ); - this.createAndRegister( blocks.skyStone(), 3 ); + final String[] data = new String[reg.length]; + for (int x = 0; x < data.length; x++) { + data[x] = reg[x].getName(); + } - final PartRegistry[] reg = PartRegistry.values(); + MultiPartRegistry.registerConverter(this); + MultiPartRegistry.registerParts(this, data); - final String[] data = new String[reg.length]; - for( int x = 0; x < data.length; x++ ) - { - data[x] = reg[x].getName(); - } + MultipartGenerator.registerPassThroughInterface("appeng.helpers.AEMultiTile"); + } - MultiPartRegistry.registerConverter( this ); - MultiPartRegistry.registerParts( this, data ); + private void createAndRegister(final IBlockDefinition definition, final int i) { + for (final Block block : definition.maybeBlock().asSet()) { + BlockMicroMaterial.createAndRegister(block, i); + } + } - MultipartGenerator.registerPassThroughInterface( "appeng.helpers.AEMultiTile" ); - } + @Override + public void postInit() { + MinecraftForge.EVENT_BUS.register(new FMPEvent()); + } - private void createAndRegister( final IBlockDefinition definition, final int i ) - { - for( final Block block : definition.maybeBlock().asSet() ) - { - BlockMicroMaterial.createAndRegister( block, i ); - } - } + @Override + public IPartHost getOrCreateHost(final TileEntity tile) { + try { + final BlockCoord loc = new BlockCoord(tile.xCoord, tile.yCoord, tile.zCoord); - @Override - public void postInit() - { - MinecraftForge.EVENT_BUS.register( new FMPEvent() ); - } + final TileMultipart mp + = TileMultipart.getOrConvertTile(tile.getWorldObj(), loc); + if (mp != null) { + final scala.collection.Iterator i = mp.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p instanceof CableBusPart) { + return (IPartHost) p; + } + } - @Override - public IPartHost getOrCreateHost( final TileEntity tile ) - { - try - { - final BlockCoord loc = new BlockCoord( tile.xCoord, tile.yCoord, tile.zCoord ); + return new FMPPlacementHelper(mp); + } + } catch (final Throwable t) { + AELog.debug(t); + } + return null; + } - final TileMultipart mp = TileMultipart.getOrConvertTile( tile.getWorldObj(), loc ); - if( mp != null ) - { - final scala.collection.Iterator i = mp.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p instanceof CableBusPart ) - { - return (IPartHost) p; - } - } + @Override + public CableBusContainer getCableContainer(final TileEntity te) { + if (te instanceof TileMultipart) { + final TileMultipart mp = (TileMultipart) te; + final scala.collection.Iterator i = mp.partList().iterator(); + while (i.hasNext()) { + final TMultiPart p = i.next(); + if (p instanceof CableBusPart) { + return ((CableBusPart) p).getCableBus(); + } + } + } + return null; + } - return new FMPPlacementHelper( mp ); - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - return null; - } + @Override + public void registerPassThrough(final Class layerInterface) { + try { + MultipartGenerator.registerPassThroughInterface(layerInterface.getName()); + } catch (final Throwable t) { + AELog.error( + "Failed to register " + layerInterface.getName() + + " with FMP, some features may not work with MultiParts." + ); + AELog.debug(t); + } + } - @Override - public CableBusContainer getCableContainer( final TileEntity te ) - { - if( te instanceof TileMultipart ) - { - final TileMultipart mp = (TileMultipart) te; - final scala.collection.Iterator i = mp.partList().iterator(); - while( i.hasNext() ) - { - final TMultiPart p = i.next(); - if( p instanceof CableBusPart ) - { - return ( (CableBusPart) p ).getCableBus(); - } - } - } - return null; - } - - @Override - public void registerPassThrough( final Class layerInterface ) - { - try - { - MultipartGenerator.registerPassThroughInterface( layerInterface.getName() ); - } - catch( final Throwable t ) - { - AELog.error( "Failed to register " + layerInterface.getName() + " with FMP, some features may not work with MultiParts." ); - AELog.debug( t ); - } - } - - @Override - public Event newFMPPacketEvent( final EntityPlayerMP sender ) - { - return new FMPPacketEvent( sender ); - } + @Override + public Event newFMPPacketEvent(final EntityPlayerMP sender) { + return new FMPPacketEvent(sender); + } } diff --git a/src/main/java/appeng/integration/modules/FZ.java b/src/main/java/appeng/integration/modules/FZ.java index 240e15ac..0c62dd1d 100644 --- a/src/main/java/appeng/integration/modules/FZ.java +++ b/src/main/java/appeng/integration/modules/FZ.java @@ -18,6 +18,9 @@ package appeng.integration.modules; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import appeng.api.AEApi; import appeng.api.storage.IMEInventory; @@ -30,184 +33,127 @@ import appeng.util.Platform; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - - /** * 100% Hacks. */ -public class FZ implements IFZ, IIntegrationModule -{ - @Reflected - public static FZ instance; +public class FZ implements IFZ, IIntegrationModule { + @Reflected + public static FZ instance; - private static Class day_BarrelClass; - private static Method day_getItemCount; - private static Method day_setItemCount; - private static Method day_getMaxSize; - private static Field day_item; + private static Class day_BarrelClass; + private static Method day_getItemCount; + private static Method day_setItemCount; + private static Method day_getMaxSize; + private static Field day_item; - @Override - public ItemStack barrelGetItem( final TileEntity te ) - { - try - { - ItemStack i = null; + @Override + public ItemStack barrelGetItem(final TileEntity te) { + try { + ItemStack i = null; - if( day_BarrelClass.isInstance( te ) ) - { - i = (ItemStack) day_item.get( te ); - } + if (day_BarrelClass.isInstance(te)) { + i = (ItemStack) day_item.get(te); + } - if( i != null ) - { - i = Platform.cloneItemStack( i ); - } + if (i != null) { + i = Platform.cloneItemStack(i); + } - return i; - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final IllegalAccessException ignored ) - { - } - return null; - } + return i; + } catch (final IllegalArgumentException ignored) { + } catch (final IllegalAccessException ignored) {} + return null; + } - @Override - public int barrelGetMaxItemCount( final TileEntity te ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - return (Integer) day_getMaxSize.invoke( te ); - } - } - catch( final IllegalAccessException ignored ) - { - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final InvocationTargetException ignored ) - { - } - return 0; - } + @Override + public int barrelGetMaxItemCount(final TileEntity te) { + try { + if (day_BarrelClass.isInstance(te)) { + return (Integer) day_getMaxSize.invoke(te); + } + } catch (final IllegalAccessException ignored) { + } catch (final IllegalArgumentException ignored) { + } catch (final InvocationTargetException ignored) {} + return 0; + } - @Override - public int barrelGetItemCount( final TileEntity te ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - return (Integer) day_getItemCount.invoke( te ); - } - } - catch( final IllegalAccessException ignored ) - { - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final InvocationTargetException ignored ) - { - } - return 0; - } + @Override + public int barrelGetItemCount(final TileEntity te) { + try { + if (day_BarrelClass.isInstance(te)) { + return (Integer) day_getItemCount.invoke(te); + } + } catch (final IllegalAccessException ignored) { + } catch (final IllegalArgumentException ignored) { + } catch (final InvocationTargetException ignored) {} + return 0; + } - @Override - public void setItemType( final TileEntity te, final ItemStack input ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - day_item.set( te, input == null ? null : input.copy() ); - } - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final IllegalAccessException ignored ) - { - } - } + @Override + public void setItemType(final TileEntity te, final ItemStack input) { + try { + if (day_BarrelClass.isInstance(te)) { + day_item.set(te, input == null ? null : input.copy()); + } + } catch (final IllegalArgumentException ignored) { + } catch (final IllegalAccessException ignored) {} + } - @Override - public void barrelSetCount( final TileEntity te, final int max ) - { - try - { - if( day_BarrelClass.isInstance( te ) ) - { - day_setItemCount.invoke( te, max ); - } + @Override + public void barrelSetCount(final TileEntity te, final int max) { + try { + if (day_BarrelClass.isInstance(te)) { + day_setItemCount.invoke(te, max); + } - te.markDirty(); - } - catch( final IllegalAccessException ignored ) - { - } - catch( final IllegalArgumentException ignored ) - { - } - catch( final InvocationTargetException ignored ) - { - } - } + te.markDirty(); + } catch (final IllegalAccessException ignored) { + } catch (final IllegalArgumentException ignored) { + } catch (final InvocationTargetException ignored) {} + } - @Override - public IMEInventory getFactorizationBarrel( final TileEntity te ) - { - return new FactorizationBarrel( this, te ); - } + @Override + public IMEInventory getFactorizationBarrel(final TileEntity te) { + return new FactorizationBarrel(this, te); + } - @Override - public boolean isBarrel( final TileEntity te ) - { - return day_BarrelClass.isAssignableFrom( te.getClass() ); - } + @Override + public boolean isBarrel(final TileEntity te) { + return day_BarrelClass.isAssignableFrom(te.getClass()); + } - @Override - public void grinderRecipe( final ItemStack in, final ItemStack out ) - { - try - { - final Class c = Class.forName( "factorization.oreprocessing.TileEntityGrinder" ); - final Method m = c.getMethod( "addRecipe", Object.class, ItemStack.class, float.class ); + @Override + public void grinderRecipe(final ItemStack in, final ItemStack out) { + try { + final Class c + = Class.forName("factorization.oreprocessing.TileEntityGrinder"); + final Method m + = c.getMethod("addRecipe", Object.class, ItemStack.class, float.class); - final float amt = out.stackSize; - out.stackSize = 1; + final float amt = out.stackSize; + out.stackSize = 1; - m.invoke( c, in, out, amt ); - } - catch( final Throwable t ) - { - // AELog.info( "" ); - // throw new RuntimeException( t ); - } - } + m.invoke(c, in, out, amt); + } catch (final Throwable t) { + // AELog.info( "" ); + // throw new RuntimeException( t ); + } + } - @Override - public void init() throws Throwable - { - day_BarrelClass = Class.forName( "factorization.weird.TileEntityDayBarrel" ); + @Override + public void init() throws Throwable { + day_BarrelClass = Class.forName("factorization.weird.TileEntityDayBarrel"); - day_getItemCount = day_BarrelClass.getDeclaredMethod( "getItemCount" ); - day_setItemCount = day_BarrelClass.getDeclaredMethod( "setItemCount", int.class ); - day_getMaxSize = day_BarrelClass.getDeclaredMethod( "getMaxSize" ); - day_item = day_BarrelClass.getDeclaredField( "item" ); - } + day_getItemCount = day_BarrelClass.getDeclaredMethod("getItemCount"); + day_setItemCount = day_BarrelClass.getDeclaredMethod("setItemCount", int.class); + day_getMaxSize = day_BarrelClass.getDeclaredMethod("getMaxSize"); + day_item = day_BarrelClass.getDeclaredField("item"); + } - @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new FactorizationHandler() ); - } + @Override + public void postInit() { + AEApi.instance().registries().externalStorage().addExternalStorageInterface( + new FactorizationHandler() + ); + } } diff --git a/src/main/java/appeng/integration/modules/IC2.java b/src/main/java/appeng/integration/modules/IC2.java index 2579187b..67d18460 100644 --- a/src/main/java/appeng/integration/modules/IC2.java +++ b/src/main/java/appeng/integration/modules/IC2.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -36,73 +35,82 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.MinecraftForge; +public class IC2 implements IIC2, IIntegrationModule { + @Reflected + public static IC2 instance; -public class IC2 implements IIC2, IIntegrationModule -{ - @Reflected - public static IC2 instance; + @Reflected + public IC2() { + IntegrationHelper.testClassExistence(this, ic2.api.energy.tile.IEnergyTile.class); + IntegrationHelper + .testClassExistence(this, ic2.api.recipe.RecipeInputItemStack.class); + } - @Reflected - public IC2() - { - IntegrationHelper.testClassExistence( this, ic2.api.energy.tile.IEnergyTile.class ); - IntegrationHelper.testClassExistence( this, ic2.api.recipe.RecipeInputItemStack.class ); - } + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + if (IntegrationRegistry.INSTANCE.isEnabled(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( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergySink", "ic2.api.energy.tile.IEnergySink" ); - partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergySource", "ic2.api.energy.tile.IEnergySource" ); - } - } + @Override + public void postInit() { + final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); + reg.addNewAttunement(this.getItem("copperCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement( + this.getItem("insulatedCopperCableItem"), TunnelType.IC2_POWER + ); + reg.addNewAttunement(this.getItem("goldCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement( + this.getItem("insulatedGoldCableItem"), TunnelType.IC2_POWER + ); + reg.addNewAttunement(this.getItem("ironCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement( + this.getItem("insulatedIronCableItem"), TunnelType.IC2_POWER + ); + reg.addNewAttunement(this.getItem("insulatedTinCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("glassFiberCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("tinCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("detectorCableItem"), TunnelType.IC2_POWER); + reg.addNewAttunement(this.getItem("splitterCableItem"), TunnelType.IC2_POWER); - @Override - public void postInit() - { - final IP2PTunnelRegistry reg = AEApi.instance().registries().p2pTunnel(); - reg.addNewAttunement( this.getItem( "copperCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedCopperCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "goldCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedGoldCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "ironCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedIronCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "insulatedTinCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "glassFiberCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "tinCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "detectorCableItem" ), TunnelType.IC2_POWER ); - reg.addNewAttunement( this.getItem( "splitterCableItem" ), TunnelType.IC2_POWER ); + // this is gone? + // AEApi.INSTANCE().registries().matterCannon().registerAmmo( getItem( + // "uraniumDrop" ), 238.0289 ); + } - // this is gone? - // AEApi.INSTANCE().registries().matterCannon().registerAmmo( getItem( "uraniumDrop" ), 238.0289 ); - } + @Override + public void addToEnergyNet(final TileEntity appEngTile) { + MinecraftForge.EVENT_BUS.post( + new ic2.api.energy.event.EnergyTileLoadEvent((IEnergyTile) appEngTile) + ); + } - @Override - public void addToEnergyNet( final TileEntity appEngTile ) - { - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergyTile) appEngTile ) ); - } + @Override + public void removeFromEnergyNet(final TileEntity appEngTile) { + MinecraftForge.EVENT_BUS.post( + new ic2.api.energy.event.EnergyTileUnloadEvent((IEnergyTile) appEngTile) + ); + } - @Override - public void removeFromEnergyNet( final TileEntity appEngTile ) - { - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergyTile) appEngTile ) ); - } + @Override + public ItemStack getItem(final String name) { + return ic2.api.item.IC2Items.getItem(name); + } - @Override - public ItemStack getItem( final String name ) - { - return ic2.api.item.IC2Items.getItem( name ); - } - - @Override - public void maceratorRecipe( final ItemStack in, final ItemStack out ) - { - ic2.api.recipe.Recipes.macerator.addRecipe( new RecipeInputItemStack( in, in.stackSize ), null, out ); - } + @Override + public void maceratorRecipe(final ItemStack in, final 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 7a7f532b..430f2c7e 100644 --- a/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java +++ b/src/main/java/appeng/integration/modules/ImmibisMicroblocks.java @@ -18,6 +18,7 @@ package appeng.integration.modules; +import java.lang.reflect.Method; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -37,106 +38,108 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.lang.reflect.Method; +public class ImmibisMicroblocks implements IImmibisMicroblocks, IIntegrationModule { + @Reflected + public static ImmibisMicroblocks instance; + private boolean canConvertTiles = false; -public class ImmibisMicroblocks implements IImmibisMicroblocks, IIntegrationModule -{ - @Reflected - public static ImmibisMicroblocks instance; + private Class MicroblockAPIUtils; + private Method mergeIntoMicroblockContainer; - private boolean canConvertTiles = false; + @Reflected + public ImmibisMicroblocks() { + IntegrationHelper.testClassExistence( + this, mods.immibis.core.api.multipart.IMultipartTile.class + ); + IntegrationHelper + .testClassExistence(this, mods.immibis.core.api.multipart.ICoverSystem.class); + IntegrationHelper.testClassExistence( + this, mods.immibis.core.api.multipart.IPartContainer.class + ); + } - private Class MicroblockAPIUtils; - private Method mergeIntoMicroblockContainer; + @Override + public void init() throws Throwable { + 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.canConvertTiles = true; + } catch (final Throwable t) { + AELog.debug(t); + } + } - @Reflected - public ImmibisMicroblocks() - { - IntegrationHelper.testClassExistence( this, mods.immibis.core.api.multipart.IMultipartTile.class ); - IntegrationHelper.testClassExistence( this, mods.immibis.core.api.multipart.ICoverSystem.class ); - IntegrationHelper.testClassExistence( this, mods.immibis.core.api.multipart.IPartContainer.class ); - } + @Override + public void postInit() {} - @Override - public void init() throws Throwable - { - 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.canConvertTiles = true; - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } + @Override + public IPartHost + getOrCreateHost(final EntityPlayer player, final int side, final TileEntity te) { + final World w = te.getWorldObj(); + final int x = te.xCoord; + final int y = te.yCoord; + final int z = te.zCoord; + final boolean isPartItem = player != null && player.getHeldItem() != null + && player.getHeldItem().getItem() instanceof IPartItem; - @Override - public void postInit() - { + if (te instanceof IMultipartTile && this.canConvertTiles && isPartItem) { + final IBlockDefinition multiPart + = AEApi.instance().definitions().blocks().multiPart(); + final Optional maybeMultiPartBlock = multiPart.maybeBlock(); + final Optional maybeMultiPartStack = multiPart.maybeStack(1); - } + final boolean multiPartPresent + = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent(); - @Override - public IPartHost getOrCreateHost( final EntityPlayer player, final int side, final TileEntity te ) - { - final World w = te.getWorldObj(); - final int x = te.xCoord; - final int y = te.yCoord; - final int z = te.zCoord; - final boolean isPartItem = player != null && player.getHeldItem() != null && player.getHeldItem().getItem() instanceof IPartItem; + if (multiPartPresent) { + final Block multiPartBlock = maybeMultiPartBlock.get(); + final ItemStack multiPartStack = maybeMultiPartStack.get(); - if( te instanceof IMultipartTile && this.canConvertTiles && isPartItem ) - { - final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); - final Optional maybeMultiPartBlock = multiPart.maybeBlock(); - final Optional maybeMultiPartStack = multiPart.maybeStack( 1 ); + try { + // ItemStack.class, EntityPlayer.class, World.class, + // 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 (final Throwable e) { + this.canConvertTiles = false; + return null; + } + } + } - final boolean multiPartPresent = maybeMultiPartBlock.isPresent() && maybeMultiPartStack.isPresent(); + final TileEntity tx = w.getTileEntity(x, y, z); + if (tx instanceof IPartHost) { + return (IPartHost) tx; + } - if( multiPartPresent ) - { - final Block multiPartBlock = maybeMultiPartBlock.get(); - final ItemStack multiPartStack = maybeMultiPartStack.get(); + return null; + } - try - { - // ItemStack.class, EntityPlayer.class, World.class, - // 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( final Throwable e ) - { - this.canConvertTiles = false; - return null; - } - } - } + @Override + public boolean leaveParts(final TileEntity te) { + if (te instanceof IMultipartTile) { + final ICoverSystem ci = ((IMultipartTile) te).getCoverSystem(); + if (ci != null) { + ci.convertToContainerBlock(); + } - final TileEntity tx = w.getTileEntity( x, y, z ); - if( tx instanceof IPartHost ) - { - return (IPartHost) tx; - } - - return null; - } - - @Override - public boolean leaveParts( final TileEntity te ) - { - if( te instanceof IMultipartTile ) - { - final ICoverSystem ci = ( (IMultipartTile) te ).getCoverSystem(); - if( ci != null ) - { - ci.convertToContainerBlock(); - } - - return true; - } - return false; - } + 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 d4039be7..b6f95c4b 100644 --- a/src/main/java/appeng/integration/modules/InvTweaks.java +++ b/src/main/java/appeng/integration/modules/InvTweaks.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; @@ -27,38 +26,34 @@ import cpw.mods.fml.common.Loader; import invtweaks.api.InvTweaksAPI; import net.minecraft.item.ItemStack; +public class InvTweaks implements IInvTweaks, IIntegrationModule { + @Reflected + public static InvTweaks instance; -public class InvTweaks implements IInvTweaks, IIntegrationModule -{ - @Reflected - public static InvTweaks instance; + static InvTweaksAPI api; - static InvTweaksAPI api; + @Reflected + public InvTweaks() { + IntegrationHelper.testClassExistence(this, invtweaks.api.InvTweaksAPI.class); + } - @Reflected - public InvTweaks() - { - IntegrationHelper.testClassExistence( this, invtweaks.api.InvTweaksAPI.class ); - } + @Override + public void init() { + api = (InvTweaksAPI) Loader.instance() + .getIndexedModList() + .get("inventorytweaks") + .getMod(); + } - @Override - public void init() - { - api = (InvTweaksAPI) Loader.instance().getIndexedModList().get( "inventorytweaks" ).getMod(); - } + @Override + public void postInit() { + if (api == null) { + throw new IllegalStateException("InvTweaks API Instance Failed."); + } + } - @Override - public void postInit() - { - if( api == null ) - { - throw new IllegalStateException( "InvTweaks API Instance Failed." ); - } - } - - @Override - public int compareItems( final ItemStack i, final ItemStack j ) - { - return api.compareItems( i, j ); - } + @Override + public int compareItems(final ItemStack i, final ItemStack j) { + return api.compareItems(i, j); + } } diff --git a/src/main/java/appeng/integration/modules/LPHelpers/LPPipeHandler.java b/src/main/java/appeng/integration/modules/LPHelpers/LPPipeHandler.java index 20bda566..034c98c3 100644 --- a/src/main/java/appeng/integration/modules/LPHelpers/LPPipeHandler.java +++ b/src/main/java/appeng/integration/modules/LPHelpers/LPPipeHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.LPHelpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -26,7 +25,6 @@ import appeng.api.storage.StorageChannel; import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.integration.abstraction.ILogisticsPipes; - import appeng.me.storage.MEMonitorIInventory; import appeng.util.inv.IMEAdaptor; import logisticspipes.api.ILPPipeTile; @@ -34,26 +32,32 @@ import logisticspipes.pipes.basic.CoreUnroutedPipe; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; - -public class LPPipeHandler implements IExternalStorageHandler -{ +public class LPPipeHandler implements IExternalStorageHandler { @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.LogisticsPipes ) ) - { - return channel == StorageChannel.ITEMS && te instanceof ILPPipeTile && - ( (CoreUnroutedPipe) ( (ILPPipeTile) te ).getLPPipe() ).canPipeConnect( te, d ); + public boolean canHandle( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource mySrc + ) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.LogisticsPipes)) { + return channel == StorageChannel.ITEMS && te instanceof ILPPipeTile + && ((CoreUnroutedPipe) ((ILPPipeTile) te).getLPPipe()) + .canPipeConnect(te, d); } return false; } @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src ) - { - if( channel == StorageChannel.ITEMS ) - { - return new MEMonitorIInventory( new IMEAdaptor( new LPPipeInventory( te, d ), src ) ); + public IMEInventory getInventory( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource src + ) { + if (channel == StorageChannel.ITEMS) { + return new MEMonitorIInventory(new IMEAdaptor(new LPPipeInventory(te, d), src) + ); } return null; } diff --git a/src/main/java/appeng/integration/modules/LPHelpers/LPPipeInventory.java b/src/main/java/appeng/integration/modules/LPHelpers/LPPipeInventory.java index f1f7e877..1ce380b7 100644 --- a/src/main/java/appeng/integration/modules/LPHelpers/LPPipeInventory.java +++ b/src/main/java/appeng/integration/modules/LPHelpers/LPPipeInventory.java @@ -18,6 +18,10 @@ package appeng.integration.modules.LPHelpers; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -30,7 +34,6 @@ import appeng.integration.IntegrationType; import appeng.integration.abstraction.ILogisticsPipes; import appeng.tile.grid.AENetworkInvTile; import appeng.util.item.AEItemStack; - import logisticspipes.api.ILPPipe; import logisticspipes.api.ILPPipeTile; import logisticspipes.api.IRequestAPI; @@ -39,46 +42,36 @@ import logisticspipes.proxy.SimpleServiceLocator; import logisticspipes.routing.ExitRoute; import logisticspipes.utils.AdjacentTile; import logisticspipes.utils.item.ItemIdentifier; - import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - - -public class LPPipeInventory implements IMEInventory -{ +public class LPPipeInventory implements IMEInventory { private final TileEntity te; private final ForgeDirection direction; - public LPPipeInventory( final TileEntity te, final ForgeDirection direction ) - { + public LPPipeInventory(final TileEntity te, final ForgeDirection direction) { this.te = te; this.direction = direction; } @Override - public IAEItemStack injectItems( IAEItemStack input, Actionable type, BaseActionSource src ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.LogisticsPipes ) ) - { - ILogisticsPipes registry = (ILogisticsPipes) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.LogisticsPipes ); + public IAEItemStack + injectItems(IAEItemStack input, Actionable type, BaseActionSource src) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.LogisticsPipes)) { + ILogisticsPipes registry = (ILogisticsPipes + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.LogisticsPipes); - if( type == Actionable.SIMULATE ) - { - if( registry.canAddItemsToPipe( this.te, input.getItemStack(), this.direction ) ) - { + if (type == Actionable.SIMULATE) { + if (registry.canAddItemsToPipe( + this.te, input.getItemStack(), this.direction + )) { return null; } return input; } - if( registry.addItemsToPipe( this.te, input.getItemStack(), this.direction ) ) - { + if (registry.addItemsToPipe(this.te, input.getItemStack(), this.direction)) { return null; } } @@ -87,31 +80,28 @@ public class LPPipeInventory implements IMEInventory } @Override - public IAEItemStack extractItems( IAEItemStack request, Actionable type, BaseActionSource src ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.LogisticsPipes ) ) - { - ILPPipe pipe = ( (ILPPipeTile) this.te ).getLPPipe(); - if( pipe instanceof IRequestAPI ) - { + public IAEItemStack + extractItems(IAEItemStack request, Actionable type, BaseActionSource src) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.LogisticsPipes)) { + ILPPipe pipe = ((ILPPipeTile) this.te).getLPPipe(); + if (pipe instanceof IRequestAPI) { IRequestAPI requestAPI = (IRequestAPI) pipe; - if( type == Actionable.SIMULATE ) - { - IRequestAPI.SimulationResult simulation = requestAPI.simulateRequest( request.getItemStack() ); - if( simulation.used.size() == 0 ) - { + if (type == Actionable.SIMULATE) { + IRequestAPI.SimulationResult simulation + = requestAPI.simulateRequest(request.getItemStack()); + if (simulation.used.size() == 0) { return null; } - return AEItemStack.create( simulation.used.get( 0 ) ); + return AEItemStack.create(simulation.used.get(0)); } - List returned = requestAPI.performRequest( request.getItemStack() ); - if( returned.size() == 0 ) - { + List returned + = requestAPI.performRequest(request.getItemStack()); + if (returned.size() == 0) { return null; } - return AEItemStack.create( returned.get( 0 ) ); + return AEItemStack.create(returned.get(0)); } } @@ -119,15 +109,12 @@ public class LPPipeInventory implements IMEInventory } @Override - public IItemList getAvailableItems( IItemList out ) - { - ILPPipe pipe = ( (ILPPipeTile) this.te ).getLPPipe(); - if( pipe instanceof IRequestAPI ) - { - List provided = this.getLPItems( pipe ); - for( ItemStack is : provided ) - { - out.add( AEItemStack.create( is ) ); + public IItemList getAvailableItems(IItemList out) { + ILPPipe pipe = ((ILPPipeTile) this.te).getLPPipe(); + if (pipe instanceof IRequestAPI) { + List provided = this.getLPItems(pipe); + for (ItemStack is : provided) { + out.add(AEItemStack.create(is)); } } return out; @@ -135,38 +122,37 @@ public class LPPipeInventory implements IMEInventory /** * Get items from Logistics Pipes network _excluding_ AE2 network items. Brilliant! - * (basically rewrite of CoreRoutedPipe.getProvidedItems() (implementation of IRequestAPI.getProvidedItems()) + * (basically rewrite of CoreRoutedPipe.getProvidedItems() (implementation of + * IRequestAPI.getProvidedItems()) * * @param pipe IRequestAPI pipe * @return list of items in shared networks */ - public List getLPItems( ILPPipe pipe ) - { + public List getLPItems(ILPPipe pipe) { CoreRoutedPipe coreRoutedPipeCast = (CoreRoutedPipe) pipe; - if( coreRoutedPipeCast.stillNeedReplace() ) - { + if (coreRoutedPipeCast.stillNeedReplace()) { return new ArrayList(); - } - else - { - List exitRoutes = coreRoutedPipeCast.getRouter().getIRoutersByCost(); + } else { + List exitRoutes + = coreRoutedPipeCast.getRouter().getIRoutersByCost(); ArrayList exitRoutesProcessed = new ArrayList(); - for( ExitRoute exitRoute : exitRoutes ) - { - if( !isExitToAE( exitRoute ) ) - { - exitRoutesProcessed.add( exitRoute ); + for (ExitRoute exitRoute : exitRoutes) { + if (!isExitToAE(exitRoute)) { + exitRoutesProcessed.add(exitRoute); } } - Map items = SimpleServiceLocator.logisticsManager.getAvailableItems( exitRoutesProcessed ); - ArrayList list = new ArrayList( items.size() ); + Map items = SimpleServiceLocator.logisticsManager.getAvailableItems( + exitRoutesProcessed + ); + ArrayList list = new ArrayList(items.size()); - for( Object o : items.entrySet() ) - { + for (Object o : items.entrySet()) { Map.Entry item = (Map.Entry) o; - ItemStack is = ( (ItemIdentifier) item.getKey() ).unsafeMakeNormalStack( ( (Integer) item.getValue() ).intValue() ); - list.add( is ); + ItemStack is + = ((ItemIdentifier) item.getKey()) + .unsafeMakeNormalStack(((Integer) item.getValue()).intValue()); + list.add(is); } return list; @@ -179,13 +165,11 @@ public class LPPipeInventory implements IMEInventory * @param exitRoute Logistics Pipes exit route to check * @return true if AENetworkInvTiles is connected, otherwise false */ - private boolean isExitToAE( ExitRoute exitRoute ) - { - LinkedList connectedEntities = exitRoute.destination.getPipe().getConnectedEntities(); - for( AdjacentTile connectedEntity : connectedEntities ) - { - if( connectedEntity.tile instanceof AENetworkInvTile ) - { + private boolean isExitToAE(ExitRoute exitRoute) { + LinkedList connectedEntities + = exitRoute.destination.getPipe().getConnectedEntities(); + for (AdjacentTile connectedEntity : connectedEntities) { + if (connectedEntity.tile instanceof AENetworkInvTile) { return true; } } @@ -193,8 +177,7 @@ public class LPPipeInventory implements IMEInventory } @Override - public StorageChannel getChannel() - { + public StorageChannel getChannel() { return StorageChannel.ITEMS; } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/LogisticsPipes.java b/src/main/java/appeng/integration/modules/LogisticsPipes.java index 1895d20d..b2a260ce 100644 --- a/src/main/java/appeng/integration/modules/LogisticsPipes.java +++ b/src/main/java/appeng/integration/modules/LogisticsPipes.java @@ -18,6 +18,7 @@ package appeng.integration.modules; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.helpers.Reflected; @@ -25,62 +26,57 @@ import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; import appeng.integration.abstraction.ILogisticsPipes; import appeng.integration.modules.LPHelpers.LPPipeHandler; - import buildcraft.api.transport.IInjectable; - import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; - - /** * @author Second_Fry * @version rv3 - 12.06.2015 * @since rv3 12.06.2015 */ @Reflected -public class LogisticsPipes implements ILogisticsPipes, IIntegrationModule -{ +public class LogisticsPipes implements ILogisticsPipes, IIntegrationModule { @Reflected public static LogisticsPipes instance; @Reflected - public LogisticsPipes() - { - IntegrationHelper.testClassExistence( this, logisticspipes.api.ILPPipe.class ); - IntegrationHelper.testClassExistence( this, logisticspipes.api.ILPPipeTile.class ); - IntegrationHelper.testClassExistence( this, logisticspipes.api.IRequestAPI.class ); - IntegrationHelper.testClassExistence( this, logisticspipes.pipes.basic.CoreRoutedPipe.class ); - IntegrationHelper.testClassExistence( this, logisticspipes.proxy.SimpleServiceLocator.class ); - IntegrationHelper.testClassExistence( this, logisticspipes.routing.ExitRoute.class ); - IntegrationHelper.testClassExistence( this, logisticspipes.utils.AdjacentTile.class ); - IntegrationHelper.testClassExistence( this, logisticspipes.utils.item.ItemIdentifier.class ); + public LogisticsPipes() { + IntegrationHelper.testClassExistence(this, logisticspipes.api.ILPPipe.class); + IntegrationHelper.testClassExistence(this, logisticspipes.api.ILPPipeTile.class); + IntegrationHelper.testClassExistence(this, logisticspipes.api.IRequestAPI.class); + IntegrationHelper + .testClassExistence(this, logisticspipes.pipes.basic.CoreRoutedPipe.class); + IntegrationHelper + .testClassExistence(this, logisticspipes.proxy.SimpleServiceLocator.class); + IntegrationHelper + .testClassExistence(this, logisticspipes.routing.ExitRoute.class); + IntegrationHelper + .testClassExistence(this, logisticspipes.utils.AdjacentTile.class); + IntegrationHelper + .testClassExistence(this, logisticspipes.utils.item.ItemIdentifier.class); } @Override - public void init() throws Throwable - { + public void init() throws Throwable {} + + @Override + public void postInit() { + AEApi.instance().registries().externalStorage().addExternalStorageInterface( + new LPPipeHandler() + ); } @Override - public void postInit() - { - AEApi.instance().registries().externalStorage().addExternalStorageInterface( new LPPipeHandler() ); - } - - @Override - public boolean canAddItemsToPipe( final TileEntity te, final ItemStack is, final ForgeDirection direction ) - { - if( is != null && te != null && te instanceof IInjectable ) - { + public boolean canAddItemsToPipe( + final TileEntity te, final ItemStack is, final ForgeDirection direction + ) { + if (is != null && te != null && te instanceof IInjectable) { final IInjectable pt = (IInjectable) te; - if( pt.canInjectItems( direction ) ) - { - final int amt = pt.injectItem( is, false, direction, null ); - if( amt == is.stackSize ) - { + if (pt.canInjectItems(direction)) { + final int amt = pt.injectItem(is, false, direction, null); + if (amt == is.stackSize) { return true; } } @@ -90,17 +86,15 @@ public class LogisticsPipes implements ILogisticsPipes, IIntegrationModule } @Override - public boolean addItemsToPipe( final TileEntity te, final ItemStack is, @Nonnull final ForgeDirection direction ) - { - if( is != null && te != null && te instanceof IInjectable ) - { + public boolean addItemsToPipe( + final TileEntity te, final ItemStack is, @Nonnull final ForgeDirection direction + ) { + if (is != null && te != null && te instanceof IInjectable) { final IInjectable pt = (IInjectable) te; - if( pt.canInjectItems( direction ) ) - { - final int amt = pt.injectItem( is, false, direction, null ); - if( amt == is.stackSize ) - { - pt.injectItem( is, true, direction, null ); + if (pt.canInjectItems(direction)) { + final int amt = pt.injectItem(is, false, direction, null); + if (amt == is.stackSize) { + pt.injectItem(is, true, direction, null); return true; } } diff --git a/src/main/java/appeng/integration/modules/MFR.java b/src/main/java/appeng/integration/modules/MFR.java index 26ab2bbc..2fc4b73a 100644 --- a/src/main/java/appeng/integration/modules/MFR.java +++ b/src/main/java/appeng/integration/modules/MFR.java @@ -18,30 +18,26 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; +public class MFR implements IIntegrationModule { + @Reflected + public static MFR instance; -public class MFR implements IIntegrationModule -{ - @Reflected - public static MFR instance; + @Reflected + public MFR() { + IntegrationHelper.testClassExistence( + this, + powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection + .class + ); + } - @Reflected - public MFR() - { - IntegrationHelper.testClassExistence( this, powercrystals.minefactoryreloaded.api.rednet.connectivity.IRedNetConnection.class ); - } + @Override + public void init() throws Throwable {} - @Override - public void init() throws Throwable - { - } - - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/Mekanism.java b/src/main/java/appeng/integration/modules/Mekanism.java index 5c1ce5b6..f9c43c87 100644 --- a/src/main/java/appeng/integration/modules/Mekanism.java +++ b/src/main/java/appeng/integration/modules/Mekanism.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; @@ -27,56 +26,48 @@ import cpw.mods.fml.common.event.FMLInterModComms; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public final class Mekanism implements IMekanism, IIntegrationModule { + @Reflected + public static Mekanism instance; -public final class Mekanism implements IMekanism, IIntegrationModule -{ - @Reflected - public static Mekanism instance; + @Reflected + public Mekanism() { + IntegrationHelper + .testClassExistence(this, mekanism.api.energy.IStrictEnergyAcceptor.class); + } - @Reflected - public Mekanism() - { - IntegrationHelper.testClassExistence( this, mekanism.api.energy.IStrictEnergyAcceptor.class ); - } + @Override + public void init() throws Throwable {} - @Override - public void init() throws Throwable - { - } + @Override + public void postInit() {} - @Override - public void postInit() - { - } + @Override + public void addCrusherRecipe(final ItemStack in, final ItemStack out) { + final NBTTagCompound sendTag = this.convertToSimpleRecipe(in, out); - @Override - public void addCrusherRecipe( final ItemStack in, final ItemStack out ) - { - final NBTTagCompound sendTag = this.convertToSimpleRecipe( in, out ); + FMLInterModComms.sendMessage("mekanism", "CrusherRecipe", sendTag); + } - FMLInterModComms.sendMessage( "mekanism", "CrusherRecipe", sendTag ); - } + @Override + public void addEnrichmentChamberRecipe(final ItemStack in, final ItemStack out) { + final NBTTagCompound sendTag = this.convertToSimpleRecipe(in, out); - @Override - public void addEnrichmentChamberRecipe( final ItemStack in, final ItemStack out ) - { - final NBTTagCompound sendTag = this.convertToSimpleRecipe( in, out ); + FMLInterModComms.sendMessage("mekanism", "EnrichmentChamberRecipe", sendTag); + } - FMLInterModComms.sendMessage( "mekanism", "EnrichmentChamberRecipe", sendTag ); - } + private NBTTagCompound + convertToSimpleRecipe(final ItemStack in, final ItemStack out) { + final NBTTagCompound sendTag = new NBTTagCompound(); + final NBTTagCompound inputTagDummy = new NBTTagCompound(); + final NBTTagCompound outputTagDummy = new NBTTagCompound(); - private NBTTagCompound convertToSimpleRecipe( final ItemStack in, final ItemStack out ) - { - final NBTTagCompound sendTag = new NBTTagCompound(); - final NBTTagCompound inputTagDummy = new NBTTagCompound(); - final NBTTagCompound outputTagDummy = new NBTTagCompound(); + final NBTTagCompound inputTag = in.writeToNBT(inputTagDummy); + final NBTTagCompound outputTag = out.writeToNBT(outputTagDummy); - final NBTTagCompound inputTag = in.writeToNBT( inputTagDummy ); - final NBTTagCompound outputTag = out.writeToNBT( outputTagDummy ); + sendTag.setTag("input", inputTag); + sendTag.setTag("output", outputTag); - sendTag.setTag( "input", inputTag ); - sendTag.setTag( "output", outputTag ); - - return sendTag; - } + return sendTag; + } } diff --git a/src/main/java/appeng/integration/modules/NEI.java b/src/main/java/appeng/integration/modules/NEI.java index 227b86e3..5aba0486 100644 --- a/src/main/java/appeng/integration/modules/NEI.java +++ b/src/main/java/appeng/integration/modules/NEI.java @@ -18,6 +18,10 @@ package appeng.integration.modules; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.List; import appeng.client.gui.AEBaseMEGui; import appeng.client.gui.implementations.GuiCraftingTerm; @@ -39,141 +43,176 @@ import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.List; +public class NEI implements INEI, IContainerTooltipHandler, IIntegrationModule { + @Reflected + public static NEI instance; + private final Class apiClass; -public class NEI implements INEI, IContainerTooltipHandler, IIntegrationModule -{ - @Reflected - public static NEI instance; + // recipe handler... + private Method registerRecipeHandler; + private Method registerUsageHandler; - private final Class apiClass; + @Reflected + public NEI() throws ClassNotFoundException { + IntegrationHelper.testClassExistence(this, codechicken.nei.api.API.class); + IntegrationHelper + .testClassExistence(this, codechicken.nei.api.IStackPositioner.class); + IntegrationHelper + .testClassExistence(this, codechicken.nei.guihook.GuiContainerManager.class); + IntegrationHelper.testClassExistence( + this, codechicken.nei.guihook.IContainerTooltipHandler.class + ); + IntegrationHelper + .testClassExistence(this, codechicken.nei.recipe.ICraftingHandler.class); + IntegrationHelper + .testClassExistence(this, codechicken.nei.recipe.IUsageHandler.class); - // recipe handler... - private Method registerRecipeHandler; - private Method registerUsageHandler; + this.apiClass = Class.forName("codechicken.nei.api.API"); + } - @Reflected - public NEI() throws ClassNotFoundException - { - IntegrationHelper.testClassExistence( this, codechicken.nei.api.API.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.api.IStackPositioner.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.guihook.GuiContainerManager.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.guihook.IContainerTooltipHandler.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.recipe.ICraftingHandler.class ); - IntegrationHelper.testClassExistence( this, codechicken.nei.recipe.IUsageHandler.class ); + @Override + public void init() throws Throwable { + this.registerRecipeHandler = this.apiClass.getDeclaredMethod( + "registerRecipeHandler", codechicken.nei.recipe.ICraftingHandler.class + ); + this.registerUsageHandler = this.apiClass.getDeclaredMethod( + "registerUsageHandler", codechicken.nei.recipe.IUsageHandler.class + ); - this.apiClass = Class.forName( "codechicken.nei.api.API" ); - } + this.registerRecipeHandler(new NEIAEShapedRecipeHandler()); + this.registerRecipeHandler(new NEIAEShapelessRecipeHandler()); + this.registerRecipeHandler(new NEIInscriberRecipeHandler()); + this.registerRecipeHandler(new NEIWorldCraftingHandler()); + this.registerRecipeHandler(new NEIGrinderRecipeHandler()); - @Override - public void init() throws Throwable - { - this.registerRecipeHandler = this.apiClass.getDeclaredMethod( "registerRecipeHandler", codechicken.nei.recipe.ICraftingHandler.class ); - this.registerUsageHandler = this.apiClass.getDeclaredMethod( "registerUsageHandler", codechicken.nei.recipe.IUsageHandler.class ); + if (AEConfig.instance.isFeatureEnabled(AEFeature.Facades) + && AEConfig.instance.isFeatureEnabled(AEFeature.EnableFacadeCrafting)) { + this.registerRecipeHandler(new NEIFacadeRecipeHandler()); + } - this.registerRecipeHandler( new NEIAEShapedRecipeHandler() ); - this.registerRecipeHandler( new NEIAEShapelessRecipeHandler() ); - this.registerRecipeHandler( new NEIInscriberRecipeHandler() ); - this.registerRecipeHandler( new NEIWorldCraftingHandler() ); - this.registerRecipeHandler( new NEIGrinderRecipeHandler() ); + // large stack tooltips + GuiContainerManager.addTooltipHandler(this); - if( AEConfig.instance.isFeatureEnabled( AEFeature.Facades ) && AEConfig.instance.isFeatureEnabled( AEFeature.EnableFacadeCrafting ) ) - { - this.registerRecipeHandler( new NEIFacadeRecipeHandler() ); - } + // crafting terminal... + final Method registerGuiOverlay = this.apiClass.getDeclaredMethod( + "registerGuiOverlay", Class.class, String.class, IStackPositioner.class + ); + final Class overlayHandler = Class.forName("codechicken.nei.api.IOverlayHandler"); - // large stack tooltips - GuiContainerManager.addTooltipHandler( this ); + final Method registrar = this.apiClass.getDeclaredMethod( + "registerGuiOverlayHandler", Class.class, overlayHandler, String.class + ); + registerGuiOverlay.invoke( + this.apiClass, + GuiCraftingTerm.class, + "crafting", + new TerminalCraftingSlotFinder() + ); + registerGuiOverlay.invoke( + this.apiClass, + GuiPatternTerm.class, + "crafting", + new TerminalCraftingSlotFinder() + ); - // crafting terminal... - final Method registerGuiOverlay = this.apiClass.getDeclaredMethod( "registerGuiOverlay", Class.class, String.class, IStackPositioner.class ); - final Class overlayHandler = Class.forName( "codechicken.nei.api.IOverlayHandler" ); + final Class defaultHandler = NEICraftingHandler.class; + final Constructor defaultConstructor + = defaultHandler.getConstructor(int.class, int.class); + registrar.invoke( + this.apiClass, + GuiCraftingTerm.class, + defaultConstructor.newInstance(6, 75), + "crafting" + ); + registrar.invoke( + this.apiClass, + GuiPatternTerm.class, + defaultConstructor.newInstance(6, 75), + "crafting" + ); + } - final Method registrar = this.apiClass.getDeclaredMethod( "registerGuiOverlayHandler", Class.class, overlayHandler, String.class ); - registerGuiOverlay.invoke( this.apiClass, GuiCraftingTerm.class, "crafting", new TerminalCraftingSlotFinder() ); - registerGuiOverlay.invoke( this.apiClass, GuiPatternTerm.class, "crafting", new TerminalCraftingSlotFinder() ); + public void registerRecipeHandler(final Object o + ) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { + this.registerRecipeHandler.invoke(this.apiClass, o); + this.registerUsageHandler.invoke(this.apiClass, o); + } - final Class defaultHandler = NEICraftingHandler.class; - final Constructor defaultConstructor = defaultHandler.getConstructor( int.class, int.class ); - registrar.invoke( this.apiClass, GuiCraftingTerm.class, defaultConstructor.newInstance( 6, 75 ), "crafting" ); - registrar.invoke( this.apiClass, GuiPatternTerm.class, defaultConstructor.newInstance( 6, 75 ), "crafting" ); - } + @Override + public void postInit() {} - public void registerRecipeHandler( final Object o ) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException - { - this.registerRecipeHandler.invoke( this.apiClass, o ); - this.registerUsageHandler.invoke( this.apiClass, o ); - } + @Override + public void drawSlot(final Slot s) { + if (s == null) { + return; + } - @Override - public void postInit() - { + final ItemStack stack = s.getStack(); - } + if (stack == null) { + return; + } - @Override - public void drawSlot( final Slot s ) - { - if( s == null ) - { - return; - } + final Minecraft mc = Minecraft.getMinecraft(); + final FontRenderer fontRenderer = mc.fontRenderer; + final int x = s.xDisplayPosition; + final int y = s.yDisplayPosition; - final ItemStack stack = s.getStack(); + GuiContainerManager.drawItems.renderItemAndEffectIntoGUI( + fontRenderer, mc.getTextureManager(), stack, x, y + ); + GuiContainerManager.drawItems.renderItemOverlayIntoGUI( + fontRenderer, + mc.getTextureManager(), + stack, + x, + y, + String.valueOf(stack.stackSize) + ); + } - if( stack == null ) - { - return; - } + @Override + public RenderItem setItemRender(final RenderItem renderItem) { + try { + final RenderItem ri = GuiContainerManager.drawItems; + GuiContainerManager.drawItems = renderItem; + return ri; + } catch (final Throwable t) { + throw new IllegalStateException("Invalid version of NEI, please update", t); + } + } - final Minecraft mc = Minecraft.getMinecraft(); - final FontRenderer fontRenderer = mc.fontRenderer; - final int x = s.xDisplayPosition; - final int y = s.yDisplayPosition; + @Override + public List handleTooltip( + final GuiContainer arg0, + final int arg1, + final int arg2, + final List current + ) { + return current; + } - GuiContainerManager.drawItems.renderItemAndEffectIntoGUI( fontRenderer, mc.getTextureManager(), stack, x, y ); - GuiContainerManager.drawItems.renderItemOverlayIntoGUI( fontRenderer, mc.getTextureManager(), stack, x, y, String.valueOf( stack.stackSize ) ); - } + @Override + public List handleItemDisplayName( + final GuiContainer arg0, final ItemStack arg1, final List current + ) { + return current; + } - @Override - public RenderItem setItemRender( final RenderItem renderItem ) - { - try - { - final RenderItem ri = GuiContainerManager.drawItems; - GuiContainerManager.drawItems = renderItem; - return ri; - } - catch( final Throwable t ) - { - throw new IllegalStateException( "Invalid version of NEI, please update", t ); - } - } + @Override + public List handleItemTooltip( + final GuiContainer guiScreen, + final ItemStack stack, + final int mouseX, + final int mouseY, + final List currentToolTip + ) { + if (guiScreen instanceof AEBaseMEGui) { + return ((AEBaseMEGui) guiScreen) + .handleItemTooltip(stack, mouseX, mouseY, currentToolTip); + } - @Override - public List handleTooltip( final GuiContainer arg0, final int arg1, final int arg2, final List current ) - { - return current; - } - - @Override - public List handleItemDisplayName( final GuiContainer arg0, final ItemStack arg1, final List current ) - { - return current; - } - - @Override - public List handleItemTooltip( final GuiContainer guiScreen, final ItemStack stack, final int mouseX, final int mouseY, final List currentToolTip ) - { - if( guiScreen instanceof AEBaseMEGui ) - { - return ( (AEBaseMEGui) guiScreen ).handleItemTooltip( stack, mouseX, mouseY, currentToolTip ); - } - - return currentToolTip; - } + return currentToolTip; + } } diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java index 7de64672..75f7bbf3 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapedRecipeHandler.java @@ -18,6 +18,9 @@ package appeng.integration.modules.NEIHelpers; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; @@ -41,221 +44,195 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; +public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler { + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(84, 23, 24, 18), "crafting" + )); + } + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("crafting")) + && (this.getClass() == NEIAEShapedRecipeHandler.class)) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapedRecipe)) { + if (((ShapedRecipe) recipe).isEnabled()) { + final CachedShapedRecipe cachedRecipe + = new CachedShapedRecipe((ShapedRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } -public class NEIAEShapedRecipeHandler extends TemplateRecipeHandler -{ + @Override + public void loadCraftingRecipes(final ItemStack result) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapedRecipe)) { + if (((ShapedRecipe) recipe).isEnabled() + && NEIServerUtils.areStacksSameTypeCrafting( + recipe.getRecipeOutput(), result + )) { + final CachedShapedRecipe cachedRecipe + = new CachedShapedRecipe((ShapedRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); - } + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapedRecipe)) { + final CachedShapedRecipe cachedRecipe + = new CachedShapedRecipe((ShapedRecipe) recipe); - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapedRecipeHandler.class ) ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapedRecipe ) ) - { - if( ( (ShapedRecipe) recipe ).isEnabled() ) - { - final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } + if (((ShapedRecipe) recipe).isEnabled() + && cachedRecipe.contains( + cachedRecipe.ingredients, ingredient.getItem() + )) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation( + cachedRecipe.ingredients, ingredient + ); + this.arecipes.add(cachedRecipe); + } + } + } + } + } - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapedRecipe ) ) - { - if( ( (ShapedRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) - { - final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } + @Override + public String getGuiTexture() { + return "textures/gui/container/crafting_table.png"; + } - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapedRecipe ) ) - { - final CachedShapedRecipe cachedRecipe = new CachedShapedRecipe( (ShapedRecipe) recipe ); + @Override + public String getOverlayIdentifier() { + return "crafting"; + } - if( ( (ShapedRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } - } + @Override + public Class getGuiClass() { + return GuiCrafting.class; + } - @Override - public String getGuiTexture() - { - return "textures/gui/container/crafting_table.png"; - } + @Override + public boolean + hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return (super.hasOverlay(gui, container, recipe)) + || ((this.isRecipe2x2(recipe)) + && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))); + } - @Override - public String getOverlayIdentifier() - { - return "crafting"; - } + @Override + public IRecipeOverlayRenderer + getOverlayRenderer(final GuiContainer gui, final int recipe) { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer(gui, recipe); + if (renderer != null) { + return renderer; + } - @Override - public Class getGuiClass() - { - return GuiCrafting.class; - } + final IStackPositioner positioner + = RecipeInfo.getStackPositioner(gui, "crafting2x2"); + if (positioner == null) { + return null; + } - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); - } + return new DefaultOverlayRenderer(this.getIngredientStacks(recipe), positioner); + } - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if( renderer != null ) - { - return renderer; - } + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + final IOverlayHandler handler = super.getOverlayHandler(gui, recipe); + if (handler != null) { + return handler; + } - final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if( positioner == null ) - { - return null; - } + return RecipeInfo.getOverlayHandler(gui, "crafting2x2"); + } - return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); - } + private boolean isRecipe2x2(final int recipe) { + for (final PositionedStack stack : this.getIngredientStacks(recipe)) { + if ((stack.relx > 43) || (stack.rely > 24)) { + return false; + } + } + return true; + } - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if( handler != null ) - { - return handler; - } + @Override + public String getRecipeName() { + return NEIClientUtils.translate("recipe.shaped"); + } - return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); - } + private class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe { + private final List ingredients; + private final PositionedStack result; - private boolean isRecipe2x2( final int recipe ) - { - for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) - { - if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) - { - return false; - } - } - return true; - } + public CachedShapedRecipe(final ShapedRecipe recipe) { + this.result = new PositionedStack(recipe.getRecipeOutput(), 119, 24); + this.ingredients = new ArrayList(); + this.setIngredients( + recipe.getWidth(), recipe.getHeight(), recipe.getIngredients() + ); + } - @Override - public String getRecipeName() - { - return NEIClientUtils.translate( "recipe.shaped" ); - } + private void + setIngredients(final int width, final int height, final Object[] items) { + final boolean useSingleItems + = AEConfig.instance.disableColoredCableRecipesInNEI(); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + if (items[(y * width + x)] != null) { + final IIngredient ing = (IIngredient) items[(y * width + x)]; - private class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe - { + try { + final ItemStack[] is = ing.getItemStackSet(); + final PositionedStack stack = new PositionedStack( + useSingleItems ? Platform.findPreferred(is) : is, + 25 + x * 18, + 6 + y * 18, + false + ); + stack.setMaxSize(1); + this.ingredients.add(stack); + } catch (final RegistrationError ignored) { + } catch (final MissingIngredientError ignored) {} + } + } + } + } - private final List ingredients; - private final PositionedStack result; + @Override + public PositionedStack getResult() { + return this.result; + } - public CachedShapedRecipe( final ShapedRecipe recipe ) - { - this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); - this.ingredients = new ArrayList(); - this.setIngredients( recipe.getWidth(), recipe.getHeight(), recipe.getIngredients() ); - } + @Override + public List getIngredients() { + return this.getCycledIngredients( + NEIAEShapedRecipeHandler.this.cycleticks / 20, this.ingredients + ); + } - private void setIngredients( final int width, final int height, final Object[] items ) - { - final boolean useSingleItems = AEConfig.instance.disableColoredCableRecipesInNEI(); - for( int x = 0; x < width; x++ ) - { - for( int y = 0; y < height; y++ ) - { - if( items[( y * width + x )] != null ) - { - final IIngredient ing = (IIngredient) items[( y * width + x )]; - - try - { - final ItemStack[] is = ing.getItemStackSet(); - final PositionedStack stack = new PositionedStack( useSingleItems ? Platform.findPreferred( is ) : is, 25 + x * 18, 6 + y * 18, false ); - stack.setMaxSize( 1 ); - this.ingredients.add( stack ); - } - catch( final RegistrationError ignored ) - { - - } - catch( final MissingIngredientError ignored ) - { - - } - } - } - } - } - - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIAEShapedRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java index 148f5753..e083bf18 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIAEShapelessRecipeHandler.java @@ -18,6 +18,9 @@ package appeng.integration.modules.NEIHelpers; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; @@ -41,222 +44,194 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; +public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler { + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(84, 23, 24, 18), "crafting" + )); + } + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("crafting")) + && (this.getClass() == NEIAEShapelessRecipeHandler.class)) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapelessRecipe)) { + if (((ShapelessRecipe) recipe).isEnabled()) { + final CachedShapelessRecipe cachedRecipe + = new CachedShapelessRecipe((ShapelessRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } -public class NEIAEShapelessRecipeHandler extends TemplateRecipeHandler -{ + @Override + public void loadCraftingRecipes(final ItemStack result) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapelessRecipe)) { + if (((ShapelessRecipe) recipe).isEnabled() + && NEIServerUtils.areStacksSameTypeCrafting( + recipe.getRecipeOutput(), result + )) { + final CachedShapelessRecipe cachedRecipe + = new CachedShapelessRecipe((ShapelessRecipe) recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } + } - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); - } + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + final List recipes = CraftingManager.getInstance().getRecipeList(); + for (final IRecipe recipe : recipes) { + if ((recipe instanceof ShapelessRecipe)) { + final CachedShapelessRecipe cachedRecipe + = new CachedShapelessRecipe((ShapelessRecipe) recipe); - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIAEShapelessRecipeHandler.class ) ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapelessRecipe ) ) - { - if( ( (ShapelessRecipe) recipe ).isEnabled() ) - { - final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } + if (((ShapelessRecipe) recipe).isEnabled() + && cachedRecipe.contains( + cachedRecipe.ingredients, ingredient.getItem() + )) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation( + cachedRecipe.ingredients, ingredient + ); + this.arecipes.add(cachedRecipe); + } + } + } + } + } - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapelessRecipe ) ) - { - if( ( (ShapelessRecipe) recipe ).isEnabled() && NEIServerUtils.areStacksSameTypeCrafting( recipe.getRecipeOutput(), result ) ) - { - final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } - } + @Override + public String getGuiTexture() { + return "textures/gui/container/crafting_table.png"; + } - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - final List recipes = CraftingManager.getInstance().getRecipeList(); - for( final IRecipe recipe : recipes ) - { - if( ( recipe instanceof ShapelessRecipe ) ) - { - final CachedShapelessRecipe cachedRecipe = new CachedShapelessRecipe( (ShapelessRecipe) recipe ); + @Override + public String getOverlayIdentifier() { + return "crafting"; + } - if( ( (ShapelessRecipe) recipe ).isEnabled() && cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } - } + @Override + public Class getGuiClass() { + return GuiCrafting.class; + } - @Override - public String getGuiTexture() - { - return "textures/gui/container/crafting_table.png"; - } + @Override + public boolean + hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return (super.hasOverlay(gui, container, recipe)) + || ((this.isRecipe2x2(recipe)) + && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))); + } - @Override - public String getOverlayIdentifier() - { - return "crafting"; - } + @Override + public IRecipeOverlayRenderer + getOverlayRenderer(final GuiContainer gui, final int recipe) { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer(gui, recipe); + if (renderer != null) { + return renderer; + } - @Override - public Class getGuiClass() - { - return GuiCrafting.class; - } + final IStackPositioner positioner + = RecipeInfo.getStackPositioner(gui, "crafting2x2"); + if (positioner == null) { + return null; + } - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); - } + return new DefaultOverlayRenderer(this.getIngredientStacks(recipe), positioner); + } - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if( renderer != null ) - { - return renderer; - } + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + final IOverlayHandler handler = super.getOverlayHandler(gui, recipe); + if (handler != null) { + return handler; + } - final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if( positioner == null ) - { - return null; - } + return RecipeInfo.getOverlayHandler(gui, "crafting2x2"); + } - return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); - } + private boolean isRecipe2x2(final int recipe) { + for (final PositionedStack stack : this.getIngredientStacks(recipe)) { + if ((stack.relx > 43) || (stack.rely > 24)) { + return false; + } + } + return true; + } - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if( handler != null ) - { - return handler; - } + @Override + public String getRecipeName() { + return NEIClientUtils.translate("recipe.shapeless"); + } - return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); - } + private class CachedShapelessRecipe extends TemplateRecipeHandler.CachedRecipe { + private final List ingredients; + private final PositionedStack result; - private boolean isRecipe2x2( final int recipe ) - { - for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) - { - if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) - { - return false; - } - } - return true; - } + public CachedShapelessRecipe(final ShapelessRecipe recipe) { + this.result = new PositionedStack(recipe.getRecipeOutput(), 119, 24); + this.ingredients = new ArrayList(); + this.setIngredients(recipe.getInput().toArray()); + } - @Override - public String getRecipeName() - { - return NEIClientUtils.translate( "recipe.shapeless" ); - } + @Override + public PositionedStack getResult() { + return this.result; + } - private class CachedShapelessRecipe extends TemplateRecipeHandler.CachedRecipe - { + @Override + public List getIngredients() { + return this.getCycledIngredients( + NEIAEShapelessRecipeHandler.this.cycleticks / 20, this.ingredients + ); + } - private final List ingredients; - private final PositionedStack result; + private void setIngredients(final Object[] items) { + final 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)) { + final IIngredient ing = (IIngredient) items[(y * 3 + x)]; - public CachedShapelessRecipe( final ShapelessRecipe recipe ) - { - this.result = new PositionedStack( recipe.getRecipeOutput(), 119, 24 ); - this.ingredients = new ArrayList(); - this.setIngredients( recipe.getInput().toArray() ); - } + try { + final ItemStack[] is = ing.getItemStackSet(); + final 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 (final RegistrationError ignored) { + } catch (final MissingIngredientError ignored) {} + } + } + } + } - @Override - public PositionedStack getResult() - { - return this.result; - } + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIAEShapelessRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - private void setIngredients( final Object[] items ) - { - final 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 ) ) - { - final IIngredient ing = (IIngredient) items[( y * 3 + x )]; - - try - { - final ItemStack[] is = ing.getItemStackSet(); - final 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( final RegistrationError ignored ) - { - - } - catch( final MissingIngredientError ignored ) - { - - } - } - } - } - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - - this.result.generatePermutations(); - } - } + this.result.generatePermutations(); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java index 88e2b695..e33229aa 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEICraftingHandler.java @@ -18,6 +18,8 @@ package appeng.integration.modules.NEIHelpers; +import java.util.LinkedList; +import java.util.List; import appeng.client.gui.implementations.GuiCraftingTerm; import appeng.client.gui.implementations.GuiPatternTerm; @@ -35,92 +37,75 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import java.util.LinkedList; -import java.util.List; +public class NEICraftingHandler implements IOverlayHandler { + public NEICraftingHandler(final int x, final int y) {} + @Override + public void overlayRecipe( + final GuiContainer gui, + final IRecipeHandler recipe, + final int recipeIndex, + final boolean shift + ) { + try { + final List ingredients = recipe.getIngredientStacks(recipeIndex); + this.overlayRecipe(gui, ingredients, shift); + } catch (final Exception ignored) { + } catch (final Error ignored) {} + } -public class NEICraftingHandler implements IOverlayHandler -{ + private void overlayRecipe( + final GuiContainer gui, + final List ingredients, + final boolean shift + ) { + try { + final NBTTagCompound recipe = new NBTTagCompound(); - public NEICraftingHandler( final int x, final int y ) - { - } + if (gui instanceof GuiCraftingTerm || gui instanceof GuiPatternTerm) { + for (final PositionedStack positionedStack : ingredients) { + final int col = (positionedStack.relx - 25) / 18; + final int row = (positionedStack.rely - 6) / 18; + if (positionedStack.items != null + && positionedStack.items.length > 0) { + for (final Slot slot : + (List) gui.inventorySlots.inventorySlots) { + if (slot instanceof SlotCraftingMatrix + || slot instanceof SlotFakeCraftingMatrix) { + if (slot.getSlotIndex() == col + row * 3) { + final NBTTagList tags = new NBTTagList(); + final List list + = new LinkedList(); - @Override - public void overlayRecipe( final GuiContainer gui, final IRecipeHandler recipe, final int recipeIndex, final boolean shift ) - { - try - { - final List ingredients = recipe.getIngredientStacks( recipeIndex ); - this.overlayRecipe( gui, ingredients, shift ); - } - catch( final Exception ignored ) - { - } - catch( final Error ignored ) - { - } - } + // prefer pure crystals. + for (int x = 0; x < positionedStack.items.length; + x++) { + if (Platform.isRecipePrioritized( + positionedStack.items[x] + )) { + list.add(0, positionedStack.items[x]); + } else { + list.add(positionedStack.items[x]); + } + } - private void overlayRecipe( final GuiContainer gui, final List ingredients, final boolean shift ) - { - try - { - final NBTTagCompound recipe = new NBTTagCompound(); + for (final ItemStack is : list) { + final NBTTagCompound tag = new NBTTagCompound(); + is.writeToNBT(tag); + tags.appendTag(tag); + } - if( gui instanceof GuiCraftingTerm || gui instanceof GuiPatternTerm ) - { - for( final PositionedStack positionedStack : ingredients ) - { - final int col = ( positionedStack.relx - 25 ) / 18; - final int row = ( positionedStack.rely - 6 ) / 18; - if( positionedStack.items != null && positionedStack.items.length > 0 ) - { - for( final Slot slot : (List) gui.inventorySlots.inventorySlots ) - { - if( slot instanceof SlotCraftingMatrix || slot instanceof SlotFakeCraftingMatrix ) - { - if( slot.getSlotIndex() == col + row * 3 ) - { - final NBTTagList tags = new NBTTagList(); - final List list = new LinkedList(); + recipe.setTag("#" + slot.getSlotIndex(), tags); + break; + } + } + } + } + } - // prefer pure crystals. - for( int x = 0; x < positionedStack.items.length; x++ ) - { - if( Platform.isRecipePrioritized( positionedStack.items[x] ) ) - { - list.add( 0, positionedStack.items[x] ); - } - else - { - list.add( positionedStack.items[x] ); - } - } - - for( final ItemStack is : list ) - { - final NBTTagCompound tag = new NBTTagCompound(); - is.writeToNBT( tag ); - tags.appendTag( tag ); - } - - recipe.setTag( "#" + slot.getSlotIndex(), tags ); - break; - } - } - } - } - } - - NetworkHandler.instance.sendToServer( new PacketNEIRecipe( recipe ) ); - } - } - catch( final Exception ignored ) - { - } - catch( final Error ignored ) - { - } - } + NetworkHandler.instance.sendToServer(new PacketNEIRecipe(recipe)); + } + } catch (final Exception ignored) { + } catch (final 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 b7cf9241..de3f7884 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIFacadeRecipeHandler.java @@ -18,6 +18,9 @@ package appeng.integration.modules.NEIHelpers; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; @@ -37,211 +40,190 @@ import net.minecraft.client.gui.inventory.GuiCrafting; import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; +public class NEIFacadeRecipeHandler extends TemplateRecipeHandler { + private final ItemFacade facade; + private final IItemDefinition anchorDefinition; + public NEIFacadeRecipeHandler() { + final IDefinitions definitions = AEApi.instance().definitions(); -public class NEIFacadeRecipeHandler extends TemplateRecipeHandler -{ - private final ItemFacade facade; - private final IItemDefinition anchorDefinition; + this.facade = (ItemFacade) definitions.items().facade().maybeItem().get(); + this.anchorDefinition = definitions.parts().cableAnchor(); + } - public NEIFacadeRecipeHandler() - { - final IDefinitions definitions = AEApi.instance().definitions(); + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(84, 23, 24, 18), "crafting" + )); + } - this.facade = (ItemFacade) definitions.items().facade().maybeItem().get(); - this.anchorDefinition = definitions.parts().cableAnchor(); - } + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("crafting")) + && (this.getClass() == NEIFacadeRecipeHandler.class)) { + final List facades = this.facade.getFacades(); + for (final ItemStack anchorStack : + this.anchorDefinition.maybeStack(1).asSet()) { + for (final ItemStack is : facades) { + final CachedShapedRecipe recipe + = new CachedShapedRecipe(this.facade, anchorStack, is); + recipe.computeVisuals(); + this.arecipes.add(recipe); + } + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "crafting" ) ); - } + @Override + public void loadCraftingRecipes(final ItemStack result) { + if (result.getItem() == this.facade) { + for (final ItemStack anchorStack : + this.anchorDefinition.maybeStack(1).asSet()) { + final CachedShapedRecipe recipe + = new CachedShapedRecipe(this.facade, anchorStack, result); + recipe.computeVisuals(); + this.arecipes.add(recipe); + } + } + } - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "crafting" ) ) && ( this.getClass() == NEIFacadeRecipeHandler.class ) ) - { - final List facades = this.facade.getFacades(); - for( final ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) - { - for( final ItemStack is : facades ) - { - final CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, is ); - recipe.computeVisuals(); - this.arecipes.add( recipe ); - } - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + final List facades = this.facade.getFacades(); + for (final ItemStack anchorStack : this.anchorDefinition.maybeStack(1).asSet()) { + for (final ItemStack is : facades) { + final CachedShapedRecipe recipe + = new CachedShapedRecipe(this.facade, anchorStack, is); - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - if( result.getItem() == this.facade ) - { - for( final ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) - { - final CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, result ); - recipe.computeVisuals(); - this.arecipes.add( recipe ); - } - } - } + if (recipe.contains(recipe.ingredients, ingredient.getItem())) { + recipe.computeVisuals(); + if (recipe.contains(recipe.ingredients, ingredient)) { + recipe.setIngredientPermutation(recipe.ingredients, ingredient); + this.arecipes.add(recipe); + } + } + } + } + } - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - final List facades = this.facade.getFacades(); - for( final ItemStack anchorStack : this.anchorDefinition.maybeStack( 1 ).asSet() ) - { - for( final ItemStack is : facades ) - { - final CachedShapedRecipe recipe = new CachedShapedRecipe( this.facade, anchorStack, is ); + @Override + public String getGuiTexture() { + return "textures/gui/container/crafting_table.png"; + } - if( recipe.contains( recipe.ingredients, ingredient.getItem() ) ) - { - recipe.computeVisuals(); - if( recipe.contains( recipe.ingredients, ingredient ) ) - { - recipe.setIngredientPermutation( recipe.ingredients, ingredient ); - this.arecipes.add( recipe ); - } - } - } - } - } + @Override + public String getOverlayIdentifier() { + return "crafting"; + } - @Override - public String getGuiTexture() - { - return "textures/gui/container/crafting_table.png"; - } + @Override + public Class getGuiClass() { + return GuiCrafting.class; + } - @Override - public String getOverlayIdentifier() - { - return "crafting"; - } + @Override + public boolean + hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return (super.hasOverlay(gui, container, recipe)) + || ((this.isRecipe2x2(recipe)) + && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))); + } - @Override - public Class getGuiClass() - { - return GuiCrafting.class; - } + @Override + public IRecipeOverlayRenderer + getOverlayRenderer(final GuiContainer gui, final int recipe) { + final IRecipeOverlayRenderer renderer = super.getOverlayRenderer(gui, recipe); + if (renderer != null) { + return renderer; + } - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return ( super.hasOverlay( gui, container, recipe ) ) || ( ( this.isRecipe2x2( recipe ) ) && ( RecipeInfo.hasDefaultOverlay( gui, "crafting2x2" ) ) ); - } + final IStackPositioner positioner + = RecipeInfo.getStackPositioner(gui, "crafting2x2"); + if (positioner == null) { + return null; + } - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - final IRecipeOverlayRenderer renderer = super.getOverlayRenderer( gui, recipe ); - if( renderer != null ) - { - return renderer; - } + return new DefaultOverlayRenderer(this.getIngredientStacks(recipe), positioner); + } - final IStackPositioner positioner = RecipeInfo.getStackPositioner( gui, "crafting2x2" ); - if( positioner == null ) - { - return null; - } + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + final IOverlayHandler handler = super.getOverlayHandler(gui, recipe); + if (handler != null) { + return handler; + } - return new DefaultOverlayRenderer( this.getIngredientStacks( recipe ), positioner ); - } + return RecipeInfo.getOverlayHandler(gui, "crafting2x2"); + } - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - final IOverlayHandler handler = super.getOverlayHandler( gui, recipe ); - if( handler != null ) - { - return handler; - } + private boolean isRecipe2x2(final int recipe) { + for (final PositionedStack stack : this.getIngredientStacks(recipe)) { + if ((stack.relx > 43) || (stack.rely > 24)) { + return false; + } + } + return true; + } - return RecipeInfo.getOverlayHandler( gui, "crafting2x2" ); - } + @Override + public String getRecipeName() { + return GuiText.FacadeCrafting.getLocal(); + } - private boolean isRecipe2x2( final int recipe ) - { - for( final PositionedStack stack : this.getIngredientStacks( recipe ) ) - { - if( ( stack.relx > 43 ) || ( stack.rely > 24 ) ) - { - return false; - } - } - return true; - } + private final class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe { + public final List ingredients; + public final PositionedStack result; - @Override - public String getRecipeName() - { - return GuiText.FacadeCrafting.getLocal(); - } + public CachedShapedRecipe( + final IFacadeItem facade, final ItemStack anchor, final ItemStack output + ) { + output.stackSize = 4; + this.result = new PositionedStack(output, 119, 24); + this.ingredients = new ArrayList(); + final ItemStack in = facade.getTextureItem(output); + this.setIngredients( + 3, + 3, + new Object[] { + null, anchor, null, anchor, in, anchor, null, anchor, null } + ); + } - private final class CachedShapedRecipe extends TemplateRecipeHandler.CachedRecipe - { - public final List ingredients; - public final PositionedStack result; + public void + setIngredients(final int width, final int height, final Object[] items) { + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + if (items[(y * width + x)] != null) { + final ItemStack is = (ItemStack) items[(y * width + x)]; + final PositionedStack stack + = new PositionedStack(is, 25 + x * 18, 6 + y * 18, false); + stack.setMaxSize(1); + this.ingredients.add(stack); + } + } + } + } - public CachedShapedRecipe( final IFacadeItem facade, final ItemStack anchor, final ItemStack output ) - { - output.stackSize = 4; - this.result = new PositionedStack( output, 119, 24 ); - this.ingredients = new ArrayList(); - final ItemStack in = facade.getTextureItem( output ); - this.setIngredients( 3, 3, new Object[] { null, anchor, null, anchor, in, anchor, null, anchor, null } ); - } + @Override + public PositionedStack getResult() { + return this.result; + } - public void setIngredients( final int width, final int height, final Object[] items ) - { - for( int x = 0; x < width; x++ ) - { - for( int y = 0; y < height; y++ ) - { - if( items[( y * width + x )] != null ) - { - final ItemStack is = (ItemStack) items[( y * width + x )]; - final PositionedStack stack = new PositionedStack( is, 25 + x * 18, 6 + y * 18, false ); - stack.setMaxSize( 1 ); - this.ingredients.add( stack ); - } - } - } - } + @Override + public List getIngredients() { + return this.getCycledIngredients( + NEIFacadeRecipeHandler.this.cycleticks / 20, this.ingredients + ); + } - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIFacadeRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - public void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } + public void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java index 1c7f0533..c9982ae4 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIGrinderRecipeHandler.java @@ -18,6 +18,9 @@ package appeng.integration.modules.NEIHelpers; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.api.features.IGrinderEntry; @@ -37,204 +40,191 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; +public class NEIGrinderRecipeHandler extends TemplateRecipeHandler { + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(84, 23, 24, 18), "grindstone" + )); + } + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("grindstone")) + && (this.getClass() == NEIGrinderRecipeHandler.class)) { + for (final IGrinderEntry recipe : + AEApi.instance().registries().grinder().getRecipes()) { + final CachedGrindStoneRecipe cachedRecipe + = new CachedGrindStoneRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } -public class NEIGrinderRecipeHandler extends TemplateRecipeHandler -{ + @Override + public void loadCraftingRecipes(final ItemStack result) { + for (final IGrinderEntry recipe : + AEApi.instance().registries().grinder().getRecipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getOutput(), result)) { + final CachedGrindStoneRecipe cachedRecipe + = new CachedGrindStoneRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "grindstone" ) ); - } + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + for (final IGrinderEntry recipe : + AEApi.instance().registries().grinder().getRecipes()) { + final CachedGrindStoneRecipe cachedRecipe + = new CachedGrindStoneRecipe(recipe); - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "grindstone" ) ) && ( this.getClass() == NEIGrinderRecipeHandler.class ) ) - { - for( final IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) - { - final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } + if ((cachedRecipe.contains(cachedRecipe.ingredients, ingredient.getItem()))) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation( + cachedRecipe.ingredients, ingredient + ); + this.arecipes.add(cachedRecipe); + } + } + } + } - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - for( final IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) - { - if( NEIServerUtils.areStacksSameTypeCrafting( recipe.getOutput(), result ) ) - { - final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } + @Override + public String getGuiTexture() { + final ResourceLocation loc + = new ResourceLocation("appliedenergistics2", "textures/guis/grinder.png"); - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - for( final IGrinderEntry recipe : AEApi.instance().registries().grinder().getRecipes() ) - { - final CachedGrindStoneRecipe cachedRecipe = new CachedGrindStoneRecipe( recipe ); + return loc.toString(); + } - if( ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } + @Override + public String getOverlayIdentifier() { + return "grindstone"; + } - @Override - public String getGuiTexture() - { - final ResourceLocation loc = new ResourceLocation( "appliedenergistics2", "textures/guis/grinder.png" ); + @Override + public Class getGuiClass() { + return GuiGrinder.class; + } - return loc.toString(); - } + @Override + public void drawBackground(final int recipe) { + GL11.glColor4f(1, 1, 1, 1); + GuiDraw.changeTexture(this.getGuiTexture()); + GuiDraw.drawTexturedModalRect(40, 10, 75, 16 + 10, 90, 66); + } - @Override - public String getOverlayIdentifier() - { - return "grindstone"; - } + @Override + public void drawForeground(final int recipe) { + super.drawForeground(recipe); + if (this.arecipes.size() > recipe) { + final CachedRecipe cr = this.arecipes.get(recipe); + if (cr instanceof CachedGrindStoneRecipe) { + final CachedGrindStoneRecipe cachedRecipe = (CachedGrindStoneRecipe) cr; + if (cachedRecipe.hasOptional) { + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(cachedRecipe.displayChance); + fr.drawString(cachedRecipe.displayChance, (168 - width) / 2, 5, 0); + } else { + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width + = fr.getStringWidth(GuiText.NoSecondOutput.getLocal()); + fr.drawString( + GuiText.NoSecondOutput.getLocal(), (168 - width) / 2, 5, 0 + ); + } + } + } + } - @Override - public Class getGuiClass() - { - return GuiGrinder.class; - } + @Override + public boolean + hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return false; + } - @Override - public void drawBackground( final int recipe ) - { - GL11.glColor4f( 1, 1, 1, 1 ); - GuiDraw.changeTexture( this.getGuiTexture() ); - GuiDraw.drawTexturedModalRect( 40, 10, 75, 16 + 10, 90, 66 ); - } + @Override + public IRecipeOverlayRenderer + getOverlayRenderer(final GuiContainer gui, final int recipe) { + return null; + } - @Override - public void drawForeground( final int recipe ) - { - super.drawForeground( recipe ); - if( this.arecipes.size() > recipe ) - { - final CachedRecipe cr = this.arecipes.get( recipe ); - if( cr instanceof CachedGrindStoneRecipe ) - { - final CachedGrindStoneRecipe cachedRecipe = (CachedGrindStoneRecipe) cr; - if( cachedRecipe.hasOptional ) - { - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( cachedRecipe.displayChance ); - fr.drawString( cachedRecipe.displayChance, ( 168 - width ) / 2, 5, 0 ); - } - else - { - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( GuiText.NoSecondOutput.getLocal() ); - fr.drawString( GuiText.NoSecondOutput.getLocal(), ( 168 - width ) / 2, 5, 0 ); - } - } - } - } + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + return null; + } - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return false; - } + @Override + public String getRecipeName() { + return GuiText.GrindStone.getLocal(); + } - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - return null; - } + private class CachedGrindStoneRecipe extends TemplateRecipeHandler.CachedRecipe { + private final List ingredients; + private final PositionedStack result; + private String displayChance; + private boolean hasOptional = false; - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - return null; - } + public CachedGrindStoneRecipe(final IGrinderEntry recipe) { + this.result = new PositionedStack(recipe.getOutput(), -30 + 107, 47); + this.ingredients = new ArrayList(); - @Override - public String getRecipeName() - { - return GuiText.GrindStone.getLocal(); - } + final ItemStack optionalOutput = recipe.getOptionalOutput(); + final int optionalChancePercent = (int) (recipe.getOptionalChance() * 100); + if (optionalOutput != null) { + this.hasOptional = true; + this.displayChance = String.format( + GuiText.OfSecondOutput.getLocal(), optionalChancePercent + ); + this.ingredients.add( + new PositionedStack(optionalOutput, -30 + 107 + 18, 47) + ); + } - private class CachedGrindStoneRecipe extends TemplateRecipeHandler.CachedRecipe - { - private final List ingredients; - private final PositionedStack result; - private String displayChance; - private boolean hasOptional = false; + final ItemStack secondOptionalOutput = recipe.getSecondOptionalOutput(); + final int secondOptionalChancePercent + = (int) (recipe.getSecondOptionalChance() * 100); + if (secondOptionalOutput != null) { + this.hasOptional = true; + this.displayChance = String.format( + GuiText.MultipleOutputs.getLocal(), + optionalChancePercent, + secondOptionalChancePercent + ); + this.ingredients.add( + new PositionedStack(secondOptionalOutput, -30 + 107 + 18 + 18, 47) + ); + } - public CachedGrindStoneRecipe( final IGrinderEntry recipe ) - { - this.result = new PositionedStack( recipe.getOutput(), -30 + 107, 47 ); - this.ingredients = new ArrayList(); + if (recipe.getInput() != null) { + this.ingredients.add(new PositionedStack(recipe.getInput(), 45, 24)); + } + } - final ItemStack optionalOutput = recipe.getOptionalOutput(); - final int optionalChancePercent = (int) ( recipe.getOptionalChance() * 100 ); - if( optionalOutput != null ) - { - this.hasOptional = true; - this.displayChance = String.format( GuiText.OfSecondOutput.getLocal(), optionalChancePercent ); - this.ingredients.add( new PositionedStack( optionalOutput, -30 + 107 + 18, 47 ) ); - } + @Override + public PositionedStack getResult() { + return this.result; + } - final ItemStack secondOptionalOutput = recipe.getSecondOptionalOutput(); - final int secondOptionalChancePercent = (int) ( recipe.getSecondOptionalChance() * 100 ); - if( secondOptionalOutput != null ) - { - this.hasOptional = true; - this.displayChance = String.format( GuiText.MultipleOutputs.getLocal(), optionalChancePercent, secondOptionalChancePercent ); - this.ingredients.add( new PositionedStack( secondOptionalOutput, -30 + 107 + 18 + 18, 47 ) ); - } + @Override + public List getIngredients() { + return this.getCycledIngredients( + NEIGrinderRecipeHandler.this.cycleticks / 20, this.ingredients + ); + } - if( recipe.getInput() != null ) - { - this.ingredients.add( new PositionedStack( recipe.getInput(), 45, 24 ) ); - } - } - - @Override - public PositionedStack getResult() - { - return this.result; - } - - @Override - public List getIngredients() - { - return this.getCycledIngredients( NEIGrinderRecipeHandler.this.cycleticks / 20, this.ingredients ); - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java index 9ff755e9..e5122d6e 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/NEIInscriberRecipeHandler.java @@ -18,6 +18,9 @@ package appeng.integration.modules.NEIHelpers; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.api.features.IInscriberRecipe; @@ -35,171 +38,149 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; -import java.awt.*; -import java.util.ArrayList; -import java.util.List; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class NEIInscriberRecipeHandler extends TemplateRecipeHandler -{ +public class NEIInscriberRecipeHandler extends TemplateRecipeHandler { + @Override + public void loadTransferRects() { + this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(84, 23, 24, 18), "inscriber" + )); + } - @Override - public void loadTransferRects() - { - this.transferRects.add( new TemplateRecipeHandler.RecipeTransferRect( new Rectangle( 84, 23, 24, 18 ), "inscriber" ) ); - } + @Override + public void loadCraftingRecipes(final String outputId, final Object... results) { + if ((outputId.equals("inscriber")) + && (this.getClass() == NEIInscriberRecipeHandler.class)) { + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + final CachedInscriberRecipe cachedRecipe + = new CachedInscriberRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } else { + super.loadCraftingRecipes(outputId, results); + } + } - @Override - public void loadCraftingRecipes( final String outputId, final Object... results ) - { - if( ( outputId.equals( "inscriber" ) ) && ( this.getClass() == NEIInscriberRecipeHandler.class ) ) - { - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - else - { - super.loadCraftingRecipes( outputId, results ); - } - } + @Override + public void loadCraftingRecipes(final ItemStack result) { + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + if (NEIServerUtils.areStacksSameTypeCrafting(recipe.getOutput(), result)) { + final CachedInscriberRecipe cachedRecipe + = new CachedInscriberRecipe(recipe); + cachedRecipe.computeVisuals(); + this.arecipes.add(cachedRecipe); + } + } + } - @Override - public void loadCraftingRecipes( final ItemStack result ) - { - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - if( NEIServerUtils.areStacksSameTypeCrafting( recipe.getOutput(), result ) ) - { - final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); - cachedRecipe.computeVisuals(); - this.arecipes.add( cachedRecipe ); - } - } - } + @Override + public void loadUsageRecipes(final ItemStack ingredient) { + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe(recipe); - @Override - public void loadUsageRecipes( final ItemStack ingredient ) - { - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - final CachedInscriberRecipe cachedRecipe = new CachedInscriberRecipe( recipe ); + if ((cachedRecipe.contains(cachedRecipe.ingredients, ingredient.getItem()))) { + cachedRecipe.computeVisuals(); + if (cachedRecipe.contains(cachedRecipe.ingredients, ingredient)) { + cachedRecipe.setIngredientPermutation( + cachedRecipe.ingredients, ingredient + ); + this.arecipes.add(cachedRecipe); + } + } + } + } - if( ( cachedRecipe.contains( cachedRecipe.ingredients, ingredient.getItem() ) ) ) - { - cachedRecipe.computeVisuals(); - if( cachedRecipe.contains( cachedRecipe.ingredients, ingredient ) ) - { - cachedRecipe.setIngredientPermutation( cachedRecipe.ingredients, ingredient ); - this.arecipes.add( cachedRecipe ); - } - } - } - } + @Override + public String getGuiTexture() { + final ResourceLocation loc + = new ResourceLocation("appliedenergistics2", "textures/guis/inscriber.png"); + return loc.toString(); + } - @Override - public String getGuiTexture() - { - final ResourceLocation loc = new ResourceLocation( "appliedenergistics2", "textures/guis/inscriber.png" ); - return loc.toString(); - } + @Override + public String getOverlayIdentifier() { + return "inscriber"; + } - @Override - public String getOverlayIdentifier() - { - return "inscriber"; - } + @Override + public Class getGuiClass() { + return GuiInscriber.class; + } - @Override - public Class getGuiClass() - { - return GuiInscriber.class; - } + @Override + public void drawBackground(final int recipe) { + GL11.glColor4f(1, 1, 1, 1); + GuiDraw.changeTexture(this.getGuiTexture()); + GuiDraw.drawTexturedModalRect(0, 0, 5, 11, 166, 75); + } - @Override - public void drawBackground( final int recipe ) - { - GL11.glColor4f( 1, 1, 1, 1 ); - GuiDraw.changeTexture( this.getGuiTexture() ); - GuiDraw.drawTexturedModalRect( 0, 0, 5, 11, 166, 75 ); - } + @Override + public boolean + hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return false; + } - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return false; - } + @Override + public IRecipeOverlayRenderer + getOverlayRenderer(final GuiContainer gui, final int recipe) { + return null; + } - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - return null; - } + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + return null; + } - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - return null; - } + @Override + public String getRecipeName() { + return GuiText.Inscriber.getLocal(); + } - @Override - public String getRecipeName() - { - return GuiText.Inscriber.getLocal(); - } + private class CachedInscriberRecipe extends TemplateRecipeHandler.CachedRecipe { + private final List ingredients; + private final PositionedStack result; - private class CachedInscriberRecipe extends TemplateRecipeHandler.CachedRecipe - { + public CachedInscriberRecipe(final IInscriberRecipe recipe) { + this.result = new PositionedStack(recipe.getOutput(), 108, 29); + this.ingredients = new ArrayList(); - private final List ingredients; - private final PositionedStack result; + for (final ItemStack top : recipe.getTopOptional().asSet()) { + this.ingredients.add(new PositionedStack(top, 40, 5)); + } - public CachedInscriberRecipe( final IInscriberRecipe recipe ) - { - this.result = new PositionedStack( recipe.getOutput(), 108, 29 ); - this.ingredients = new ArrayList(); + this.ingredients.add(new PositionedStack(recipe.getInputs(), 40 + 18, 28)); - for( final ItemStack top : recipe.getTopOptional().asSet() ) - { - this.ingredients.add( new PositionedStack( top, 40, 5 ) ); - } + for (final ItemStack bot : recipe.getBottomOptional().asSet()) { + this.ingredients.add(new PositionedStack(bot, 40, 51)); + } + } - this.ingredients.add( new PositionedStack( recipe.getInputs(), 40 + 18, 28 ) ); + @Override + public PositionedStack getResult() { + return this.result; + } - for( final ItemStack bot : recipe.getBottomOptional().asSet() ) - { - this.ingredients.add( new PositionedStack( bot, 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 ); - } - - private void computeVisuals() - { - for( final PositionedStack p : this.ingredients ) - { - p.generatePermutations(); - } - this.result.generatePermutations(); - } - } + private void computeVisuals() { + for (final PositionedStack p : this.ingredients) { + p.generatePermutations(); + } + this.result.generatePermutations(); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java b/src/main/java/appeng/integration/modules/NEIHelpers/NEIWorldCraftingHandler.java index 1f2d1689..a31ebefc 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.*; import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; @@ -40,208 +41,196 @@ import net.minecraft.inventory.Container; import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; -import java.util.*; +public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler { + private final Map details + = new HashMap(); + private final List offsets = new LinkedList(); + private final List outputs = new LinkedList(); + private ItemStack target; -public class NEIWorldCraftingHandler implements ICraftingHandler, IUsageHandler -{ + @Override + public String getRecipeName() { + return GuiText.InWorldCrafting.getLocal(); + } - private final Map details = new HashMap(); - private final List offsets = new LinkedList(); - private final List outputs = new LinkedList(); + @Override + public int numRecipes() { + return this.offsets.size(); + } - private ItemStack target; + @Override + public void drawBackground(final int recipe) { + GL11.glColor4f(1, 1, 1, 1); // nothing. + } - @Override - public String getRecipeName() - { - return GuiText.InWorldCrafting.getLocal(); - } + @Override + public void drawForeground(final int recipe) { + if (this.outputs.size() > recipe) { + // PositionedStack cr = this.outputs.get( recipe ); + final String details = this.details.get(this.offsets.get(recipe)); - @Override - public int numRecipes() - { - return this.offsets.size(); - } + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + fr.drawSplitString(details, 10, 25, 150, 0); + } + } - @Override - public void drawBackground( final int recipe ) - { - GL11.glColor4f( 1, 1, 1, 1 );// nothing. - } + @Override + public List getIngredientStacks(final int recipeIndex) { + return new ArrayList(); + } - @Override - public void drawForeground( final int recipe ) - { - if( this.outputs.size() > recipe ) - { - // PositionedStack cr = this.outputs.get( recipe ); - final String details = this.details.get( this.offsets.get( recipe ) ); + @Override + public List getOtherStacks(final int recipeIndex) { + return new ArrayList(); + } - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - fr.drawSplitString( details, 10, 25, 150, 0 ); - } - } + @Override + public PositionedStack getResultStack(final int recipe) { + return this.outputs.get(recipe); + } - @Override - public List getIngredientStacks( final int recipeIndex ) - { - return new ArrayList(); - } + @Override + public void onUpdate() {} - @Override - public List getOtherStacks( final int recipeIndex ) - { - return new ArrayList(); - } + @Override + public boolean + hasOverlay(final GuiContainer gui, final Container container, final int recipe) { + return false; + } - @Override - public PositionedStack getResultStack( final int recipe ) - { - return this.outputs.get( recipe ); - } + @Override + public IRecipeOverlayRenderer + getOverlayRenderer(final GuiContainer gui, final int recipe) { + return null; + } - @Override - public void onUpdate() - { + @Override + public IOverlayHandler getOverlayHandler(final GuiContainer gui, final int recipe) { + return null; + } - } + @Override + public int recipiesPerPage() { + return 1; + } - @Override - public boolean hasOverlay( final GuiContainer gui, final Container container, final int recipe ) - { - return false; - } + @Override + public List handleTooltip( + final GuiRecipe gui, final List currentToolTip, final int recipe + ) { + return currentToolTip; + } - @Override - public IRecipeOverlayRenderer getOverlayRenderer( final GuiContainer gui, final int recipe ) - { - return null; - } + @Override + public List handleItemTooltip( + final GuiRecipe gui, + final ItemStack stack, + final List currentToolTip, + final int recipe + ) { + return currentToolTip; + } - @Override - public IOverlayHandler getOverlayHandler( final GuiContainer gui, final int recipe ) - { - return null; - } + @Override + public boolean keyTyped( + final GuiRecipe gui, final char keyChar, final int keyCode, final int recipe + ) { + return false; + } - @Override - public int recipiesPerPage() - { - return 1; - } + @Override + public boolean mouseClicked(final GuiRecipe gui, final int button, final int recipe) { + return false; + } - @Override - public List handleTooltip( final GuiRecipe gui, final List currentToolTip, final int recipe ) - { - return currentToolTip; - } + @Override + public IUsageHandler + getUsageHandler(final String inputId, final Object... ingredients) { + return this; + } - @Override - public List handleItemTooltip( final GuiRecipe gui, final ItemStack stack, final List currentToolTip, final int recipe ) - { - return currentToolTip; - } + @Override + public ICraftingHandler + getRecipeHandler(final String outputId, final Object... results) { + final NEIWorldCraftingHandler g = this.newInstance(); + if (results.length > 0 && results[0] instanceof ItemStack) { + g.target = (ItemStack) results[0]; + g.addRecipes(); + return g; + } + return this; + } - @Override - public boolean keyTyped( final GuiRecipe gui, final char keyChar, final int keyCode, final int recipe ) - { - return false; - } + private NEIWorldCraftingHandler newInstance() { + try { + return this.getClass().newInstance(); + } catch (final InstantiationException e) { + throw new IllegalStateException(e); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } + } - @Override - public boolean mouseClicked( final GuiRecipe gui, final int button, final int recipe ) - { - return false; - } + private void addRecipes() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IMaterials materials = definitions.materials(); - @Override - public IUsageHandler getUsageHandler( final String inputId, final Object... ingredients ) - { - return this; - } + final String message; + if (AEConfig.instance.isFeatureEnabled(AEFeature.CertusQuartzWorldGen)) { + message = GuiText.ChargedQuartz.getLocal() + "\n\n" + + GuiText.ChargedQuartzFind.getLocal(); + } else { + message = GuiText.ChargedQuartzFind.getLocal(); + } - @Override - public ICraftingHandler getRecipeHandler( final String outputId, final Object... results ) - { - final NEIWorldCraftingHandler g = this.newInstance(); - if( results.length > 0 && results[0] instanceof ItemStack ) - { - g.target = (ItemStack) results[0]; - g.addRecipes(); - return g; - } - return this; - } + this.addRecipe(materials.certusQuartzCrystalCharged(), message); - private NEIWorldCraftingHandler newInstance() - { - try - { - return this.getClass().newInstance(); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - } + 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() + ); + } - private void addRecipes() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IMaterials materials = definitions.materials(); + if (AEConfig.instance.isFeatureEnabled(AEFeature.InWorldFluix)) { + this.addRecipe(materials.fluixCrystal(), GuiText.inWorldFluix.getLocal()); + } - final String message; - if( AEConfig.instance.isFeatureEnabled( AEFeature.CertusQuartzWorldGen ) ) - { - message = GuiText.ChargedQuartz.getLocal() + "\n\n" + GuiText.ChargedQuartzFind.getLocal(); - } - else - { - message = GuiText.ChargedQuartzFind.getLocal(); - } + if (AEConfig.instance.isFeatureEnabled(AEFeature.InWorldSingularity)) { + this.addRecipe( + materials.qESingularity(), GuiText.inWorldSingularity.getLocal() + ); + } - this.addRecipe( materials.certusQuartzCrystalCharged(), message ); + 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() + ); + } + } - 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( final IItemDefinition def, final String msg ) - { - for( final 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 addRecipe(final IItemDefinition def, final String msg) { + for (final 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 737db30e..432879cc 100644 --- a/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java +++ b/src/main/java/appeng/integration/modules/NEIHelpers/TerminalCraftingSlotFinder.java @@ -18,28 +18,21 @@ package appeng.integration.modules.NEIHelpers; +import java.util.ArrayList; import appeng.client.gui.implementations.GuiMEMonitorable; import codechicken.nei.PositionedStack; import codechicken.nei.api.IStackPositioner; -import java.util.ArrayList; - - -public class TerminalCraftingSlotFinder implements IStackPositioner -{ - - @Override - public ArrayList positionStacks( final ArrayList a ) - { - for( final PositionedStack ps : a ) - { - if( ps != null ) - { - ps.relx += GuiMEMonitorable.craftingGridOffsetX; - ps.rely += GuiMEMonitorable.craftingGridOffsetY; - } - } - return a; - } +public class TerminalCraftingSlotFinder implements IStackPositioner { + @Override + public ArrayList positionStacks(final ArrayList a) { + for (final 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/OpenComputers.java b/src/main/java/appeng/integration/modules/OpenComputers.java index 3c05fbaa..87a18152 100644 --- a/src/main/java/appeng/integration/modules/OpenComputers.java +++ b/src/main/java/appeng/integration/modules/OpenComputers.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -31,47 +30,62 @@ import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import li.cil.oc.api.Items; +public class OpenComputers implements IIntegrationModule { + @Reflected + public static OpenComputers instance; -public class OpenComputers implements IIntegrationModule -{ - @Reflected - public static OpenComputers instance; + @Reflected + public OpenComputers() { + IntegrationHelper.testClassExistence(this, li.cil.oc.api.Items.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.Network.class); + IntegrationHelper + .testClassExistence(this, li.cil.oc.api.network.Environment.class); + IntegrationHelper + .testClassExistence(this, li.cil.oc.api.network.SidedEnvironment.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.network.Node.class); + IntegrationHelper.testClassExistence(this, li.cil.oc.api.network.Message.class); + } - @Reflected - public OpenComputers() - { - IntegrationHelper.testClassExistence( this, li.cil.oc.api.Items.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.Network.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.Environment.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.SidedEnvironment.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.Node.class ); - IntegrationHelper.testClassExistence( this, li.cil.oc.api.network.Message.class ); - } + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.OpenComputers)) { + partHelper.registerNewLayer( + "appeng.parts.layers.LayerSidedEnvironment", + "li.cil.oc.api.network.SidedEnvironment" + ); + } + } - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.OpenComputers ) ) - { - partHelper.registerNewLayer( "appeng.parts.layers.LayerSidedEnvironment", "li.cil.oc.api.network.SidedEnvironment" ); - } - } + @Override + public void postInit() { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - @Override - public void postInit() - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - - registry.addNewAttunement( Items.get( "cable" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "adapter" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "switch" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "accessPoint" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "lanCard" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "linkedCard" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "wlanCard" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - registry.addNewAttunement( Items.get( "analyzer" ).createItemStack( 1 ), TunnelType.COMPUTER_MESSAGE ); - } + registry.addNewAttunement( + Items.get("cable").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + registry.addNewAttunement( + Items.get("adapter").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + registry.addNewAttunement( + Items.get("switch").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + registry.addNewAttunement( + Items.get("accessPoint").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + registry.addNewAttunement( + Items.get("lanCard").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + registry.addNewAttunement( + Items.get("linkedCard").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + registry.addNewAttunement( + Items.get("wlanCard").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + registry.addNewAttunement( + Items.get("analyzer").createItemStack(1), TunnelType.COMPUTER_MESSAGE + ); + } } diff --git a/src/main/java/appeng/integration/modules/PneumaticCraft.java b/src/main/java/appeng/integration/modules/PneumaticCraft.java index 75c0f7bd..9bf23f82 100644 --- a/src/main/java/appeng/integration/modules/PneumaticCraft.java +++ b/src/main/java/appeng/integration/modules/PneumaticCraft.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -33,51 +32,53 @@ import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; +public class PneumaticCraft implements IIntegrationModule { + @Reflected + public static PneumaticCraft instance; -public class PneumaticCraft implements IIntegrationModule -{ - @Reflected - public static PneumaticCraft instance; + private static final String PNEUMATIC_CRAFT_MOD_ID = "PneumaticCraft"; - private static final String PNEUMATIC_CRAFT_MOD_ID = "PneumaticCraft"; + @Reflected + public PneumaticCraft() { + IntegrationHelper + .testClassExistence(this, pneumaticCraft.api.block.BlockSupplier.class); + IntegrationHelper.testClassExistence( + this, pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class + ); + IntegrationHelper.testClassExistence( + this, pneumaticCraft.api.tileentity.AirHandlerSupplier.class + ); + IntegrationHelper + .testClassExistence(this, pneumaticCraft.api.tileentity.IAirHandler.class); + } - @Reflected - public PneumaticCraft() - { - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.block.BlockSupplier.class ); - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class ); - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.tileentity.AirHandlerSupplier.class ); - IntegrationHelper.testClassExistence( this, pneumaticCraft.api.tileentity.IAirHandler.class ); - } + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.PneumaticCraft)) { + partHelper.registerNewLayer( + appeng.parts.layers.LayerPressure.class.getName(), + pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class.getName() + ); + } + } - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.PneumaticCraft ) ) - { - partHelper.registerNewLayer( appeng.parts.layers.LayerPressure.class.getName(), pneumaticCraft.api.tileentity.ISidedPneumaticMachine.class.getName() ); - } - } + @Override + public void postInit() { + this.registerPressureAttunement("pressureTube"); + this.registerPressureAttunement("advancedPressureTube"); + } - @Override - public void postInit() - { - this.registerPressureAttunement( "pressureTube" ); - this.registerPressureAttunement( "advancedPressureTube" ); - } + private void registerPressureAttunement(final String itemID) { + final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); + final ItemStack modItem + = GameRegistry.findItemStack(PNEUMATIC_CRAFT_MOD_ID, itemID, 1); - private void registerPressureAttunement( final String itemID ) - { - final IP2PTunnelRegistry registry = AEApi.instance().registries().p2pTunnel(); - final ItemStack modItem = GameRegistry.findItemStack( PNEUMATIC_CRAFT_MOD_ID, itemID, 1 ); - - if( modItem != null ) - { - modItem.setItemDamage( OreDictionary.WILDCARD_VALUE ); - registry.addNewAttunement( modItem, TunnelType.PRESSURE ); - } - } + if (modItem != null) { + modItem.setItemDamage(OreDictionary.WILDCARD_VALUE); + registry.addNewAttunement(modItem, TunnelType.PRESSURE); + } + } } diff --git a/src/main/java/appeng/integration/modules/RC.java b/src/main/java/appeng/integration/modules/RC.java index 107b57d6..705644ec 100644 --- a/src/main/java/appeng/integration/modules/RC.java +++ b/src/main/java/appeng/integration/modules/RC.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; @@ -27,33 +26,30 @@ import mods.railcraft.api.crafting.IRockCrusherRecipe; import mods.railcraft.api.crafting.RailcraftCraftingManager; import net.minecraft.item.ItemStack; +public class RC implements IRC, IIntegrationModule { + @Reflected + public static RC instance; -public class RC implements IRC, IIntegrationModule -{ - @Reflected - public static RC instance; + @Reflected + public RC() { + IntegrationHelper.testClassExistence( + this, mods.railcraft.api.crafting.RailcraftCraftingManager.class + ); + IntegrationHelper.testClassExistence( + this, mods.railcraft.api.crafting.IRockCrusherRecipe.class + ); + } - @Reflected - public RC() - { - IntegrationHelper.testClassExistence( this, mods.railcraft.api.crafting.RailcraftCraftingManager.class ); - IntegrationHelper.testClassExistence( this, mods.railcraft.api.crafting.IRockCrusherRecipe.class ); - } + @Override + public void rockCrusher(final ItemStack input, final ItemStack output) { + final IRockCrusherRecipe re + = RailcraftCraftingManager.rockCrusher.createNewRecipe(input, true, true); + re.addOutput(output, 1.0f); + } - @Override - public void rockCrusher( final ItemStack input, final ItemStack output ) - { - final IRockCrusherRecipe re = RailcraftCraftingManager.rockCrusher.createNewRecipe( input, true, true ); - re.addOutput( output, 1.0f ); - } + @Override + public void init() {} - @Override - public void init() - { - } - - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/RF.java b/src/main/java/appeng/integration/modules/RF.java index 15f075b7..d462c74a 100644 --- a/src/main/java/appeng/integration/modules/RF.java +++ b/src/main/java/appeng/integration/modules/RF.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.config.TunnelType; @@ -32,65 +31,72 @@ import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; +public final class RF implements IIntegrationModule { + @Reflected + public static RF instance; -public final class RF implements IIntegrationModule -{ - @Reflected - public static RF instance; + @Reflected + public RF() { + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyReceiver.class); + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyProvider.class); + IntegrationHelper.testClassExistence(this, cofh.api.energy.IEnergyHandler.class); + IntegrationHelper + .testClassExistence(this, cofh.api.energy.IEnergyConnection.class); + } - @Reflected - public RF() - { - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyReceiver.class ); - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyProvider.class ); - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyHandler.class ); - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyConnection.class ); - } + @Override + public void init() { + final IAppEngApi api = AEApi.instance(); + final IPartHelper partHelper = api.partHelper(); - @Override - public void init() - { - final IAppEngApi api = AEApi.instance(); - final IPartHelper partHelper = api.partHelper(); + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.RF)) { + partHelper.registerNewLayer( + "appeng.parts.layers.LayerIEnergyHandler", + "cofh.api.energy.IEnergyReceiver" + ); + } + } - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.RF ) ) - { - partHelper.registerNewLayer( "appeng.parts.layers.LayerIEnergyHandler", "cofh.api.energy.IEnergyReceiver" ); - } - } + @Override + public void postInit() { + this.registerRFAttunement("ExtraUtilities", "extractor_base", 12); + this.registerRFAttunement("ExtraUtilities", "pipes", 11); + this.registerRFAttunement("ExtraUtilities", "pipes", 14); + this.registerRFAttunement( + "ExtraUtilities", "generator", OreDictionary.WILDCARD_VALUE + ); - @Override - public void postInit() - { - this.registerRFAttunement( "ExtraUtilities", "extractor_base", 12 ); - this.registerRFAttunement( "ExtraUtilities", "pipes", 11 ); - this.registerRFAttunement( "ExtraUtilities", "pipes", 14 ); - this.registerRFAttunement( "ExtraUtilities", "generator", OreDictionary.WILDCARD_VALUE ); + this.registerRFAttunement( + "ThermalExpansion", "Cell", OreDictionary.WILDCARD_VALUE + ); + this.registerRFAttunement( + "ThermalExpansion", "Dynamo", OreDictionary.WILDCARD_VALUE + ); - this.registerRFAttunement( "ThermalExpansion", "Cell", OreDictionary.WILDCARD_VALUE ); - this.registerRFAttunement( "ThermalExpansion", "Dynamo", OreDictionary.WILDCARD_VALUE ); + // Fluxduct + this.registerRFAttunement("ThermalDynamics", "ThermalDynamics_0", 0); - // Fluxduct - this.registerRFAttunement( "ThermalDynamics", "ThermalDynamics_0", 0 ); + this.registerRFAttunement( + "EnderIO", "itemPowerConduit", OreDictionary.WILDCARD_VALUE + ); + this.registerRFAttunement("EnderIO", "blockCapacitorBank", 0); + this.registerRFAttunement("EnderIO", "blockPowerMonitor", 0); + } - this.registerRFAttunement( "EnderIO", "itemPowerConduit", OreDictionary.WILDCARD_VALUE ); - this.registerRFAttunement( "EnderIO", "blockCapacitorBank", 0 ); - this.registerRFAttunement( "EnderIO", "blockPowerMonitor", 0 ); - } + private void + registerRFAttunement(final String mod, final String name, final int dmg) { + assert mod != null; + assert !mod.isEmpty(); + assert name != null; + assert !name.isEmpty(); + assert dmg >= 0; - private void registerRFAttunement( final String mod, final String name, final int dmg ) - { - assert mod != null; - assert !mod.isEmpty(); - assert name != null; - assert !name.isEmpty(); - assert dmg >= 0; - - final ItemStack modItem = GameRegistry.findItemStack( mod, name, 1 ); - if( modItem != null ) - { - modItem.setItemDamage( dmg ); - AEApi.instance().registries().p2pTunnel().addNewAttunement( modItem, TunnelType.RF_POWER ); - } - } + final 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 d2ded2c8..9d31ed1e 100644 --- a/src/main/java/appeng/integration/modules/RFItem.java +++ b/src/main/java/appeng/integration/modules/RFItem.java @@ -18,30 +18,23 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; +public class RFItem implements IIntegrationModule { + @Reflected + public static RFItem instance; -public class RFItem implements IIntegrationModule -{ - @Reflected - public static RFItem instance; + @Reflected + public RFItem() { + IntegrationHelper + .testClassExistence(this, cofh.api.energy.IEnergyContainerItem.class); + } - @Reflected - public RFItem() - { - IntegrationHelper.testClassExistence( this, cofh.api.energy.IEnergyContainerItem.class ); - } + @Override + public void init() {} - @Override - public void init() - { - } - - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/RotaryCraft.java b/src/main/java/appeng/integration/modules/RotaryCraft.java index 90cd7f58..fe3c64eb 100644 --- a/src/main/java/appeng/integration/modules/RotaryCraft.java +++ b/src/main/java/appeng/integration/modules/RotaryCraft.java @@ -18,31 +18,27 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; +public class RotaryCraft implements IIntegrationModule { + @Reflected + public static RotaryCraft instance; -public class RotaryCraft implements IIntegrationModule -{ - @Reflected - public static RotaryCraft instance; + @Reflected + public RotaryCraft() { + IntegrationHelper.testClassExistence( + this, Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver.class + ); + IntegrationHelper.testClassExistence( + this, Reika.RotaryCraft.API.Interfaces.Transducerable.class + ); + } - @Reflected - public RotaryCraft() - { - IntegrationHelper.testClassExistence( this, Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver.class ); - IntegrationHelper.testClassExistence( this, Reika.RotaryCraft.API.Interfaces.Transducerable.class ); - } + @Override + public void init() throws Throwable {} - @Override - public void init() throws Throwable - { - } - - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/Waila.java b/src/main/java/appeng/integration/modules/Waila.java index c7660436..a4e2d08a 100644 --- a/src/main/java/appeng/integration/modules/Waila.java +++ b/src/main/java/appeng/integration/modules/Waila.java @@ -18,7 +18,6 @@ package appeng.integration.modules; - import appeng.helpers.Reflected; import appeng.integration.IIntegrationModule; import appeng.integration.IntegrationHelper; @@ -29,44 +28,44 @@ import cpw.mods.fml.common.event.FMLInterModComms; import mcp.mobius.waila.api.IWailaDataProvider; import mcp.mobius.waila.api.IWailaRegistrar; +public class Waila implements IIntegrationModule { + @Reflected + public static Waila instance; -public class Waila implements IIntegrationModule -{ - @Reflected - public static Waila instance; + @Reflected + public Waila() { + IntegrationHelper + .testClassExistence(this, mcp.mobius.waila.api.IWailaDataProvider.class); + IntegrationHelper + .testClassExistence(this, mcp.mobius.waila.api.IWailaRegistrar.class); + IntegrationHelper + .testClassExistence(this, mcp.mobius.waila.api.IWailaConfigHandler.class); + IntegrationHelper + .testClassExistence(this, mcp.mobius.waila.api.IWailaDataAccessor.class); + IntegrationHelper + .testClassExistence(this, mcp.mobius.waila.api.ITaggedList.class); + } - @Reflected - public Waila() - { - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaDataProvider.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaRegistrar.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaConfigHandler.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.IWailaDataAccessor.class ); - IntegrationHelper.testClassExistence( this, mcp.mobius.waila.api.ITaggedList.class ); - } + public static void register(final IWailaRegistrar registrar) { + final IWailaDataProvider partHost = new PartWailaDataProvider(); - public static void register( final IWailaRegistrar registrar ) - { - final IWailaDataProvider partHost = new PartWailaDataProvider(); + registrar.registerStackProvider(partHost, AEBaseTile.class); + registrar.registerBodyProvider(partHost, AEBaseTile.class); + registrar.registerNBTProvider(partHost, AEBaseTile.class); - registrar.registerStackProvider( partHost, AEBaseTile.class ); - registrar.registerBodyProvider( partHost, AEBaseTile.class ); - registrar.registerNBTProvider( partHost, AEBaseTile.class ); + final IWailaDataProvider tile = new TileWailaDataProvider(); - final IWailaDataProvider tile = new TileWailaDataProvider(); + registrar.registerBodyProvider(tile, AEBaseTile.class); + registrar.registerNBTProvider(tile, AEBaseTile.class); + } - registrar.registerBodyProvider( tile, AEBaseTile.class ); - registrar.registerNBTProvider( tile, AEBaseTile.class ); - } + @Override + public void init() throws Throwable { + FMLInterModComms.sendMessage( + "Waila", "register", this.getClass().getName() + ".register" + ); + } - @Override - public void init() throws Throwable - { - FMLInterModComms.sendMessage( "Waila", "register", this.getClass().getName() + ".register" ); - } - - @Override - public void postInit() - { - } + @Override + public void postInit() {} } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrate.java b/src/main/java/appeng/integration/modules/helpers/BSCrate.java index d0b66743..b5dd9ddf 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrate.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrate.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -29,59 +28,56 @@ import appeng.util.item.AEItemStack; import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraft.item.ItemStack; +public class BSCrate implements IMEInventory { + private final ICrateStorage crateStorage; -public class BSCrate implements IMEInventory -{ - private final ICrateStorage crateStorage; + public BSCrate(final Object object) { + this.crateStorage = (ICrateStorage) object; + } - public BSCrate( final Object object ) - { - this.crateStorage = (ICrateStorage) object; - } + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + if (mode == Actionable.SIMULATE) { + return null; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return null; - } + final ItemStack failed = this.crateStorage.insertItems(input.getItemStack()); + if (failed == null) { + return null; + } + input.setStackSize(failed.stackSize); + return input; + } - final ItemStack failed = this.crateStorage.insertItems( input.getItemStack() ); - if( failed == null ) - { - return null; - } - input.setStackSize( failed.stackSize ); - return input; - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + if (mode == Actionable.SIMULATE) { + final int howMany = this.crateStorage.getItemCount(request.getItemStack()); + return howMany > request.getStackSize() + ? request + : request.copy().setStackSize(howMany); + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - final int howMany = this.crateStorage.getItemCount( request.getItemStack() ); - return howMany > request.getStackSize() ? request : request.copy().setStackSize( howMany ); - } + final ItemStack obtained = this.crateStorage.extractItems( + request.getItemStack(), (int) request.getStackSize() + ); + return AEItemStack.create(obtained); + } - final ItemStack obtained = this.crateStorage.extractItems( request.getItemStack(), (int) request.getStackSize() ); - return AEItemStack.create( obtained ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final ItemStack is : this.crateStorage.getContents()) { + out.add(AEItemStack.create(is)); + } + return out; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final ItemStack is : this.crateStorage.getContents() ) - { - out.add( AEItemStack.create( is ) ); - } - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java b/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java index 3a92d6da..41d0e71a 100644 --- a/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/BSCrateHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -27,23 +26,27 @@ import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class BSCrateHandler implements IExternalStorageHandler { + @Override + public boolean canHandle( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource mySrc + ) { + return channel == StorageChannel.ITEMS && te instanceof ICrateStorage; + } -public class BSCrateHandler implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc ) - { - return channel == StorageChannel.ITEMS && te instanceof ICrateStorage; - } - - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src ) - { - if( channel == StorageChannel.ITEMS ) - { - return new BSCrate( te ); - } - return null; - } + @Override + public IMEInventory getInventory( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource src + ) { + if (channel == StorageChannel.ITEMS) { + return new BSCrate(te); + } + 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 f16c7fde..e39b330b 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 appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; @@ -28,185 +29,166 @@ import appeng.util.iterators.StackToSlotIterator; import net.mcft.copy.betterstorage.api.crate.ICrateStorage; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public class BSCrateStorageAdaptor extends InventoryAdaptor { + private final ICrateStorage cs; + public BSCrateStorageAdaptor(final Object te) { + this.cs = (ICrateStorage) te; + } -public class BSCrateStorageAdaptor extends InventoryAdaptor -{ + @Override + public ItemStack removeItems( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + ItemStack target = null; - private final ICrateStorage cs; + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 + && (filter == null || Platform.isSameItem(filter, is))) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } - public BSCrateStorageAdaptor( final Object te ) - { - this.cs = (ICrateStorage) te; - } + if (target != null) { + final ItemStack f = Platform.cloneItemStack(target); + f.stackSize = amount; + return this.cs.extractItems(f, amount); + } - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - ItemStack target = null; + return null; + } - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } + @Override + public ItemStack simulateRemove( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + ItemStack target = null; - if( target != null ) - { - final ItemStack f = Platform.cloneItemStack( target ); - f.stackSize = amount; - return this.cs.extractItems( f, amount ); - } + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 + && (filter == null || Platform.isSameItem(filter, is))) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } - return null; - } + if (target != null) { + int cnt = this.cs.getItemCount(target); + if (cnt == 0) { + return null; + } + if (cnt > amount) { + cnt = amount; + } + final ItemStack c = target.copy(); + c.stackSize = cnt; + return c; + } - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - ItemStack target = null; + return null; + } - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItem( filter, is ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + ItemStack target = null; - if( target != null ) - { - int cnt = this.cs.getItemCount( target ); - if( cnt == 0 ) - { - return null; - } - if( cnt > amount ) - { - cnt = amount; - } - final ItemStack c = target.copy(); - c.stackSize = cnt; - return c; - } + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 + && (filter == null || Platform.isSameItemFuzzy(filter, is, fuzzyMode) + )) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } - return null; - } + if (target != null) { + final ItemStack f = Platform.cloneItemStack(target); + f.stackSize = amount; + return this.cs.extractItems(f, amount); + } - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - ItemStack target = null; + return null; + } - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + ItemStack target = null; - if( target != null ) - { - final ItemStack f = Platform.cloneItemStack( target ); - f.stackSize = amount; - return this.cs.extractItems( f, amount ); - } + for (final ItemStack is : this.cs.getContents()) { + if (is != null) { + if (is.stackSize > 0 + && (filter == null || Platform.isSameItemFuzzy(filter, is, fuzzyMode) + )) { + if (destination == null || destination.canInsert(is)) { + target = is; + break; + } + } + } + } - return null; - } + if (target != null) { + int cnt = this.cs.getItemCount(target); + if (cnt == 0) { + return null; + } + if (cnt > amount) { + cnt = amount; + } + final ItemStack c = target.copy(); + c.stackSize = cnt; + return c; + } - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - ItemStack target = null; + return null; + } - for( final ItemStack is : this.cs.getContents() ) - { - if( is != null ) - { - if( is.stackSize > 0 && ( filter == null || Platform.isSameItemFuzzy( filter, is, fuzzyMode ) ) ) - { - if( destination == null || destination.canInsert( is ) ) - { - target = is; - break; - } - } - } - } + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + return this.cs.insertItems(toBeAdded); + } - if( target != null ) - { - int cnt = this.cs.getItemCount( target ); - if( cnt == 0 ) - { - return null; - } - if( cnt > amount ) - { - cnt = amount; - } - final ItemStack c = target.copy(); - c.stackSize = cnt; - return c; - } + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + final int items = this.cs.getSpaceForItem(toBeSimulated); + final ItemStack cloned = Platform.cloneItemStack(toBeSimulated); + if (toBeSimulated.stackSize <= items) { + return null; + } + cloned.stackSize -= items; + return cloned; + } - return null; - } + @Override + public boolean containsItems() { + return this.cs.getUniqueItems() > 0; + } - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - return this.cs.insertItems( toBeAdded ); - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - final int items = this.cs.getSpaceForItem( toBeSimulated ); - final ItemStack cloned = Platform.cloneItemStack( toBeSimulated ); - if( toBeSimulated.stackSize <= items ) - { - return null; - } - cloned.stackSize -= items; - return cloned; - } - - @Override - public boolean containsItems() - { - return this.cs.getUniqueItems() > 0; - } - - @Override - public Iterator iterator() - { - return new StackToSlotIterator( this.cs.getContents().iterator() ); - } + @Override + public Iterator iterator() { + 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 21f9eb7c..e0d82d7a 100644 --- a/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java +++ b/src/main/java/appeng/integration/modules/helpers/FMPPacketEvent.java @@ -18,23 +18,17 @@ package appeng.integration.modules.helpers; - import cpw.mods.fml.common.eventhandler.Event; import net.minecraft.entity.player.EntityPlayerMP; +public class FMPPacketEvent extends Event { + private final EntityPlayerMP sender; -public class FMPPacketEvent extends Event -{ + public FMPPacketEvent(final EntityPlayerMP sender) { + this.sender = sender; + } - private final EntityPlayerMP sender; - - public FMPPacketEvent( final EntityPlayerMP sender ) - { - this.sender = sender; - } - - public EntityPlayerMP getSender() - { - return this.sender; - } + public EntityPlayerMP getSender() { + return this.sender; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java b/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java index c78a9e78..3b27928a 100644 --- a/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java +++ b/src/main/java/appeng/integration/modules/helpers/FactorizationBarrel.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -30,146 +29,123 @@ import appeng.util.item.AEItemStack; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; +public class FactorizationBarrel implements IMEInventory { + private final IFZ fProxy; + private final TileEntity te; -public class FactorizationBarrel implements IMEInventory -{ + public FactorizationBarrel(final IFZ proxy, final TileEntity tile) { + this.te = tile; + this.fProxy = proxy; + } - private final IFZ fProxy; - private final TileEntity te; + public long remainingItemCount() { + return this.fProxy.barrelGetMaxItemCount(this.te) + - this.fProxy.barrelGetItemCount(this.te); + } - public FactorizationBarrel( final IFZ proxy, final TileEntity tile ) - { - this.te = tile; - this.fProxy = proxy; - } + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + if (input == null) { + return null; + } + if (input.getStackSize() == 0) { + return null; + } - public long remainingItemCount() - { - return this.fProxy.barrelGetMaxItemCount( this.te ) - this.fProxy.barrelGetItemCount( this.te ); - } + final ItemStack shared = input.getItemStack(); + if (shared.isItemDamaged()) { + return input; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( input == null ) - { - return null; - } - if( input.getStackSize() == 0 ) - { - return null; - } + if (this.remainingItemTypes() > 0) { + if (mode == Actionable.MODULATE) { + this.fProxy.setItemType(this.te, input.getItemStack()); + } + } - final ItemStack shared = input.getItemStack(); - if( shared.isItemDamaged() ) - { - return input; - } + if (this.containsItemType(input, mode == Actionable.SIMULATE)) { + final int max = this.fProxy.barrelGetMaxItemCount(this.te); + final int newTotal + = (int) this.storedItemCount() + (int) input.getStackSize(); + if (newTotal > max) { + if (mode == Actionable.MODULATE) { + this.fProxy.barrelSetCount(this.te, max); + } + final IAEItemStack result = input.copy(); + result.setStackSize(newTotal - max); + return result; + } else { + if (mode == Actionable.MODULATE) { + this.fProxy.barrelSetCount(this.te, newTotal); + } + return null; + } + } - if( this.remainingItemTypes() > 0 ) - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.setItemType( this.te, input.getItemStack() ); - } - } + return input; + } - if( this.containsItemType( input, mode == Actionable.SIMULATE ) ) - { - final int max = this.fProxy.barrelGetMaxItemCount( this.te ); - final int newTotal = (int) this.storedItemCount() + (int) input.getStackSize(); - if( newTotal > max ) - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.barrelSetCount( this.te, max ); - } - final IAEItemStack result = input.copy(); - result.setStackSize( newTotal - max ); - return result; - } - else - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.barrelSetCount( this.te, newTotal ); - } - return null; - } - } + private long remainingItemTypes() { + return this.fProxy.barrelGetItem(this.te) == null ? 1 : 0; + } - return input; - } + private boolean containsItemType(final IAEItemStack i, final boolean acceptEmpty) { + final ItemStack currentItem = this.fProxy.barrelGetItem(this.te); - private long remainingItemTypes() - { - return this.fProxy.barrelGetItem( this.te ) == null ? 1 : 0; - } + // empty barrels want your love too! + if (acceptEmpty && currentItem == null) { + return true; + } - private boolean containsItemType( final IAEItemStack i, final boolean acceptEmpty ) - { - final ItemStack currentItem = this.fProxy.barrelGetItem( this.te ); + return i.equals(currentItem); + } - // empty barrels want your love too! - if( acceptEmpty && currentItem == null ) - { - return true; - } + private long storedItemCount() { + return this.fProxy.barrelGetItemCount(this.te); + } - return i.equals( currentItem ); - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + if (this.containsItemType(request, false)) { + final int howMany = (int) this.storedItemCount(); + if (request.getStackSize() >= howMany) { + if (mode == Actionable.MODULATE) { + this.fProxy.setItemType(this.te, null); + this.fProxy.barrelSetCount(this.te, 0); + } - private long storedItemCount() - { - return this.fProxy.barrelGetItemCount( this.te ); - } + final IAEItemStack r = request.copy(); + r.setStackSize(howMany); + return r; + } else { + if (mode == Actionable.MODULATE) { + this.fProxy.barrelSetCount( + this.te, (int) (howMany - request.getStackSize()) + ); + } + return request.copy(); + } + } + return null; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( this.containsItemType( request, false ) ) - { - final int howMany = (int) this.storedItemCount(); - if( request.getStackSize() >= howMany ) - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.setItemType( this.te, null ); - this.fProxy.barrelSetCount( this.te, 0 ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + final ItemStack i = this.fProxy.barrelGetItem(this.te); + if (i != null) { + i.stackSize = this.fProxy.barrelGetItemCount(this.te); + out.addStorage(AEItemStack.create(i)); + } - final IAEItemStack r = request.copy(); - r.setStackSize( howMany ); - return r; - } - else - { - if( mode == Actionable.MODULATE ) - { - this.fProxy.barrelSetCount( this.te, (int) ( howMany - request.getStackSize() ) ); - } - return request.copy(); - } - } - return null; - } + return out; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - final ItemStack i = this.fProxy.barrelGetItem( this.te ); - if( i != null ) - { - i.stackSize = this.fProxy.barrelGetItemCount( this.te ); - out.addStorage( AEItemStack.create( i ) ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @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 a5da4b37..774aca59 100644 --- a/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/FactorizationHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,23 +28,29 @@ import appeng.util.inv.IMEAdaptor; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class FactorizationHandler implements IExternalStorageHandler { + @Override + public boolean canHandle( + final TileEntity te, + final ForgeDirection d, + final StorageChannel chan, + final BaseActionSource mySrc + ) { + return chan == StorageChannel.ITEMS && FZ.instance.isBarrel(te); + } -public class FactorizationHandler implements IExternalStorageHandler -{ - - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - return chan == StorageChannel.ITEMS && FZ.instance.isBarrel( te ); - } - - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - return new MEMonitorIInventory( new IMEAdaptor( FZ.instance.getFactorizationBarrel( te ), src ) ); - } - return null; - } + @Override + public IMEInventory getInventory( + final TileEntity te, + final ForgeDirection d, + final StorageChannel chan, + final BaseActionSource src + ) { + 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 62f27823..5fb87725 100644 --- a/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/MFRDSUHandler.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; import appeng.api.storage.IMEInventory; @@ -29,24 +28,28 @@ import appeng.util.inv.IMEAdaptor; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class MFRDSUHandler implements IExternalStorageHandler { + @Override + public boolean canHandle( + final TileEntity te, + final ForgeDirection d, + final StorageChannel chan, + final BaseActionSource mySrc + ) { + return chan == StorageChannel.ITEMS && DSU.instance.isDSU(te); + } -public class MFRDSUHandler implements IExternalStorageHandler -{ + @Override + public IMEInventory getInventory( + final TileEntity te, + final ForgeDirection d, + final StorageChannel chan, + final BaseActionSource src + ) { + if (chan == StorageChannel.ITEMS) { + return new MEMonitorIInventory(new IMEAdaptor(DSU.instance.getDSU(te), src)); + } - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource mySrc ) - { - return chan == StorageChannel.ITEMS && DSU.instance.isDSU( te ); - } - - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel chan, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - return new MEMonitorIInventory( new IMEAdaptor( DSU.instance.getDSU( te ), src ) ); - } - - return null; - } + 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 25725efc..1bc3f57c 100644 --- a/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java +++ b/src/main/java/appeng/integration/modules/helpers/MinefactoryReloadedDeepStorageUnit.java @@ -18,7 +18,6 @@ package appeng.integration.modules.helpers; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -30,109 +29,92 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import powercrystals.minefactoryreloaded.api.IDeepStorageUnit; +public class MinefactoryReloadedDeepStorageUnit implements IMEInventory { + private final IDeepStorageUnit dsu; -public class MinefactoryReloadedDeepStorageUnit implements IMEInventory -{ + public MinefactoryReloadedDeepStorageUnit(final TileEntity ta) { + this.dsu = (IDeepStorageUnit) ta; + } - private final IDeepStorageUnit dsu; + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + final ItemStack is = this.dsu.getStoredItemType(); + if (is != null) { + if (input.equals(is)) { + final long max = this.dsu.getMaxStoredCount(); + long storedItems = is.stackSize; + if (max == storedItems) { + return input; + } - public MinefactoryReloadedDeepStorageUnit( final TileEntity ta ) - { - this.dsu = (IDeepStorageUnit) ta; - } + storedItems += input.getStackSize(); + if (storedItems > max) { + final IAEItemStack overflow = AEItemStack.create(is); + overflow.setStackSize((int) (storedItems - max)); + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount((int) max); + } + return overflow; + } else { + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount( + is.stackSize + (int) input.getStackSize() + ); + } + return null; + } + } + } else { + if (input.getTagCompound() != null) { + return input; + } + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemType( + input.getItemStack(), (int) input.getStackSize() + ); + } + return null; + } + return input; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - final ItemStack is = this.dsu.getStoredItemType(); - if( is != null ) - { - if( input.equals( is ) ) - { - final long max = this.dsu.getMaxStoredCount(); - long storedItems = is.stackSize; - if( max == storedItems ) - { - return input; - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + ItemStack is = this.dsu.getStoredItemType(); + if (request.equals(is)) { + if (request.getStackSize() >= is.stackSize) { + is = is.copy(); + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount(0); + } + return AEItemStack.create(is); + } else { + if (mode == Actionable.MODULATE) { + this.dsu.setStoredItemCount( + is.stackSize - (int) request.getStackSize() + ); + } + return request.copy(); + } + } + return null; + } - storedItems += input.getStackSize(); - if( storedItems > max ) - { - final IAEItemStack overflow = AEItemStack.create( is ); - overflow.setStackSize( (int) ( storedItems - max ) ); - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( (int) max ); - } - return overflow; - } - else - { - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( is.stackSize + (int) input.getStackSize() ); - } - return null; - } - } - } - else - { - if( input.getTagCompound() != null ) - { - return input; - } - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemType( input.getItemStack(), (int) input.getStackSize() ); - } - return null; - } - return input; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + final ItemStack is = this.dsu.getStoredItemType(); + if (is != null) { + out.add(AEItemStack.create(is)); + } + return out; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - ItemStack is = this.dsu.getStoredItemType(); - if( request.equals( is ) ) - { - if( request.getStackSize() >= is.stackSize ) - { - is = is.copy(); - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( 0 ); - } - return AEItemStack.create( is ); - } - else - { - if( mode == Actionable.MODULATE ) - { - this.dsu.setStoredItemCount( is.stackSize - (int) request.getStackSize() ); - } - return request.copy(); - } - } - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - final ItemStack is = this.dsu.getStoredItemType(); - if( is != null ) - { - out.add( AEItemStack.create( is ) ); - } - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } } diff --git a/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java b/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java index 27a90d37..801b8a75 100644 --- a/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java +++ b/src/main/java/appeng/integration/modules/helpers/NullRFHandler.java @@ -18,35 +18,29 @@ package appeng.integration.modules.helpers; - import cofh.api.energy.IEnergyReceiver; import net.minecraftforge.common.util.ForgeDirection; +public class NullRFHandler implements IEnergyReceiver { + @Override + public int receiveEnergy( + final ForgeDirection from, final int maxReceive, final boolean simulate + ) { + return 0; + } -public class NullRFHandler implements IEnergyReceiver -{ + @Override + public int getEnergyStored(final ForgeDirection from) { + return 0; + } - @Override - public int receiveEnergy( final ForgeDirection from, final int maxReceive, final boolean simulate ) - { - return 0; - } + @Override + public int getMaxEnergyStored(final ForgeDirection from) { + return 0; + } - @Override - public int getEnergyStored( final ForgeDirection from ) - { - return 0; - } - - @Override - public int getMaxEnergyStored( final ForgeDirection from ) - { - return 0; - } - - @Override - public boolean canConnectEnergy( final ForgeDirection from ) - { - return true; - } + @Override + public boolean canConnectEnergy(final ForgeDirection from) { + return true; + } } diff --git a/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java index a52181c9..0fee2b4a 100644 --- a/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/BaseWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; @@ -28,9 +29,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Base implementation for {@link mcp.mobius.waila.api.IWailaDataProvider} * @@ -38,35 +36,53 @@ import java.util.List; * @version rv2 * @since rv2 */ -public abstract class BaseWailaDataProvider implements IWailaDataProvider -{ - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return null; - } +public abstract class BaseWailaDataProvider implements IWailaDataProvider { + @Override + public ItemStack + getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return null; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaHead( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + return currentToolTip; + } - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + return currentToolTip; + } - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaTail( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - return tag; - } + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z + ) { + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java index f382b2b8..30b9344a 100644 --- a/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/PartWailaDataProvider.java @@ -18,23 +18,8 @@ package appeng.integration.modules.waila; - import java.util.List; -import com.google.common.base.Optional; -import com.google.common.collect.Lists; - -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.world.World; - -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; - import appeng.api.parts.IPart; import appeng.integration.modules.waila.part.ChannelWailaDataProvider; import appeng.integration.modules.waila.part.IPartWailaDataProvider; @@ -44,7 +29,17 @@ import appeng.integration.modules.waila.part.PartStackWailaDataProvider; import appeng.integration.modules.waila.part.PowerStateWailaDataProvider; import appeng.integration.modules.waila.part.StorageMonitorWailaDataProvider; import appeng.integration.modules.waila.part.Tracer; - +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.MovingObjectPosition; +import net.minecraft.world.World; /** * Delegation provider for parts through {@link IPartWailaDataProvider} @@ -53,144 +48,153 @@ import appeng.integration.modules.waila.part.Tracer; * @version rv2 * @since rv2 */ -public final class PartWailaDataProvider implements IWailaDataProvider -{ - /** - * Contains all providers - */ - private final List providers; +public final class PartWailaDataProvider implements IWailaDataProvider { + /** + * Contains all providers + */ + private final List providers; - /** - * Can access parts through view-hits - */ - private final PartAccessor accessor = new PartAccessor(); + /** + * Can access parts through view-hits + */ + private final PartAccessor accessor = new PartAccessor(); - /** - * Traces views hit on blocks - */ - private final Tracer tracer = new Tracer(); + /** + * Traces views hit on blocks + */ + private final Tracer tracer = new Tracer(); - /** - * Initializes the provider list with all wanted providers - */ - public PartWailaDataProvider() - { - final IPartWailaDataProvider channel = new ChannelWailaDataProvider(); - final IPartWailaDataProvider storageMonitor = new StorageMonitorWailaDataProvider(); - final IPartWailaDataProvider powerState = new PowerStateWailaDataProvider(); - final IPartWailaDataProvider p2pState = new P2PStateWailaDataProvider(); - final IPartWailaDataProvider partStack = new PartStackWailaDataProvider(); + /** + * Initializes the provider list with all wanted providers + */ + public PartWailaDataProvider() { + final IPartWailaDataProvider channel = new ChannelWailaDataProvider(); + final IPartWailaDataProvider storageMonitor + = new StorageMonitorWailaDataProvider(); + final IPartWailaDataProvider powerState = new PowerStateWailaDataProvider(); + final IPartWailaDataProvider p2pState = new P2PStateWailaDataProvider(); + final IPartWailaDataProvider partStack = new PartStackWailaDataProvider(); - this.providers = Lists.newArrayList( channel, storageMonitor, powerState, partStack, p2pState ); - } + this.providers = Lists.newArrayList( + channel, storageMonitor, powerState, partStack, p2pState + ); + } - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); + @Override + public ItemStack + getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - ItemStack wailaStack = null; + ItemStack wailaStack = null; - for( final IPartWailaDataProvider provider : this.providers ) - { - wailaStack = provider.getWailaStack( part, config, wailaStack ); - } - return wailaStack; - } + for (final IPartWailaDataProvider provider : this.providers) { + wailaStack = provider.getWailaStack(part, config, wailaStack); + } + return wailaStack; + } - return null; - } + return null; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); + @Override + public List getWailaHead( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaHead( part, currentToolTip, accessor, config ); - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaHead(part, currentToolTip, accessor, config); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaBody( part, currentToolTip, accessor, config ); - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaBody(part, currentToolTip, accessor, config); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - final MovingObjectPosition mop = accessor.getPosition(); + @Override + public List getWailaTail( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + final TileEntity te = accessor.getTileEntity(); + final MovingObjectPosition mop = accessor.getPosition(); - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getWailaTail( part, currentToolTip, accessor, config ); - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getWailaTail(part, currentToolTip, accessor, config); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - final MovingObjectPosition mop = this.tracer.retraceBlock( world, player, x, y, z ); + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z + ) { + final MovingObjectPosition mop = this.tracer.retraceBlock(world, player, x, y, z); - if( mop != null ) - { - final Optional maybePart = this.accessor.getMaybePart( te, mop ); + if (mop != null) { + final Optional maybePart = this.accessor.getMaybePart(te, mop); - if( maybePart.isPresent() ) - { - final IPart part = maybePart.get(); + if (maybePart.isPresent()) { + final IPart part = maybePart.get(); - for( final IPartWailaDataProvider provider : this.providers ) - { - provider.getNBTData( player, part, te, tag, world, x, y, z ); - } - } - } + for (final IPartWailaDataProvider provider : this.providers) { + provider.getNBTData(player, part, te, tag, world, x, y, z); + } + } + } - return tag; - } + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java index 8b38bf67..c6f8f9a6 100644 --- a/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/TileWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila; +import java.util.List; import appeng.integration.modules.waila.tile.ChargerWailaDataProvider; import appeng.integration.modules.waila.tile.CraftingMonitorWailaDataProvider; @@ -33,9 +34,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Delegation provider for tiles through {@link mcp.mobius.waila.api.IWailaDataProvider} * @@ -43,73 +41,87 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class TileWailaDataProvider implements IWailaDataProvider -{ - /** - * Contains all providers - */ - private final List providers; +public final class TileWailaDataProvider implements IWailaDataProvider { + /** + * Contains all providers + */ + private final List providers; - /** - * Initializes the provider list with all wanted providers - */ - public TileWailaDataProvider() - { - final IWailaDataProvider charger = new ChargerWailaDataProvider(); - final IWailaDataProvider energyCell = new PowerStorageWailaDataProvider(); - final IWailaDataProvider craftingBlock = new PowerStateWailaDataProvider(); - final IWailaDataProvider craftingMonitor = new CraftingMonitorWailaDataProvider(); + /** + * Initializes the provider list with all wanted providers + */ + public TileWailaDataProvider() { + final IWailaDataProvider charger = new ChargerWailaDataProvider(); + final IWailaDataProvider energyCell = new PowerStorageWailaDataProvider(); + final IWailaDataProvider craftingBlock = new PowerStateWailaDataProvider(); + final IWailaDataProvider craftingMonitor = new CraftingMonitorWailaDataProvider(); - this.providers = Lists.newArrayList( charger, energyCell, craftingBlock, craftingMonitor ); - } + this.providers + = Lists.newArrayList(charger, energyCell, craftingBlock, craftingMonitor); + } - @Override - public ItemStack getWailaStack( final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return null; - } + @Override + public ItemStack + getWailaStack(final IWailaDataAccessor accessor, final IWailaConfigHandler config) { + return null; + } - @Override - public List getWailaHead( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaHead( itemStack, currentToolTip, accessor, config ); - } + @Override + public List getWailaHead( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaHead(itemStack, currentToolTip, accessor, config); + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaBody( itemStack, currentToolTip, accessor, config ); - } + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaBody(itemStack, currentToolTip, accessor, config); + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public List getWailaTail( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getWailaTail( itemStack, currentToolTip, accessor, config ); - } + @Override + public List getWailaTail( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + for (final IWailaDataProvider provider : this.providers) { + provider.getWailaTail(itemStack, currentToolTip, accessor, config); + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - for( final IWailaDataProvider provider : this.providers ) - { - provider.getNBTData( player, te, tag, world, x, y, z ); - } + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z + ) { + for (final IWailaDataProvider provider : this.providers) { + provider.getNBTData(player, te, tag, world, x, y, z); + } - return tag; - } + return tag; + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java index 64d057fb..f36cfddd 100644 --- a/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/BasePartWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.part; +import java.util.List; import appeng.api.parts.IPart; import mcp.mobius.waila.api.IWailaConfigHandler; @@ -28,45 +29,63 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** - * Default implementation of {@link appeng.integration.modules.waila.part.IPartWailaDataProvider} + * Default implementation of {@link + * appeng.integration.modules.waila.part.IPartWailaDataProvider} * * @author thatsIch * @version rv2 * @since rv2 */ -public abstract class BasePartWailaDataProvider implements IPartWailaDataProvider -{ - @Override - public ItemStack getWailaStack( final IPart part, final IWailaConfigHandler config, final ItemStack partStack ) - { - return null; - } +public abstract class BasePartWailaDataProvider implements IPartWailaDataProvider { + @Override + public ItemStack getWailaStack( + final IPart part, final IWailaConfigHandler config, final ItemStack partStack + ) { + return null; + } - @Override - public List getWailaHead( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaHead( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + return currentToolTip; + } - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + return currentToolTip; + } - @Override - public List getWailaTail( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - return currentToolTip; - } + @Override + public List getWailaTail( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final IPart part, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - return tag; - } + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final IPart part, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z + ) { + return tag; + } } 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 6efa14be..f8fe78bb 100644 --- a/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/ChannelWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.part; +import java.util.List; import appeng.api.parts.IPart; import appeng.core.localization.WailaText; @@ -32,9 +33,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Channel-information provider for WAILA * @@ -42,114 +40,119 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class ChannelWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Channel key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} - */ - private static final String ID_USED_CHANNELS = "usedChannels"; +public final class ChannelWailaDataProvider extends BasePartWailaDataProvider { + /** + * Channel key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} + */ + private static final String ID_USED_CHANNELS = "usedChannels"; - /** - * Used cache for channels if the channel was not transmitted through the server. - *

- * This is useful, when a player just started to look at a tile and thus just requested the new information from the - * server. - *

- * The cache will be updated from the server. - */ - private final TObjectByteMap cache = new TObjectByteHashMap(); + /** + * Used cache for channels if the channel was not transmitted through the server. + *

+ * This is useful, when a player just started to look at a tile and thus just + * requested the new information from the server.

The cache will be updated from + * the server. + */ + private final TObjectByteMap cache = new TObjectByteHashMap(); - /** - * Adds the used and max channel to the tool tip - * - * @param part being looked at part - * @param currentToolTip current tool tip - * @param accessor wrapper for various world information - * @param config config to react to various settings - * @return modified tool tip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof PartCableSmart || part instanceof PartDenseCable ) - { - final NBTTagCompound tag = accessor.getNBTData(); + /** + * Adds the used and max channel to the tool tip + * + * @param part being looked at part + * @param currentToolTip current tool tip + * @param accessor wrapper for various world information + * @param config config to react to various settings + * @return modified tool tip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + 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 usedChannels = this.getUsedChannels(part, tag, this.cache); + final byte maxChannels = (byte) ((part instanceof PartDenseCable) ? 32 : 8); - final String formattedToolTip = String.format( WailaText.Channels.getLocal(), usedChannels, maxChannels ); - currentToolTip.add( formattedToolTip ); - } + final String formattedToolTip + = String.format(WailaText.Channels.getLocal(), usedChannels, maxChannels); + currentToolTip.add(formattedToolTip); + } - return currentToolTip; - } + return currentToolTip; + } - /** - * Determines the source of the channel. - *

- * If the client received information of the channels on the server, they are used, else if the cache contains a - * previous stored value, this will be used. Default value is 0. - * - * @param part part to be looked at - * @param tag tag maybe containing the channel information - * @param cache cache with previous knowledge - * @return used channels on the cable - */ - private byte getUsedChannels( final IPart part, final NBTTagCompound tag, final TObjectByteMap cache ) - { - final byte usedChannels; + /** + * Determines the source of the channel. + *

+ * If the client received information of the channels on the server, they are used, + * else if the cache contains a previous stored value, this will be used. Default + * value is 0. + * + * @param part part to be looked at + * @param tag tag maybe containing the channel information + * @param cache cache with previous knowledge + * @return used channels on the cable + */ + private byte getUsedChannels( + final IPart part, final NBTTagCompound tag, final TObjectByteMap cache + ) { + final byte usedChannels; - if( tag.hasKey( ID_USED_CHANNELS ) ) - { - usedChannels = tag.getByte( ID_USED_CHANNELS ); - this.cache.put( part, usedChannels ); - } - else if( this.cache.containsKey( part ) ) - { - usedChannels = this.cache.get( part ); - } - else - { - usedChannels = 0; - } + if (tag.hasKey(ID_USED_CHANNELS)) { + usedChannels = tag.getByte(ID_USED_CHANNELS); + this.cache.put(part, usedChannels); + } else if (this.cache.containsKey(part)) { + usedChannels = this.cache.get(part); + } else { + usedChannels = 0; + } - return usedChannels; - } + return usedChannels; + } - /** - * Called on server to transfer information from server to client. - *

- * If the part is a cable, it writes the channel information in the {@code #tag} using the {@code ID_USED_CHANNELS} - * key. - * - * @param player player looking at the part - * @param part part being looked at - * @param te host of the part - * @param tag transferred tag which is send to the client - * @param world world of the part - * @param x x pos of the part - * @param y y pos of the part - * @param z z pos of the part - * @return tag send to the client - */ - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final IPart part, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - if( part instanceof PartCableSmart || part instanceof PartDenseCable ) - { - final NBTTagCompound tempTag = new NBTTagCompound(); + /** + * Called on server to transfer information from server to client. + *

+ * If the part is a cable, it writes the channel information in the {@code #tag} using + * the {@code ID_USED_CHANNELS} key. + * + * @param player player looking at the part + * @param part part being looked at + * @param te host of the part + * @param tag transferred tag which is send to the client + * @param world world of the part + * @param x x pos of the part + * @param y y pos of the part + * @param z z pos of the part + * @return tag send to the client + */ + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final IPart part, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z + ) { + if (part instanceof PartCableSmart || part instanceof PartDenseCable) { + final NBTTagCompound tempTag = new NBTTagCompound(); - part.writeToNBT( tempTag ); + part.writeToNBT(tempTag); - if( tempTag.hasKey( ID_USED_CHANNELS ) ) - { - final byte usedChannels = tempTag.getByte( ID_USED_CHANNELS ); + if (tempTag.hasKey(ID_USED_CHANNELS)) { + final byte usedChannels = tempTag.getByte(ID_USED_CHANNELS); - tag.setByte( ID_USED_CHANNELS, usedChannels ); - } - } + tag.setByte(ID_USED_CHANNELS, usedChannels); + } + } - return tag; - } + return tag; + } } 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 57816d49..53ea65bc 100644 --- a/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/IPartWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.part; +import java.util.List; import appeng.api.parts.IPart; import mcp.mobius.waila.api.IWailaConfigHandler; @@ -28,26 +29,47 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** - * An abstraction layer of the {@link appeng.integration.modules.waila.part.IPartWailaDataProvider} for + * An abstraction layer of the {@link + * appeng.integration.modules.waila.part.IPartWailaDataProvider} for * {@link appeng.api.parts.IPart}. * * @author thatsIch * @version rv2 * @since rv2 */ -public interface IPartWailaDataProvider -{ - ItemStack getWailaStack( IPart part, IWailaConfigHandler config, ItemStack partStack ); +public interface IPartWailaDataProvider { + ItemStack getWailaStack(IPart part, IWailaConfigHandler config, ItemStack partStack); - List getWailaHead( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaHead( + IPart part, + List currentToolTip, + IWailaDataAccessor accessor, + IWailaConfigHandler config + ); - List getWailaBody( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + List getWailaBody( + IPart part, + List currentToolTip, + IWailaDataAccessor accessor, + IWailaConfigHandler config + ); - List getWailaTail( IPart part, List currentToolTip, IWailaDataAccessor accessor, IWailaConfigHandler config ); + 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/P2PStateWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java index 10a6184d..bacb2830 100644 --- a/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/P2PStateWailaDataProvider.java @@ -18,162 +18,144 @@ package appeng.integration.modules.waila.part; - import java.text.NumberFormat; import java.util.List; import java.util.Locale; +import appeng.api.parts.IPart; import appeng.core.localization.ButtonToolTips; +import appeng.core.localization.WailaText; +import appeng.me.GridAccessException; +import appeng.parts.p2p.PartP2PTunnel; +import appeng.util.Platform; import com.google.common.collect.Iterators; - +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; - -import appeng.api.parts.IPart; -import appeng.core.localization.WailaText; -import appeng.me.GridAccessException; -import appeng.parts.p2p.PartP2PTunnel; -import appeng.util.Platform; - - /** * Provides information about a P2P tunnel to WAILA. */ -public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider -{ +public final class P2PStateWailaDataProvider extends BasePartWailaDataProvider { + private static final int STATE_UNLINKED = 0; + private static final int STATE_OUTPUT = 1; + private static final int STATE_INPUT = 2; + public static final String TAG_P2P_STATE = "p2p_state"; + public static final String TAG_P2P_FREQUENCY = "p2p_frequency"; - private static final int STATE_UNLINKED = 0; - private static final int STATE_OUTPUT = 1; - private static final int STATE_INPUT = 2; - public static final String TAG_P2P_STATE = "p2p_state"; - public static final String TAG_P2P_FREQUENCY = "p2p_frequency"; + /** + * Adds state to the tooltip + * + * @param part part with state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * + * @return modified tooltip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + if (part instanceof PartP2PTunnel) { + NBTTagCompound nbtData = accessor.getNBTData(); + if (nbtData.hasKey(TAG_P2P_STATE)) { + int[] stateArr = nbtData.getIntArray(TAG_P2P_STATE); + if (stateArr.length == 2) { + int state = stateArr[0]; + int outputs = stateArr[1]; - /** - * Adds state to the tooltip - * - * @param part part with state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof PartP2PTunnel ) - { - NBTTagCompound nbtData = accessor.getNBTData(); - if( nbtData.hasKey( TAG_P2P_STATE ) ) - { - int[] stateArr = nbtData.getIntArray( TAG_P2P_STATE ); - if( stateArr.length == 2 ) - { - int state = stateArr[0]; - int outputs = stateArr[1]; + switch (state) { + case STATE_UNLINKED: + currentToolTip.add(WailaText.P2PUnlinked.getLocal()); + break; + case STATE_OUTPUT: + currentToolTip.add(WailaText.P2POutput.getLocal()); + break; + case STATE_INPUT: + currentToolTip.add(getOutputText(outputs)); + break; + } + } - switch( state ) - { - case STATE_UNLINKED: - currentToolTip.add( WailaText.P2PUnlinked.getLocal() ); - break; - case STATE_OUTPUT: - currentToolTip.add( WailaText.P2POutput.getLocal() ); - break; - case STATE_INPUT: - currentToolTip.add( getOutputText( outputs ) ); - break; - } - } - - final long freq = nbtData.getLong( TAG_P2P_FREQUENCY ); - final String freqTooltip = String.format("%X", freq ).replaceAll("(.{4})", "$0 ").trim(); + final long freq = nbtData.getLong(TAG_P2P_FREQUENCY); + final String freqTooltip + = String.format("%X", freq).replaceAll("(.{4})", "$0 ").trim(); final String local = ButtonToolTips.P2PFrequency.getLocal(); - currentToolTip.add( String.format( local, freqTooltip ) ); - } - } + currentToolTip.add(String.format(local, freqTooltip)); + } + } - return currentToolTip; - } + return currentToolTip; + } - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final IPart part, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - if( part instanceof PartP2PTunnel ) - { - final PartP2PTunnel tunnel = (PartP2PTunnel) part; + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final IPart part, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z + ) { + if (part instanceof PartP2PTunnel) { + final PartP2PTunnel tunnel = (PartP2PTunnel) part; - if( !tunnel.isPowered() ) - { - return tag; - } + if (!tunnel.isPowered()) { + return tag; + } - // Frquency - final long frequency = tunnel.getFrequency(); - tag.setLong( TAG_P2P_FREQUENCY, frequency ); + // Frquency + final long frequency = tunnel.getFrequency(); + tag.setLong(TAG_P2P_FREQUENCY, frequency); - // The default state - int state = STATE_UNLINKED; - int outputCount = 0; + // The default state + int state = STATE_UNLINKED; + int outputCount = 0; - if( !tunnel.isOutput() ) - { - outputCount = getOutputCount( tunnel ); - if( outputCount > 0 ) - { - // Only set it to INPUT if we know there are any outputs - state = STATE_INPUT; - } - } - else - { - PartP2PTunnel input = tunnel.getInput(); - if( input != null ) - { - state = STATE_OUTPUT; - } - } + if (!tunnel.isOutput()) { + outputCount = getOutputCount(tunnel); + if (outputCount > 0) { + // Only set it to INPUT if we know there are any outputs + state = STATE_INPUT; + } + } else { + PartP2PTunnel input = tunnel.getInput(); + if (input != null) { + state = STATE_OUTPUT; + } + } - tag.setIntArray( TAG_P2P_STATE, new int[] { - state, - outputCount - } ); + tag.setIntArray(TAG_P2P_STATE, new int[] { state, outputCount }); + } - } + return tag; + } - return tag; - } - - private static int getOutputCount( PartP2PTunnel tunnel ) - { - try - { - return Iterators.size( tunnel.getOutputs().iterator() ); - } - catch( GridAccessException e ) - { - // Well... unknown size it is! - return 0; - } - } - - private static String getOutputText( int outputs ) - { - if( outputs <= 1 ) - { - return WailaText.P2PInputOneOutput.getLocal(); - } - else - { - return String.format( WailaText.P2PInputManyOutputs.getLocal(), outputs ); - } - } + private static int getOutputCount(PartP2PTunnel tunnel) { + try { + return Iterators.size(tunnel.getOutputs().iterator()); + } catch (GridAccessException e) { + // Well... unknown size it is! + return 0; + } + } + private static String getOutputText(int outputs) { + if (outputs <= 1) { + return WailaText.P2PInputOneOutput.getLocal(); + } else { + return String.format(WailaText.P2PInputManyOutputs.getLocal(), outputs); + } + } } 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 9344aeff..28a21abd 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java +++ b/src/main/java/appeng/integration/modules/waila/part/PartAccessor.java @@ -18,7 +18,6 @@ package appeng.integration.modules.waila.part; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.SelectedPart; @@ -27,7 +26,6 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; - /** * Accessor to access specific parts for WAILA * @@ -35,32 +33,30 @@ import net.minecraft.util.Vec3; * @version rv2 * @since rv2 */ -public final class PartAccessor -{ - /** - * Hits a {@link appeng.api.parts.IPartHost} with {@link net.minecraft.util.MovingObjectPosition}. - *

- * You can derive the looked at {@link appeng.api.parts.IPart} by doing that. If a facade is being looked at, it is - * defined as being absent. - * - * @param te being looked at {@link net.minecraft.tileentity.TileEntity} - * @param mop type of ray-trace - * @return maybe the looked at {@link appeng.api.parts.IPart} - */ - public Optional getMaybePart( final TileEntity te, final MovingObjectPosition mop ) - { - if( te instanceof IPartHost ) - { - final Vec3 position = mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ); - final IPartHost host = (IPartHost) te; - final SelectedPart sp = host.selectPart( position ); +public final class PartAccessor { + /** + * Hits a {@link appeng.api.parts.IPartHost} with {@link + * net.minecraft.util.MovingObjectPosition}.

You can derive the looked at {@link + * appeng.api.parts.IPart} by doing that. If a facade is being looked at, it is + * defined as being absent. + * + * @param te being looked at {@link net.minecraft.tileentity.TileEntity} + * @param mop type of ray-trace + * @return maybe the looked at {@link appeng.api.parts.IPart} + */ + public Optional + getMaybePart(final TileEntity te, final MovingObjectPosition mop) { + if (te instanceof IPartHost) { + final Vec3 position + = mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ); + final IPartHost host = (IPartHost) te; + final SelectedPart sp = host.selectPart(position); - if( sp.part != null ) - { - return Optional.of( sp.part ); - } - } + if (sp.part != null) { + return Optional.of(sp.part); + } + } - return Optional.absent(); - } + return Optional.absent(); + } } diff --git a/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java b/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java index 45f106e1..5a9acbb6 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/PartStackWailaDataProvider.java @@ -18,13 +18,11 @@ package appeng.integration.modules.waila.part; - import appeng.api.parts.IPart; import appeng.api.parts.PartItemStack; import mcp.mobius.waila.api.IWailaConfigHandler; import net.minecraft.item.ItemStack; - /** * Part ItemStack provider for WAILA * @@ -32,14 +30,12 @@ import net.minecraft.item.ItemStack; * @version rv2 * @since rv2 */ -public class PartStackWailaDataProvider extends BasePartWailaDataProvider -{ - - @Override - public ItemStack getWailaStack( final IPart part, final IWailaConfigHandler config, ItemStack partStack ) - { - partStack = part.getItemStack( PartItemStack.Pick ); - return partStack; - } - +public class PartStackWailaDataProvider extends BasePartWailaDataProvider { + @Override + public ItemStack getWailaStack( + final IPart part, final IWailaConfigHandler config, ItemStack partStack + ) { + partStack = part.getItemStack(PartItemStack.Pick); + return partStack; + } } 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 2a471117..bca6bb4c 100644 --- a/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/PowerStateWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.part; +import java.util.List; import appeng.api.implementations.IPowerChannelState; import appeng.api.parts.IPart; @@ -25,9 +26,6 @@ import appeng.core.localization.WailaText; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; -import java.util.List; - - /** * Power state provider for WAILA * @@ -35,54 +33,51 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Adds state to the tooltip - * - * @param part part with state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) part; +public final class PowerStateWailaDataProvider extends BasePartWailaDataProvider { + /** + * Adds state to the tooltip + * + * @param part part with state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * @return modified tooltip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + if (part instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) part; - currentToolTip.add( this.getToolTip( state.isActive(), state.isPowered() ) ); - } + currentToolTip.add(this.getToolTip(state.isActive(), state.isPowered())); + } - return currentToolTip; - } + return currentToolTip; + } - /** - * Gets the corresponding tool tip for different values of {@code #isActive} and {@code #isPowered} - * - * @param isActive if part is active - * @param isPowered if part is powered - * @return tooltip of the state - */ - private String getToolTip( final boolean isActive, final boolean isPowered ) - { - final String result; + /** + * Gets the corresponding tool tip for different values of {@code #isActive} and + * {@code #isPowered} + * + * @param isActive if part is active + * @param isPowered if part is powered + * @return tooltip of the state + */ + private String getToolTip(final boolean isActive, final boolean isPowered) { + final String result; - if( isActive && isPowered ) - { - result = WailaText.DeviceOnline.getLocal(); - } - else if( isPowered ) - { - result = WailaText.DeviceMissingChannel.getLocal(); - } - else - { - result = WailaText.DeviceOffline.getLocal(); - } + if (isActive && isPowered) { + result = WailaText.DeviceOnline.getLocal(); + } else if (isPowered) { + result = WailaText.DeviceMissingChannel.getLocal(); + } else { + result = WailaText.DeviceOffline.getLocal(); + } - return result; - } + return result; + } } 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 937d30ec..b40161d8 100644 --- a/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/part/StorageMonitorWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.part; +import java.util.List; import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.parts.IPart; @@ -28,9 +29,6 @@ import appeng.core.localization.WailaText; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; -import java.util.List; - - /** * Storage monitor provider for WAILA * @@ -38,42 +36,49 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class StorageMonitorWailaDataProvider extends BasePartWailaDataProvider -{ - /** - * Displays the stack if present and if the monitor is locked. - * Can handle fluids and items. - * - * @param part maybe storage monitor - * @param currentToolTip to be written to tooltip - * @param accessor information wrapper - * @param config config option - * @return modified tooltip - */ - @Override - public List getWailaBody( final IPart part, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - if( part instanceof IPartStorageMonitor ) - { - final IPartStorageMonitor monitor = (IPartStorageMonitor) part; +public final class StorageMonitorWailaDataProvider extends BasePartWailaDataProvider { + /** + * Displays the stack if present and if the monitor is locked. + * Can handle fluids and items. + * + * @param part maybe storage monitor + * @param currentToolTip to be written to tooltip + * @param accessor information wrapper + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody( + final IPart part, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + if (part instanceof IPartStorageMonitor) { + final IPartStorageMonitor monitor = (IPartStorageMonitor) part; - final IAEStack displayed = monitor.getDisplayed(); - final boolean isLocked = monitor.isLocked(); + final IAEStack displayed = monitor.getDisplayed(); + final boolean isLocked = monitor.isLocked(); - if( displayed instanceof IAEItemStack ) - { - final IAEItemStack ais = (IAEItemStack) displayed; - currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.getItemStack().getDisplayName() ); - } - else if( displayed instanceof IAEFluidStack ) - { - final IAEFluidStack ais = (IAEFluidStack) displayed; - currentToolTip.add( WailaText.Showing.getLocal() + ": " + ais.getFluid().getLocalizedName( ais.getFluidStack() ) ); - } + if (displayed instanceof IAEItemStack) { + final IAEItemStack ais = (IAEItemStack) displayed; + currentToolTip.add( + WailaText.Showing.getLocal() + ": " + + ais.getItemStack().getDisplayName() + ); + } else if (displayed instanceof IAEFluidStack) { + final IAEFluidStack ais = (IAEFluidStack) displayed; + currentToolTip.add( + WailaText.Showing.getLocal() + ": " + + ais.getFluid().getLocalizedName(ais.getFluidStack()) + ); + } - currentToolTip.add( ( isLocked ) ? WailaText.Locked.getLocal() : WailaText.Unlocked.getLocal() ); - } + currentToolTip.add( + (isLocked) ? WailaText.Locked.getLocal() : WailaText.Unlocked.getLocal() + ); + } - return currentToolTip; - } + return currentToolTip; + } } 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 e326a1b5..ca4c13e4 100644 --- a/src/main/java/appeng/integration/modules/waila/part/Tracer.java +++ b/src/main/java/appeng/integration/modules/waila/part/Tracer.java @@ -18,7 +18,6 @@ package appeng.integration.modules.waila.part; - import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; @@ -26,7 +25,6 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; - /** * Tracer for players hitting blocks * @@ -34,62 +32,62 @@ import net.minecraft.world.World; * @version rv2 * @since rv2 */ -public final class Tracer -{ - /** - * Trace view of players to blocks. - * Ignore all which are out of reach. - * - * @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 - * @return trace movement. Can be null - */ - public MovingObjectPosition retraceBlock( final World world, final EntityPlayerMP player, final int x, final int y, final int z ) - { - final Block block = world.getBlock( x, y, z ); +public final class Tracer { + /** + * Trace view of players to blocks. + * Ignore all which are out of reach. + * + * @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 + * @return trace movement. Can be null + */ + public MovingObjectPosition retraceBlock( + final World world, + final EntityPlayerMP player, + final int x, + final int y, + final int z + ) { + final Block block = world.getBlock(x, y, z); - final Vec3 headVec = this.getCorrectedHeadVec( player ); - final Vec3 lookVec = player.getLook( 1.0F ); - final double reach = this.getBlockReachDistance_server( player ); - final Vec3 endVec = headVec.addVector( lookVec.xCoord * reach, lookVec.yCoord * reach, lookVec.zCoord * reach ); + final Vec3 headVec = this.getCorrectedHeadVec(player); + final Vec3 lookVec = player.getLook(1.0F); + final double reach = this.getBlockReachDistance_server(player); + final Vec3 endVec = headVec.addVector( + lookVec.xCoord * reach, lookVec.yCoord * reach, lookVec.zCoord * reach + ); - return block.collisionRayTrace( world, x, y, z, headVec, endVec ); - } + return block.collisionRayTrace(world, x, y, z, headVec, endVec); + } - /** - * Gets the view point of a player - * - * @param player player with head - * @return view point of player - */ - private Vec3 getCorrectedHeadVec( final EntityPlayer player ) - { - final Vec3 v = Vec3.createVectorHelper( player.posX, player.posY, player.posZ ); - if( player.worldObj.isRemote ) - { - // compatibility with eye height changing mods - v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight(); - } - else - { - v.yCoord += player.getEyeHeight(); - if( player instanceof EntityPlayerMP && player.isSneaking() ) - { - v.yCoord -= 0.08; - } - } - return v; - } + /** + * Gets the view point of a player + * + * @param player player with head + * @return view point of player + */ + private Vec3 getCorrectedHeadVec(final EntityPlayer player) { + final Vec3 v = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); + if (player.worldObj.isRemote) { + // compatibility with eye height changing mods + v.yCoord += player.getEyeHeight() - player.getDefaultEyeHeight(); + } else { + v.yCoord += player.getEyeHeight(); + if (player instanceof EntityPlayerMP && player.isSneaking()) { + v.yCoord -= 0.08; + } + } + return v; + } - /** - * @param player multi-player player - * @return block reach distance of player - */ - private double getBlockReachDistance_server( final EntityPlayerMP player ) - { - return player.theItemInWorldManager.getBlockReachDistance(); - } + /** + * @param player multi-player player + * @return block reach distance of player + */ + private double getBlockReachDistance_server(final EntityPlayerMP player) { + return player.theItemInWorldManager.getBlockReachDistance(); + } } 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 03fd06fa..9f4181ab 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/ChargerWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.tile; +import java.util.List; import appeng.core.localization.WailaText; import appeng.integration.modules.waila.BaseWailaDataProvider; @@ -29,9 +30,6 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; - - /** * Charger provider for WAILA * @@ -39,37 +37,40 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class ChargerWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Displays the holding item and its tooltip - * - * @param itemStack stack of charger - * @param currentToolTip unmodified tooltip - * @param accessor wrapper information - * @param config config option - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - if( te instanceof TileCharger ) - { - final TileCharger charger = (TileCharger) te; - final IInventory chargerInventory = charger.getInternalInventory(); - final ItemStack chargingItem = chargerInventory.getStackInSlot( 0 ); +public final class ChargerWailaDataProvider extends BaseWailaDataProvider { + /** + * Displays the holding item and its tooltip + * + * @param itemStack stack of charger + * @param currentToolTip unmodified tooltip + * @param accessor wrapper information + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + final TileEntity te = accessor.getTileEntity(); + if (te instanceof TileCharger) { + final TileCharger charger = (TileCharger) te; + final IInventory chargerInventory = charger.getInternalInventory(); + final ItemStack chargingItem = chargerInventory.getStackInSlot(0); - if( chargingItem != null ) - { - final String currentInventory = chargingItem.getDisplayName(); - final EntityPlayer player = accessor.getPlayer(); + if (chargingItem != null) { + final String currentInventory = chargingItem.getDisplayName(); + final EntityPlayer player = accessor.getPlayer(); - currentToolTip.add( WailaText.Contains + ": " + currentInventory ); - chargingItem.getItem().addInformation( chargingItem, player, currentToolTip, true ); - } - } + currentToolTip.add(WailaText.Contains + ": " + currentInventory); + chargingItem.getItem().addInformation( + chargingItem, player, currentToolTip, true + ); + } + } - return currentToolTip; - } + return currentToolTip; + } } 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 c30c5c4a..271a3c5c 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/CraftingMonitorWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.tile; +import java.util.List; import appeng.api.storage.data.IAEItemStack; import appeng.core.localization.WailaText; @@ -28,9 +29,6 @@ import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; - - /** * Crafting-monitor provider for WAILA * @@ -38,34 +36,38 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class CraftingMonitorWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Displays the item currently crafted by the CPU cluster - * - * @param itemStack stack of crafting monitor - * @param currentToolTip unmodified tooltip - * @param accessor information wrapper - * @param config config option - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); - if( te instanceof TileCraftingMonitorTile ) - { - final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) te; - final IAEItemStack displayStack = monitor.getJobProgress(); +public final class CraftingMonitorWailaDataProvider extends BaseWailaDataProvider { + /** + * Displays the item currently crafted by the CPU cluster + * + * @param itemStack stack of crafting monitor + * @param currentToolTip unmodified tooltip + * @param accessor information wrapper + * @param config config option + * @return modified tooltip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + final TileEntity te = accessor.getTileEntity(); + if (te instanceof TileCraftingMonitorTile) { + final TileCraftingMonitorTile monitor = (TileCraftingMonitorTile) te; + final IAEItemStack displayStack = monitor.getJobProgress(); - if( displayStack != null ) - { - final String currentCrafting = displayStack.getItemStack().getDisplayName(); + if (displayStack != null) { + final String currentCrafting + = displayStack.getItemStack().getDisplayName(); - currentToolTip.add( WailaText.Crafting.getLocal() + ": " + currentCrafting ); - } - } + currentToolTip.add( + WailaText.Crafting.getLocal() + ": " + currentCrafting + ); + } + } - return currentToolTip; - } + return currentToolTip; + } } 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 7346deb8..c09f4397 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStateWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.tile; +import java.util.List; import appeng.api.implementations.IPowerChannelState; import appeng.core.localization.WailaText; @@ -27,9 +28,6 @@ import mcp.mobius.waila.api.IWailaDataAccessor; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; -import java.util.List; - - /** * Power state provider for WAILA * @@ -37,43 +35,40 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class PowerStateWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Adds state to the tooltip - * - * @param itemStack stack of power state - * @param currentToolTip to be added to tooltip - * @param accessor wrapper for various information - * @param config config settings - * @return modified tooltip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - final TileEntity te = accessor.getTileEntity(); +public final class PowerStateWailaDataProvider extends BaseWailaDataProvider { + /** + * Adds state to the tooltip + * + * @param itemStack stack of power state + * @param currentToolTip to be added to tooltip + * @param accessor wrapper for various information + * @param config config settings + * @return modified tooltip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + final TileEntity te = accessor.getTileEntity(); - if( te instanceof IPowerChannelState ) - { - final IPowerChannelState state = (IPowerChannelState) te; + if (te instanceof IPowerChannelState) { + final IPowerChannelState state = (IPowerChannelState) te; - final boolean isActive = state.isActive(); - final boolean isPowered = state.isPowered(); + final boolean isActive = state.isActive(); + final boolean isPowered = state.isPowered(); - if( isActive && isPowered ) - { - currentToolTip.add( WailaText.DeviceOnline.getLocal() ); - } - else if( isPowered ) - { - currentToolTip.add( WailaText.DeviceMissingChannel.getLocal() ); - } - else - { - currentToolTip.add( WailaText.DeviceOffline.getLocal() ); - } - } + if (isActive && isPowered) { + currentToolTip.add(WailaText.DeviceOnline.getLocal()); + } else if (isPowered) { + currentToolTip.add(WailaText.DeviceMissingChannel.getLocal()); + } else { + currentToolTip.add(WailaText.DeviceOffline.getLocal()); + } + } - return currentToolTip; - } + return currentToolTip; + } } \ No newline at end of file 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 7c7864b0..87ebb196 100644 --- a/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java +++ b/src/main/java/appeng/integration/modules/waila/tile/PowerStorageWailaDataProvider.java @@ -18,6 +18,7 @@ package appeng.integration.modules.waila.tile; +import java.util.List; import appeng.api.networking.energy.IAEPowerStorage; import appeng.core.localization.WailaText; @@ -34,9 +35,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; - - /** * Power storage provider for WAILA * @@ -44,123 +42,129 @@ import java.util.List; * @version rv2 * @since rv2 */ -public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider -{ - /** - * Power key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} - */ - private static final String ID_CURRENT_POWER = "currentPower"; +public final class PowerStorageWailaDataProvider extends BaseWailaDataProvider { + /** + * Power key used for the transferred {@link net.minecraft.nbt.NBTTagCompound} + */ + private static final String ID_CURRENT_POWER = "currentPower"; - /** - * Used cache for power if the power was not transmitted through the server. - *

- * This is useful, when a player just started to look at a tile and thus just requested the new information from the - * server. - *

- * The cache will be updated from the server. - */ - private final TObjectLongMap cache = new TObjectLongHashMap(); + /** + * Used cache for power if the power was not transmitted through the server. + *

+ * This is useful, when a player just started to look at a tile and thus just + * requested the new information from the server.

The cache will be updated from + * the server. + */ + private final TObjectLongMap cache = new TObjectLongHashMap(); - /** - * Adds the current and max power to the tool tip - * Will ignore if the tile has an energy buffer ( > 0 ) - * - * @param itemStack stack of power storage - * @param currentToolTip current tool tip - * @param accessor wrapper for various world information - * @param config config to react to various settings - * @return modified tool tip - */ - @Override - public List getWailaBody( final ItemStack itemStack, final List currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) - { - // Removes RF tooltip on WAILA 1.5.9+ - ( (ITaggedList) currentToolTip ).removeEntries( "RFEnergyStorage" ); + /** + * Adds the current and max power to the tool tip + * Will ignore if the tile has an energy buffer ( > 0 ) + * + * @param itemStack stack of power storage + * @param currentToolTip current tool tip + * @param accessor wrapper for various world information + * @param config config to react to various settings + * @return modified tool tip + */ + @Override + public List getWailaBody( + final ItemStack itemStack, + final List currentToolTip, + final IWailaDataAccessor accessor, + final IWailaConfigHandler config + ) { + // Removes RF tooltip on WAILA 1.5.9+ + ((ITaggedList) currentToolTip).removeEntries("RFEnergyStorage"); - final TileEntity te = accessor.getTileEntity(); - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage storage = (IAEPowerStorage) te; + final TileEntity te = accessor.getTileEntity(); + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage storage = (IAEPowerStorage) te; - final double maxPower = storage.getAEMaxPower(); - if( maxPower > 0 ) - { - final NBTTagCompound tag = accessor.getNBTData(); + final double maxPower = storage.getAEMaxPower(); + if (maxPower > 0) { + final NBTTagCompound tag = accessor.getNBTData(); - final long internalCurrentPower = this.getInternalCurrentPower( tag, te ); - final long internalMaxPower = (long) ( 100 * maxPower ); + final long internalCurrentPower = this.getInternalCurrentPower(tag, te); + final long internalMaxPower = (long) (100 * maxPower); - final String formatCurrentPower = Platform.formatPowerLong( internalCurrentPower, false ); - final String formatMaxPower = Platform.formatPowerLong( internalMaxPower, false ); + final String formatCurrentPower + = Platform.formatPowerLong(internalCurrentPower, false); + final String formatMaxPower + = Platform.formatPowerLong(internalMaxPower, false); - currentToolTip.add( WailaText.Contains.getLocal() + ": " + formatCurrentPower + " / " + formatMaxPower ); - } - } + currentToolTip.add( + WailaText.Contains.getLocal() + ": " + formatCurrentPower + " / " + + formatMaxPower + ); + } + } - return currentToolTip; - } + return currentToolTip; + } - /** - * Called on server to transfer information from server to client. - *

- * If the {@link net.minecraft.tileentity.TileEntity} is a {@link appeng.api.networking.energy.IAEPowerStorage}, it - * writes the power information to the {@code #tag} using the {@code #ID_CURRENT_POWER} key. - * - * @param player player looking at the power storage - * @param te power storage - * @param tag transferred tag which is send to the client - * @param world world of the power storage - * @param x x pos of the power storage - * @param y y pos of the power storage - * @param z z pos of the power storage - * @return tag send to the client - */ - @Override - public NBTTagCompound getNBTData( final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag, final World world, final int x, final int y, final int z ) - { - if( te instanceof IAEPowerStorage ) - { - final IAEPowerStorage storage = (IAEPowerStorage) te; + /** + * Called on server to transfer information from server to client. + *

+ * If the {@link net.minecraft.tileentity.TileEntity} is a {@link + * appeng.api.networking.energy.IAEPowerStorage}, it writes the power information to + * the {@code #tag} using the {@code #ID_CURRENT_POWER} key. + * + * @param player player looking at the power storage + * @param te power storage + * @param tag transferred tag which is send to the client + * @param world world of the power storage + * @param x x pos of the power storage + * @param y y pos of the power storage + * @param z z pos of the power storage + * @return tag send to the client + */ + @Override + public NBTTagCompound getNBTData( + final EntityPlayerMP player, + final TileEntity te, + final NBTTagCompound tag, + final World world, + final int x, + final int y, + final int z + ) { + if (te instanceof IAEPowerStorage) { + final IAEPowerStorage storage = (IAEPowerStorage) te; - if( storage.getAEMaxPower() > 0 ) - { - final long internalCurrentPower = (long) ( 100 * storage.getAECurrentPower() ); + if (storage.getAEMaxPower() > 0) { + final long internalCurrentPower + = (long) (100 * storage.getAECurrentPower()); - tag.setLong( ID_CURRENT_POWER, internalCurrentPower ); - } - } + tag.setLong(ID_CURRENT_POWER, internalCurrentPower); + } + } - return tag; - } + return tag; + } - /** - * Determines the current power. - *

- * If the client received power information on the server, they are used, else if the cache contains a previous - * stored value, this will be used. Default value is 0. - * - * @param te te to be looked at - * @param tag tag maybe containing the channel information - * @return used channels on the cable - */ - private long getInternalCurrentPower( final NBTTagCompound tag, final TileEntity te ) - { - final long internalCurrentPower; + /** + * Determines the current power. + *

+ * If the client received power information on the server, they are used, else if the + * cache contains a previous stored value, this will be used. Default value is 0. + * + * @param te te to be looked at + * @param tag tag maybe containing the channel information + * @return used channels on the cable + */ + private long getInternalCurrentPower(final NBTTagCompound tag, final TileEntity te) { + final long internalCurrentPower; - if( tag.hasKey( ID_CURRENT_POWER ) ) - { - internalCurrentPower = tag.getLong( ID_CURRENT_POWER ); - this.cache.put( te, internalCurrentPower ); - } - else if( this.cache.containsKey( te ) ) - { - internalCurrentPower = this.cache.get( te ); - } - else - { - internalCurrentPower = 0; - } + if (tag.hasKey(ID_CURRENT_POWER)) { + internalCurrentPower = tag.getLong(ID_CURRENT_POWER); + this.cache.put(te, internalCurrentPower); + } else if (this.cache.containsKey(te)) { + internalCurrentPower = this.cache.get(te); + } else { + internalCurrentPower = 0; + } - return internalCurrentPower; - } + return internalCurrentPower; + } } diff --git a/src/main/java/appeng/items/AEBaseItem.java b/src/main/java/appeng/items/AEBaseItem.java index 969ee353..ec11a619 100644 --- a/src/main/java/appeng/items/AEBaseItem.java +++ b/src/main/java/appeng/items/AEBaseItem.java @@ -18,6 +18,8 @@ package appeng.items; +import java.util.EnumSet; +import java.util.List; import appeng.core.features.*; import com.google.common.base.Optional; @@ -26,78 +28,79 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.util.EnumSet; -import java.util.List; +public abstract class AEBaseItem extends Item implements IAEFeature { + private final String fullName; + private final Optional subName; + private IFeatureHandler feature; + public AEBaseItem() { + this(Optional.absent()); + this.setNoRepair(); + } -public abstract class AEBaseItem extends Item implements IAEFeature -{ - private final String fullName; - private final Optional subName; - private IFeatureHandler feature; + public AEBaseItem(final Optional subName) { + this.subName = subName; + this.fullName = new FeatureNameExtractor(this.getClass(), subName).get(); + } - public AEBaseItem() - { - this( Optional.absent() ); - this.setNoRepair(); - } + @Override + public String toString() { + return this.fullName; + } - public AEBaseItem( final Optional subName ) - { - this.subName = subName; - this.fullName = new FeatureNameExtractor( this.getClass(), subName ).get(); - } + @Override + public IFeatureHandler handler() { + return this.feature; + } - @Override - public String toString() - { - return this.fullName; - } + @Override + public void postInit() { + // override! + } - @Override - public IFeatureHandler handler() - { - return this.feature; - } + public void setFeature(final EnumSet f) { + this.feature = new ItemFeatureHandler(f, this, this, this.subName); + } - @Override - public void postInit() - { - // override! - } + @Override + @SuppressWarnings("unchecked") + public final void addInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + this.addCheckedInformation(stack, player, lines, displayMoreInfo); + } - public void setFeature( final EnumSet f ) - { - this.feature = new ItemFeatureHandler( f, this, this, this.subName ); - } + @Override + @SuppressWarnings("unchecked") + public final void getSubItems( + final Item sameItem, final CreativeTabs creativeTab, final List itemStacks + ) { + this.getCheckedSubItems(sameItem, creativeTab, itemStacks); + } - @Override - @SuppressWarnings( "unchecked" ) - public final void addInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - this.addCheckedInformation( stack, player, lines, displayMoreInfo ); - } + @Override + public boolean + isBookEnchantable(final ItemStack itemstack1, final ItemStack itemstack2) { + return false; + } - @Override - @SuppressWarnings( "unchecked" ) - public final void getSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - this.getCheckedSubItems( sameItem, creativeTab, itemStacks ); - } + protected void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + super.addInformation(stack, player, lines, displayMoreInfo); + } - @Override - public boolean isBookEnchantable( final ItemStack itemstack1, final ItemStack itemstack2 ) - { - return false; - } - - protected void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addInformation( stack, player, lines, displayMoreInfo ); - } - - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - super.getSubItems( sameItem, creativeTab, itemStacks ); - } + protected void getCheckedSubItems( + final Item sameItem, + final CreativeTabs creativeTab, + final List itemStacks + ) { + super.getSubItems(sameItem, creativeTab, itemStacks); + } } diff --git a/src/main/java/appeng/items/contents/CellConfig.java b/src/main/java/appeng/items/contents/CellConfig.java index 9230d128..cb7e12af 100644 --- a/src/main/java/appeng/items/contents/CellConfig.java +++ b/src/main/java/appeng/items/contents/CellConfig.java @@ -18,28 +18,22 @@ package appeng.items.contents; - import appeng.me.storage.CellInventory; import appeng.tile.inventory.AppEngInternalInventory; import appeng.util.Platform; import net.minecraft.item.ItemStack; +public class CellConfig extends AppEngInternalInventory { + private final ItemStack is; -public class CellConfig extends AppEngInternalInventory -{ + public CellConfig(final ItemStack is) { + super(null, CellInventory.cellItemType); + this.is = is; + this.readFromNBT(Platform.openNbtData(is), "list"); + } - private final ItemStack is; - - public CellConfig( final ItemStack is ) - { - super( null, CellInventory.cellItemType ); - this.is = is; - this.readFromNBT( Platform.openNbtData( is ), "list" ); - } - - @Override - public void markDirty() - { - this.writeToNBT( Platform.openNbtData( this.is ), "list" ); - } + @Override + public void markDirty() { + this.writeToNBT(Platform.openNbtData(this.is), "list"); + } } \ No newline at end of file diff --git a/src/main/java/appeng/items/contents/CellUpgrades.java b/src/main/java/appeng/items/contents/CellUpgrades.java index 59af1688..1d265585 100644 --- a/src/main/java/appeng/items/contents/CellUpgrades.java +++ b/src/main/java/appeng/items/contents/CellUpgrades.java @@ -18,26 +18,21 @@ package appeng.items.contents; - import appeng.parts.automation.StackUpgradeInventory; import appeng.util.Platform; import net.minecraft.item.ItemStack; +public final class CellUpgrades extends StackUpgradeInventory { + private final ItemStack is; -public final class CellUpgrades extends StackUpgradeInventory -{ - private final ItemStack is; + public CellUpgrades(final ItemStack is, final int upgrades) { + super(is, null, upgrades); + this.is = is; + this.readFromNBT(Platform.openNbtData(is), "upgrades"); + } - public CellUpgrades( final ItemStack is, final int upgrades ) - { - super( is, null, upgrades ); - this.is = is; - this.readFromNBT( Platform.openNbtData( is ), "upgrades" ); - } - - @Override - public void markDirty() - { - this.writeToNBT( Platform.openNbtData( this.is ), "upgrades" ); - } + @Override + public void markDirty() { + this.writeToNBT(Platform.openNbtData(this.is), "upgrades"); + } } \ 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 d6f625c9..feb32c68 100644 --- a/src/main/java/appeng/items/contents/NetworkToolViewer.java +++ b/src/main/java/appeng/items/contents/NetworkToolViewer.java @@ -18,7 +18,6 @@ package appeng.items.contents; - import appeng.api.implementations.guiobjects.INetworkTool; import appeng.api.implementations.items.IUpgradeModule; import appeng.api.networking.IGridHost; @@ -27,113 +26,96 @@ import appeng.util.Platform; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +public class NetworkToolViewer implements INetworkTool { + private final AppEngInternalInventory inv; + private final ItemStack is; + private final IGridHost gh; -public class NetworkToolViewer implements INetworkTool -{ + public NetworkToolViewer(final ItemStack is, final IGridHost gHost) { + this.is = is; + this.gh = gHost; + this.inv = new AppEngInternalInventory(null, 9); + if (is.hasTagCompound()) // prevent crash when opening network status screen. + { + this.inv.readFromNBT(Platform.openNbtData(is), "inv"); + } + } - private final AppEngInternalInventory inv; - private final ItemStack is; - private final IGridHost gh; + @Override + public int getSizeInventory() { + return this.inv.getSizeInventory(); + } - public NetworkToolViewer( final ItemStack is, final IGridHost gHost ) - { - this.is = is; - this.gh = gHost; - this.inv = new AppEngInternalInventory( null, 9 ); - if( is.hasTagCompound() ) // prevent crash when opening network status screen. - { - this.inv.readFromNBT( Platform.openNbtData( is ), "inv" ); - } - } + @Override + public ItemStack getStackInSlot(final int i) { + return this.inv.getStackInSlot(i); + } - @Override - public int getSizeInventory() - { - return this.inv.getSizeInventory(); - } + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.inv.decrStackSize(i, j); + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.inv.getStackInSlot( i ); - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return this.inv.getStackInSlotOnClosing(i); + } - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.inv.decrStackSize( i, j ); - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.inv.setInventorySlotContents(i, itemstack); + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return this.inv.getStackInSlotOnClosing( i ); - } + @Override + public String getInventoryName() { + return this.inv.getInventoryName(); + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.inv.setInventorySlotContents( i, itemstack ); - } + @Override + public boolean hasCustomInventoryName() { + return this.inv.hasCustomInventoryName(); + } - @Override - public String getInventoryName() - { - return this.inv.getInventoryName(); - } + @Override + public int getInventoryStackLimit() { + return this.inv.getInventoryStackLimit(); + } - @Override - public boolean hasCustomInventoryName() - { - return this.inv.hasCustomInventoryName(); - } + @Override + public void markDirty() { + this.inv.markDirty(); + this.inv.writeToNBT(Platform.openNbtData(this.is), "inv"); + } - @Override - public int getInventoryStackLimit() - { - return this.inv.getInventoryStackLimit(); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return this.inv.isUseableByPlayer(entityplayer); + } - @Override - public void markDirty() - { - this.inv.markDirty(); - this.inv.writeToNBT( Platform.openNbtData( this.is ), "inv" ); - } + @Override + public void openInventory() { + this.inv.openInventory(); + } - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return this.inv.isUseableByPlayer( entityplayer ); - } + @Override + public void closeInventory() { + this.inv.closeInventory(); + } - @Override - public void openInventory() - { - this.inv.openInventory(); - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return this.inv.isItemValidForSlot(i, itemstack) + && itemstack.getItem() instanceof IUpgradeModule + && ((IUpgradeModule) itemstack.getItem()).getType(itemstack) != null; + } - @Override - public void closeInventory() - { - this.inv.closeInventory(); - } + @Override + public ItemStack getItemStack() { + return this.is; + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.inv.isItemValidForSlot( i, itemstack ) && itemstack.getItem() instanceof IUpgradeModule && ( (IUpgradeModule) itemstack.getItem() ).getType( itemstack ) != null; - } - - @Override - public ItemStack getItemStack() - { - return this.is; - } - - @Override - public IGridHost getGridHost() - { - return this.gh; - } + @Override + public IGridHost getGridHost() { + return this.gh; + } } diff --git a/src/main/java/appeng/items/contents/PortableCellViewer.java b/src/main/java/appeng/items/contents/PortableCellViewer.java index fd8cc0b1..5729d660 100644 --- a/src/main/java/appeng/items/contents/PortableCellViewer.java +++ b/src/main/java/appeng/items/contents/PortableCellViewer.java @@ -18,7 +18,6 @@ package appeng.items.contents; - import appeng.api.config.*; import appeng.api.implementations.guiobjects.IPortableCell; import appeng.api.implementations.items.IAEItemPowerStorage; @@ -35,78 +34,72 @@ import appeng.util.Platform; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public class PortableCellViewer + extends MEMonitorHandler implements IPortableCell, IInventorySlotAware { + private final ItemStack target; + private final IAEItemPowerStorage ips; + private final int inventorySlot; -public class PortableCellViewer extends MEMonitorHandler implements IPortableCell, IInventorySlotAware -{ + public PortableCellViewer(final ItemStack is, final int slot) { + super(CellInventory.getCell(is, null)); + this.ips = (IAEItemPowerStorage) is.getItem(); + this.target = is; + this.inventorySlot = slot; + } - private final ItemStack target; - private final IAEItemPowerStorage ips; - private final int inventorySlot; + @Override + public int getInventorySlot() { + return this.inventorySlot; + } - public PortableCellViewer( final ItemStack is, final int slot ) - { - super( CellInventory.getCell( is, null ) ); - this.ips = (IAEItemPowerStorage) is.getItem(); - this.target = is; - this.inventorySlot = slot; - } + @Override + public ItemStack getItemStack() { + return this.target; + } - @Override - public int getInventorySlot() - { - return this.inventorySlot; - } + @Override + public double extractAEPower( + double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier + ) { + amt = usePowerMultiplier.multiply(amt); - @Override - public ItemStack getItemStack() - { - return this.target; - } + if (mode == Actionable.SIMULATE) { + return usePowerMultiplier.divide( + Math.min(amt, this.ips.getAECurrentPower(this.target)) + ); + } - @Override - public double extractAEPower( double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - amt = usePowerMultiplier.multiply( amt ); + return usePowerMultiplier.divide(this.ips.extractAEPower(this.target, amt)); + } - if( mode == Actionable.SIMULATE ) - { - return usePowerMultiplier.divide( Math.min( amt, this.ips.getAECurrentPower( this.target ) ) ); - } + @Override + public IMEMonitor getItemInventory() { + return this; + } - return usePowerMultiplier.divide( this.ips.extractAEPower( this.target, amt ) ); - } + @Override + public IMEMonitor getFluidInventory() { + return null; + } - @Override - public IMEMonitor getItemInventory() - { - return this; - } + @Override + public IConfigManager getConfigManager() { + final ConfigManager out = new ConfigManager(new IConfigManagerHost() { + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + final NBTTagCompound data + = Platform.openNbtData(PortableCellViewer.this.target); + manager.writeToNBT(data); + } + }); - @Override - public IMEMonitor getFluidInventory() - { - return null; - } + out.registerSetting(Settings.SORT_BY, SortOrder.NAME); + out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); - @Override - public IConfigManager getConfigManager() - { - final ConfigManager out = new ConfigManager( new IConfigManagerHost() - { - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - final NBTTagCompound data = Platform.openNbtData( PortableCellViewer.this.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( this.target ).copy() ); - return out; - } + 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 a3b45288..83234f92 100644 --- a/src/main/java/appeng/items/contents/QuartzKnifeObj.java +++ b/src/main/java/appeng/items/contents/QuartzKnifeObj.java @@ -18,24 +18,18 @@ package appeng.items.contents; - import appeng.api.implementations.guiobjects.IGuiItemObject; import net.minecraft.item.ItemStack; +public class QuartzKnifeObj implements IGuiItemObject { + private final ItemStack is; -public class QuartzKnifeObj implements IGuiItemObject -{ + public QuartzKnifeObj(final ItemStack o) { + this.is = o; + } - private final ItemStack is; - - public QuartzKnifeObj( final ItemStack o ) - { - this.is = o; - } - - @Override - public ItemStack getItemStack() - { - return this.is; - } + @Override + public ItemStack getItemStack() { + return this.is; + } } diff --git a/src/main/java/appeng/items/materials/ItemMultiMaterial.java b/src/main/java/appeng/items/materials/ItemMultiMaterial.java index 9d47061c..5c5ebc85 100644 --- a/src/main/java/appeng/items/materials/ItemMultiMaterial.java +++ b/src/main/java/appeng/items/materials/ItemMultiMaterial.java @@ -18,6 +18,10 @@ package appeng.items.materials; +import java.util.*; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import appeng.api.config.Upgrades; import appeng.api.implementations.IUpgradeableHost; @@ -55,416 +59,383 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +public final class ItemMultiMaterial + extends AEBaseItem implements IStorageComponent, IUpgradeModule { + public static ItemMultiMaterial instance; + private static final int KILO_SCALAR = 1024; -public final class ItemMultiMaterial extends AEBaseItem implements IStorageComponent, IUpgradeModule -{ - public static ItemMultiMaterial instance; + private final Map dmgToMaterial + = new HashMap(); + private final NameResolver nameResolver; - private static final int KILO_SCALAR = 1024; + public ItemMultiMaterial() { + this.nameResolver = new NameResolver(this.getClass()); + this.setFeature(EnumSet.of(AEFeature.Core)); + this.setHasSubtypes(true); + instance = this; + } - private final Map dmgToMaterial = new HashMap(); - private final NameResolver nameResolver; + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); - public ItemMultiMaterial() - { - this.nameResolver = new NameResolver( this.getClass() ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - this.setHasSubtypes( true ); - instance = this; - } + final MaterialType mt = this.getTypeByStack(stack); + if (mt == null) { + return; + } - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); + if (mt == MaterialType.NamePress) { + final NBTTagCompound c = Platform.openNbtData(stack); + lines.add(c.getString("InscribeName")); + } - final MaterialType mt = this.getTypeByStack( stack ); - if( mt == null ) - { - return; - } + final Upgrades u = this.getType(stack); + if (u != null) { + final List textList = new LinkedList(); + for (final Entry j : u.getSupported().entrySet()) { + String name = null; - if( mt == MaterialType.NamePress ) - { - final NBTTagCompound c = Platform.openNbtData( stack ); - lines.add( c.getString( "InscribeName" ) ); - } + final int limit = j.getValue(); - final Upgrades u = this.getType( stack ); - if( u != null ) - { - final List textList = new LinkedList(); - for( final Entry j : u.getSupported().entrySet() ) - { - String name = null; + if (j.getKey().getItem() instanceof IItemGroup) { + final IItemGroup ig = (IItemGroup) j.getKey().getItem(); + final String str = ig.getUnlocalizedGroupName( + u.getSupported().keySet(), j.getKey() + ); + if (str != null) { + name = Platform.gui_localize(str) + + (limit > 1 ? " (" + limit + ')' : ""); + } + } - final int limit = j.getValue(); + if (name == null) { + name = j.getKey().getDisplayName() + + (limit > 1 ? " (" + limit + ')' : ""); + } - if( j.getKey().getItem() instanceof IItemGroup ) - { - final IItemGroup ig = (IItemGroup) j.getKey().getItem(); - final String str = ig.getUnlocalizedGroupName( u.getSupported().keySet(), j.getKey() ); - if( str != null ) - { - name = Platform.gui_localize( str ) + ( limit > 1 ? " (" + limit + ')' : "" ); - } - } + if (!textList.contains(name)) { + textList.add(name); + } + } - if( name == null ) - { - name = j.getKey().getDisplayName() + ( limit > 1 ? " (" + limit + ')' : "" ); - } + final Pattern p = Pattern.compile("(\\d+)[^\\d]"); + final SlightlyBetterSort s = new SlightlyBetterSort(p); + Collections.sort(textList, s); + lines.addAll(textList); + } + } - if( !textList.contains( name ) ) - { - textList.add( name ); - } - } + public MaterialType getTypeByStack(final ItemStack is) { + if (this.dmgToMaterial.containsKey(is.getItemDamage())) { + return this.dmgToMaterial.get(is.getItemDamage()); + } + return MaterialType.InvalidType; + } - final Pattern p = Pattern.compile( "(\\d+)[^\\d]" ); - final SlightlyBetterSort s = new SlightlyBetterSort( p ); - Collections.sort( textList, s ); - lines.addAll( textList ); - } - } + @Override + public Upgrades getType(final ItemStack itemstack) { + switch (this.getTypeByStack(itemstack)) { + case CardCapacity: + return Upgrades.CAPACITY; + case CardFuzzy: + return Upgrades.FUZZY; + case CardRedstone: + return Upgrades.REDSTONE; + case CardSpeed: + return Upgrades.SPEED; + case CardInverter: + return Upgrades.INVERTER; + case CardCrafting: + return Upgrades.CRAFTING; + default: + return null; + } + } - public MaterialType getTypeByStack( final ItemStack is ) - { - if( this.dmgToMaterial.containsKey( is.getItemDamage() ) ) - { - return this.dmgToMaterial.get( is.getItemDamage() ); - } - return MaterialType.InvalidType; - } + public IStackSrc createMaterial(final MaterialType mat) { + Preconditions.checkState( + !mat.isRegistered(), "Cannot create the same material twice." + ); - @Override - public Upgrades getType( final ItemStack itemstack ) - { - switch( this.getTypeByStack( itemstack ) ) - { - case CardCapacity: - return Upgrades.CAPACITY; - case CardFuzzy: - return Upgrades.FUZZY; - case CardRedstone: - return Upgrades.REDSTONE; - case CardSpeed: - return Upgrades.SPEED; - case CardInverter: - return Upgrades.INVERTER; - case CardCrafting: - return Upgrades.CRAFTING; - default: - return null; - } - } + boolean enabled = true; - public IStackSrc createMaterial( final MaterialType mat ) - { - Preconditions.checkState( !mat.isRegistered(), "Cannot create the same material twice." ); + for (final AEFeature f : mat.getFeature()) { + enabled = enabled && AEConfig.instance.isFeatureEnabled(f); + } - boolean enabled = true; + mat.setStackSrc(new MaterialStackSrc(mat)); - for( final AEFeature f : mat.getFeature() ) - { - enabled = enabled && AEConfig.instance.isFeatureEnabled( f ); - } + if (enabled) { + mat.setItemInstance(this); + mat.markReady(); + final int newMaterialNum = mat.getDamageValue(); - mat.setStackSrc( new MaterialStackSrc( mat ) ); + if (this.dmgToMaterial.get(newMaterialNum) == null) { + this.dmgToMaterial.put(newMaterialNum, mat); + } else - if( enabled ) - { - mat.setItemInstance( this ); - mat.markReady(); - final int newMaterialNum = mat.getDamageValue(); + { + throw new IllegalStateException("Meta Overlap detected."); + } + } - if( this.dmgToMaterial.get( newMaterialNum ) == null ) - { - this.dmgToMaterial.put( newMaterialNum, mat ); - } - else + return mat.getStackSrc(); + } - { - throw new IllegalStateException( "Meta Overlap detected." ); - } - } + public void makeUnique() { + for (final MaterialType mt : ImmutableSet.copyOf(this.dmgToMaterial.values())) { + if (mt.getOreName() != null) { + ItemStack replacement = null; - return mat.getStackSrc(); - } + final String[] names = mt.getOreName().split(","); - public void makeUnique() - { - for( final MaterialType mt : ImmutableSet.copyOf( this.dmgToMaterial.values() ) ) - { - if( mt.getOreName() != null ) - { - ItemStack replacement = null; + for (final String name : names) { + if (replacement != null) { + break; + } - final String[] names = mt.getOreName().split( "," ); + final List options = OreDictionary.getOres(name); + if (options != null && options.size() > 0) { + for (final ItemStack is : options) { + if (is != null && is.getItem() != null) { + replacement = is.copy(); + break; + } + } + } + } - for( final String name : names ) - { - if( replacement != null ) - { - break; - } + if (replacement == null || AEConfig.instance.useAEVersion(mt)) { + // continue using the AE2 item. + for (final String name : names) { + OreDictionary.registerOre(name, mt.stack(1)); + } + } else { + if (mt.getItemInstance() == this) { + this.dmgToMaterial.remove(mt.getDamageValue()); + } - final List options = OreDictionary.getOres( name ); - if( options != null && options.size() > 0 ) - { - for( final ItemStack is : options ) - { - if( is != null && is.getItem() != null ) - { - replacement = is.copy(); - break; - } - } - } - } + mt.setItemInstance(replacement.getItem()); + mt.setDamageValue(replacement.getItemDamage()); + } + } + } + } - if( replacement == null || AEConfig.instance.useAEVersion( mt ) ) - { - // continue using the AE2 item. - for( final String name : names ) - { - OreDictionary.registerOre( name, mt.stack( 1 ) ); - } - } - else - { - if( mt.getItemInstance() == this ) - { - this.dmgToMaterial.remove( mt.getDamageValue() ); - } + @Override + public IIcon getIconFromDamage(final int dmg) { + if (this.dmgToMaterial.containsKey(dmg)) { + return this.dmgToMaterial.get(dmg).getIIcon(); + } + return new MissingIcon(this); + } - mt.setItemInstance( replacement.getItem() ); - mt.setDamageValue( replacement.getItemDamage() ); - } - } - } - } + @Override + public String getUnlocalizedName(final ItemStack is) { + return "item.appliedenergistics2." + this.nameOf(is); + } - @Override - public IIcon getIconFromDamage( final int dmg ) - { - if( this.dmgToMaterial.containsKey( dmg ) ) - { - return this.dmgToMaterial.get( dmg ).getIIcon(); - } - return new MissingIcon( this ); - } + private String nameOf(final ItemStack is) { + if (is == null) { + return "null"; + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return "item.appliedenergistics2." + this.nameOf( is ); - } + final MaterialType mt = this.getTypeByStack(is); + if (mt == null) { + return "null"; + } - private String nameOf( final ItemStack is ) - { - if( is == null ) - { - return "null"; - } + return this.nameResolver.getName(mt.name()); + } - final MaterialType mt = this.getTypeByStack( is ); - if( mt == null ) - { - return "null"; - } + @Override + protected void getCheckedSubItems( + final Item sameItem, + final CreativeTabs creativeTab, + final List itemStacks + ) { + final List types = Arrays.asList(MaterialType.values()); + Collections.sort(types, new Comparator() { + @Override + public int compare(final MaterialType o1, final MaterialType o2) { + return o1.name().compareTo(o2.name()); + } + }); - return this.nameResolver.getName( mt.name() ); - } + for (final MaterialType mat : types) { + if (mat.getDamageValue() >= 0 && mat.isRegistered() + && mat.getItemInstance() == this) { + itemStacks.add(new ItemStack(this, 1, mat.getDamageValue())); + } + } + } - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - final List types = Arrays.asList( MaterialType.values() ); - Collections.sort( types, new Comparator() - { + @Override + public void registerIcons(final IIconRegister icoRegister) { + for (final MaterialType mat : MaterialType.values()) { + if (mat.getDamageValue() != -1) { + final ItemStack what = new ItemStack(this, 1, mat.getDamageValue()); + if (this.getTypeByStack(what) != MaterialType.InvalidType) { + final String tex = "appliedenergistics2:" + this.nameOf(what); + mat.setIIcon(icoRegister.registerIcon(tex)); + } + } + } + } - @Override - public int compare( final MaterialType o1, final MaterialType o2 ) - { - return o1.name().compareTo( o2.name() ); - } - } ); + @Override + public boolean onItemUseFirst( + final ItemStack is, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) + return true; - for( final MaterialType mat : types ) - { - if( mat.getDamageValue() >= 0 && mat.isRegistered() && mat.getItemInstance() == this ) - { - itemStacks.add( new ItemStack( this, 1, mat.getDamageValue() ) ); - } - } - } + if (player.isSneaking()) { + final TileEntity te = world.getTileEntity(x, y, z); + IInventory upgrades = null; - @Override - public void registerIcons( final IIconRegister icoRegister ) - { - for( final MaterialType mat : MaterialType.values() ) - { - if( mat.getDamageValue() != -1 ) - { - final ItemStack what = new ItemStack( this, 1, mat.getDamageValue() ); - if( this.getTypeByStack( what ) != MaterialType.InvalidType ) - { - final String tex = "appliedenergistics2:" + this.nameOf( what ); - mat.setIIcon( icoRegister.registerIcon( tex ) ); - } - } - } - } + if (te instanceof IPartHost) { + final SelectedPart sp + = ((IPartHost) te) + .selectPart(Vec3.createVectorHelper(hitX, hitY, hitZ)); + if (sp.part instanceof IUpgradeableHost) { + upgrades + = ((ISegmentedInventory) sp.part).getInventoryByName("upgrades"); + } + } else if (te instanceof IUpgradeableHost) { + upgrades = ((ISegmentedInventory) te).getInventoryByName("upgrades"); + } - @Override - public boolean onItemUseFirst( final ItemStack is, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return true; + if (upgrades != null && is != null + && is.getItem() instanceof IUpgradeModule) { + final IUpgradeModule um = (IUpgradeModule) is.getItem(); + final Upgrades u = um.getType(is); - if( player.isSneaking() ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - IInventory upgrades = null; + if (u != null) { + final InventoryAdaptor ad + = InventoryAdaptor.getAdaptor(upgrades, ForgeDirection.UNKNOWN); + if (ad != null) { + if (player.worldObj.isRemote) { + return false; + } - if( te instanceof IPartHost ) - { - final SelectedPart sp = ( (IPartHost) te ).selectPart( Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - if( sp.part instanceof IUpgradeableHost ) - { - upgrades = ( (ISegmentedInventory) sp.part ).getInventoryByName( "upgrades" ); - } - } - else if( te instanceof IUpgradeableHost ) - { - upgrades = ( (ISegmentedInventory) te ).getInventoryByName( "upgrades" ); - } + player.inventory.setInventorySlotContents( + player.inventory.currentItem, ad.addItems(is) + ); + return true; + } + } + } + } - if( upgrades != null && is != null && is.getItem() instanceof IUpgradeModule ) - { - final IUpgradeModule um = (IUpgradeModule) is.getItem(); - final Upgrades u = um.getType( is ); + return super.onItemUseFirst(is, player, world, x, y, z, side, hitX, hitY, hitZ); + } - if( u != null ) - { - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( upgrades, ForgeDirection.UNKNOWN ); - if( ad != null ) - { - if( player.worldObj.isRemote ) - { - return false; - } + @Override + public boolean hasCustomEntity(final ItemStack is) { + return this.getTypeByStack(is).hasCustomEntity(); + } - player.inventory.setInventorySlotContents( player.inventory.currentItem, ad.addItems( is ) ); - return true; - } - } - } - } + @Override + public Entity + createEntity(final World w, final Entity location, final ItemStack itemstack) { + final Class droppedEntity + = this.getTypeByStack(itemstack).getCustomEntityClass(); + final Entity eqi; - return super.onItemUseFirst( is, player, world, x, y, z, side, hitX, hitY, hitZ ); - } + try { + eqi = droppedEntity + .getConstructor( + World.class, + double.class, + double.class, + double.class, + ItemStack.class + ) + .newInstance( + w, location.posX, location.posY, location.posZ, itemstack + ); + } catch (final Throwable t) { + throw new IllegalStateException(t); + } - @Override - public boolean hasCustomEntity( final ItemStack is ) - { - return this.getTypeByStack( is ).hasCustomEntity(); - } + eqi.motionX = location.motionX; + eqi.motionY = location.motionY; + eqi.motionZ = location.motionZ; - @Override - public Entity createEntity( final World w, final Entity location, final ItemStack itemstack ) - { - final Class droppedEntity = this.getTypeByStack( itemstack ).getCustomEntityClass(); - final Entity eqi; + if (location instanceof EntityItem && eqi instanceof EntityItem) { + ((EntityItem) eqi).delayBeforeCanPickup + = ((EntityItem) location).delayBeforeCanPickup; + } - try - { - eqi = droppedEntity.getConstructor( World.class, double.class, double.class, double.class, ItemStack.class ).newInstance( w, location.posX, location.posY, location.posZ, itemstack ); - } - catch( final Throwable t ) - { - throw new IllegalStateException( t ); - } + return eqi; + } - eqi.motionX = location.motionX; - eqi.motionY = location.motionY; - eqi.motionZ = location.motionZ; + @Override + public int getBytes(final ItemStack is) { + switch (this.getTypeByStack(is)) { + case Cell1kPart: + return KILO_SCALAR; + case Cell4kPart: + return KILO_SCALAR * 4; + case Cell16kPart: + return KILO_SCALAR * 16; + case Cell64kPart: + return KILO_SCALAR * 64; + default: + } + return 0; + } - if( location instanceof EntityItem && eqi instanceof EntityItem ) - { - ( (EntityItem) eqi ).delayBeforeCanPickup = ( (EntityItem) location ).delayBeforeCanPickup; - } + @Override + public boolean isStorageComponent(final ItemStack is) { + switch (this.getTypeByStack(is)) { + case Cell1kPart: + case Cell4kPart: + case Cell16kPart: + case Cell64kPart: + return true; + default: + } + return false; + } - return eqi; - } + private static class SlightlyBetterSort implements Comparator { + private final Pattern pattern; - @Override - public int getBytes( final ItemStack is ) - { - switch( this.getTypeByStack( is ) ) - { - case Cell1kPart: - return KILO_SCALAR; - case Cell4kPart: - return KILO_SCALAR * 4; - case Cell16kPart: - return KILO_SCALAR * 16; - case Cell64kPart: - return KILO_SCALAR * 64; - default: - } - return 0; - } + public SlightlyBetterSort(final Pattern pattern) { + this.pattern = pattern; + } - @Override - public boolean isStorageComponent( final ItemStack is ) - { - switch( this.getTypeByStack( is ) ) - { - case Cell1kPart: - case Cell4kPart: - case Cell16kPart: - case Cell64kPart: - return true; - default: - } - return false; - } - - private static class SlightlyBetterSort implements Comparator - { - private final Pattern pattern; - - public SlightlyBetterSort( final Pattern pattern ) - { - this.pattern = pattern; - } - - @Override - public int compare( final String o1, final String o2 ) - { - try - { - final Matcher a = this.pattern.matcher( o1 ); - final Matcher b = this.pattern.matcher( o2 ); - if( a.find() && b.find() ) - { - final int ia = Integer.parseInt( a.group( 1 ) ); - final int ib = Integer.parseInt( b.group( 1 ) ); - return Integer.compare( ia, ib ); - } - } - catch( final Throwable t ) - { - // ek! - } - return o1.compareTo( o2 ); - } - } + @Override + public int compare(final String o1, final String o2) { + try { + final Matcher a = this.pattern.matcher(o1); + final Matcher b = this.pattern.matcher(o2); + if (a.find() && b.find()) { + final int ia = Integer.parseInt(a.group(1)); + final int ib = Integer.parseInt(b.group(1)); + return Integer.compare(ia, ib); + } + } catch (final Throwable t) { + // ek! + } + return o1.compareTo(o2); + } + } } diff --git a/src/main/java/appeng/items/materials/MaterialType.java b/src/main/java/appeng/items/materials/MaterialType.java index d71c49ae..59e7fd27 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 appeng.core.AppEng; import appeng.core.features.AEFeature; @@ -33,211 +34,215 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; -import java.util.EnumSet; +public enum MaterialType { + InvalidType(-1, AEFeature.Core), + CertusQuartzCrystal(0, AEFeature.Core, "crystalCertusQuartz"), + CertusQuartzCrystalCharged(1, AEFeature.Core, EntityChargedQuartz.class), -public enum MaterialType -{ - InvalidType( -1, AEFeature.Core ), + 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"), - CertusQuartzCrystal( 0, AEFeature.Core, "crystalCertusQuartz" ), - CertusQuartzCrystalCharged( 1, AEFeature.Core, EntityChargedQuartz.class ), + Silicon(5, AEFeature.Core, "itemSilicon"), + MatterBall(6), - 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" ), + FluixCrystal(7, AEFeature.Core, "crystalFluix"), + FluixDust(8, AEFeature.Core, "dustFluix"), + FluixPearl(9, AEFeature.Core, "pearlFluix"), - Silicon( 5, AEFeature.Core, "itemSilicon" ), - MatterBall( 6 ), + PurifiedCertusQuartzCrystal(10), + PurifiedNetherQuartzCrystal(11), + PurifiedFluixCrystal(12), - FluixCrystal( 7, AEFeature.Core, "crystalFluix" ), - FluixDust( 8, AEFeature.Core, "dustFluix" ), - FluixPearl( 9, AEFeature.Core, "pearlFluix" ), + CalcProcessorPress(13), + EngProcessorPress(14), + LogicProcessorPress(15), - PurifiedCertusQuartzCrystal( 10 ), - PurifiedNetherQuartzCrystal( 11 ), - PurifiedFluixCrystal( 12 ), + CalcProcessorPrint(16), + EngProcessorPrint(17), + LogicProcessorPrint(18), - CalcProcessorPress( 13 ), - EngProcessorPress( 14 ), - LogicProcessorPress( 15 ), + SiliconPress(19), + SiliconPrint(20), - CalcProcessorPrint( 16 ), - EngProcessorPrint( 17 ), - LogicProcessorPrint( 18 ), + NamePress(21), - SiliconPress( 19 ), - SiliconPrint( 20 ), + LogicProcessor(22), + CalcProcessor(23), + EngProcessor(24), - NamePress( 21 ), + // Basic Cards + BasicCard(25), + CardRedstone(26), + CardCapacity(27), - LogicProcessor( 22 ), - CalcProcessor( 23 ), - EngProcessor( 24 ), + // Adv Cards + AdvCard(28), + CardFuzzy(29), + CardSpeed(30), + CardInverter(31), - // Basic Cards - BasicCard( 25 ), - CardRedstone( 26 ), - CardCapacity( 27 ), + Cell2SpatialPart(32, AEFeature.SpatialIO), + Cell16SpatialPart(33, AEFeature.SpatialIO), + Cell128SpatialPart(34, AEFeature.SpatialIO), - // Adv Cards - AdvCard( 28 ), - CardFuzzy( 29 ), CardSpeed( 30 ), - CardInverter( 31 ), + Cell1kPart(35, AEFeature.StorageCells), + Cell4kPart(36, AEFeature.StorageCells), + Cell16kPart(37, AEFeature.StorageCells), + Cell64kPart(38, AEFeature.StorageCells), + EmptyStorageCell(39, AEFeature.StorageCells), - Cell2SpatialPart( 32, AEFeature.SpatialIO ), - Cell16SpatialPart( 33, AEFeature.SpatialIO ), - Cell128SpatialPart( 34, AEFeature.SpatialIO ), + WoodenGear(40, AEFeature.GrindStone, "gearWood"), - Cell1kPart( 35, AEFeature.StorageCells ), - Cell4kPart( 36, AEFeature.StorageCells ), - Cell16kPart( 37, AEFeature.StorageCells ), - Cell64kPart( 38, AEFeature.StorageCells ), - EmptyStorageCell( 39, AEFeature.StorageCells ), + Wireless(41, AEFeature.WirelessAccessTerminal), + WirelessBooster(42, AEFeature.WirelessAccessTerminal), - WoodenGear( 40, AEFeature.GrindStone, "gearWood" ), + FormationCore(43), + AnnihilationCore(44), + ConversionMatrix(54, AEFeature.Legacy), - Wireless( 41, AEFeature.WirelessAccessTerminal ), - WirelessBooster( 42, AEFeature.WirelessAccessTerminal ), + SkyDust(45, AEFeature.Core), - FormationCore( 43 ), - AnnihilationCore( 44 ), - ConversionMatrix(54, AEFeature.Legacy), + EnderDust( + 46, + AEFeature.QuantumNetworkBridge, + "dustEnder,dustEnderPearl", + EntitySingularity.class + ), + Singularity(47, AEFeature.QuantumNetworkBridge, EntitySingularity.class), + QESingularity(48, AEFeature.QuantumNetworkBridge, EntitySingularity.class), - SkyDust( 45, AEFeature.Core ), + BlankPattern(52), + CardCrafting(53); - EnderDust( 46, AEFeature.QuantumNetworkBridge, "dustEnder,dustEnderPearl", EntitySingularity.class ), - Singularity( 47, AEFeature.QuantumNetworkBridge, EntitySingularity.class ), - QESingularity( 48, AEFeature.QuantumNetworkBridge, EntitySingularity.class ), + private final EnumSet features; + // IIcon for the material. + @SideOnly(Side.CLIENT) + private IIcon IIcon; + private Item itemInstance; + private int damageValue; + // stack! + private MaterialStackSrc stackSrc; + private String oreName; + private Class droppedEntity; + private boolean isRegistered = false; - BlankPattern( 52 ), - CardCrafting( 53 ); + MaterialType(final int metaValue) { + this.setDamageValue(metaValue); + this.features = EnumSet.of(AEFeature.Core); + } - private final EnumSet features; - // IIcon for the material. - @SideOnly( Side.CLIENT ) - private IIcon IIcon; - private Item itemInstance; - private int damageValue; - // stack! - private MaterialStackSrc stackSrc; - private String oreName; - private Class droppedEntity; - private boolean isRegistered = false; + MaterialType(final int metaValue, final AEFeature part) { + this.setDamageValue(metaValue); + this.features = EnumSet.of(part); + } - MaterialType( final int metaValue ) - { - this.setDamageValue( metaValue ); - this.features = EnumSet.of( AEFeature.Core ); - } + MaterialType( + final int metaValue, final AEFeature part, final Class c + ) { + this.features = EnumSet.of(part); + this.setDamageValue(metaValue); + this.droppedEntity = c; - MaterialType( final int metaValue, final AEFeature part ) - { - this.setDamageValue( metaValue ); - this.features = EnumSet.of( part ); - } + EntityRegistry.registerModEntity( + this.droppedEntity, + this.droppedEntity.getSimpleName(), + EntityIds.get(this.droppedEntity), + AppEng.instance(), + 16, + 4, + true + ); + } - MaterialType( final int metaValue, final AEFeature part, final Class c ) - { - this.features = EnumSet.of( part ); - this.setDamageValue( metaValue ); - this.droppedEntity = c; + MaterialType( + final int metaValue, + final AEFeature part, + final String oreDictionary, + final Class c + ) { + this.features = EnumSet.of(part); + this.setDamageValue(metaValue); + this.oreName = oreDictionary; + this.droppedEntity = c; + EntityRegistry.registerModEntity( + this.droppedEntity, + this.droppedEntity.getSimpleName(), + EntityIds.get(this.droppedEntity), + AppEng.instance(), + 16, + 4, + true + ); + } - EntityRegistry.registerModEntity( this.droppedEntity, this.droppedEntity.getSimpleName(), EntityIds.get( this.droppedEntity ), AppEng.instance(), 16, 4, true ); - } + MaterialType(final int metaValue, final AEFeature part, final String oreDictionary) { + this.features = EnumSet.of(part); + this.setDamageValue(metaValue); + this.oreName = oreDictionary; + } - MaterialType( final int metaValue, final AEFeature part, final String oreDictionary, final Class c ) - { - this.features = EnumSet.of( part ); - this.setDamageValue( metaValue ); - this.oreName = oreDictionary; - this.droppedEntity = c; - EntityRegistry.registerModEntity( this.droppedEntity, this.droppedEntity.getSimpleName(), EntityIds.get( this.droppedEntity ), AppEng.instance(), 16, 4, true ); - } + public ItemStack stack(final int size) { + return new ItemStack(this.getItemInstance(), size, this.getDamageValue()); + } - MaterialType( final int metaValue, final AEFeature part, final String oreDictionary ) - { - this.features = EnumSet.of( part ); - this.setDamageValue( metaValue ); - this.oreName = oreDictionary; - } + EnumSet getFeature() { + return this.features; + } - public ItemStack stack( final int size ) - { - return new ItemStack( this.getItemInstance(), size, this.getDamageValue() ); - } + public String getOreName() { + return this.oreName; + } - EnumSet getFeature() - { - return this.features; - } + boolean hasCustomEntity() { + return this.droppedEntity != null; + } - public String getOreName() - { - return this.oreName; - } + Class getCustomEntityClass() { + return this.droppedEntity; + } - boolean hasCustomEntity() - { - return this.droppedEntity != null; - } + public boolean isRegistered() { + return this.isRegistered; + } - Class getCustomEntityClass() - { - return this.droppedEntity; - } + void markReady() { + this.isRegistered = true; + } - public boolean isRegistered() - { - return this.isRegistered; - } + public int getDamageValue() { + return this.damageValue; + } - void markReady() - { - this.isRegistered = true; - } + void setDamageValue(final int damageValue) { + this.damageValue = damageValue; + } - public int getDamageValue() - { - return this.damageValue; - } + public Item getItemInstance() { + return this.itemInstance; + } - void setDamageValue( final int damageValue ) - { - this.damageValue = damageValue; - } + void setItemInstance(final Item itemInstance) { + this.itemInstance = itemInstance; + } - public Item getItemInstance() - { - return this.itemInstance; - } + IIcon getIIcon() { + return this.IIcon; + } - void setItemInstance( final Item itemInstance ) - { - this.itemInstance = itemInstance; - } + void setIIcon(final IIcon iIcon) { + this.IIcon = iIcon; + } - IIcon getIIcon() - { - return this.IIcon; - } - - void setIIcon( final IIcon iIcon ) - { - this.IIcon = iIcon; - } - - MaterialStackSrc getStackSrc() - { - return this.stackSrc; - } - - void setStackSrc( final MaterialStackSrc stackSrc ) - { - this.stackSrc = stackSrc; - } + MaterialStackSrc getStackSrc() { + return this.stackSrc; + } + void setStackSrc(final MaterialStackSrc stackSrc) { + this.stackSrc = stackSrc; + } } diff --git a/src/main/java/appeng/items/misc/ItemCrystalSeed.java b/src/main/java/appeng/items/misc/ItemCrystalSeed.java index 9f5cdf88..fde40817 100644 --- a/src/main/java/appeng/items/misc/ItemCrystalSeed.java +++ b/src/main/java/appeng/items/misc/ItemCrystalSeed.java @@ -18,6 +18,9 @@ package appeng.items.misc; +import java.util.EnumSet; +import java.util.List; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.definitions.IMaterials; @@ -45,284 +48,261 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import javax.annotation.Nullable; -import java.util.EnumSet; -import java.util.List; +public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal { + private static final int LEVEL_OFFSET = 200; + private static final int SINGLE_OFFSET = LEVEL_OFFSET * 3; + public static final int CERTUS = 0; + public static final int NETHER = SINGLE_OFFSET; + public static final int FLUIX = SINGLE_OFFSET * 2; + public static final int FINAL_STAGE = SINGLE_OFFSET * 3; -public class ItemCrystalSeed extends AEBaseItem implements IGrowableCrystal -{ + private final IIcon[] certus = new IIcon[3]; + private final IIcon[] fluix = new IIcon[3]; + private final IIcon[] nether = new IIcon[3]; - private static final int LEVEL_OFFSET = 200; - private static final int SINGLE_OFFSET = LEVEL_OFFSET * 3; + public ItemCrystalSeed() { + this.setHasSubtypes(true); + this.setFeature(EnumSet.of(AEFeature.Core)); - public static final int CERTUS = 0; - public static final int NETHER = SINGLE_OFFSET; - public static final int FLUIX = SINGLE_OFFSET * 2; - public static final int FINAL_STAGE = SINGLE_OFFSET * 3; + EntityRegistry.registerModEntity( + EntityGrowingCrystal.class, + EntityGrowingCrystal.class.getSimpleName(), + EntityIds.get(EntityGrowingCrystal.class), + AppEng.instance(), + 16, + 4, + true + ); + } - private final IIcon[] certus = new IIcon[3]; - private final IIcon[] fluix = new IIcon[3]; - private final IIcon[] nether = new IIcon[3]; + @Nullable + public static ResolverResult getResolver(final int certus2) { + ResolverResult resolver = null; - public ItemCrystalSeed() - { - this.setHasSubtypes( true ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); + for (ItemStack crystalSeedStack : + AEApi.instance().definitions().items().crystalSeed().maybeStack(1).asSet()) { + crystalSeedStack.setItemDamage(certus2); + crystalSeedStack = newStyle(crystalSeedStack); + resolver = new ResolverResult( + "ItemCrystalSeed", + crystalSeedStack.getItemDamage(), + crystalSeedStack.getTagCompound() + ); + } - EntityRegistry.registerModEntity( EntityGrowingCrystal.class, EntityGrowingCrystal.class.getSimpleName(), EntityIds.get( EntityGrowingCrystal.class ), AppEng.instance(), 16, 4, true ); - } + return resolver; + } - @Nullable - public static ResolverResult getResolver( final int certus2 ) - { - ResolverResult resolver = null; + private static ItemStack newStyle(final ItemStack itemStack) { + ((ItemCrystalSeed) itemStack.getItem()).getProgress(itemStack); + return itemStack; + } - for( ItemStack crystalSeedStack : AEApi.instance().definitions().items().crystalSeed().maybeStack( 1 ).asSet() ) - { - crystalSeedStack.setItemDamage( certus2 ); - crystalSeedStack = newStyle( crystalSeedStack ); - resolver = new ResolverResult( "ItemCrystalSeed", crystalSeedStack.getItemDamage(), crystalSeedStack.getTagCompound() ); - } + private int getProgress(final ItemStack is) { + if (is.hasTagCompound()) { + return is.getTagCompound().getInteger("progress"); + } else { + final int progress; + final NBTTagCompound comp = Platform.openNbtData(is); + comp.setInteger("progress", progress = is.getItemDamage()); + is.setItemDamage((is.getItemDamage() / SINGLE_OFFSET) * SINGLE_OFFSET); + return progress; + } + } - return resolver; - } + @Nullable + @Override + public ItemStack triggerGrowth(final ItemStack is) { + final int newDamage = this.getProgress(is) + 1; + final IMaterials materials = AEApi.instance().definitions().materials(); + final int size = is.stackSize; - private static ItemStack newStyle( final ItemStack itemStack ) - { - ( (ItemCrystalSeed) itemStack.getItem() ).getProgress( itemStack ); - return itemStack; - } + if (newDamage == CERTUS + SINGLE_OFFSET) { + for (final ItemStack quartzStack : + materials.purifiedCertusQuartzCrystal().maybeStack(size).asSet()) { + return quartzStack; + } + } + if (newDamage == NETHER + SINGLE_OFFSET) { + for (final ItemStack quartzStack : + materials.purifiedNetherQuartzCrystal().maybeStack(size).asSet()) { + return quartzStack; + } + } + if (newDamage == FLUIX + SINGLE_OFFSET) { + for (final ItemStack quartzStack : + materials.purifiedFluixCrystal().maybeStack(size).asSet()) { + return quartzStack; + } + } + if (newDamage > FINAL_STAGE) { + return null; + } - private int getProgress( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - return is.getTagCompound().getInteger( "progress" ); - } - else - { - final int progress; - final NBTTagCompound comp = Platform.openNbtData( is ); - comp.setInteger( "progress", progress = is.getItemDamage() ); - is.setItemDamage( ( is.getItemDamage() / SINGLE_OFFSET ) * SINGLE_OFFSET ); - return progress; - } - } + this.setProgress(is, newDamage); + return is; + } - @Nullable - @Override - public ItemStack triggerGrowth( final ItemStack is ) - { - final int newDamage = this.getProgress( is ) + 1; - final IMaterials materials = AEApi.instance().definitions().materials(); - final int size = is.stackSize; + private void setProgress(final ItemStack is, final int newDamage) { + final NBTTagCompound comp = Platform.openNbtData(is); + comp.setInteger("progress", newDamage); + is.setItemDamage(is.getItemDamage() / LEVEL_OFFSET * LEVEL_OFFSET); + } - if( newDamage == CERTUS + SINGLE_OFFSET ) - { - for( final ItemStack quartzStack : materials.purifiedCertusQuartzCrystal().maybeStack( size ).asSet() ) - { - return quartzStack; - } - } - if( newDamage == NETHER + SINGLE_OFFSET ) - { - for( final ItemStack quartzStack : materials.purifiedNetherQuartzCrystal().maybeStack( size ).asSet() ) - { - return quartzStack; - } - } - if( newDamage == FLUIX + SINGLE_OFFSET ) - { - for( final ItemStack quartzStack : materials.purifiedFluixCrystal().maybeStack( size ).asSet() ) - { - return quartzStack; - } - } - if( newDamage > FINAL_STAGE ) - { - return null; - } + @Override + public float getMultiplier(final Block blk, final Material mat) { + return 0.5f; + } - this.setProgress( is, newDamage ); - return is; - } + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + lines.add(ButtonToolTips.DoesntDespawn.getLocal()); + final int progress = this.getProgress(stack) % SINGLE_OFFSET; + lines.add(Math.floor((float) progress / (float) (SINGLE_OFFSET / 100)) + "%"); - private void setProgress( final ItemStack is, final int newDamage ) - { - final NBTTagCompound comp = Platform.openNbtData( is ); - comp.setInteger( "progress", newDamage ); - is.setItemDamage( is.getItemDamage() / LEVEL_OFFSET * LEVEL_OFFSET ); - } + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + } - @Override - public float getMultiplier( final Block blk, final Material mat ) - { - return 0.5f; - } + @Override + public int getEntityLifespan(final ItemStack itemStack, final World world) { + return Integer.MAX_VALUE; + } - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - lines.add( ButtonToolTips.DoesntDespawn.getLocal() ); - final int progress = this.getProgress( stack ) % SINGLE_OFFSET; - lines.add( Math.floor( (float) progress / (float) ( SINGLE_OFFSET / 100 ) ) + "%" ); + @Override + public String getUnlocalizedName(final ItemStack is) { + final int damage = this.getProgress(is); - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - } + if (damage < CERTUS + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".Certus"; + } - @Override - public int getEntityLifespan( final ItemStack itemStack, final World world ) - { - return Integer.MAX_VALUE; - } + if (damage < NETHER + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".Nether"; + } - @Override - public String getUnlocalizedName( final ItemStack is ) - { - final int damage = this.getProgress( is ); + if (damage < FLUIX + SINGLE_OFFSET) { + return this.getUnlocalizedName() + ".Fluix"; + } - if( damage < CERTUS + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".Certus"; - } + return this.getUnlocalizedName(); + } - if( damage < NETHER + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".Nether"; - } + @Override + public boolean isDamageable() { + return false; + } - if( damage < FLUIX + SINGLE_OFFSET ) - { - return this.getUnlocalizedName() + ".Fluix"; - } + @Override + public boolean isDamaged(final ItemStack stack) { + return false; + } - return this.getUnlocalizedName(); - } + @Override + public int getMaxDamage(final ItemStack stack) { + return FINAL_STAGE; + } - @Override - public boolean isDamageable() - { - return false; - } + @Override + public IIcon getIcon(final ItemStack stack, final int pass) { + return this.getIconIndex(stack); + } - @Override - public boolean isDamaged( final ItemStack stack ) - { - return false; - } + @Override + public IIcon getIconIndex(final ItemStack stack) { + IIcon[] list = null; - @Override - public int getMaxDamage( final ItemStack stack ) - { - return FINAL_STAGE; - } + int damage = this.getProgress(stack); - @Override - public IIcon getIcon( final ItemStack stack, final int pass ) - { - return this.getIconIndex( stack ); - } + if (damage < CERTUS + SINGLE_OFFSET) { + list = this.certus; + } else if (damage < NETHER + SINGLE_OFFSET) { + damage -= NETHER; + list = this.nether; + } - @Override - public IIcon getIconIndex( final ItemStack stack ) - { - IIcon[] list = null; + else if (damage < FLUIX + SINGLE_OFFSET) { + damage -= FLUIX; + list = this.fluix; + } - int damage = this.getProgress( stack ); + if (list == null) { + return Items.diamond.getIconFromDamage(0); + } - if( damage < CERTUS + SINGLE_OFFSET ) - { - list = this.certus; - } - else if( damage < NETHER + SINGLE_OFFSET ) - { - damage -= NETHER; - list = this.nether; - } + if (damage < LEVEL_OFFSET) { + return list[0]; + } else if (damage < LEVEL_OFFSET * 2) { + return list[1]; + } else { + return list[2]; + } + } - else if( damage < FLUIX + SINGLE_OFFSET ) - { - damage -= FLUIX; - list = this.fluix; - } + @Override + public void registerIcons(final IIconRegister ir) { + final String preFix = "appliedenergistics2:ItemCrystalSeed."; - if( list == null ) - { - return Items.diamond.getIconFromDamage( 0 ); - } + this.certus[0] = ir.registerIcon(preFix + "Certus"); + this.certus[1] = ir.registerIcon(preFix + "Certus2"); + this.certus[2] = ir.registerIcon(preFix + "Certus3"); - if( damage < LEVEL_OFFSET ) - { - return list[0]; - } - else if( damage < LEVEL_OFFSET * 2 ) - { - return list[1]; - } - else - { - return list[2]; - } - } + this.nether[0] = ir.registerIcon(preFix + "Nether"); + this.nether[1] = ir.registerIcon(preFix + "Nether2"); + this.nether[2] = ir.registerIcon(preFix + "Nether3"); - @Override - public void registerIcons( final IIconRegister ir ) - { - final String preFix = "appliedenergistics2:ItemCrystalSeed."; + this.fluix[0] = ir.registerIcon(preFix + "Fluix"); + this.fluix[1] = ir.registerIcon(preFix + "Fluix2"); + this.fluix[2] = ir.registerIcon(preFix + "Fluix3"); + } - this.certus[0] = ir.registerIcon( preFix + "Certus" ); - this.certus[1] = ir.registerIcon( preFix + "Certus2" ); - this.certus[2] = ir.registerIcon( preFix + "Certus3" ); + @Override + public boolean hasCustomEntity(final ItemStack stack) { + return true; + } - this.nether[0] = ir.registerIcon( preFix + "Nether" ); - this.nether[1] = ir.registerIcon( preFix + "Nether2" ); - this.nether[2] = ir.registerIcon( preFix + "Nether3" ); + @Override + public Entity + createEntity(final World world, final Entity location, final ItemStack itemstack) { + final EntityGrowingCrystal egc = new EntityGrowingCrystal( + world, location.posX, location.posY, location.posZ, itemstack + ); - this.fluix[0] = ir.registerIcon( preFix + "Fluix" ); - this.fluix[1] = ir.registerIcon( preFix + "Fluix2" ); - this.fluix[2] = ir.registerIcon( preFix + "Fluix3" ); - } + egc.motionX = location.motionX; + egc.motionY = location.motionY; + egc.motionZ = location.motionZ; - @Override - public boolean hasCustomEntity( final ItemStack stack ) - { - return true; - } + if (location instanceof EntityItem) { + egc.delayBeforeCanPickup = ((EntityItem) location).delayBeforeCanPickup; + } - @Override - public Entity createEntity( final World world, final Entity location, final ItemStack itemstack ) - { - final EntityGrowingCrystal egc = new EntityGrowingCrystal( world, location.posX, location.posY, location.posZ, itemstack ); + return egc; + } - egc.motionX = location.motionX; - egc.motionY = location.motionY; - egc.motionZ = location.motionZ; + @Override + protected void getCheckedSubItems( + final Item sameItem, + final CreativeTabs creativeTab, + final List itemStacks + ) { + // lvl 0 + itemStacks.add(newStyle(new ItemStack(this, 1, CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, FLUIX))); - if( location instanceof EntityItem ) - { - egc.delayBeforeCanPickup = ( (EntityItem) location ).delayBeforeCanPickup; - } + // lvl 1 + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + NETHER))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET + FLUIX))); - return egc; - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - // lvl 0 - itemStacks.add( newStyle( new ItemStack( this, 1, CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, FLUIX ) ) ); - - // lvl 1 - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET + FLUIX ) ) ); - - // lvl 2 - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + CERTUS ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + NETHER ) ) ); - itemStacks.add( newStyle( new ItemStack( this, 1, LEVEL_OFFSET * 2 + FLUIX ) ) ); - } + // lvl 2 + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + CERTUS))); + itemStacks.add(newStyle(new ItemStack(this, 1, LEVEL_OFFSET * 2 + NETHER))); + itemStacks.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 ea22491a..d668c0d2 100644 --- a/src/main/java/appeng/items/misc/ItemEncodedPattern.java +++ b/src/main/java/appeng/items/misc/ItemEncodedPattern.java @@ -18,6 +18,10 @@ package appeng.items.misc; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; import appeng.api.AEApi; import appeng.api.implementations.ICraftingPatternItem; @@ -38,158 +42,162 @@ import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.WeakHashMap; +public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternItem { + // rather simple client side caching. + private static final Map SIMPLE_CACHE + = new WeakHashMap(); + public ItemEncodedPattern() { + this.setFeature(EnumSet.of(AEFeature.Patterns)); + this.setMaxStackSize(1); + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer( + this, new ItemEncodedPatternRenderer() + ); + } + } -public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternItem -{ - // rather simple client side caching. - private static final Map SIMPLE_CACHE = new WeakHashMap(); + @Override + public ItemStack + onItemRightClick(final ItemStack stack, final World w, final EntityPlayer player) { + this.clearPattern(stack, player); - public ItemEncodedPattern() - { - this.setFeature( EnumSet.of( AEFeature.Patterns ) ); - this.setMaxStackSize( 1 ); - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new ItemEncodedPatternRenderer() ); - } - } + return stack; + } - @Override - public ItemStack onItemRightClick( final ItemStack stack, final World w, final EntityPlayer player ) - { - this.clearPattern( stack, player ); + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) + return true; - return stack; - } + return this.clearPattern(stack, player); + } - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; + private boolean clearPattern(final ItemStack stack, final EntityPlayer player) { + if (player.isSneaking()) { + if (Platform.isClient()) { + return false; + } - return this.clearPattern( stack, player ); - } + final InventoryPlayer inv = player.inventory; - private boolean clearPattern( final ItemStack stack, final EntityPlayer player ) - { - if( player.isSneaking() ) - { - if( Platform.isClient() ) - { - return false; - } + for (int s = 0; s < player.inventory.getSizeInventory(); s++) { + if (inv.getStackInSlot(s) == stack) { + for (final ItemStack blankPattern : AEApi.instance() + .definitions() + .materials() + .blankPattern() + .maybeStack(stack.stackSize) + .asSet()) { + inv.setInventorySlotContents(s, blankPattern); + } - final InventoryPlayer inv = player.inventory; + return true; + } + } + } - for( int s = 0; s < player.inventory.getSizeInventory(); s++ ) - { - if( inv.getStackInSlot( s ) == stack ) - { - for( final ItemStack blankPattern : AEApi.instance().definitions().materials().blankPattern().maybeStack( stack.stackSize ).asSet() ) - { - inv.setInventorySlotContents( s, blankPattern ); - } + return false; + } - return true; - } - } - } + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + final ICraftingPatternDetails details + = this.getPatternForItem(stack, player.worldObj); - return false; - } + if (details == null) { + lines.add(EnumChatFormatting.RED + GuiText.InvalidPattern.getLocal()); + return; + } - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final ICraftingPatternDetails details = this.getPatternForItem( stack, player.worldObj ); + final boolean isCrafting = details.isCraftable(); + final boolean substitute = details.canSubstitute(); - if( details == null ) - { - lines.add( EnumChatFormatting.RED + GuiText.InvalidPattern.getLocal() ); - return; - } + final IAEItemStack[] in = details.getCondensedInputs(); + final IAEItemStack[] out = details.getCondensedOutputs(); - final boolean isCrafting = details.isCraftable(); - final boolean substitute = details.canSubstitute(); + final String label + = (isCrafting ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal()) + + ": "; + final String and = ' ' + GuiText.And.getLocal() + ' '; + final String with = GuiText.With.getLocal() + ": "; - final IAEItemStack[] in = details.getCondensedInputs(); - final IAEItemStack[] out = details.getCondensedOutputs(); + boolean first = true; + for (final IAEItemStack anOut : out) { + if (anOut == null) { + continue; + } - final String label = ( isCrafting ? GuiText.Crafts.getLocal() : GuiText.Creates.getLocal() ) + ": "; - final String and = ' ' + GuiText.And.getLocal() + ' '; - final String with = GuiText.With.getLocal() + ": "; + lines.add( + (first ? label : and) + anOut.getStackSize() + ' ' + + Platform.getItemDisplayName(anOut) + ); + first = false; + } - boolean first = true; - for( final IAEItemStack anOut : out ) - { - if( anOut == null ) - { - continue; - } + first = true; + for (final IAEItemStack anIn : in) { + if (anIn == null) { + continue; + } - lines.add( ( first ? label : and ) + anOut.getStackSize() + ' ' + Platform.getItemDisplayName( anOut ) ); - first = false; - } + lines.add( + (first ? with : and) + anIn.getStackSize() + ' ' + + Platform.getItemDisplayName(anIn) + ); + first = false; + } - first = true; - for( final IAEItemStack anIn : in ) - { - if( anIn == null ) - { - continue; - } + final String substitutionLabel = GuiText.Substitute.getLocal() + " "; + final String canSubstitute + = substitute ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); - lines.add( ( first ? with : and ) + anIn.getStackSize() + ' ' + Platform.getItemDisplayName( anIn ) ); - first = false; - } + lines.add(substitutionLabel + canSubstitute); + } - final String substitutionLabel = GuiText.Substitute.getLocal() + " "; - final String canSubstitute = substitute ? GuiText.Yes.getLocal() : GuiText.No.getLocal(); + @Override + public ICraftingPatternDetails getPatternForItem(final ItemStack is, final World w) { + try { + return new PatternHelper(is, w); + } catch (final Throwable t) { + return null; + } + } - lines.add( substitutionLabel + canSubstitute ); - } + public ItemStack getOutput(final ItemStack item) { + ItemStack out = SIMPLE_CACHE.get(item); + if (out != null) { + return out; + } - @Override - public ICraftingPatternDetails getPatternForItem( final ItemStack is, final World w ) - { - try - { - return new PatternHelper( is, w ); - } - catch( final Throwable t ) - { - return null; - } - } + final World w = CommonHelper.proxy.getWorld(); + if (w == null) { + return null; + } - public ItemStack getOutput( final ItemStack item ) - { - ItemStack out = SIMPLE_CACHE.get( item ); - if( out != null ) - { - return out; - } + final ICraftingPatternDetails details = this.getPatternForItem(item, w); - final World w = CommonHelper.proxy.getWorld(); - if( w == null ) - { - return null; - } + if (details == null) { + return null; + } - final ICraftingPatternDetails details = this.getPatternForItem( item, w ); - - if( details == null ) - { - return null; - } - - SIMPLE_CACHE.put( item, out = details.getCondensedOutputs()[0].getItemStack() ); - return out; - } + SIMPLE_CACHE.put(item, out = details.getCondensedOutputs()[0].getItemStack()); + return out; + } } diff --git a/src/main/java/appeng/items/misc/ItemPaintBall.java b/src/main/java/appeng/items/misc/ItemPaintBall.java index 5e82c223..f45e8546 100644 --- a/src/main/java/appeng/items/misc/ItemPaintBall.java +++ b/src/main/java/appeng/items/misc/ItemPaintBall.java @@ -18,6 +18,8 @@ package appeng.items.misc; +import java.util.EnumSet; +import java.util.List; import appeng.api.util.AEColor; import appeng.client.render.items.PaintBallRender; @@ -30,76 +32,63 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.client.MinecraftForgeClient; -import java.util.EnumSet; -import java.util.List; +public class ItemPaintBall extends AEBaseItem { + private static final int DAMAGE_THRESHOLD = 20; + public ItemPaintBall() { + this.setFeature(EnumSet.of(AEFeature.PaintBalls)); + this.setHasSubtypes(true); -public class ItemPaintBall extends AEBaseItem -{ + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, new PaintBallRender()); + } + } - private static final int DAMAGE_THRESHOLD = 20; + @Override + public String getItemStackDisplayName(final ItemStack is) { + return super.getItemStackDisplayName(is) + " - " + this.getExtraName(is); + } - public ItemPaintBall() - { - this.setFeature( EnumSet.of( AEFeature.PaintBalls ) ); - this.setHasSubtypes( true ); + private String getExtraName(final ItemStack is) { + return (is.getItemDamage() >= DAMAGE_THRESHOLD ? GuiText.Lumen.getLocal() + ' ' + : "") + + this.getColor(is); + } - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new PaintBallRender() ); - } - } + public AEColor getColor(final ItemStack is) { + int dmg = is.getItemDamage(); + if (dmg >= DAMAGE_THRESHOLD) { + dmg -= DAMAGE_THRESHOLD; + } - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - return super.getItemStackDisplayName( is ) + " - " + this.getExtraName( is ); - } + if (dmg >= AEColor.values().length) { + return AEColor.Transparent; + } - private String getExtraName( final ItemStack is ) - { - return ( is.getItemDamage() >= DAMAGE_THRESHOLD ? GuiText.Lumen.getLocal() + ' ' : "" ) + this.getColor( is ); - } + return AEColor.values()[dmg]; + } - public AEColor getColor( final ItemStack is ) - { - int dmg = is.getItemDamage(); - if( dmg >= DAMAGE_THRESHOLD ) - { - dmg -= DAMAGE_THRESHOLD; - } + @Override + protected void getCheckedSubItems( + final Item sameItem, + final CreativeTabs creativeTab, + final List itemStacks + ) { + for (final AEColor c : AEColor.values()) { + if (c != AEColor.Transparent) { + itemStacks.add(new ItemStack(this, 1, c.ordinal())); + } + } - if( dmg >= AEColor.values().length ) - { - return AEColor.Transparent; - } + for (final AEColor c : AEColor.values()) { + if (c != AEColor.Transparent) { + itemStacks.add(new ItemStack(this, 1, DAMAGE_THRESHOLD + c.ordinal())); + } + } + } - return AEColor.values()[dmg]; - } - - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - for( final AEColor c : AEColor.values() ) - { - if( c != AEColor.Transparent ) - { - itemStacks.add( new ItemStack( this, 1, c.ordinal() ) ); - } - } - - for( final AEColor c : AEColor.values() ) - { - if( c != AEColor.Transparent ) - { - itemStacks.add( new ItemStack( this, 1, DAMAGE_THRESHOLD + c.ordinal() ) ); - } - } - } - - public boolean isLumen( final ItemStack is ) - { - final int dmg = is.getItemDamage(); - return dmg >= DAMAGE_THRESHOLD; - } + public boolean isLumen(final ItemStack is) { + final int dmg = is.getItemDamage(); + return dmg >= DAMAGE_THRESHOLD; + } } diff --git a/src/main/java/appeng/items/parts/ItemFacade.java b/src/main/java/appeng/items/parts/ItemFacade.java index 330f8bf5..0d84aa56 100644 --- a/src/main/java/appeng/items/parts/ItemFacade.java +++ b/src/main/java/appeng/items/parts/ItemFacade.java @@ -18,6 +18,9 @@ package appeng.items.parts; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; @@ -48,244 +51,214 @@ import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; +public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassItem { + private List subTypes = null; + public ItemFacade() { + this.setFeature(EnumSet.of(AEFeature.Facades)); + this.setHasSubtypes(true); + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer(this, BusRenderer.INSTANCE); + } + } -public class ItemFacade extends AEBaseItem implements IFacadeItem, IAlphaPassItem -{ + @Override + @SideOnly(Side.CLIENT) + public int getSpriteNumber() { + return 0; + } - private List subTypes = null; + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + return AEApi.instance().partHelper().placeBus(is, x, y, z, side, player, w); + } - public ItemFacade() - { - this.setFeature( EnumSet.of( AEFeature.Facades ) ); - this.setHasSubtypes( true ); - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, BusRenderer.INSTANCE ); - } - } + @Override + public String getItemStackDisplayName(final ItemStack is) { + try { + final ItemStack in = this.getTextureItem(is); + if (in != null) { + return super.getItemStackDisplayName(is) + " - " + in.getDisplayName(); + } + } catch (final Throwable ignored) {} - @Override - @SideOnly( Side.CLIENT ) - public int getSpriteNumber() - { - return 0; - } + return super.getItemStackDisplayName(is); + } - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - return AEApi.instance().partHelper().placeBus( is, x, y, z, side, player, w ); - } + @Override + protected void getCheckedSubItems( + final Item sameItem, + final CreativeTabs creativeTab, + final List itemStacks + ) { + this.calculateSubTypes(); + itemStacks.addAll(this.subTypes); + } - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - try - { - final ItemStack in = this.getTextureItem( is ); - if( in != null ) - { - return super.getItemStackDisplayName( is ) + " - " + in.getDisplayName(); - } - } - catch( final Throwable ignored ) - { + private void calculateSubTypes() { + if (this.subTypes == null) { + this.subTypes = new ArrayList(1000); + for (final Object blk : Block.blockRegistry) { + final Block b = (Block) blk; + try { + final Item item = Item.getItemFromBlock(b); - } + final List tmpList = new ArrayList(100); + b.getSubBlocks(item, b.getCreativeTabToDisplayOn(), tmpList); + for (final ItemStack l : tmpList) { + final ItemStack facade = this.createFacadeForItem(l, false); + if (facade != null) { + this.subTypes.add(facade); + } + } + } catch (final Throwable t) { + // just absorb.. + } + } - return super.getItemStackDisplayName( is ); - } + if (FacadeConfig.instance.hasChanged()) { + FacadeConfig.instance.save(); + } + } + } - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - this.calculateSubTypes(); - itemStacks.addAll( this.subTypes ); - } + public ItemStack createFacadeForItem(final ItemStack l, final boolean returnItem) { + if (l == null) { + return null; + } - private void calculateSubTypes() - { - if( this.subTypes == null ) - { - this.subTypes = new ArrayList( 1000 ); - for( final Object blk : Block.blockRegistry ) - { - final Block b = (Block) blk; - try - { - final Item item = Item.getItemFromBlock( b ); + final Block b = Block.getBlockFromItem(l.getItem()); + if (b == null || l.hasTagCompound()) { + return null; + } - final List tmpList = new ArrayList( 100 ); - b.getSubBlocks( item, b.getCreativeTabToDisplayOn(), tmpList ); - for( final ItemStack l : tmpList ) - { - final ItemStack facade = this.createFacadeForItem( l, false ); - if( facade != null ) - { - this.subTypes.add( facade ); - } - } - } - catch( final Throwable t ) - { - // just absorb.. - } - } + final int metadata = l.getItem().getMetadata(l.getItemDamage()); - if( FacadeConfig.instance.hasChanged() ) - { - FacadeConfig.instance.save(); - } - } - } + final boolean hasTile = b.hasTileEntity(metadata); + final boolean enableGlass + = b instanceof BlockGlass || b instanceof BlockStainedGlass; + final boolean disableOre = b instanceof OreQuartz; - public ItemStack createFacadeForItem( final ItemStack l, final boolean returnItem ) - { - if( l == null ) - { - return null; - } + final boolean defaultValue + = (b.isOpaqueCube() && !b.getTickRandomly() && !hasTile && !disableOre) + || enableGlass; + if (FacadeConfig.instance.checkEnabled(b, metadata, defaultValue)) { + if (returnItem) { + return l; + } - final Block b = Block.getBlockFromItem( l.getItem() ); - if( b == null || l.hasTagCompound() ) - { - return null; - } + final ItemStack is = new ItemStack(this); + final NBTTagCompound data = new NBTTagCompound(); + final int[] ds = new int[2]; + ds[0] = Item.getIdFromItem(l.getItem()); + ds[1] = metadata; + data.setIntArray("x", ds); + final UniqueIdentifier ui = GameRegistry.findUniqueIdentifierFor(l.getItem()); + data.setString("modid", ui.modId); + data.setString("itemname", ui.name); + is.setTagCompound(data); + return is; + } + return null; + } - final int metadata = l.getItem().getMetadata( l.getItemDamage() ); + @Override + public FacadePart + createPartFromItemStack(final ItemStack is, final ForgeDirection side) { + final ItemStack in = this.getTextureItem(is); + if (in != null) { + return new FacadePart(is, side); + } + return null; + } - final boolean hasTile = b.hasTileEntity( metadata ); - final boolean enableGlass = b instanceof BlockGlass || b instanceof BlockStainedGlass; - final boolean disableOre = b instanceof OreQuartz; + @Override + public ItemStack getTextureItem(final ItemStack is) { + final Block blk = this.getBlock(is); + if (blk != null) { + return new ItemStack(blk, 1, this.getMeta(is)); + } + return null; + } - final boolean defaultValue = ( b.isOpaqueCube() && !b.getTickRandomly() && !hasTile && !disableOre ) || enableGlass; - if( FacadeConfig.instance.checkEnabled( b, metadata, defaultValue ) ) - { - if( returnItem ) - { - return l; - } + @Override + public int getMeta(final ItemStack is) { + final NBTTagCompound data = is.getTagCompound(); + if (data != null) { + final int[] blk = data.getIntArray("x"); + if (blk != null && blk.length == 2) { + return blk[1]; + } + } + return 0; + } - final ItemStack is = new ItemStack( this ); - final NBTTagCompound data = new NBTTagCompound(); - final int[] ds = new int[2]; - ds[0] = Item.getIdFromItem( l.getItem() ); - ds[1] = metadata; - data.setIntArray( "x", ds ); - final UniqueIdentifier ui = GameRegistry.findUniqueIdentifierFor( l.getItem() ); - data.setString( "modid", ui.modId ); - data.setString( "itemname", ui.name ); - is.setTagCompound( data ); - return is; - } - return null; - } + @Override + public Block getBlock(final ItemStack is) { + final NBTTagCompound data = is.getTagCompound(); + if (data != null) { + if (data.hasKey("modid") && data.hasKey("itemname")) { + return GameRegistry.findBlock( + data.getString("modid"), data.getString("itemname") + ); + } else { + final int[] blk = data.getIntArray("x"); + if (blk != null && blk.length == 2) { + return Block.getBlockById(blk[0]); + } + } + } + return Blocks.glass; + } - @Override - public FacadePart createPartFromItemStack( final ItemStack is, final ForgeDirection side ) - { - final ItemStack in = this.getTextureItem( is ); - if( in != null ) - { - return new FacadePart( is, side ); - } - return null; - } + public List getFacades() { + this.calculateSubTypes(); + return this.subTypes; + } - @Override - public ItemStack getTextureItem( final ItemStack is ) - { - final Block blk = this.getBlock( is ); - if( blk != null ) - { - return new ItemStack( blk, 1, this.getMeta( is ) ); - } - return null; - } + public ItemStack getCreativeTabIcon() { + this.calculateSubTypes(); + if (this.subTypes.isEmpty()) { + return new ItemStack(Items.cake); + } + return this.subTypes.get(0); + } - @Override - public int getMeta( final ItemStack is ) - { - final NBTTagCompound data = is.getTagCompound(); - if( data != null ) - { - final int[] blk = data.getIntArray( "x" ); - if( blk != null && blk.length == 2 ) - { - return blk[1]; - } - } - return 0; - } + public ItemStack createFromIDs(final int[] ids) { + for (final ItemStack facadeStack : + AEApi.instance().definitions().items().facade().maybeStack(1).asSet()) { + final NBTTagCompound facadeTag = new NBTTagCompound(); + facadeTag.setIntArray("x", ids.clone()); + facadeStack.setTagCompound(facadeTag); - @Override - public Block getBlock( final ItemStack is ) - { - final NBTTagCompound data = is.getTagCompound(); - if( data != null ) - { - if( data.hasKey( "modid" ) && data.hasKey( "itemname" ) ) - { - return GameRegistry.findBlock( data.getString( "modid" ), data.getString( "itemname" ) ); - } - else - { - final int[] blk = data.getIntArray( "x" ); - if( blk != null && blk.length == 2 ) - { - return Block.getBlockById( blk[0] ); - } - } - } - return Blocks.glass; - } + return facadeStack; + } - public List getFacades() - { - this.calculateSubTypes(); - return this.subTypes; - } + throw new MissingDefinition( + "Tried to create a facade, while facades are being deactivated." + ); + } - public ItemStack getCreativeTabIcon() - { - this.calculateSubTypes(); - if( this.subTypes.isEmpty() ) - { - return new ItemStack( Items.cake ); - } - return this.subTypes.get( 0 ); - } + @Override + public boolean useAlphaPass(final ItemStack is) { + final ItemStack out = this.getTextureItem(is); - public ItemStack createFromIDs( final int[] ids ) - { - for( final ItemStack facadeStack : AEApi.instance().definitions().items().facade().maybeStack( 1 ).asSet() ) - { - final NBTTagCompound facadeTag = new NBTTagCompound(); - facadeTag.setIntArray( "x", ids.clone() ); - facadeStack.setTagCompound( facadeTag ); + if (out == null || out.getItem() == null) { + return false; + } - return facadeStack; - } - - throw new MissingDefinition( "Tried to create a facade, while facades are being deactivated." ); - } - - @Override - public boolean useAlphaPass( final ItemStack is ) - { - final ItemStack out = this.getTextureItem( is ); - - if( out == null || out.getItem() == null ) - { - return false; - } - - final Block blk = Block.getBlockFromItem( out.getItem() ); - return blk != null && blk.canRenderInPass( 1 ); - - } + final Block blk = Block.getBlockFromItem(out.getItem()); + return blk != null && blk.canRenderInPass(1); + } } diff --git a/src/main/java/appeng/items/parts/ItemMultiPart.java b/src/main/java/appeng/items/parts/ItemMultiPart.java index 5315d525..a2f2233e 100644 --- a/src/main/java/appeng/items/parts/ItemMultiPart.java +++ b/src/main/java/appeng/items/parts/ItemMultiPart.java @@ -18,6 +18,11 @@ package appeng.items.parts; +import java.lang.reflect.InvocationTargetException; +import java.util.*; +import java.util.Map.Entry; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.exceptions.MissingDefinition; @@ -46,360 +51,350 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.lang.reflect.InvocationTargetException; -import java.util.*; -import java.util.Map.Entry; +public final class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup { + private static final int INITIAL_REGISTERED_CAPACITY = PartType.values().length; + private static final Comparator> + REGISTERED_COMPARATOR = new RegisteredComparator(); + public static ItemMultiPart instance; + private final NameResolver nameResolver; + private final Map registered; -public final class ItemMultiPart extends AEBaseItem implements IPartItem, IItemGroup -{ - private static final int INITIAL_REGISTERED_CAPACITY = PartType.values().length; - private static final Comparator> REGISTERED_COMPARATOR = new RegisteredComparator(); + public ItemMultiPart(final IPartHelper partHelper) { + Preconditions.checkNotNull(partHelper); - public static ItemMultiPart instance; - private final NameResolver nameResolver; - private final Map registered; + this.registered + = new HashMap(INITIAL_REGISTERED_CAPACITY); - public ItemMultiPart( final IPartHelper partHelper ) - { - Preconditions.checkNotNull( partHelper ); + this.nameResolver = new NameResolver(this.getClass()); + this.setFeature(EnumSet.of(AEFeature.Core)); + partHelper.setItemBusRenderer(this); + this.setHasSubtypes(true); - this.registered = new HashMap( INITIAL_REGISTERED_CAPACITY ); + instance = this; + } - this.nameResolver = new NameResolver( this.getClass() ); - this.setFeature( EnumSet.of( AEFeature.Core ) ); - partHelper.setItemBusRenderer( this ); - this.setHasSubtypes( true ); + @Nonnull + public final ItemStackSrc createPart(final PartType mat) { + Preconditions.checkNotNull(mat); - instance = this; - } + return this.createPart(mat, 0); + } - @Nonnull - public final ItemStackSrc createPart( final PartType mat ) - { - Preconditions.checkNotNull( mat ); + @Nonnull + public ItemStackSrc createPart(final PartType mat, final AEColor color) { + Preconditions.checkNotNull(mat); + Preconditions.checkNotNull(color); - return this.createPart( mat, 0 ); - } + final int varID = color.ordinal(); - @Nonnull - public ItemStackSrc createPart( final PartType mat, final AEColor color ) - { - Preconditions.checkNotNull( mat ); - Preconditions.checkNotNull( color ); + return this.createPart(mat, varID); + } - final int varID = color.ordinal(); + @Nonnull + private ItemStackSrc createPart(final PartType mat, final int varID) { + assert mat != null; + assert varID >= 0; - return this.createPart( mat, varID ); - } + // verify + for (final PartTypeWithVariant p : this.registered.values()) { + if (p.part == mat && p.variant == varID) { + throw new IllegalStateException("Cannot create the same material twice..." + ); + } + } - @Nonnull - private ItemStackSrc createPart( final PartType mat, final int varID ) - { - assert mat != null; - assert varID >= 0; + boolean enabled = true; + for (final AEFeature f : mat.getFeature()) { + enabled = enabled && AEConfig.instance.isFeatureEnabled(f); + } - // verify - for( final PartTypeWithVariant p : this.registered.values() ) - { - if( p.part == mat && p.variant == varID ) - { - throw new IllegalStateException( "Cannot create the same material twice..." ); - } - } + for (final IntegrationType integrationType : mat.getIntegrations()) { + enabled &= IntegrationRegistry.INSTANCE.isEnabled(integrationType); + } - boolean enabled = true; - for( final AEFeature f : mat.getFeature() ) - { - enabled = enabled && AEConfig.instance.isFeatureEnabled( f ); - } + final int partDamage = mat.getBaseDamage() + varID; + final ActivityState state = ActivityState.from(enabled); + final ItemStackSrc output = new ItemStackSrc(this, partDamage, state); - for( final IntegrationType integrationType : mat.getIntegrations() ) - { - enabled &= IntegrationRegistry.INSTANCE.isEnabled( integrationType ); - } + final PartTypeWithVariant pti = new PartTypeWithVariant(mat, varID); - final int partDamage = mat.getBaseDamage() + varID; - final ActivityState state = ActivityState.from( enabled ); - final ItemStackSrc output = new ItemStackSrc( this, partDamage, state ); + this.processMetaOverlap(enabled, partDamage, mat, pti); - final PartTypeWithVariant pti = new PartTypeWithVariant( mat, varID ); + return output; + } - this.processMetaOverlap( enabled, partDamage, mat, pti ); + private void processMetaOverlap( + final boolean enabled, + final int partDamage, + final PartType mat, + final PartTypeWithVariant pti + ) { + assert partDamage >= 0; + assert mat != null; + assert pti != null; - return output; - } + final PartTypeWithVariant registeredPartType = this.registered.get(partDamage); + if (registeredPartType != null) { + throw new IllegalStateException( + "Meta Overlap detected with type " + mat + " and damage " + partDamage + + ". Found " + registeredPartType + " there already." + ); + } - private void processMetaOverlap( final boolean enabled, final int partDamage, final PartType mat, final PartTypeWithVariant pti ) - { - assert partDamage >= 0; - assert mat != null; - assert pti != null; + if (enabled) { + this.registered.put(partDamage, pti); + } + } - final PartTypeWithVariant registeredPartType = this.registered.get( partDamage ); - if( registeredPartType != null ) - { - throw new IllegalStateException( "Meta Overlap detected with type " + mat + " and damage " + partDamage + ". Found " + registeredPartType + " there already." ); - } + public int getDamageByType(final PartType t) { + Preconditions.checkNotNull(t); - if( enabled ) - { - this.registered.put( partDamage, pti ); - } - } + for (final Entry pt : this.registered.entrySet()) { + if (pt.getValue().part == t) { + return pt.getKey(); + } + } + return -1; + } - public int getDamageByType( final PartType t ) - { - Preconditions.checkNotNull( t ); + @Override + @SideOnly(Side.CLIENT) + public int getSpriteNumber() { + return 0; + } - for( final Entry pt : this.registered.entrySet() ) - { - if( pt.getValue().part == t ) - { - return pt.getKey(); - } - } - return -1; - } + @Override + public IIcon getIconFromDamage(final int dmg) { + final PartTypeWithVariant registeredType = this.registered.get(dmg); + if (registeredType != null) { + return registeredType.ico; + } - @Override - @SideOnly( Side.CLIENT ) - public int getSpriteNumber() - { - return 0; - } + final String formattedRegistered + = Arrays.toString(this.registered.keySet().toArray()); + throw new MissingDefinition( + "Tried to get the icon from a non-existent part with damage value " + dmg + + ". There were registered: " + formattedRegistered + '.' + ); + } - @Override - public IIcon getIconFromDamage( final int dmg ) - { - final PartTypeWithVariant registeredType = this.registered.get( dmg ); - if( registeredType != null ) - { - return registeredType.ico; - } + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (this.getTypeByStack(is) == PartType.InvalidType) { + return false; + } - final String formattedRegistered = Arrays.toString( this.registered.keySet().toArray() ); - throw new MissingDefinition( "Tried to get the icon from a non-existent part with damage value " + dmg + ". There were registered: " + formattedRegistered + '.' ); - } + return AEApi.instance().partHelper().placeBus(is, x, y, z, side, player, w); + } - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( this.getTypeByStack( is ) == PartType.InvalidType ) - { - return false; - } + @Override + public String getUnlocalizedName(final ItemStack is) { + return "item.appliedenergistics2." + this.getName(is); + } - return AEApi.instance().partHelper().placeBus( is, x, y, z, side, player, w ); - } + @Override + public String getItemStackDisplayName(final ItemStack is) { + final PartType pt = this.getTypeByStack(is); - @Override - public String getUnlocalizedName( final ItemStack is ) - { - return "item.appliedenergistics2." + this.getName( is ); - } + if (pt.isCable()) { + final AEColor[] variants = AEColor.values(); - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - final PartType pt = this.getTypeByStack( is ); + final int itemDamage = is.getItemDamage(); + final PartTypeWithVariant registeredPartType + = this.registered.get(itemDamage); + if (registeredPartType != null) { + return super.getItemStackDisplayName(is) + " - " + + variants[registeredPartType.variant].toString(); + } + } - if( pt.isCable() ) - { - final AEColor[] variants = AEColor.values(); + if (pt.getExtraName() != null) { + return super.getItemStackDisplayName(is) + " - " + + pt.getExtraName().getLocal(); + } - final int itemDamage = is.getItemDamage(); - final PartTypeWithVariant registeredPartType = this.registered.get( itemDamage ); - if( registeredPartType != null ) - { - return super.getItemStackDisplayName( is ) + " - " + variants[registeredPartType.variant].toString(); - } - } + return super.getItemStackDisplayName(is); + } - if( pt.getExtraName() != null ) - { - return super.getItemStackDisplayName( is ) + " - " + pt.getExtraName().getLocal(); - } + @Override + public void registerIcons(final IIconRegister iconRegister) { + for (final Entry part : + this.registered.entrySet()) { + final String tex = "appliedenergistics2:" + + this.getName(new ItemStack(this, 1, part.getKey())); + part.getValue().ico = iconRegister.registerIcon(tex); + } + } - return super.getItemStackDisplayName( is ); - } + @Override + protected void getCheckedSubItems( + final Item sameItem, + final CreativeTabs creativeTab, + final List itemStacks + ) { + final List> types + = new ArrayList>(this.registered.entrySet( + )); + Collections.sort(types, REGISTERED_COMPARATOR); - @Override - public void registerIcons( final IIconRegister iconRegister ) - { - for( final Entry part : this.registered.entrySet() ) - { - final String tex = "appliedenergistics2:" + this.getName( new ItemStack( this, 1, part.getKey() ) ); - part.getValue().ico = iconRegister.registerIcon( tex ); - } - } + for (final Entry part : types) { + itemStacks.add(new ItemStack(this, 1, part.getKey())); + } + } - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - final List> types = new ArrayList>( this.registered.entrySet() ); - Collections.sort( types, REGISTERED_COMPARATOR ); + private String getName(final ItemStack is) { + Preconditions.checkNotNull(is); - for( final Entry part : types ) - { - itemStacks.add( new ItemStack( this, 1, part.getKey() ) ); - } - } + final PartType stackType = this.getTypeByStack(is); + final String typeName = stackType.name(); - private String getName( final ItemStack is ) - { - Preconditions.checkNotNull( is ); + return this.nameResolver.getName(typeName); + } - final PartType stackType = this.getTypeByStack( is ); - final String typeName = stackType.name(); + @Nonnull + public PartType getTypeByStack(final ItemStack is) { + Preconditions.checkNotNull(is); - return this.nameResolver.getName( typeName ); - } + final PartTypeWithVariant pt = this.registered.get(is.getItemDamage()); + if (pt != null) { + return pt.part; + } - @Nonnull - public PartType getTypeByStack( final ItemStack is ) - { - Preconditions.checkNotNull( is ); + return PartType.InvalidType; + } - final PartTypeWithVariant pt = this.registered.get( is.getItemDamage() ); - if( pt != null ) - { - return pt.part; - } + @Nullable + @Override + public IPart createPartFromItemStack(final ItemStack is) { + final PartType type = this.getTypeByStack(is); + final Class part = type.getPart(); + if (part == null) { + return null; + } - return PartType.InvalidType; - } + try { + if (type.getConstructor() == null) { + type.setConstructor(part.getConstructor(ItemStack.class)); + } - @Nullable - @Override - public IPart createPartFromItemStack( final ItemStack is ) - { - final PartType type = this.getTypeByStack( is ); - final Class part = type.getPart(); - if( part == null ) - { - return null; - } + return type.getConstructor().newInstance(is); + } catch (final InstantiationException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e + ); + } catch (final IllegalAccessException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e + ); + } catch (final InvocationTargetException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e + ); + } catch (final NoSuchMethodException e) { + throw new IllegalStateException( + "Unable to construct IBusPart from IBusItem : " + part.getName() + + " ; Possibly didn't have correct constructor( ItemStack )", + e + ); + } + } - try - { - if( type.getConstructor() == null ) - { - type.setConstructor( part.getConstructor( ItemStack.class ) ); - } + public int variantOf(final int itemDamage) { + final PartTypeWithVariant registeredPartType = this.registered.get(itemDamage); + if (registeredPartType != null) { + return registeredPartType.variant; + } - return type.getConstructor().newInstance( is ); - } - catch( final InstantiationException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - catch( final NoSuchMethodException e ) - { - throw new IllegalStateException( "Unable to construct IBusPart from IBusItem : " + part.getName() + " ; Possibly didn't have correct constructor( ItemStack )", e ); - } - } + return 0; + } - public int variantOf( final int itemDamage ) - { - final PartTypeWithVariant registeredPartType = this.registered.get( itemDamage ); - if( registeredPartType != null ) - { - return registeredPartType.variant; - } + @Nullable + @Override + public String + getUnlocalizedGroupName(final Set others, final ItemStack is) { + boolean importBus = false; + boolean exportBus = false; + boolean group = false; - return 0; - } + final PartType u = this.getTypeByStack(is); - @Nullable - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - boolean importBus = false; - boolean exportBus = false; - boolean group = false; + for (final ItemStack stack : others) { + if (stack.getItem() == this) { + final PartType pt = this.getTypeByStack(stack); + switch (pt) { + case ImportBus: + importBus = true; + if (u == pt) { + group = true; + } + break; + case ExportBus: + exportBus = true; + if (u == pt) { + group = true; + } + break; + default: + } + } + } - final PartType u = this.getTypeByStack( is ); + if (group && importBus && exportBus) { + return GuiText.IOBuses.getUnlocalized(); + } - for( final ItemStack stack : others ) - { - if( stack.getItem() == this ) - { - final PartType pt = this.getTypeByStack( stack ); - switch( pt ) - { - case ImportBus: - importBus = true; - if( u == pt ) - { - group = true; - } - break; - case ExportBus: - exportBus = true; - if( u == pt ) - { - group = true; - } - break; - default: - } - } - } + return null; + } - if( group && importBus && exportBus ) - { - return GuiText.IOBuses.getUnlocalized(); - } + private static final class PartTypeWithVariant { + private final PartType part; + private final int variant; - return null; - } + @SideOnly(Side.CLIENT) + private IIcon ico; - private static final class PartTypeWithVariant - { - private final PartType part; - private final int variant; + private PartTypeWithVariant(final PartType part, final int variant) { + assert part != null; + assert variant >= 0; - @SideOnly( Side.CLIENT ) - private IIcon ico; + this.part = part; + this.variant = variant; + } - private PartTypeWithVariant( final PartType part, final int variant ) - { - assert part != null; - assert variant >= 0; + @Override + public String toString() { + return "PartTypeWithVariant{" + + "part=" + this.part + ", variant=" + this.variant + ", ico=" + this.ico + + '}'; + } + } - this.part = part; - this.variant = variant; - } - - @Override - public String toString() - { - return "PartTypeWithVariant{" + - "part=" + this.part + - ", variant=" + this.variant + - ", ico=" + this.ico + - '}'; - } - } - - - private static final class RegisteredComparator implements Comparator> - { - @Override - public int compare( final Entry o1, final Entry o2 ) - { - return o1.getValue().part.name().compareTo( o2.getValue().part.name() ); - } - } + private static final class RegisteredComparator + implements Comparator> { + @Override + public int compare( + final Entry o1, + final Entry o2 + ) { + return o1.getValue().part.name().compareTo(o2.getValue().part.name()); + } + } } diff --git a/src/main/java/appeng/items/parts/PartType.java b/src/main/java/appeng/items/parts/PartType.java index 44e3df93..1854a4e2 100644 --- a/src/main/java/appeng/items/parts/PartType.java +++ b/src/main/java/appeng/items/parts/PartType.java @@ -18,6 +18,10 @@ package appeng.items.parts; +import java.lang.reflect.Constructor; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; import appeng.api.parts.IPart; import appeng.core.features.AEFeature; @@ -29,171 +33,337 @@ import appeng.parts.networking.*; import appeng.parts.p2p.*; import appeng.parts.reporting.*; -import java.lang.reflect.Constructor; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Set; +public enum PartType { + InvalidType( + -1, EnumSet.of(AEFeature.Core), EnumSet.noneOf(IntegrationType.class), null + ), + CableGlass( + 0, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartCableGlass.class + ) { + @Override + public boolean isCable() { + return true; + } + }, -public enum PartType -{ - InvalidType( -1, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), null ), + CableCovered( + 20, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartCableCovered.class + ) { + @Override + public boolean isCable() { + return true; + } + }, - CableGlass( 0, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartCableGlass.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, + CableSmart( + 40, + EnumSet.of(AEFeature.Channels), + EnumSet.noneOf(IntegrationType.class), + PartCableSmart.class + ) { + @Override + public boolean isCable() { + return true; + } + }, - CableCovered( 20, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartCableCovered.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, + CableDense( + 60, + EnumSet.of(AEFeature.Channels), + EnumSet.noneOf(IntegrationType.class), + PartDenseCable.class + ) { + @Override + public boolean isCable() { + return true; + } + }, - CableSmart( 40, EnumSet.of( AEFeature.Channels ), EnumSet.noneOf( IntegrationType.class ), PartCableSmart.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, + ToggleBus( + 80, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartToggleBus.class + ), - CableDense( 60, EnumSet.of( AEFeature.Channels ), EnumSet.noneOf( IntegrationType.class ), PartDenseCable.class ) - { - @Override - public boolean isCable() - { - return true; - } - }, + InvertedToggleBus( + 100, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartInvertedToggleBus.class + ), - ToggleBus( 80, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartToggleBus.class ), + CableAnchor( + 120, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartCableAnchor.class + ), - InvertedToggleBus( 100, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartInvertedToggleBus.class ), + QuartzFiber( + 140, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartQuartzFiber.class + ), - CableAnchor( 120, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartCableAnchor.class ), + Monitor( + 160, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartPanel.class + ), - QuartzFiber( 140, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartQuartzFiber.class ), + SemiDarkMonitor( + 180, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartSemiDarkPanel.class + ), - Monitor( 160, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartPanel.class ), + DarkMonitor( + 200, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartDarkPanel.class + ), - SemiDarkMonitor( 180, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartSemiDarkPanel.class ), + StorageBus( + 220, + EnumSet.of(AEFeature.StorageBus), + EnumSet.noneOf(IntegrationType.class), + PartStorageBus.class + ), - DarkMonitor( 200, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartDarkPanel.class ), + ImportBus( + 240, + EnumSet.of(AEFeature.ImportBus), + EnumSet.noneOf(IntegrationType.class), + PartImportBus.class + ), - StorageBus( 220, EnumSet.of( AEFeature.StorageBus ), EnumSet.noneOf( IntegrationType.class ), PartStorageBus.class ), + ExportBus( + 260, + EnumSet.of(AEFeature.ExportBus), + EnumSet.noneOf(IntegrationType.class), + PartExportBus.class + ), - ImportBus( 240, EnumSet.of( AEFeature.ImportBus ), EnumSet.noneOf( IntegrationType.class ), PartImportBus.class ), + LevelEmitter( + 280, + EnumSet.of(AEFeature.LevelEmitter), + EnumSet.noneOf(IntegrationType.class), + PartLevelEmitter.class + ), - ExportBus( 260, EnumSet.of( AEFeature.ExportBus ), EnumSet.noneOf( IntegrationType.class ), PartExportBus.class ), + AnnihilationPlane( + 300, + EnumSet.of(AEFeature.AnnihilationPlane), + EnumSet.noneOf(IntegrationType.class), + PartAnnihilationPlane.class + ), - LevelEmitter( 280, EnumSet.of( AEFeature.LevelEmitter ), EnumSet.noneOf( IntegrationType.class ), PartLevelEmitter.class ), + IdentityAnnihilationPlane( + 301, + EnumSet.of(AEFeature.AnnihilationPlane, AEFeature.IdentityAnnihilationPlane), + EnumSet.noneOf(IntegrationType.class), + PartIdentityAnnihilationPlane.class + ), - AnnihilationPlane( 300, EnumSet.of( AEFeature.AnnihilationPlane ), EnumSet.noneOf( IntegrationType.class ), PartAnnihilationPlane.class ), + FormationPlane( + 320, + EnumSet.of(AEFeature.FormationPlane), + EnumSet.noneOf(IntegrationType.class), + PartFormationPlane.class + ), - IdentityAnnihilationPlane( 301, EnumSet.of( AEFeature.AnnihilationPlane, AEFeature.IdentityAnnihilationPlane ), EnumSet.noneOf( IntegrationType.class ), PartIdentityAnnihilationPlane.class ), + PatternTerminal( + 340, + EnumSet.of(AEFeature.Patterns), + EnumSet.noneOf(IntegrationType.class), + PartPatternTerminal.class + ), - FormationPlane( 320, EnumSet.of( AEFeature.FormationPlane ), EnumSet.noneOf( IntegrationType.class ), PartFormationPlane.class ), + CraftingTerminal( + 360, + EnumSet.of(AEFeature.CraftingTerminal), + EnumSet.noneOf(IntegrationType.class), + PartCraftingTerminal.class + ), - PatternTerminal( 340, EnumSet.of( AEFeature.Patterns ), EnumSet.noneOf( IntegrationType.class ), PartPatternTerminal.class ), + Terminal( + 380, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartTerminal.class + ), - CraftingTerminal( 360, EnumSet.of( AEFeature.CraftingTerminal ), EnumSet.noneOf( IntegrationType.class ), PartCraftingTerminal.class ), + StorageMonitor( + 400, + EnumSet.of(AEFeature.StorageMonitor), + EnumSet.noneOf(IntegrationType.class), + PartStorageMonitor.class + ), - Terminal( 380, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartTerminal.class ), + ConversionMonitor( + 420, + EnumSet.of(AEFeature.PartConversionMonitor), + EnumSet.noneOf(IntegrationType.class), + PartConversionMonitor.class + ), - StorageMonitor( 400, EnumSet.of( AEFeature.StorageMonitor ), EnumSet.noneOf( IntegrationType.class ), PartStorageMonitor.class ), + Interface( + 440, + EnumSet.of(AEFeature.Core), + EnumSet.noneOf(IntegrationType.class), + PartInterface.class + ), - ConversionMonitor( 420, EnumSet.of( AEFeature.PartConversionMonitor ), EnumSet.noneOf( IntegrationType.class ), PartConversionMonitor.class ), + P2PTunnelME( + 460, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelME), + EnumSet.noneOf(IntegrationType.class), + PartP2PTunnelME.class, + GuiText.METunnel + ), - Interface( 440, EnumSet.of( AEFeature.Core ), EnumSet.noneOf( IntegrationType.class ), PartInterface.class ), + P2PTunnelRedstone( + 461, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelRedstone), + EnumSet.noneOf(IntegrationType.class), + PartP2PRedstone.class, + GuiText.RedstoneTunnel + ), - P2PTunnelME( 460, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelME ), EnumSet.noneOf( IntegrationType.class ), PartP2PTunnelME.class, GuiText.METunnel ), + P2PTunnelItems( + 462, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelItems), + EnumSet.noneOf(IntegrationType.class), + PartP2PItems.class, + GuiText.ItemTunnel + ), - P2PTunnelRedstone( 461, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelRedstone ), EnumSet.noneOf( IntegrationType.class ), PartP2PRedstone.class, GuiText.RedstoneTunnel ), + P2PTunnelLiquids( + 463, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelLiquids), + EnumSet.noneOf(IntegrationType.class), + PartP2PLiquids.class, + GuiText.FluidTunnel + ), - P2PTunnelItems( 462, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelItems ), EnumSet.noneOf( IntegrationType.class ), PartP2PItems.class, GuiText.ItemTunnel ), + P2PTunnelEU( + 465, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelEU), + EnumSet.of(IntegrationType.IC2), + PartP2PIC2Power.class, + GuiText.EUTunnel + ), - P2PTunnelLiquids( 463, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelLiquids ), EnumSet.noneOf( IntegrationType.class ), PartP2PLiquids.class, GuiText.FluidTunnel ), + P2PTunnelRF( + 466, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelRF), + EnumSet.of(IntegrationType.RF), + PartP2PRFPower.class, + GuiText.RFTunnel + ), - P2PTunnelEU( 465, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelEU ), EnumSet.of( IntegrationType.IC2 ), PartP2PIC2Power.class, GuiText.EUTunnel ), + P2PTunnelLight( + 467, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelLight), + EnumSet.noneOf(IntegrationType.class), + PartP2PLight.class, + GuiText.LightTunnel + ), - P2PTunnelRF( 466, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelRF ), EnumSet.of( IntegrationType.RF ), PartP2PRFPower.class, GuiText.RFTunnel ), + P2PTunnelOpenComputers( + 468, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelOpenComputers), + EnumSet.of(IntegrationType.OpenComputers), + PartP2POpenComputers.class, + GuiText.OCTunnel + ), - P2PTunnelLight( 467, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelLight ), EnumSet.noneOf( IntegrationType.class ), PartP2PLight.class, GuiText.LightTunnel ), + P2PTunnelPressure( + 469, + EnumSet.of(AEFeature.P2PTunnel, AEFeature.P2PTunnelPressure), + EnumSet.of(IntegrationType.PneumaticCraft), + PartP2PPressure.class, + GuiText.PressureTunnel + ), - P2PTunnelOpenComputers( 468, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelOpenComputers ), EnumSet.of( IntegrationType.OpenComputers ), PartP2POpenComputers.class, GuiText.OCTunnel ), + InterfaceTerminal( + 480, + EnumSet.of(AEFeature.InterfaceTerminal), + EnumSet.noneOf(IntegrationType.class), + PartInterfaceTerminal.class + ); - P2PTunnelPressure( 469, EnumSet.of( AEFeature.P2PTunnel, AEFeature.P2PTunnelPressure ), EnumSet.of( IntegrationType.PneumaticCraft ), PartP2PPressure.class, GuiText.PressureTunnel ), + private final int baseDamage; + private final Set features; + private final Set integrations; + private final Class myPart; + private final GuiText extraName; + private Constructor constructor; - InterfaceTerminal( 480, EnumSet.of( AEFeature.InterfaceTerminal ), EnumSet.noneOf( IntegrationType.class ), PartInterfaceTerminal.class ); + PartType( + final int baseMetaValue, + final Set features, + final Set integrations, + final Class c + ) { + this(baseMetaValue, features, integrations, c, null); + } - private final int baseDamage; - private final Set features; - private final Set integrations; - private final Class myPart; - private final GuiText extraName; - private Constructor constructor; + PartType( + final int baseMetaValue, + final Set features, + final Set integrations, + final Class c, + final GuiText en + ) { + this.features = Collections.unmodifiableSet(features); + this.integrations = Collections.unmodifiableSet(integrations); + this.myPart = c; + this.extraName = en; + this.baseDamage = baseMetaValue; + } - PartType( final int baseMetaValue, final Set features, final Set integrations, final Class c ) - { - this( baseMetaValue, features, integrations, c, null ); - } + public boolean isCable() { + return false; + } - PartType( final int baseMetaValue, final Set features, final Set integrations, final Class c, final GuiText en ) - { - this.features = Collections.unmodifiableSet( features ); - this.integrations = Collections.unmodifiableSet( integrations ); - this.myPart = c; - this.extraName = en; - this.baseDamage = baseMetaValue; - } + Set getFeature() { + return this.features; + } - public boolean isCable() - { - return false; - } + Set getIntegrations() { + return this.integrations; + } - Set getFeature() - { - return this.features; - } + Class getPart() { + return this.myPart; + } - Set getIntegrations() - { - return this.integrations; - } + GuiText getExtraName() { + return this.extraName; + } - Class getPart() - { - return this.myPart; - } + Constructor getConstructor() { + return this.constructor; + } - GuiText getExtraName() - { - return this.extraName; - } - - Constructor getConstructor() - { - return this.constructor; - } - - void setConstructor( final Constructor constructor ) - { - this.constructor = constructor; - } - - int getBaseDamage() - { - return this.baseDamage; - } + void setConstructor(final Constructor constructor) { + this.constructor = constructor; + } + int getBaseDamage() { + return this.baseDamage; + } } diff --git a/src/main/java/appeng/items/storage/ItemBasicStorageCell.java b/src/main/java/appeng/items/storage/ItemBasicStorageCell.java index 1049d8b8..53a2322e 100644 --- a/src/main/java/appeng/items/storage/ItemBasicStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemBasicStorageCell.java @@ -18,6 +18,9 @@ package appeng.items.storage; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; import appeng.api.AEApi; import appeng.api.config.FuzzyMode; @@ -39,6 +42,7 @@ import appeng.items.AEBaseItem; import appeng.items.contents.CellConfig; import appeng.items.contents.CellUpgrades; import appeng.items.materials.MaterialType; +import appeng.me.storage.CellInventory; import appeng.util.InventoryAdaptor; import appeng.util.Platform; import com.google.common.base.Optional; @@ -49,268 +53,284 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import appeng.me.storage.CellInventory; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; +public final class ItemBasicStorageCell + extends AEBaseItem implements IStorageCell, IItemGroup { + private final MaterialType component; + private final int totalBytes; + private final int perType; + private final double idleDrain; + public ItemBasicStorageCell(final MaterialType whichCell, final int kilobytes) { + super(Optional.of(kilobytes + "k")); -public final class ItemBasicStorageCell extends AEBaseItem implements IStorageCell, IItemGroup -{ - private final MaterialType component; - private final int totalBytes; - private final int perType; - private final double idleDrain; + this.setFeature(EnumSet.of(AEFeature.StorageCells)); + this.setMaxStackSize(1); + this.totalBytes = kilobytes * 1024; + this.component = whichCell; - public ItemBasicStorageCell( final MaterialType whichCell, final int kilobytes ) - { - super( Optional.of( kilobytes + "k" ) ); + switch (this.component) { + case Cell1kPart: + this.idleDrain = 0.5; + this.perType = 8; + break; + case Cell4kPart: + this.idleDrain = 1.0; + this.perType = 32; + break; + case Cell16kPart: + this.idleDrain = 1.5; + this.perType = 128; + break; + case Cell64kPart: + this.idleDrain = 2.0; + this.perType = 512; + break; + default: + this.idleDrain = 0.0; + this.perType = 8; + } + } - this.setFeature( EnumSet.of( AEFeature.StorageCells ) ); - this.setMaxStackSize( 1 ); - this.totalBytes = kilobytes * 1024; - this.component = whichCell; + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + final IMEInventoryHandler inventory + = AEApi.instance().registries().cell().getCellInventory( + stack, null, StorageChannel.ITEMS + ); - switch( this.component ) - { - case Cell1kPart: - this.idleDrain = 0.5; - this.perType = 8; - break; - case Cell4kPart: - this.idleDrain = 1.0; - this.perType = 32; - break; - case Cell16kPart: - this.idleDrain = 1.5; - this.perType = 128; - break; - case Cell64kPart: - this.idleDrain = 2.0; - this.perType = 512; - break; - default: - this.idleDrain = 0.0; - this.perType = 8; - } - } + if (inventory instanceof ICellInventoryHandler) { + final ICellInventoryHandler handler = (ICellInventoryHandler) inventory; + final ICellInventory cellInventory = handler.getCellInv(); - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final IMEInventoryHandler inventory = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); + if (cellInventory != null) { + lines.add( + cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + + cellInventory.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() + ); - if( inventory instanceof ICellInventoryHandler ) - { - final ICellInventoryHandler handler = (ICellInventoryHandler) inventory; - final ICellInventory cellInventory = handler.getCellInv(); + lines.add( + cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + + cellInventory.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() + ); - if( cellInventory != null ) - { - lines.add( cellInventory.getUsedBytes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalBytes() + ' ' + GuiText.BytesUsed.getLocal() ); + if (handler.isPreformatted()) { + final String list + = (handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST + ? GuiText.Included + : GuiText.Excluded) + .getLocal(); - lines.add( cellInventory.getStoredItemTypes() + " " + GuiText.Of.getLocal() + ' ' + cellInventory.getTotalItemTypes() + ' ' + GuiText.Types.getLocal() ); + if (handler.isFuzzy()) { + lines.add( + GuiText.Partitioned.getLocal() + " - " + list + ' ' + + GuiText.Fuzzy.getLocal() + ); + } else { + lines.add( + GuiText.Partitioned.getLocal() + " - " + list + ' ' + + GuiText.Precise.getLocal() + ); + } + } + } + } + } - if( handler.isPreformatted() ) - { - final String list = ( handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST ? GuiText.Included : GuiText.Excluded ).getLocal(); + @Override + public int getBytes(final ItemStack cellItem) { + return this.totalBytes; + } - if( handler.isFuzzy() ) - { - lines.add( GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Fuzzy.getLocal() ); - } - else - { - lines.add( GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Precise.getLocal() ); - } - } - } - } - } + @Override + public int BytePerType(final ItemStack cell) { + return this.perType; + } - @Override - public int getBytes( final ItemStack cellItem ) - { - return this.totalBytes; - } + @Override + public int getBytesPerType(final ItemStack cellItem) { + return this.perType; + } - @Override - public int BytePerType( final ItemStack cell ) - { - return this.perType; - } + @Override + public int getTotalTypes(final ItemStack cellItem) { + return CellInventory.cellItemType; + } - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return this.perType; - } + @Override + public boolean + isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + return false; + } - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return CellInventory.cellItemType; - } + @Override + public boolean storableInStorageCell() { + return false; + } - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - return false; - } + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } - @Override - public boolean storableInStorageCell() - { - return false; - } + @Override + public double getIdleDrain() { + return this.idleDrain; + } - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } + @Override + public String + getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } - @Override - public double getIdleDrain() - { - return this.idleDrain; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } + @Override + public ItemStack onItemRightClick( + final ItemStack stack, final World world, final EntityPlayer player + ) { + this.disassembleDrive(stack, world, player); + return stack; + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } + private boolean disassembleDrive( + final ItemStack stack, final World world, final EntityPlayer player + ) { + if (player.isSneaking()) { + if (Platform.isClient()) { + return false; + } - @Override - public ItemStack onItemRightClick( final ItemStack stack, final World world, final EntityPlayer player ) - { - this.disassembleDrive( stack, world, player ); - return stack; - } + final InventoryPlayer playerInventory = player.inventory; + final IMEInventoryHandler inv + = AEApi.instance().registries().cell().getCellInventory( + stack, null, StorageChannel.ITEMS + ); + if (inv != null && playerInventory.getCurrentItem() == stack) { + final InventoryAdaptor ia + = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + final IItemList list + = inv.getAvailableItems(StorageChannel.ITEMS.createList()); + if (list.isEmpty() && ia != null) { + playerInventory.setInventorySlotContents( + playerInventory.currentItem, null + ); - private boolean disassembleDrive( final ItemStack stack, final World world, final EntityPlayer player ) - { - if( player.isSneaking() ) - { - if( Platform.isClient() ) - { - return false; - } + // drop core + final ItemStack extraB = ia.addItems(this.component.stack(1)); + if (extraB != null) { + player.dropPlayerItemWithRandomChoice(extraB, false); + } - final InventoryPlayer playerInventory = player.inventory; - final IMEInventoryHandler inv = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - if( inv != null && playerInventory.getCurrentItem() == stack ) - { - final InventoryAdaptor ia = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - final IItemList list = inv.getAvailableItems( StorageChannel.ITEMS.createList() ); - if( list.isEmpty() && ia != null ) - { - playerInventory.setInventorySlotContents( playerInventory.currentItem, null ); + // drop upgrades + final IInventory upgradesInventory = this.getUpgradesInventory(stack); + for (int upgradeIndex = 0; + upgradeIndex < upgradesInventory.getSizeInventory(); + upgradeIndex++) { + final ItemStack upgradeStack + = upgradesInventory.getStackInSlot(upgradeIndex); + final ItemStack leftStack = ia.addItems(upgradeStack); + if (leftStack != null + && upgradeStack.getItem() instanceof IUpgradeModule) { + player.dropPlayerItemWithRandomChoice(upgradeStack, false); + } + } - // drop core - final ItemStack extraB = ia.addItems( this.component.stack( 1 ) ); - if( extraB != null ) - { - player.dropPlayerItemWithRandomChoice( extraB, false ); - } + // drop empty storage cell case + for (final ItemStack storageCellStack : AEApi.instance() + .definitions() + .materials() + .emptyStorageCell() + .maybeStack(1) + .asSet()) { + final ItemStack extraA = ia.addItems(storageCellStack); + if (extraA != null) { + player.dropPlayerItemWithRandomChoice(extraA, false); + } + } - // drop upgrades - final IInventory upgradesInventory = this.getUpgradesInventory( stack ); - for( int upgradeIndex = 0; upgradeIndex < upgradesInventory.getSizeInventory(); upgradeIndex++ ) - { - final ItemStack upgradeStack = upgradesInventory.getStackInSlot( upgradeIndex ); - final ItemStack leftStack = ia.addItems( upgradeStack ); - if( leftStack != null && upgradeStack.getItem() instanceof IUpgradeModule ) - { - player.dropPlayerItemWithRandomChoice( upgradeStack, false ); - } - } + if (player.inventoryContainer != null) { + player.inventoryContainer.detectAndSendChanges(); + } - // drop empty storage cell case - for( final ItemStack storageCellStack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) - { - final ItemStack extraA = ia.addItems( storageCellStack ); - if( extraA != null ) - { - player.dropPlayerItemWithRandomChoice( extraA, false ); - } - } + return true; + } + } + } + return false; + } - if( player.inventoryContainer != null ) - { - player.inventoryContainer.detectAndSendChanges(); - } + @Override + public boolean onItemUseFirst( + final ItemStack stack, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, stack, 1) <= 0) + return true; - return true; - } - } - } - return false; - } + return this.disassembleDrive(stack, world, player); + } - @Override - public boolean onItemUseFirst( final ItemStack stack, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, stack, 1 ) <= 0 ) - return true; + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + for (final ItemStack stack : AEApi.instance() + .definitions() + .materials() + .emptyStorageCell() + .maybeStack(1) + .asSet()) { + return stack; + } - return this.disassembleDrive( stack, world, player ); - } + throw new MissingDefinition( + "Tried to use empty storage cells while basic storage cells are defined." + ); + } - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - for( final ItemStack stack : AEApi.instance().definitions().materials().emptyStorageCell().maybeStack( 1 ).asSet() ) - { - return stack; - } - - throw new MissingDefinition( "Tried to use empty storage cells while basic storage cells are defined." ); - } - - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return AEConfig.instance.isFeatureEnabled( AEFeature.EnableDisassemblyCrafting ); - } + @Override + public boolean hasContainerItem(final ItemStack stack) { + return AEConfig.instance.isFeatureEnabled(AEFeature.EnableDisassemblyCrafting); + } } diff --git a/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java b/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java index 3432ba85..0f637240 100644 --- a/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemCreativeStorageCell.java @@ -18,6 +18,7 @@ package appeng.items.storage; +import java.util.EnumSet; import appeng.api.config.FuzzyMode; import appeng.api.storage.ICellWorkbenchItem; @@ -27,45 +28,32 @@ import appeng.items.contents.CellConfig; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.EnumSet; +public class ItemCreativeStorageCell extends AEBaseItem implements ICellWorkbenchItem { + public ItemCreativeStorageCell() { + this.setFeature(EnumSet.of(AEFeature.StorageCells, AEFeature.Creative)); + this.setMaxStackSize(1); + } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } -public class ItemCreativeStorageCell extends AEBaseItem implements ICellWorkbenchItem -{ + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return null; + } - public ItemCreativeStorageCell() - { - this.setFeature( EnumSet.of( AEFeature.StorageCells, AEFeature.Creative ) ); - this.setMaxStackSize( 1 ); - } + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + return FuzzyMode.IGNORE_ALL; + } - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return null; - } - - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - return FuzzyMode.IGNORE_ALL; - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) {} } diff --git a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java index f17102b7..6cd975a0 100644 --- a/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java +++ b/src/main/java/appeng/items/storage/ItemSpatialStorageCell.java @@ -18,6 +18,8 @@ package appeng.items.storage; +import java.util.EnumSet; +import java.util.List; import appeng.api.implementations.TransitionResult; import appeng.api.implementations.items.ISpatialStorageCell; @@ -36,170 +38,179 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; -import java.util.EnumSet; -import java.util.List; +public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorageCell { + private final int maxRegion; + public ItemSpatialStorageCell(final int spatialScale) { + super(Optional.of(spatialScale + "Cubed")); + this.setFeature(EnumSet.of(AEFeature.SpatialIO)); + this.setMaxStackSize(1); + this.maxRegion = spatialScale; + } -public class ItemSpatialStorageCell extends AEBaseItem implements ISpatialStorageCell -{ - private final int maxRegion; + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + final WorldCoord wc = this.getStoredSize(stack); + if (wc.x > 0) { + lines.add( + GuiText.StoredSize.getLocal() + ": " + wc.x + " x " + wc.y + " x " + wc.z + ); + } + } - public ItemSpatialStorageCell( final int spatialScale ) - { - super( Optional.of( spatialScale + "Cubed" ) ); - this.setFeature( EnumSet.of( AEFeature.SpatialIO ) ); - this.setMaxStackSize( 1 ); - this.maxRegion = spatialScale; - } + @Override + public boolean isSpatialStorage(final ItemStack is) { + return true; + } - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final WorldCoord wc = this.getStoredSize( stack ); - if( wc.x > 0 ) - { - lines.add( GuiText.StoredSize.getLocal() + ": " + wc.x + " x " + wc.y + " x " + wc.z ); - } - } + @Override + public int getMaxStoredDim(final ItemStack is) { + return this.maxRegion; + } - @Override - public boolean isSpatialStorage( final ItemStack is ) - { - return true; - } + @Override + public World getWorld(final ItemStack is) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + final int dim = c.getInteger("StorageDim"); + World w = DimensionManager.getWorld(dim); + if (w == null) { + DimensionManager.initDimension(dim); + w = DimensionManager.getWorld(dim); + } - @Override - public int getMaxStoredDim( final ItemStack is ) - { - return this.maxRegion; - } + if (w != null) { + if (w.provider instanceof StorageWorldProvider) { + return w; + } + } + } + return null; + } - @Override - public World getWorld( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - final int dim = c.getInteger( "StorageDim" ); - World w = DimensionManager.getWorld( dim ); - if( w == null ) - { - DimensionManager.initDimension( dim ); - w = DimensionManager.getWorld( dim ); - } + @Override + public WorldCoord getStoredSize(final ItemStack is) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + if (Platform.isServer()) { + final int dim = c.getInteger("StorageDim"); + return WorldData.instance().dimensionData().getStoredSize(dim); + } else { + return new WorldCoord( + c.getInteger("sizeX"), c.getInteger("sizeY"), c.getInteger("sizeZ") + ); + } + } + return new WorldCoord(0, 0, 0); + } - if( w != null ) - { - if( w.provider instanceof StorageWorldProvider ) - { - return w; - } - } - } - return null; - } + @Override + public WorldCoord getMin(final ItemStack is) { + final World w = this.getWorld(is); + if (w != null) { + final NBTTagCompound info + = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty("storageCell"); + if (info != null) { + return new WorldCoord( + info.getInteger("minX"), + info.getInteger("minY"), + info.getInteger("minZ") + ); + } + } + return new WorldCoord(0, 0, 0); + } - @Override - public WorldCoord getStoredSize( final ItemStack is ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - if( Platform.isServer() ) - { - final int dim = c.getInteger( "StorageDim" ); - return WorldData.instance().dimensionData().getStoredSize( dim ); - } - else - { - return new WorldCoord( c.getInteger( "sizeX" ), c.getInteger( "sizeY" ), c.getInteger( "sizeZ" ) ); - } - } - return new WorldCoord( 0, 0, 0 ); - } + @Override + public WorldCoord getMax(final ItemStack is) { + final World w = this.getWorld(is); + if (w != null) { + final NBTTagCompound info + = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty("storageCell"); + if (info != null) { + return new WorldCoord( + info.getInteger("maxX"), + info.getInteger("maxY"), + info.getInteger("maxZ") + ); + } + } + return new WorldCoord(0, 0, 0); + } - @Override - public WorldCoord getMin( final ItemStack is ) - { - final World w = this.getWorld( is ); - if( w != null ) - { - final NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty( "storageCell" ); - if( info != null ) - { - return new WorldCoord( info.getInteger( "minX" ), info.getInteger( "minY" ), info.getInteger( "minZ" ) ); - } - } - return new WorldCoord( 0, 0, 0 ); - } + @Override + public TransitionResult doSpatialTransition( + final ItemStack is, + final World w, + final WorldCoord min, + final WorldCoord max, + final boolean doTransition + ) { + final WorldCoord scale = this.getStoredSize(is); - @Override - public WorldCoord getMax( final ItemStack is ) - { - final World w = this.getWorld( is ); - if( w != null ) - { - final NBTTagCompound info = (NBTTagCompound) w.getWorldInfo().getAdditionalProperty( "storageCell" ); - if( info != null ) - { - return new WorldCoord( info.getInteger( "maxX" ), info.getInteger( "maxY" ), info.getInteger( "maxZ" ) ); - } - } - return new WorldCoord( 0, 0, 0 ); - } + final int targetX = max.x - min.x - 1; + final int targetY = max.y - min.y - 1; + final int targetZ = max.z - min.z - 1; + final int maxSize = this.getMaxStoredDim(is); - @Override - public TransitionResult doSpatialTransition( final ItemStack is, final World w, final WorldCoord min, final WorldCoord max, final boolean doTransition ) - { - final WorldCoord scale = this.getStoredSize( is ); + World destination = this.getWorld(is); - final int targetX = max.x - min.x - 1; - final int targetY = max.y - min.y - 1; - final int targetZ = max.z - min.z - 1; - final int maxSize = this.getMaxStoredDim( is ); + 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 (destination == null) { + destination = this.createNewWorld(is); + } - World destination = this.getWorld( is ); + final int floorBuffer = 64; + 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); - 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( destination == null ) - { - destination = this.createNewWorld( is ); - } + return new TransitionResult(true, 0); + } + } - final int floorBuffer = 64; - 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(false, 0); + } - return new TransitionResult( true, 0 ); - } - } + private World createNewWorld(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + final int newDim = DimensionManager.getNextFreeDimId(); + c.setInteger("StorageDim", newDim); + WorldData.instance().dimensionData().addStorageCell(newDim); + DimensionManager.initDimension(newDim); + return DimensionManager.getWorld(newDim); + } - return new TransitionResult( false, 0 ); - } - - private World createNewWorld( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - final int newDim = DimensionManager.getNextFreeDimId(); - c.setInteger( "StorageDim", newDim ); - WorldData.instance().dimensionData().addStorageCell( newDim ); - DimensionManager.initDimension( newDim ); - return DimensionManager.getWorld( newDim ); - } - - private void setStoredSize( final ItemStack is, final int targetX, final int targetY, final int targetZ ) - { - if( is.hasTagCompound() ) - { - final NBTTagCompound c = is.getTagCompound(); - final int dim = c.getInteger( "StorageDim" ); - c.setInteger( "sizeX", targetX ); - c.setInteger( "sizeY", targetY ); - c.setInteger( "sizeZ", targetZ ); - WorldData.instance().dimensionData().setStoredSize( dim, targetX, targetY, targetZ ); - } - } + private void setStoredSize( + final ItemStack is, final int targetX, final int targetY, final int targetZ + ) { + if (is.hasTagCompound()) { + final NBTTagCompound c = is.getTagCompound(); + final int dim = c.getInteger("StorageDim"); + c.setInteger("sizeX", targetX); + c.setInteger("sizeY", targetY); + c.setInteger("sizeZ", targetZ); + WorldData.instance().dimensionData().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 2eaeff2a..02b8ecb4 100644 --- a/src/main/java/appeng/items/storage/ItemViewCell.java +++ b/src/main/java/appeng/items/storage/ItemViewCell.java @@ -18,6 +18,7 @@ package appeng.items.storage; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.config.FuzzyMode; @@ -39,127 +40,109 @@ import appeng.util.prioitylist.PrecisePriorityList; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.EnumSet; +public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem { + public ItemViewCell() { + this.setFeature(EnumSet.of(AEFeature.Core)); + this.setMaxStackSize(1); + } + public static IPartitionList createFilter(final ItemStack[] list) { + IPartitionList myPartitionList = null; -public class ItemViewCell extends AEBaseItem implements ICellWorkbenchItem -{ - public ItemViewCell() - { - this.setFeature( EnumSet.of( AEFeature.Core ) ); - this.setMaxStackSize( 1 ); - } + final MergedPriorityList myMergedList + = new MergedPriorityList(); - public static IPartitionList createFilter( final ItemStack[] list ) - { - IPartitionList myPartitionList = null; + for (final ItemStack currentViewCell : list) { + if (currentViewCell == null) { + continue; + } - final MergedPriorityList myMergedList = new MergedPriorityList(); + if ((currentViewCell.getItem() instanceof ItemViewCell)) { + final IItemList priorityList + = AEApi.instance().storage().createItemList(); - for( final ItemStack currentViewCell : list ) - { - if( currentViewCell == null ) - { - continue; - } + final ICellWorkbenchItem vc + = (ICellWorkbenchItem) currentViewCell.getItem(); + final IInventory upgrades = vc.getUpgradesInventory(currentViewCell); + final IInventory config = vc.getConfigInventory(currentViewCell); + final FuzzyMode fzMode = vc.getFuzzyMode(currentViewCell); - if( ( currentViewCell.getItem() instanceof ItemViewCell ) ) - { - final IItemList priorityList = AEApi.instance().storage().createItemList(); + boolean hasInverter = false; + boolean hasFuzzy = false; - final ICellWorkbenchItem vc = (ICellWorkbenchItem) currentViewCell.getItem(); - final IInventory upgrades = vc.getUpgradesInventory( currentViewCell ); - final IInventory config = vc.getConfigInventory( currentViewCell ); - final FuzzyMode fzMode = vc.getFuzzyMode( currentViewCell ); + for (int x = 0; x < upgrades.getSizeInventory(); x++) { + final ItemStack is = upgrades.getStackInSlot(x); + if (is != null && is.getItem() instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is); + if (u != null) { + switch (u) { + case FUZZY: + hasFuzzy = true; + break; + case INVERTER: + hasInverter = true; + break; + default: + } + } + } + } - boolean hasInverter = false; - boolean hasFuzzy = false; + for (int x = 0; x < config.getSizeInventory(); x++) { + final ItemStack is = config.getStackInSlot(x); + if (is != null) { + priorityList.add(AEItemStack.create(is)); + } + } - for( int x = 0; x < upgrades.getSizeInventory(); x++ ) - { - final ItemStack is = upgrades.getStackInSlot( x ); - if( is != null && is.getItem() instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) is.getItem() ).getType( is ); - if( u != null ) - { - switch( u ) - { - case FUZZY: - hasFuzzy = true; - break; - case INVERTER: - hasInverter = true; - break; - default: - } - } - } - } + if (!priorityList.isEmpty()) { + if (hasFuzzy) { + myMergedList.addNewList( + new FuzzyPriorityList(priorityList, fzMode), + !hasInverter + ); + } else { + myMergedList.addNewList( + new PrecisePriorityList(priorityList), + !hasInverter + ); + } - for( int x = 0; x < config.getSizeInventory(); x++ ) - { - final ItemStack is = config.getStackInSlot( x ); - if( is != null ) - { - priorityList.add( AEItemStack.create( is ) ); - } - } + myPartitionList = myMergedList; + } + } + } - if( !priorityList.isEmpty() ) - { - if( hasFuzzy ) - { - myMergedList.addNewList( new FuzzyPriorityList( priorityList, fzMode ), !hasInverter ); - } - else - { - myMergedList.addNewList( new PrecisePriorityList( priorityList ), !hasInverter ); - } + return myPartitionList; + } - myPartitionList = myMergedList; - } - } - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - return myPartitionList; - } + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } } diff --git a/src/main/java/appeng/items/tools/ToolBiometricCard.java b/src/main/java/appeng/items/tools/ToolBiometricCard.java index 1cd86812..74e2f654 100644 --- a/src/main/java/appeng/items/tools/ToolBiometricCard.java +++ b/src/main/java/appeng/items/tools/ToolBiometricCard.java @@ -18,6 +18,8 @@ package appeng.items.tools; +import java.util.EnumSet; +import java.util.List; import appeng.api.config.SecurityPermissions; import appeng.api.features.IPlayerRegistry; @@ -38,172 +40,151 @@ import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.List; +public class ToolBiometricCard extends AEBaseItem implements IBiometricCard { + public ToolBiometricCard() { + this.setFeature(EnumSet.of(AEFeature.Security)); + this.setMaxStackSize(1); + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer( + this, new ToolBiometricCardRender() + ); + } + } -public class ToolBiometricCard extends AEBaseItem implements IBiometricCard -{ - public ToolBiometricCard() - { - this.setFeature( EnumSet.of( AEFeature.Security ) ); - this.setMaxStackSize( 1 ); + @Override + public ItemStack + onItemRightClick(final ItemStack is, final World w, final EntityPlayer p) { + if (ForgeEventFactory.onItemUseStart(p, is, 1) > 0 && p.isSneaking()) { + this.encode(is, p); + p.swingItem(); + return is; + } - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new ToolBiometricCardRender() ); - } - } + return is; + } - @Override - public ItemStack onItemRightClick( final ItemStack is, final World w, final EntityPlayer p ) - { - if( ForgeEventFactory.onItemUseStart( p, is, 1 ) > 0 && p.isSneaking() ) - { - this.encode( is, p ); - p.swingItem(); - return is; - } + @Override + public boolean itemInteractionForEntity( + ItemStack is, final EntityPlayer par2EntityPlayer, final EntityLivingBase target + ) { + if (target instanceof EntityPlayer && !par2EntityPlayer.isSneaking()) { + if (par2EntityPlayer.capabilities.isCreativeMode) { + is = par2EntityPlayer.getCurrentEquippedItem(); + } + this.encode(is, (EntityPlayer) target); + par2EntityPlayer.swingItem(); + return true; + } + return false; + } - return is; - } + @Override + public String getItemStackDisplayName(final ItemStack is) { + final GameProfile username = this.getProfile(is); + return username != null + ? super.getItemStackDisplayName(is) + " - " + username.getName() + : super.getItemStackDisplayName(is); + } - @Override - public boolean itemInteractionForEntity( ItemStack is, final EntityPlayer par2EntityPlayer, final EntityLivingBase target ) - { - if( target instanceof EntityPlayer && !par2EntityPlayer.isSneaking() ) - { - if( par2EntityPlayer.capabilities.isCreativeMode ) - { - is = par2EntityPlayer.getCurrentEquippedItem(); - } - this.encode( is, (EntityPlayer) target ); - par2EntityPlayer.swingItem(); - return true; - } - return false; - } + private void encode(final ItemStack is, final EntityPlayer p) { + final GameProfile username = this.getProfile(is); - @Override - public String getItemStackDisplayName( final ItemStack is ) - { - final GameProfile username = this.getProfile( is ); - return username != null ? super.getItemStackDisplayName( is ) + " - " + username.getName() : super.getItemStackDisplayName( is ); - } + if (username != null && username.equals(p.getGameProfile())) { + this.setProfile(is, null); + } else { + this.setProfile(is, p.getGameProfile()); + } + } - private void encode( final ItemStack is, final EntityPlayer p ) - { - final GameProfile username = this.getProfile( is ); + @Override + public void setProfile(final ItemStack itemStack, final GameProfile profile) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); - if( username != null && username.equals( p.getGameProfile() ) ) - { - this.setProfile( is, null ); - } - else - { - this.setProfile( is, p.getGameProfile() ); - } - } + if (profile != null) { + final NBTTagCompound pNBT = new NBTTagCompound(); + NBTUtil.func_152460_a(pNBT, profile); + tag.setTag("profile", pNBT); + } else { + tag.removeTag("profile"); + } + } - @Override - public void setProfile( final ItemStack itemStack, final GameProfile profile ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); + @Override + public GameProfile getProfile(final ItemStack is) { + final NBTTagCompound tag = Platform.openNbtData(is); + if (tag.hasKey("profile")) { + return NBTUtil.func_152459_a(tag.getCompoundTag("profile")); + } + return null; + } - if( profile != null ) - { - final NBTTagCompound pNBT = new NBTTagCompound(); - NBTUtil.func_152460_a( pNBT, profile ); - tag.setTag( "profile", pNBT ); - } - else - { - tag.removeTag( "profile" ); - } - } + @Override + public EnumSet getPermissions(final ItemStack is) { + final NBTTagCompound tag = Platform.openNbtData(is); + final EnumSet result + = EnumSet.noneOf(SecurityPermissions.class); - @Override - public GameProfile getProfile( final ItemStack is ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - if( tag.hasKey( "profile" ) ) - { - return NBTUtil.func_152459_a( tag.getCompoundTag( "profile" ) ); - } - return null; - } + for (final SecurityPermissions sp : SecurityPermissions.values()) { + if (tag.getBoolean(sp.name())) { + result.add(sp); + } + } - @Override - public EnumSet getPermissions( final ItemStack is ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - final EnumSet result = EnumSet.noneOf( SecurityPermissions.class ); + return result; + } - for( final SecurityPermissions sp : SecurityPermissions.values() ) - { - if( tag.getBoolean( sp.name() ) ) - { - result.add( sp ); - } - } + @Override + public boolean + hasPermission(final ItemStack is, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(is); + return tag.getBoolean(permission.name()); + } - return result; - } + @Override + public void + removePermission(final ItemStack itemStack, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); + if (tag.hasKey(permission.name())) { + tag.removeTag(permission.name()); + } + } - @Override - public boolean hasPermission( final ItemStack is, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( is ); - return tag.getBoolean( permission.name() ); - } + @Override + public void + addPermission(final ItemStack itemStack, final SecurityPermissions permission) { + final NBTTagCompound tag = Platform.openNbtData(itemStack); + tag.setBoolean(permission.name(), true); + } - @Override - public void removePermission( final ItemStack itemStack, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); - if( tag.hasKey( permission.name() ) ) - { - tag.removeTag( permission.name() ); - } - } + @Override + public void registerPermissions( + final ISecurityRegistry register, final IPlayerRegistry pr, final ItemStack is + ) { + register.addPlayer(pr.getID(this.getProfile(is)), this.getPermissions(is)); + } - @Override - public void addPermission( final ItemStack itemStack, final SecurityPermissions permission ) - { - final NBTTagCompound tag = Platform.openNbtData( itemStack ); - tag.setBoolean( permission.name(), true ); - } + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + final EnumSet perms = this.getPermissions(stack); + if (perms.isEmpty()) { + lines.add(GuiText.NoPermissions.getLocal()); + } else { + String msg = null; - @Override - public void registerPermissions( final ISecurityRegistry register, final IPlayerRegistry pr, final ItemStack is ) - { - register.addPlayer( pr.getID( this.getProfile( is ) ), this.getPermissions( is ) ); - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final EnumSet perms = this.getPermissions( stack ); - if( perms.isEmpty() ) - { - lines.add( GuiText.NoPermissions.getLocal() ); - } - else - { - String msg = null; - - for( final SecurityPermissions sp : perms ) - { - if( msg == null ) - { - msg = Platform.gui_localize( sp.getUnlocalizedName() ); - } - else - { - msg = msg + ", " + Platform.gui_localize( sp.getUnlocalizedName() ); - } - } - lines.add( msg ); - } - } + for (final SecurityPermissions sp : perms) { + if (msg == null) { + msg = Platform.gui_localize(sp.getUnlocalizedName()); + } else { + msg = msg + ", " + Platform.gui_localize(sp.getUnlocalizedName()); + } + } + lines.add(msg); + } + } } diff --git a/src/main/java/appeng/items/tools/ToolMemoryCard.java b/src/main/java/appeng/items/tools/ToolMemoryCard.java index 639ec828..72aee712 100644 --- a/src/main/java/appeng/items/tools/ToolMemoryCard.java +++ b/src/main/java/appeng/items/tools/ToolMemoryCard.java @@ -18,6 +18,10 @@ package appeng.items.tools; +import java.text.NumberFormat; +import java.util.EnumSet; +import java.util.List; +import java.util.Locale; import appeng.api.implementations.items.IMemoryCard; import appeng.api.implementations.items.MemoryCardMessages; @@ -28,7 +32,6 @@ import appeng.core.localization.GuiText; import appeng.core.localization.PlayerMessages; import appeng.items.AEBaseItem; import appeng.util.Platform; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -36,143 +39,144 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; -import java.text.NumberFormat; -import java.util.EnumSet; -import java.util.List; -import java.util.Locale; +public class ToolMemoryCard extends AEBaseItem implements IMemoryCard { + public ToolMemoryCard() { + this.setFeature(EnumSet.of(AEFeature.Core)); + this.setMaxStackSize(1); + } + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + lines.add(this.getLocalizedName( + this.getSettingsName(stack) + ".name", this.getSettingsName(stack) + )); -public class ToolMemoryCard extends AEBaseItem implements IMemoryCard -{ + final NBTTagCompound data = this.getData(stack); + if (data.hasKey("tooltip")) { + lines.add(StatCollector.translateToLocal(this.getLocalizedName( + data.getString("tooltip") + ".name", data.getString("tooltip") + ))); + } - public ToolMemoryCard() - { - this.setFeature( EnumSet.of( AEFeature.Core ) ); - this.setMaxStackSize( 1 ); - } + if (data.hasKey("freq")) { + final long freq = data.getLong("freq"); + final String freqTooltip + = String.format("%X", freq).replaceAll("(.{4})", "$0 ").trim(); - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - lines.add( this.getLocalizedName( this.getSettingsName( stack ) + ".name", this.getSettingsName( stack ) ) ); + final String local = ButtonToolTips.P2PFrequency.getLocal(); - final NBTTagCompound data = this.getData( stack ); - if( data.hasKey( "tooltip" ) ) - { - lines.add( StatCollector.translateToLocal( this.getLocalizedName( data.getString( "tooltip" ) + ".name", data.getString( "tooltip" ) ) ) ); - } + lines.add(String.format(local, freqTooltip)); + } + } - if( data.hasKey( "freq" ) ) - { - final long freq = data.getLong( "freq" ); - final String freqTooltip = String.format("%X", freq ).replaceAll("(.{4})", "$0 ").trim(); + /** + * Find the localized string... + * + * @param name possible names for the localized string + * @return localized name + */ + private String getLocalizedName(final String... name) { + for (final String n : name) { + final String l = StatCollector.translateToLocal(n); + if (!l.equals(n)) { + return l; + } + } - final String local = ButtonToolTips.P2PFrequency.getLocal(); + for (final String n : name) { + return n; + } - lines.add( String.format( local, freqTooltip ) ); - } - } + return ""; + } - /** - * Find the localized string... - * - * @param name possible names for the localized string - * @return localized name - */ - private String getLocalizedName( final String... name ) - { - for( final String n : name ) - { - final String l = StatCollector.translateToLocal( n ); - if( !l.equals( n ) ) - { - return l; - } - } + @Override + public void setMemoryCardContents( + final ItemStack is, final String settingsName, final NBTTagCompound data + ) { + final NBTTagCompound c = Platform.openNbtData(is); + c.setString("Config", settingsName); + c.setTag("Data", data); + } - for( final String n : name ) - { - return n; - } + @Override + public String getSettingsName(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + final String name = c.getString("Config"); + return name == null || name.isEmpty() ? GuiText.Blank.getUnlocalized() : name; + } - return ""; - } + @Override + public NBTTagCompound getData(final ItemStack is) { + final NBTTagCompound c = Platform.openNbtData(is); + NBTTagCompound o = c.getCompoundTag("Data"); + if (o == null) { + o = new NBTTagCompound(); + } + return (NBTTagCompound) o.copy(); + } - @Override - public void setMemoryCardContents( final ItemStack is, final String settingsName, final NBTTagCompound data ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - c.setString( "Config", settingsName ); - c.setTag( "Data", data ); - } + @Override + public void notifyUser(final EntityPlayer player, final MemoryCardMessages msg) { + if (Platform.isClient()) { + return; + } - @Override - public String getSettingsName( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - final String name = c.getString( "Config" ); - return name == null || name.isEmpty() ? GuiText.Blank.getUnlocalized() : name; - } + switch (msg) { + case SETTINGS_CLEARED: + player.addChatMessage(PlayerMessages.SettingCleared.get()); + break; + case INVALID_MACHINE: + player.addChatMessage(PlayerMessages.InvalidMachine.get()); + break; + case SETTINGS_LOADED: + player.addChatMessage(PlayerMessages.LoadedSettings.get()); + break; + case SETTINGS_SAVED: + player.addChatMessage(PlayerMessages.SavedSettings.get()); + break; + default: + } + } - @Override - public NBTTagCompound getData( final ItemStack is ) - { - final NBTTagCompound c = Platform.openNbtData( is ); - NBTTagCompound o = c.getCompoundTag( "Data" ); - if( o == null ) - { - o = new NBTTagCompound(); - } - return (NBTTagCompound) o.copy(); - } + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer player, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hx, + final float hy, + final float hz + ) { + if (player.isSneaking() && !w.isRemote) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) + return false; + final IMemoryCard mem = (IMemoryCard) is.getItem(); + mem.notifyUser(player, MemoryCardMessages.SETTINGS_CLEARED); + is.setTagCompound(null); + return true; + } else { + return super.onItemUse(is, player, w, x, y, z, side, hx, hy, hz); + } + } - @Override - public void notifyUser( final EntityPlayer player, final MemoryCardMessages msg ) - { - if( Platform.isClient() ) - { - return; - } - - switch( msg ) - { - case SETTINGS_CLEARED: - player.addChatMessage( PlayerMessages.SettingCleared.get() ); - break; - case INVALID_MACHINE: - player.addChatMessage( PlayerMessages.InvalidMachine.get() ); - break; - case SETTINGS_LOADED: - player.addChatMessage( PlayerMessages.LoadedSettings.get() ); - break; - case SETTINGS_SAVED: - player.addChatMessage( PlayerMessages.SavedSettings.get() ); - break; - default: - } - } - - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer player, final World w, final int x, final int y, final int z, final int side, final float hx, final float hy, final float hz ) - { - if( player.isSneaking() && !w.isRemote ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return false; - final IMemoryCard mem = (IMemoryCard) is.getItem(); - mem.notifyUser( player, MemoryCardMessages.SETTINGS_CLEARED ); - is.setTagCompound( null ); - return true; - } - else - { - return super.onItemUse( is, player, w, x, y, z, side, hx, hy, hz ); - } - } - - @Override - public boolean doesSneakBypassUse( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - return true; - } + @Override + public boolean doesSneakBypassUse( + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player + ) { + return true; + } } diff --git a/src/main/java/appeng/items/tools/ToolNetworkTool.java b/src/main/java/appeng/items/tools/ToolNetworkTool.java index 28637cf8..dc73a60b 100644 --- a/src/main/java/appeng/items/tools/ToolNetworkTool.java +++ b/src/main/java/appeng/items/tools/ToolNetworkTool.java @@ -18,6 +18,7 @@ package appeng.items.tools; +import java.util.EnumSet; import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.IGuiItemObject; @@ -51,180 +52,217 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.util.EnumSet; +@Interface( + iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore +) +public class ToolNetworkTool + extends AEBaseItem implements IGuiItem, IAEWrench, IToolWrench { + public ToolNetworkTool() { + super(Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.NetworkTool)); + this.setMaxStackSize(1); + this.setHarvestLevel("wrench", 0); + } -@Interface( iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore ) -public class ToolNetworkTool extends AEBaseItem implements IGuiItem, IAEWrench, IToolWrench -{ + @Override + public IGuiItemObject getGuiObject( + final ItemStack is, final World world, final int x, final int y, final int z + ) { + final TileEntity te = world.getTileEntity(x, y, z); + return new NetworkToolViewer( + is, (IGridHost) (te instanceof IGridHost ? te : null) + ); + } - public ToolNetworkTool() - { - super( Optional.absent() ); + @Override + public ItemStack + onItemRightClick(final ItemStack it, final World w, final EntityPlayer p) { + if (Platform.isClient()) { + final MovingObjectPosition mop = ClientHelper.proxy.getMOP(); - this.setFeature( EnumSet.of( AEFeature.NetworkTool ) ); - this.setMaxStackSize( 1 ); - this.setHarvestLevel( "wrench", 0 ); - } + if (mop == null) { + this.onItemUseFirst(it, p, w, 0, 0, 0, -1, 0, 0, 0); + } else { + final int i = mop.blockX; + final int j = mop.blockY; + final int k = mop.blockZ; - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World world, final int x, final int y, final int z ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - return new NetworkToolViewer( is, (IGridHost) ( te instanceof IGridHost ? te : null ) ); - } + if (w.getBlock(i, j, k).isAir(w, i, j, k)) { + this.onItemUseFirst(it, p, w, 0, 0, 0, -1, 0, 0, 0); + } + } + } - @Override - public ItemStack onItemRightClick( final ItemStack it, final World w, final EntityPlayer p ) - { - if( Platform.isClient() ) - { - final MovingObjectPosition mop = ClientHelper.proxy.getMOP(); + return it; + } - if( mop == null ) - { - this.onItemUseFirst( it, p, w, 0, 0, 0, -1, 0, 0, 0 ); - } - else - { - final int i = mop.blockX; - final int j = mop.blockY; - final int k = mop.blockZ; + @Override + public boolean onItemUseFirst( + final ItemStack is, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) + return true; - if( w.getBlock( i, j, k ).isAir( w, i, j, k ) ) - { - this.onItemUseFirst( it, p, w, 0, 0, 0, -1, 0, 0, 0 ); - } - } - } + Block blk = world.getBlock(x, y, z); + if (blk != null) + if (ForgeEventFactory + .onPlayerInteract( + player, + blk.isAir(world, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + world + ) + .isCanceled()) + return true; - return it; - } + final MovingObjectPosition mop = new MovingObjectPosition( + x, y, z, side, Vec3.createVectorHelper(hitX, hitY, hitZ) + ); + final TileEntity te = world.getTileEntity(x, y, z); + if (te instanceof IPartHost) { + final SelectedPart part = ((IPartHost) te).selectPart(mop.hitVec); - @Override - public boolean onItemUseFirst( final ItemStack is, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return true; + if (part.part != null || part.facade != null) { + if (part.part instanceof INetworkToolAgent + && !((INetworkToolAgent) part.part).showNetworkInfo(mop)) { + return false; + } + } + } else if (te instanceof INetworkToolAgent && !((INetworkToolAgent) te).showNetworkInfo(mop)) { + return false; + } - Block blk = world.getBlock( x, y, z ); - if( blk != null ) - if( ForgeEventFactory.onPlayerInteract( player, - blk.isAir( world, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, world ).isCanceled() ) - return true; + if (Platform.isClient()) { + NetworkHandler.instance.sendToServer( + new PacketClick(x, y, z, side, hitX, hitY, hitZ) + ); + } + return true; + } - final MovingObjectPosition mop = new MovingObjectPosition( x, y, z, side, Vec3.createVectorHelper( hitX, hitY, hitZ ) ); - final TileEntity te = world.getTileEntity( x, y, z ); - if( te instanceof IPartHost ) - { - final SelectedPart part = ( (IPartHost) te ).selectPart( mop.hitVec ); + @Override + public boolean doesSneakBypassUse( + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player + ) { + return true; + } - if( part.part != null || part.facade != null ) - { - if( part.part instanceof INetworkToolAgent && !( (INetworkToolAgent) part.part ).showNetworkInfo( mop ) ) - { - return false; - } - } - } - else if( te instanceof INetworkToolAgent && !( (INetworkToolAgent) te ).showNetworkInfo( mop ) ) - { - return false; - } + public boolean serverSideToolLogic( + final ItemStack is, + final EntityPlayer p, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (side >= 0) { + if (!Platform.hasPermissions(new DimensionalCoord(w, x, y, z), p)) { + return false; + } - if( Platform.isClient() ) - { - NetworkHandler.instance.sendToServer( new PacketClick( x, y, z, side, hitX, hitY, hitZ ) ); - } - return true; - } + final Block b = w.getBlock(x, y, z); - @Override - public boolean doesSneakBypassUse( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - return true; - } + if (b != null) + if (ForgeEventFactory + .onPlayerInteract( + p, + b.isAir(w, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + w + ) + .isCanceled()) + return false; - public boolean serverSideToolLogic( final ItemStack is, final EntityPlayer p, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( side >= 0 ) - { - if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) - { - return false; - } + if (b != null && !p.isSneaking()) { + final TileEntity te = w.getTileEntity(x, y, z); + if (!(te instanceof IGridHost)) { + if (b.rotateBlock(w, x, y, z, ForgeDirection.getOrientation(side))) { + b.onNeighborBlockChange(w, x, y, z, Platform.AIR_BLOCK); + p.swingItem(); + return !w.isRemote; + } + } + } - final Block b = w.getBlock( x, y, z ); + if (!p.isSneaking()) { + if (p.openContainer instanceof AEBaseContainer) { + return true; + } - if( b != null ) - if( ForgeEventFactory.onPlayerInteract( p, - b.isAir( w, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, w ).isCanceled() ) - return false; + final TileEntity te = w.getTileEntity(x, y, z); - if( b != null && !p.isSneaking() ) - { - final TileEntity te = w.getTileEntity( x, y, z ); - if( !( te instanceof IGridHost ) ) - { - if( b.rotateBlock( w, x, y, z, ForgeDirection.getOrientation( side ) ) ) - { - b.onNeighborBlockChange( w, x, y, z, Platform.AIR_BLOCK ); - p.swingItem(); - return !w.isRemote; - } - } - } + 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 + ); + } - if( !p.isSneaking() ) - { - if( p.openContainer instanceof AEBaseContainer ) - { - return true; - } + return true; + } else { + b.onBlockActivated(w, x, y, z, p, side, hitX, hitY, hitZ); + } + } else { + Platform.openGUI(p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_NETWORK_TOOL); + } - final TileEntity te = w.getTileEntity( x, y, z ); + return false; + } - 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 ); - } + @Override + public boolean canWrench( + final ItemStack is, + final EntityPlayer player, + final int x, + final int y, + final int z + ) { + return true; + } - return true; - } - else - { - b.onBlockActivated( w, x, y, z, p, side, hitX, hitY, hitZ ); - } - } - else - { - Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_NETWORK_TOOL ); - } + @Override + public boolean + canWrench(final EntityPlayer player, final int x, final int y, final int z) { + return true; + } - return false; - } - - @Override - public boolean canWrench( final ItemStack is, final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public boolean canWrench( final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public void wrenchUsed( final EntityPlayer player, final int x, final int y, final int z ) - { - player.swingItem(); - } + @Override + public void + wrenchUsed(final EntityPlayer player, final int x, final int y, final int z) { + 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 65c2e54d..29b10c6b 100644 --- a/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java +++ b/src/main/java/appeng/items/tools/powered/ToolChargedStaff.java @@ -18,6 +18,7 @@ package appeng.items.tools.powered; +import java.util.EnumSet; import appeng.core.AEConfig; import appeng.core.features.AEFeature; @@ -32,41 +33,48 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; +public class ToolChargedStaff extends AEBasePoweredItem { + public ToolChargedStaff() { + super(AEConfig.instance.chargedStaffBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.ChargedStaff, AEFeature.PoweredTools)); + } + @Override + public boolean hitEntity( + final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter + ) { + if (hitter instanceof EntityPlayer + && ForgeEventFactory.onItemUseStart((EntityPlayer) hitter, item, 1) <= 0) + return false; -public class ToolChargedStaff extends AEBasePoweredItem -{ + if (this.getAECurrentPower(item) > 300) { + this.extractAEPower(item, 300); + if (Platform.isServer()) { + for (int x = 0; x < 2; x++) { + final float dx = (float + ) (Platform.getRandomFloat() * target.width + target.boundingBox.minX + ); + final float dy = (float + ) (Platform.getRandomFloat() * target.height + target.boundingBox.minY + ); + final 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) + ); + } + } + target.attackEntityFrom(DamageSource.magic, 6); + return true; + } - public ToolChargedStaff() - { - super( AEConfig.instance.chargedStaffBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.ChargedStaff, AEFeature.PoweredTools ) ); - } - - @Override - public boolean hitEntity( final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter ) - { - if( hitter instanceof EntityPlayer && ForgeEventFactory.onItemUseStart( (EntityPlayer) hitter, item, 1 ) <= 0 ) - return false; - - if( this.getAECurrentPower( item ) > 300 ) - { - this.extractAEPower( item, 300 ); - if( Platform.isServer() ) - { - for( int x = 0; x < 2; x++ ) - { - final float dx = (float) ( Platform.getRandomFloat() * target.width + target.boundingBox.minX ); - final float dy = (float) ( Platform.getRandomFloat() * target.height + target.boundingBox.minY ); - final 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 ) ); - } - } - target.attackEntityFrom( DamageSource.magic, 6 ); - return true; - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java index 3df13071..d00b34a1 100644 --- a/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java +++ b/src/main/java/appeng/items/tools/powered/ToolColorApplicator.java @@ -18,6 +18,7 @@ package appeng.items.tools.powered; +import java.util.*; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -66,492 +67,485 @@ import net.minecraft.world.World; import net.minecraftforge.client.MinecraftForgeClient; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; - -import java.util.*; - import org.apache.commons.lang3.text.WordUtils; -public class ToolColorApplicator extends AEBasePoweredItem implements IStorageCell, IItemGroup, IBlockTool, IMouseWheelItem -{ - - private static final Map ORE_TO_COLOR = new HashMap(); - - static - { - - for( final AEColor color : AEColor.VALID_COLORS ) - { - final String dyeName = color.unlocalizedName; - final String oreDictName = "dye" + WordUtils.capitalize( dyeName ); - final int oreDictId = OreDictionary.getOreID( oreDictName ); - - ORE_TO_COLOR.put( oreDictId, color ); - } - } - - public ToolColorApplicator() - { - super( AEConfig.instance.colorApplicatorBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.ColorApplicator, AEFeature.PoweredTools ) ); - if( Platform.isClient() ) - { - MinecraftForgeClient.registerItemRenderer( this, new ToolColorApplicatorRender() ); - } - } - - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( this, new DispenserBlockTool() ); - } - - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer p, final World w, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - final Block blk = w.getBlock( x, y, z ); - - ItemStack paintBall = this.getColor( is ); - - final IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - if( inv != null ) - { - final IAEItemStack option = inv.extractItems( AEItemStack.create( paintBall ), Actionable.SIMULATE, new BaseActionSource() ); - - if( option != null ) - { - paintBall = option.getItemStack(); - paintBall.stackSize = 1; - } - else - { - paintBall = null; - } - - if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) - { - return false; - } - - final double powerPerUse = 100; - if( paintBall != null && paintBall.getItem() instanceof ItemSnowball ) - { - final ForgeDirection orientation = ForgeDirection.getOrientation( side ); - final TileEntity te = w.getTileEntity( x, y, z ); - // clean cables. - if( te instanceof IColorableTile ) - { - if( this.getAECurrentPower( is ) > powerPerUse && ( (IColorableTile) te ).getColor() != AEColor.Transparent ) - { - if( ( (IColorableTile) te ).recolourBlock( orientation, AEColor.Transparent, p ) ) - { - inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse ); - return true; - } - } - } - - // clean paint balls.. - final Block testBlk = w.getBlock( x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ ); - final TileEntity painted = w.getTileEntity( x + orientation.offsetX, y + orientation.offsetY, z + orientation.offsetZ ); - 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() ); - return true; - } - } - else if( paintBall != null ) - { - final AEColor color = this.getColorFromItem( paintBall ); - - 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 ) ) - { - inv.extractItems( AEItemStack.create( paintBall ), Actionable.MODULATE, new BaseActionSource() ); - this.extractAEPower( is, powerPerUse ); - return true; - } - } - } - } - - if( p.isSneaking() ) - { - this.cycleColors( is, paintBall, 1 ); - } - - return false; - } - - @Override - public String getItemStackDisplayName( final ItemStack par1ItemStack ) - { - String extra = GuiText.Empty.getLocal(); - - final AEColor selected = this.getActiveColor( par1ItemStack ); - - if( selected != null && Platform.isClient() ) - { - extra = Platform.gui_localize( selected.unlocalizedName ); - } - - return super.getItemStackDisplayName( par1ItemStack ) + " - " + extra; - } - - public AEColor getActiveColor( final ItemStack tol ) - { - return this.getColorFromItem( this.getColor( tol ) ); - } - - private AEColor getColorFromItem( final ItemStack paintBall ) - { - if( paintBall == null ) - { - return null; - } - - if( paintBall.getItem() instanceof ItemSnowball ) - { - return AEColor.Transparent; - } - - if( paintBall.getItem() instanceof ItemPaintBall ) - { - final ItemPaintBall ipb = (ItemPaintBall) paintBall.getItem(); - return ipb.getColor( paintBall ); - } - else - { - final int[] id = OreDictionary.getOreIDs( paintBall ); - - for( final int oreID : id ) - { - if( ORE_TO_COLOR.containsKey( oreID ) ) - { - return ORE_TO_COLOR.get( oreID ); - } - } - } - - return null; - } - - public ItemStack getColor( final ItemStack is ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null && c.hasKey( "color" ) ) - { - final NBTTagCompound color = c.getCompoundTag( "color" ); - final ItemStack oldColor = ItemStack.loadItemStackFromNBT( color ); - if( oldColor != null ) - { - return oldColor; - } - } - - return this.findNextColor( is, null, 0 ); - } - - private ItemStack findNextColor( final ItemStack is, final ItemStack anchor, final int scrollOffset ) - { - ItemStack newColor = null; - - final IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - if( inv != null ) - { - final IItemList itemList = inv.getAvailableItems( AEApi.instance().storage().createItemList() ); - if( anchor == null ) - { - final IAEItemStack firstItem = itemList.getFirstItem(); - if( firstItem != null ) - { - newColor = firstItem.getItemStack(); - } - } - else - { - final LinkedList list = new LinkedList(); - - for( final IAEItemStack i : itemList ) - { - list.add( i ); - } - - Collections.sort( list, new Comparator() - { - - @Override - public int compare( final IAEItemStack a, final IAEItemStack b ) - { - return ItemSorters.compareInt( a.getItemDamage(), b.getItemDamage() ); - } - } ); - - if( list.size() <= 0 ) - { - return null; - } - - IAEItemStack where = list.getFirst(); - int cycles = 1 + list.size(); - - while( cycles > 0 && !where.equals( anchor ) ) - { - list.addLast( list.removeFirst() ); - cycles--; - where = list.getFirst(); - } - - if( scrollOffset > 0 ) - { - list.addLast( list.removeFirst() ); - } - - if( scrollOffset < 0 ) - { - list.addFirst( list.removeLast() ); - } - - return list.get( 0 ).getItemStack(); - } - } - - if( newColor != null ) - { - this.setColor( is, newColor ); - } - - return newColor; - } - - private void setColor( final ItemStack is, final ItemStack newColor ) - { - final NBTTagCompound data = Platform.openNbtData( is ); - if( newColor == null ) - { - data.removeTag( "color" ); - } - else - { - final NBTTagCompound color = new NBTTagCompound(); - newColor.writeToNBT( color ); - data.setTag( "color", color ); - } - } - - private boolean recolourBlock( final Block blk, final ForgeDirection side, final World w, final int x, final int y, final int z, final ForgeDirection orientation, final AEColor newColor, final EntityPlayer p ) - { - if( blk == Blocks.carpet ) - { - final int meta = w.getBlockMetadata( x, y, z ); - if( newColor.ordinal() == meta ) - { - return false; - } - return w.setBlock( x, y, z, Blocks.carpet, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.glass ) - { - return w.setBlock( x, y, z, Blocks.stained_glass, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.stained_glass ) - { - final int meta = w.getBlockMetadata( x, y, z ); - if( newColor.ordinal() == meta ) - { - return false; - } - return w.setBlock( x, y, z, Blocks.stained_glass, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.glass_pane ) - { - return w.setBlock( x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.stained_glass_pane ) - { - final int meta = w.getBlockMetadata( x, y, z ); - if( newColor.ordinal() == meta ) - { - return false; - } - return w.setBlock( x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.hardened_clay ) - { - return w.setBlock( x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3 ); - } - - if( blk == Blocks.stained_hardened_clay ) - { - final int meta = w.getBlockMetadata( x, y, z ); - 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 ); - } - - return blk.recolourBlock( w, x, y, z, side, newColor.ordinal() ); - } - - public void cycleColors( final ItemStack is, final ItemStack paintBall, final int i ) - { - if( paintBall == null ) - { - this.setColor( is, this.getColor( is ) ); - } - else - { - this.setColor( is, this.findNextColor( is, paintBall, i ) ); - } - } - - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); - - final IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); - - if( cdi instanceof CellInventoryHandler ) - { - final 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() ); - } - } - } - - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } - - @Override - public int BytePerType( final ItemStack cell ) - { - return 8; - } - - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } - - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 27; - } - - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - if( requestedAddition != null ) - { - final int[] id = OreDictionary.getOreIDs( requestedAddition.getItemStack() ); - - for( final int x : id ) - { - if( ORE_TO_COLOR.containsKey( x ) ) - { - return false; - } - } - - if( requestedAddition.getItem() instanceof ItemSnowball ) - { - return false; - } - - return !( requestedAddition.getItem() instanceof ItemPaintBall && requestedAddition.getItemDamage() < 20 ); - } - return true; - } - - @Override - public boolean storableInStorageCell() - { - return true; - } - - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } - - @Override - public double getIdleDrain() - { - return 0.5; - } - - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } - - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } - - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } - - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } - - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public void onWheel( final ItemStack is, final boolean up ) - { - this.cycleColors( is, this.getColor( is ), up ? 1 : -1 ); - } +public class ToolColorApplicator extends AEBasePoweredItem + implements IStorageCell, IItemGroup, IBlockTool, IMouseWheelItem { + private static final Map ORE_TO_COLOR + = new HashMap(); + + static { + for (final AEColor color : AEColor.VALID_COLORS) { + final String dyeName = color.unlocalizedName; + final String oreDictName = "dye" + WordUtils.capitalize(dyeName); + final int oreDictId = OreDictionary.getOreID(oreDictName); + + ORE_TO_COLOR.put(oreDictId, color); + } + } + + public ToolColorApplicator() { + super(AEConfig.instance.colorApplicatorBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.ColorApplicator, AEFeature.PoweredTools)); + if (Platform.isClient()) { + MinecraftForgeClient.registerItemRenderer( + this, new ToolColorApplicatorRender() + ); + } + } + + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject(this, new DispenserBlockTool()); + } + + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer p, + final World w, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + final Block blk = w.getBlock(x, y, z); + + ItemStack paintBall = this.getColor(is); + + final IMEInventory inv + = AEApi.instance().registries().cell().getCellInventory( + is, null, StorageChannel.ITEMS + ); + if (inv != null) { + final IAEItemStack option = inv.extractItems( + AEItemStack.create(paintBall), Actionable.SIMULATE, new BaseActionSource() + ); + + if (option != null) { + paintBall = option.getItemStack(); + paintBall.stackSize = 1; + } else { + paintBall = null; + } + + if (!Platform.hasPermissions(new DimensionalCoord(w, x, y, z), p)) { + return false; + } + + final double powerPerUse = 100; + if (paintBall != null && paintBall.getItem() instanceof ItemSnowball) { + final ForgeDirection orientation = ForgeDirection.getOrientation(side); + final TileEntity te = w.getTileEntity(x, y, z); + // clean cables. + if (te instanceof IColorableTile) { + if (this.getAECurrentPower(is) > powerPerUse + && ((IColorableTile) te).getColor() != AEColor.Transparent) { + if (((IColorableTile) te) + .recolourBlock(orientation, AEColor.Transparent, p)) { + inv.extractItems( + AEItemStack.create(paintBall), + Actionable.MODULATE, + new BaseActionSource() + ); + this.extractAEPower(is, powerPerUse); + return true; + } + } + } + + // clean paint balls.. + final Block testBlk = w.getBlock( + x + orientation.offsetX, + y + orientation.offsetY, + z + orientation.offsetZ + ); + final TileEntity painted = w.getTileEntity( + x + orientation.offsetX, + y + orientation.offsetY, + z + orientation.offsetZ + ); + 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()); + return true; + } + } else if (paintBall != null) { + final AEColor color = this.getColorFromItem(paintBall); + + 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 + )) { + inv.extractItems( + AEItemStack.create(paintBall), + Actionable.MODULATE, + new BaseActionSource() + ); + this.extractAEPower(is, powerPerUse); + return true; + } + } + } + } + + if (p.isSneaking()) { + this.cycleColors(is, paintBall, 1); + } + + return false; + } + + @Override + public String getItemStackDisplayName(final ItemStack par1ItemStack) { + String extra = GuiText.Empty.getLocal(); + + final AEColor selected = this.getActiveColor(par1ItemStack); + + if (selected != null && Platform.isClient()) { + extra = Platform.gui_localize(selected.unlocalizedName); + } + + return super.getItemStackDisplayName(par1ItemStack) + " - " + extra; + } + + public AEColor getActiveColor(final ItemStack tol) { + return this.getColorFromItem(this.getColor(tol)); + } + + private AEColor getColorFromItem(final ItemStack paintBall) { + if (paintBall == null) { + return null; + } + + if (paintBall.getItem() instanceof ItemSnowball) { + return AEColor.Transparent; + } + + if (paintBall.getItem() instanceof ItemPaintBall) { + final ItemPaintBall ipb = (ItemPaintBall) paintBall.getItem(); + return ipb.getColor(paintBall); + } else { + final int[] id = OreDictionary.getOreIDs(paintBall); + + for (final int oreID : id) { + if (ORE_TO_COLOR.containsKey(oreID)) { + return ORE_TO_COLOR.get(oreID); + } + } + } + + return null; + } + + public ItemStack getColor(final ItemStack is) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null && c.hasKey("color")) { + final NBTTagCompound color = c.getCompoundTag("color"); + final ItemStack oldColor = ItemStack.loadItemStackFromNBT(color); + if (oldColor != null) { + return oldColor; + } + } + + return this.findNextColor(is, null, 0); + } + + private ItemStack + findNextColor(final ItemStack is, final ItemStack anchor, final int scrollOffset) { + ItemStack newColor = null; + + final IMEInventory inv + = AEApi.instance().registries().cell().getCellInventory( + is, null, StorageChannel.ITEMS + ); + if (inv != null) { + final IItemList itemList + = inv.getAvailableItems(AEApi.instance().storage().createItemList()); + if (anchor == null) { + final IAEItemStack firstItem = itemList.getFirstItem(); + if (firstItem != null) { + newColor = firstItem.getItemStack(); + } + } else { + final LinkedList list = new LinkedList(); + + for (final IAEItemStack i : itemList) { + list.add(i); + } + + Collections.sort(list, new Comparator() { + @Override + public int compare(final IAEItemStack a, final IAEItemStack b) { + return ItemSorters.compareInt( + a.getItemDamage(), b.getItemDamage() + ); + } + }); + + if (list.size() <= 0) { + return null; + } + + IAEItemStack where = list.getFirst(); + int cycles = 1 + list.size(); + + while (cycles > 0 && !where.equals(anchor)) { + list.addLast(list.removeFirst()); + cycles--; + where = list.getFirst(); + } + + if (scrollOffset > 0) { + list.addLast(list.removeFirst()); + } + + if (scrollOffset < 0) { + list.addFirst(list.removeLast()); + } + + return list.get(0).getItemStack(); + } + } + + if (newColor != null) { + this.setColor(is, newColor); + } + + return newColor; + } + + private void setColor(final ItemStack is, final ItemStack newColor) { + final NBTTagCompound data = Platform.openNbtData(is); + if (newColor == null) { + data.removeTag("color"); + } else { + final NBTTagCompound color = new NBTTagCompound(); + newColor.writeToNBT(color); + data.setTag("color", color); + } + } + + private boolean recolourBlock( + final Block blk, + final ForgeDirection side, + final World w, + final int x, + final int y, + final int z, + final ForgeDirection orientation, + final AEColor newColor, + final EntityPlayer p + ) { + if (blk == Blocks.carpet) { + final int meta = w.getBlockMetadata(x, y, z); + if (newColor.ordinal() == meta) { + return false; + } + return w.setBlock(x, y, z, Blocks.carpet, newColor.ordinal(), 3); + } + + if (blk == Blocks.glass) { + return w.setBlock(x, y, z, Blocks.stained_glass, newColor.ordinal(), 3); + } + + if (blk == Blocks.stained_glass) { + final int meta = w.getBlockMetadata(x, y, z); + if (newColor.ordinal() == meta) { + return false; + } + return w.setBlock(x, y, z, Blocks.stained_glass, newColor.ordinal(), 3); + } + + if (blk == Blocks.glass_pane) { + return w.setBlock(x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3); + } + + if (blk == Blocks.stained_glass_pane) { + final int meta = w.getBlockMetadata(x, y, z); + if (newColor.ordinal() == meta) { + return false; + } + return w.setBlock(x, y, z, Blocks.stained_glass_pane, newColor.ordinal(), 3); + } + + if (blk == Blocks.hardened_clay) { + return w.setBlock( + x, y, z, Blocks.stained_hardened_clay, newColor.ordinal(), 3 + ); + } + + if (blk == Blocks.stained_hardened_clay) { + final int meta = w.getBlockMetadata(x, y, z); + 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); + } + + return blk.recolourBlock(w, x, y, z, side, newColor.ordinal()); + } + + public void cycleColors(final ItemStack is, final ItemStack paintBall, final int i) { + if (paintBall == null) { + this.setColor(is, this.getColor(is)); + } else { + this.setColor(is, this.findNextColor(is, paintBall, i)); + } + } + + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); + + final IMEInventory cdi + = AEApi.instance().registries().cell().getCellInventory( + stack, null, StorageChannel.ITEMS + ); + + if (cdi instanceof CellInventoryHandler) { + final 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() + ); + } + } + } + + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } + + @Override + public int BytePerType(final ItemStack cell) { + return 8; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 27; + } + + @Override + public boolean + isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + if (requestedAddition != null) { + final int[] id = OreDictionary.getOreIDs(requestedAddition.getItemStack()); + + for (final int x : id) { + if (ORE_TO_COLOR.containsKey(x)) { + return false; + } + } + + if (requestedAddition.getItem() instanceof ItemSnowball) { + return false; + } + + return !( + requestedAddition.getItem() instanceof ItemPaintBall + && requestedAddition.getItemDamage() < 20 + ); + } + return true; + } + + @Override + public boolean storableInStorageCell() { + return true; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain() { + return 0.5; + } + + @Override + public String + getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } + + @Override + public boolean isEditable(final ItemStack is) { + return true; + } + + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } + + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } + + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } + + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } + + @Override + public void onWheel(final ItemStack is, final boolean up) { + 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 40ac625c..da78f314 100644 --- a/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java +++ b/src/main/java/appeng/items/tools/powered/ToolEntropyManipulator.java @@ -18,6 +18,7 @@ package appeng.items.tools.powered; +import java.util.*; import appeng.api.util.DimensionalCoord; import appeng.block.misc.BlockTinyTNT; @@ -50,336 +51,423 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; +public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockTool { + private final Map heatUp; + private final Map + coolDown; + public ToolEntropyManipulator() { + super(AEConfig.instance.entropyManipulatorBattery, Optional.absent()); -public class ToolEntropyManipulator extends AEBasePoweredItem implements IBlockTool -{ - private final Map heatUp; - private final Map coolDown; + this.setFeature(EnumSet.of(AEFeature.EntropyManipulator, AEFeature.PoweredTools)); - public ToolEntropyManipulator() - { - super( AEConfig.instance.entropyManipulatorBattery, Optional.absent() ); + this.heatUp + = new HashMap(); + this.coolDown + = new HashMap(); - this.setFeature( EnumSet.of( AEFeature.EntropyManipulator, AEFeature.PoweredTools ) ); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.stone, 0), + new InWorldToolOperationResult(new ItemStack(Blocks.cobblestone)) + ); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.stonebrick, 0), + new InWorldToolOperationResult(new ItemStack(Blocks.stonebrick, 1, 2)) + ); + this.coolDown.put( + new InWorldToolOperationIngredient(Blocks.lava, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(new ItemStack(Blocks.obsidian)) + ); + this.coolDown.put( + new InWorldToolOperationIngredient( + Blocks.flowing_lava, OreDictionary.WILDCARD_VALUE + ), + new InWorldToolOperationResult(new ItemStack(Blocks.obsidian)) + ); + this.coolDown.put( + new InWorldToolOperationIngredient( + Blocks.grass, OreDictionary.WILDCARD_VALUE + ), + new InWorldToolOperationResult(new ItemStack(Blocks.dirt)) + ); - this.heatUp = new HashMap(); - this.coolDown = new HashMap(); + final List snowBalls = new ArrayList(); + snowBalls.add(new ItemStack(Items.snowball)); + this.coolDown.put( + new InWorldToolOperationIngredient( + Blocks.flowing_water, OreDictionary.WILDCARD_VALUE + ), + new InWorldToolOperationResult(null, snowBalls) + ); + this.coolDown.put( + new InWorldToolOperationIngredient( + Blocks.water, OreDictionary.WILDCARD_VALUE + ), + new InWorldToolOperationResult(new ItemStack(Blocks.ice)) + ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.stone, 0 ), new InWorldToolOperationResult( new ItemStack( Blocks.cobblestone ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.stonebrick, 0 ), new InWorldToolOperationResult( new ItemStack( Blocks.stonebrick, 1, 2 ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.lava, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.obsidian ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.flowing_lava, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.obsidian ) ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.grass, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.dirt ) ) ); + this.heatUp.put( + new InWorldToolOperationIngredient(Blocks.ice, 0), + new InWorldToolOperationResult(new ItemStack(Blocks.water)) + ); + this.heatUp.put( + new InWorldToolOperationIngredient( + Blocks.flowing_water, OreDictionary.WILDCARD_VALUE + ), + new InWorldToolOperationResult() + ); + this.heatUp.put( + new InWorldToolOperationIngredient( + Blocks.water, OreDictionary.WILDCARD_VALUE + ), + new InWorldToolOperationResult() + ); + this.heatUp.put( + new InWorldToolOperationIngredient(Blocks.snow, OreDictionary.WILDCARD_VALUE), + new InWorldToolOperationResult(new ItemStack(Blocks.flowing_water)) + ); + } - final List snowBalls = new ArrayList(); - snowBalls.add( new ItemStack( Items.snowball ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.flowing_water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( null, snowBalls ) ); - this.coolDown.put( new InWorldToolOperationIngredient( Blocks.water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.ice ) ) ); + private static final boolean breakBlockWithCheck( + final World w, final EntityPlayer p, final int x, final int y, final int z + ) { + BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( + x, y, z, w, w.getBlock(x, y, z), w.getBlockMetadata(x, y, z), p + ); + MinecraftForge.EVENT_BUS.post(event); + return !event.isCanceled() && w.setBlockToAir(x, y, z); + } - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.ice, 0 ), new InWorldToolOperationResult( new ItemStack( Blocks.water ) ) ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.flowing_water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult() ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.water, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult() ); - this.heatUp.put( new InWorldToolOperationIngredient( Blocks.snow, OreDictionary.WILDCARD_VALUE ), new InWorldToolOperationResult( new ItemStack( Blocks.flowing_water ) ) ); - } + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject(this, new DispenserBlockTool()); + } - private static final boolean breakBlockWithCheck( final World w, final EntityPlayer p, final int x, final int y, final int z ) - { - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, w, w.getBlock( x, y, z ), w.getBlockMetadata( x, y, z ), p ); - MinecraftForge.EVENT_BUS.post( event ); - return !event.isCanceled() && w.setBlockToAir( x, y, z ); - } + private boolean heat( + final Block blockID, + final EntityPlayer p, + final int metadata, + final World w, + final int x, + final int y, + final int z + ) { + if (!breakBlockWithCheck(w, p, x, y, z)) + return false; - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( this, new DispenserBlockTool() ); - } + InWorldToolOperationResult r + = this.heatUp.get(new InWorldToolOperationIngredient(blockID, metadata)); - private boolean heat( final Block blockID, final EntityPlayer p, final int metadata, final World w, final int x, final int y, final int z ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; + if (r == null) { + r = this.heatUp.get( + new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE) + ); + } - InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, metadata ) ); + if (r.getBlockItem() != null) { + w.setBlock( + x, + y, + z, + Block.getBlockFromItem(r.getBlockItem().getItem()), + r.getBlockItem().getItemDamage(), + 3 + ); + } + if (r.getDrops() != null) { + Platform.spawnDrops(w, x, y, z, r.getDrops()); + } - if( r == null ) - { - r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } + return true; + } - if( r.getBlockItem() != null ) - { - w.setBlock( x, y, z, Block.getBlockFromItem( r.getBlockItem().getItem() ), r.getBlockItem().getItemDamage(), 3 ); - } + private boolean canHeat(final Block blockID, final int metadata) { + InWorldToolOperationResult r + = this.heatUp.get(new InWorldToolOperationIngredient(blockID, metadata)); - if( r.getDrops() != null ) - { - Platform.spawnDrops( w, x, y, z, r.getDrops() ); - } + if (r == null) { + r = this.heatUp.get( + new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE) + ); + } - return true; - } + return r != null; + } - private boolean canHeat( final Block blockID, final int metadata ) - { - InWorldToolOperationResult r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, metadata ) ); + private boolean cool( + final Block blockID, + final EntityPlayer p, + final int metadata, + final World w, + final int x, + final int y, + final int z + ) { + if (!breakBlockWithCheck(w, p, x, y, z)) + return false; - if( r == null ) - { - r = this.heatUp.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } + InWorldToolOperationResult r + = this.coolDown.get(new InWorldToolOperationIngredient(blockID, metadata)); - return r != null; - } + if (r == null) { + r = this.coolDown.get( + new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE) + ); + } - private boolean cool( final Block blockID, final EntityPlayer p, final int metadata, final World w, final int x, final int y, final int z ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; + if (r.getBlockItem() != null) { + w.setBlock( + x, + y, + z, + Block.getBlockFromItem(r.getBlockItem().getItem()), + r.getBlockItem().getItemDamage(), + 3 + ); + } - InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, metadata ) ); + if (r.getDrops() != null) { + Platform.spawnDrops(w, x, y, z, r.getDrops()); + } - if( r == null ) - { - r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } + return true; + } - if( r.getBlockItem() != null ) - { - w.setBlock( x, y, z, Block.getBlockFromItem( r.getBlockItem().getItem() ), r.getBlockItem().getItemDamage(), 3 ); - } + private boolean canCool(final Block blockID, final int metadata) { + InWorldToolOperationResult r + = this.coolDown.get(new InWorldToolOperationIngredient(blockID, metadata)); - if( r.getDrops() != null ) - { - Platform.spawnDrops( w, x, y, z, r.getDrops() ); - } + if (r == null) { + r = this.coolDown.get( + new InWorldToolOperationIngredient(blockID, OreDictionary.WILDCARD_VALUE) + ); + } - return true; - } + return r != null; + } - private boolean canCool( final Block blockID, final int metadata ) - { - InWorldToolOperationResult r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, metadata ) ); + @Override + public boolean hitEntity( + final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter + ) { + if (this.getAECurrentPower(item) > 1600) { + this.extractAEPower(item, 1600); + target.setFire(8); + } - if( r == null ) - { - r = this.coolDown.get( new InWorldToolOperationIngredient( blockID, OreDictionary.WILDCARD_VALUE ) ); - } + return false; + } - return r != null; - } + @Override + public ItemStack + onItemRightClick(final ItemStack item, final World w, final EntityPlayer p) { + final MovingObjectPosition target + = this.getMovingObjectPositionFromPlayer(w, p, true); - @Override - public boolean hitEntity( final ItemStack item, final EntityLivingBase target, final EntityLivingBase hitter ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - this.extractAEPower( item, 1600 ); - target.setFire( 8 ); - } + if (target == null) { + return item; + } else { + if (target.typeOfHit == MovingObjectType.BLOCK) { + final int x = target.blockX; + final int y = target.blockY; + final int z = target.blockZ; - return false; - } + 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)) { + this.onItemUse(item, p, w, x, y, z, 0, 0.0F, 0.0F, 0.0F); + } + } + } + } - @Override - public ItemStack onItemRightClick( final ItemStack item, final World w, final EntityPlayer p ) - { - final MovingObjectPosition target = this.getMovingObjectPositionFromPlayer( w, p, true ); + return item; + } - if( target == null ) - { - return item; - } - else - { - if( target.typeOfHit == MovingObjectType.BLOCK ) - { - final int x = target.blockX; - final int y = target.blockY; - final int z = target.blockZ; + @Override + public boolean onItemUse( + final ItemStack item, + final EntityPlayer p, + final World w, + int x, + int y, + int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (this.getAECurrentPower(item) > 1600) { + if (!p.canPlayerEdit(x, y, z, side, item)) { + return false; + } - 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 ) ) - { - this.onItemUse( item, p, w, x, y, z, 0, 0.0F, 0.0F, 0.0F ); - } - } - } - } + final Block blockID = w.getBlock(x, y, z); + final int metadata = w.getBlockMetadata(x, y, z); - return item; - } + if (blockID == null + || ForgeEventFactory + .onPlayerInteract( + p, + blockID.isAir(w, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + w + ) + .isCanceled()) + return false; - @Override - public boolean onItemUse( final ItemStack item, final EntityPlayer p, final World w, int x, int y, int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - if( !p.canPlayerEdit( x, y, z, side, item ) ) - { - return false; - } + if (p.isSneaking()) { + if (this.canCool(blockID, metadata)) { + if (this.cool(blockID, p, metadata, w, x, y, z)) { + this.extractAEPower(item, 1600); + return true; + } + return false; + } + } else { + if (blockID instanceof BlockTNT) { + if (!breakBlockWithCheck(w, p, x, y, z)) + return false; + ((BlockTNT) blockID).func_150114_a(w, x, y, z, 1, p); + return true; + } - final Block blockID = w.getBlock( x, y, z ); - final int metadata = w.getBlockMetadata( x, y, z ); + if (blockID instanceof BlockTinyTNT) { + if (!breakBlockWithCheck(w, p, x, y, z)) + return false; + ((BlockTinyTNT) blockID).startFuse(w, x, y, z, p); + return true; + } - if( blockID == null || ForgeEventFactory.onPlayerInteract( p, - blockID.isAir( w, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, w ).isCanceled() ) - return false; + if (this.canHeat(blockID, metadata)) { + if (this.heat(blockID, p, metadata, w, x, y, z)) { + this.extractAEPower(item, 1600); + return true; + } + return false; + } - if( p.isSneaking() ) - { - if( this.canCool( blockID, metadata ) ) - { - if( this.cool( blockID, p, metadata, w, x, y, z ) ) - { - this.extractAEPower( item, 1600 ); - return true; - } - return false; - } - } - else - { - if( blockID instanceof BlockTNT ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; - ( (BlockTNT) blockID ).func_150114_a( w, x, y, z, 1, p ); - return true; - } + final ItemStack[] stack = Platform.getBlockDrops(w, x, y, z); + final List out = new ArrayList(); + boolean hasFurnaceable = false; + boolean canFurnaceable = true; - if( blockID instanceof BlockTinyTNT ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; - ( (BlockTinyTNT) blockID ).startFuse( w, x, y, z, p ); - return true; - } + for (final ItemStack i : stack) { + final ItemStack result + = FurnaceRecipes.smelting().getSmeltingResult(i); - if( this.canHeat( blockID, metadata ) ) - { - if( this.heat( blockID, p, metadata, w, x, y, z ) ) - { - this.extractAEPower( item, 1600 ); - return true; - } - return false; - } + if (result != null) { + if (result.getItem() instanceof ItemBlock) { + if (Block.getBlockFromItem(result.getItem()) == blockID + && result.getItem().getDamage(result) == metadata) { + canFurnaceable = false; + } + } + hasFurnaceable = true; + out.add(result); + } else { + canFurnaceable = false; + out.add(i); + } + } - final ItemStack[] stack = Platform.getBlockDrops( w, x, y, z ); - final List out = new ArrayList(); - boolean hasFurnaceable = false; - boolean canFurnaceable = true; + if (hasFurnaceable && canFurnaceable) { + if (!breakBlockWithCheck(w, p, x, y, z)) + return false; - for( final ItemStack i : stack ) - { - final ItemStack result = FurnaceRecipes.smelting().getSmeltingResult( i ); + this.extractAEPower(item, 1600); + final 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( result != null ) - { - if( result.getItem() instanceof ItemBlock ) - { - if( Block.getBlockFromItem( result.getItem() ) == blockID && result.getItem().getDamage( result ) == metadata ) - { - canFurnaceable = false; - } - } - hasFurnaceable = true; - out.add( result ); - } - else - { - canFurnaceable = false; - out.add( i ); - } - } + if (or.getBlockItem() != null) { + w.setBlock( + x, + y, + z, + Block.getBlockFromItem(or.getBlockItem().getItem()), + or.getBlockItem().getItemDamage(), + 3 + ); + } - if( hasFurnaceable && canFurnaceable ) - { - if( !breakBlockWithCheck( w, p, x, y, z ) ) - return false; + if (or.getDrops() != null) { + Platform.spawnDrops(w, x, y, z, or.getDrops()); + } - this.extractAEPower( item, 1600 ); - final 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 ); + return true; + } else { + final ForgeDirection dir = ForgeDirection.getOrientation(side); + x += dir.offsetX; + y += dir.offsetY; + z += dir.offsetZ; - if( or.getBlockItem() != null ) - { - w.setBlock( x, y, z, Block.getBlockFromItem( or.getBlockItem().getItem() ), or.getBlockItem().getItemDamage(), 3 ); - } + if (!p.canPlayerEdit(x, y, z, side, item)) { + return false; + } - if( or.getDrops() != null ) - { - Platform.spawnDrops( w, x, y, z, or.getDrops() ); - } + 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 + ); + w.setBlock(x, y, z, Blocks.fire); + } - return true; - } - else - { - final ForgeDirection dir = ForgeDirection.getOrientation( side ); - x += dir.offsetX; - y += dir.offsetY; - z += dir.offsetZ; + return true; + } + } + } - if( !p.canPlayerEdit( x, y, z, side, item ) ) - { - return false; - } + return false; + } - 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 ); - w.setBlock( x, y, z, Blocks.fire ); - } + private static class InWorldToolOperationIngredient { + private final Block blockID; + private final int metadata; - return true; - } - } - } + public InWorldToolOperationIngredient(final Block blockID, final int metadata) { + this.blockID = blockID; + this.metadata = metadata; + } - return false; - } - - private static class InWorldToolOperationIngredient - { - private final Block blockID; - private final int metadata; - - public InWorldToolOperationIngredient( final Block blockID, final int metadata ) - { - this.blockID = blockID; - this.metadata = metadata; - } - - @Override - public int hashCode() - { - return this.blockID.hashCode() ^ this.metadata; - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final InWorldToolOperationIngredient other = (InWorldToolOperationIngredient) obj; - return this.blockID == other.blockID && this.metadata == other.metadata; - } - } + @Override + public int hashCode() { + return this.blockID.hashCode() ^ this.metadata; + } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final InWorldToolOperationIngredient other + = (InWorldToolOperationIngredient) obj; + return this.blockID == other.blockID && this.metadata == other.metadata; + } + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolMassCannon.java b/src/main/java/appeng/items/tools/powered/ToolMassCannon.java index 8eb01c59..88d09a2f 100644 --- a/src/main/java/appeng/items/tools/powered/ToolMassCannon.java +++ b/src/main/java/appeng/items/tools/powered/ToolMassCannon.java @@ -18,6 +18,8 @@ package appeng.items.tools.powered; +import java.util.EnumSet; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -68,470 +70,507 @@ import net.minecraft.util.MovingObjectPosition.MovingObjectType; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; +public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell { + public ToolMassCannon() { + super(AEConfig.instance.matterCannonBattery, Optional.absent()); + this.setFeature(EnumSet.of(AEFeature.MatterCannon, AEFeature.PoweredTools)); + } + @Override + public void postInit() { + super.postInit(); + BlockDispenser.dispenseBehaviorRegistry.putObject( + this, new DispenserMatterCannon() + ); + } -public class ToolMassCannon extends AEBasePoweredItem implements IStorageCell -{ + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); - public ToolMassCannon() - { - super( AEConfig.instance.matterCannonBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.MatterCannon, AEFeature.PoweredTools ) ); - } + final IMEInventory cdi + = AEApi.instance().registries().cell().getCellInventory( + stack, null, StorageChannel.ITEMS + ); - @Override - public void postInit() - { - super.postInit(); - BlockDispenser.dispenseBehaviorRegistry.putObject( this, new DispenserMatterCannon() ); - } + if (cdi instanceof CellInventoryHandler) { + final 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() + ); + } + } + } - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); + @Override + public ItemStack + onItemRightClick(final ItemStack item, final World w, final EntityPlayer p) { + if (this.getAECurrentPower(item) > 1600) { + int shots = 1; - final IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); + final CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory(item); + if (cu != null) { + shots += cu.getInstalledUpgrades(Upgrades.SPEED); + } - if( cdi instanceof CellInventoryHandler ) - { - final 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() ); - } - } - } + final IMEInventory inv + = AEApi.instance().registries().cell().getCellInventory( + item, null, StorageChannel.ITEMS + ); + if (inv != null) { + final IItemList itemList + = inv.getAvailableItems(AEApi.instance().storage().createItemList()); + IAEStack aeAmmo = itemList.getFirstItem(); + if (aeAmmo instanceof IAEItemStack) { + shots = Math.min(shots, (int) aeAmmo.getStackSize()); + for (int sh = 0; sh < shots; sh++) { + this.extractAEPower(item, 1600); - @Override - public ItemStack onItemRightClick( final ItemStack item, final World w, final EntityPlayer p ) - { - if( this.getAECurrentPower( item ) > 1600 ) - { - int shots = 1; + if (Platform.isClient()) { + return item; + } - final CellUpgrades cu = (CellUpgrades) this.getUpgradesInventory( item ); - if( cu != null ) - { - shots += cu.getInstalledUpgrades( Upgrades.SPEED ); - } + aeAmmo.setStackSize(1); + final ItemStack ammo = ((IAEItemStack) aeAmmo).getItemStack(); + if (ammo == null) { + return item; + } - final IMEInventory inv = AEApi.instance().registries().cell().getCellInventory( item, null, StorageChannel.ITEMS ); - if( inv != null ) - { - final IItemList itemList = inv.getAvailableItems( AEApi.instance().storage().createItemList() ); - IAEStack aeAmmo = itemList.getFirstItem(); - if( aeAmmo instanceof IAEItemStack ) - { - shots = Math.min( shots, (int) aeAmmo.getStackSize() ); - for( int sh = 0; sh < shots; sh++ ) - { - this.extractAEPower( item, 1600 ); + ammo.stackSize = 1; + aeAmmo = inv.extractItems( + aeAmmo, Actionable.MODULATE, new PlayerSource(p, null) + ); + if (aeAmmo == null) { + return item; + } - if( Platform.isClient() ) - { - return item; - } + final float f = 1.0F; + final float f1 = p.prevRotationPitch + + (p.rotationPitch - p.prevRotationPitch) * f; + final float f2 + = p.prevRotationYaw + (p.rotationYaw - p.prevRotationYaw) * f; + final double d0 = p.prevPosX + (p.posX - p.prevPosX) * f; + final double d1 + = p.prevPosY + (p.posY - p.prevPosY) * f + 1.62D - p.yOffset; + final double d2 = p.prevPosZ + (p.posZ - p.prevPosZ) * f; + final Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); + final float f3 + = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); + final float f4 + = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); + final float f5 = -MathHelper.cos(-f1 * 0.017453292F); + final float f6 = MathHelper.sin(-f1 * 0.017453292F); + final float f7 = f4 * f5; + final float f8 = f3 * f5; + final double d3 = 32.0D; - aeAmmo.setStackSize( 1 ); - final ItemStack ammo = ( (IAEItemStack) aeAmmo ).getItemStack(); - if( ammo == null ) - { - return item; - } + final Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); + final Vec3 direction + = Vec3.createVectorHelper(f7 * d3, f6 * d3, f8 * d3); + direction.normalize(); - ammo.stackSize = 1; - aeAmmo = inv.extractItems( aeAmmo, Actionable.MODULATE, new PlayerSource( p, null ) ); - if( aeAmmo == null ) - { - return item; - } + final float penetration + = AEApi.instance().registries().matterCannon().getPenetration( + ammo + ); // 196.96655f; + if (penetration <= 0) { + final ItemStack type = ((IAEItemStack) aeAmmo).getItemStack(); + if (type.getItem() instanceof ItemPaintBall) { + this.shootPaintBalls( + type, w, p, vec3, vec31, direction, d0, d1, d2 + ); + } + return item; + } else { + this.standardAmmo( + penetration, w, p, vec3, vec31, direction, d0, d1, d2 + ); + } + } + } else { + if (Platform.isServer()) { + p.addChatMessage(PlayerMessages.AmmoDepleted.get()); + } + return item; + } + } + } + return item; + } - final float f = 1.0F; - final float f1 = p.prevRotationPitch + ( p.rotationPitch - p.prevRotationPitch ) * f; - final float f2 = p.prevRotationYaw + ( p.rotationYaw - p.prevRotationYaw ) * f; - final double d0 = p.prevPosX + ( p.posX - p.prevPosX ) * f; - final double d1 = p.prevPosY + ( p.posY - p.prevPosY ) * f + 1.62D - p.yOffset; - final double d2 = p.prevPosZ + ( p.posZ - p.prevPosZ ) * f; - final Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); - final float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); - final float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); - final float f5 = -MathHelper.cos( -f1 * 0.017453292F ); - final float f6 = MathHelper.sin( -f1 * 0.017453292F ); - final float f7 = f4 * f5; - final float f8 = f3 * f5; - final double d3 = 32.0D; + private void shootPaintBalls( + final ItemStack type, + final World w, + final EntityPlayer p, + final Vec3 vec3, + final Vec3 vec31, + final Vec3 direction, + final double d0, + final double d1, + final double d2 + ) { + final 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); - final Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - final Vec3 direction = Vec3.createVectorHelper( f7 * d3, f6 * d3, f8 * d3 ); - direction.normalize(); + Entity entity = null; + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + double closest = 9999999.0D; - final float penetration = AEApi.instance().registries().matterCannon().getPenetration( ammo ); // 196.96655f; - if( penetration <= 0 ) - { - final ItemStack type = ( (IAEItemStack) aeAmmo ).getItemStack(); - if( type.getItem() instanceof ItemPaintBall ) - { - this.shootPaintBalls( type, w, p, vec3, vec31, direction, d0, d1, d2 ); - } - return item; - } - else - { - this.standardAmmo( penetration, w, p, vec3, vec31, direction, d0, d1, d2 ); - } - } - } - else - { - if( Platform.isServer() ) - { - p.addChatMessage( PlayerMessages.AmmoDepleted.get() ); - } - return item; - } - } - } - return item; - } + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); - private void shootPaintBalls( final ItemStack type, final World w, final EntityPlayer p, final Vec3 vec3, final Vec3 vec31, final Vec3 direction, final double d0, final double d1, final double d2 ) - { - final 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 ); + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.riddenByEntity == p) { + continue; + } - Entity entity = null; - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - double closest = 9999999.0D; + final float f1 = 0.3F; - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); + final AxisAlignedBB boundingBox + = entity1.boundingBox.expand(f1, f1, f1); + final MovingObjectPosition movingObjectPosition + = boundingBox.calculateIntercept(vec3, vec31); - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.riddenByEntity == p ) - { - continue; - } + if (movingObjectPosition != null) { + final double nd + = vec3.squareDistanceTo(movingObjectPosition.hitVec); - final float f1 = 0.3F; + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } - final AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); - final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); + MovingObjectPosition pos = w.rayTraceBlocks(vec3, vec31, false); - if( movingObjectPosition != null ) - { - final double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); + final Vec3 vec = Vec3.createVectorHelper(d0, d1, d2); + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new MovingObjectPosition(entity); + } else if (entity != null && pos == null) { + pos = new MovingObjectPosition(entity); + } - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } + 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) + ) + ); + } catch (final Exception err) { + AELog.debug(err); + } - MovingObjectPosition pos = w.rayTraceBlocks( vec3, vec31, false ); + if (pos != null && type != null && type.getItem() instanceof ItemPaintBall) { + final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); - final Vec3 vec = Vec3.createVectorHelper( d0, d1, d2 ); - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new MovingObjectPosition( entity ); - } - else if( entity != null && pos == null ) - { - pos = new MovingObjectPosition( entity ); - } + final AEColor col = ipb.getColor(type); + // boolean lit = ipb.isLumen( type ); - 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 ) ) ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } + if (pos.typeOfHit == MovingObjectType.ENTITY) { + final int id = pos.entityHit.getEntityId(); + final PlayerColor marker = new PlayerColor(id, col, 20 * 30); + TickHandler.INSTANCE.getPlayerColors().put(id, marker); - if( pos != null && type != null && type.getItem() instanceof ItemPaintBall ) - { - final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); + if (pos.entityHit instanceof EntitySheep) { + final EntitySheep sh = (EntitySheep) pos.entityHit; + sh.setFleeceColor(col.ordinal()); + } - final AEColor col = ipb.getColor( type ); - // boolean lit = ipb.isLumen( type ); + pos.entityHit.attackEntityFrom(DamageSource.causePlayerDamage(p), 0); + NetworkHandler.instance.sendToAll(marker.getPacket()); + } else if (pos.typeOfHit == MovingObjectType.BLOCK) { + final ForgeDirection side = ForgeDirection.getOrientation(pos.sideHit); - if( pos.typeOfHit == MovingObjectType.ENTITY ) - { - final int id = pos.entityHit.getEntityId(); - final PlayerColor marker = new PlayerColor( id, col, 20 * 30 ); - TickHandler.INSTANCE.getPlayerColors().put( id, marker ); + final int x = pos.blockX + side.offsetX; + final int y = pos.blockY + side.offsetY; + final int z = pos.blockZ + side.offsetZ; - if( pos.entityHit instanceof EntitySheep ) - { - final EntitySheep sh = (EntitySheep) pos.entityHit; - sh.setFleeceColor( col.ordinal() ); - } + if (!Platform.hasPermissions(new DimensionalCoord(w, x, y, z), p)) { + return; + } - pos.entityHit.attackEntityFrom( DamageSource.causePlayerDamage( p ), 0 ); - NetworkHandler.instance.sendToAll( marker.getPacket() ); - } - else if( pos.typeOfHit == MovingObjectType.BLOCK ) - { - final ForgeDirection side = ForgeDirection.getOrientation( pos.sideHit ); + final Block whatsThere = w.getBlock(x, y, z); + if (whatsThere.isReplaceable(w, x, y, z) && w.isAirBlock(x, y, z)) { + for (final Block paintBlock : AEApi.instance() + .definitions() + .blocks() + .paint() + .maybeBlock() + .asSet()) { + w.setBlock(x, y, z, paintBlock, 0, 3); + } + } - final int x = pos.blockX + side.offsetX; - final int y = pos.blockY + side.offsetY; - final int z = pos.blockZ + side.offsetZ; + final TileEntity te = w.getTileEntity(x, y, z); + if (te instanceof TilePaint) { + pos.hitVec.xCoord -= x; + pos.hitVec.yCoord -= y; + pos.hitVec.zCoord -= z; + ((TilePaint) te).addBlot(type, side.getOpposite(), pos.hitVec); + } + } + } + } - if( !Platform.hasPermissions( new DimensionalCoord( w, x, y, z ), p ) ) - { - return; - } + private void standardAmmo( + float penetration, + final World w, + final EntityPlayer p, + final Vec3 vec3, + final Vec3 vec31, + final Vec3 direction, + final double d0, + final double d1, + final double d2 + ) { + boolean hasDestroyed = true; + while (penetration > 0 && hasDestroyed) { + hasDestroyed = false; - final Block whatsThere = w.getBlock( x, y, z ); - if( whatsThere.isReplaceable( w, x, y, z ) && w.isAirBlock( x, y, z ) ) - { - for( final Block paintBlock : AEApi.instance().definitions().blocks().paint().maybeBlock().asSet() ) - { - w.setBlock( x, y, z, paintBlock, 0, 3 ); - } - } + final 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); - final TileEntity te = w.getTileEntity( x, y, z ); - if( te instanceof TilePaint ) - { - pos.hitVec.xCoord -= x; - pos.hitVec.yCoord -= y; - pos.hitVec.zCoord -= z; - ( (TilePaint) te ).addBlot( type, side.getOpposite(), pos.hitVec ); - } - } - } - } + Entity entity = null; + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + double closest = 9999999.0D; - private void standardAmmo( float penetration, final World w, final EntityPlayer p, final Vec3 vec3, final Vec3 vec31, final Vec3 direction, final double d0, final double d1, final double d2 ) - { - boolean hasDestroyed = true; - while( penetration > 0 && hasDestroyed ) - { - hasDestroyed = false; + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); - final 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 ); + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.riddenByEntity == p) { + continue; + } - Entity entity = null; - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - double closest = 9999999.0D; + final float f1 = 0.3F; - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); + final AxisAlignedBB boundingBox + = entity1.boundingBox.expand(f1, f1, f1); + final MovingObjectPosition movingObjectPosition + = boundingBox.calculateIntercept(vec3, vec31); - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.riddenByEntity == p ) - { - continue; - } + if (movingObjectPosition != null) { + final double nd + = vec3.squareDistanceTo(movingObjectPosition.hitVec); - final float f1 = 0.3F; + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } - final AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); - final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); + final Vec3 vec = Vec3.createVectorHelper(d0, d1, d2); + MovingObjectPosition pos = w.rayTraceBlocks(vec3, vec31, true); + if (entity != null && pos != null + && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new MovingObjectPosition(entity); + } else if (entity != null && pos == null) { + pos = new MovingObjectPosition(entity); + } - if( movingObjectPosition != null ) - { - final double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); + 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) + ) + ); + } catch (final Exception err) { + AELog.debug(err); + } - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } + if (pos != null) { + final DamageSource dmgSrc = DamageSource.causePlayerDamage(p); + dmgSrc.damageType = "masscannon"; - final Vec3 vec = Vec3.createVectorHelper( d0, d1, d2 ); - MovingObjectPosition pos = w.rayTraceBlocks( vec3, vec31, true ); - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new MovingObjectPosition( entity ); - } - else if( entity != null && pos == null ) - { - pos = new MovingObjectPosition( entity ); - } + if (pos.typeOfHit == MovingObjectType.ENTITY) { + final int dmg = (int) Math.ceil(penetration / 20.0f); + if (pos.entityHit instanceof EntityLivingBase) { + final 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()) { + hasDestroyed = true; + } + } else if (pos.entityHit instanceof EntityItem) { + hasDestroyed = true; + pos.entityHit.setDead(); + } else if (pos.entityHit.attackEntityFrom(dmgSrc, dmg)) { + hasDestroyed = true; + } + } else if (pos.typeOfHit == MovingObjectType.BLOCK) { + if (!AEConfig.instance.isFeatureEnabled( + AEFeature.MassCannonBlockDamage + )) { + penetration = 0; + } else { + final Block b = w.getBlock(pos.blockX, pos.blockY, pos.blockZ); + // int meta = w.getBlockMetadata( + // pos.blockX, pos.blockY, pos.blockZ ); - 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 ) ) ); - } - catch( final Exception err ) - { - AELog.debug( err ); - } + final float hardness + = b.getBlockHardness(w, pos.blockX, pos.blockY, pos.blockZ) + * 9.0f; + if (hardness >= 0.0) { + if (penetration > hardness + && Platform.hasPermissions( + new DimensionalCoord( + w, pos.blockX, pos.blockY, pos.blockZ + ), + p + )) { + hasDestroyed = true; + penetration -= hardness; + penetration *= 0.60; + w.func_147480_a(pos.blockX, pos.blockY, pos.blockZ, true); + // w.destroyBlock( pos.blockX, pos.blockY, pos.blockZ, + // true ); + } + } + } + } + } + } + } - if( pos != null ) - { - final DamageSource dmgSrc = DamageSource.causePlayerDamage( p ); - dmgSrc.damageType = "masscannon"; + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - if( pos.typeOfHit == MovingObjectType.ENTITY ) - { - final int dmg = (int) Math.ceil( penetration / 20.0f ); - if( pos.entityHit instanceof EntityLivingBase ) - { - final 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() ) - { - hasDestroyed = true; - } - } - else if( pos.entityHit instanceof EntityItem ) - { - hasDestroyed = true; - pos.entityHit.setDead(); - } - else if( pos.entityHit.attackEntityFrom( dmgSrc, dmg ) ) - { - hasDestroyed = true; - } - } - else if( pos.typeOfHit == MovingObjectType.BLOCK ) - { - if( !AEConfig.instance.isFeatureEnabled( AEFeature.MassCannonBlockDamage ) ) - { - penetration = 0; - } - else - { - final Block b = w.getBlock( pos.blockX, pos.blockY, pos.blockZ ); - // int meta = w.getBlockMetadata( - // pos.blockX, pos.blockY, pos.blockZ ); + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 4); + } - final float hardness = b.getBlockHardness( w, pos.blockX, pos.blockY, pos.blockZ ) * 9.0f; - if( hardness >= 0.0 ) - { - if( penetration > hardness && Platform.hasPermissions( new DimensionalCoord( w, pos.blockX, pos.blockY, pos.blockZ ), p ) ) - { - hasDestroyed = true; - penetration -= hardness; - penetration *= 0.60; - w.func_147480_a( pos.blockX, pos.blockY, pos.blockZ, true ); - // w.destroyBlock( pos.blockX, pos.blockY, pos.blockZ, true ); - } - } - } - } - } - } - } + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 4 ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } + @Override + public int BytePerType(final ItemStack cell) { + return 8; + } - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 1; + } - @Override - public int BytePerType( final ItemStack cell ) - { - return 8; - } + @Override + public boolean + isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + final float pen = AEApi.instance().registries().matterCannon().getPenetration( + requestedAddition.getItemStack() + ); + if (pen > 0) { + return false; + } - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } + return !(requestedAddition.getItem() instanceof ItemPaintBall); + } - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 1; - } + @Override + public boolean storableInStorageCell() { + return true; + } - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - final float pen = AEApi.instance().registries().matterCannon().getPenetration( requestedAddition.getItemStack() ); - if( pen > 0 ) - { - return false; - } + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } - return !( requestedAddition.getItem() instanceof ItemPaintBall ); - } - - @Override - public boolean storableInStorageCell() - { - return true; - } - - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } - - @Override - public double getIdleDrain() - { - return 0.5; - } + @Override + public double getIdleDrain() { + return 0.5; + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java index 29c4fa97..dcbeb397 100644 --- a/src/main/java/appeng/items/tools/powered/ToolPortableCell.java +++ b/src/main/java/appeng/items/tools/powered/ToolPortableCell.java @@ -18,6 +18,9 @@ package appeng.items.tools.powered; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; import appeng.api.AEApi; import appeng.api.config.FuzzyMode; @@ -49,146 +52,140 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; +public class ToolPortableCell + extends AEBasePoweredItem implements IStorageCell, IGuiItem, IItemGroup { + public ToolPortableCell() { + super(AEConfig.instance.portableCellBattery, Optional.absent()); + this.setFeature(EnumSet.of( + AEFeature.PortableCell, AEFeature.StorageCells, AEFeature.PoweredTools + )); + } + @Override + public ItemStack + onItemRightClick(final ItemStack item, final World w, final EntityPlayer player) { + Platform.openGUI( + player, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_PORTABLE_CELL + ); + return item; + } -public class ToolPortableCell extends AEBasePoweredItem implements IStorageCell, IGuiItem, IItemGroup -{ - public ToolPortableCell() - { - 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( final ItemStack item, final World w, final EntityPlayer player ) - { - Platform.openGUI( player, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_PORTABLE_CELL ); - return item; - } + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); - @SideOnly( Side.CLIENT ) - @Override - public boolean isFull3D() - { - return false; - } + final IMEInventory cdi + = AEApi.instance().registries().cell().getCellInventory( + stack, null, StorageChannel.ITEMS + ); - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); + if (cdi instanceof CellInventoryHandler) { + final 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() + ); + } + } + } - final IMEInventory cdi = AEApi.instance().registries().cell().getCellInventory( stack, null, StorageChannel.ITEMS ); + @Override + public int getBytes(final ItemStack cellItem) { + return 512; + } - if( cdi instanceof CellInventoryHandler ) - { - final 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() ); - } - } - } + @Override + public int BytePerType(final ItemStack cell) { + return 8; + } - @Override - public int getBytes( final ItemStack cellItem ) - { - return 512; - } + @Override + public int getBytesPerType(final ItemStack cellItem) { + return 8; + } - @Override - public int BytePerType( final ItemStack cell ) - { - return 8; - } + @Override + public int getTotalTypes(final ItemStack cellItem) { + return 27; + } - @Override - public int getBytesPerType( final ItemStack cellItem ) - { - return 8; - } + @Override + public boolean + isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + return false; + } - @Override - public int getTotalTypes( final ItemStack cellItem ) - { - return 27; - } + @Override + public boolean storableInStorageCell() { + return false; + } - @Override - public boolean isBlackListed( final ItemStack cellItem, final IAEItemStack requestedAddition ) - { - return false; - } + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } - @Override - public boolean storableInStorageCell() - { - return false; - } + @Override + public double getIdleDrain() { + return 0.5; + } - @Override - public boolean isStorageCell( final ItemStack i ) - { - return true; - } + @Override + public String + getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } - @Override - public double getIdleDrain() - { - return 0.5; - } + @Override + public boolean isEditable(final ItemStack is) { + return true; + } - @Override - public String getUnlocalizedGroupName( final Set others, final ItemStack is ) - { - return GuiText.StorageCells.getUnlocalized(); - } + @Override + public IInventory getUpgradesInventory(final ItemStack is) { + return new CellUpgrades(is, 2); + } - @Override - public boolean isEditable( final ItemStack is ) - { - return true; - } + @Override + public IInventory getConfigInventory(final ItemStack is) { + return new CellConfig(is); + } - @Override - public IInventory getUpgradesInventory( final ItemStack is ) - { - return new CellUpgrades( is, 2 ); - } + @Override + public FuzzyMode getFuzzyMode(final ItemStack is) { + final String fz = Platform.openNbtData(is).getString("FuzzyMode"); + try { + return FuzzyMode.valueOf(fz); + } catch (final Throwable t) { + return FuzzyMode.IGNORE_ALL; + } + } - @Override - public IInventory getConfigInventory( final ItemStack is ) - { - return new CellConfig( is ); - } + @Override + public void setFuzzyMode(final ItemStack is, final FuzzyMode fzMode) { + Platform.openNbtData(is).setString("FuzzyMode", fzMode.name()); + } - @Override - public FuzzyMode getFuzzyMode( final ItemStack is ) - { - final String fz = Platform.openNbtData( is ).getString( "FuzzyMode" ); - try - { - return FuzzyMode.valueOf( fz ); - } - catch( final Throwable t ) - { - return FuzzyMode.IGNORE_ALL; - } - } - - @Override - public void setFuzzyMode( final ItemStack is, final FuzzyMode fzMode ) - { - Platform.openNbtData( is ).setString( "FuzzyMode", fzMode.name() ); - } - - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World w, final int x, final int y, final int z ) - { - return new PortableCellViewer( is, x ); - } + @Override + public IGuiItemObject getGuiObject( + final ItemStack is, final World w, final int x, final int y, final int z + ) { + return new PortableCellViewer(is, x); + } } diff --git a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java index 07178313..65ec0976 100644 --- a/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java +++ b/src/main/java/appeng/items/tools/powered/ToolWirelessTerminal.java @@ -18,6 +18,8 @@ package appeng.items.tools.powered; +import java.util.EnumSet; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.Settings; @@ -43,114 +45,104 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.World; import net.minecraftforge.event.ForgeEventFactory; -import java.util.EnumSet; -import java.util.List; +public class ToolWirelessTerminal + extends AEBasePoweredItem implements IWirelessTermHandler { + public ToolWirelessTerminal() { + super(AEConfig.instance.wirelessTerminalBattery, Optional.absent()); + this.setFeature( + EnumSet.of(AEFeature.WirelessAccessTerminal, AEFeature.PoweredTools) + ); + } + @Override + public ItemStack + onItemRightClick(final ItemStack item, final World w, final EntityPlayer player) { + if (ForgeEventFactory.onItemUseStart(player, item, 1) > 0) + AEApi.instance().registries().wireless().openWirelessTerminalGui( + item, w, player + ); + return item; + } -public class ToolWirelessTerminal extends AEBasePoweredItem implements IWirelessTermHandler -{ + @SideOnly(Side.CLIENT) + @Override + public boolean isFull3D() { + return false; + } - public ToolWirelessTerminal() - { - super( AEConfig.instance.wirelessTerminalBattery, Optional.absent() ); - this.setFeature( EnumSet.of( AEFeature.WirelessAccessTerminal, AEFeature.PoweredTools ) ); - } + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + super.addCheckedInformation(stack, player, lines, displayMoreInfo); - @Override - public ItemStack onItemRightClick( final ItemStack item, final World w, final EntityPlayer player ) - { - if( ForgeEventFactory.onItemUseStart( player, item, 1 ) > 0 ) - AEApi.instance().registries().wireless().openWirelessTerminalGui( item, w, player ); - return item; - } + if (stack.hasTagCompound()) { + final NBTTagCompound tag = Platform.openNbtData(stack); + if (tag != null) { + final String encKey = tag.getString("encryptionKey"); - @SideOnly( Side.CLIENT ) - @Override - public boolean isFull3D() - { - return false; - } + if (encKey == null || encKey.isEmpty()) { + lines.add(GuiText.Unlinked.getLocal()); + } else { + lines.add(GuiText.Linked.getLocal()); + } + } + } else { + lines.add(StatCollector.translateToLocal("AppEng.GuiITooltip.Unlinked")); + } + } - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - super.addCheckedInformation( stack, player, lines, displayMoreInfo ); + @Override + public boolean canHandle(final ItemStack is) { + return AEApi.instance().definitions().items().wirelessTerminal().isSameAs(is); + } - if( stack.hasTagCompound() ) - { - final NBTTagCompound tag = Platform.openNbtData( stack ); - if( tag != null ) - { - final String encKey = tag.getString( "encryptionKey" ); + @Override + public boolean + usePower(final EntityPlayer player, final double amount, final ItemStack is) { + return this.extractAEPower(is, amount) >= amount - 0.5; + } - if( encKey == null || encKey.isEmpty() ) - { - lines.add( GuiText.Unlinked.getLocal() ); - } - else - { - lines.add( GuiText.Linked.getLocal() ); - } - } - } - else - { - lines.add( StatCollector.translateToLocal( "AppEng.GuiITooltip.Unlinked" ) ); - } - } + @Override + public boolean + hasPower(final EntityPlayer player, final double amt, final ItemStack is) { + return this.getAECurrentPower(is) >= amt; + } - @Override - public boolean canHandle( final ItemStack is ) - { - return AEApi.instance().definitions().items().wirelessTerminal().isSameAs( is ); - } + @Override + public IConfigManager getConfigManager(final ItemStack target) { + final ConfigManager out = new ConfigManager(new IConfigManagerHost() { + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + final NBTTagCompound data = Platform.openNbtData(target); + manager.writeToNBT(data); + } + }); - @Override - public boolean usePower( final EntityPlayer player, final double amount, final ItemStack is ) - { - return this.extractAEPower( is, amount ) >= amount - 0.5; - } + out.registerSetting(Settings.SORT_BY, SortOrder.NAME); + out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); - @Override - public boolean hasPower( final EntityPlayer player, final double amt, final ItemStack is ) - { - return this.getAECurrentPower( is ) >= amt; - } + out.readFromNBT((NBTTagCompound) Platform.openNbtData(target).copy()); + return out; + } - @Override - public IConfigManager getConfigManager( final ItemStack target ) - { - final ConfigManager out = new ConfigManager( new IConfigManagerHost() - { + @Override + public String getEncryptionKey(final ItemStack item) { + final NBTTagCompound tag = Platform.openNbtData(item); + return tag.getString("encryptionKey"); + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - final 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() ); - return out; - } - - @Override - public String getEncryptionKey( final ItemStack item ) - { - final NBTTagCompound tag = Platform.openNbtData( item ); - return tag.getString( "encryptionKey" ); - } - - @Override - public void setEncryptionKey( final ItemStack item, final String encKey, final String name ) - { - final NBTTagCompound tag = Platform.openNbtData( item ); - tag.setString( "encryptionKey", encKey ); - tag.setString( "name", name ); - } + @Override + public void + setEncryptionKey(final ItemStack item, final String encKey, final String name) { + final NBTTagCompound tag = Platform.openNbtData(item); + tag.setString("encryptionKey", encKey); + tag.setString("name", name); + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java b/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java index 9cd1dedb..a1add405 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java +++ b/src/main/java/appeng/items/tools/powered/powersink/AEBasePoweredItem.java @@ -18,16 +18,12 @@ package appeng.items.tools.powered.powersink; - import com.google.common.base.Optional; +public abstract class AEBasePoweredItem extends RedstoneFlux { + public AEBasePoweredItem(final double powerCapacity, final Optional subName) { + super(powerCapacity, subName); -public abstract class AEBasePoweredItem extends RedstoneFlux -{ - public AEBasePoweredItem( final double powerCapacity, final Optional subName ) - { - super( powerCapacity, subName ); - - this.setMaxStackSize( 1 ); - } + this.setMaxStackSize(1); + } } 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 4b782645..bcb302fc 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java +++ b/src/main/java/appeng/items/tools/powered/powersink/AERootPoweredItem.java @@ -18,6 +18,8 @@ package appeng.items.tools.powered.powersink; +import java.text.MessageFormat; +import java.util.List; import appeng.api.config.AccessRestriction; import appeng.api.config.PowerUnits; @@ -32,173 +34,165 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.text.MessageFormat; -import java.util.List; +public abstract class AERootPoweredItem + extends AEBaseItem implements IAEItemPowerStorage { + private static final String POWER_NBT_KEY = "internalCurrentPower"; + private final double powerCapacity; + public AERootPoweredItem(final double powerCapacity, final Optional subName) { + super(subName); + this.setMaxDamage(32); + this.hasSubtypes = false; + this.setFull3D(); -public abstract class AERootPoweredItem extends AEBaseItem implements IAEItemPowerStorage -{ - private static final String POWER_NBT_KEY = "internalCurrentPower"; - private final double powerCapacity; + this.powerCapacity = powerCapacity; + } - public AERootPoweredItem( final double powerCapacity, final Optional subName ) - { - super( subName ); - this.setMaxDamage( 32 ); - this.hasSubtypes = false; - this.setFull3D(); + @Override + public void addCheckedInformation( + final ItemStack stack, + final EntityPlayer player, + final List lines, + final boolean displayMoreInfo + ) { + final NBTTagCompound tag = stack.getTagCompound(); + double internalCurrentPower = 0; + final double internalMaxPower = this.getAEMaxPower(stack); - this.powerCapacity = powerCapacity; - } + if (tag != null) { + internalCurrentPower = tag.getDouble("internalCurrentPower"); + } - @Override - public void addCheckedInformation( final ItemStack stack, final EntityPlayer player, final List lines, final boolean displayMoreInfo ) - { - final NBTTagCompound tag = stack.getTagCompound(); - double internalCurrentPower = 0; - final double internalMaxPower = this.getAEMaxPower( stack ); + final double percent = internalCurrentPower / internalMaxPower; - if( tag != null ) - { - internalCurrentPower = tag.getDouble( "internalCurrentPower" ); - } + lines.add( + GuiText.StoredEnergy.getLocal() + ':' + + MessageFormat.format(" {0,number,#} ", internalCurrentPower) + + Platform.gui_localize(PowerUnits.AE.unlocalizedName) + " - " + + MessageFormat.format(" {0,number,#.##%} ", percent) + ); + } - final double percent = internalCurrentPower / internalMaxPower; + @Override + public boolean isDamageable() { + return true; + } - lines.add( GuiText.StoredEnergy.getLocal() + ':' + MessageFormat.format( " {0,number,#} ", internalCurrentPower ) + Platform.gui_localize( PowerUnits.AE.unlocalizedName ) + " - " + MessageFormat.format( " {0,number,#.##%} ", percent ) ); - } + @Override + protected void getCheckedSubItems( + final Item sameItem, + final CreativeTabs creativeTab, + final List itemStacks + ) { + super.getCheckedSubItems(sameItem, creativeTab, itemStacks); - @Override - public boolean isDamageable() - { - return true; - } + final ItemStack charged = new ItemStack(this, 1); + final NBTTagCompound tag = Platform.openNbtData(charged); + tag.setDouble("internalCurrentPower", this.getAEMaxPower(charged)); + tag.setDouble("internalMaxPower", this.getAEMaxPower(charged)); - @Override - protected void getCheckedSubItems( final Item sameItem, final CreativeTabs creativeTab, final List itemStacks ) - { - super.getCheckedSubItems( sameItem, creativeTab, itemStacks ); + itemStacks.add(charged); + } - final ItemStack charged = new ItemStack( this, 1 ); - final NBTTagCompound tag = Platform.openNbtData( charged ); - tag.setDouble( "internalCurrentPower", this.getAEMaxPower( charged ) ); - tag.setDouble( "internalMaxPower", this.getAEMaxPower( charged ) ); + @Override + public boolean isRepairable() { + return false; + } - itemStacks.add( charged ); - } + @Override + public double getDurabilityForDisplay(final ItemStack is) { + return 1 - this.getAECurrentPower(is) / this.getAEMaxPower(is); + } - @Override - public boolean isRepairable() - { - return false; - } + @Override + public boolean isDamaged(final ItemStack stack) { + return true; + } - @Override - public double getDurabilityForDisplay( final ItemStack is ) - { - return 1 - this.getAECurrentPower( is ) / this.getAEMaxPower( is ); - } + @Override + public void setDamage(final ItemStack stack, final int damage) {} - @Override - public boolean isDamaged( final ItemStack stack ) - { - return true; - } + private double getInternalBattery( + final ItemStack is, final batteryOperation op, final double adjustment + ) { + final NBTTagCompound data = Platform.openNbtData(is); - @Override - public void setDamage( final ItemStack stack, final int damage ) - { + double currentStorage = data.getDouble(POWER_NBT_KEY); + final double maxStorage = this.getAEMaxPower(is); - } + switch (op) { + case INJECT: + currentStorage += adjustment; + if (currentStorage > maxStorage) { + final double diff = currentStorage - maxStorage; + data.setDouble(POWER_NBT_KEY, maxStorage); + return diff; + } + data.setDouble(POWER_NBT_KEY, currentStorage); + return 0; + case EXTRACT: + if (currentStorage > adjustment) { + currentStorage -= adjustment; + data.setDouble(POWER_NBT_KEY, currentStorage); + return adjustment; + } + data.setDouble(POWER_NBT_KEY, 0); + return currentStorage; + default: + break; + } - private double getInternalBattery( final ItemStack is, final batteryOperation op, final double adjustment ) - { - final NBTTagCompound data = Platform.openNbtData( is ); + return currentStorage; + } - double currentStorage = data.getDouble( POWER_NBT_KEY ); - final double maxStorage = this.getAEMaxPower( is ); + /** + * inject external + */ + double injectExternalPower( + final PowerUnits input, + final ItemStack is, + final double amount, + final boolean simulate + ) { + if (simulate) { + final int requiredEU = (int) PowerUnits.AE.convertTo( + PowerUnits.EU, this.getAEMaxPower(is) - this.getAECurrentPower(is) + ); + if (amount < requiredEU) { + return 0; + } + return amount - requiredEU; + } else { + final double powerRemainder + = this.injectAEPower(is, PowerUnits.EU.convertTo(PowerUnits.AE, amount)); + return PowerUnits.AE.convertTo(PowerUnits.EU, powerRemainder); + } + } - switch( op ) - { - case INJECT: - currentStorage += adjustment; - if( currentStorage > maxStorage ) - { - final double diff = currentStorage - maxStorage; - data.setDouble( POWER_NBT_KEY, maxStorage ); - return diff; - } - data.setDouble( POWER_NBT_KEY, currentStorage ); - return 0; - case EXTRACT: - if( currentStorage > adjustment ) - { - currentStorage -= adjustment; - data.setDouble( POWER_NBT_KEY, currentStorage ); - return adjustment; - } - data.setDouble( POWER_NBT_KEY, 0 ); - return currentStorage; - default: - break; - } + @Override + public double injectAEPower(final ItemStack is, final double amt) { + return this.getInternalBattery(is, batteryOperation.INJECT, amt); + } - return currentStorage; - } + @Override + public double extractAEPower(final ItemStack is, final double amt) { + return this.getInternalBattery(is, batteryOperation.EXTRACT, amt); + } - /** - * inject external - */ - double injectExternalPower( final PowerUnits input, final ItemStack is, final double amount, final boolean simulate ) - { - if( simulate ) - { - final int requiredEU = (int) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAEMaxPower( is ) - this.getAECurrentPower( is ) ); - if( amount < requiredEU ) - { - return 0; - } - return amount - requiredEU; - } - else - { - final double powerRemainder = this.injectAEPower( is, PowerUnits.EU.convertTo( PowerUnits.AE, amount ) ); - return PowerUnits.AE.convertTo( PowerUnits.EU, powerRemainder ); - } - } + @Override + public double getAEMaxPower(final ItemStack is) { + return this.powerCapacity; + } - @Override - public double injectAEPower( final ItemStack is, final double amt ) - { - return this.getInternalBattery( is, batteryOperation.INJECT, amt ); - } + @Override + public double getAECurrentPower(final ItemStack is) { + return this.getInternalBattery(is, batteryOperation.STORAGE, 0); + } - @Override - public double extractAEPower( final ItemStack is, final double amt ) - { - return this.getInternalBattery( is, batteryOperation.EXTRACT, amt ); - } + @Override + public AccessRestriction getPowerFlow(final ItemStack is) { + return AccessRestriction.WRITE; + } - @Override - public double getAEMaxPower( final ItemStack is ) - { - return this.powerCapacity; - } - - @Override - public double getAECurrentPower( final ItemStack is ) - { - return this.getInternalBattery( is, batteryOperation.STORAGE, 0 ); - } - - @Override - public AccessRestriction getPowerFlow( final ItemStack is ) - { - return AccessRestriction.WRITE; - } - - private enum batteryOperation - { - STORAGE, INJECT, EXTRACT - } + private enum batteryOperation { 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 f7949353..bbe555a4 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/IC2.java +++ b/src/main/java/appeng/items/tools/powered/powersink/IC2.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; @@ -31,111 +30,109 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - @InterfaceList( value = { @Interface( iface = "ic2.api.item.ISpecialElectricItem", iname = IntegrationType.IC2 ), @Interface( iface = "ic2.api.item.IElectricItemManager", iname = IntegrationType.IC2 ) } ) public abstract class IC2 extends AERootPoweredItem implements IElectricItemManager, ISpecialElectricItem { - public IC2( final double powerCapacity, final Optional subName ) - { - super( powerCapacity, subName ); - } + public IC2(final double powerCapacity, final Optional subName) { + super(powerCapacity, subName); + } - @Override - public double charge( final ItemStack is, final double amount, final int tier, final boolean ignoreTransferLimit, final boolean simulate ) - { - double addedAmt = amount; - final double limit = this.getTransferLimit( is ); + @Override + public double charge( + final ItemStack is, + final double amount, + final int tier, + final boolean ignoreTransferLimit, + final boolean simulate + ) { + double addedAmt = amount; + final double limit = this.getTransferLimit(is); - if( !ignoreTransferLimit && amount > limit ) - { - addedAmt = 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 - public double discharge( final ItemStack itemStack, final double amount, final int tier, final boolean ignoreTransferLimit, final boolean externally, final boolean simulate ) - { - return 0; - } + @Override + public double discharge( + final ItemStack itemStack, + final double amount, + final int tier, + final boolean ignoreTransferLimit, + final boolean externally, + final boolean simulate + ) { + return 0; + } - @Override - public double getCharge( final ItemStack is ) - { - return (int) PowerUnits.AE.convertTo( PowerUnits.EU, this.getAECurrentPower( is ) ); - } + @Override + public double getCharge(final ItemStack is) { + return (int) PowerUnits.AE.convertTo(PowerUnits.EU, this.getAECurrentPower(is)); + } - @Override - public boolean canUse( final ItemStack is, final double amount ) - { - return this.getCharge( is ) > amount; - } + @Override + public boolean canUse(final ItemStack is, final double amount) { + return this.getCharge(is) > amount; + } - @Override - public boolean use( final ItemStack is, final double amount, final EntityLivingBase entity ) - { - if( this.canUse( is, amount ) ) - { - // use the power.. - this.extractAEPower( is, PowerUnits.EU.convertTo( PowerUnits.AE, amount ) ); - return true; - } - return false; - } + @Override + public boolean + use(final ItemStack is, final double amount, final EntityLivingBase entity) { + if (this.canUse(is, amount)) { + // use the power.. + this.extractAEPower(is, PowerUnits.EU.convertTo(PowerUnits.AE, amount)); + return true; + } + return false; + } - @Override - public void chargeFromArmor( final ItemStack itemStack, final EntityLivingBase entity ) - { - // wtf? - } + @Override + public void + chargeFromArmor(final ItemStack itemStack, final EntityLivingBase entity) { + // wtf? + } - @Override - public String getToolTip( final ItemStack itemStack ) - { - return null; - } + @Override + public String getToolTip(final ItemStack itemStack) { + return null; + } - @Override - public boolean canProvideEnergy( final ItemStack itemStack ) - { - return false; - } + @Override + public boolean canProvideEnergy(final ItemStack itemStack) { + return false; + } - @Override - public Item getChargedItem( final ItemStack itemStack ) - { - return itemStack.getItem(); - } + @Override + public Item getChargedItem(final ItemStack itemStack) { + return itemStack.getItem(); + } - @Override - public Item getEmptyItem( final ItemStack itemStack ) - { - return itemStack.getItem(); - } + @Override + public Item getEmptyItem(final ItemStack itemStack) { + return itemStack.getItem(); + } - @Override - public double getMaxCharge( final ItemStack itemStack ) - { - return PowerUnits.AE.convertTo( PowerUnits.EU, this.getAEMaxPower( itemStack ) ); - } + @Override + public double getMaxCharge(final ItemStack itemStack) { + return PowerUnits.AE.convertTo(PowerUnits.EU, this.getAEMaxPower(itemStack)); + } - @Override - public int getTier( final ItemStack itemStack ) - { - return 1; - } + @Override + public int getTier(final ItemStack itemStack) { + return 1; + } - @Override - public double getTransferLimit( final ItemStack itemStack ) - { - return Math.max( 32, this.getMaxCharge( itemStack ) / 200 ); - } + @Override + public double getTransferLimit(final ItemStack itemStack) { + return Math.max(32, this.getMaxCharge(itemStack) / 200); + } - @Override - @Method( iname = IntegrationType.IC2 ) - public IElectricItemManager getManager( final ItemStack itemStack ) - { - return this; - } + @Override + @Method(iname = IntegrationType.IC2) + public IElectricItemManager getManager(final ItemStack itemStack) { + return this; + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java b/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java index 455e30f5..86126f14 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java +++ b/src/main/java/appeng/items/tools/powered/powersink/RedstoneFlux.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; @@ -26,36 +25,33 @@ import cofh.api.energy.IEnergyContainerItem; import com.google.common.base.Optional; import net.minecraft.item.ItemStack; +@Interface(iface = "cofh.api.energy.IEnergyContainerItem", iname = IntegrationType.RFItem) +public abstract class RedstoneFlux extends IC2 implements IEnergyContainerItem { + public RedstoneFlux(final double powerCapacity, final Optional subName) { + super(powerCapacity, subName); + } -@Interface( iface = "cofh.api.energy.IEnergyContainerItem", iname = IntegrationType.RFItem ) -public abstract class RedstoneFlux extends IC2 implements IEnergyContainerItem -{ - public RedstoneFlux( final double powerCapacity, final Optional subName ) - { - super( powerCapacity, subName ); - } + @Override + public int + receiveEnergy(final ItemStack is, final int maxReceive, final boolean simulate) { + return maxReceive + - (int) this.injectExternalPower(PowerUnits.RF, is, maxReceive, simulate); + } - @Override - public int receiveEnergy( final ItemStack is, final int maxReceive, final boolean simulate ) - { - return maxReceive - (int) this.injectExternalPower( PowerUnits.RF, is, maxReceive, simulate ); - } + @Override + public int extractEnergy( + final ItemStack container, final int maxExtract, final boolean simulate + ) { + return 0; + } - @Override - public int extractEnergy( final ItemStack container, final int maxExtract, final boolean simulate ) - { - return 0; - } + @Override + public int getEnergyStored(final ItemStack is) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.getAECurrentPower(is)); + } - @Override - public int getEnergyStored( final ItemStack is ) - { - return (int) PowerUnits.AE.convertTo( PowerUnits.RF, this.getAECurrentPower( is ) ); - } - - @Override - public int getMaxEnergyStored( final ItemStack is ) - { - return (int) PowerUnits.AE.convertTo( PowerUnits.RF, this.getAEMaxPower( is ) ); - } + @Override + public int getMaxEnergyStored(final ItemStack is) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, this.getAEMaxPower(is)); + } } diff --git a/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java b/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java index 53e4b337..3696a46b 100644 --- a/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java +++ b/src/main/java/appeng/items/tools/powered/powersink/UniversalElectricity.java @@ -18,7 +18,6 @@ package appeng.items.tools.powered.powersink; - /* @Interface(iface = "universalelectricity.core.item.IItemElectric", modid = "IC2") public class UniversalElectricity extends ThermalExpansion implements IItemElectric @@ -53,4 +52,3 @@ package appeng.items.tools.powered.powersink; } */ - diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java index 3016c0d0..ff74655c 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzAxe.java @@ -18,6 +18,7 @@ package appeng.items.tools.quartz; +import java.util.EnumSet; import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; @@ -28,35 +29,32 @@ import com.google.common.base.Optional; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; -import java.util.EnumSet; +public class ToolQuartzAxe extends ItemAxe implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler feature; + public ToolQuartzAxe(final AEFeature type) { + super(ToolMaterial.IRON); + this.feature = new ItemFeatureHandler( + EnumSet.of(this.type = type, AEFeature.QuartzAxe), + this, + this, + Optional.of(type.name()) + ); + } -public class ToolQuartzAxe extends ItemAxe implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler feature; + @Override + public IFeatureHandler handler() { + return this.feature; + } - public ToolQuartzAxe( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.feature = new ItemFeatureHandler( EnumSet.of( this.type = type, AEFeature.QuartzAxe ), this, this, Optional.of( type.name() ) ); - } + @Override + public void postInit() { + // override! + } - @Override - public IFeatureHandler handler() - { - return this.feature; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java index 2ee81bab..96bc8730 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzCuttingKnife.java @@ -18,6 +18,7 @@ package appeng.items.tools.quartz; +import java.util.EnumSet; import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.IGuiItemObject; @@ -32,78 +33,77 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem { + private final AEFeature type; + public ToolQuartzCuttingKnife(final AEFeature type) { + super(Optional.of(type.name())); -public class ToolQuartzCuttingKnife extends AEBaseItem implements IGuiItem -{ - private final AEFeature type; + this.type = type; + this.setFeature(EnumSet.of(type, AEFeature.QuartzKnife)); + this.setMaxDamage(50); + this.setMaxStackSize(1); + } - public ToolQuartzCuttingKnife( final AEFeature type ) - { - super( Optional.of( type.name() ) ); + @Override + public boolean onItemUse( + final ItemStack is, + final EntityPlayer p, + final World w, + final int x, + final int y, + final int z, + final int s, + final float hitX, + final float hitY, + final float hitZ + ) { + if (Platform.isServer()) { + Platform.openGUI(p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE); + } + return true; + } - this.type = type; - this.setFeature( EnumSet.of( type, AEFeature.QuartzKnife ) ); - this.setMaxDamage( 50 ); - this.setMaxStackSize( 1 ); - } + @Override + public ItemStack + onItemRightClick(final ItemStack it, final World w, final EntityPlayer p) { + if (Platform.isServer()) { + Platform.openGUI(p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE); + } + p.swingItem(); + return it; + } - @Override - public boolean onItemUse( final ItemStack is, final EntityPlayer p, final World w, final int x, final int y, final int z, final int s, final float hitX, final float hitY, final float hitZ ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE ); - } - return true; - } + @Override + public boolean doesContainerItemLeaveCraftingGrid(final ItemStack par1ItemStack) { + return false; + } - @Override - public ItemStack onItemRightClick( final ItemStack it, final World w, final EntityPlayer p ) - { - if( Platform.isServer() ) - { - Platform.openGUI( p, null, ForgeDirection.UNKNOWN, GuiBridge.GUI_QUARTZ_KNIFE ); - } - p.swingItem(); - return it; - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } - @Override - public boolean doesContainerItemLeaveCraftingGrid( final ItemStack par1ItemStack ) - { - return false; - } + @Override + public boolean isRepairable() { + return false; + } - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public ItemStack getContainerItem(final ItemStack itemStack) { + itemStack.setItemDamage(itemStack.getItemDamage() + 1); + return itemStack; + } - @Override - public boolean isRepairable() - { - return false; - } + @Override + public boolean hasContainerItem(final ItemStack stack) { + return true; + } - @Override - public ItemStack getContainerItem( final ItemStack itemStack ) - { - itemStack.setItemDamage( itemStack.getItemDamage() + 1 ); - return itemStack; - } - - @Override - public boolean hasContainerItem( final ItemStack stack ) - { - return true; - } - - @Override - public IGuiItemObject getGuiObject( final ItemStack is, final World world, final int x, final int y, final int z ) - { - return new QuartzKnifeObj( is ); - } + @Override + public IGuiItemObject getGuiObject( + final ItemStack is, final World world, final int x, final int y, final int z + ) { + 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 ea9b5a6b..6c83cd33 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzHoe.java @@ -18,6 +18,7 @@ package appeng.items.tools.quartz; +import java.util.EnumSet; import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; @@ -28,37 +29,34 @@ import com.google.common.base.Optional; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemStack; -import java.util.EnumSet; +public class ToolQuartzHoe extends ItemHoe implements IAEFeature { + private final AEFeature feature; + private final IFeatureHandler handler; + public ToolQuartzHoe(final AEFeature feature) { + super(ToolMaterial.IRON); -public class ToolQuartzHoe extends ItemHoe implements IAEFeature -{ - private final AEFeature feature; - private final IFeatureHandler handler; + this.feature = feature; + this.handler = new ItemFeatureHandler( + EnumSet.of(feature, AEFeature.QuartzHoe), + this, + this, + Optional.of(feature.name()) + ); + } - public ToolQuartzHoe( final AEFeature feature ) - { - super( ToolMaterial.IRON ); + @Override + public IFeatureHandler handler() { + return this.handler; + } - this.feature = feature; - this.handler = new ItemFeatureHandler( EnumSet.of( feature, AEFeature.QuartzHoe ), this, this, Optional.of( feature.name() ) ); - } + @Override + public void postInit() { + // override! + } - @Override - public IFeatureHandler handler() - { - return this.handler; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.feature, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.feature, a, b); + } } \ No newline at end of file diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java index 505ebc2b..f052482b 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzPickaxe.java @@ -18,6 +18,7 @@ package appeng.items.tools.quartz; +import java.util.EnumSet; import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; @@ -28,37 +29,34 @@ import com.google.common.base.Optional; import net.minecraft.item.ItemPickaxe; import net.minecraft.item.ItemStack; -import java.util.EnumSet; +public class ToolQuartzPickaxe extends ItemPickaxe implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler feature; + public ToolQuartzPickaxe(final AEFeature type) { + super(ToolMaterial.IRON); -public class ToolQuartzPickaxe extends ItemPickaxe implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler feature; + this.type = type; + this.feature = new ItemFeatureHandler( + EnumSet.of(type, AEFeature.QuartzPickaxe), + this, + this, + Optional.of(type.name()) + ); + } - public ToolQuartzPickaxe( final AEFeature type ) - { - super( ToolMaterial.IRON ); + @Override + public IFeatureHandler handler() { + return this.feature; + } - this.type = type; - this.feature = new ItemFeatureHandler( EnumSet.of( type, AEFeature.QuartzPickaxe ), this, this, Optional.of( type.name() ) ); - } + @Override + public void postInit() { + // override! + } - @Override - public IFeatureHandler handler() - { - return this.feature; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java index b5488012..f7f06c85 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSpade.java @@ -18,6 +18,7 @@ package appeng.items.tools.quartz; +import java.util.EnumSet; import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; @@ -28,36 +29,33 @@ import com.google.common.base.Optional; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; -import java.util.EnumSet; +public class ToolQuartzSpade extends ItemSpade implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler handler; + public ToolQuartzSpade(final AEFeature type) { + super(ToolMaterial.IRON); -public class ToolQuartzSpade extends ItemSpade implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler handler; + this.handler = new ItemFeatureHandler( + EnumSet.of(this.type = type, AEFeature.QuartzSpade), + this, + this, + Optional.of(type.name()) + ); + } - public ToolQuartzSpade( final AEFeature type ) - { - super( ToolMaterial.IRON ); + @Override + public IFeatureHandler handler() { + return this.handler; + } - this.handler = new ItemFeatureHandler( EnumSet.of( this.type = type, AEFeature.QuartzSpade ), this, this, Optional.of( type.name() ) ); - } + @Override + public void postInit() { + // override! + } - @Override - public IFeatureHandler handler() - { - return this.handler; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java index ccc3cbe2..c5e2ebca 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzSword.java @@ -18,6 +18,7 @@ package appeng.items.tools.quartz; +import java.util.EnumSet; import appeng.core.features.AEFeature; import appeng.core.features.IAEFeature; @@ -28,35 +29,32 @@ import com.google.common.base.Optional; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; -import java.util.EnumSet; +public class ToolQuartzSword extends ItemSword implements IAEFeature { + private final AEFeature type; + private final IFeatureHandler feature; + public ToolQuartzSword(final AEFeature type) { + super(ToolMaterial.IRON); + this.feature = new ItemFeatureHandler( + EnumSet.of(this.type = type, AEFeature.QuartzSword), + this, + this, + Optional.of(type.name()) + ); + } -public class ToolQuartzSword extends ItemSword implements IAEFeature -{ - private final AEFeature type; - private final IFeatureHandler feature; + @Override + public IFeatureHandler handler() { + return this.feature; + } - public ToolQuartzSword( final AEFeature type ) - { - super( ToolMaterial.IRON ); - this.feature = new ItemFeatureHandler( EnumSet.of( this.type = type, AEFeature.QuartzSword ), this, this, Optional.of( type.name() ) ); - } + @Override + public void postInit() { + // override! + } - @Override - public IFeatureHandler handler() - { - return this.feature; - } - - @Override - public void postInit() - { - // override! - } - - @Override - public boolean getIsRepairable( final ItemStack a, final ItemStack b ) - { - return Platform.canRepair( this.type, a, b ); - } + @Override + public boolean getIsRepairable(final ItemStack a, final ItemStack b) { + return Platform.canRepair(this.type, a, b); + } } diff --git a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java index 50db358f..8a515454 100644 --- a/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java +++ b/src/main/java/appeng/items/tools/quartz/ToolQuartzWrench.java @@ -18,6 +18,7 @@ package appeng.items.tools.quartz; +import java.util.EnumSet; import appeng.api.implementations.items.IAEWrench; import appeng.api.util.DimensionalCoord; @@ -36,75 +37,100 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.util.EnumSet; +@Interface( + iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore +) +public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolWrench { + public ToolQuartzWrench(final AEFeature type) { + super(Optional.of(type.name())); + this.setFeature(EnumSet.of(type, AEFeature.QuartzWrench)); + this.setMaxStackSize(1); + this.setHarvestLevel("wrench", 0); + } -@Interface( iface = "buildcraft.api.tools.IToolWrench", iname = IntegrationType.BuildCraftCore ) -public class ToolQuartzWrench extends AEBaseItem implements IAEWrench, IToolWrench -{ + @Override + public boolean onItemUseFirst( + final ItemStack is, + final EntityPlayer player, + final World world, + final int x, + final int y, + final int z, + final int side, + final float hitX, + final float hitY, + final float hitZ + ) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) + return true; - public ToolQuartzWrench( final AEFeature type ) - { - super( Optional.of( type.name() ) ); + final Block b = world.getBlock(x, y, z); - this.setFeature( EnumSet.of( type, AEFeature.QuartzWrench ) ); - this.setMaxStackSize( 1 ); - this.setHarvestLevel( "wrench", 0 ); - } + if (b != null + && ForgeEventFactory + .onPlayerInteract( + player, + b.isAir(world, x, y, z) + ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR + : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + side, + world + ) + .isCanceled()) + return true; - @Override - public boolean onItemUseFirst( final ItemStack is, final EntityPlayer player, final World world, final int x, final int y, final int z, final int side, final float hitX, final float hitY, final float hitZ ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return true; + if (b != null && !player.isSneaking() + && Platform.hasPermissions(new DimensionalCoord(world, x, y, z), player)) { + if (Platform.isClient()) { + return !world.isRemote; + } - final Block b = world.getBlock( x, y, z ); + final ForgeDirection mySide = ForgeDirection.getOrientation(side); + if (b.rotateBlock(world, x, y, z, mySide)) { + b.onNeighborBlockChange(world, x, y, z, Platform.AIR_BLOCK); + player.swingItem(); + return !world.isRemote; + } + } + return false; + } - if( b != null && ForgeEventFactory.onPlayerInteract( player, - b.isAir( world, x, y, z ) ? PlayerInteractEvent.Action.RIGHT_CLICK_AIR : PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, - x, y, z, side, world ).isCanceled() ) - return true; + @Override + // public boolean shouldPassSneakingClickToBlock(World w, int x, int y, int z) + public boolean doesSneakBypassUse( + final World world, + final int x, + final int y, + final int z, + final EntityPlayer player + ) { + return true; + } - if( b != null && !player.isSneaking() && Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) - { - if( Platform.isClient() ) - { - return !world.isRemote; - } + @Override + public boolean canWrench( + final ItemStack is, + final EntityPlayer player, + final int x, + final int y, + final int z + ) { + return true; + } - final ForgeDirection mySide = ForgeDirection.getOrientation( side ); - if( b.rotateBlock( world, x, y, z, mySide ) ) - { - b.onNeighborBlockChange( world, x, y, z, Platform.AIR_BLOCK ); - player.swingItem(); - return !world.isRemote; - } - } - return false; - } + @Override + public boolean + canWrench(final EntityPlayer player, final int x, final int y, final int z) { + return true; + } - @Override - // public boolean shouldPassSneakingClickToBlock(World w, int x, int y, int z) - public boolean doesSneakBypassUse( final World world, final int x, final int y, final int z, final EntityPlayer player ) - { - return true; - } - - @Override - public boolean canWrench( final ItemStack is, final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public boolean canWrench( final EntityPlayer player, final int x, final int y, final int z ) - { - return true; - } - - @Override - public void wrenchUsed( final EntityPlayer player, final int x, final int y, final int z ) - { - player.swingItem(); - } + @Override + public void + wrenchUsed(final EntityPlayer player, final int x, final int y, final int z) { + player.swingItem(); + } } diff --git a/src/main/java/appeng/me/Grid.java b/src/main/java/appeng/me/Grid.java index e937acc8..12ef583c 100644 --- a/src/main/java/appeng/me/Grid.java +++ b/src/main/java/appeng/me/Grid.java @@ -18,6 +18,8 @@ package appeng.me; +import java.util.*; +import java.util.Map.Entry; import appeng.api.AEApi; import appeng.api.networking.*; @@ -28,262 +30,217 @@ import appeng.core.worlddata.WorldData; import appeng.hooks.TickHandler; import appeng.util.ReadOnlyCollection; -import java.util.*; -import java.util.Map.Entry; +public class Grid implements IGrid { + private final NetworkEventBus eventBus = new NetworkEventBus(); + private final Map, MachineSet> machines + = new HashMap, MachineSet>(); + private final Map, GridCacheWrapper> caches + = new HashMap, GridCacheWrapper>(); + private GridNode pivot; + private int priority; // how import is this network? + private GridStorage myStorage; + public Grid(final GridNode center) { + this.pivot = center; -public class Grid implements IGrid -{ - private final NetworkEventBus eventBus = new NetworkEventBus(); - private final Map, MachineSet> machines = new HashMap, MachineSet>(); - private final Map, GridCacheWrapper> caches = new HashMap, GridCacheWrapper>(); - private GridNode pivot; - private int priority; // how import is this network? - private GridStorage myStorage; + final Map, IGridCache> myCaches + = AEApi.instance().registries().gridCache().createCacheInstance(this); + for (final Entry, IGridCache> c : + myCaches.entrySet()) { + final Class key = c.getKey(); + final IGridCache value = c.getValue(); + final Class valueClass = value.getClass(); - public Grid( final GridNode center ) - { - this.pivot = center; + this.eventBus.readClass(key, valueClass); + this.caches.put(key, new GridCacheWrapper(value)); + } - final Map, IGridCache> myCaches = AEApi.instance().registries().gridCache().createCacheInstance( this ); - for( final Entry, IGridCache> c : myCaches.entrySet() ) - { - final Class key = c.getKey(); - final IGridCache value = c.getValue(); - final Class valueClass = value.getClass(); + this.postEvent(new MENetworkPostCacheConstruction()); - this.eventBus.readClass( key, valueClass ); - this.caches.put( key, new GridCacheWrapper( value ) ); - } + TickHandler.INSTANCE.addNetwork(this); + center.setGrid(this); + } - this.postEvent( new MENetworkPostCacheConstruction() ); + int getPriority() { + return this.priority; + } - TickHandler.INSTANCE.addNetwork( this ); - center.setGrid( this ); - } + IGridStorage getMyStorage() { + return this.myStorage; + } - int getPriority() - { - return this.priority; - } + Map, GridCacheWrapper> getCaches() { + return this.caches; + } - IGridStorage getMyStorage() - { - return this.myStorage; - } + public Iterable> getMachineClasses() { + return this.machines.keySet(); + } - Map, GridCacheWrapper> getCaches() - { - return this.caches; - } + int size() { + int out = 0; + for (final Collection x : this.machines.values()) { + out += x.size(); + } + return out; + } - public Iterable> getMachineClasses() - { - return this.machines.keySet(); - } + void remove(final GridNode gridNode) { + for (final IGridCache c : this.caches.values()) { + final IGridHost machine = gridNode.getMachine(); + c.removeNode(gridNode, machine); + } - int size() - { - int out = 0; - for( final Collection x : this.machines.values() ) - { - out += x.size(); - } - return out; - } + final Class machineClass = gridNode.getMachineClass(); + final Set nodes = this.machines.get(machineClass); + if (nodes != null) { + nodes.remove(gridNode); + } - void remove( final GridNode gridNode ) - { - for( final IGridCache c : this.caches.values() ) - { - final IGridHost machine = gridNode.getMachine(); - c.removeNode( gridNode, machine ); - } + gridNode.setGridStorage(null); - final Class machineClass = gridNode.getMachineClass(); - final Set nodes = this.machines.get( machineClass ); - if( nodes != null ) - { - nodes.remove( gridNode ); - } + if (this.pivot == gridNode) { + final Iterator n = this.getNodes().iterator(); + if (n.hasNext()) { + this.pivot = (GridNode) n.next(); + } else { + this.pivot = null; + TickHandler.INSTANCE.removeNetwork(this); + this.myStorage.remove(); + } + } + } - gridNode.setGridStorage( null ); + void add(final GridNode gridNode) { + final Class mClass = gridNode.getMachineClass(); - if( this.pivot == gridNode ) - { - final Iterator n = this.getNodes().iterator(); - if( n.hasNext() ) - { - this.pivot = (GridNode) n.next(); - } - else - { - this.pivot = null; - TickHandler.INSTANCE.removeNetwork( this ); - this.myStorage.remove(); - } - } - } + MachineSet nodes = this.machines.get(mClass); + if (nodes == null) { + nodes = new MachineSet(mClass); + this.machines.put(mClass, nodes); + this.eventBus.readClass(mClass, mClass); + } - void add( final GridNode gridNode ) - { - final Class mClass = gridNode.getMachineClass(); + // handle loading grid storages. + if (gridNode.getGridStorage() != null) { + final GridStorage gs = gridNode.getGridStorage(); + final IGrid grid = gs.getGrid(); - MachineSet nodes = this.machines.get( mClass ); - if( nodes == null ) - { - nodes = new MachineSet( mClass ); - this.machines.put( mClass, nodes ); - this.eventBus.readClass( mClass, mClass ); - } + if (grid == null) { + this.myStorage = gs; + this.myStorage.setGrid(this); - // handle loading grid storages. - if( gridNode.getGridStorage() != null ) - { - final GridStorage gs = gridNode.getGridStorage(); - final IGrid grid = gs.getGrid(); + for (final IGridCache gc : this.caches.values()) { + gc.onJoin(this.myStorage); + } + } else if (grid != this) { + if (this.myStorage == null) { + this.myStorage + = WorldData.instance().storageData().getNewGridStorage(); + this.myStorage.setGrid(this); + } - if( grid == null ) - { - this.myStorage = gs; - this.myStorage.setGrid( this ); + final IGridStorage tmp = new GridStorage(); + if (!gs.hasDivided(this.myStorage)) { + gs.addDivided(this.myStorage); - for( final IGridCache gc : this.caches.values() ) - { - gc.onJoin( this.myStorage ); - } - } - else if( grid != this ) - { - if( this.myStorage == null ) - { - this.myStorage = WorldData.instance().storageData().getNewGridStorage(); - this.myStorage.setGrid( this ); - } + for (final IGridCache gc : ((Grid) grid).caches.values()) { + gc.onSplit(tmp); + } - final IGridStorage tmp = new GridStorage(); - if( !gs.hasDivided( this.myStorage ) ) - { - gs.addDivided( this.myStorage ); + for (final IGridCache gc : this.caches.values()) { + gc.onJoin(tmp); + } + } + } + } else if (this.myStorage == null) { + this.myStorage = WorldData.instance().storageData().getNewGridStorage(); + this.myStorage.setGrid(this); + } - for( final IGridCache gc : ( (Grid) grid ).caches.values() ) - { - gc.onSplit( tmp ); - } + // update grid node... + gridNode.setGridStorage(this.myStorage); - for( final IGridCache gc : this.caches.values() ) - { - gc.onJoin( tmp ); - } - } - } - } - else if( this.myStorage == null ) - { - this.myStorage = WorldData.instance().storageData().getNewGridStorage(); - this.myStorage.setGrid( this ); - } + // track node. + nodes.add(gridNode); - // update grid node... - gridNode.setGridStorage( this.myStorage ); + for (final IGridCache cache : this.caches.values()) { + final IGridHost machine = gridNode.getMachine(); + cache.addNode(gridNode, machine); + } - // track node. - nodes.add( gridNode ); + gridNode.getGridProxy().gridChanged(); + // postEventTo( gridNode, networkChanged ); + } - for( final IGridCache cache : this.caches.values() ) - { - final IGridHost machine = gridNode.getMachine(); - cache.addNode( gridNode, machine ); - } + @Override + @SuppressWarnings("unchecked") + public C getCache(final Class iface) { + return (C) this.caches.get(iface).getCache(); + } - gridNode.getGridProxy().gridChanged(); - // postEventTo( gridNode, networkChanged ); - } + @Override + public MENetworkEvent postEvent(final MENetworkEvent ev) { + return this.eventBus.postEvent(this, ev); + } - @Override - @SuppressWarnings( "unchecked" ) - public C getCache( final Class iface ) - { - return (C) this.caches.get( iface ).getCache(); - } + @Override + public MENetworkEvent postEventTo(final IGridNode node, final MENetworkEvent ev) { + return this.eventBus.postEventTo(this, (GridNode) node, ev); + } - @Override - public MENetworkEvent postEvent( final MENetworkEvent ev ) - { - return this.eventBus.postEvent( this, ev ); - } + @Override + public IReadOnlyCollection> getMachinesClasses() { + final Set> machineKeys = this.machines.keySet(); - @Override - public MENetworkEvent postEventTo( final IGridNode node, final MENetworkEvent ev ) - { - return this.eventBus.postEventTo( this, (GridNode) node, ev ); - } + return new ReadOnlyCollection>(machineKeys); + } - @Override - public IReadOnlyCollection> getMachinesClasses() - { - final Set> machineKeys = this.machines.keySet(); + @Override + public IMachineSet getMachines(final Class c) { + final MachineSet s = this.machines.get(c); + if (s == null) { + return new MachineSet(c); + } + return s; + } - return new ReadOnlyCollection>( machineKeys ); - } + @Override + public IReadOnlyCollection getNodes() { + return new GridNodeCollection(this.machines); + } - @Override - public IMachineSet getMachines( final Class c ) - { - final MachineSet s = this.machines.get( c ); - if( s == null ) - { - return new MachineSet( c ); - } - return s; - } + @Override + public boolean isEmpty() { + return this.pivot == null; + } - @Override - public IReadOnlyCollection getNodes() - { - return new GridNodeCollection( this.machines ); - } + @Override + public IGridNode getPivot() { + return this.pivot; + } - @Override - public boolean isEmpty() - { - return this.pivot == null; - } + void setPivot(final GridNode pivot) { + this.pivot = pivot; + } - @Override - public IGridNode getPivot() - { - return this.pivot; - } + public void update() { + for (final IGridCache gc : this.caches.values()) { + // are there any nodes left? + if (this.pivot != null) { + gc.onUpdateTick(); + } + } + } - void setPivot( final GridNode pivot ) - { - this.pivot = pivot; - } + void saveState() { + for (final IGridCache c : this.caches.values()) { + c.populateGridStorage(this.myStorage); + } + } - public void update() - { - for( final IGridCache gc : this.caches.values() ) - { - // are there any nodes left? - if( this.pivot != null ) - { - gc.onUpdateTick(); - } - } - } - - void saveState() - { - for( final IGridCache c : this.caches.values() ) - { - c.populateGridStorage( this.myStorage ); - } - } - - public void setImportantFlag( final int i, final boolean publicHasPower ) - { - final int flag = 1 << i; - this.priority = ( this.priority & ~flag ) | ( publicHasPower ? flag : 0 ); - } + public void setImportantFlag(final int i, final boolean publicHasPower) { + final int flag = 1 << i; + this.priority = (this.priority & ~flag) | (publicHasPower ? flag : 0); + } } diff --git a/src/main/java/appeng/me/GridAccessException.java b/src/main/java/appeng/me/GridAccessException.java index 6877e217..097214ad 100644 --- a/src/main/java/appeng/me/GridAccessException.java +++ b/src/main/java/appeng/me/GridAccessException.java @@ -18,9 +18,6 @@ package appeng.me; - -public class GridAccessException extends Exception -{ - - private static final long serialVersionUID = 3914554394866375300L; +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 2825faa4..607e3ffa 100644 --- a/src/main/java/appeng/me/GridCacheWrapper.java +++ b/src/main/java/appeng/me/GridCacheWrapper.java @@ -18,68 +18,55 @@ 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 { + private final IGridCache myCache; + private final String name; -public class GridCacheWrapper implements IGridCache -{ + public GridCacheWrapper(final IGridCache gc) { + this.myCache = gc; + this.name = this.getCache().getClass().getName(); + } - private final IGridCache myCache; - private final String name; + @Override + public void onUpdateTick() { + this.getCache().onUpdateTick(); + } - public GridCacheWrapper( final IGridCache gc ) - { - this.myCache = gc; - this.name = this.getCache().getClass().getName(); - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + this.getCache().removeNode(gridNode, machine); + } - @Override - public void onUpdateTick() - { - this.getCache().onUpdateTick(); - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + this.getCache().addNode(gridNode, machine); + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - this.getCache().removeNode( gridNode, machine ); - } + @Override + public void onSplit(final IGridStorage storageB) { + this.getCache().onSplit(storageB); + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - this.getCache().addNode( gridNode, machine ); - } + @Override + public void onJoin(final IGridStorage storageB) { + this.getCache().onJoin(storageB); + } - @Override - public void onSplit( final IGridStorage storageB ) - { - this.getCache().onSplit( storageB ); - } + @Override + public void populateGridStorage(final IGridStorage storage) { + this.getCache().populateGridStorage(storage); + } - @Override - public void onJoin( final IGridStorage storageB ) - { - this.getCache().onJoin( storageB ); - } + public String getName() { + return this.name; + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { - this.getCache().populateGridStorage( storage ); - } - - public String getName() - { - return this.name; - } - - IGridCache getCache() - { - return this.myCache; - } + IGridCache getCache() { + return this.myCache; + } } diff --git a/src/main/java/appeng/me/GridConnection.java b/src/main/java/appeng/me/GridConnection.java index 1b0fd40a..2cb005e7 100644 --- a/src/main/java/appeng/me/GridConnection.java +++ b/src/main/java/appeng/me/GridConnection.java @@ -18,6 +18,8 @@ package appeng.me; +import java.util.Arrays; +import java.util.EnumSet; import appeng.api.exceptions.ExistingConnectionException; import appeng.api.exceptions.FailedConnection; @@ -38,256 +40,227 @@ import appeng.util.Platform; import appeng.util.ReadOnlyCollection; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Arrays; -import java.util.EnumSet; +public class GridConnection implements IGridConnection, IPathItem { + private static final String EXISTING_CONNECTION_MESSAGE + = "Connection between node [machine=%s, %s] and [machine=%s, %s] on [%s] already exists."; + private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); + private int channelData = 0; + private Object visitorIterationNumber = null; + private GridNode sideA; + private ForgeDirection fromAtoB; + private GridNode sideB; -public class GridConnection implements IGridConnection, IPathItem -{ + public GridConnection( + final IGridNode aNode, final IGridNode bNode, final ForgeDirection fromAtoB + ) throws FailedConnection { + final GridNode a = (GridNode) aNode; + final GridNode b = (GridNode) bNode; - private static final String EXISTING_CONNECTION_MESSAGE = "Connection between node [machine=%s, %s] and [machine=%s, %s] on [%s] already exists."; + if (Platform.securityCheck(a, b)) { + if (AEConfig.instance.isFeatureEnabled(AEFeature.LogSecurityAudits)) { + final DimensionalCoord aCoordinates = a.getGridBlock().getLocation(); + final DimensionalCoord bCoordinates = b.getGridBlock().getLocation(); - private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); - private int channelData = 0; - private Object visitorIterationNumber = null; - private GridNode sideA; - private ForgeDirection fromAtoB; - private GridNode sideB; + AELog.info( + "Security audit 1 failed at [%s] belonging to player [id=%d]", + aCoordinates.toString(), + a.getPlayerID() + ); + AELog.info( + "Security audit 2 failed at [%s] belonging to player [id=%d]", + bCoordinates.toString(), + b.getPlayerID() + ); + } - public GridConnection( final IGridNode aNode, final IGridNode bNode, final ForgeDirection fromAtoB ) throws FailedConnection - { + throw new SecurityConnectionException(); + } - final GridNode a = (GridNode) aNode; - final GridNode b = (GridNode) bNode; + if (a == null || b == null) { + throw new NullNodeConnectionException(); + } - if( Platform.securityCheck( a, b ) ) - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) - { - final DimensionalCoord aCoordinates = a.getGridBlock().getLocation(); - final DimensionalCoord bCoordinates = b.getGridBlock().getLocation(); + if (a.hasConnection(b) || b.hasConnection(a)) { + final String aMachineClass + = a.getGridBlock().getMachine().getClass().getSimpleName(); + final String bMachineClass + = b.getGridBlock().getMachine().getClass().getSimpleName(); + final String aCoordinates = a.getGridBlock().getLocation().toString(); + final String bCoordinates = b.getGridBlock().getLocation().toString(); - AELog.info( "Security audit 1 failed at [%s] belonging to player [id=%d]", aCoordinates.toString(), a.getPlayerID() ); - AELog.info( "Security audit 2 failed at [%s] belonging to player [id=%d]", bCoordinates.toString(), b.getPlayerID() ); - } + throw new ExistingConnectionException(String.format( + EXISTING_CONNECTION_MESSAGE, + aMachineClass, + aCoordinates, + bMachineClass, + bCoordinates, + fromAtoB + )); + } - throw new SecurityConnectionException(); - } + this.sideA = a; + this.fromAtoB = fromAtoB; + this.sideB = b; - if( a == null || b == null ) - { - throw new NullNodeConnectionException(); - } + if (b.getMyGrid() == null) { + b.setGrid(a.getInternalGrid()); + } else { + if (a.getMyGrid() == null) { + final GridPropagator gp = new GridPropagator(b.getInternalGrid()); + a.beginVisit(gp); + } else if (b.getMyGrid() == null) { + final GridPropagator gp = new GridPropagator(a.getInternalGrid()); + b.beginVisit(gp); + } else if (this.isNetworkABetter(a, b)) { + final GridPropagator gp = new GridPropagator(a.getInternalGrid()); + b.beginVisit(gp); + } else { + final GridPropagator gp = new GridPropagator(b.getInternalGrid()); + a.beginVisit(gp); + } + } - if( a.hasConnection( b ) || b.hasConnection( a ) ) - { - final String aMachineClass = a.getGridBlock().getMachine().getClass().getSimpleName(); - final String bMachineClass = b.getGridBlock().getMachine().getClass().getSimpleName(); - final String aCoordinates = a.getGridBlock().getLocation().toString(); - final String bCoordinates = b.getGridBlock().getLocation().toString(); + // a connection was destroyed RE-PATH!! + final IPathingGrid p = this.sideA.getInternalGrid().getCache(IPathingGrid.class); + p.repath(); - throw new ExistingConnectionException( String.format( EXISTING_CONNECTION_MESSAGE, aMachineClass, aCoordinates, bMachineClass, bCoordinates, fromAtoB ) ); - } + this.sideA.addConnection(this); + this.sideB.addConnection(this); + } - this.sideA = a; - this.fromAtoB = fromAtoB; - this.sideB = b; + private boolean isNetworkABetter(final GridNode a, final GridNode b) { + return a.getMyGrid().getPriority() > b.getMyGrid().getPriority() + || a.getMyGrid().size() > b.getMyGrid().size(); + } - if( b.getMyGrid() == null ) - { - b.setGrid( a.getInternalGrid() ); - } - else - { - if( a.getMyGrid() == null ) - { - final GridPropagator gp = new GridPropagator( b.getInternalGrid() ); - a.beginVisit( gp ); - } - else if( b.getMyGrid() == null ) - { - final GridPropagator gp = new GridPropagator( a.getInternalGrid() ); - b.beginVisit( gp ); - } - else if( this.isNetworkABetter( a, b ) ) - { - final GridPropagator gp = new GridPropagator( a.getInternalGrid() ); - b.beginVisit( gp ); - } - else - { - final GridPropagator gp = new GridPropagator( b.getInternalGrid() ); - a.beginVisit( gp ); - } - } + @Override + public IGridNode getOtherSide(final IGridNode gridNode) { + if (gridNode == this.sideA) { + return this.sideB; + } + if (gridNode == this.sideB) { + return this.sideA; + } - // a connection was destroyed RE-PATH!! - final IPathingGrid p = this.sideA.getInternalGrid().getCache( IPathingGrid.class ); - p.repath(); + throw new GridException("Invalid Side of Connection"); + } - this.sideA.addConnection( this ); - this.sideB.addConnection( this ); - } + @Override + public ForgeDirection getDirection(final IGridNode side) { + if (this.fromAtoB == ForgeDirection.UNKNOWN) { + return this.fromAtoB; + } - private boolean isNetworkABetter( final GridNode a, final GridNode b ) - { - return a.getMyGrid().getPriority() > b.getMyGrid().getPriority() || a.getMyGrid().size() > b.getMyGrid().size(); - } + if (this.sideA == side) { + return this.fromAtoB; + } else { + return this.fromAtoB.getOpposite(); + } + } - @Override - public IGridNode getOtherSide( final IGridNode gridNode ) - { - if( gridNode == this.sideA ) - { - return this.sideB; - } - if( gridNode == this.sideB ) - { - return this.sideA; - } + @Override + public void destroy() { + // a connection was destroyed RE-PATH!! + final IPathingGrid p = this.sideA.getInternalGrid().getCache(IPathingGrid.class); + p.repath(); - throw new GridException( "Invalid Side of Connection" ); - } + this.sideA.removeConnection(this); + this.sideB.removeConnection(this); - @Override - public ForgeDirection getDirection( final IGridNode side ) - { - if( this.fromAtoB == ForgeDirection.UNKNOWN ) - { - return this.fromAtoB; - } + this.sideA.validateGrid(); + this.sideB.validateGrid(); + } - if( this.sideA == side ) - { - return this.fromAtoB; - } - else - { - return this.fromAtoB.getOpposite(); - } - } + @Override + public IGridNode a() { + return this.sideA; + } - @Override - public void destroy() - { - // a connection was destroyed RE-PATH!! - final IPathingGrid p = this.sideA.getInternalGrid().getCache( IPathingGrid.class ); - p.repath(); + @Override + public IGridNode b() { + return this.sideB; + } - this.sideA.removeConnection( this ); - this.sideB.removeConnection( this ); + @Override + public boolean hasDirection() { + return this.fromAtoB != ForgeDirection.UNKNOWN; + } - this.sideA.validateGrid(); - this.sideB.validateGrid(); - } + @Override + public int getUsedChannels() { + return (this.channelData >> 8) & 0xff; + } - @Override - public IGridNode a() - { - return this.sideA; - } + @Override + public IPathItem getControllerRoute() { + if (this.sideA.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return null; + } + return this.sideA; + } - @Override - public IGridNode b() - { - return this.sideB; - } + @Override + public void setControllerRoute(final IPathItem fast, final boolean zeroOut) { + if (zeroOut) { + this.channelData &= ~0xff; + } - @Override - public boolean hasDirection() - { - return this.fromAtoB != ForgeDirection.UNKNOWN; - } + if (this.sideB == fast) { + final GridNode tmp = this.sideA; + this.sideA = this.sideB; + this.sideB = tmp; + this.fromAtoB = this.fromAtoB.getOpposite(); + } + } - @Override - public int getUsedChannels() - { - return ( this.channelData >> 8 ) & 0xff; - } + @Override + public boolean canSupportMoreChannels() { + return this.getLastUsedChannels() < 32; // max, PERIOD. + } - @Override - public IPathItem getControllerRoute() - { - if( this.sideA.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return null; - } - return this.sideA; - } + @Override + public IReadOnlyCollection getPossibleOptions() { + return new ReadOnlyCollection( + Arrays.asList((IPathItem) this.a(), (IPathItem) this.b()) + ); + } - @Override - public void setControllerRoute( final IPathItem fast, final boolean zeroOut ) - { - if( zeroOut ) - { - this.channelData &= ~0xff; - } + @Override + public void incrementChannelCount(final int usedChannels) { + this.channelData += usedChannels; + } - if( this.sideB == fast ) - { - final GridNode tmp = this.sideA; - this.sideA = this.sideB; - this.sideB = tmp; - this.fromAtoB = this.fromAtoB.getOpposite(); - } - } + @Override + public EnumSet getFlags() { + return EnumSet.noneOf(GridFlags.class); + } - @Override - public boolean canSupportMoreChannels() - { - return this.getLastUsedChannels() < 32; // max, PERIOD. - } + @Override + public void finalizeChannels() { + if (this.getUsedChannels() != this.getLastUsedChannels()) { + this.channelData &= 0xff; + this.channelData |= this.channelData << 8; - @Override - public IReadOnlyCollection getPossibleOptions() - { - return new ReadOnlyCollection( Arrays.asList( (IPathItem) this.a(), (IPathItem) this.b() ) ); - } + if (this.sideA.getInternalGrid() != null) { + this.sideA.getInternalGrid().postEventTo(this.sideA, EVENT); + } - @Override - public void incrementChannelCount( final int usedChannels ) - { - this.channelData += usedChannels; - } + if (this.sideB.getInternalGrid() != null) { + this.sideB.getInternalGrid().postEventTo(this.sideB, EVENT); + } + } + } - @Override - public EnumSet getFlags() - { - return EnumSet.noneOf( GridFlags.class ); - } + private int getLastUsedChannels() { + return this.channelData & 0xff; + } - @Override - public void finalizeChannels() - { - if( this.getUsedChannels() != this.getLastUsedChannels() ) - { - this.channelData &= 0xff; - this.channelData |= this.channelData << 8; + Object getVisitorIterationNumber() { + return this.visitorIterationNumber; + } - if( this.sideA.getInternalGrid() != null ) - { - this.sideA.getInternalGrid().postEventTo( this.sideA, EVENT ); - } - - if( this.sideB.getInternalGrid() != null ) - { - this.sideB.getInternalGrid().postEventTo( this.sideB, EVENT ); - } - } - } - - private int getLastUsedChannels() - { - return this.channelData & 0xff; - } - - Object getVisitorIterationNumber() - { - return this.visitorIterationNumber; - } - - void setVisitorIterationNumber( final Object visitorIterationNumber ) - { - this.visitorIterationNumber = visitorIterationNumber; - } + void setVisitorIterationNumber(final Object visitorIterationNumber) { + this.visitorIterationNumber = visitorIterationNumber; + } } diff --git a/src/main/java/appeng/me/GridException.java b/src/main/java/appeng/me/GridException.java index 5a3f418b..0e9bbb5f 100644 --- a/src/main/java/appeng/me/GridException.java +++ b/src/main/java/appeng/me/GridException.java @@ -18,15 +18,10 @@ package appeng.me; +public class GridException extends RuntimeException { + private static final long serialVersionUID = -8110077032108243076L; -public class GridException extends RuntimeException -{ - - private static final long serialVersionUID = -8110077032108243076L; - - public GridException( final String s ) - { - - super( s ); - } + public GridException(final String s) { + super(s); + } } diff --git a/src/main/java/appeng/me/GridNode.java b/src/main/java/appeng/me/GridNode.java index ed668474..d378c729 100644 --- a/src/main/java/appeng/me/GridNode.java +++ b/src/main/java/appeng/me/GridNode.java @@ -18,6 +18,7 @@ package appeng.me; +import java.util.*; import appeng.api.exceptions.FailedConnection; import appeng.api.networking.*; @@ -37,673 +38,573 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.*; - - -public class GridNode implements IGridNode, IPathItem -{ - private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); - private static final int[] CHANNEL_COUNT = { 0, 8, 32 }; - - private final List connections = new LinkedList(); - private final IGridBlock gridProxy; - // old power draw, used to diff - private double previousDraw = 0.0; - private long lastSecurityKey = -1; - private int playerID = -1; - private GridStorage myStorage = null; - private Grid myGrid; - private Object visitorIterationNumber = null; - // connection criteria - private int compressedData = 0; - private int usedChannels = 0; - private int lastUsedChannels = 0; - - public GridNode( final IGridBlock what ) - { - this.gridProxy = what; - } - - IGridBlock getGridProxy() - { - return this.gridProxy; - } - - Grid getMyGrid() - { - return this.myGrid; - } - - public int usedChannels() - { - return this.lastUsedChannels; - } - - Class getMachineClass() - { - return this.getMachine().getClass(); - } - - void addConnection( final IGridConnection gridConnection ) - { - this.connections.add( gridConnection ); - if( gridConnection.hasDirection() ) - { - this.gridProxy.onGridNotification( GridNotification.ConnectionsChanged ); - } - - final IGridNode gn = this; - - Collections.sort( this.connections, new ConnectionComparator( gn ) ); - } - - void removeConnection( final IGridConnection gridConnection ) - { - this.connections.remove( gridConnection ); - if( gridConnection.hasDirection() ) - { - this.gridProxy.onGridNotification( GridNotification.ConnectionsChanged ); - } - } - - boolean hasConnection( final IGridNode otherSide ) - { - for( final IGridConnection gc : this.connections ) - { - if( gc.a() == otherSide || gc.b() == otherSide ) - { - return true; - } - } - return false; - } - - void validateGrid() - { - final GridSplitDetector gsd = new GridSplitDetector( this.getInternalGrid().getPivot() ); - this.beginVisit( gsd ); - if( !gsd.isPivotFound() ) - { - final IGridVisitor gp = new GridPropagator( new Grid( this ) ); - this.beginVisit( gp ); - } - } - - public Grid getInternalGrid() - { - if( this.myGrid == null ) - { - this.myGrid = new Grid( this ); - } - - return this.myGrid; - } - - @Override - public void beginVisit( final IGridVisitor g ) - { - final Object tracker = new Object(); - - LinkedList nextRun = new LinkedList(); - nextRun.add( this ); - - this.visitorIterationNumber = tracker; - - if( g instanceof IGridConnectionVisitor ) - { - final LinkedList nextConn = new LinkedList(); - final IGridConnectionVisitor gcv = (IGridConnectionVisitor) g; - - while( !nextRun.isEmpty() ) - { - while( !nextConn.isEmpty() ) - { - gcv.visitConnection( nextConn.poll() ); - } - - final Iterable thisRun = nextRun; - nextRun = new LinkedList(); - - for( final GridNode n : thisRun ) - { - n.visitorConnection( tracker, g, nextRun, nextConn ); - } - } - } - else - { - while( !nextRun.isEmpty() ) - { - final Iterable thisRun = nextRun; - nextRun = new LinkedList(); - - for( final GridNode n : thisRun ) - { - n.visitorNode( tracker, g, nextRun ); - } - } - } - } - - @Override - public void updateState() - { - final EnumSet set = this.gridProxy.getFlags(); - - this.compressedData = set.contains( GridFlags.CANNOT_CARRY ) ? 0 : ( set.contains( GridFlags.DENSE_CAPACITY ) ? 2 : 1 ); - - this.compressedData |= ( this.gridProxy.getGridColor().ordinal() << 3 ); - - for( final ForgeDirection dir : this.gridProxy.getConnectableSides() ) - { - this.compressedData |= ( 1 << ( dir.ordinal() + 8 ) ); - } - - this.FindConnections(); - this.getInternalGrid(); - } - - @Override - public IGridHost getMachine() - { - return this.gridProxy.getMachine(); - } - - @Override - public IGrid getGrid() - { - return this.myGrid; - } - - void setGrid( final Grid grid ) - { - if( this.myGrid == grid ) - { - return; - } - - if( this.myGrid != null ) - { - this.myGrid.remove( this ); - - if( this.myGrid.isEmpty() ) - { - this.myGrid.saveState(); - - for( final IGridCache c : grid.getCaches().values() ) - { - c.onJoin( this.myGrid.getMyStorage() ); - } - } - } - - this.myGrid = grid; - this.myGrid.add( this ); - } - - @Override - public void destroy() - { - while( !this.connections.isEmpty() ) - { - // not part of this network for real anymore. - if( this.connections.size() == 1 ) - { - this.setGridStorage( null ); - } - - final IGridConnection c = this.connections.listIterator().next(); - final GridNode otherSide = (GridNode) c.getOtherSide( this ); - otherSide.getInternalGrid().setPivot( otherSide ); - c.destroy(); - } - - if( this.myGrid != null ) - { - this.myGrid.remove( this ); - } - } - - @Override - public World getWorld() - { - return this.gridProxy.getLocation().getWorld(); - } - - @Override - public EnumSet getConnectedSides() - { - final EnumSet set = EnumSet.noneOf( ForgeDirection.class ); - for( final IGridConnection gc : this.connections ) - { - set.add( gc.getDirection( this ) ); - } - return set; - } - - @Override - public IReadOnlyCollection getConnections() - { - return new ReadOnlyCollection( this.connections ); - } - - @Override - public IGridBlock getGridBlock() - { - return this.gridProxy; - } - - @Override - public boolean isActive() - { - final IGrid g = this.getGrid(); - if( g != null ) - { - final IPathingGrid pg = g.getCache( IPathingGrid.class ); - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - return this.meetsChannelRequirements() && eg.isNetworkPowered() && !pg.isNetworkBooting(); - } - return false; - } - - @Override - public void loadFromNBT( final String name, final NBTTagCompound nodeData ) - { - if( this.myGrid == null ) - { - final NBTTagCompound node = nodeData.getCompoundTag( name ); - this.playerID = node.getInteger( "p" ); - this.setLastSecurityKey( node.getLong( "k" ) ); - - final long storageID = node.getLong( "g" ); - final GridStorage gridStorage = WorldData.instance().storageData().getGridStorage( storageID ); - this.setGridStorage( gridStorage ); - } - else - { - throw new IllegalStateException( "Loading data after part of a grid, this is invalid." ); - } - } - - @Override - public void saveToNBT( final String name, final NBTTagCompound nodeData ) - { - if( this.myStorage != null ) - { - final NBTTagCompound node = new NBTTagCompound(); - - node.setInteger( "p", this.playerID ); - node.setLong( "k", this.getLastSecurityKey() ); - node.setLong( "g", this.myStorage.getID() ); - - nodeData.setTag( name, node ); - } - else - { - nodeData.removeTag( name ); - } - } - - @Override - public boolean meetsChannelRequirements() - { - return ( !this.gridProxy.getFlags().contains( GridFlags.REQUIRE_CHANNEL ) || this.getUsedChannels() > 0 ); - } - - @Override - public boolean hasFlag( final GridFlags flag ) - { - return this.gridProxy.getFlags().contains( flag ); - } - - @Override - public int getPlayerID() - { - return this.playerID; - } - - @Override - public void setPlayerID( final int playerID ) - { - if( playerID >= 0 ) - { - this.playerID = playerID; - } - } - - private int getUsedChannels() - { - return this.usedChannels; - } - - private void FindConnections() - { - if( !this.gridProxy.isWorldAccessible() ) - { - return; - } - - final EnumSet newSecurityConnections = EnumSet.noneOf( ForgeDirection.class ); - - final DimensionalCoord dc = this.gridProxy.getLocation(); - for( final ForgeDirection f : ForgeDirection.VALID_DIRECTIONS ) - { - final IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ ); - if( te != null ) - { - final GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); - if( node == null ) - { - continue; - } - - final boolean isValidConnection = this.canConnect( node, f ) && node.canConnect( this, f.getOpposite() ); - - IGridConnection con = null; // find the connection for this - // direction.. - for( final IGridConnection c : this.getConnections() ) - { - if( c.getDirection( this ) == f ) - { - con = c; - break; - } - } - - if( con != null ) - { - final IGridNode os = con.getOtherSide( this ); - if( os == node ) - { - // if this connection is no longer valid, destroy it. - if( !isValidConnection ) - { - con.destroy(); - } - } - else - { - con.destroy(); - // throw new GridException( "invalid state found, encountered connection to phantom block." ); - } - } - else if( isValidConnection ) - { - if( node.getLastSecurityKey() != -1 ) - { - newSecurityConnections.add( f ); - } - else - { - // construct a new connection between these two nodes. - try - { - new GridConnection( node, this, f.getOpposite() ); - } - catch( final FailedConnection e ) - { - TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); - - return; - } - } - } - } - } - - for( final ForgeDirection f : newSecurityConnections ) - { - final IGridHost te = this.findGridHost( dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ ); - if( te != null ) - { - final GridNode node = (GridNode) te.getGridNode( f.getOpposite() ); - if( node == null ) - { - continue; - } - - // construct a new connection between these two nodes. - try - { - new GridConnection( node, this, f.getOpposite() ); - } - catch( final FailedConnection e ) - { - TickHandler.INSTANCE.addCallable( node.getWorld(), new MachineSecurityBreak( this ) ); - - return; - } - } - } - } - - private IGridHost findGridHost( final World world, final int x, final int y, final int z ) - { - if( world.blockExists( x, y, z ) ) - { - final TileEntity te = world.getTileEntity( x, y, z ); - if( te instanceof IGridHost ) - { - return (IGridHost) te; - } - } - return null; - } - - private boolean canConnect( final GridNode from, final ForgeDirection dir ) - { - if( !this.isValidDirection( dir ) ) - { - return false; - } - - return from.getColor().matches( this.getColor() ); - } - - private boolean isValidDirection( final ForgeDirection dir ) - { - return ( this.compressedData & ( 1 << ( 8 + dir.ordinal() ) ) ) > 0; - } - - private AEColor getColor() - { - return AEColor.values()[( this.compressedData >> 3 ) & 0x1F]; - } - - private void visitorConnection( final Object tracker, final IGridVisitor g, final Deque nextRun, final Deque nextConnections ) - { - if( g.visitNode( this ) ) - { - for( final IGridConnection gc : this.getConnections() ) - { - final GridNode gn = (GridNode) gc.getOtherSide( this ); - final GridConnection gcc = (GridConnection) gc; - - if( gcc.getVisitorIterationNumber() != tracker ) - { - gcc.setVisitorIterationNumber( tracker ); - nextConnections.add( gc ); - } - - if( tracker == gn.visitorIterationNumber ) - { - continue; - } - - gn.visitorIterationNumber = tracker; - - nextRun.add( gn ); - } - } - } - - private void visitorNode( final Object tracker, final IGridVisitor g, final Deque nextRun ) - { - if( g.visitNode( this ) ) - { - for( final IGridConnection gc : this.getConnections() ) - { - final GridNode gn = (GridNode) gc.getOtherSide( this ); - - if( tracker == gn.visitorIterationNumber ) - { - continue; - } - - gn.visitorIterationNumber = tracker; - - nextRun.add( gn ); - } - } - } - - GridStorage getGridStorage() - { - return this.myStorage; - } - - void setGridStorage( final GridStorage s ) - { - this.myStorage = s; - this.usedChannels = 0; - this.lastUsedChannels = 0; - } - - @Override - public IPathItem getControllerRoute() - { - if( this.connections.isEmpty() || this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return null; - } - - return (IPathItem) this.connections.get( 0 ); - } - - @Override - public void setControllerRoute( final IPathItem fast, final boolean zeroOut ) - { - if( zeroOut ) - { - this.usedChannels = 0; - } - - final int idx = this.connections.indexOf( fast ); - if( idx > 0 ) - { - this.connections.remove( fast ); - this.connections.add( 0, (IGridConnection) fast ); - } - } - - @Override - public boolean canSupportMoreChannels() - { - return this.getUsedChannels() < this.getMaxChannels(); - } - - private int getMaxChannels() - { - return CHANNEL_COUNT[this.compressedData & 0x03]; - } - - @Override - public IReadOnlyCollection getPossibleOptions() - { - return (IReadOnlyCollection) this.getConnections(); - } - - @Override - public void incrementChannelCount( final int usedChannels ) - { - this.usedChannels += usedChannels; - } - - @Override - public EnumSet getFlags() - { - return this.gridProxy.getFlags(); - } - - @Override - public void finalizeChannels() - { - if( this.getFlags().contains( GridFlags.CANNOT_CARRY ) ) - { - return; - } - - if( this.getLastUsedChannels() != this.getUsedChannels() ) - { - this.lastUsedChannels = this.usedChannels; - - if( this.getInternalGrid() != null ) - { - this.getInternalGrid().postEventTo( this, EVENT ); - } - } - } - - private int getLastUsedChannels() - { - return this.lastUsedChannels; - } - - public long getLastSecurityKey() - { - return this.lastSecurityKey; - } - - public void setLastSecurityKey( final long lastSecurityKey ) - { - this.lastSecurityKey = lastSecurityKey; - } - - public double getPreviousDraw() - { - return this.previousDraw; - } - - public void setPreviousDraw( final double previousDraw ) - { - this.previousDraw = previousDraw; - } - - private static class MachineSecurityBreak implements IWorldCallable - { - private final GridNode node; - - public MachineSecurityBreak( final GridNode node ) - { - this.node = node; - } - - @Override - public Void call( final World world ) throws Exception - { - this.node.getMachine().securityBreak(); - - return null; - } - } - - - private static class ConnectionComparator implements Comparator - { - private final IGridNode gn; - - public ConnectionComparator( final IGridNode gn ) - { - this.gn = gn; - } - - @Override - public int compare( final IGridConnection o1, final IGridConnection o2 ) - { - final boolean preferredA = o1.getOtherSide( this.gn ).hasFlag( GridFlags.PREFERRED ); - final boolean preferredB = o2.getOtherSide( this.gn ).hasFlag( GridFlags.PREFERRED ); - - return preferredA == preferredB ? 0 : ( preferredA ? -1 : 1 ); - } - } +public class GridNode implements IGridNode, IPathItem { + private static final MENetworkChannelsChanged EVENT = new MENetworkChannelsChanged(); + private static final int[] CHANNEL_COUNT = { 0, 8, 32 }; + + private final List connections = new LinkedList(); + private final IGridBlock gridProxy; + // old power draw, used to diff + private double previousDraw = 0.0; + private long lastSecurityKey = -1; + private int playerID = -1; + private GridStorage myStorage = null; + private Grid myGrid; + private Object visitorIterationNumber = null; + // connection criteria + private int compressedData = 0; + private int usedChannels = 0; + private int lastUsedChannels = 0; + + public GridNode(final IGridBlock what) { + this.gridProxy = what; + } + + IGridBlock getGridProxy() { + return this.gridProxy; + } + + Grid getMyGrid() { + return this.myGrid; + } + + public int usedChannels() { + return this.lastUsedChannels; + } + + Class getMachineClass() { + return this.getMachine().getClass(); + } + + void addConnection(final IGridConnection gridConnection) { + this.connections.add(gridConnection); + if (gridConnection.hasDirection()) { + this.gridProxy.onGridNotification(GridNotification.ConnectionsChanged); + } + + final IGridNode gn = this; + + Collections.sort(this.connections, new ConnectionComparator(gn)); + } + + void removeConnection(final IGridConnection gridConnection) { + this.connections.remove(gridConnection); + if (gridConnection.hasDirection()) { + this.gridProxy.onGridNotification(GridNotification.ConnectionsChanged); + } + } + + boolean hasConnection(final IGridNode otherSide) { + for (final IGridConnection gc : this.connections) { + if (gc.a() == otherSide || gc.b() == otherSide) { + return true; + } + } + return false; + } + + void validateGrid() { + final GridSplitDetector gsd + = new GridSplitDetector(this.getInternalGrid().getPivot()); + this.beginVisit(gsd); + if (!gsd.isPivotFound()) { + final IGridVisitor gp = new GridPropagator(new Grid(this)); + this.beginVisit(gp); + } + } + + public Grid getInternalGrid() { + if (this.myGrid == null) { + this.myGrid = new Grid(this); + } + + return this.myGrid; + } + + @Override + public void beginVisit(final IGridVisitor g) { + final Object tracker = new Object(); + + LinkedList nextRun = new LinkedList(); + nextRun.add(this); + + this.visitorIterationNumber = tracker; + + if (g instanceof IGridConnectionVisitor) { + final LinkedList nextConn + = new LinkedList(); + final IGridConnectionVisitor gcv = (IGridConnectionVisitor) g; + + while (!nextRun.isEmpty()) { + while (!nextConn.isEmpty()) { + gcv.visitConnection(nextConn.poll()); + } + + final Iterable thisRun = nextRun; + nextRun = new LinkedList(); + + for (final GridNode n : thisRun) { + n.visitorConnection(tracker, g, nextRun, nextConn); + } + } + } else { + while (!nextRun.isEmpty()) { + final Iterable thisRun = nextRun; + nextRun = new LinkedList(); + + for (final GridNode n : thisRun) { + n.visitorNode(tracker, g, nextRun); + } + } + } + } + + @Override + public void updateState() { + final EnumSet set = this.gridProxy.getFlags(); + + this.compressedData = set.contains(GridFlags.CANNOT_CARRY) + ? 0 + : (set.contains(GridFlags.DENSE_CAPACITY) ? 2 : 1); + + this.compressedData |= (this.gridProxy.getGridColor().ordinal() << 3); + + for (final ForgeDirection dir : this.gridProxy.getConnectableSides()) { + this.compressedData |= (1 << (dir.ordinal() + 8)); + } + + this.FindConnections(); + this.getInternalGrid(); + } + + @Override + public IGridHost getMachine() { + return this.gridProxy.getMachine(); + } + + @Override + public IGrid getGrid() { + return this.myGrid; + } + + void setGrid(final Grid grid) { + if (this.myGrid == grid) { + return; + } + + if (this.myGrid != null) { + this.myGrid.remove(this); + + if (this.myGrid.isEmpty()) { + this.myGrid.saveState(); + + for (final IGridCache c : grid.getCaches().values()) { + c.onJoin(this.myGrid.getMyStorage()); + } + } + } + + this.myGrid = grid; + this.myGrid.add(this); + } + + @Override + public void destroy() { + while (!this.connections.isEmpty()) { + // not part of this network for real anymore. + if (this.connections.size() == 1) { + this.setGridStorage(null); + } + + final IGridConnection c = this.connections.listIterator().next(); + final GridNode otherSide = (GridNode) c.getOtherSide(this); + otherSide.getInternalGrid().setPivot(otherSide); + c.destroy(); + } + + if (this.myGrid != null) { + this.myGrid.remove(this); + } + } + + @Override + public World getWorld() { + return this.gridProxy.getLocation().getWorld(); + } + + @Override + public EnumSet getConnectedSides() { + final EnumSet set = EnumSet.noneOf(ForgeDirection.class); + for (final IGridConnection gc : this.connections) { + set.add(gc.getDirection(this)); + } + return set; + } + + @Override + public IReadOnlyCollection getConnections() { + return new ReadOnlyCollection(this.connections); + } + + @Override + public IGridBlock getGridBlock() { + return this.gridProxy; + } + + @Override + public boolean isActive() { + final IGrid g = this.getGrid(); + if (g != null) { + final IPathingGrid pg = g.getCache(IPathingGrid.class); + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + return this.meetsChannelRequirements() && eg.isNetworkPowered() + && !pg.isNetworkBooting(); + } + return false; + } + + @Override + public void loadFromNBT(final String name, final NBTTagCompound nodeData) { + if (this.myGrid == null) { + final NBTTagCompound node = nodeData.getCompoundTag(name); + this.playerID = node.getInteger("p"); + this.setLastSecurityKey(node.getLong("k")); + + final long storageID = node.getLong("g"); + final GridStorage gridStorage + = WorldData.instance().storageData().getGridStorage(storageID); + this.setGridStorage(gridStorage); + } else { + throw new IllegalStateException( + "Loading data after part of a grid, this is invalid." + ); + } + } + + @Override + public void saveToNBT(final String name, final NBTTagCompound nodeData) { + if (this.myStorage != null) { + final NBTTagCompound node = new NBTTagCompound(); + + node.setInteger("p", this.playerID); + node.setLong("k", this.getLastSecurityKey()); + node.setLong("g", this.myStorage.getID()); + + nodeData.setTag(name, node); + } else { + nodeData.removeTag(name); + } + } + + @Override + public boolean meetsChannelRequirements() { + return ( + !this.gridProxy.getFlags().contains(GridFlags.REQUIRE_CHANNEL) + || this.getUsedChannels() > 0 + ); + } + + @Override + public boolean hasFlag(final GridFlags flag) { + return this.gridProxy.getFlags().contains(flag); + } + + @Override + public int getPlayerID() { + return this.playerID; + } + + @Override + public void setPlayerID(final int playerID) { + if (playerID >= 0) { + this.playerID = playerID; + } + } + + private int getUsedChannels() { + return this.usedChannels; + } + + private void FindConnections() { + if (!this.gridProxy.isWorldAccessible()) { + return; + } + + final EnumSet newSecurityConnections + = EnumSet.noneOf(ForgeDirection.class); + + final DimensionalCoord dc = this.gridProxy.getLocation(); + for (final ForgeDirection f : ForgeDirection.VALID_DIRECTIONS) { + final IGridHost te = this.findGridHost( + dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ + ); + if (te != null) { + final GridNode node = (GridNode) te.getGridNode(f.getOpposite()); + if (node == null) { + continue; + } + + final boolean isValidConnection + = this.canConnect(node, f) && node.canConnect(this, f.getOpposite()); + + IGridConnection con = null; // find the connection for this + // direction.. + for (final IGridConnection c : this.getConnections()) { + if (c.getDirection(this) == f) { + con = c; + break; + } + } + + if (con != null) { + final IGridNode os = con.getOtherSide(this); + if (os == node) { + // if this connection is no longer valid, destroy it. + if (!isValidConnection) { + con.destroy(); + } + } else { + con.destroy(); + // throw new GridException( "invalid state found, encountered + // connection to phantom block." ); + } + } else if (isValidConnection) { + if (node.getLastSecurityKey() != -1) { + newSecurityConnections.add(f); + } else { + // construct a new connection between these two nodes. + try { + new GridConnection(node, this, f.getOpposite()); + } catch (final FailedConnection e) { + TickHandler.INSTANCE.addCallable( + node.getWorld(), new MachineSecurityBreak(this) + ); + + return; + } + } + } + } + } + + for (final ForgeDirection f : newSecurityConnections) { + final IGridHost te = this.findGridHost( + dc.getWorld(), dc.x + f.offsetX, dc.y + f.offsetY, dc.z + f.offsetZ + ); + if (te != null) { + final GridNode node = (GridNode) te.getGridNode(f.getOpposite()); + if (node == null) { + continue; + } + + // construct a new connection between these two nodes. + try { + new GridConnection(node, this, f.getOpposite()); + } catch (final FailedConnection e) { + TickHandler.INSTANCE.addCallable( + node.getWorld(), new MachineSecurityBreak(this) + ); + + return; + } + } + } + } + + private IGridHost + findGridHost(final World world, final int x, final int y, final int z) { + if (world.blockExists(x, y, z)) { + final TileEntity te = world.getTileEntity(x, y, z); + if (te instanceof IGridHost) { + return (IGridHost) te; + } + } + return null; + } + + private boolean canConnect(final GridNode from, final ForgeDirection dir) { + if (!this.isValidDirection(dir)) { + return false; + } + + return from.getColor().matches(this.getColor()); + } + + private boolean isValidDirection(final ForgeDirection dir) { + return (this.compressedData & (1 << (8 + dir.ordinal()))) > 0; + } + + private AEColor getColor() { + return AEColor.values()[(this.compressedData >> 3) & 0x1F]; + } + + private void visitorConnection( + final Object tracker, + final IGridVisitor g, + final Deque nextRun, + final Deque nextConnections + ) { + if (g.visitNode(this)) { + for (final IGridConnection gc : this.getConnections()) { + final GridNode gn = (GridNode) gc.getOtherSide(this); + final GridConnection gcc = (GridConnection) gc; + + if (gcc.getVisitorIterationNumber() != tracker) { + gcc.setVisitorIterationNumber(tracker); + nextConnections.add(gc); + } + + if (tracker == gn.visitorIterationNumber) { + continue; + } + + gn.visitorIterationNumber = tracker; + + nextRun.add(gn); + } + } + } + + private void visitorNode( + final Object tracker, final IGridVisitor g, final Deque nextRun + ) { + if (g.visitNode(this)) { + for (final IGridConnection gc : this.getConnections()) { + final GridNode gn = (GridNode) gc.getOtherSide(this); + + if (tracker == gn.visitorIterationNumber) { + continue; + } + + gn.visitorIterationNumber = tracker; + + nextRun.add(gn); + } + } + } + + GridStorage getGridStorage() { + return this.myStorage; + } + + void setGridStorage(final GridStorage s) { + this.myStorage = s; + this.usedChannels = 0; + this.lastUsedChannels = 0; + } + + @Override + public IPathItem getControllerRoute() { + if (this.connections.isEmpty() + || this.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return null; + } + + return (IPathItem) this.connections.get(0); + } + + @Override + public void setControllerRoute(final IPathItem fast, final boolean zeroOut) { + if (zeroOut) { + this.usedChannels = 0; + } + + final int idx = this.connections.indexOf(fast); + if (idx > 0) { + this.connections.remove(fast); + this.connections.add(0, (IGridConnection) fast); + } + } + + @Override + public boolean canSupportMoreChannels() { + return this.getUsedChannels() < this.getMaxChannels(); + } + + private int getMaxChannels() { + return CHANNEL_COUNT[this.compressedData & 0x03]; + } + + @Override + public IReadOnlyCollection getPossibleOptions() { + return (IReadOnlyCollection) this.getConnections(); + } + + @Override + public void incrementChannelCount(final int usedChannels) { + this.usedChannels += usedChannels; + } + + @Override + public EnumSet getFlags() { + return this.gridProxy.getFlags(); + } + + @Override + public void finalizeChannels() { + if (this.getFlags().contains(GridFlags.CANNOT_CARRY)) { + return; + } + + if (this.getLastUsedChannels() != this.getUsedChannels()) { + this.lastUsedChannels = this.usedChannels; + + if (this.getInternalGrid() != null) { + this.getInternalGrid().postEventTo(this, EVENT); + } + } + } + + private int getLastUsedChannels() { + return this.lastUsedChannels; + } + + public long getLastSecurityKey() { + return this.lastSecurityKey; + } + + public void setLastSecurityKey(final long lastSecurityKey) { + this.lastSecurityKey = lastSecurityKey; + } + + public double getPreviousDraw() { + return this.previousDraw; + } + + public void setPreviousDraw(final double previousDraw) { + this.previousDraw = previousDraw; + } + + private static class MachineSecurityBreak implements IWorldCallable { + private final GridNode node; + + public MachineSecurityBreak(final GridNode node) { + this.node = node; + } + + @Override + public Void call(final World world) throws Exception { + this.node.getMachine().securityBreak(); + + return null; + } + } + + private static class ConnectionComparator implements Comparator { + private final IGridNode gn; + + public ConnectionComparator(final IGridNode gn) { + this.gn = gn; + } + + @Override + public int compare(final IGridConnection o1, final IGridConnection o2) { + final boolean preferredA + = o1.getOtherSide(this.gn).hasFlag(GridFlags.PREFERRED); + final boolean preferredB + = o2.getOtherSide(this.gn).hasFlag(GridFlags.PREFERRED); + + return preferredA == preferredB ? 0 : (preferredA ? -1 : 1); + } + } } diff --git a/src/main/java/appeng/me/GridNodeCollection.java b/src/main/java/appeng/me/GridNodeCollection.java index 64d39def..3cb87109 100644 --- a/src/main/java/appeng/me/GridNodeCollection.java +++ b/src/main/java/appeng/me/GridNodeCollection.java @@ -18,78 +18,65 @@ package appeng.me; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.util.IReadOnlyCollection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; +public class GridNodeCollection implements IReadOnlyCollection { + private final Map, MachineSet> machines; + public GridNodeCollection(final Map, MachineSet> machines + ) { + this.machines = machines; + } -public class GridNodeCollection implements IReadOnlyCollection -{ - private final Map, MachineSet> machines; + @Override + public Iterator iterator() { + return new GridNodeIterator(this.machines); + } - public GridNodeCollection( final Map, MachineSet> machines ) - { - this.machines = machines; - } + @Override + public int size() { + int size = 0; - @Override - public Iterator iterator() - { - return new GridNodeIterator( this.machines ); - } + for (final Set o : this.machines.values()) { + size += o.size(); + } - @Override - public int size() - { - int size = 0; + return size; + } - for( final Set o : this.machines.values() ) - { - size += o.size(); - } + @Override + public boolean isEmpty() { + for (final Set o : this.machines.values()) { + if (!o.isEmpty()) { + return false; + } + } - return size; - } + return true; + } - @Override - public boolean isEmpty() - { - for( final Set o : this.machines.values() ) - { - if( !o.isEmpty() ) - { - return false; - } - } + @Override + public boolean contains(final Object maybeGridNode) { + final boolean doesContainNode; - return true; - } + if (maybeGridNode instanceof IGridNode) { + final IGridNode node = (IGridNode) maybeGridNode; + final IGridHost machine = node.getMachine(); + final Class machineClass = machine.getClass(); - @Override - public boolean contains( final Object maybeGridNode ) - { - final boolean doesContainNode; + final MachineSet machineSet = this.machines.get(machineClass); - if( maybeGridNode instanceof IGridNode ) - { - final IGridNode node = (IGridNode) maybeGridNode; - final IGridHost machine = node.getMachine(); - final Class machineClass = machine.getClass(); + doesContainNode = machineSet != null && machineSet.contains(maybeGridNode); + } else { + doesContainNode = false; + } - final MachineSet machineSet = this.machines.get( machineClass ); - - doesContainNode = machineSet != null && machineSet.contains( maybeGridNode ); - } - else - { - doesContainNode = false; - } - - return doesContainNode; - } + return doesContainNode; + } } diff --git a/src/main/java/appeng/me/GridNodeIterator.java b/src/main/java/appeng/me/GridNodeIterator.java index 219ea588..fcc5366f 100644 --- a/src/main/java/appeng/me/GridNodeIterator.java +++ b/src/main/java/appeng/me/GridNodeIterator.java @@ -18,13 +18,11 @@ package appeng.me; - -import appeng.api.networking.IGridHost; -import appeng.api.networking.IGridNode; - import java.util.Iterator; import java.util.Map; +import appeng.api.networking.IGridHost; +import appeng.api.networking.IGridNode; /** * Nested iterator for {@link appeng.me.MachineSet} @@ -32,55 +30,44 @@ import java.util.Map; * Traverses first over the {@link appeng.me.MachineSet} and then over every containing * {@link appeng.api.networking.IGridNode} */ -public class GridNodeIterator implements Iterator -{ - private final Iterator outerIterator; - private Iterator innerIterator; +public class GridNodeIterator implements Iterator { + private final Iterator outerIterator; + private Iterator innerIterator; - public GridNodeIterator( final Map, MachineSet> machines ) - { - this.outerIterator = machines.values().iterator(); - this.innerHasNext(); - } + public GridNodeIterator(final Map, MachineSet> machines) { + this.outerIterator = machines.values().iterator(); + this.innerHasNext(); + } - private boolean innerHasNext() - { - final boolean hasNext = this.outerIterator.hasNext(); + private boolean innerHasNext() { + final boolean hasNext = this.outerIterator.hasNext(); - if( hasNext ) - { - final MachineSet nextElem = this.outerIterator.next(); - this.innerIterator = nextElem.iterator(); - } + if (hasNext) { + final MachineSet nextElem = this.outerIterator.next(); + this.innerIterator = nextElem.iterator(); + } - return hasNext; - } + return hasNext; + } - @Override - public boolean hasNext() - { - while( true ) - { - if( this.innerIterator.hasNext() ) - { - return true; - } - else if( !this.innerHasNext() ) - { - return false; - } - } - } + @Override + public boolean hasNext() { + while (true) { + if (this.innerIterator.hasNext()) { + return true; + } else if (!this.innerHasNext()) { + return false; + } + } + } - @Override - public IGridNode next() - { - return this.innerIterator.next(); - } + @Override + public IGridNode next() { + return this.innerIterator.next(); + } - @Override - public void remove() - { - this.innerIterator.remove(); - } + @Override + public void remove() { + this.innerIterator.remove(); + } } diff --git a/src/main/java/appeng/me/GridPropagator.java b/src/main/java/appeng/me/GridPropagator.java index 4bc6c99f..2e12292e 100644 --- a/src/main/java/appeng/me/GridPropagator.java +++ b/src/main/java/appeng/me/GridPropagator.java @@ -18,30 +18,24 @@ package appeng.me; - import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; +public class GridPropagator implements IGridVisitor { + private final Grid g; -public class GridPropagator implements IGridVisitor -{ - private final Grid g; + public GridPropagator(final Grid g) { + this.g = g; + } - public GridPropagator( final Grid g ) - { - this.g = g; - } + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + if (gn.getMyGrid() != this.g || this.g.getPivot() == n) { + gn.setGrid(this.g); - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - if( gn.getMyGrid() != this.g || this.g.getPivot() == n ) - { - gn.setGrid( this.g ); - - return true; - } - return false; - } + return true; + } + return false; + } } diff --git a/src/main/java/appeng/me/GridSplitDetector.java b/src/main/java/appeng/me/GridSplitDetector.java index ac0b98c7..f9490241 100644 --- a/src/main/java/appeng/me/GridSplitDetector.java +++ b/src/main/java/appeng/me/GridSplitDetector.java @@ -18,40 +18,31 @@ package appeng.me; - import appeng.api.networking.IGridNode; import appeng.api.networking.IGridVisitor; +class GridSplitDetector implements IGridVisitor { + private final IGridNode pivot; + private boolean pivotFound; -class GridSplitDetector implements IGridVisitor -{ + public GridSplitDetector(final IGridNode pivot) { + this.pivot = pivot; + } - private final IGridNode pivot; - private boolean pivotFound; + @Override + public boolean visitNode(final IGridNode n) { + if (n == this.pivot) { + this.setPivotFound(true); + } - public GridSplitDetector( final IGridNode pivot ) - { - this.pivot = pivot; - } + return !this.isPivotFound(); + } - @Override - public boolean visitNode( final IGridNode n ) - { - if( n == this.pivot ) - { - this.setPivotFound( true ); - } + public boolean isPivotFound() { + return this.pivotFound; + } - return !this.isPivotFound(); - } - - public boolean isPivotFound() - { - return this.pivotFound; - } - - private void setPivotFound( final boolean pivotFound ) - { - this.pivotFound = pivotFound; - } + private void setPivotFound(final boolean pivotFound) { + this.pivotFound = pivotFound; + } } diff --git a/src/main/java/appeng/me/GridStorage.java b/src/main/java/appeng/me/GridStorage.java index cf9cfc58..c5263f14 100644 --- a/src/main/java/appeng/me/GridStorage.java +++ b/src/main/java/appeng/me/GridStorage.java @@ -18,6 +18,11 @@ package appeng.me; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.util.WeakHashMap; import appeng.api.networking.IGrid; import appeng.api.networking.IGridStorage; @@ -26,129 +31,105 @@ import appeng.core.worlddata.WorldData; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.util.WeakHashMap; +public class GridStorage implements IGridStorage { + private final long myID; + private final NBTTagCompound data; + private final GridStorageSearch mySearchEntry; // keep myself in the list until I'm + private final WeakHashMap divided + = new WeakHashMap(); + private WeakReference internalGrid = null; + // lost... -public class GridStorage implements IGridStorage -{ + /** + * for use with world settings + * + * @param id ID of grid storage + * @param gss grid storage search + */ + public GridStorage(final long id, final GridStorageSearch gss) { + this.myID = id; + this.mySearchEntry = gss; + this.data = new NBTTagCompound(); + } - private final long myID; - private final NBTTagCompound data; - private final GridStorageSearch mySearchEntry; // keep myself in the list until I'm - private final WeakHashMap divided = new WeakHashMap(); - private WeakReference internalGrid = null; + /** + * for use with world settings + * + * @param input array of bytes string + * @param id ID of grid storage + * @param gss grid storage search + */ + public GridStorage(final String input, final long id, final GridStorageSearch gss) { + this.myID = id; + this.mySearchEntry = gss; + NBTTagCompound myTag = null; - // lost... + try { + final byte[] byteData + = javax.xml.bind.DatatypeConverter.parseBase64Binary(input); + myTag = CompressedStreamTools.readCompressed(new ByteArrayInputStream(byteData + )); + } catch (final Throwable t) { + myTag = new NBTTagCompound(); + } - /** - * for use with world settings - * - * @param id ID of grid storage - * @param gss grid storage search - */ - public GridStorage( final long id, final GridStorageSearch gss ) - { - this.myID = id; - this.mySearchEntry = gss; - this.data = new NBTTagCompound(); - } + this.data = myTag; + } - /** - * for use with world settings - * - * @param input array of bytes string - * @param id ID of grid storage - * @param gss grid storage search - */ - public GridStorage( final String input, final long id, final GridStorageSearch gss ) - { - this.myID = id; - this.mySearchEntry = gss; - NBTTagCompound myTag = null; + /** + * fake storage. + */ + public GridStorage() { + this.myID = 0; + this.mySearchEntry = null; + this.data = new NBTTagCompound(); + } - try - { - final byte[] byteData = javax.xml.bind.DatatypeConverter.parseBase64Binary( input ); - myTag = CompressedStreamTools.readCompressed( new ByteArrayInputStream( byteData ) ); - } - catch( final Throwable t ) - { - myTag = new NBTTagCompound(); - } + public String getValue() { + final Grid currentGrid = (Grid) this.getGrid(); + if (currentGrid != null) { + currentGrid.saveState(); + } - this.data = myTag; - } + try { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + CompressedStreamTools.writeCompressed(this.data, out); + return javax.xml.bind.DatatypeConverter.printBase64Binary(out.toByteArray()); + } catch (final IOException e) { + AELog.debug(e); + } - /** - * fake storage. - */ - public GridStorage() - { - this.myID = 0; - this.mySearchEntry = null; - this.data = new NBTTagCompound(); - } + return ""; + } - public String getValue() - { - final Grid currentGrid = (Grid) this.getGrid(); - if( currentGrid != null ) - { - currentGrid.saveState(); - } + public IGrid getGrid() { + return this.internalGrid == null ? null : this.internalGrid.get(); + } - try - { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - CompressedStreamTools.writeCompressed( this.data, out ); - return javax.xml.bind.DatatypeConverter.printBase64Binary( out.toByteArray() ); - } - catch( final IOException e ) - { - AELog.debug( e ); - } + void setGrid(final Grid grid) { + this.internalGrid = new WeakReference(grid); + } - return ""; - } + @Override + public NBTTagCompound dataObject() { + return this.data; + } - public IGrid getGrid() - { - return this.internalGrid == null ? null : this.internalGrid.get(); - } + @Override + public long getID() { + return this.myID; + } - void setGrid( final Grid grid ) - { - this.internalGrid = new WeakReference( grid ); - } + void addDivided(final GridStorage gs) { + this.divided.put(gs, true); + } - @Override - public NBTTagCompound dataObject() - { - return this.data; - } + boolean hasDivided(final GridStorage myStorage) { + return this.divided.containsKey(myStorage); + } - @Override - public long getID() - { - return this.myID; - } - - void addDivided( final GridStorage gs ) - { - this.divided.put( gs, true ); - } - - boolean hasDivided( final GridStorage myStorage ) - { - return this.divided.containsKey( myStorage ); - } - - void remove() - { - WorldData.instance().storageData().destroyGridStorage( this.myID ); - } + void remove() { + WorldData.instance().storageData().destroyGridStorage(this.myID); + } } diff --git a/src/main/java/appeng/me/GridStorageSearch.java b/src/main/java/appeng/me/GridStorageSearch.java index c4107205..06a72a44 100644 --- a/src/main/java/appeng/me/GridStorageSearch.java +++ b/src/main/java/appeng/me/GridStorageSearch.java @@ -18,56 +18,44 @@ package appeng.me; - import java.lang.ref.WeakReference; +public class GridStorageSearch { + private final long id; + private WeakReference gridStorage; -public class GridStorageSearch -{ + /** + * for use with the world settings + * + * @param id ID of grid storage search + */ + public GridStorageSearch(final long id) { + this.id = id; + } - private final long id; - private WeakReference gridStorage; + @Override + public int hashCode() { + return ((Long) this.id).hashCode(); + } - /** - * for use with the world settings - * - * @param id ID of grid storage search - */ - public GridStorageSearch( final long id ) - { - this.id = id; - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } - @Override - public int hashCode() - { - return ( (Long) this.id ).hashCode(); - } + final GridStorageSearch other = (GridStorageSearch) obj; + return this.id == other.id; + } - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } + public WeakReference getGridStorage() { + return this.gridStorage; + } - final GridStorageSearch other = (GridStorageSearch) obj; - return this.id == other.id; - - } - - public WeakReference getGridStorage() - { - return this.gridStorage; - } - - public void setGridStorage( final WeakReference gridStorage ) - { - this.gridStorage = gridStorage; - } + public void setGridStorage(final WeakReference gridStorage) { + this.gridStorage = gridStorage; + } } diff --git a/src/main/java/appeng/me/MachineSet.java b/src/main/java/appeng/me/MachineSet.java index a3de198f..e35970be 100644 --- a/src/main/java/appeng/me/MachineSet.java +++ b/src/main/java/appeng/me/MachineSet.java @@ -18,29 +18,23 @@ package appeng.me; +import java.util.HashSet; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.IMachineSet; -import java.util.HashSet; +public class MachineSet extends HashSet implements IMachineSet { + private static final long serialVersionUID = 3224660708327386933L; + private final Class machine; -public class MachineSet extends HashSet implements IMachineSet -{ + MachineSet(final Class m) { + this.machine = m; + } - private static final long serialVersionUID = 3224660708327386933L; - - private final Class machine; - - MachineSet( final Class m ) - { - this.machine = m; - } - - @Override - public Class getMachineClass() - { - return this.machine; - } + @Override + public Class getMachineClass() { + return this.machine; + } } diff --git a/src/main/java/appeng/me/NetworkEventBus.java b/src/main/java/appeng/me/NetworkEventBus.java index f0b64084..5fea4875 100644 --- a/src/main/java/appeng/me/NetworkEventBus.java +++ b/src/main/java/appeng/me/NetworkEventBus.java @@ -18,199 +18,171 @@ package appeng.me; +import java.lang.reflect.Method; +import java.util.*; +import java.util.Map.Entry; import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkEvent; import appeng.api.networking.events.MENetworkEventSubscribe; import appeng.core.AELog; -import java.lang.reflect.Method; -import java.util.*; -import java.util.Map.Entry; +public class NetworkEventBus { + private static final Collection READ_CLASSES = new HashSet(); + private static final + Map, Map> EVENTS + = new HashMap, Map>(); + void readClass(final Class listAs, final Class c) { + if (READ_CLASSES.contains(c)) { + return; + } + READ_CLASSES.add(c); -public class NetworkEventBus -{ - private static final Collection READ_CLASSES = new HashSet(); - private static final Map, Map> EVENTS = new HashMap, Map>(); + try { + for (final Method m : c.getMethods()) { + final MENetworkEventSubscribe s + = m.getAnnotation(MENetworkEventSubscribe.class); + if (s != null) { + final Class[] types = m.getParameterTypes(); + if (types.length == 1) { + if (MENetworkEvent.class.isAssignableFrom(types[0])) { + Map classEvents + = EVENTS.get(types[0]); + if (classEvents == null) { + EVENTS.put( + types[0], + classEvents = new HashMap() + ); + } - void readClass( final Class listAs, final Class c ) - { - if( READ_CLASSES.contains( c ) ) - { - return; - } - READ_CLASSES.add( c ); + MENetworkEventInfo thisEvent = classEvents.get(listAs); + if (thisEvent == null) { + thisEvent = new MENetworkEventInfo(); + } - try - { - for( final Method m : c.getMethods() ) - { - final MENetworkEventSubscribe s = m.getAnnotation( MENetworkEventSubscribe.class ); - if( s != null ) - { - final Class[] types = m.getParameterTypes(); - if( types.length == 1 ) - { - if( MENetworkEvent.class.isAssignableFrom( types[0] ) ) - { + thisEvent.Add(types[0], c, m); - Map classEvents = EVENTS.get( types[0] ); - if( classEvents == null ) - { - EVENTS.put( types[0], classEvents = new HashMap() ); - } + classEvents.put(listAs, thisEvent); + } else { + throw new IllegalStateException( + "Invalid ME Network Event Subscriber, " + m.getName() + + "s Parameter must extend MENetworkEvent." + ); + } + } else { + throw new IllegalStateException( + "Invalid ME Network Event Subscriber, " + m.getName() + + " must have exactly 1 parameter." + ); + } + } + } + } catch (final Throwable t) { + throw new IllegalStateException( + "Error while adding " + c.getName() + " to event bus", t + ); + } + } - MENetworkEventInfo thisEvent = classEvents.get( listAs ); - if( thisEvent == null ) - { - thisEvent = new MENetworkEventInfo(); - } + MENetworkEvent postEvent(final Grid g, final MENetworkEvent e) { + final Map subscribers = EVENTS.get(e.getClass()); + int x = 0; - thisEvent.Add( types[0], c, m ); + try { + if (subscribers != null) { + for (final Entry subscriber : + subscribers.entrySet()) { + final MENetworkEventInfo target = subscriber.getValue(); + final GridCacheWrapper cache = g.getCaches().get(subscriber.getKey()); + if (cache != null) { + x++; + target.invoke(cache.getCache(), e); + } - classEvents.put( listAs, thisEvent ); - } - else - { - throw new IllegalStateException( "Invalid ME Network Event Subscriber, " + m.getName() + "s Parameter must extend MENetworkEvent." ); - } - } - else - { - throw new IllegalStateException( "Invalid ME Network Event Subscriber, " + m.getName() + " must have exactly 1 parameter." ); - } - } - } - } - catch( final Throwable t ) - { - throw new IllegalStateException( "Error while adding " + c.getName() + " to event bus", t ); - } - } + for (final IGridNode obj : g.getMachines(subscriber.getKey())) { + x++; + target.invoke(obj.getMachine(), e); + } + } + } + } catch (final NetworkEventDone done) { + // Early out. + } - MENetworkEvent postEvent( final Grid g, final MENetworkEvent e ) - { - final Map subscribers = EVENTS.get( e.getClass() ); - int x = 0; + e.setVisitedObjects(x); + return e; + } - try - { - if( subscribers != null ) - { - for( final Entry subscriber : subscribers.entrySet() ) - { - final MENetworkEventInfo target = subscriber.getValue(); - final GridCacheWrapper cache = g.getCaches().get( subscriber.getKey() ); - if( cache != null ) - { - x++; - target.invoke( cache.getCache(), e ); - } + MENetworkEvent + postEventTo(final Grid grid, final GridNode node, final MENetworkEvent e) { + final Map subscribers = EVENTS.get(e.getClass()); + int x = 0; - for( final IGridNode obj : g.getMachines( subscriber.getKey() ) ) - { - x++; - target.invoke( obj.getMachine(), e ); - } - } - } - } - catch( final NetworkEventDone done ) - { - // Early out. - } + try { + if (subscribers != null) { + final MENetworkEventInfo target = subscribers.get(node.getMachineClass()); + if (target != null) { + x++; + target.invoke(node.getMachine(), e); + } + } + } catch (final NetworkEventDone done) { + // Early out. + } - e.setVisitedObjects( x ); - return e; - } + e.setVisitedObjects(x); + return e; + } - MENetworkEvent postEventTo( final Grid grid, final GridNode node, final MENetworkEvent e ) - { - final Map subscribers = EVENTS.get( e.getClass() ); - int x = 0; + private static class NetworkEventDone extends Throwable { + private static final long serialVersionUID = -3079021487019171205L; + } - try - { - if( subscribers != null ) - { - final MENetworkEventInfo target = subscribers.get( node.getMachineClass() ); - if( target != null ) - { - x++; - target.invoke( node.getMachine(), e ); - } - } - } - catch( final NetworkEventDone done ) - { - // Early out. - } + private class EventMethod { + private final Class objClass; + private final Method objMethod; + private final Class objEvent; - e.setVisitedObjects( x ); - return e; - } + public EventMethod( + final Class Event, final Class ObjClass, final Method ObjMethod + ) { + this.objClass = ObjClass; + this.objMethod = ObjMethod; + this.objEvent = Event; + } - private static class NetworkEventDone extends Throwable - { + private void invoke(final Object obj, final MENetworkEvent e) + throws NetworkEventDone { + try { + this.objMethod.invoke(obj, e); + } catch (final Throwable e1) { + AELog.error("[AppEng] Network Event caused exception:"); + AELog.error("Offending Class: " + obj.getClass().getName()); + AELog.error("Offending Object: " + obj.toString()); + AELog.debug(e1); + throw new IllegalStateException(e1); + } - private static final long serialVersionUID = -3079021487019171205L; - } + if (e.isCanceled()) { + throw new NetworkEventDone(); + } + } + } + private class MENetworkEventInfo { + private final List methods = new ArrayList(); - private class EventMethod - { + private void + Add(final Class Event, final Class ObjClass, final Method ObjMethod) { + this.methods.add(new EventMethod(Event, ObjClass, ObjMethod)); + } - private final Class objClass; - private final Method objMethod; - private final Class objEvent; - - public EventMethod( final Class Event, final Class ObjClass, final Method ObjMethod ) - { - this.objClass = ObjClass; - this.objMethod = ObjMethod; - this.objEvent = Event; - } - - private void invoke( final Object obj, final MENetworkEvent e ) throws NetworkEventDone - { - try - { - this.objMethod.invoke( obj, e ); - } - catch( final Throwable e1 ) - { - AELog.error( "[AppEng] Network Event caused exception:" ); - AELog.error( "Offending Class: " + obj.getClass().getName() ); - AELog.error( "Offending Object: " + obj.toString() ); - AELog.debug( e1 ); - throw new IllegalStateException( e1 ); - } - - if( e.isCanceled() ) - { - throw new NetworkEventDone(); - } - } - } - - - private class MENetworkEventInfo - { - - private final List methods = new ArrayList(); - - private void Add( final Class Event, final Class ObjClass, final Method ObjMethod ) - { - this.methods.add( new EventMethod( Event, ObjClass, ObjMethod ) ); - } - - private void invoke( final Object obj, final MENetworkEvent e ) throws NetworkEventDone - { - for( final EventMethod em : this.methods ) - { - em.invoke( obj, e ); - } - } - } + private void invoke(final Object obj, final MENetworkEvent e) + throws NetworkEventDone { + for (final 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 9397d276..4bd5d0da 100644 --- a/src/main/java/appeng/me/NetworkList.java +++ b/src/main/java/appeng/me/NetworkList.java @@ -18,96 +18,79 @@ package appeng.me; - import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; - /** * TODO: Test if copy was actually necessary. */ -public class NetworkList implements Collection -{ +public class NetworkList implements Collection { + private List networks = new CopyOnWriteArrayList(); - private List networks = new CopyOnWriteArrayList(); + @Override + public int size() { + return this.networks.size(); + } - @Override - public int size() - { - return this.networks.size(); - } + @Override + public boolean isEmpty() { + return this.networks.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.networks.isEmpty(); - } + @Override + public boolean contains(final Object o) { + return this.networks.contains(o); + } - @Override - public boolean contains( final Object o ) - { - return this.networks.contains( o ); - } + @Override + public Iterator iterator() { + return this.networks.iterator(); + } - @Override - public Iterator iterator() - { - return this.networks.iterator(); - } + @Override + public Object[] toArray() { + return this.networks.toArray(); + } - @Override - public Object[] toArray() - { - return this.networks.toArray(); - } + @Override + public T[] toArray(final T[] a) { + return this.networks.toArray(a); + } - @Override - public T[] toArray( final T[] a ) - { - return this.networks.toArray( a ); - } + @Override + public boolean add(final Grid e) { + return this.networks.add(e); + } - @Override - public boolean add( final Grid e ) - { - return this.networks.add( e ); - } + @Override + public boolean remove(final Object o) { + return this.networks.remove(o); + } - @Override - public boolean remove( final Object o ) - { - return this.networks.remove( o ); - } + @Override + public boolean containsAll(final Collection c) { + return this.networks.containsAll(c); + } - @Override - public boolean containsAll( final Collection c ) - { - return this.networks.containsAll( c ); - } + @Override + public boolean addAll(final Collection c) { + return this.networks.addAll(c); + } - @Override - public boolean addAll( final Collection c ) - { - return this.networks.addAll( c ); - } + @Override + public boolean removeAll(final Collection c) { + return this.networks.removeAll(c); + } - @Override - public boolean removeAll( final Collection c ) - { - return this.networks.removeAll( c ); - } + @Override + public boolean retainAll(final Collection c) { + return this.networks.retainAll(c); + } - @Override - public boolean retainAll( final Collection c ) - { - return this.networks.retainAll( c ); - } - - @Override - public void clear() - { - this.networks.clear(); - } + @Override + public void clear() { + this.networks.clear(); + } } diff --git a/src/main/java/appeng/me/cache/CraftingGridCache.java b/src/main/java/appeng/me/cache/CraftingGridCache.java index de430697..6ff0ff4d 100644 --- a/src/main/java/appeng/me/cache/CraftingGridCache.java +++ b/src/main/java/appeng/me/cache/CraftingGridCache.java @@ -18,6 +18,12 @@ package appeng.me.cache; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -51,594 +57,545 @@ import appeng.util.ItemSorters; import com.google.common.collect.*; import net.minecraft.world.World; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadFactory; - - -public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper, ICellProvider, IMEInventoryHandler -{ - - private static final ExecutorService CRAFTING_POOL; - private static final Comparator COMPARATOR = new Comparator() - { - @Override - public int compare( final ICraftingPatternDetails firstDetail, final ICraftingPatternDetails nextDetail ) - { - return nextDetail.getPriority() - firstDetail.getPriority(); - } - }; - - static - { - final ThreadFactory factory = new ThreadFactory() - { - - @Override - public Thread newThread( final 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 final Map> craftingMethods = new HashMap>(); - private final Map> craftableItems = new HashMap>(); - private final Set emitableItems = new HashSet(); - private final Map craftingLinks = new HashMap(); - private final Multimap interests = HashMultimap.create(); - private final GenericInterestManager interestManager = new GenericInterestManager( this.interests ); - private IStorageGrid storageGrid; - private IEnergyGrid energyGrid; - private boolean updateList = false; - - public CraftingGridCache( final IGrid grid ) - { - this.grid = grid; - } - - @MENetworkEventSubscribe - public void afterCacheConstruction( final 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(); - } - - final Iterator craftingLinkIterator = this.craftingLinks.values().iterator(); - while( craftingLinkIterator.hasNext() ) - { - if( craftingLinkIterator.next().isDead( this.grid, this ) ) - { - craftingLinkIterator.remove(); - } - } - - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - cpu.updateCraftingLogic( this.grid, this.energyGrid, this ); - } - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ICraftingWatcherHost ) - { - final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( machine ); - if( craftingWatcher != null ) - { - craftingWatcher.clear(); - this.craftingWatchers.remove( machine ); - } - } - - if( machine instanceof ICraftingRequester ) - { - for( final 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( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ICraftingWatcherHost ) - { - final ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; - final CraftingWatcher watcher = new CraftingWatcher( this, watcherHost ); - this.craftingWatchers.put( gridNode, watcher ); - watcherHost.updateWatcher( watcher ); - } - - if( machine instanceof ICraftingRequester ) - { - for( final 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( final IGridStorage destinationStorage ) - { // nothing! - } - - @Override - public void onJoin( final IGridStorage sourceStorage ) - { - // nothing! - } - - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { - // nothing! - } - - private void updatePatterns() - { - final 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( final ICraftingProvider provider : this.craftingProviders ) - { - provider.provideCrafting( this ); - } - - final Map> tmpCraft = new HashMap>(); - - // new craftables! - for( final 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( final 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( final IGridNode cst : this.grid.getMachines( TileCraftingStorageTile.class ) ) - { - final TileCraftingStorageTile tile = (TileCraftingStorageTile) cst.getMachine(); - final CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); - if( cluster != null ) - { - this.craftingCPUClusters.add( cluster ); - - if( cluster.getLastCraftingLink() != null ) - { - this.addLink( (CraftingLink) cluster.getLastCraftingLink() ); - } - } - } - } - - public void addLink( final 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( final MENetworkCraftingCpuChange c ) - { - this.updateList = true; - } - - @MENetworkEventSubscribe - public void updateCPUClusters( final MENetworkCraftingPatternChange c ) - { - this.updatePatterns(); - } - - @Override - public void addCraftingOption( final ICraftingMedium medium, final 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( final IAEItemStack someItem ) - { - this.emitableItems.add( someItem.copy() ); - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - final 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( final IAEStack input ) - { - return true; - } - - @Override - public boolean canAccept( final IAEStack input ) - { - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - if( cpu.canAccept( input ) ) - { - return true; - } - } - - return false; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 1; - } - - @Override - public IAEStack injectItems( IAEStack input, final Actionable type, final BaseActionSource src ) - { - for( final CraftingCPUCluster cpu : this.craftingCPUClusters ) - { - input = cpu.injectItems( input, type, src ); - } - - return input; - } - - @Override - public IAEStack extractItems( final IAEStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - // add craftable items! - for( final IAEItemStack stack : this.craftableItems.keySet() ) - { - out.addCrafting( stack ); - } - - for( final IAEItemStack st : this.emitableItems ) - { - out.addCrafting( st ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public ImmutableCollection getCraftingFor( final IAEItemStack whatToCraft, final ICraftingPatternDetails details, final int slotIndex, final World world ) - { - final ImmutableList res = this.craftableItems.get( whatToCraft ); - - if( res == null ) - { - if( details != null && details.isCraftable() ) - { - for( final 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( final World world, final IGrid grid, final BaseActionSource actionSrc, final IAEItemStack slotItem, final ICraftingCallback cb ) - { - if( world == null || grid == null || actionSrc == null || slotItem == null ) - { - throw new IllegalArgumentException( "Invalid Crafting Job Request" ); - } - - final CraftingJob job = new CraftingJob( world, grid, actionSrc, slotItem, cb ); - - return CRAFTING_POOL.submit( job, (ICraftingJob) job ); - } - - @Override - public ICraftingLink submitJob( final ICraftingJob job, final ICraftingRequester requestingMachine, final ICraftingCPU target, final boolean prioritizePower, final BaseActionSource src ) - { - if( job.isSimulation() ) - { - return null; - } - - CraftingCPUCluster cpuCluster = null; - - if( target instanceof CraftingCPUCluster ) - { - cpuCluster = (CraftingCPUCluster) target; - } - - if( target == null ) - { - final List validCpusClusters = new ArrayList(); - for( final 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( final CraftingCPUCluster firstCluster, final CraftingCPUCluster nextCluster ) - { - if( prioritizePower ) - { - final int comparison = ItemSorters.compareLong( nextCluster.getCoProcessors(), firstCluster.getCoProcessors() ); - if( comparison != 0 ) - { - return comparison; - } - return ItemSorters.compareLong( nextCluster.getAvailableStorage(), firstCluster.getAvailableStorage() ); - } - - final 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( final IAEItemStack someItem ) - { - return this.emitableItems.contains( someItem ); - } - - @Override - public boolean isRequesting( final IAEItemStack what ) - { - for( final CraftingCPUCluster cluster : this.craftingCPUClusters ) - { - if( cluster.isMaking( what ) ) - { - return true; - } - } - - return false; - } - - public List getMediums( final ICraftingPatternDetails key ) - { - List mediums = this.craftingMethods.get( key ); - - if( mediums == null ) - { - mediums = ImmutableList.of(); - } - - return mediums; - } - - public boolean hasCpu( final ICraftingCPU cpu ) - { - return this.craftingCPUClusters.contains( cpu ); - } - - public GenericInterestManager getInterestManager() - { - return this.interestManager; - } - - private static class ActiveCpuIterator implements Iterator - { - - private final Iterator iterator; - private CraftingCPUCluster cpuCluster; - - public ActiveCpuIterator( final Collection o ) - { - this.iterator = o.iterator(); - this.cpuCluster = null; - } - - @Override - public boolean hasNext() - { - this.findNext(); - - return this.cpuCluster != null; - } - - private void findNext() - { - while( this.iterator.hasNext() && this.cpuCluster == null ) - { - this.cpuCluster = this.iterator.next(); - if( !this.cpuCluster.isActive() || this.cpuCluster.isDestroyed() ) - { - this.cpuCluster = null; - } - } - } - - @Override - public ICraftingCPU next() - { - final ICraftingCPU o = this.cpuCluster; - this.cpuCluster = null; - - return o; - } - - @Override - public void remove() - { - // no.. - } - } +public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper, + ICellProvider, IMEInventoryHandler { + private static final ExecutorService CRAFTING_POOL; + private static final Comparator COMPARATOR + = new Comparator() { + @Override + public int compare( + final ICraftingPatternDetails firstDetail, + final ICraftingPatternDetails nextDetail + ) { + return nextDetail.getPriority() - firstDetail.getPriority(); + } + }; + + static { + final ThreadFactory factory = new ThreadFactory() { + @Override + public Thread newThread(final 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 final Map> craftingMethods + = new HashMap>(); + private final Map> craftableItems + = new HashMap>(); + private final Set emitableItems = new HashSet(); + private final Map craftingLinks + = new HashMap(); + private final Multimap interests = HashMultimap.create(); + private final GenericInterestManager interestManager + = new GenericInterestManager(this.interests); + private IStorageGrid storageGrid; + private IEnergyGrid energyGrid; + private boolean updateList = false; + + public CraftingGridCache(final IGrid grid) { + this.grid = grid; + } + + @MENetworkEventSubscribe + public void + afterCacheConstruction(final 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(); + } + + final Iterator craftingLinkIterator + = this.craftingLinks.values().iterator(); + while (craftingLinkIterator.hasNext()) { + if (craftingLinkIterator.next().isDead(this.grid, this)) { + craftingLinkIterator.remove(); + } + } + + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + cpu.updateCraftingLogic(this.grid, this.energyGrid, this); + } + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ICraftingWatcherHost) { + final ICraftingWatcher craftingWatcher = this.craftingWatchers.get(machine); + if (craftingWatcher != null) { + craftingWatcher.clear(); + this.craftingWatchers.remove(machine); + } + } + + if (machine instanceof ICraftingRequester) { + for (final 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(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ICraftingWatcherHost) { + final ICraftingWatcherHost watcherHost = (ICraftingWatcherHost) machine; + final CraftingWatcher watcher = new CraftingWatcher(this, watcherHost); + this.craftingWatchers.put(gridNode, watcher); + watcherHost.updateWatcher(watcher); + } + + if (machine instanceof ICraftingRequester) { + for (final 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(final IGridStorage destinationStorage) { // nothing! + } + + @Override + public void onJoin(final IGridStorage sourceStorage) { + // nothing! + } + + @Override + public void populateGridStorage(final IGridStorage destinationStorage) { + // nothing! + } + + private void updatePatterns() { + final 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 (final ICraftingProvider provider : this.craftingProviders) { + provider.provideCrafting(this); + } + + final Map> tmpCraft + = new HashMap>(); + + // new craftables! + for (final 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 (final 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 (final IGridNode cst : this.grid.getMachines(TileCraftingStorageTile.class)) { + final TileCraftingStorageTile tile + = (TileCraftingStorageTile) cst.getMachine(); + final CraftingCPUCluster cluster = (CraftingCPUCluster) tile.getCluster(); + if (cluster != null) { + this.craftingCPUClusters.add(cluster); + + if (cluster.getLastCraftingLink() != null) { + this.addLink((CraftingLink) cluster.getLastCraftingLink()); + } + } + } + } + + public void addLink(final 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(final MENetworkCraftingCpuChange c) { + this.updateList = true; + } + + @MENetworkEventSubscribe + public void updateCPUClusters(final MENetworkCraftingPatternChange c) { + this.updatePatterns(); + } + + @Override + public void + addCraftingOption(final ICraftingMedium medium, final 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(final IAEItemStack someItem) { + this.emitableItems.add(someItem.copy()); + } + + @Override + public List getCellArray(final StorageChannel channel) { + final 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(final IAEStack input) { + return true; + } + + @Override + public boolean canAccept(final IAEStack input) { + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + if (cpu.canAccept(input)) { + return true; + } + } + + return false; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public boolean validForPass(final int i) { + return i == 1; + } + + @Override + public IAEStack + injectItems(IAEStack input, final Actionable type, final BaseActionSource src) { + for (final CraftingCPUCluster cpu : this.craftingCPUClusters) { + input = cpu.injectItems(input, type, src); + } + + return input; + } + + @Override + public IAEStack extractItems( + final IAEStack request, final Actionable mode, final BaseActionSource src + ) { + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + // add craftable items! + for (final IAEItemStack stack : this.craftableItems.keySet()) { + out.addCrafting(stack); + } + + for (final IAEItemStack st : this.emitableItems) { + out.addCrafting(st); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public ImmutableCollection getCraftingFor( + final IAEItemStack whatToCraft, + final ICraftingPatternDetails details, + final int slotIndex, + final World world + ) { + final ImmutableList res + = this.craftableItems.get(whatToCraft); + + if (res == null) { + if (details != null && details.isCraftable()) { + for (final 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( + final World world, + final IGrid grid, + final BaseActionSource actionSrc, + final IAEItemStack slotItem, + final ICraftingCallback cb + ) { + if (world == null || grid == null || actionSrc == null || slotItem == null) { + throw new IllegalArgumentException("Invalid Crafting Job Request"); + } + + final CraftingJob job = new CraftingJob(world, grid, actionSrc, slotItem, cb); + + return CRAFTING_POOL.submit(job, (ICraftingJob) job); + } + + @Override + public ICraftingLink submitJob( + final ICraftingJob job, + final ICraftingRequester requestingMachine, + final ICraftingCPU target, + final boolean prioritizePower, + final BaseActionSource src + ) { + if (job.isSimulation()) { + return null; + } + + CraftingCPUCluster cpuCluster = null; + + if (target instanceof CraftingCPUCluster) { + cpuCluster = (CraftingCPUCluster) target; + } + + if (target == null) { + final List validCpusClusters + = new ArrayList(); + for (final 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( + final CraftingCPUCluster firstCluster, + final CraftingCPUCluster nextCluster + ) { + if (prioritizePower) { + final int comparison = ItemSorters.compareLong( + nextCluster.getCoProcessors(), firstCluster.getCoProcessors() + ); + if (comparison != 0) { + return comparison; + } + return ItemSorters.compareLong( + nextCluster.getAvailableStorage(), + firstCluster.getAvailableStorage() + ); + } + + final 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(final IAEItemStack someItem) { + return this.emitableItems.contains(someItem); + } + + @Override + public boolean isRequesting(final IAEItemStack what) { + for (final CraftingCPUCluster cluster : this.craftingCPUClusters) { + if (cluster.isMaking(what)) { + return true; + } + } + + return false; + } + + public List getMediums(final ICraftingPatternDetails key) { + List mediums = this.craftingMethods.get(key); + + if (mediums == null) { + mediums = ImmutableList.of(); + } + + return mediums; + } + + public boolean hasCpu(final ICraftingCPU cpu) { + return this.craftingCPUClusters.contains(cpu); + } + + public GenericInterestManager getInterestManager() { + return this.interestManager; + } + + private static class ActiveCpuIterator implements Iterator { + private final Iterator iterator; + private CraftingCPUCluster cpuCluster; + + public ActiveCpuIterator(final Collection o) { + this.iterator = o.iterator(); + this.cpuCluster = null; + } + + @Override + public boolean hasNext() { + this.findNext(); + + return this.cpuCluster != null; + } + + private void findNext() { + while (this.iterator.hasNext() && this.cpuCluster == null) { + this.cpuCluster = this.iterator.next(); + if (!this.cpuCluster.isActive() || this.cpuCluster.isDestroyed()) { + this.cpuCluster = null; + } + } + } + + @Override + public ICraftingCPU next() { + final ICraftingCPU o = this.cpuCluster; + this.cpuCluster = null; + + return o; + } + + @Override + public void remove() { + // no.. + } + } } diff --git a/src/main/java/appeng/me/cache/EnergyGridCache.java b/src/main/java/appeng/me/cache/EnergyGridCache.java index 2a5cc790..064c0ba5 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.*; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -34,587 +35,512 @@ import appeng.me.energy.EnergyWatcher; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; -import java.util.*; - - -public class EnergyGridCache implements IEnergyGrid -{ - - private final TreeSet interests = new TreeSet(); - private final double AvgLength = 40.0; - private final Set providers = new LinkedHashSet(); - private final Set requesters = new LinkedHashSet(); - private final Multiset energyGridProviders = HashMultiset.create(); - private final IGrid myGrid; - private final HashMap watchers = new HashMap(); - private final Set localSeen = new HashSet(); - /** - * estimated power available. - */ - private int availableTicksSinceUpdate = 0; - private double globalAvailablePower = 0; - private double globalMaxPower = 0; - /** - * idle draw. - */ - private double drainPerTick = 0; - private double avgDrainPerTick = 0; - private double avgInjectionPerTick = 0; - private double tickDrainPerTick = 0; - private double tickInjectionPerTick = 0; - /** - * power status - */ - private boolean publicHasPower = false; - private boolean hasPower = true; - private long ticksSinceHasPowerChange = 900; - /** - * excess power in the system. - */ - private double extra = 0; - private IAEPowerStorage lastProvider; - private IAEPowerStorage lastRequester; - private PathGridCache pgc; - private double lastStoredPower = -1; - - public EnergyGridCache( final IGrid g ) - { - this.myGrid = g; - } - - @MENetworkEventSubscribe - public void postInit( final MENetworkPostCacheConstruction pcc ) - { - this.pgc = this.myGrid.getCache( IPathingGrid.class ); - } - - @MENetworkEventSubscribe - public void EnergyNodeChanges( final MENetworkPowerIdleChange ev ) - { - // update power usage based on event. - final GridNode node = (GridNode) ev.node; - final IGridBlock gb = node.getGridBlock(); - - final double newDraw = gb.getIdlePowerUsage(); - final double diffDraw = newDraw - node.getPreviousDraw(); - node.setPreviousDraw( newDraw ); - - this.drainPerTick += diffDraw; - } - - @MENetworkEventSubscribe - public void EnergyNodeChanges( final MENetworkPowerStorage ev ) - { - if( ev.storage.isAEPublicPowerStorage() ) - { - 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; - } - } - else - { - ( new RuntimeException( "Attempt to ask the IEnergyGrid to charge a non public energy store." ) ).printStackTrace(); - } - } - - @Override - public void onUpdateTick() - { - if( !this.getInterests().isEmpty() ) - { - final double oldPower = this.lastStoredPower; - this.lastStoredPower = this.getStoredPower(); - - final EnergyThreshold low = new EnergyThreshold( Math.min( oldPower, this.lastStoredPower ), null ); - final EnergyThreshold high = new EnergyThreshold( Math.max( oldPower, this.lastStoredPower ), null ); - for( final EnergyThreshold th : this.getInterests().subSet( low, true, high, true ) ) - { - ( (EnergyWatcher) th.getWatcher() ).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 ) - { - final 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 extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - this.localSeen.clear(); - return pm.divide( this.extractAEPower( pm.multiply( amt ), mode, this.localSeen ) ); - } - - @Override - public double getIdlePowerUsage() - { - return this.drainPerTick + this.pgc.getChannelPowerUsage(); - } - - private void publicPowerState( final boolean newState, final 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. - */ - private void refreshPower() - { - this.availableTicksSinceUpdate = 0; - this.globalAvailablePower = 0; - for( final IAEPowerStorage p : this.providers ) - { - this.globalAvailablePower += p.getAECurrentPower(); - } - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final Set seen ) - { - if( !seen.add( this ) ) - { - return 0; - } - - double extractedPower = this.extra; - - if( mode == Actionable.SIMULATE ) - { - extractedPower += this.simulateExtract( extractedPower, amt ); - - if( extractedPower < amt ) - { - final 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 ); - } - - // got more then we wanted? - if( extractedPower > amt ) - { - this.extra = extractedPower - amt; - this.globalAvailablePower -= amt; - - this.tickDrainPerTick += amt; - return amt; - } - - if( extractedPower < amt ) - { - final 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 injectAEPower( double amt, final Actionable mode, final Set seen ) - { - if( !seen.add( this ) ) - { - return 0; - } - - final double ignore = this.extra; - amt += this.extra; - - if( mode == Actionable.SIMULATE ) - { - final Iterator it = this.requesters.iterator(); - while( amt > 0 && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - amt = node.injectAEPower( amt, Actionable.SIMULATE ); - } - - final Iterator i = this.energyGridProviders.iterator(); - while( amt > 0 && i.hasNext() ) - { - amt = i.next().injectAEPower( amt, mode, seen ); - } - } - else - { - this.tickInjectionPerTick += amt - ignore; - // totalInjectionPastTicks[0] += i; - - while( amt > 0 && !this.requesters.isEmpty() ) - { - final IAEPowerStorage node = this.getFirstRequester(); - - amt = node.injectAEPower( amt, Actionable.MODULATE ); - if( amt > 0 ) - { - this.requesters.remove( node ); - this.lastRequester = null; - } - } - - final Iterator i = this.energyGridProviders.iterator(); - while( amt > 0 && i.hasNext() ) - { - final IEnergyGridProvider what = i.next(); - final Set listCopy = new HashSet(); - listCopy.addAll( seen ); - - final double cannotHold = what.injectAEPower( amt, Actionable.SIMULATE, listCopy ); - what.injectAEPower( amt - cannotHold, mode, seen ); - - amt = cannotHold; - } - - this.extra = amt; - } - - return Math.max( 0.0, amt - this.buffer() ); - } - - @Override - public double getEnergyDemand( final double maxRequired, final Set seen ) - { - if( !seen.add( this ) ) - { - return 0; - } - - double required = this.buffer() - this.extra; - - final Iterator it = this.requesters.iterator(); - while( required < maxRequired && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - if( node.getPowerFlow() != AccessRestriction.READ ) - { - required += Math.max( 0.0, node.getAEMaxPower() - node.getAECurrentPower() ); - } - } - - final Iterator ix = this.energyGridProviders.iterator(); - while( required < maxRequired && ix.hasNext() ) - { - final IEnergyGridProvider node = ix.next(); - required += node.getEnergyDemand( maxRequired - required, seen ); - } - - return required; - } - - private double simulateExtract( double extractedPower, final double amt ) - { - final Iterator it = this.providers.iterator(); - - while( extractedPower < amt && it.hasNext() ) - { - final IAEPowerStorage node = it.next(); - - final double req = amt - extractedPower; - final double newPower = node.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.ONE ); - extractedPower += newPower; - } - - return extractedPower; - } - - private double doExtract( double extractedPower, final double amt ) - { - while( extractedPower < amt && !this.providers.isEmpty() ) - { - final IAEPowerStorage node = this.getFirstProvider(); - - final double req = amt - extractedPower; - final 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 IAEPowerStorage getFirstProvider() - { - if( this.lastProvider == null ) - { - final Iterator i = this.providers.iterator(); - this.lastProvider = i.hasNext() ? i.next() : null; - } - - return this.lastProvider; - } - - @Override - public double getAvgPowerUsage() - { - return this.avgDrainPerTick; - } - - @Override - public double getAvgPowerInjection() - { - return this.avgInjectionPerTick; - } - - @Override - public boolean isNetworkPowered() - { - return this.publicHasPower; - } - - @Override - public double injectPower( final double amt, final Actionable mode ) - { - this.localSeen.clear(); - return this.injectAEPower( amt, mode, this.localSeen ); - } - - private IAEPowerStorage getFirstRequester() - { - if( this.lastRequester == null ) - { - final 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( final double maxRequired ) - { - this.localSeen.clear(); - return this.getEnergyDemand( maxRequired, this.localSeen ); - } - - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof IEnergyGridProvider ) - { - this.energyGridProviders.remove( machine ); - } - - // idle draw. - final GridNode gridNode = (GridNode) node; - this.drainPerTick -= gridNode.getPreviousDraw(); - - // power storage. - if( machine instanceof IAEPowerStorage ) - { - final 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 ) - { - final IEnergyWatcher myWatcher = this.watchers.get( machine ); - if( myWatcher != null ) - { - myWatcher.clear(); - this.watchers.remove( machine ); - } - } - } - - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof IEnergyGridProvider ) - { - this.energyGridProviders.add( (IEnergyGridProvider) machine ); - } - - // idle draw... - final GridNode gridNode = (GridNode) node; - final IGridBlock gb = gridNode.getGridBlock(); - gridNode.setPreviousDraw( gb.getIdlePowerUsage() ); - this.drainPerTick += gridNode.getPreviousDraw(); - - // power storage - if( machine instanceof IAEPowerStorage ) - { - final IAEPowerStorage ps = (IAEPowerStorage) machine; - if( ps.isAEPublicPowerStorage() ) - { - final double max = ps.getAEMaxPower(); - final 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 ) - { - final IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; - final EnergyWatcher iw = new EnergyWatcher( this, swh ); - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - - this.myGrid.postEventTo( node, new MENetworkPowerStatusChange() ); - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - this.extra /= 2; - storageB.dataObject().setDouble( "extraEnergy", this.extra ); - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - this.extra += storageB.dataObject().getDouble( "extraEnergy" ); - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - storage.dataObject().setDouble( "extraEnergy", this.extra ); - } - - public TreeSet getInterests() - { - return this.interests; - } +public class EnergyGridCache implements IEnergyGrid { + private final TreeSet interests = new TreeSet(); + private final double AvgLength = 40.0; + private final Set providers = new LinkedHashSet(); + private final Set requesters = new LinkedHashSet(); + private final Multiset energyGridProviders + = HashMultiset.create(); + private final IGrid myGrid; + private final HashMap watchers + = new HashMap(); + private final Set localSeen = new HashSet(); + /** + * estimated power available. + */ + private int availableTicksSinceUpdate = 0; + private double globalAvailablePower = 0; + private double globalMaxPower = 0; + /** + * idle draw. + */ + private double drainPerTick = 0; + private double avgDrainPerTick = 0; + private double avgInjectionPerTick = 0; + private double tickDrainPerTick = 0; + private double tickInjectionPerTick = 0; + /** + * power status + */ + private boolean publicHasPower = false; + private boolean hasPower = true; + private long ticksSinceHasPowerChange = 900; + /** + * excess power in the system. + */ + private double extra = 0; + private IAEPowerStorage lastProvider; + private IAEPowerStorage lastRequester; + private PathGridCache pgc; + private double lastStoredPower = -1; + + public EnergyGridCache(final IGrid g) { + this.myGrid = g; + } + + @MENetworkEventSubscribe + public void postInit(final MENetworkPostCacheConstruction pcc) { + this.pgc = this.myGrid.getCache(IPathingGrid.class); + } + + @MENetworkEventSubscribe + public void EnergyNodeChanges(final MENetworkPowerIdleChange ev) { + // update power usage based on event. + final GridNode node = (GridNode) ev.node; + final IGridBlock gb = node.getGridBlock(); + + final double newDraw = gb.getIdlePowerUsage(); + final double diffDraw = newDraw - node.getPreviousDraw(); + node.setPreviousDraw(newDraw); + + this.drainPerTick += diffDraw; + } + + @MENetworkEventSubscribe + public void EnergyNodeChanges(final MENetworkPowerStorage ev) { + if (ev.storage.isAEPublicPowerStorage()) { + 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; + } + } else { + (new RuntimeException( + "Attempt to ask the IEnergyGrid to charge a non public energy store." + )) + .printStackTrace(); + } + } + + @Override + public void onUpdateTick() { + if (!this.getInterests().isEmpty()) { + final double oldPower = this.lastStoredPower; + this.lastStoredPower = this.getStoredPower(); + + final EnergyThreshold low + = new EnergyThreshold(Math.min(oldPower, this.lastStoredPower), null); + final EnergyThreshold high + = new EnergyThreshold(Math.max(oldPower, this.lastStoredPower), null); + for (final EnergyThreshold th : + this.getInterests().subSet(low, true, high, true)) { + ((EnergyWatcher) th.getWatcher()).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) { + final 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 + extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + this.localSeen.clear(); + return pm.divide(this.extractAEPower(pm.multiply(amt), mode, this.localSeen)); + } + + @Override + public double getIdlePowerUsage() { + return this.drainPerTick + this.pgc.getChannelPowerUsage(); + } + + private void publicPowerState(final boolean newState, final 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. + */ + private void refreshPower() { + this.availableTicksSinceUpdate = 0; + this.globalAvailablePower = 0; + for (final IAEPowerStorage p : this.providers) { + this.globalAvailablePower += p.getAECurrentPower(); + } + } + + @Override + public double + extractAEPower(final double amt, final Actionable mode, final Set seen) { + if (!seen.add(this)) { + return 0; + } + + double extractedPower = this.extra; + + if (mode == Actionable.SIMULATE) { + extractedPower += this.simulateExtract(extractedPower, amt); + + if (extractedPower < amt) { + final 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); + } + + // got more then we wanted? + if (extractedPower > amt) { + this.extra = extractedPower - amt; + this.globalAvailablePower -= amt; + + this.tickDrainPerTick += amt; + return amt; + } + + if (extractedPower < amt) { + final 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 + injectAEPower(double amt, final Actionable mode, final Set seen) { + if (!seen.add(this)) { + return 0; + } + + final double ignore = this.extra; + amt += this.extra; + + if (mode == Actionable.SIMULATE) { + final Iterator it = this.requesters.iterator(); + while (amt > 0 && it.hasNext()) { + final IAEPowerStorage node = it.next(); + amt = node.injectAEPower(amt, Actionable.SIMULATE); + } + + final Iterator i = this.energyGridProviders.iterator(); + while (amt > 0 && i.hasNext()) { + amt = i.next().injectAEPower(amt, mode, seen); + } + } else { + this.tickInjectionPerTick += amt - ignore; + // totalInjectionPastTicks[0] += i; + + while (amt > 0 && !this.requesters.isEmpty()) { + final IAEPowerStorage node = this.getFirstRequester(); + + amt = node.injectAEPower(amt, Actionable.MODULATE); + if (amt > 0) { + this.requesters.remove(node); + this.lastRequester = null; + } + } + + final Iterator i = this.energyGridProviders.iterator(); + while (amt > 0 && i.hasNext()) { + final IEnergyGridProvider what = i.next(); + final Set listCopy = new HashSet(); + listCopy.addAll(seen); + + final double cannotHold + = what.injectAEPower(amt, Actionable.SIMULATE, listCopy); + what.injectAEPower(amt - cannotHold, mode, seen); + + amt = cannotHold; + } + + this.extra = amt; + } + + return Math.max(0.0, amt - this.buffer()); + } + + @Override + public double getEnergyDemand(final double maxRequired, final Set seen) { + if (!seen.add(this)) { + return 0; + } + + double required = this.buffer() - this.extra; + + final Iterator it = this.requesters.iterator(); + while (required < maxRequired && it.hasNext()) { + final IAEPowerStorage node = it.next(); + if (node.getPowerFlow() != AccessRestriction.READ) { + required + += Math.max(0.0, node.getAEMaxPower() - node.getAECurrentPower()); + } + } + + final Iterator ix = this.energyGridProviders.iterator(); + while (required < maxRequired && ix.hasNext()) { + final IEnergyGridProvider node = ix.next(); + required += node.getEnergyDemand(maxRequired - required, seen); + } + + return required; + } + + private double simulateExtract(double extractedPower, final double amt) { + final Iterator it = this.providers.iterator(); + + while (extractedPower < amt && it.hasNext()) { + final IAEPowerStorage node = it.next(); + + final double req = amt - extractedPower; + final double newPower + = node.extractAEPower(req, Actionable.SIMULATE, PowerMultiplier.ONE); + extractedPower += newPower; + } + + return extractedPower; + } + + private double doExtract(double extractedPower, final double amt) { + while (extractedPower < amt && !this.providers.isEmpty()) { + final IAEPowerStorage node = this.getFirstProvider(); + + final double req = amt - extractedPower; + final 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 IAEPowerStorage getFirstProvider() { + if (this.lastProvider == null) { + final Iterator i = this.providers.iterator(); + this.lastProvider = i.hasNext() ? i.next() : null; + } + + return this.lastProvider; + } + + @Override + public double getAvgPowerUsage() { + return this.avgDrainPerTick; + } + + @Override + public double getAvgPowerInjection() { + return this.avgInjectionPerTick; + } + + @Override + public boolean isNetworkPowered() { + return this.publicHasPower; + } + + @Override + public double injectPower(final double amt, final Actionable mode) { + this.localSeen.clear(); + return this.injectAEPower(amt, mode, this.localSeen); + } + + private IAEPowerStorage getFirstRequester() { + if (this.lastRequester == null) { + final 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(final double maxRequired) { + this.localSeen.clear(); + return this.getEnergyDemand(maxRequired, this.localSeen); + } + + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof IEnergyGridProvider) { + this.energyGridProviders.remove(machine); + } + + // idle draw. + final GridNode gridNode = (GridNode) node; + this.drainPerTick -= gridNode.getPreviousDraw(); + + // power storage. + if (machine instanceof IAEPowerStorage) { + final 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) { + final IEnergyWatcher myWatcher = this.watchers.get(machine); + if (myWatcher != null) { + myWatcher.clear(); + this.watchers.remove(machine); + } + } + } + + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof IEnergyGridProvider) { + this.energyGridProviders.add((IEnergyGridProvider) machine); + } + + // idle draw... + final GridNode gridNode = (GridNode) node; + final IGridBlock gb = gridNode.getGridBlock(); + gridNode.setPreviousDraw(gb.getIdlePowerUsage()); + this.drainPerTick += gridNode.getPreviousDraw(); + + // power storage + if (machine instanceof IAEPowerStorage) { + final IAEPowerStorage ps = (IAEPowerStorage) machine; + if (ps.isAEPublicPowerStorage()) { + final double max = ps.getAEMaxPower(); + final 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) { + final IEnergyWatcherHost swh = (IEnergyWatcherHost) machine; + final EnergyWatcher iw = new EnergyWatcher(this, swh); + this.watchers.put(node, iw); + swh.updateWatcher(iw); + } + + this.myGrid.postEventTo(node, new MENetworkPowerStatusChange()); + } + + @Override + public void onSplit(final IGridStorage storageB) { + this.extra /= 2; + storageB.dataObject().setDouble("extraEnergy", this.extra); + } + + @Override + public void onJoin(final IGridStorage storageB) { + this.extra += storageB.dataObject().getDouble("extraEnergy"); + } + + @Override + public void populateGridStorage(final IGridStorage storage) { + storage.dataObject().setDouble("extraEnergy", this.extra); + } + + public TreeSet getInterests() { + return this.interests; + } } diff --git a/src/main/java/appeng/me/cache/GridStorageCache.java b/src/main/java/appeng/me/cache/GridStorageCache.java index 722a2fbe..503781a8 100644 --- a/src/main/java/appeng/me/cache/GridStorageCache.java +++ b/src/main/java/appeng/me/cache/GridStorageCache.java @@ -18,6 +18,10 @@ package appeng.me.cache; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import appeng.api.AEApi; import appeng.api.networking.IGrid; @@ -44,366 +48,331 @@ import appeng.me.storage.NetworkInventoryHandler; import com.google.common.collect.HashMultimap; import com.google.common.collect.SetMultimap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; +public class GridStorageCache implements IStorageGrid { + private final IGrid myGrid; + private final HashSet activeCellProviders + = new HashSet(); + private final HashSet inactiveCellProviders + = new HashSet(); + private final SetMultimap interests = HashMultimap.create(); + private final GenericInterestManager interestManager + = new GenericInterestManager(this.interests); + private final NetworkMonitor itemMonitor + = new NetworkMonitor(this, StorageChannel.ITEMS); + private final NetworkMonitor fluidMonitor + = new NetworkMonitor(this, StorageChannel.FLUIDS); + private final HashMap watchers + = new HashMap(); + private NetworkInventoryHandler myItemNetwork; + private NetworkInventoryHandler myFluidNetwork; + public GridStorageCache(final IGrid g) { + this.myGrid = g; + } -public class GridStorageCache implements IStorageGrid -{ + @Override + public void onUpdateTick() { + this.itemMonitor.onTick(); + this.fluidMonitor.onTick(); + } - private final IGrid myGrid; - private final HashSet activeCellProviders = new HashSet(); - private final HashSet inactiveCellProviders = new HashSet(); - private final SetMultimap interests = HashMultimap.create(); - private final GenericInterestManager interestManager = new GenericInterestManager( this.interests ); - private final NetworkMonitor itemMonitor = new NetworkMonitor( this, StorageChannel.ITEMS ); - private final NetworkMonitor fluidMonitor = new NetworkMonitor( this, StorageChannel.FLUIDS ); - private final HashMap watchers = new HashMap(); - private NetworkInventoryHandler myItemNetwork; - private NetworkInventoryHandler myFluidNetwork; + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof ICellContainer) { + final ICellContainer cc = (ICellContainer) machine; + final CellChangeTracker tracker = new CellChangeTracker(); - public GridStorageCache( final IGrid g ) - { - this.myGrid = g; - } + this.removeCellProvider(cc, tracker); + this.inactiveCellProviders.remove(cc); + this.getGrid().postEvent(new MENetworkCellArrayUpdate()); - @Override - public void onUpdateTick() - { - this.itemMonitor.onTick(); - this.fluidMonitor.onTick(); - } + tracker.applyChanges(); + } - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof ICellContainer ) - { - final ICellContainer cc = (ICellContainer) machine; - final CellChangeTracker tracker = new CellChangeTracker(); + if (machine instanceof IStackWatcherHost) { + final IStackWatcher myWatcher = this.watchers.get(machine); - this.removeCellProvider( cc, tracker ); - this.inactiveCellProviders.remove( cc ); - this.getGrid().postEvent( new MENetworkCellArrayUpdate() ); + if (myWatcher != null) { + myWatcher.clear(); + this.watchers.remove(machine); + } + } + } - tracker.applyChanges(); - } + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof ICellContainer) { + final ICellContainer cc = (ICellContainer) machine; + this.inactiveCellProviders.add(cc); - if( machine instanceof IStackWatcherHost ) - { - final IStackWatcher myWatcher = this.watchers.get( machine ); + this.getGrid().postEvent(new MENetworkCellArrayUpdate()); - if( myWatcher != null ) - { - myWatcher.clear(); - this.watchers.remove( machine ); - } - } - } + if (node.isActive()) { + final CellChangeTracker tracker = new CellChangeTracker(); - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof ICellContainer ) - { - final ICellContainer cc = (ICellContainer) machine; - this.inactiveCellProviders.add( cc ); + this.addCellProvider(cc, tracker); + tracker.applyChanges(); + } + } - this.getGrid().postEvent( new MENetworkCellArrayUpdate() ); + if (machine instanceof IStackWatcherHost) { + final IStackWatcherHost swh = (IStackWatcherHost) machine; + final ItemWatcher iw = new ItemWatcher(this, swh); + this.watchers.put(node, iw); + swh.updateWatcher(iw); + } + } - if( node.isActive() ) - { - final CellChangeTracker tracker = new CellChangeTracker(); + @Override + public void onSplit(final IGridStorage storageB) {} - this.addCellProvider( cc, tracker ); - tracker.applyChanges(); - } - } + @Override + public void onJoin(final IGridStorage storageB) {} - if( machine instanceof IStackWatcherHost ) - { - final IStackWatcherHost swh = (IStackWatcherHost) machine; - final ItemWatcher iw = new ItemWatcher( this, swh ); - this.watchers.put( node, iw ); - swh.updateWatcher( iw ); - } - } + @Override + public void populateGridStorage(final IGridStorage storage) {} - @Override - public void onSplit( final IGridStorage storageB ) - { + private CellChangeTracker + addCellProvider(final ICellProvider cc, final CellChangeTracker tracker) { + if (this.inactiveCellProviders.contains(cc)) { + this.inactiveCellProviders.remove(cc); + this.activeCellProviders.add(cc); - } + BaseActionSource actionSrc = new BaseActionSource(); + if (cc instanceof IActionHost) { + actionSrc = new MachineSource((IActionHost) cc); + } - @Override - public void onJoin( final IGridStorage storageB ) - { + for (final IMEInventoryHandler h : + cc.getCellArray(StorageChannel.ITEMS)) { + tracker.postChanges(StorageChannel.ITEMS, 1, h, actionSrc); + } - } + for (final IMEInventoryHandler h : + cc.getCellArray(StorageChannel.FLUIDS)) { + tracker.postChanges(StorageChannel.FLUIDS, 1, h, actionSrc); + } + } - @Override - public void populateGridStorage( final IGridStorage storage ) - { + return tracker; + } - } + private CellChangeTracker + removeCellProvider(final ICellProvider cc, final CellChangeTracker tracker) { + if (this.activeCellProviders.contains(cc)) { + this.activeCellProviders.remove(cc); + this.inactiveCellProviders.add(cc); - private CellChangeTracker addCellProvider( final ICellProvider cc, final CellChangeTracker tracker ) - { - if( this.inactiveCellProviders.contains( cc ) ) - { - this.inactiveCellProviders.remove( cc ); - this.activeCellProviders.add( cc ); + BaseActionSource actionSrc = new BaseActionSource(); - BaseActionSource actionSrc = new BaseActionSource(); - if( cc instanceof IActionHost ) - { - actionSrc = new MachineSource( (IActionHost) cc ); - } + if (cc instanceof IActionHost) { + actionSrc = new MachineSource((IActionHost) cc); + } - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS ) ) - { - tracker.postChanges( StorageChannel.ITEMS, 1, h, actionSrc ); - } + for (final IMEInventoryHandler h : + cc.getCellArray(StorageChannel.ITEMS)) { + tracker.postChanges(StorageChannel.ITEMS, -1, h, actionSrc); + } - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS ) ) - { - tracker.postChanges( StorageChannel.FLUIDS, 1, h, actionSrc ); - } - } + for (final IMEInventoryHandler h : + cc.getCellArray(StorageChannel.FLUIDS)) { + tracker.postChanges(StorageChannel.FLUIDS, -1, h, actionSrc); + } + } - return tracker; - } + return tracker; + } - private CellChangeTracker removeCellProvider( final ICellProvider cc, final CellChangeTracker tracker ) - { - if( this.activeCellProviders.contains( cc ) ) - { - this.activeCellProviders.remove( cc ); - this.inactiveCellProviders.add( cc ); + @MENetworkEventSubscribe + public void cellUpdate(final MENetworkCellArrayUpdate ev) { + this.myItemNetwork = null; + this.myFluidNetwork = null; - BaseActionSource actionSrc = new BaseActionSource(); + final LinkedList ll = new LinkedList(); + ll.addAll(this.inactiveCellProviders); + ll.addAll(this.activeCellProviders); - if( cc instanceof IActionHost ) - { - actionSrc = new MachineSource( (IActionHost) cc ); - } + final CellChangeTracker tracker = new CellChangeTracker(); - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.ITEMS ) ) - { - tracker.postChanges( StorageChannel.ITEMS, -1, h, actionSrc ); - } + for (final ICellProvider cc : ll) { + boolean active = true; - for( final IMEInventoryHandler h : cc.getCellArray( StorageChannel.FLUIDS ) ) - { - tracker.postChanges( StorageChannel.FLUIDS, -1, h, actionSrc ); - } - } + if (cc instanceof IActionHost) { + final IGridNode node = ((IActionHost) cc).getActionableNode(); + active = node != null && node.isActive(); + } - return tracker; - } + if (active) { + this.addCellProvider(cc, tracker); + } else { + this.removeCellProvider(cc, tracker); + } + } - @MENetworkEventSubscribe - public void cellUpdate( final MENetworkCellArrayUpdate ev ) - { - this.myItemNetwork = null; - this.myFluidNetwork = null; + this.itemMonitor.forceUpdate(); + this.fluidMonitor.forceUpdate(); - final LinkedList ll = new LinkedList(); - ll.addAll( this.inactiveCellProviders ); - ll.addAll( this.activeCellProviders ); + tracker.applyChanges(); + } - final CellChangeTracker tracker = new CellChangeTracker(); + private void postChangesToNetwork( + final StorageChannel chan, + final int upOrDown, + final IItemList availableItems, + final BaseActionSource src + ) { + switch (chan) { + case FLUIDS: + this.fluidMonitor.postChange(upOrDown > 0, availableItems, src); + break; + case ITEMS: + this.itemMonitor.postChange(upOrDown > 0, availableItems, src); + break; + default: + } + } - for( final ICellProvider cc : ll ) - { - boolean active = true; + IMEInventoryHandler getItemInventoryHandler() { + if (this.myItemNetwork == null) { + this.buildNetworkStorage(StorageChannel.ITEMS); + } + return this.myItemNetwork; + } - if( cc instanceof IActionHost ) - { - final IGridNode node = ( (IActionHost) cc ).getActionableNode(); - active = node != null && node.isActive(); - } + private void buildNetworkStorage(final StorageChannel chan) { + final SecurityCache security = this.getGrid().getCache(ISecurityGrid.class); - if( active ) - { - this.addCellProvider( cc, tracker ); - } - else - { - this.removeCellProvider( cc, tracker ); - } - } + switch (chan) { + case FLUIDS: + this.myFluidNetwork = new NetworkInventoryHandler( + StorageChannel.FLUIDS, security + ); + for (final ICellProvider cc : this.activeCellProviders) { + for (final IMEInventoryHandler h : + cc.getCellArray(chan)) { + this.myFluidNetwork.addNewStorage(h); + } + } + break; + case ITEMS: + this.myItemNetwork = new NetworkInventoryHandler( + StorageChannel.ITEMS, security + ); + for (final ICellProvider cc : this.activeCellProviders) { + for (final IMEInventoryHandler h : + cc.getCellArray(chan)) { + this.myItemNetwork.addNewStorage(h); + } + } + break; + default: + } + } - this.itemMonitor.forceUpdate(); - this.fluidMonitor.forceUpdate(); + IMEInventoryHandler getFluidInventoryHandler() { + if (this.myFluidNetwork == null) { + this.buildNetworkStorage(StorageChannel.FLUIDS); + } + return this.myFluidNetwork; + } - tracker.applyChanges(); - } + @Override + public void postAlterationOfStoredItems( + final StorageChannel chan, + final Iterable input, + final BaseActionSource src + ) { + if (chan == StorageChannel.ITEMS) { + this.itemMonitor.postChange(true, (Iterable) input, src); + } else if (chan == StorageChannel.FLUIDS) { + this.fluidMonitor.postChange(true, (Iterable) input, src); + } + } - private void postChangesToNetwork( final StorageChannel chan, final int upOrDown, final IItemList availableItems, final BaseActionSource src ) - { - switch( chan ) - { - case FLUIDS: - this.fluidMonitor.postChange( upOrDown > 0, availableItems, src ); - break; - case ITEMS: - this.itemMonitor.postChange( upOrDown > 0, availableItems, src ); - break; - default: - } - } + @Override + public void registerCellProvider(final ICellProvider provider) { + this.inactiveCellProviders.add(provider); + this.addCellProvider(provider, new CellChangeTracker()).applyChanges(); + } - IMEInventoryHandler getItemInventoryHandler() - { - if( this.myItemNetwork == null ) - { - this.buildNetworkStorage( StorageChannel.ITEMS ); - } - return this.myItemNetwork; - } + @Override + public void unregisterCellProvider(final ICellProvider provider) { + this.removeCellProvider(provider, new CellChangeTracker()).applyChanges(); + this.inactiveCellProviders.remove(provider); + } - private void buildNetworkStorage( final StorageChannel chan ) - { - final SecurityCache security = this.getGrid().getCache( ISecurityGrid.class ); + @Override + public IMEMonitor getItemInventory() { + return this.itemMonitor; + } - switch( chan ) - { - case FLUIDS: - this.myFluidNetwork = new NetworkInventoryHandler( StorageChannel.FLUIDS, security ); - for( final ICellProvider cc : this.activeCellProviders ) - { - for( final IMEInventoryHandler h : cc.getCellArray( chan ) ) - { - this.myFluidNetwork.addNewStorage( h ); - } - } - break; - case ITEMS: - this.myItemNetwork = new NetworkInventoryHandler( StorageChannel.ITEMS, security ); - for( final ICellProvider cc : this.activeCellProviders ) - { - for( final IMEInventoryHandler h : cc.getCellArray( chan ) ) - { - this.myItemNetwork.addNewStorage( h ); - } - } - break; - default: - } - } + @Override + public IMEMonitor getFluidInventory() { + return this.fluidMonitor; + } - IMEInventoryHandler getFluidInventoryHandler() - { - if( this.myFluidNetwork == null ) - { - this.buildNetworkStorage( StorageChannel.FLUIDS ); - } - return this.myFluidNetwork; - } + public GenericInterestManager getInterestManager() { + return this.interestManager; + } - @Override - public void postAlterationOfStoredItems( final StorageChannel chan, final Iterable input, final BaseActionSource src ) - { - if( chan == StorageChannel.ITEMS ) - { - this.itemMonitor.postChange( true, (Iterable) input, src ); - } - else if( chan == StorageChannel.FLUIDS ) - { - this.fluidMonitor.postChange( true, (Iterable) input, src ); - } - } + IGrid getGrid() { + return this.myGrid; + } - @Override - public void registerCellProvider( final ICellProvider provider ) - { - this.inactiveCellProviders.add( provider ); - this.addCellProvider( provider, new CellChangeTracker() ).applyChanges(); - } + private class CellChangeTrackerRecord { + final StorageChannel channel; + final int up_or_down; + final IItemList list; + final BaseActionSource src; - @Override - public void unregisterCellProvider( final ICellProvider provider ) - { - this.removeCellProvider( provider, new CellChangeTracker() ).applyChanges(); - this.inactiveCellProviders.remove( provider ); - } + public CellChangeTrackerRecord( + final StorageChannel channel, + final int i, + final IMEInventoryHandler h, + final BaseActionSource actionSrc + ) { + this.channel = channel; + this.up_or_down = i; + this.src = actionSrc; - @Override - public IMEMonitor getItemInventory() - { - return this.itemMonitor; - } + 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; + } + } - @Override - public IMEMonitor getFluidInventory() - { - return this.fluidMonitor; - } + public void applyChanges() { + GridStorageCache.this.postChangesToNetwork( + this.channel, this.up_or_down, this.list, this.src + ); + } + } - public GenericInterestManager getInterestManager() - { - return this.interestManager; - } + private class CellChangeTracker { + final List data + = new LinkedList(); - IGrid getGrid() - { - return this.myGrid; - } + public void postChanges( + final StorageChannel channel, + final int i, + final IMEInventoryHandler h, + final BaseActionSource actionSrc + ) { + this.data.add(new CellChangeTrackerRecord(channel, i, h, actionSrc)); + } - private class CellChangeTrackerRecord - { - - final StorageChannel channel; - final int up_or_down; - final IItemList list; - final BaseActionSource src; - - public CellChangeTrackerRecord( final StorageChannel channel, final int i, final IMEInventoryHandler h, final 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 ); - } - } - - - private class CellChangeTracker - { - - final List data = new LinkedList(); - - public void postChanges( final StorageChannel channel, final int i, final IMEInventoryHandler h, final BaseActionSource actionSrc ) - { - this.data.add( new CellChangeTrackerRecord( channel, i, h, actionSrc ) ); - } - - public void applyChanges() - { - for( final CellChangeTrackerRecord rec : this.data ) - { - rec.applyChanges(); - } - } - } + public void applyChanges() { + for (final 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 6b33d5e9..f6444998 100644 --- a/src/main/java/appeng/me/cache/NetworkMonitor.java +++ b/src/main/java/appeng/me/cache/NetworkMonitor.java @@ -18,6 +18,11 @@ package appeng.me.cache; +import java.util.*; +import java.util.Map.Entry; +import javax.annotation.Nonnegative; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -33,307 +38,275 @@ import appeng.me.storage.ItemWatcher; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; -import javax.annotation.Nonnegative; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.*; -import java.util.Map.Entry; +public class NetworkMonitor> implements IMEMonitor { + @Nonnull + private static final Deque> GLOBAL_DEPTH = Lists.newLinkedList(); + @Nonnull + private final GridStorageCache myGridCache; + @Nonnull + private final StorageChannel myChannel; + @Nonnull + private final IItemList cachedList; + @Nonnull + private final Map, Object> listeners; -public class NetworkMonitor> implements IMEMonitor -{ - @Nonnull - private static final Deque> GLOBAL_DEPTH = Lists.newLinkedList(); + private boolean sendEvent = false; + private boolean hasChanged = false; + @Nonnegative + private int localDepthSemaphore = 0; - @Nonnull - private final GridStorageCache myGridCache; - @Nonnull - private final StorageChannel myChannel; - @Nonnull - private final IItemList cachedList; - @Nonnull - private final Map, Object> listeners; + public NetworkMonitor(final GridStorageCache cache, final StorageChannel chan) { + this.myGridCache = cache; + this.myChannel = chan; + this.cachedList = (IItemList) chan.createList(); + this.listeners = new HashMap, Object>(); + } - private boolean sendEvent = false; - private boolean hasChanged = false; - @Nonnegative - private int localDepthSemaphore = 0; + @Override + public void + addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - public NetworkMonitor( final GridStorageCache cache, final StorageChannel chan ) - { - this.myGridCache = cache; - this.myChannel = chan; - this.cachedList = (IItemList) chan.createList(); - this.listeners = new HashMap, Object>(); - } + @Override + public boolean canAccept(final T input) { + return this.getHandler().canAccept(input); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public T + extractItems(final T request, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return this.getHandler().extractItems(request, mode, src); + } - @Override - public boolean canAccept( final T input ) - { - return this.getHandler().canAccept( input ); - } + localDepthSemaphore++; + final T leftover = this.getHandler().extractItems(request, mode, src); + localDepthSemaphore--; - @Override - public T extractItems( final T request, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return this.getHandler().extractItems( request, mode, src ); - } + if (localDepthSemaphore == 0) { + this.monitorDifference(request.copy(), leftover, true, src); + } - localDepthSemaphore++; - final T leftover = this.getHandler().extractItems( request, mode, src ); - localDepthSemaphore--; + return leftover; + } - if( localDepthSemaphore == 0 ) - { - this.monitorDifference( request.copy(), leftover, true, src ); - } + @Override + public AccessRestriction getAccess() { + return this.getHandler().getAccess(); + } - return leftover; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.getHandler().getAvailableItems(out); + } - @Override - public AccessRestriction getAccess() - { - return this.getHandler().getAccess(); - } + @Override + public StorageChannel getChannel() { + return this.getHandler().getChannel(); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.getHandler().getAvailableItems( out ); - } + @Override + public int getPriority() { + return this.getHandler().getPriority(); + } - @Override - public StorageChannel getChannel() - { - return this.getHandler().getChannel(); - } + @Override + public int getSlot() { + return this.getHandler().getSlot(); + } - @Override - public int getPriority() - { - return this.getHandler().getPriority(); - } + @Nonnull + @Override + public IItemList getStorageList() { + if (this.hasChanged) { + this.hasChanged = false; + this.cachedList.resetStatus(); + return this.getAvailableItems(this.cachedList); + } - @Override - public int getSlot() - { - return this.getHandler().getSlot(); - } + return this.cachedList; + } - @Nonnull - @Override - public IItemList getStorageList() - { - if( this.hasChanged ) - { - this.hasChanged = false; - this.cachedList.resetStatus(); - return this.getAvailableItems( this.cachedList ); - } + @Override + public T + injectItems(final T input, final Actionable mode, final BaseActionSource src) { + if (mode == Actionable.SIMULATE) { + return this.getHandler().injectItems(input, mode, src); + } - return this.cachedList; - } + localDepthSemaphore++; + final T leftover = this.getHandler().injectItems(input, mode, src); + localDepthSemaphore--; - @Override - public T injectItems( final T input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return this.getHandler().injectItems( input, mode, src ); - } + if (localDepthSemaphore == 0) { + this.monitorDifference(input.copy(), leftover, false, src); + } - localDepthSemaphore++; - final T leftover = this.getHandler().injectItems( input, mode, src ); - localDepthSemaphore--; + return leftover; + } - if( localDepthSemaphore == 0 ) - { - this.monitorDifference( input.copy(), leftover, false, src ); - } + @Override + public boolean isPrioritized(final T input) { + return this.getHandler().isPrioritized(input); + } - return leftover; - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public boolean isPrioritized( final T input ) - { - return this.getHandler().isPrioritized( input ); - } + @Override + public boolean validForPass(final int i) { + return this.getHandler().validForPass(i); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Nullable + @SuppressWarnings("unchecked") + private IMEInventoryHandler getHandler() { + switch (this.myChannel) { + case ITEMS: + return (IMEInventoryHandler) this.myGridCache.getItemInventoryHandler( + ); + case FLUIDS: + return (IMEInventoryHandler) this.myGridCache.getFluidInventoryHandler( + ); + default: + } + return null; + } - @Override - public boolean validForPass( final int i ) - { - return this.getHandler().validForPass( i ); - } + private Iterator, Object>> getListeners() { + return this.listeners.entrySet().iterator(); + } - @Nullable - @SuppressWarnings( "unchecked" ) - private IMEInventoryHandler getHandler() - { - switch( this.myChannel ) - { - case ITEMS: - return (IMEInventoryHandler) this.myGridCache.getItemInventoryHandler(); - case FLUIDS: - return (IMEInventoryHandler) this.myGridCache.getFluidInventoryHandler(); - default: - } - return null; - } + private T monitorDifference( + final IAEStack original, + final T leftOvers, + final boolean extraction, + final BaseActionSource src + ) { + final T diff = (T) original.copy(); - private Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } + if (extraction) { + diff.setStackSize(leftOvers == null ? 0 : -leftOvers.getStackSize()); + } else if (leftOvers != null) { + diff.decStackSize(leftOvers.getStackSize()); + } - private T monitorDifference( final IAEStack original, final T leftOvers, final boolean extraction, final BaseActionSource src ) - { - final T diff = (T) original.copy(); + if (diff.getStackSize() != 0) { + this.postChangesToListeners(ImmutableList.of(diff), src); + } - if( extraction ) - { - diff.setStackSize( leftOvers == null ? 0 : -leftOvers.getStackSize() ); - } - else if( leftOvers != null ) - { - diff.decStackSize( leftOvers.getStackSize() ); - } + return leftOvers; + } - if( diff.getStackSize() != 0 ) - { - this.postChangesToListeners( ImmutableList.of( diff ), src ); - } + private void + notifyListenersOfChange(final Iterable diff, final BaseActionSource src) { + this.hasChanged = true; + final Iterator, Object>> i + = this.getListeners(); - return leftOvers; - } + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + if (receiver.isValid(o.getValue())) { + receiver.postChange(this, diff, src); + } else { + i.remove(); + } + } + } - private void notifyListenersOfChange( final Iterable diff, final BaseActionSource src ) - { - this.hasChanged = true; - final Iterator, Object>> i = this.getListeners(); + private void + postChangesToListeners(final Iterable changes, final BaseActionSource src) { + this.postChange(true, changes, src); + } - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( this, diff, src ); - } - else - { - i.remove(); - } - } - } + protected void + postChange(final boolean add, final Iterable changes, final BaseActionSource src) { + if (localDepthSemaphore > 0 || GLOBAL_DEPTH.contains(this)) { + return; + } - private void postChangesToListeners( final Iterable changes, final BaseActionSource src ) - { - this.postChange( true, changes, src ); - } + GLOBAL_DEPTH.push(this); + localDepthSemaphore++; - protected void postChange( final boolean add, final Iterable changes, final BaseActionSource src ) - { - if( localDepthSemaphore > 0 || GLOBAL_DEPTH.contains( this ) ) - { - return; - } + this.sendEvent = true; - GLOBAL_DEPTH.push( this ); - localDepthSemaphore++; + this.notifyListenersOfChange(changes, src); - this.sendEvent = true; + for (final T changedItem : changes) { + T difference = changedItem; - this.notifyListenersOfChange( changes, src ); + if (!add && changedItem != null) { + difference = changedItem.copy(); + difference.setStackSize(-changedItem.getStackSize()); + } - for( final T changedItem : changes ) - { - T difference = changedItem; + if (this.myGridCache.getInterestManager().containsKey(changedItem)) { + final Collection list + = this.myGridCache.getInterestManager().get(changedItem); - if( !add && changedItem != null ) - { - difference = changedItem.copy(); - difference.setStackSize( -changedItem.getStackSize() ); - } + if (!list.isEmpty()) { + IAEStack fullStack = this.getStorageList().findPrecise(changedItem); - if( this.myGridCache.getInterestManager().containsKey( changedItem ) ) - { - final Collection list = this.myGridCache.getInterestManager().get( changedItem ); + if (fullStack == null) { + fullStack = changedItem.copy(); + fullStack.setStackSize(0); + } - if( !list.isEmpty() ) - { - IAEStack fullStack = this.getStorageList().findPrecise( changedItem ); + this.myGridCache.getInterestManager().enableTransactions(); - if( fullStack == null ) - { - fullStack = changedItem.copy(); - fullStack.setStackSize( 0 ); - } + for (final ItemWatcher iw : list) { + iw.getHost().onStackChange( + this.getStorageList(), + fullStack, + difference, + src, + this.getChannel() + ); + } - this.myGridCache.getInterestManager().enableTransactions(); + this.myGridCache.getInterestManager().disableTransactions(); + } + } + } - for( final ItemWatcher iw : list ) - { - iw.getHost().onStackChange( this.getStorageList(), fullStack, difference, src, this.getChannel() ); - } + final NetworkMonitor last = GLOBAL_DEPTH.pop(); + localDepthSemaphore--; - this.myGridCache.getInterestManager().disableTransactions(); - } - } - } + if (last != this) { + throw new IllegalStateException( + "Invalid Access to Networked Storage API detected." + ); + } + } - final NetworkMonitor last = GLOBAL_DEPTH.pop(); - localDepthSemaphore--; + void forceUpdate() { + this.hasChanged = true; - if( last != this ) - { - throw new IllegalStateException( "Invalid Access to Networked Storage API detected." ); - } - } + final Iterator, Object>> i + = this.getListeners(); + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); - void forceUpdate() - { - this.hasChanged = true; - - final Iterator, Object>> i = this.getListeners(); - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - - if( receiver.isValid( o.getValue() ) ) - { - receiver.onListUpdate(); - } - else - { - i.remove(); - } - } - } - - void onTick() - { - if( this.sendEvent ) - { - this.sendEvent = false; - this.myGridCache.getGrid().postEvent( new MENetworkStorageEvent( this, this.myChannel ) ); - } - } + if (receiver.isValid(o.getValue())) { + receiver.onListUpdate(); + } else { + i.remove(); + } + } + } + void onTick() { + if (this.sendEvent) { + this.sendEvent = false; + this.myGridCache.getGrid().postEvent( + new MENetworkStorageEvent(this, this.myChannel) + ); + } + } } diff --git a/src/main/java/appeng/me/cache/P2PCache.java b/src/main/java/appeng/me/cache/P2PCache.java index b3a57c62..6564dbd1 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 appeng.api.networking.*; import appeng.api.networking.events.MENetworkBootingStatusChange; @@ -30,202 +31,155 @@ import appeng.parts.p2p.PartP2PTunnelME; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; -import java.util.HashMap; +public class P2PCache implements IGridCache { + private final IGrid myGrid; + private final HashMap inputs + = new HashMap(); + private final Multimap outputs = LinkedHashMultimap.create(); + private final TunnelCollection NullColl + = new TunnelCollection(null, null); + public P2PCache(final IGrid g) { + this.myGrid = g; + } -public class P2PCache implements IGridCache -{ + @MENetworkEventSubscribe + public void bootComplete(final MENetworkBootingStatusChange bootStatus) { + final ITickManager tm = this.myGrid.getCache(ITickManager.class); + for (final PartP2PTunnel me : this.inputs.values()) { + if (me instanceof PartP2PTunnelME) { + tm.wakeDevice(me.getGridNode()); + } + } + } - private final IGrid myGrid; - private final HashMap inputs = new HashMap(); - private final Multimap outputs = LinkedHashMultimap.create(); - private final TunnelCollection NullColl = new TunnelCollection( null, null ); + @MENetworkEventSubscribe + public void bootComplete(final MENetworkPowerStatusChange power) { + final ITickManager tm = this.myGrid.getCache(ITickManager.class); + for (final PartP2PTunnel me : this.inputs.values()) { + if (me instanceof PartP2PTunnelME) { + tm.wakeDevice(me.getGridNode()); + } + } + } - public P2PCache( final IGrid g ) - { - this.myGrid = g; - } + @Override + public void onUpdateTick() {} - @MENetworkEventSubscribe - public void bootComplete( final MENetworkBootingStatusChange bootStatus ) - { - final ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for( final PartP2PTunnel me : this.inputs.values() ) - { - if( me instanceof PartP2PTunnelME ) - { - tm.wakeDevice( me.getGridNode() ); - } - } - } + @Override + public void removeNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof PartP2PTunnel) { + if (machine instanceof PartP2PTunnelME) { + if (!node.hasFlag(GridFlags.REQUIRE_CHANNEL)) { + return; + } + } - @MENetworkEventSubscribe - public void bootComplete( final MENetworkPowerStatusChange power ) - { - final ITickManager tm = this.myGrid.getCache( ITickManager.class ); - for( final PartP2PTunnel me : this.inputs.values() ) - { - if( me instanceof PartP2PTunnelME ) - { - tm.wakeDevice( me.getGridNode() ); - } - } - } + final PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq + // ); - @Override - public void onUpdateTick() - { + if (t.isOutput()) { + this.outputs.remove(t.getFrequency(), t); + } else { + this.inputs.remove(t.getFrequency()); + } - } + this.updateTunnel(t.getFrequency(), !t.isOutput(), false); + } + } - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof PartP2PTunnel ) - { - if( machine instanceof PartP2PTunnelME ) - { - if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - { - return; - } - } + @Override + public void addNode(final IGridNode node, final IGridHost machine) { + if (machine instanceof PartP2PTunnel) { + if (machine instanceof PartP2PTunnelME) { + if (!node.hasFlag(GridFlags.REQUIRE_CHANNEL)) { + return; + } + } - final PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "rmv-" + (t.output ? "output: " : "input: ") + t.freq - // ); + final PartP2PTunnel t = (PartP2PTunnel) machine; + // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq + // ); - if( t.isOutput() ) - { - this.outputs.remove( t.getFrequency(), t ); - } - else - { - this.inputs.remove( t.getFrequency() ); - } + if (t.isOutput()) { + this.outputs.put(t.getFrequency(), t); + } else { + this.inputs.put(t.getFrequency(), t); + } - this.updateTunnel( t.getFrequency(), !t.isOutput(), false ); - } - } + this.updateTunnel(t.getFrequency(), !t.isOutput(), false); + } + } - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - if( machine instanceof PartP2PTunnel ) - { - if( machine instanceof PartP2PTunnelME ) - { - if( !node.hasFlag( GridFlags.REQUIRE_CHANNEL ) ) - { - return; - } - } + @Override + public void onSplit(final IGridStorage storageB) {} - final PartP2PTunnel t = (PartP2PTunnel) machine; - // AELog.info( "add-" + (t.output ? "output: " : "input: ") + t.freq - // ); + @Override + public void onJoin(final IGridStorage storageB) {} - if( t.isOutput() ) - { - this.outputs.put( t.getFrequency(), t ); - } - else - { - this.inputs.put( t.getFrequency(), t ); - } + @Override + public void populateGridStorage(final IGridStorage storage) {} - this.updateTunnel( t.getFrequency(), !t.isOutput(), false ); - } - } + private void updateTunnel( + final long freq, final boolean updateOutputs, final boolean configChange + ) { + for (final PartP2PTunnel p : this.outputs.get(freq)) { + if (configChange) { + p.onTunnelConfigChange(); + } + p.onTunnelNetworkChange(); + } - @Override - public void onSplit( final IGridStorage storageB ) - { + final PartP2PTunnel in = this.inputs.get(freq); + if (in != null) { + if (configChange) { + in.onTunnelConfigChange(); + } + in.onTunnelNetworkChange(); + } + } - } + public void updateFreq(final PartP2PTunnel t, final long newFrequency) { + if (this.outputs.containsValue(t)) { + this.outputs.remove(t.getFrequency(), t); + } - @Override - public void onJoin( final IGridStorage storageB ) - { + if (this.inputs.containsValue(t)) { + this.inputs.remove(t.getFrequency()); + } - } + t.setFrequency(newFrequency); - @Override - public void populateGridStorage( final IGridStorage storage ) - { + if (t.isOutput()) { + this.outputs.put(t.getFrequency(), t); + } else { + this.inputs.put(t.getFrequency(), t); + } - } + // AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq + // ); + this.updateTunnel(t.getFrequency(), t.isOutput(), true); + this.updateTunnel(t.getFrequency(), !t.isOutput(), true); + } - private void updateTunnel( final long freq, final boolean updateOutputs, final boolean configChange ) - { - for( final PartP2PTunnel p : this.outputs.get( freq ) ) - { - if( configChange ) - { - p.onTunnelConfigChange(); - } - p.onTunnelNetworkChange(); - } + public TunnelCollection + getOutputs(final long freq, final Class c) { + final PartP2PTunnel in = this.inputs.get(freq); + if (in == null) { + return this.NullColl; + } - final PartP2PTunnel in = this.inputs.get( freq ); - if( in != null ) - { - if( configChange ) - { - in.onTunnelConfigChange(); - } - in.onTunnelNetworkChange(); - } - } + final TunnelCollection out + = this.inputs.get(freq).getCollection(this.outputs.get(freq), c); + if (out == null) { + return this.NullColl; + } - public void updateFreq( final PartP2PTunnel t, final long newFrequency ) - { - if( this.outputs.containsValue( t ) ) - { - this.outputs.remove( t.getFrequency(), t ); - } + return out; + } - if( this.inputs.containsValue( t ) ) - { - this.inputs.remove( t.getFrequency() ); - } - - t.setFrequency( newFrequency ); - - if( t.isOutput() ) - { - this.outputs.put( t.getFrequency(), t ); - } - else - { - this.inputs.put( t.getFrequency(), t ); - } - - // AELog.info( "update-" + (t.output ? "output: " : "input: ") + t.freq - // ); - this.updateTunnel( t.getFrequency(), t.isOutput(), true ); - this.updateTunnel( t.getFrequency(), !t.isOutput(), true ); - } - - public TunnelCollection getOutputs( final long freq, final Class c ) - { - final PartP2PTunnel in = this.inputs.get( freq ); - if( in == null ) - { - return this.NullColl; - } - - final TunnelCollection out = this.inputs.get( freq ).getCollection( this.outputs.get( freq ), c ); - if( out == null ) - { - return this.NullColl; - } - - return out; - } - - public PartP2PTunnel getInput( final long freq ) - { - return this.inputs.get( freq ); - } + public PartP2PTunnel getInput(final long freq) { + return this.inputs.get(freq); + } } diff --git a/src/main/java/appeng/me/cache/PathGridCache.java b/src/main/java/appeng/me/cache/PathGridCache.java index 7a72983a..7581a601 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.*; import appeng.api.networking.*; import appeng.api.networking.events.MENetworkBootingStatusChange; @@ -38,422 +39,353 @@ import appeng.tile.networking.TileController; import appeng.util.Platform; import net.minecraftforge.common.util.ForgeDirection; -import java.util.*; - - -public class PathGridCache implements IPathingGrid -{ - - private final LinkedList active = new LinkedList(); - private final Set controllers = new HashSet(); - private final Set legacyControllers = new HashSet(); - private final Set requireChannels = new HashSet(); - private final Set blockDense = new HashSet(); - private final IGrid myGrid; - private int channelsInUse = 0; - private int channelsByBlocks = 0; - private double channelPowerUsage = 0.0; - private boolean recalculateControllerNextTick = true; - private boolean updateNetwork = true; - private boolean booting = false; - private ControllerState controllerState = ControllerState.NO_CONTROLLER; - private int ticksUntilReady = 20; - private int lastChannels = 0; - private HashSet semiOpen = new HashSet(); - - public PathGridCache( final IGrid g ) - { - this.myGrid = g; - } - - @Override - public void onUpdateTick() - { - if( this.recalculateControllerNextTick ) - { - this.recalcController(); - } - - if( this.updateNetwork ) - { - if( !this.booting ) - { - this.myGrid.postEvent( new MENetworkBootingStatusChange() ); - } - - this.booting = true; - this.updateNetwork = false; - this.setChannelsInUse( 0 ); - - if( this.controllerState == ControllerState.CONTROLLER_INFINITE ) - { - final int used = this.calculateRequiredChannels(); - - final int nodes = this.myGrid.getNodes().size(); - this.ticksUntilReady = 20 + Math.max( 0, nodes / 100 - 20 ); - this.setChannelsByBlocks( nodes * used ); - this.setChannelPowerUsage( this.getChannelsByBlocks() / 128.0 ); - - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( used ) ); - } - else if( this.controllerState == ControllerState.NO_CONTROLLER ) { - if (AEConfig.instance.NeedController) { - this.ticksUntilReady = 20; - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) ); - } else { - final int requiredChannels = this.calculateRequiredChannels(); - int used = requiredChannels; - if (requiredChannels > 8) { - used = 0; - } - - final int nodes = this.myGrid.getNodes().size(); - this.setChannelsInUse(used); - - this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); - this.setChannelsByBlocks(nodes * used); - this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); - - this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(used)); - } - } - else if( this.controllerState == ControllerState.CONTROLLER_CONFLICT ) - { - this.ticksUntilReady = 20; - this.myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) ); - } - else - { - final int nodes = this.myGrid.getNodes().size(); - this.ticksUntilReady = 20 + Math.max( 0, nodes / 100 - 20 ); - final HashSet closedList = new HashSet(); - this.semiOpen = new HashSet(); - - // myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) - // ); - for( final IGridNode node : this.myGrid.getMachines( TileController.class ) ) - { - closedList.add( (IPathItem) node ); - for( final IGridConnection gcc : node.getConnections() ) - { - final GridConnection gc = (GridConnection) gcc; - if( !( gc.getOtherSide( node ).getMachine() instanceof TileController ) ) - { - final List open = new LinkedList(); - closedList.add( gc ); - open.add( gc ); - gc.setControllerRoute( (GridNode) node, true ); - this.active.add( new PathSegment( this, open, this.semiOpen, closedList ) ); - } - } - } - } - } - - if( !this.active.isEmpty() || this.ticksUntilReady > 0 ) - { - final Iterator i = this.active.iterator(); - while( i.hasNext() ) - { - final PathSegment pat = i.next(); - if( pat.step() ) - { - pat.setDead( true ); - i.remove(); - } - } - - this.ticksUntilReady--; - - if( this.active.isEmpty() && this.ticksUntilReady <= 0 ) - { - if( this.controllerState == ControllerState.CONTROLLER_ONLINE || this.controllerState == ControllerState.CONTROLLER_INFINITE) - { - final Iterator controllerIterator = this.controllers.iterator(); - if( controllerIterator.hasNext() ) - { - final TileController controller = controllerIterator.next(); - controller.getGridNode( ForgeDirection.UNKNOWN ).beginVisit( new ControllerChannelUpdater() ); - } - } - - // check for achievements - this.achievementPost(); - - this.booting = false; - this.setChannelPowerUsage( this.getChannelsByBlocks() / 128.0 ); - this.myGrid.postEvent( new MENetworkBootingStatusChange() ); - } - } - } - - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof TileController ) - { - this.controllers.remove( machine ); - this.recalculateControllerNextTick = true; - } - else if (machine instanceof TileLegacyController) { - this.legacyControllers.remove(machine); - this.recalculateControllerNextTick = true; - } - - final 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( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof TileController ) - { - this.controllers.add( (TileController) machine ); - this.recalculateControllerNextTick = true; - } - else if(machine instanceof TileLegacyController) { - this.legacyControllers.add((TileLegacyController) machine); - this.recalculateControllerNextTick = true; - } - - final 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( final IGridStorage storageB ) - { - - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - - } - - private void recalcController() - { - this.recalculateControllerNextTick = false; - final ControllerState old = this.controllerState; - - if (this.legacyControllers.size() > 1) { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - } - else if (this.legacyControllers.size() == 1 && !AEConfig.instance.HardLegacyController) { - this.controllerState = ControllerState.CONTROLLER_INFINITE; - } - else if( this.controllers.isEmpty() ) - { - this.controllerState = ControllerState.NO_CONTROLLER; - } - else { - final IGridNode startingNode = this.controllers.iterator().next().getGridNode( ForgeDirection.UNKNOWN ); - if( startingNode == null ) - { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - return; - } - - final DimensionalCoord dc = startingNode.getGridBlock().getLocation(); - final ControllerValidator cv = new ControllerValidator( dc.x, dc.y, dc.z ); - - startingNode.beginVisit( cv ); - - if( cv.isValid() && cv.getFound() == this.controllers.size() ) - { - if (this.legacyControllers.size() == 1 && this.controllers.size() >= 68) { - this.controllerState = ControllerState.CONTROLLER_INFINITE; - } else if (AEConfig.instance.isFeatureEnabled( AEFeature.Channels )) { - this.controllerState = ControllerState.CONTROLLER_ONLINE; - } else { - this.controllerState = ControllerState.CONTROLLER_INFINITE; - } - } - else - { - this.controllerState = ControllerState.CONTROLLER_CONFLICT; - } - } - - if( old != this.controllerState ) - { - this.myGrid.postEvent( new MENetworkControllerChange() ); - } - } - - private int calculateRequiredChannels() - { - this.semiOpen.clear(); - - int depth = 0; - for( final IGridNode nodes : this.requireChannels ) - { - if( !this.semiOpen.contains( nodes ) ) - { - final IGridBlock gb = nodes.getGridBlock(); - final EnumSet flags = gb.getFlags(); - - if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) && !this.blockDense.isEmpty() ) - { - return 9; - } - - depth++; - - if( flags.contains( GridFlags.MULTIBLOCK ) ) - { - final IGridMultiblock gmb = (IGridMultiblock) gb; - final Iterator i = gmb.getMultiblockNodes(); - while( i.hasNext() ) - { - this.semiOpen.add( (IPathItem) i.next() ); - } - } - } - } - - return depth; - } - - private void achievementPost() - { - if( this.lastChannels != this.getChannelsInUse() && AEConfig.instance.isFeatureEnabled( AEFeature.Channels ) ) - { - final Achievements currentBracket = this.getAchievementBracket( this.getChannelsInUse() ); - final Achievements lastBracket = this.getAchievementBracket( this.lastChannels ); - if( currentBracket != lastBracket && currentBracket != null ) - { - final Set players = new HashSet(); - for( final IGridNode n : this.requireChannels ) - { - players.add( n.getPlayerID() ); - } - - for( final int id : players ) - { - Platform.addStat( id, currentBracket.getAchievement() ); - } - } - } - this.lastChannels = this.getChannelsInUse(); - } - - private Achievements getAchievementBracket( final int ch ) - { - if( ch < 8 ) - { - return null; - } - - if( ch < 128 ) - { - return Achievements.Networking1; - } - - if( ch < 2048 ) - { - return Achievements.Networking2; - } - - return Achievements.Networking3; - } - - @MENetworkEventSubscribe - void updateNodReq( final MENetworkChannelChanged ev ) - { - final IGridNode gridNode = ev.node; - - if( gridNode.getGridBlock().getFlags().contains( GridFlags.REQUIRE_CHANNEL ) ) - { - this.requireChannels.add( gridNode ); - } - else - { - this.requireChannels.remove( gridNode ); - } - - this.repath(); - } - - @Override - public boolean isNetworkBooting() - { - return !this.active.isEmpty() && !this.booting; - } - - @Override - public ControllerState getControllerState() - { - return this.controllerState; - } - - @Override - public void repath() - { - // clean up... - this.active.clear(); - - this.setChannelsByBlocks( 0 ); - this.updateNetwork = true; - } - - double getChannelPowerUsage() - { - return this.channelPowerUsage; - } - - private void setChannelPowerUsage( final double channelPowerUsage ) - { - this.channelPowerUsage = channelPowerUsage; - } - - public int getChannelsByBlocks() - { - return this.channelsByBlocks; - } - - public void setChannelsByBlocks( final int channelsByBlocks ) - { - this.channelsByBlocks = channelsByBlocks; - } - - public int getChannelsInUse() - { - return this.channelsInUse; - } - - public void setChannelsInUse( final int channelsInUse ) - { - this.channelsInUse = channelsInUse; - } +public class PathGridCache implements IPathingGrid { + private final LinkedList active = new LinkedList(); + private final Set controllers = new HashSet(); + private final Set legacyControllers + = new HashSet(); + private final Set requireChannels = new HashSet(); + private final Set blockDense = new HashSet(); + private final IGrid myGrid; + private int channelsInUse = 0; + private int channelsByBlocks = 0; + private double channelPowerUsage = 0.0; + private boolean recalculateControllerNextTick = true; + private boolean updateNetwork = true; + private boolean booting = false; + private ControllerState controllerState = ControllerState.NO_CONTROLLER; + private int ticksUntilReady = 20; + private int lastChannels = 0; + private HashSet semiOpen = new HashSet(); + + public PathGridCache(final IGrid g) { + this.myGrid = g; + } + + @Override + public void onUpdateTick() { + if (this.recalculateControllerNextTick) { + this.recalcController(); + } + + if (this.updateNetwork) { + if (!this.booting) { + this.myGrid.postEvent(new MENetworkBootingStatusChange()); + } + + this.booting = true; + this.updateNetwork = false; + this.setChannelsInUse(0); + + if (this.controllerState == ControllerState.CONTROLLER_INFINITE) { + final int used = this.calculateRequiredChannels(); + + final int nodes = this.myGrid.getNodes().size(); + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + this.setChannelsByBlocks(nodes * used); + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); + + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(used)); + } else if (this.controllerState == ControllerState.NO_CONTROLLER) { + if (AEConfig.instance.NeedController) { + this.ticksUntilReady = 20; + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(0)); + } else { + final int requiredChannels = this.calculateRequiredChannels(); + int used = requiredChannels; + if (requiredChannels > 8) { + used = 0; + } + + final int nodes = this.myGrid.getNodes().size(); + this.setChannelsInUse(used); + + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + this.setChannelsByBlocks(nodes * used); + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); + + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(used)); + } + } else if (this.controllerState == ControllerState.CONTROLLER_CONFLICT) { + this.ticksUntilReady = 20; + this.myGrid.getPivot().beginVisit(new AdHocChannelUpdater(0)); + } else { + final int nodes = this.myGrid.getNodes().size(); + this.ticksUntilReady = 20 + Math.max(0, nodes / 100 - 20); + final HashSet closedList = new HashSet(); + this.semiOpen = new HashSet(); + + // myGrid.getPivot().beginVisit( new AdHocChannelUpdater( 0 ) + // ); + for (final IGridNode node : + this.myGrid.getMachines(TileController.class)) { + closedList.add((IPathItem) node); + for (final IGridConnection gcc : node.getConnections()) { + final GridConnection gc = (GridConnection) gcc; + if (!(gc.getOtherSide(node).getMachine() instanceof TileController + )) { + final List open = new LinkedList(); + closedList.add(gc); + open.add(gc); + gc.setControllerRoute((GridNode) node, true); + this.active.add( + new PathSegment(this, open, this.semiOpen, closedList) + ); + } + } + } + } + } + + if (!this.active.isEmpty() || this.ticksUntilReady > 0) { + final Iterator i = this.active.iterator(); + while (i.hasNext()) { + final PathSegment pat = i.next(); + if (pat.step()) { + pat.setDead(true); + i.remove(); + } + } + + this.ticksUntilReady--; + + if (this.active.isEmpty() && this.ticksUntilReady <= 0) { + if (this.controllerState == ControllerState.CONTROLLER_ONLINE + || this.controllerState == ControllerState.CONTROLLER_INFINITE) { + final Iterator controllerIterator + = this.controllers.iterator(); + if (controllerIterator.hasNext()) { + final TileController controller = controllerIterator.next(); + controller.getGridNode(ForgeDirection.UNKNOWN) + .beginVisit(new ControllerChannelUpdater()); + } + } + + // check for achievements + this.achievementPost(); + + this.booting = false; + this.setChannelPowerUsage(this.getChannelsByBlocks() / 128.0); + this.myGrid.postEvent(new MENetworkBootingStatusChange()); + } + } + } + + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof TileController) { + this.controllers.remove(machine); + this.recalculateControllerNextTick = true; + } else if (machine instanceof TileLegacyController) { + this.legacyControllers.remove(machine); + this.recalculateControllerNextTick = true; + } + + final 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(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof TileController) { + this.controllers.add((TileController) machine); + this.recalculateControllerNextTick = true; + } else if (machine instanceof TileLegacyController) { + this.legacyControllers.add((TileLegacyController) machine); + this.recalculateControllerNextTick = true; + } + + final 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(final IGridStorage storageB) {} + + @Override + public void onJoin(final IGridStorage storageB) {} + + @Override + public void populateGridStorage(final IGridStorage storage) {} + + private void recalcController() { + this.recalculateControllerNextTick = false; + final ControllerState old = this.controllerState; + + if (this.legacyControllers.size() > 1) { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + } else if (this.legacyControllers.size() == 1 && !AEConfig.instance.HardLegacyController) { + this.controllerState = ControllerState.CONTROLLER_INFINITE; + } else if (this.controllers.isEmpty()) { + this.controllerState = ControllerState.NO_CONTROLLER; + } else { + final IGridNode startingNode + = this.controllers.iterator().next().getGridNode(ForgeDirection.UNKNOWN); + if (startingNode == null) { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + return; + } + + final DimensionalCoord dc = startingNode.getGridBlock().getLocation(); + final ControllerValidator cv = new ControllerValidator(dc.x, dc.y, dc.z); + + startingNode.beginVisit(cv); + + if (cv.isValid() && cv.getFound() == this.controllers.size()) { + if (this.legacyControllers.size() == 1 && this.controllers.size() >= 68) { + this.controllerState = ControllerState.CONTROLLER_INFINITE; + } else if (AEConfig.instance.isFeatureEnabled(AEFeature.Channels)) { + this.controllerState = ControllerState.CONTROLLER_ONLINE; + } else { + this.controllerState = ControllerState.CONTROLLER_INFINITE; + } + } else { + this.controllerState = ControllerState.CONTROLLER_CONFLICT; + } + } + + if (old != this.controllerState) { + this.myGrid.postEvent(new MENetworkControllerChange()); + } + } + + private int calculateRequiredChannels() { + this.semiOpen.clear(); + + int depth = 0; + for (final IGridNode nodes : this.requireChannels) { + if (!this.semiOpen.contains(nodes)) { + final IGridBlock gb = nodes.getGridBlock(); + final EnumSet flags = gb.getFlags(); + + if (flags.contains(GridFlags.COMPRESSED_CHANNEL) + && !this.blockDense.isEmpty()) { + return 9; + } + + depth++; + + if (flags.contains(GridFlags.MULTIBLOCK)) { + final IGridMultiblock gmb = (IGridMultiblock) gb; + final Iterator i = gmb.getMultiblockNodes(); + while (i.hasNext()) { + this.semiOpen.add((IPathItem) i.next()); + } + } + } + } + + return depth; + } + + private void achievementPost() { + if (this.lastChannels != this.getChannelsInUse() + && AEConfig.instance.isFeatureEnabled(AEFeature.Channels)) { + final Achievements currentBracket + = this.getAchievementBracket(this.getChannelsInUse()); + final Achievements lastBracket + = this.getAchievementBracket(this.lastChannels); + if (currentBracket != lastBracket && currentBracket != null) { + final Set players = new HashSet(); + for (final IGridNode n : this.requireChannels) { + players.add(n.getPlayerID()); + } + + for (final int id : players) { + Platform.addStat(id, currentBracket.getAchievement()); + } + } + } + this.lastChannels = this.getChannelsInUse(); + } + + private Achievements getAchievementBracket(final int ch) { + if (ch < 8) { + return null; + } + + if (ch < 128) { + return Achievements.Networking1; + } + + if (ch < 2048) { + return Achievements.Networking2; + } + + return Achievements.Networking3; + } + + @MENetworkEventSubscribe + void updateNodReq(final MENetworkChannelChanged ev) { + final IGridNode gridNode = ev.node; + + if (gridNode.getGridBlock().getFlags().contains(GridFlags.REQUIRE_CHANNEL)) { + this.requireChannels.add(gridNode); + } else { + this.requireChannels.remove(gridNode); + } + + this.repath(); + } + + @Override + public boolean isNetworkBooting() { + return !this.active.isEmpty() && !this.booting; + } + + @Override + public ControllerState getControllerState() { + return this.controllerState; + } + + @Override + public void repath() { + // clean up... + this.active.clear(); + + this.setChannelsByBlocks(0); + this.updateNetwork = true; + } + + double getChannelPowerUsage() { + return this.channelPowerUsage; + } + + private void setChannelPowerUsage(final double channelPowerUsage) { + this.channelPowerUsage = channelPowerUsage; + } + + public int getChannelsByBlocks() { + return this.channelsByBlocks; + } + + public void setChannelsByBlocks(final int channelsByBlocks) { + this.channelsByBlocks = channelsByBlocks; + } + + public int getChannelsInUse() { + return this.channelsInUse; + } + + public void setChannelsInUse(final int channelsInUse) { + this.channelsInUse = channelsInUse; + } } diff --git a/src/main/java/appeng/me/cache/SecurityCache.java b/src/main/java/appeng/me/cache/SecurityCache.java index cac6aa3d..16512d48 100644 --- a/src/main/java/appeng/me/cache/SecurityCache.java +++ b/src/main/java/appeng/me/cache/SecurityCache.java @@ -18,6 +18,10 @@ package appeng.me.cache; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; @@ -34,167 +38,125 @@ import com.google.common.base.Preconditions; import com.mojang.authlib.GameProfile; import net.minecraft.entity.player.EntityPlayer; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; +public class SecurityCache implements ISecurityGrid { + private final IGrid myGrid; + private final List securityProvider + = new ArrayList(); + private final HashMap> playerPerms + = new HashMap>(); + private long securityKey = -1; + public SecurityCache(final IGrid g) { + this.myGrid = g; + } -public class SecurityCache implements ISecurityGrid -{ + @MENetworkEventSubscribe + public void updatePermissions(final MENetworkSecurityChange ev) { + this.playerPerms.clear(); + if (this.securityProvider.isEmpty()) { + return; + } - private final IGrid myGrid; - private final List securityProvider = new ArrayList(); - private final HashMap> playerPerms = new HashMap>(); - private long securityKey = -1; + this.securityProvider.get(0).readPermissions(this.playerPerms); + } - public SecurityCache( final IGrid g ) - { - this.myGrid = g; - } + public long getSecurityKey() { + return this.securityKey; + } - @MENetworkEventSubscribe - public void updatePermissions( final MENetworkSecurityChange ev ) - { - this.playerPerms.clear(); - if( this.securityProvider.isEmpty() ) - { - return; - } + @Override + public void onUpdateTick() {} - this.securityProvider.get( 0 ).readPermissions( this.playerPerms ); - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ISecurityProvider) { + this.securityProvider.remove(machine); + this.updateSecurityKey(); + } + } - public long getSecurityKey() - { - return this.securityKey; - } + private void updateSecurityKey() { + final long lastCode = this.securityKey; - @Override - public void onUpdateTick() - { + if (this.securityProvider.size() == 1) { + this.securityKey = this.securityProvider.get(0).getSecurityKey(); + } else { + this.securityKey = -1; + } - } + if (lastCode != this.securityKey) { + this.getGrid().postEvent(new MENetworkSecurityChange()); + for (final IGridNode n : this.getGrid().getNodes()) { + ((GridNode) n).setLastSecurityKey(this.securityKey); + } + } + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ISecurityProvider ) - { - this.securityProvider.remove( machine ); - this.updateSecurityKey(); - } - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof ISecurityProvider) { + this.securityProvider.add((ISecurityProvider) machine); + this.updateSecurityKey(); + } else { + ((GridNode) gridNode).setLastSecurityKey(this.securityKey); + } + } - private void updateSecurityKey() - { - final long lastCode = this.securityKey; + @Override + public void onSplit(final IGridStorage destinationStorage) {} - if( this.securityProvider.size() == 1 ) - { - this.securityKey = this.securityProvider.get( 0 ).getSecurityKey(); - } - else - { - this.securityKey = -1; - } + @Override + public void onJoin(final IGridStorage sourceStorage) {} - if( lastCode != this.securityKey ) - { - this.getGrid().postEvent( new MENetworkSecurityChange() ); - for( final IGridNode n : this.getGrid().getNodes() ) - { - ( (GridNode) n ).setLastSecurityKey( this.securityKey ); - } - } - } + @Override + public void populateGridStorage(final IGridStorage destinationStorage) {} - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof ISecurityProvider ) - { - this.securityProvider.add( (ISecurityProvider) machine ); - this.updateSecurityKey(); - } - else - { - ( (GridNode) gridNode ).setLastSecurityKey( this.securityKey ); - } - } + @Override + public boolean isAvailable() { + return this.securityProvider.size() == 1 + && this.securityProvider.get(0).isSecurityEnabled(); + } - @Override - public void onSplit( final IGridStorage destinationStorage ) - { + @Override + public boolean + hasPermission(final EntityPlayer player, final SecurityPermissions perm) { + Preconditions.checkNotNull(player); + Preconditions.checkNotNull(perm); - } + final GameProfile profile = player.getGameProfile(); + final int playerID = WorldData.instance().playerData().getPlayerID(profile); - @Override - public void onJoin( final IGridStorage sourceStorage ) - { + return this.hasPermission(playerID, perm); + } - } + @Override + public boolean hasPermission(final int playerID, final SecurityPermissions perm) { + if (this.isAvailable()) { + final EnumSet perms = this.playerPerms.get(playerID); - @Override - public void populateGridStorage( final IGridStorage destinationStorage ) - { + if (perms == null) { + if (playerID == -1) // no default? + { + return false; + } else { + return this.hasPermission(-1, perm); + } + } - } + return perms.contains(perm); + } + return true; + } - @Override - public boolean isAvailable() - { - return this.securityProvider.size() == 1 && this.securityProvider.get( 0 ).isSecurityEnabled(); - } + @Override + public int getOwner() { + if (this.isAvailable()) { + return this.securityProvider.get(0).getOwner(); + } + return -1; + } - @Override - public boolean hasPermission( final EntityPlayer player, final SecurityPermissions perm ) - { - Preconditions.checkNotNull( player ); - Preconditions.checkNotNull( perm ); - - final GameProfile profile = player.getGameProfile(); - final int playerID = WorldData.instance().playerData().getPlayerID( profile ); - - return this.hasPermission( playerID, perm ); - } - - @Override - public boolean hasPermission( final int playerID, final SecurityPermissions perm ) - { - if( this.isAvailable() ) - { - final EnumSet perms = this.playerPerms.get( playerID ); - - if( perms == null ) - { - if( playerID == -1 ) // no default? - { - return false; - } - else - { - return this.hasPermission( -1, perm ); - } - } - - return perms.contains( perm ); - } - return true; - } - - @Override - public int getOwner() - { - if( this.isAvailable() ) - { - return this.securityProvider.get( 0 ).getOwner(); - } - return -1; - } - - public IGrid getGrid() - { - return this.myGrid; - } + public IGrid getGrid() { + return this.myGrid; + } } diff --git a/src/main/java/appeng/me/cache/SpatialPylonCache.java b/src/main/java/appeng/me/cache/SpatialPylonCache.java index f1adba5e..abe7cad3 100644 --- a/src/main/java/appeng/me/cache/SpatialPylonCache.java +++ b/src/main/java/appeng/me/cache/SpatialPylonCache.java @@ -18,6 +18,9 @@ package appeng.me.cache; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -33,218 +36,202 @@ import appeng.me.cluster.implementations.SpatialPylonCluster; import appeng.tile.spatial.TileSpatialIOPort; import appeng.tile.spatial.TileSpatialPylon; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; +public class SpatialPylonCache implements ISpatialCache { + private final IGrid myGrid; + private long powerRequired = 0; + private double efficiency = 0.0; + private DimensionalCoord captureMin; + private DimensionalCoord captureMax; + private boolean isValid = false; + private List ioPorts = new LinkedList(); + private HashMap clusters + = new HashMap(); + public SpatialPylonCache(final IGrid g) { + this.myGrid = g; + } -public class SpatialPylonCache implements ISpatialCache -{ + @MENetworkEventSubscribe + public void bootingRender(final MENetworkBootingStatusChange c) { + this.reset(this.myGrid); + } - private final IGrid myGrid; - private long powerRequired = 0; - private double efficiency = 0.0; - private DimensionalCoord captureMin; - private DimensionalCoord captureMax; - private boolean isValid = false; - private List ioPorts = new LinkedList(); - private HashMap clusters = new HashMap(); + private void reset(final IGrid grid) { + this.clusters = new HashMap(); + this.ioPorts = new LinkedList(); - public SpatialPylonCache( final IGrid g ) - { - this.myGrid = g; - } + for (final IGridNode gm : grid.getMachines(TileSpatialIOPort.class)) { + this.ioPorts.add((TileSpatialIOPort) gm.getMachine()); + } - @MENetworkEventSubscribe - public void bootingRender( final MENetworkBootingStatusChange c ) - { - this.reset( this.myGrid ); - } + final IReadOnlyCollection set + = grid.getMachines(TileSpatialPylon.class); + for (final IGridNode gm : set) { + if (gm.meetsChannelRequirements()) { + final SpatialPylonCluster c + = ((TileSpatialPylon) gm.getMachine()).getCluster(); + if (c != null) { + this.clusters.put(c, c); + } + } + } - private void reset( final IGrid grid ) - { + this.captureMax = null; + this.captureMin = null; + this.isValid = true; - this.clusters = new HashMap(); - this.ioPorts = new LinkedList(); + int pylonBlocks = 0; + for (final SpatialPylonCluster cl : this.clusters.values()) { + if (this.captureMax == null) { + this.captureMax = cl.getMax().copy(); + } + if (this.captureMin == null) { + this.captureMin = cl.getMin().copy(); + } - for( final IGridNode gm : grid.getMachines( TileSpatialIOPort.class ) ) - { - this.ioPorts.add( (TileSpatialIOPort) gm.getMachine() ); - } + pylonBlocks += cl.tileCount(); - final IReadOnlyCollection set = grid.getMachines( TileSpatialPylon.class ); - for( final IGridNode gm : set ) - { - if( gm.meetsChannelRequirements() ) - { - final SpatialPylonCluster c = ( (TileSpatialPylon) gm.getMachine() ).getCluster(); - if( c != null ) - { - this.clusters.put( c, c ); - } - } - } + this.captureMin.x = Math.min(this.captureMin.x, cl.getMin().x); + this.captureMin.y = Math.min(this.captureMin.y, cl.getMin().y); + this.captureMin.z = Math.min(this.captureMin.z, cl.getMin().z); - this.captureMax = null; - this.captureMin = null; - this.isValid = true; + this.captureMax.x = Math.max(this.captureMax.x, cl.getMax().x); + this.captureMax.y = Math.max(this.captureMax.y, cl.getMax().y); + this.captureMax.z = Math.max(this.captureMax.z, cl.getMax().z); + } - int pylonBlocks = 0; - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - if( this.captureMax == null ) - { - this.captureMax = cl.getMax().copy(); - } - if( this.captureMin == null ) - { - this.captureMin = cl.getMin().copy(); - } + double maxPower = 0; + double minPower = 0; + 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; - pylonBlocks += cl.tileCount(); + for (final SpatialPylonCluster cl : this.clusters.values()) { + switch (cl.getCurrentAxis()) { + case X: - this.captureMin.x = Math.min( this.captureMin.x, cl.getMin().x ); - this.captureMin.y = Math.min( this.captureMin.y, cl.getMin().y ); - this.captureMin.z = Math.min( this.captureMin.z, cl.getMin().z ); + this.isValid = this.isValid + && ((this.captureMax.y == cl.getMin().y + || this.captureMin.y == cl.getMax().y) + || (this.captureMax.z == cl.getMin().z + || this.captureMin.z == cl.getMax().z)) + && ((this.captureMax.y == cl.getMax().y + || this.captureMin.y == cl.getMin().y) + || (this.captureMax.z == cl.getMax().z + || this.captureMin.z == cl.getMin().z)); - this.captureMax.x = Math.max( this.captureMax.x, cl.getMax().x ); - this.captureMax.y = Math.max( this.captureMax.y, cl.getMax().y ); - this.captureMax.z = Math.max( this.captureMax.z, cl.getMax().z ); - } + break; + case Y: - double maxPower = 0; - double minPower = 0; - 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; + this.isValid = this.isValid + && ((this.captureMax.x == cl.getMin().x + || this.captureMin.x == cl.getMax().x) + || (this.captureMax.z == cl.getMin().z + || this.captureMin.z == cl.getMax().z)) + && ((this.captureMax.x == cl.getMax().x + || this.captureMin.x == cl.getMin().x) + || (this.captureMax.z == cl.getMax().z + || this.captureMin.z == cl.getMin().z)); - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - switch( cl.getCurrentAxis() ) - { - case X: + break; + case Z: - this.isValid = this.isValid && ( ( this.captureMax.y == cl.getMin().y || this.captureMin.y == cl.getMax().y ) || ( this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z ) ) && ( ( this.captureMax.y == cl.getMax().y || this.captureMin.y == cl.getMin().y ) || ( this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z ) ); + this.isValid = this.isValid + && ((this.captureMax.y == cl.getMin().y + || this.captureMin.y == cl.getMax().y) + || (this.captureMax.x == cl.getMin().x + || this.captureMin.x == cl.getMax().x)) + && ((this.captureMax.y == cl.getMax().y + || this.captureMin.y == cl.getMin().y) + || (this.captureMax.x == cl.getMax().x + || this.captureMin.x == cl.getMin().x)); - break; - case Y: + break; + case UNFORMED: + this.isValid = false; + break; + } + } - this.isValid = this.isValid && ( ( this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x ) || ( this.captureMax.z == cl.getMin().z || this.captureMin.z == cl.getMax().z ) ) && ( ( this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x ) || ( this.captureMax.z == cl.getMax().z || this.captureMin.z == cl.getMin().z ) ); + final int reqX = this.captureMax.x - this.captureMin.x; + final int reqY = this.captureMax.y - this.captureMin.y; + final int reqZ = this.captureMax.z - this.captureMin.z; + final int requirePylonBlocks + = Math.max(6, ((reqX * reqZ + reqX * reqY + reqY * reqZ) * 3) / 8); - break; - case Z: + this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; - this.isValid = this.isValid && ( ( this.captureMax.y == cl.getMin().y || this.captureMin.y == cl.getMax().y ) || ( this.captureMax.x == cl.getMin().x || this.captureMin.x == cl.getMax().x ) ) && ( ( this.captureMax.y == cl.getMax().y || this.captureMin.y == cl.getMin().y ) || ( this.captureMax.x == cl.getMax().x || this.captureMin.x == cl.getMin().x ) ); + if (this.efficiency > 1.0) { + this.efficiency = 1.0; + } + if (this.efficiency < 0.0) { + this.efficiency = 0.0; + } - break; - case UNFORMED: - this.isValid = false; - break; - } - } + minPower = (double) reqX * (double) reqY * reqZ + * AEConfig.instance.spatialPowerMultiplier; + maxPower = Math.pow(minPower, AEConfig.instance.spatialPowerExponent); + } - final int reqX = this.captureMax.x - this.captureMin.x; - final int reqY = this.captureMax.y - this.captureMin.y; - final int reqZ = this.captureMax.z - this.captureMin.z; - final int requirePylonBlocks = Math.max( 6, ( ( reqX * reqZ + reqX * reqY + reqY * reqZ ) * 3 ) / 8 ); + final double affective_efficiency = Math.pow(this.efficiency, 0.25); + this.powerRequired = (long + ) (affective_efficiency * minPower + (1.0 - affective_efficiency) * maxPower); - this.efficiency = (double) pylonBlocks / (double) requirePylonBlocks; + for (final SpatialPylonCluster cl : this.clusters.values()) { + final boolean myWasValid = cl.isValid(); + cl.setValid(this.isValid); + if (myWasValid != this.isValid) { + cl.updateStatus(false); + } + } + } - if( this.efficiency > 1.0 ) - { - this.efficiency = 1.0; - } - if( this.efficiency < 0.0 ) - { - this.efficiency = 0.0; - } + @Override + public boolean hasRegion() { + return this.captureMin != null; + } - minPower = (double) reqX * (double) reqY * reqZ * AEConfig.instance.spatialPowerMultiplier; - maxPower = Math.pow( minPower, AEConfig.instance.spatialPowerExponent ); - } + @Override + public boolean isValidRegion() { + return this.hasRegion() && this.isValid; + } - final double affective_efficiency = Math.pow( this.efficiency, 0.25 ); - this.powerRequired = (long) ( affective_efficiency * minPower + ( 1.0 - affective_efficiency ) * maxPower ); + @Override + public DimensionalCoord getMin() { + return this.captureMin; + } - for( final SpatialPylonCluster cl : this.clusters.values() ) - { - final boolean myWasValid = cl.isValid(); - cl.setValid( this.isValid ); - if( myWasValid != this.isValid ) - { - cl.updateStatus( false ); - } - } - } + @Override + public DimensionalCoord getMax() { + return this.captureMax; + } - @Override - public boolean hasRegion() - { - return this.captureMin != null; - } + @Override + public long requiredPower() { + return this.powerRequired; + } - @Override - public boolean isValidRegion() - { - return this.hasRegion() && this.isValid; - } + @Override + public float currentEfficiency() { + return (float) this.efficiency * 100; + } - @Override - public DimensionalCoord getMin() - { - return this.captureMin; - } + @Override + public void onUpdateTick() {} - @Override - public DimensionalCoord getMax() - { - return this.captureMax; - } + @Override + public void removeNode(final IGridNode node, final IGridHost machine) {} - @Override - public long requiredPower() - { - return this.powerRequired; - } + @Override + public void addNode(final IGridNode node, final IGridHost machine) {} - @Override - public float currentEfficiency() - { - return (float) this.efficiency * 100; - } + @Override + public void onSplit(final IGridStorage storageB) {} - @Override - public void onUpdateTick() - { - } + @Override + public void onJoin(final IGridStorage storageB) {} - @Override - public void removeNode( final IGridNode node, final IGridHost machine ) - { - - } - - @Override - public void addNode( final IGridNode node, final IGridHost machine ) - { - - } - - @Override - public void onSplit( final IGridStorage storageB ) - { - - } - - @Override - public void onJoin( final IGridStorage storageB ) - { - - } - - @Override - public void populateGridStorage( final IGridStorage storage ) - { - - } + @Override + public void populateGridStorage(final IGridStorage storage) {} } diff --git a/src/main/java/appeng/me/cache/TickManagerCache.java b/src/main/java/appeng/me/cache/TickManagerCache.java index 247e9593..acbfba4e 100644 --- a/src/main/java/appeng/me/cache/TickManagerCache.java +++ b/src/main/java/appeng/me/cache/TickManagerCache.java @@ -18,6 +18,8 @@ package appeng.me.cache; +import java.util.HashMap; +import java.util.PriorityQueue; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -32,224 +34,190 @@ import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.util.ReportedException; -import java.util.HashMap; -import java.util.PriorityQueue; +public class TickManagerCache implements ITickManager { + private final IGrid myGrid; + private final HashMap alertable + = new HashMap(); + private final HashMap sleeping + = new HashMap(); + private final HashMap awake + = new HashMap(); + private final PriorityQueue upcomingTicks + = new PriorityQueue(); + private long currentTick = 0; + public TickManagerCache(final IGrid g) { + this.myGrid = g; + } -public class TickManagerCache implements ITickManager -{ + public long getCurrentTick() { + return this.currentTick; + } - private final IGrid myGrid; - private final HashMap alertable = new HashMap(); - private final HashMap sleeping = new HashMap(); - private final HashMap awake = new HashMap(); - private final PriorityQueue upcomingTicks = new PriorityQueue(); - private long currentTick = 0; + public long getAvgNanoTime(final IGridNode node) { + TickTracker tt = this.awake.get(node); - public TickManagerCache( final IGrid g ) - { - this.myGrid = g; - } + if (tt == null) { + tt = this.sleeping.get(node); + } - public long getCurrentTick() - { - return this.currentTick; - } + if (tt == null) { + return -1; + } - public long getAvgNanoTime( final IGridNode node ) - { - TickTracker tt = this.awake.get( node ); + return tt.getAvgNanos(); + } - if( tt == null ) - { - tt = this.sleeping.get( node ); - } + @Override + public void onUpdateTick() { + TickTracker tt = null; + try { + this.currentTick++; + while (!this.upcomingTicks.isEmpty()) { + tt = this.upcomingTicks.peek(); + final int diff = (int) (this.currentTick - tt.getLastTick()); + if (diff >= tt.getCurrentRate()) { + // remove tt.. + this.upcomingTicks.poll(); + final TickRateModulation mod + = tt.getGridTickable().tickingRequest(tt.getNode(), diff); - if( tt == null ) - { - return -1; - } + switch (mod) { + case FASTER: + tt.setRate(tt.getCurrentRate() - 2); + break; + case IDLE: + tt.setRate(tt.getRequest().maxTickRate); + break; + case SAME: + break; + case SLEEP: + this.sleepDevice(tt.getNode()); + break; + case SLOWER: + tt.setRate(tt.getCurrentRate() + 1); + break; + case URGENT: + tt.setRate(0); + break; + default: + break; + } - return tt.getAvgNanos(); - } + if (this.awake.containsKey(tt.getNode())) { + this.addToQueue(tt); + } + } else { + return; // done! + } + } + } catch (final Throwable t) { + final CrashReport crashreport + = CrashReport.makeCrashReport(t, "Ticking GridNode"); + final CrashReportCategory crashreportcategory = crashreport.makeCategory( + tt.getGridTickable().getClass().getSimpleName() + " being ticked." + ); + tt.addEntityCrashInfo(crashreportcategory); + throw new ReportedException(crashreport); + } + } - @Override - public void onUpdateTick() - { - TickTracker tt = null; - try - { - this.currentTick++; - while( !this.upcomingTicks.isEmpty() ) - { - tt = this.upcomingTicks.peek(); - final int diff = (int) ( this.currentTick - tt.getLastTick() ); - if( diff >= tt.getCurrentRate() ) - { - // remove tt.. - this.upcomingTicks.poll(); - final TickRateModulation mod = tt.getGridTickable().tickingRequest( tt.getNode(), diff ); + private void addToQueue(final TickTracker tt) { + tt.setLastTick(this.currentTick); + this.upcomingTicks.add(tt); + } - switch( mod ) - { - case FASTER: - tt.setRate( tt.getCurrentRate() - 2 ); - break; - case IDLE: - tt.setRate( tt.getRequest().maxTickRate ); - break; - case SAME: - break; - case SLEEP: - this.sleepDevice( tt.getNode() ); - break; - case SLOWER: - tt.setRate( tt.getCurrentRate() + 1 ); - break; - case URGENT: - tt.setRate( 0 ); - break; - default: - break; - } + @Override + public void removeNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof IGridTickable) { + this.alertable.remove(gridNode); + this.sleeping.remove(gridNode); + this.awake.remove(gridNode); + } + } - if( this.awake.containsKey( tt.getNode() ) ) - { - this.addToQueue( tt ); - } - } - else - { - return; // done! - } - } - } - catch( final Throwable t ) - { - final CrashReport crashreport = CrashReport.makeCrashReport( t, "Ticking GridNode" ); - final CrashReportCategory crashreportcategory = crashreport.makeCategory( tt.getGridTickable().getClass().getSimpleName() + " being ticked." ); - tt.addEntityCrashInfo( crashreportcategory ); - throw new ReportedException( crashreport ); - } - } + @Override + public void addNode(final IGridNode gridNode, final IGridHost machine) { + if (machine instanceof IGridTickable) { + final TickingRequest tr + = ((IGridTickable) machine).getTickingRequest(gridNode); + if (tr != null) { + final TickTracker tt = new TickTracker( + tr, gridNode, (IGridTickable) machine, this.currentTick, this + ); - private void addToQueue( final TickTracker tt ) - { - tt.setLastTick( this.currentTick ); - this.upcomingTicks.add( tt ); - } + if (tr.canBeAlerted) { + this.alertable.put(gridNode, tt); + } - @Override - public void removeNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof IGridTickable ) - { - this.alertable.remove( gridNode ); - this.sleeping.remove( gridNode ); - this.awake.remove( gridNode ); - } - } + if (tr.isSleeping) { + this.sleeping.put(gridNode, tt); + } else { + this.awake.put(gridNode, tt); + this.addToQueue(tt); + } + } + } + } - @Override - public void addNode( final IGridNode gridNode, final IGridHost machine ) - { - if( machine instanceof IGridTickable ) - { - final TickingRequest tr = ( (IGridTickable) machine ).getTickingRequest( gridNode ); - if( tr != null ) - { - final TickTracker tt = new TickTracker( tr, gridNode, (IGridTickable) machine, this.currentTick, this ); + @Override + public void onSplit(final IGridStorage storageB) {} - if( tr.canBeAlerted ) - { - this.alertable.put( gridNode, tt ); - } + @Override + public void onJoin(final IGridStorage storageB) {} - if( tr.isSleeping ) - { - this.sleeping.put( gridNode, tt ); - } - else - { - this.awake.put( gridNode, tt ); - this.addToQueue( tt ); - } - } - } - } + @Override + public void populateGridStorage(final IGridStorage storage) {} - @Override - public void onSplit( final IGridStorage storageB ) - { + @Override + public boolean alertDevice(final IGridNode node) { + final TickTracker tt = this.alertable.get(node); + if (tt == null) { + return false; + } + // throw new RuntimeException( + // "Invalid alerted device, this node is not marked as alertable, or part of this + // grid." ); - } + // set to awake, this is for sanity. + this.sleeping.remove(node); + this.awake.put(node, tt); - @Override - public void onJoin( final IGridStorage storageB ) - { + // configure sort. + tt.setLastTick(tt.getLastTick() - tt.getRequest().maxTickRate); + tt.setCurrentRate(tt.getRequest().minTickRate); - } + // prevent dupes and tick build up. + this.upcomingTicks.remove(tt); + this.upcomingTicks.add(tt); - @Override - public void populateGridStorage( final IGridStorage storage ) - { + return true; + } - } + @Override + public boolean sleepDevice(final IGridNode node) { + if (this.awake.containsKey(node)) { + final TickTracker gt = this.awake.get(node); + this.awake.remove(node); + this.sleeping.put(node, gt); - @Override - public boolean alertDevice( final IGridNode node ) - { - final TickTracker tt = this.alertable.get( node ); - if( tt == null ) - { - return false; - } - // throw new RuntimeException( - // "Invalid alerted device, this node is not marked as alertable, or part of this grid." ); + return true; + } - // set to awake, this is for sanity. - this.sleeping.remove( node ); - this.awake.put( node, tt ); + return false; + } - // configure sort. - tt.setLastTick( tt.getLastTick() - tt.getRequest().maxTickRate ); - tt.setCurrentRate( tt.getRequest().minTickRate ); + @Override + public boolean wakeDevice(final IGridNode node) { + if (this.sleeping.containsKey(node)) { + final TickTracker gt = this.sleeping.get(node); + this.sleeping.remove(node); + this.awake.put(node, gt); + this.addToQueue(gt); - // prevent dupes and tick build up. - this.upcomingTicks.remove( tt ); - this.upcomingTicks.add( tt ); + return true; + } - return true; - } - - @Override - public boolean sleepDevice( final IGridNode node ) - { - if( this.awake.containsKey( node ) ) - { - final TickTracker gt = this.awake.get( node ); - this.awake.remove( node ); - this.sleeping.put( node, gt ); - - return true; - } - - return false; - } - - @Override - public boolean wakeDevice( final IGridNode node ) - { - if( this.sleeping.containsKey( node ) ) - { - final TickTracker gt = this.sleeping.get( node ); - this.sleeping.remove( node ); - this.awake.put( node, gt ); - this.addToQueue( gt ); - - return true; - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java index 759a9408..d6adcd3a 100644 --- a/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java +++ b/src/main/java/appeng/me/cache/helpers/ConnectionWrapper.java @@ -18,27 +18,20 @@ package appeng.me.cache.helpers; - import appeng.api.networking.IGridConnection; +public class ConnectionWrapper { + private IGridConnection connection; -public class ConnectionWrapper -{ + public ConnectionWrapper(final IGridConnection gc) { + this.setConnection(gc); + } - private IGridConnection connection; + public IGridConnection getConnection() { + return this.connection; + } - public ConnectionWrapper( final IGridConnection gc ) - { - this.setConnection( gc ); - } - - public IGridConnection getConnection() - { - return this.connection; - } - - public void setConnection( final IGridConnection connection ) - { - this.connection = connection; - } + public void setConnection(final IGridConnection connection) { + this.connection = connection; + } } \ 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 dabd4c5d..b97f9272 100644 --- a/src/main/java/appeng/me/cache/helpers/Connections.java +++ b/src/main/java/appeng/me/cache/helpers/Connections.java @@ -18,70 +18,58 @@ package appeng.me.cache.helpers; +import java.util.HashMap; import appeng.api.networking.IGridNode; import appeng.parts.p2p.PartP2PTunnelME; import appeng.util.IWorldCallable; import net.minecraft.world.World; -import java.util.HashMap; +public class Connections implements IWorldCallable { + private final HashMap connections + = new HashMap(); + private final PartP2PTunnelME me; + private boolean create = false; + private boolean destroy = false; + public Connections(final PartP2PTunnelME o) { + this.me = o; + } -public class Connections implements IWorldCallable -{ + @Override + public Void call(final World world) throws Exception { + this.me.updateConnections(this); - private final HashMap connections = new HashMap(); - private final PartP2PTunnelME me; - private boolean create = false; - private boolean destroy = false; + return null; + } - public Connections( final PartP2PTunnelME o ) - { - this.me = o; - } + public void markDestroy() { + this.setCreate(false); + this.setDestroy(true); + } - @Override - public Void call( final World world ) throws Exception - { - this.me.updateConnections( this ); + public void markCreate() { + this.setCreate(true); + this.setDestroy(false); + } - return null; - } + public HashMap getConnections() { + return this.connections; + } - public void markDestroy() - { - this.setCreate( false ); - this.setDestroy( true ); - } + public boolean isCreate() { + return this.create; + } - public void markCreate() - { - this.setCreate( true ); - this.setDestroy( false ); - } + private void setCreate(final boolean create) { + this.create = create; + } - public HashMap getConnections() - { - return this.connections; - } + public boolean isDestroy() { + return this.destroy; + } - public boolean isCreate() - { - return this.create; - } - - private void setCreate( final boolean create ) - { - this.create = create; - } - - public boolean isDestroy() - { - return this.destroy; - } - - private void setDestroy( final boolean destroy ) - { - this.destroy = destroy; - } + private void setDestroy(final boolean destroy) { + this.destroy = destroy; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TickTracker.java b/src/main/java/appeng/me/cache/helpers/TickTracker.java index 2f254a1f..4c505867 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 javax.annotation.Nonnull; import appeng.api.networking.IGridNode; import appeng.api.networking.ticking.IGridTickable; @@ -27,114 +28,107 @@ import appeng.me.cache.TickManagerCache; import appeng.parts.AEBasePart; import net.minecraft.crash.CrashReportCategory; -import javax.annotation.Nonnull; +public class TickTracker implements Comparable { + private final TickingRequest request; + private final IGridTickable gt; + private final IGridNode node; + private final TickManagerCache host; + private final long LastFiveTicksTime = 0; -public class TickTracker implements Comparable -{ + private long lastTick; + private int currentRate; - private final TickingRequest request; - private final IGridTickable gt; - private final IGridNode node; - private final TickManagerCache host; + public TickTracker( + final TickingRequest req, + final IGridNode node, + final IGridTickable gt, + final long currentTick, + final TickManagerCache tickManagerCache + ) { + this.request = req; + this.gt = gt; + this.node = node; + this.setCurrentRate((req.minTickRate + req.maxTickRate) / 2); + this.setLastTick(currentTick); + this.host = tickManagerCache; + } - private final long LastFiveTicksTime = 0; + public long getAvgNanos() { + return (this.LastFiveTicksTime / 5); + } - private long lastTick; - private int currentRate; + public void setRate(final int rate) { + this.setCurrentRate(rate); - public TickTracker( final TickingRequest req, final IGridNode node, final IGridTickable gt, final long currentTick, final TickManagerCache tickManagerCache ) - { - this.request = req; - this.gt = gt; - this.node = node; - this.setCurrentRate( ( req.minTickRate + req.maxTickRate ) / 2 ); - this.setLastTick( currentTick ); - this.host = tickManagerCache; - } + if (this.getCurrentRate() < this.getRequest().minTickRate) { + this.setCurrentRate(this.getRequest().minTickRate); + } - public long getAvgNanos() - { - return ( this.LastFiveTicksTime / 5 ); - } + if (this.getCurrentRate() > this.getRequest().maxTickRate) { + this.setCurrentRate(this.getRequest().maxTickRate); + } + } - public void setRate( final int rate ) - { - this.setCurrentRate( rate ); + @Override + public int compareTo(@Nonnull final TickTracker t) { + final int nextTick = (int + ) ((this.getLastTick() - this.host.getCurrentTick()) + this.getCurrentRate()); + final int ts_nextTick + = (int) ((t.getLastTick() - this.host.getCurrentTick()) + t.getCurrentRate()); + return nextTick - ts_nextTick; + } - if( this.getCurrentRate() < this.getRequest().minTickRate ) - { - this.setCurrentRate( this.getRequest().minTickRate ); - } + public void addEntityCrashInfo(final CrashReportCategory crashreportcategory) { + if (this.getGridTickable() instanceof AEBasePart) { + final AEBasePart part = (AEBasePart) this.getGridTickable(); + part.addEntityCrashInfo(crashreportcategory); + } - if( this.getCurrentRate() > this.getRequest().maxTickRate ) - { - this.setCurrentRate( this.getRequest().maxTickRate ); - } - } + crashreportcategory.addCrashSection("CurrentTickRate", this.getCurrentRate()); + crashreportcategory.addCrashSection("MinTickRate", this.getRequest().minTickRate); + crashreportcategory.addCrashSection("MaxTickRate", this.getRequest().maxTickRate); + crashreportcategory.addCrashSection( + "MachineType", this.getGridTickable().getClass().getName() + ); + crashreportcategory.addCrashSection( + "GridBlockType", this.getNode().getGridBlock().getClass().getName() + ); + crashreportcategory.addCrashSection( + "ConnectedSides", this.getNode().getConnectedSides() + ); - @Override - public int compareTo( @Nonnull final TickTracker t ) - { - final int nextTick = (int) ( ( this.getLastTick() - this.host.getCurrentTick() ) + this.getCurrentRate() ); - final int ts_nextTick = (int) ( ( t.getLastTick() - this.host.getCurrentTick() ) + t.getCurrentRate() ); - return nextTick - ts_nextTick; - } + final DimensionalCoord dc = this.getNode().getGridBlock().getLocation(); + if (dc != null) { + crashreportcategory.addCrashSection("Location", dc); + } + } - public void addEntityCrashInfo( final CrashReportCategory crashreportcategory ) - { - if( this.getGridTickable() instanceof AEBasePart ) - { - final AEBasePart part = (AEBasePart) this.getGridTickable(); - part.addEntityCrashInfo( crashreportcategory ); - } + public int getCurrentRate() { + return this.currentRate; + } - crashreportcategory.addCrashSection( "CurrentTickRate", this.getCurrentRate() ); - crashreportcategory.addCrashSection( "MinTickRate", this.getRequest().minTickRate ); - crashreportcategory.addCrashSection( "MaxTickRate", this.getRequest().maxTickRate ); - crashreportcategory.addCrashSection( "MachineType", this.getGridTickable().getClass().getName() ); - crashreportcategory.addCrashSection( "GridBlockType", this.getNode().getGridBlock().getClass().getName() ); - crashreportcategory.addCrashSection( "ConnectedSides", this.getNode().getConnectedSides() ); + public void setCurrentRate(final int currentRate) { + this.currentRate = currentRate; + } - final DimensionalCoord dc = this.getNode().getGridBlock().getLocation(); - if( dc != null ) - { - crashreportcategory.addCrashSection( "Location", dc ); - } - } + public long getLastTick() { + return this.lastTick; + } - public int getCurrentRate() - { - return this.currentRate; - } + public void setLastTick(final long lastTick) { + this.lastTick = lastTick; + } - public void setCurrentRate( final int currentRate ) - { - this.currentRate = currentRate; - } + public IGridNode getNode() { + return this.node; + } - public long getLastTick() - { - return this.lastTick; - } + public IGridTickable getGridTickable() { + return this.gt; + } - public void setLastTick( final long lastTick ) - { - this.lastTick = lastTick; - } - - public IGridNode getNode() - { - return this.node; - } - - public IGridTickable getGridTickable() - { - return this.gt; - } - - public TickingRequest getRequest() - { - return this.request; - } + public TickingRequest getRequest() { + return this.request; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java index 45f16f90..d47c2305 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelCollection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelCollection.java @@ -18,53 +18,42 @@ package appeng.me.cache.helpers; +import java.util.Collection; +import java.util.Iterator; import appeng.parts.p2p.PartP2PTunnel; import appeng.util.iterators.NullIterator; -import java.util.Collection; -import java.util.Iterator; +public class TunnelCollection implements Iterable { + private final Class clz; + private Collection tunnelSources; + public TunnelCollection(final Collection src, final Class c) { + this.tunnelSources = src; + this.clz = c; + } -public class TunnelCollection implements Iterable -{ + public void setSource(final Collection c) { + this.tunnelSources = c; + } - private final Class clz; - private Collection tunnelSources; + public boolean isEmpty() { + return !this.iterator().hasNext(); + } - public TunnelCollection( final Collection src, final 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( final Collection c ) - { - this.tunnelSources = c; - } + public boolean matches(final Class c) { + return this.clz == c; + } - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } - - @Override - public Iterator iterator() - { - if( this.tunnelSources == null ) - { - return new NullIterator(); - } - return new TunnelIterator( this.tunnelSources, this.clz ); - } - - public boolean matches( final Class c ) - { - return this.clz == c; - } - - public Class getClz() - { - return this.clz; - } + public Class getClz() { + return this.clz; + } } diff --git a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java index b4abb1b3..57dde06a 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelConnection.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelConnection.java @@ -18,30 +18,23 @@ package appeng.me.cache.helpers; - import appeng.api.networking.IGridConnection; import appeng.parts.p2p.PartP2PTunnelME; +public class TunnelConnection { + private final PartP2PTunnelME tunnel; + private final IGridConnection c; -public class TunnelConnection -{ + public TunnelConnection(final PartP2PTunnelME t, final IGridConnection con) { + this.tunnel = t; + this.c = con; + } - private final PartP2PTunnelME tunnel; - private final IGridConnection c; + public IGridConnection getConnection() { + return this.c; + } - public TunnelConnection( final PartP2PTunnelME t, final IGridConnection con ) - { - this.tunnel = t; - this.c = con; - } - - public IGridConnection getConnection() - { - return this.c; - } - - public PartP2PTunnelME getTunnel() - { - return this.tunnel; - } + public PartP2PTunnelME getTunnel() { + return this.tunnel; + } } \ No newline at end of file diff --git a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java index 7e9a5f55..325aa610 100644 --- a/src/main/java/appeng/me/cache/helpers/TunnelIterator.java +++ b/src/main/java/appeng/me/cache/helpers/TunnelIterator.java @@ -18,57 +18,46 @@ package appeng.me.cache.helpers; - -import appeng.parts.p2p.PartP2PTunnel; - import java.util.Collection; import java.util.Iterator; +import appeng.parts.p2p.PartP2PTunnel; -public class TunnelIterator implements Iterator -{ +public class TunnelIterator implements Iterator { + private final Iterator wrapped; + private final Class targetType; + private T Next; - private final Iterator wrapped; - private final Class targetType; - private T Next; + public TunnelIterator(final Collection tunnelSources, final Class clz) { + this.wrapped = tunnelSources.iterator(); + this.targetType = clz; + this.findNext(); + } - public TunnelIterator( final Collection tunnelSources, final 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; + } + } + } - 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() { + this.findNext(); + return this.Next != null; + } - @Override - public boolean hasNext() - { - this.findNext(); - return this.Next != null; - } + @Override + public T next() { + final T tmp = this.Next; + this.Next = null; + return tmp; + } - @Override - public T next() - { - final T tmp = this.Next; - this.Next = null; - return tmp; - } - - @Override - public void remove() - { - // no. - } + @Override + public void remove() { + // no. + } } diff --git a/src/main/java/appeng/me/cluster/IAECluster.java b/src/main/java/appeng/me/cluster/IAECluster.java index caff5a0b..4ee3737d 100644 --- a/src/main/java/appeng/me/cluster/IAECluster.java +++ b/src/main/java/appeng/me/cluster/IAECluster.java @@ -18,18 +18,14 @@ package appeng.me.cluster; +import java.util.Iterator; import appeng.api.networking.IGridHost; -import java.util.Iterator; +public interface IAECluster { + void updateStatus(boolean updateGrid); + void destroy(); -public interface IAECluster -{ - - void updateStatus( boolean updateGrid ); - - void destroy(); - - Iterator getTiles(); + Iterator getTiles(); } diff --git a/src/main/java/appeng/me/cluster/IAEMultiBlock.java b/src/main/java/appeng/me/cluster/IAEMultiBlock.java index 8dc36f99..f8280e09 100644 --- a/src/main/java/appeng/me/cluster/IAEMultiBlock.java +++ b/src/main/java/appeng/me/cluster/IAEMultiBlock.java @@ -18,13 +18,10 @@ package appeng.me.cluster; +public interface IAEMultiBlock { + void disconnect(boolean b); -public interface IAEMultiBlock -{ + IAECluster getCluster(); - void disconnect( boolean b ); - - IAECluster getCluster(); - - boolean isValid(); + boolean isValid(); } diff --git a/src/main/java/appeng/me/cluster/MBCalculator.java b/src/main/java/appeng/me/cluster/MBCalculator.java index 939273f5..6a146b4a 100644 --- a/src/main/java/appeng/me/cluster/MBCalculator.java +++ b/src/main/java/appeng/me/cluster/MBCalculator.java @@ -18,7 +18,6 @@ package appeng.me.cluster; - import appeng.api.util.WorldCoord; import appeng.core.AELog; import appeng.util.Platform; @@ -26,210 +25,190 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public abstract class MBCalculator { + private final IAEMultiBlock target; -public abstract class MBCalculator -{ + public MBCalculator(final IAEMultiBlock t) { + this.target = t; + } - private final IAEMultiBlock target; + public void calculateMultiblock(final World world, final WorldCoord loc) { + if (Platform.isClient()) { + return; + } - public MBCalculator( final IAEMultiBlock t ) - { - this.target = t; - } + try { + final WorldCoord min = loc.copy(); + final WorldCoord max = loc.copy(); - public void calculateMultiblock( final World world, final WorldCoord loc ) - { - if( Platform.isClient() ) - { - return; - } + // find size of MB structure... + while (this.isValidTileAt(world, min.x - 1, min.y, min.z)) { + min.x--; + } + while (this.isValidTileAt(world, min.x, min.y - 1, min.z)) { + min.y--; + } + while (this.isValidTileAt(world, min.x, min.y, min.z - 1)) { + min.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)) { + max.y++; + } + while (this.isValidTileAt(world, max.x, max.y, max.z + 1)) { + max.z++; + } - try - { - final WorldCoord min = loc.copy(); - final WorldCoord max = loc.copy(); + if (this.checkMultiblockScale(min, max)) { + if (this.verifyUnownedRegion(world, min, max)) { + IAECluster c = this.createCluster(world, min, max); - // find size of MB structure... - while( this.isValidTileAt( world, min.x - 1, min.y, min.z ) ) - { - min.x--; - } - while( this.isValidTileAt( world, min.x, min.y - 1, min.z ) ) - { - min.y--; - } - while( this.isValidTileAt( world, min.x, min.y, min.z - 1 ) ) - { - min.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 ) ) - { - max.y++; - } - while( this.isValidTileAt( world, max.x, max.y, max.z + 1 ) ) - { - max.z++; - } + try { + if (!this.verifyInternalStructure(world, min, max)) { + this.disconnect(); + return; + } + } catch (final Exception err) { + this.disconnect(); + return; + } - if( this.checkMultiblockScale( min, max ) ) - { - if( this.verifyUnownedRegion( world, min, max ) ) - { - IAECluster c = this.createCluster( world, min, max ); + boolean updateGrid = false; + final IAECluster cluster = this.target.getCluster(); + if (cluster == null) { + this.updateTiles(c, world, min, max); - try - { - if( !this.verifyInternalStructure( world, min, max ) ) - { - this.disconnect(); - return; - } - } - catch( final Exception err ) - { - this.disconnect(); - return; - } + updateGrid = true; + } else { + c = cluster; + } - boolean updateGrid = false; - final IAECluster cluster = this.target.getCluster(); - if( cluster == null ) - { - this.updateTiles( c, world, min, max ); + c.updateStatus(updateGrid); + return; + } + } + } catch (final Throwable err) { + AELog.debug(err); + } - updateGrid = true; - } - else - { - c = cluster; - } + this.disconnect(); + } - c.updateStatus( updateGrid ); - return; - } - } - } - catch( final Throwable err ) - { - AELog.debug( err ); - } + private boolean isValidTileAt(final World w, final int x, final int y, final int z) { + return this.isValidTile(w.getTileEntity(x, y, z)); + } - this.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); - private boolean isValidTileAt( final World w, final int x, final int y, final int z ) - { - return this.isValidTile( w.getTileEntity( x, y, z ) ); - } + private boolean + verifyUnownedRegion(final World w, final WorldCoord min, final WorldCoord max) { + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (this.verifyUnownedRegionInner( + w, min.x, min.y, min.z, max.x, max.y, max.z, side + )) { + return false; + } + } - /** - * 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 ); + return true; + } - private boolean verifyUnownedRegion( final World w, final WorldCoord min, final WorldCoord max ) - { - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.verifyUnownedRegionInner( w, min.x, min.y, min.z, max.x, max.y, max.z, side ) ) - { - return false; - } - } + /** + * 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); - return true; - } + public abstract boolean + verifyInternalStructure(World worldObj, WorldCoord min, WorldCoord max); - /** - * 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 ); + /** + * disassembles the multi-block. + */ + public abstract void disconnect(); - public abstract boolean verifyInternalStructure( World worldObj, 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(); + /** + * 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); - /** - * 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 ); + private boolean verifyUnownedRegionInner( + final World w, + int minX, + int minY, + int minZ, + int maxX, + int maxY, + int maxZ, + final 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; + } - /** - * 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 ); + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { + final TileEntity te = w.getTileEntity(x, y, z); + if (this.isValidTile(te)) { + return true; + } + } + } + } - private boolean verifyUnownedRegionInner( final World w, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, final 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; - } - - for( int x = minX; x <= maxX; x++ ) - { - for( int y = minY; y <= maxY; y++ ) - { - for( int z = minZ; z <= maxZ; z++ ) - { - final TileEntity te = w.getTileEntity( x, y, z ); - if( this.isValidTile( te ) ) - { - return true; - } - } - } - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCalculator.java index eb985a45..86c69e13 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 appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; @@ -32,117 +33,97 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Iterator; +public class CraftingCPUCalculator extends MBCalculator { + private final TileCraftingTile tqb; + public CraftingCPUCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileCraftingTile) t; + } -public class CraftingCPUCalculator extends MBCalculator -{ + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { + if (max.x - min.x > 16) { + return false; + } - private final TileCraftingTile tqb; + if (max.y - min.y > 16) { + return false; + } - public CraftingCPUCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileCraftingTile) t; - } + return max.z - min.z <= 16; + } - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { - if( max.x - min.x > 16 ) - { - return false; - } + @Override + public IAECluster + createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new CraftingCPUCluster(min, max); + } - if( max.y - min.y > 16 ) - { - return false; - } + @Override + public boolean + verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { + boolean storage = false; - return max.z - min.z <= 16; - } + 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++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(x, y, z); - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new CraftingCPUCluster( min, max ); - } + if (!te.isValid()) { + return false; + } - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { - boolean storage = false; + if (!storage && te instanceof TileCraftingTile) { + storage = ((TileCraftingTile) te).getStorageBytes() > 0; + } + } + } + } - 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++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); + return storage; + } - if( !te.isValid() ) - { - return false; - } + @Override + public void disconnect() { + this.tqb.disconnect(true); + } - if( !storage && te instanceof TileCraftingTile ) - { - storage = ( (TileCraftingTile) te ).getStorageBytes() > 0; - } - } - } - } + @Override + public void updateTiles( + final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max + ) { + final CraftingCPUCluster c = (CraftingCPUCluster) cl; - return storage; - } + 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++) { + final TileCraftingTile te + = (TileCraftingTile) w.getTileEntity(x, y, z); + te.updateStatus(c); + c.addTile(te); + } + } + } - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } + c.done(); - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - final CraftingCPUCluster c = (CraftingCPUCluster) cl; + final Iterator i = c.getTiles(); + while (i.hasNext()) { + final IGridHost gh = i.next(); + final IGridNode n = gh.getGridNode(ForgeDirection.UNKNOWN); + if (n != null) { + final IGrid g = n.getGrid(); + if (g != null) { + g.postEvent(new MENetworkCraftingCpuChange(n)); + return; + } + } + } + } - 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++ ) - { - final TileCraftingTile te = (TileCraftingTile) w.getTileEntity( x, y, z ); - te.updateStatus( c ); - c.addTile( te ); - } - } - } - - c.done(); - - final Iterator i = c.getTiles(); - while( i.hasNext() ) - { - final IGridHost gh = i.next(); - final IGridNode n = gh.getGridNode( ForgeDirection.UNKNOWN ); - if( n != null ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - g.postEvent( new MENetworkCraftingCpuChange( n ) ); - return; - } - } - } - } - - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileCraftingTile; - } + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileCraftingTile; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java index 8ef92c1f..e02ea5b2 100644 --- a/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/CraftingCPUCluster.java @@ -18,6 +18,8 @@ package appeng.me.cluster.implementations; +import java.util.*; +import java.util.Map.Entry; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -58,1271 +60,1148 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import java.util.*; -import java.util.Map.Entry; - - -public final class CraftingCPUCluster implements IAECluster, ICraftingCPU -{ - - private static final String LOG_MARK_AS_COMPLETE = "Completed job for %s."; - - private final WorldCoord min; - private final WorldCoord max; - private final int[] usedOps = new int[3]; - private final Map tasks = new HashMap(); - // INSTANCE sate - private final LinkedList tiles = new LinkedList(); - private final LinkedList storage = new LinkedList(); - private final LinkedList status = new LinkedList(); - private final HashMap, Object> listeners = new HashMap, Object>(); - private ICraftingLink myLastLink; - private String myName = ""; - private boolean isDestroyed = false; - /** - * crafting job info - */ - private MECraftingInventory inventory = new MECraftingInventory(); - private IAEItemStack finalOutput; - private boolean waiting = false; - private IItemList waitingFor = AEApi.instance().storage().createItemList(); - private long availableStorage = 0; - private MachineSource machineSrc = null; - private int accelerator = 0; - private boolean isComplete = true; - private int remainingOperations; - private boolean somethingChanged; - - private long lastTime; - private long elapsedTime; - private long startItemCount; - private long remainingItemCount; - - public CraftingCPUCluster( final WorldCoord min, final WorldCoord max ) - { - this.min = min; - this.max = max; - } - - public boolean isDestroyed() - { - return this.isDestroyed; - } - - public ICraftingLink getLastCraftingLink() - { - return this.myLastLink; - } - - /** - * add a new Listener to the monitor, be sure to properly remove yourself when your done. - */ - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } - - /** - * remove a Listener to the monitor. - */ - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } - - public IMEInventory getInventory() - { - return this.inventory; - } - - @Override - public void updateStatus( final boolean updateGrid ) - { - for( final TileCraftingTile r : this.tiles ) - { - r.updateMeta( true ); - } - } - - @Override - public void destroy() - { - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; - - boolean posted = false; - - for( final TileCraftingTile r : this.tiles ) - { - final IGridNode n = r.getActionableNode(); - if( n != null && !posted ) - { - final IGrid g = n.getGrid(); - if( g != null ) - { - g.postEvent( new MENetworkCraftingCpuChange( n ) ); - posted = true; - } - } - - r.updateStatus( null ); - } - } - - @Override - public Iterator getTiles() - { - return (Iterator) this.tiles.iterator(); - } - - void addTile( final TileCraftingTile te ) - { - if( this.machineSrc == null || te.isCoreBlock() ) - { - this.machineSrc = new MachineSource( te ); - } - - te.setCoreBlock( false ); - te.markDirty(); - this.tiles.push( te ); - - if( te.isStorage() ) - { - this.availableStorage += te.getStorageBytes(); - this.storage.add( te ); - } - else if( te.isStatus() ) - { - this.status.add( (TileCraftingMonitorTile) te ); - } - else if( te.isAccelerator() ) - { - this.accelerator++; - } - } - - public boolean canAccept( final IAEStack input ) - { - if( input instanceof IAEItemStack ) - { - final IAEItemStack is = this.waitingFor.findPrecise( (IAEItemStack) input ); - if( is != null && is.getStackSize() > 0 ) - { - return true; - } - } - return false; - } - - public IAEStack injectItems( final IAEStack input, final Actionable type, final BaseActionSource src ) - { - if( !( input instanceof IAEItemStack ) ) - { - return input; - } - - final IAEItemStack what = (IAEItemStack) input.copy(); - final IAEItemStack is = this.waitingFor.findPrecise( what ); - - if( type == Actionable.SIMULATE )// causes crafting to lock up? - { - if( is != null && is.getStackSize() > 0 ) - { - if( is.getStackSize() >= what.getStackSize() ) - { - if( this.finalOutput.equals( what ) ) - { - if( this.myLastLink != null ) - { - return ( (CraftingLink) this.myLastLink ).injectItems( what.copy(), type ); - } - - return what; // ignore it. - } - - return null; - } - - final IAEItemStack leftOver = what.copy(); - leftOver.decStackSize( is.getStackSize() ); - - final IAEItemStack used = what.copy(); - used.setStackSize( is.getStackSize() ); - - if( this.finalOutput.equals( what ) ) - { - if( this.myLastLink != null ) - { - leftOver.add( ( (CraftingLink) this.myLastLink ).injectItems( used.copy(), type ) ); - return leftOver; - } - - return what; // ignore it. - } - - return leftOver; - } - } - else if( type == Actionable.MODULATE ) - { - if( is != null && is.getStackSize() > 0 ) - { - this.waiting = false; - - this.postChange( what, src ); - - if( is.getStackSize() >= what.getStackSize() ) - { - is.decStackSize( what.getStackSize() ); - - this.updateElapsedTime( what ); - this.markDirty(); - this.postCraftingStatusChange( is ); - - if( this.finalOutput.equals( what ) ) - { - IAEStack leftover = what; - - this.finalOutput.decStackSize( what.getStackSize() ); - - if( this.myLastLink != null ) - { - leftover = ( (CraftingLink) this.myLastLink ).injectItems( what, type ); - } - - if( this.finalOutput.getStackSize() <= 0 ) - { - this.completeJob(); - } - - this.updateCPU(); - - return leftover; // ignore it. - } - - // 2000 - return this.inventory.injectItems( what, type, src ); - } - - final IAEItemStack insert = what.copy(); - insert.setStackSize( is.getStackSize() ); - what.decStackSize( is.getStackSize() ); - - is.setStackSize( 0 ); - - if( this.finalOutput.equals( insert ) ) - { - IAEStack leftover = input; - - this.finalOutput.decStackSize( insert.getStackSize() ); - - if( this.myLastLink != null ) - { - what.add( ( (CraftingLink) this.myLastLink ).injectItems( insert.copy(), type ) ); - leftover = what; - } - - if( this.finalOutput.getStackSize() <= 0 ) - { - this.completeJob(); - } - - this.updateCPU(); - this.markDirty(); - - return leftover; // ignore it. - } - - this.inventory.injectItems( insert, type, src ); - this.markDirty(); - - return what; - } - } - - return input; - } - - private void postChange( final IAEItemStack diff, final BaseActionSource src ) - { - final Iterator, Object>> i = this.getListeners(); - - // protect integrity - if( i.hasNext() ) - { - final ImmutableList single = ImmutableList.of( diff.copy() ); - - while( i.hasNext() ) - { - final Entry, Object> o = i.next(); - final IMEMonitorHandlerReceiver receiver = o.getKey(); - - if( receiver.isValid( o.getValue() ) ) - { - receiver.postChange( null, single, src ); - } - else - { - i.remove(); - } - } - } - - } - - private void markDirty() - { - this.getCore().markDirty(); - } - - private void postCraftingStatusChange( final IAEItemStack diff ) - { - if( this.getGrid() == null ) - { - return; - } - - final CraftingGridCache sg = this.getGrid().getCache( ICraftingGrid.class ); - - if( sg.getInterestManager().containsKey( diff ) ) - { - final Collection list = sg.getInterestManager().get( diff ); - - if( !list.isEmpty() ) - { - for( final CraftingWatcher iw : list ) - - { - iw.getHost().onRequestChange( sg, diff ); - } - } - } - } - - private void completeJob() - { - if( this.myLastLink != null ) - { - ( (CraftingLink) this.myLastLink ).markDone(); - } - - if( AELog.isCraftingLogEnabled() ) - { - final IAEItemStack logStack = this.finalOutput.copy(); - logStack.setStackSize( this.startItemCount ); - AELog.crafting( LOG_MARK_AS_COMPLETE, logStack ); - } - - this.remainingItemCount = 0; - this.startItemCount = 0; - this.lastTime = 0; - this.elapsedTime = 0; - this.isComplete = true; - - } - - private void updateCPU() - { - IAEItemStack send = this.finalOutput; - - if( this.finalOutput != null && this.finalOutput.getStackSize() <= 0 ) - { - send = null; - } - - for( final TileCraftingMonitorTile t : this.status ) - { - t.setJob( send ); - } - } - - private Iterator, Object>> getListeners() - { - return this.listeners.entrySet().iterator(); - } - - private TileCraftingTile getCore() - { - return (TileCraftingTile) this.machineSrc.via; - } - - private IGrid getGrid() - { - for( final TileCraftingTile r : this.tiles ) - { - final IGridNode gn = r.getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - return r.getActionableNode().getGrid(); - } - } - } - - return null; - } - - private boolean canCraft( final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs ) - { - for( IAEItemStack g : condensedInputs ) - { - - if( details.isCraftable() ) - { - boolean found = false; - - for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) ) - { - fuzz = fuzz.copy(); - fuzz.setStackSize( g.getStackSize() ); - final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is != null && is.stackSize == g.getStackSize() ) - { - found = true; - break; - } - else if( is != null ) - { - g = g.copy(); - g.decStackSize( is.stackSize ); - } - } - - if( !found ) - { - return false; - } - } - else - { - final IAEItemStack ais = this.inventory.extractItems( g.copy(), Actionable.SIMULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is == null || is.stackSize < g.getStackSize() ) - { - return false; - } - } - } - - return true; - } - - public void cancel() - { - if( this.myLastLink != null ) - { - this.myLastLink.cancel(); - } - - final IItemList list; - this.getListOfItem( list = AEApi.instance().storage().createItemList(), CraftingItemList.ALL ); - for( final IAEItemStack is : list ) - { - this.postChange( is, this.machineSrc ); - } - - this.isComplete = true; - this.myLastLink = null; - this.tasks.clear(); - - final ImmutableSet items = ImmutableSet.copyOf( this.waitingFor ); - - this.waitingFor.resetStatus(); - - for( final IAEItemStack is : items ) - { - this.postCraftingStatusChange( is ); - } - - this.finalOutput = null; - this.updateCPU(); - - this.storeItems(); // marks dirty - } - - public void updateCraftingLogic( final IGrid grid, final IEnergyGrid eg, final CraftingGridCache cc ) - { - if( !this.getCore().isActive() ) - { - return; - } - - if( this.myLastLink != null ) - { - if( this.myLastLink.isCanceled() ) - { - this.myLastLink = null; - this.cancel(); - } - } - - if( this.isComplete ) - { - if( this.inventory.getItemList().isEmpty() ) - { - return; - } - - this.storeItems(); - return; - } - - this.waiting = false; - 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] ); - final int started = this.remainingOperations; - - if( this.remainingOperations > 0 ) - { - do - { - this.somethingChanged = false; - this.executeCrafting( eg, cc ); - } - 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 ) - { - this.waiting = true; - } - } - - private void executeCrafting( final IEnergyGrid eg, final CraftingGridCache cc ) - { - final Iterator> i = this.tasks.entrySet().iterator(); - - while( i.hasNext() ) - { - final Entry e = i.next(); - - if( e.getValue().value <= 0 ) - { - i.remove(); - continue; - } - - final ICraftingPatternDetails details = e.getKey(); - - if( this.canCraft( details, details.getCondensedInputs() ) ) - { - InventoryCrafting ic = null; - - for( final ICraftingMedium m : cc.getMediums( e.getKey() ) ) - { - if( e.getValue().value <= 0 ) - { - continue; - } - - if( !m.isBusy() ) - { - if( ic == null ) - { - final IAEItemStack[] input = details.getInputs(); - double sum = 0; - - for( final IAEItemStack anInput : input ) - { - if( anInput != null ) - { - sum += anInput.getStackSize(); - } - } - - // power... - 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++ ) - { - if( input[x] != null ) - { - found = false; - - if( details.isCraftable() ) - { - 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() ) ) - { - final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.MODULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is != null ) - { - this.postChange( AEItemStack.create( is ), this.machineSrc ); - ic.setInventorySlotContents( x, is ); - found = true; - break; - } - } - } - } - else - { - final IAEItemStack ais = this.inventory.extractItems( input[x].copy(), Actionable.MODULATE, this.machineSrc ); - final ItemStack is = ais == null ? null : ais.getItemStack(); - - if( is != null ) - { - this.postChange( input[x], this.machineSrc ); - ic.setInventorySlotContents( x, is ); - if( is.stackSize == input[x].getStackSize() ) - { - found = true; - continue; - } - } - } - - if( !found ) - { - break; - } - } - } - - if( !found ) - { - // put stuff back.. - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack is = ic.getStackInSlot( x ); - if( is != null ) - { - this.inventory.injectItems( AEItemStack.create( is ), Actionable.MODULATE, this.machineSrc ); - } - } - ic = null; - break; - } - } - - if( m.pushPattern( details, ic ) ) - { - this.somethingChanged = true; - this.remainingOperations--; - - for( final IAEItemStack out : details.getCondensedOutputs() ) - { - this.postChange( out, this.machineSrc ); - this.waitingFor.add( out.copy() ); - this.postCraftingStatusChange( out.copy() ); - } - - if( details.isCraftable() ) - { - FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.getWorld() ), details.getOutput( ic, this.getWorld() ), ic ); - - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack output = Platform.getContainerItem( ic.getStackInSlot( x ) ); - if( output != null ) - { - final IAEItemStack cItem = AEItemStack.create( output ); - this.postChange( cItem, this.machineSrc ); - this.waitingFor.add( cItem ); - this.postCraftingStatusChange( cItem ); - } - } - } - - ic = null; // hand off complete! - this.markDirty(); - - e.getValue().value--; - if( e.getValue().value <= 0 ) - { - continue; - } - - if( this.remainingOperations == 0 ) - { - return; - } - } - } - } - - if( ic != null ) - { - // put stuff back.. - for( int x = 0; x < ic.getSizeInventory(); x++ ) - { - final ItemStack is = ic.getStackInSlot( x ); - if( is != null ) - { - this.inventory.injectItems( AEItemStack.create( is ), Actionable.MODULATE, this.machineSrc ); - } - } - } - } - } - } - - private void storeItems() - { - final IGrid g = this.getGrid(); - - if( g == null ) - { - return; - } - - final IStorageGrid sg = g.getCache( IStorageGrid.class ); - final IMEInventory ii = sg.getItemInventory(); - - for( IAEItemStack is : this.inventory.getItemList() ) - { - is = this.inventory.extractItems( is.copy(), Actionable.MODULATE, this.machineSrc ); - - if( is != null ) - { - this.postChange( is, this.machineSrc ); - is = ii.injectItems( is, Actionable.MODULATE, this.machineSrc ); - } - - if( is != null ) - { - this.inventory.injectItems( is, Actionable.MODULATE, this.machineSrc ); - } - } - - if( this.inventory.getItemList().isEmpty() ) - { - this.inventory = new MECraftingInventory(); - } - - this.markDirty(); - } - - public ICraftingLink submitJob( final IGrid g, final ICraftingJob job, final BaseActionSource src, final ICraftingRequester requestingMachine ) - { - if( !this.tasks.isEmpty() || !this.waitingFor.isEmpty() ) - { - return null; - } - - if( !( job instanceof CraftingJob ) ) - { - return null; - } - - if( this.isBusy() || !this.isActive() || this.availableStorage < job.getByteTotal() ) - { - return null; - } - - final IStorageGrid sg = g.getCache( IStorageGrid.class ); - final IMEInventory storage = sg.getItemInventory(); - final MECraftingInventory ci = new MECraftingInventory( storage, true, false, false ); - - try - { - this.waitingFor.resetStatus(); - ( (CraftingJob) job ).getTree().setJob( ci, this, src ); - if( ci.commit( src ) ) - { - this.finalOutput = job.getOutput(); - this.waiting = false; - this.isComplete = false; - this.markDirty(); - - this.updateCPU(); - final String craftID = this.generateCraftingID(); - - this.myLastLink = new CraftingLink( this.generateLinkData( craftID, requestingMachine == null, false ), this ); - - this.prepareElapsedTime(); - - if( requestingMachine == null ) - { - return this.myLastLink; - } - - final ICraftingLink whatLink = new CraftingLink( this.generateLinkData( craftID, false, true ), requestingMachine ); - - this.submitLink( this.myLastLink ); - this.submitLink( whatLink ); - - final IItemList list = AEApi.instance().storage().createItemList(); - this.getListOfItem( list, CraftingItemList.ALL ); - for( final IAEItemStack ge : list ) - { - this.postChange( ge, this.machineSrc ); - } - - return whatLink; - } - else - { - this.tasks.clear(); - this.inventory.getItemList().resetStatus(); - } - } - catch( final CraftBranchFailure e ) - { - this.tasks.clear(); - this.inventory.getItemList().resetStatus(); - // AELog.error( e ); - } - - return null; - } - - @Override - public boolean isBusy() - { - final Iterator> i = this.tasks.entrySet().iterator(); - - while( i.hasNext() ) - { - 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() - { - final TileCraftingTile core = this.getCore(); - - if( core == null ) - { - return false; - } - - final IGridNode node = core.getActionableNode(); - if( node == null ) - { - return false; - } - - return node.isActive(); - } - - private String generateCraftingID() - { - final long now = System.currentTimeMillis(); - final int hash = System.identityHashCode( this ); - final 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 ); - } - - private NBTTagCompound generateLinkData( final String craftingID, final boolean standalone, final boolean req ) - { - final NBTTagCompound tag = new NBTTagCompound(); - - tag.setString( "CraftID", craftingID ); - tag.setBoolean( "canceled", false ); - tag.setBoolean( "done", false ); - tag.setBoolean( "standalone", standalone ); - tag.setBoolean( "req", req ); - - return tag; - } - - private void submitLink( final ICraftingLink myLastLink2 ) - { - if( this.getGrid() != null ) - { - final CraftingGridCache cc = this.getGrid().getCache( ICraftingGrid.class ); - cc.addLink( (CraftingLink) myLastLink2 ); - } - } - - public void getListOfItem( final IItemList list, final CraftingItemList whichList ) - { - switch( whichList ) - { - case ACTIVE: - for( final IAEItemStack ais : this.waitingFor ) - { - list.add( ais ); - } - break; - case PENDING: - for( final 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( final IAEItemStack ais : this.waitingFor ) - { - list.add( ais ); - } - - for( final 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( final IAEItemStack extractItems ) - { - this.inventory.injectItems( extractItems, Actionable.MODULATE, null ); - } - - public void addEmitable( final IAEItemStack i ) - { - this.waitingFor.add( i ); - this.postCraftingStatusChange( i ); - } - - public void addCrafting( final ICraftingPatternDetails details, final long crafts ) - { - TaskProgress i = this.tasks.get( details ); - - if( i == null ) - { - this.tasks.put( details, i = new TaskProgress() ); - } - - i.value += crafts; - } - - public IAEItemStack getItemStack( final IAEItemStack what, final CraftingItemList storage2 ) - { - IAEItemStack is; - - switch( storage2 ) - { - 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 ); - - for( final Entry t : this.tasks.entrySet() ) - { - for( final IAEItemStack ais : t.getKey().getCondensedOutputs() ) - { - if( ais.equals( is ) ) - { - is.setStackSize( is.getStackSize() + ais.getStackSize() * t.getValue().value ); - } - } - } - - break; - default: - case ALL: - throw new IllegalStateException( "Invalid Operation" ); - } - - if( is != null ) - { - return is.copy(); - } - - is = what.copy(); - is.setStackSize( 0 ); - return is; - } - - public void writeToNBT( final 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 ) - { - final NBTTagCompound link = new NBTTagCompound(); - this.myLastLink.writeToNBT( link ); - data.setTag( "link", link ); - } - - final NBTTagList list = new NBTTagList(); - for( final Entry e : this.tasks.entrySet() ) - { - final NBTTagCompound item = this.writeItem( AEItemStack.create( e.getKey().getPattern() ) ); - item.setLong( "craftingProgress", e.getValue().value ); - list.appendTag( item ); - } - data.setTag( "tasks", list ); - - data.setTag( "waitingFor", this.writeList( this.waitingFor ) ); - - data.setLong( "elapsedTime", this.getElapsedTime() ); - data.setLong( "startItemCount", this.getStartItemCount() ); - data.setLong( "remainingItemCount", this.getRemainingItemCount() ); - } - - private NBTTagCompound writeItem( final IAEItemStack finalOutput2 ) - { - final NBTTagCompound out = new NBTTagCompound(); - - if( finalOutput2 != null ) - { - finalOutput2.writeToNBT( out ); - } - - return out; - } - - private NBTTagList writeList( final IItemList myList ) - { - final NBTTagList out = new NBTTagList(); - - for( final IAEItemStack ais : myList ) - { - out.appendTag( this.writeItem( ais ) ); - } - - return out; - } - - void done() - { - final TileCraftingTile core = this.getCore(); - - core.setCoreBlock( true ); - - if( core.getPreviousState() != null ) - { - this.readFromNBT( core.getPreviousState() ); - core.setPreviousState( null ); - } - - this.updateCPU(); - this.updateName(); - } - - public void readFromNBT( final NBTTagCompound data ) - { - this.finalOutput = AEItemStack.loadItemStackFromNBT( (NBTTagCompound) data.getTag( "finalOutput" ) ); - for( final 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" ) ) - { - final NBTTagCompound link = data.getCompoundTag( "link" ); - this.myLastLink = new CraftingLink( link, this ); - this.submitLink( this.myLastLink ); - } - - final NBTTagList list = data.getTagList( "tasks", 10 ); - for( int x = 0; x < list.tagCount(); x++ ) - { - final NBTTagCompound item = list.getCompoundTagAt( x ); - final IAEItemStack pattern = AEItemStack.loadItemStackFromNBT( item ); - if( pattern != null && pattern.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); - final ICraftingPatternDetails details = cpi.getPatternForItem( pattern.getItemStack(), this.getWorld() ); - if( details != null ) - { - final TaskProgress tp = new TaskProgress(); - tp.value = item.getLong( "craftingProgress" ); - this.tasks.put( details, tp ); - } - } - } - - this.waitingFor = this.readList( (NBTTagList) data.getTag( "waitingFor" ) ); - for( final IAEItemStack is : this.waitingFor ) - { - this.postCraftingStatusChange( is.copy() ); - } - - this.lastTime = System.nanoTime(); - this.elapsedTime = data.getLong( "elapsedTime" ); - this.startItemCount = data.getLong( "startItemCount" ); - this.remainingItemCount = data.getLong( "remainingItemCount" ); - } - - public void updateName() - { - this.myName = ""; - for( final TileCraftingTile te : this.tiles ) - { - - if( te.hasCustomName() ) - { - if( this.myName.length() > 0 ) - { - this.myName += ' ' + te.getCustomName(); - } - else - { - this.myName = te.getCustomName(); - } - } - } - } - - private IItemList readList( final NBTTagList tag ) - { - final IItemList out = AEApi.instance().storage().createItemList(); - - if( tag == null ) - { - return out; - } - - for( int x = 0; x < tag.tagCount(); x++ ) - { - final IAEItemStack ais = AEItemStack.loadItemStackFromNBT( tag.getCompoundTagAt( x ) ); - if( ais != null ) - { - out.add( ais ); - } - } - - return out; - } - - private World getWorld() - { - return this.getCore().getWorldObj(); - } - - public boolean isMaking( final IAEItemStack what ) - { - final IAEItemStack wat = this.waitingFor.findPrecise( what ); - return wat != null && wat.getStackSize() > 0; - } - - public void breakCluster() - { - final TileCraftingTile t = this.getCore(); - - if( t != null ) - { - t.breakCluster(); - } - } - - private void prepareElapsedTime() - { - this.lastTime = System.nanoTime(); - this.elapsedTime = 0; - - final IItemList list = AEApi.instance().storage().createItemList(); - - this.getListOfItem( list, CraftingItemList.ACTIVE ); - this.getListOfItem( list, CraftingItemList.PENDING ); - - int itemCount = 0; - for( final IAEItemStack ge : list ) - { - itemCount += ge.getStackSize(); - } - - this.startItemCount = itemCount; - this.remainingItemCount = itemCount; - } - - private void updateElapsedTime( final IAEItemStack is ) - { - final long nextStartTime = System.nanoTime(); - this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; - this.lastTime = nextStartTime; - this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize(); - } - - public long getElapsedTime() - { - return this.elapsedTime; - } - - public long getRemainingItemCount() - { - return this.remainingItemCount; - } - - public long getStartItemCount() - { - return this.startItemCount; - } - - private static class TaskProgress - { - private long value; - } +public final class CraftingCPUCluster implements IAECluster, ICraftingCPU { + private static final String LOG_MARK_AS_COMPLETE = "Completed job for %s."; + + private final WorldCoord min; + private final WorldCoord max; + private final int[] usedOps = new int[3]; + private final Map tasks + = new HashMap(); + // INSTANCE sate + private final LinkedList tiles = new LinkedList(); + private final LinkedList storage + = new LinkedList(); + private final LinkedList status + = new LinkedList(); + private final HashMap, Object> listeners + = new HashMap, Object>(); + private ICraftingLink myLastLink; + private String myName = ""; + private boolean isDestroyed = false; + /** + * crafting job info + */ + private MECraftingInventory inventory = new MECraftingInventory(); + private IAEItemStack finalOutput; + private boolean waiting = false; + private IItemList waitingFor + = AEApi.instance().storage().createItemList(); + private long availableStorage = 0; + private MachineSource machineSrc = null; + private int accelerator = 0; + private boolean isComplete = true; + private int remainingOperations; + private boolean somethingChanged; + + private long lastTime; + private long elapsedTime; + private long startItemCount; + private long remainingItemCount; + + public CraftingCPUCluster(final WorldCoord min, final WorldCoord max) { + this.min = min; + this.max = max; + } + + public boolean isDestroyed() { + return this.isDestroyed; + } + + public ICraftingLink getLastCraftingLink() { + return this.myLastLink; + } + + /** + * add a new Listener to the monitor, be sure to properly remove yourself when your + * done. + */ + @Override + public void addListener( + final IMEMonitorHandlerReceiver l, final Object verificationToken + ) { + this.listeners.put(l, verificationToken); + } + + /** + * remove a Listener to the monitor. + */ + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } + + public IMEInventory getInventory() { + return this.inventory; + } + + @Override + public void updateStatus(final boolean updateGrid) { + for (final TileCraftingTile r : this.tiles) { + r.updateMeta(true); + } + } + + @Override + public void destroy() { + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; + + boolean posted = false; + + for (final TileCraftingTile r : this.tiles) { + final IGridNode n = r.getActionableNode(); + if (n != null && !posted) { + final IGrid g = n.getGrid(); + if (g != null) { + g.postEvent(new MENetworkCraftingCpuChange(n)); + posted = true; + } + } + + r.updateStatus(null); + } + } + + @Override + public Iterator getTiles() { + return (Iterator) this.tiles.iterator(); + } + + void addTile(final TileCraftingTile te) { + if (this.machineSrc == null || te.isCoreBlock()) { + this.machineSrc = new MachineSource(te); + } + + te.setCoreBlock(false); + te.markDirty(); + this.tiles.push(te); + + if (te.isStorage()) { + this.availableStorage += te.getStorageBytes(); + this.storage.add(te); + } else if (te.isStatus()) { + this.status.add((TileCraftingMonitorTile) te); + } else if (te.isAccelerator()) { + this.accelerator++; + } + } + + public boolean canAccept(final IAEStack input) { + if (input instanceof IAEItemStack) { + final IAEItemStack is = this.waitingFor.findPrecise((IAEItemStack) input); + if (is != null && is.getStackSize() > 0) { + return true; + } + } + return false; + } + + public IAEStack + injectItems(final IAEStack input, final Actionable type, final BaseActionSource src) { + if (!(input instanceof IAEItemStack)) { + return input; + } + + final IAEItemStack what = (IAEItemStack) input.copy(); + final IAEItemStack is = this.waitingFor.findPrecise(what); + + if (type == Actionable.SIMULATE) // causes crafting to lock up? + { + if (is != null && is.getStackSize() > 0) { + if (is.getStackSize() >= what.getStackSize()) { + if (this.finalOutput.equals(what)) { + if (this.myLastLink != null) { + return ((CraftingLink) this.myLastLink) + .injectItems(what.copy(), type); + } + + return what; // ignore it. + } + + return null; + } + + final IAEItemStack leftOver = what.copy(); + leftOver.decStackSize(is.getStackSize()); + + final IAEItemStack used = what.copy(); + used.setStackSize(is.getStackSize()); + + if (this.finalOutput.equals(what)) { + if (this.myLastLink != null) { + leftOver.add(((CraftingLink) this.myLastLink) + .injectItems(used.copy(), type)); + return leftOver; + } + + return what; // ignore it. + } + + return leftOver; + } + } else if (type == Actionable.MODULATE) { + if (is != null && is.getStackSize() > 0) { + this.waiting = false; + + this.postChange(what, src); + + if (is.getStackSize() >= what.getStackSize()) { + is.decStackSize(what.getStackSize()); + + this.updateElapsedTime(what); + this.markDirty(); + this.postCraftingStatusChange(is); + + if (this.finalOutput.equals(what)) { + IAEStack leftover = what; + + this.finalOutput.decStackSize(what.getStackSize()); + + if (this.myLastLink != null) { + leftover = ((CraftingLink) this.myLastLink) + .injectItems(what, type); + } + + if (this.finalOutput.getStackSize() <= 0) { + this.completeJob(); + } + + this.updateCPU(); + + return leftover; // ignore it. + } + + // 2000 + return this.inventory.injectItems(what, type, src); + } + + final IAEItemStack insert = what.copy(); + insert.setStackSize(is.getStackSize()); + what.decStackSize(is.getStackSize()); + + is.setStackSize(0); + + if (this.finalOutput.equals(insert)) { + IAEStack leftover = input; + + this.finalOutput.decStackSize(insert.getStackSize()); + + if (this.myLastLink != null) { + what.add(((CraftingLink) this.myLastLink) + .injectItems(insert.copy(), type)); + leftover = what; + } + + if (this.finalOutput.getStackSize() <= 0) { + this.completeJob(); + } + + this.updateCPU(); + this.markDirty(); + + return leftover; // ignore it. + } + + this.inventory.injectItems(insert, type, src); + this.markDirty(); + + return what; + } + } + + return input; + } + + private void postChange(final IAEItemStack diff, final BaseActionSource src) { + final Iterator, Object>> i + = this.getListeners(); + + // protect integrity + if (i.hasNext()) { + final ImmutableList single = ImmutableList.of(diff.copy()); + + while (i.hasNext()) { + final Entry, Object> o = i.next(); + final IMEMonitorHandlerReceiver receiver = o.getKey(); + + if (receiver.isValid(o.getValue())) { + receiver.postChange(null, single, src); + } else { + i.remove(); + } + } + } + } + + private void markDirty() { + this.getCore().markDirty(); + } + + private void postCraftingStatusChange(final IAEItemStack diff) { + if (this.getGrid() == null) { + return; + } + + final CraftingGridCache sg = this.getGrid().getCache(ICraftingGrid.class); + + if (sg.getInterestManager().containsKey(diff)) { + final Collection list = sg.getInterestManager().get(diff); + + if (!list.isEmpty()) { + for (final CraftingWatcher iw : list) + + { + iw.getHost().onRequestChange(sg, diff); + } + } + } + } + + private void completeJob() { + if (this.myLastLink != null) { + ((CraftingLink) this.myLastLink).markDone(); + } + + if (AELog.isCraftingLogEnabled()) { + final IAEItemStack logStack = this.finalOutput.copy(); + logStack.setStackSize(this.startItemCount); + AELog.crafting(LOG_MARK_AS_COMPLETE, logStack); + } + + this.remainingItemCount = 0; + this.startItemCount = 0; + this.lastTime = 0; + this.elapsedTime = 0; + this.isComplete = true; + } + + private void updateCPU() { + IAEItemStack send = this.finalOutput; + + if (this.finalOutput != null && this.finalOutput.getStackSize() <= 0) { + send = null; + } + + for (final TileCraftingMonitorTile t : this.status) { + t.setJob(send); + } + } + + private Iterator, Object>> + getListeners() { + return this.listeners.entrySet().iterator(); + } + + private TileCraftingTile getCore() { + return (TileCraftingTile) this.machineSrc.via; + } + + private IGrid getGrid() { + for (final TileCraftingTile r : this.tiles) { + final IGridNode gn = r.getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + return r.getActionableNode().getGrid(); + } + } + } + + return null; + } + + private boolean canCraft( + final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs + ) { + for (IAEItemStack g : condensedInputs) { + if (details.isCraftable()) { + boolean found = false; + + for (IAEItemStack fuzz : + this.inventory.getItemList().findFuzzy(g, FuzzyMode.IGNORE_ALL)) { + fuzz = fuzz.copy(); + fuzz.setStackSize(g.getStackSize()); + final IAEItemStack ais = this.inventory.extractItems( + fuzz, Actionable.SIMULATE, this.machineSrc + ); + final ItemStack is = ais == null ? null : ais.getItemStack(); + + if (is != null && is.stackSize == g.getStackSize()) { + found = true; + break; + } else if (is != null) { + g = g.copy(); + g.decStackSize(is.stackSize); + } + } + + if (!found) { + return false; + } + } else { + final IAEItemStack ais = this.inventory.extractItems( + g.copy(), Actionable.SIMULATE, this.machineSrc + ); + final ItemStack is = ais == null ? null : ais.getItemStack(); + + if (is == null || is.stackSize < g.getStackSize()) { + return false; + } + } + } + + return true; + } + + public void cancel() { + if (this.myLastLink != null) { + this.myLastLink.cancel(); + } + + final IItemList list; + this.getListOfItem( + list = AEApi.instance().storage().createItemList(), CraftingItemList.ALL + ); + for (final IAEItemStack is : list) { + this.postChange(is, this.machineSrc); + } + + this.isComplete = true; + this.myLastLink = null; + this.tasks.clear(); + + final ImmutableSet items = ImmutableSet.copyOf(this.waitingFor); + + this.waitingFor.resetStatus(); + + for (final IAEItemStack is : items) { + this.postCraftingStatusChange(is); + } + + this.finalOutput = null; + this.updateCPU(); + + this.storeItems(); // marks dirty + } + + public void updateCraftingLogic( + final IGrid grid, final IEnergyGrid eg, final CraftingGridCache cc + ) { + if (!this.getCore().isActive()) { + return; + } + + if (this.myLastLink != null) { + if (this.myLastLink.isCanceled()) { + this.myLastLink = null; + this.cancel(); + } + } + + if (this.isComplete) { + if (this.inventory.getItemList().isEmpty()) { + return; + } + + this.storeItems(); + return; + } + + this.waiting = false; + 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]); + final int started = this.remainingOperations; + + if (this.remainingOperations > 0) { + do { + this.somethingChanged = false; + this.executeCrafting(eg, cc); + } 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) { + this.waiting = true; + } + } + + private void executeCrafting(final IEnergyGrid eg, final CraftingGridCache cc) { + final Iterator> i + = this.tasks.entrySet().iterator(); + + while (i.hasNext()) { + final Entry e = i.next(); + + if (e.getValue().value <= 0) { + i.remove(); + continue; + } + + final ICraftingPatternDetails details = e.getKey(); + + if (this.canCraft(details, details.getCondensedInputs())) { + InventoryCrafting ic = null; + + for (final ICraftingMedium m : cc.getMediums(e.getKey())) { + if (e.getValue().value <= 0) { + continue; + } + + if (!m.isBusy()) { + if (ic == null) { + final IAEItemStack[] input = details.getInputs(); + double sum = 0; + + for (final IAEItemStack anInput : input) { + if (anInput != null) { + sum += anInput.getStackSize(); + } + } + + // power... + 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++) { + if (input[x] != null) { + found = false; + + if (details.isCraftable()) { + 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() + )) { + final IAEItemStack ais + = this.inventory.extractItems( + fuzz, + Actionable.MODULATE, + this.machineSrc + ); + final ItemStack is = ais == null + ? null + : ais.getItemStack(); + + if (is != null) { + this.postChange( + AEItemStack.create(is), + this.machineSrc + ); + ic.setInventorySlotContents(x, is); + found = true; + break; + } + } + } + } else { + final IAEItemStack ais + = this.inventory.extractItems( + input[x].copy(), + Actionable.MODULATE, + this.machineSrc + ); + final ItemStack is + = ais == null ? null : ais.getItemStack(); + + if (is != null) { + this.postChange(input[x], this.machineSrc); + ic.setInventorySlotContents(x, is); + if (is.stackSize == input[x].getStackSize()) { + found = true; + continue; + } + } + } + + if (!found) { + break; + } + } + } + + if (!found) { + // put stuff back.. + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack is = ic.getStackInSlot(x); + if (is != null) { + this.inventory.injectItems( + AEItemStack.create(is), + Actionable.MODULATE, + this.machineSrc + ); + } + } + ic = null; + break; + } + } + + if (m.pushPattern(details, ic)) { + this.somethingChanged = true; + this.remainingOperations--; + + for (final IAEItemStack out : details.getCondensedOutputs()) { + this.postChange(out, this.machineSrc); + this.waitingFor.add(out.copy()); + this.postCraftingStatusChange(out.copy()); + } + + if (details.isCraftable()) { + FMLCommonHandler.instance().firePlayerCraftingEvent( + Platform.getPlayer((WorldServer) this.getWorld()), + details.getOutput(ic, this.getWorld()), + ic + ); + + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack output + = Platform.getContainerItem(ic.getStackInSlot(x)); + if (output != null) { + final IAEItemStack cItem + = AEItemStack.create(output); + this.postChange(cItem, this.machineSrc); + this.waitingFor.add(cItem); + this.postCraftingStatusChange(cItem); + } + } + } + + ic = null; // hand off complete! + this.markDirty(); + + e.getValue().value--; + if (e.getValue().value <= 0) { + continue; + } + + if (this.remainingOperations == 0) { + return; + } + } + } + } + + if (ic != null) { + // put stuff back.. + for (int x = 0; x < ic.getSizeInventory(); x++) { + final ItemStack is = ic.getStackInSlot(x); + if (is != null) { + this.inventory.injectItems( + AEItemStack.create(is), + Actionable.MODULATE, + this.machineSrc + ); + } + } + } + } + } + } + + private void storeItems() { + final IGrid g = this.getGrid(); + + if (g == null) { + return; + } + + final IStorageGrid sg = g.getCache(IStorageGrid.class); + final IMEInventory ii = sg.getItemInventory(); + + for (IAEItemStack is : this.inventory.getItemList()) { + is = this.inventory.extractItems( + is.copy(), Actionable.MODULATE, this.machineSrc + ); + + if (is != null) { + this.postChange(is, this.machineSrc); + is = ii.injectItems(is, Actionable.MODULATE, this.machineSrc); + } + + if (is != null) { + this.inventory.injectItems(is, Actionable.MODULATE, this.machineSrc); + } + } + + if (this.inventory.getItemList().isEmpty()) { + this.inventory = new MECraftingInventory(); + } + + this.markDirty(); + } + + public ICraftingLink submitJob( + final IGrid g, + final ICraftingJob job, + final BaseActionSource src, + final ICraftingRequester requestingMachine + ) { + if (!this.tasks.isEmpty() || !this.waitingFor.isEmpty()) { + return null; + } + + if (!(job instanceof CraftingJob)) { + return null; + } + + if (this.isBusy() || !this.isActive() + || this.availableStorage < job.getByteTotal()) { + return null; + } + + final IStorageGrid sg = g.getCache(IStorageGrid.class); + final IMEInventory storage = sg.getItemInventory(); + final MECraftingInventory ci + = new MECraftingInventory(storage, true, false, false); + + try { + this.waitingFor.resetStatus(); + ((CraftingJob) job).getTree().setJob(ci, this, src); + if (ci.commit(src)) { + this.finalOutput = job.getOutput(); + this.waiting = false; + this.isComplete = false; + this.markDirty(); + + this.updateCPU(); + final String craftID = this.generateCraftingID(); + + this.myLastLink = new CraftingLink( + this.generateLinkData(craftID, requestingMachine == null, false), this + ); + + this.prepareElapsedTime(); + + if (requestingMachine == null) { + return this.myLastLink; + } + + final ICraftingLink whatLink = new CraftingLink( + this.generateLinkData(craftID, false, true), requestingMachine + ); + + this.submitLink(this.myLastLink); + this.submitLink(whatLink); + + final IItemList list + = AEApi.instance().storage().createItemList(); + this.getListOfItem(list, CraftingItemList.ALL); + for (final IAEItemStack ge : list) { + this.postChange(ge, this.machineSrc); + } + + return whatLink; + } else { + this.tasks.clear(); + this.inventory.getItemList().resetStatus(); + } + } catch (final CraftBranchFailure e) { + this.tasks.clear(); + this.inventory.getItemList().resetStatus(); + // AELog.error( e ); + } + + return null; + } + + @Override + public boolean isBusy() { + final Iterator> i + = this.tasks.entrySet().iterator(); + + while (i.hasNext()) { + 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() { + final TileCraftingTile core = this.getCore(); + + if (core == null) { + return false; + } + + final IGridNode node = core.getActionableNode(); + if (node == null) { + return false; + } + + return node.isActive(); + } + + private String generateCraftingID() { + final long now = System.currentTimeMillis(); + final int hash = System.identityHashCode(this); + final 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); + } + + private NBTTagCompound generateLinkData( + final String craftingID, final boolean standalone, final boolean req + ) { + final NBTTagCompound tag = new NBTTagCompound(); + + tag.setString("CraftID", craftingID); + tag.setBoolean("canceled", false); + tag.setBoolean("done", false); + tag.setBoolean("standalone", standalone); + tag.setBoolean("req", req); + + return tag; + } + + private void submitLink(final ICraftingLink myLastLink2) { + if (this.getGrid() != null) { + final CraftingGridCache cc = this.getGrid().getCache(ICraftingGrid.class); + cc.addLink((CraftingLink) myLastLink2); + } + } + + public void + getListOfItem(final IItemList list, final CraftingItemList whichList) { + switch (whichList) { + case ACTIVE: + for (final IAEItemStack ais : this.waitingFor) { + list.add(ais); + } + break; + case PENDING: + for (final 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 (final IAEItemStack ais : this.waitingFor) { + list.add(ais); + } + + for (final 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(final IAEItemStack extractItems) { + this.inventory.injectItems(extractItems, Actionable.MODULATE, null); + } + + public void addEmitable(final IAEItemStack i) { + this.waitingFor.add(i); + this.postCraftingStatusChange(i); + } + + public void addCrafting(final ICraftingPatternDetails details, final long crafts) { + TaskProgress i = this.tasks.get(details); + + if (i == null) { + this.tasks.put(details, i = new TaskProgress()); + } + + i.value += crafts; + } + + public IAEItemStack + getItemStack(final IAEItemStack what, final CraftingItemList storage2) { + IAEItemStack is; + + switch (storage2) { + 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); + + for (final Entry t : + this.tasks.entrySet()) { + for (final IAEItemStack ais : t.getKey().getCondensedOutputs()) { + if (ais.equals(is)) { + is.setStackSize( + is.getStackSize() + + ais.getStackSize() * t.getValue().value + ); + } + } + } + + break; + default: + case ALL: + throw new IllegalStateException("Invalid Operation"); + } + + if (is != null) { + return is.copy(); + } + + is = what.copy(); + is.setStackSize(0); + return is; + } + + public void writeToNBT(final 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) { + final NBTTagCompound link = new NBTTagCompound(); + this.myLastLink.writeToNBT(link); + data.setTag("link", link); + } + + final NBTTagList list = new NBTTagList(); + for (final Entry e : + this.tasks.entrySet()) { + final NBTTagCompound item + = this.writeItem(AEItemStack.create(e.getKey().getPattern())); + item.setLong("craftingProgress", e.getValue().value); + list.appendTag(item); + } + data.setTag("tasks", list); + + data.setTag("waitingFor", this.writeList(this.waitingFor)); + + data.setLong("elapsedTime", this.getElapsedTime()); + data.setLong("startItemCount", this.getStartItemCount()); + data.setLong("remainingItemCount", this.getRemainingItemCount()); + } + + private NBTTagCompound writeItem(final IAEItemStack finalOutput2) { + final NBTTagCompound out = new NBTTagCompound(); + + if (finalOutput2 != null) { + finalOutput2.writeToNBT(out); + } + + return out; + } + + private NBTTagList writeList(final IItemList myList) { + final NBTTagList out = new NBTTagList(); + + for (final IAEItemStack ais : myList) { + out.appendTag(this.writeItem(ais)); + } + + return out; + } + + void done() { + final TileCraftingTile core = this.getCore(); + + core.setCoreBlock(true); + + if (core.getPreviousState() != null) { + this.readFromNBT(core.getPreviousState()); + core.setPreviousState(null); + } + + this.updateCPU(); + this.updateName(); + } + + public void readFromNBT(final NBTTagCompound data) { + this.finalOutput = AEItemStack.loadItemStackFromNBT((NBTTagCompound + ) data.getTag("finalOutput")); + for (final 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")) { + final NBTTagCompound link = data.getCompoundTag("link"); + this.myLastLink = new CraftingLink(link, this); + this.submitLink(this.myLastLink); + } + + final NBTTagList list = data.getTagList("tasks", 10); + for (int x = 0; x < list.tagCount(); x++) { + final NBTTagCompound item = list.getCompoundTagAt(x); + final IAEItemStack pattern = AEItemStack.loadItemStackFromNBT(item); + if (pattern != null && pattern.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem cpi = (ICraftingPatternItem) pattern.getItem(); + final ICraftingPatternDetails details + = cpi.getPatternForItem(pattern.getItemStack(), this.getWorld()); + if (details != null) { + final TaskProgress tp = new TaskProgress(); + tp.value = item.getLong("craftingProgress"); + this.tasks.put(details, tp); + } + } + } + + this.waitingFor = this.readList((NBTTagList) data.getTag("waitingFor")); + for (final IAEItemStack is : this.waitingFor) { + this.postCraftingStatusChange(is.copy()); + } + + this.lastTime = System.nanoTime(); + this.elapsedTime = data.getLong("elapsedTime"); + this.startItemCount = data.getLong("startItemCount"); + this.remainingItemCount = data.getLong("remainingItemCount"); + } + + public void updateName() { + this.myName = ""; + for (final TileCraftingTile te : this.tiles) { + if (te.hasCustomName()) { + if (this.myName.length() > 0) { + this.myName += ' ' + te.getCustomName(); + } else { + this.myName = te.getCustomName(); + } + } + } + } + + private IItemList readList(final NBTTagList tag) { + final IItemList out = AEApi.instance().storage().createItemList(); + + if (tag == null) { + return out; + } + + for (int x = 0; x < tag.tagCount(); x++) { + final IAEItemStack ais + = AEItemStack.loadItemStackFromNBT(tag.getCompoundTagAt(x)); + if (ais != null) { + out.add(ais); + } + } + + return out; + } + + private World getWorld() { + return this.getCore().getWorldObj(); + } + + public boolean isMaking(final IAEItemStack what) { + final IAEItemStack wat = this.waitingFor.findPrecise(what); + return wat != null && wat.getStackSize() > 0; + } + + public void breakCluster() { + final TileCraftingTile t = this.getCore(); + + if (t != null) { + t.breakCluster(); + } + } + + private void prepareElapsedTime() { + this.lastTime = System.nanoTime(); + this.elapsedTime = 0; + + final IItemList list = AEApi.instance().storage().createItemList(); + + this.getListOfItem(list, CraftingItemList.ACTIVE); + this.getListOfItem(list, CraftingItemList.PENDING); + + int itemCount = 0; + for (final IAEItemStack ge : list) { + itemCount += ge.getStackSize(); + } + + this.startItemCount = itemCount; + this.remainingItemCount = itemCount; + } + + private void updateElapsedTime(final IAEItemStack is) { + final long nextStartTime = System.nanoTime(); + this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; + this.lastTime = nextStartTime; + this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize(); + } + + public long getElapsedTime() { + return this.elapsedTime; + } + + public long getRemainingItemCount() { + return this.remainingItemCount; + } + + public long getStartItemCount() { + return this.startItemCount; + } + + private static class TaskProgress { private 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 6e127730..00b02e0d 100644 --- a/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/QuantumCalculator.java @@ -18,7 +18,6 @@ package appeng.me.cluster.implementations; - import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; import appeng.api.definitions.IBlocks; @@ -32,141 +31,121 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; +public class QuantumCalculator extends MBCalculator { + private final TileQuantumBridge tqb; -public class QuantumCalculator extends MBCalculator -{ + public QuantumCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileQuantumBridge) t; + } - private final TileQuantumBridge tqb; + @Override + public boolean checkMultiblockScale(final WorldCoord min, final WorldCoord max) { + if ((max.x - min.x + 1) * (max.y - min.y + 1) * (max.z - min.z + 1) == 9) { + final int ones = ((max.x - min.x) == 0 ? 1 : 0) + + ((max.y - min.y) == 0 ? 1 : 0) + ((max.z - min.z) == 0 ? 1 : 0); - public QuantumCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileQuantumBridge) t; - } + final int threes = ((max.x - min.x) == 2 ? 1 : 0) + + ((max.y - min.y) == 2 ? 1 : 0) + ((max.z - min.z) == 2 ? 1 : 0); - @Override - public boolean checkMultiblockScale( final WorldCoord min, final WorldCoord max ) - { + return ones == 1 && threes == 2; + } + return false; + } - if( ( max.x - min.x + 1 ) * ( max.y - min.y + 1 ) * ( max.z - min.z + 1 ) == 9 ) - { - final int ones = ( ( max.x - min.x ) == 0 ? 1 : 0 ) + ( ( max.y - min.y ) == 0 ? 1 : 0 ) + ( ( max.z - min.z ) == 0 ? 1 : 0 ); + @Override + public IAECluster + createCluster(final World w, final WorldCoord min, final WorldCoord max) { + return new QuantumCluster(min, max); + } - final int threes = ( ( max.x - min.x ) == 2 ? 1 : 0 ) + ( ( max.y - min.y ) == 2 ? 1 : 0 ) + ( ( max.z - min.z ) == 2 ? 1 : 0 ); + @Override + public boolean + verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { + byte num = 0; - return ones == 1 && threes == 2; - } - return 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++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(x, y, z); - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new QuantumCluster( min, max ); - } + if (!te.isValid()) { + return false; + } - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { + num++; + final IBlocks blocks = AEApi.instance().definitions().blocks(); + if (num == 5) { + if (!this.isBlockAtLocation(w, x, y, z, blocks.quantumLink())) { + return false; + } + } else { + if (!this.isBlockAtLocation(w, x, y, z, blocks.quantumRing())) { + return false; + } + } + } + } + } + return true; + } - byte num = 0; + @Override + public void disconnect() { + this.tqb.disconnect(true); + } - 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++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); + @Override + public void updateTiles( + final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max + ) { + byte num = 0; + byte ringNum = 0; + final QuantumCluster c = (QuantumCluster) cl; - if( !te.isValid() ) - { - return 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++) { + final TileQuantumBridge te + = (TileQuantumBridge) w.getTileEntity(x, y, z); - num++; - final IBlocks blocks = AEApi.instance().definitions().blocks(); - if( num == 5 ) - { - if( !this.isBlockAtLocation( w, x, y, z, blocks.quantumLink() ) ) - { - return false; - } - } - else - { - if( !this.isBlockAtLocation( w, x, y, z, blocks.quantumRing() ) ) - { - return false; - } - } - } - } - } - return true; - } + num++; + final byte flags; + if (num == 5) { + flags = num; + c.setCenter(te); + } else { + if (num == 1 || num == 3 || num == 7 || num == 9) { + flags = (byte) (this.tqb.getCorner() | num); + } else { + flags = num; + } + c.getRing()[ringNum] = te; + ringNum++; + } - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } + te.updateStatus(c, flags, true); + } + } + } + } - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - byte num = 0; - byte ringNum = 0; - final QuantumCluster c = (QuantumCluster) cl; + @Override + public boolean isValidTile(final TileEntity te) { + return te instanceof TileQuantumBridge; + } - 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++ ) - { - final TileQuantumBridge te = (TileQuantumBridge) w.getTileEntity( x, y, z ); + private boolean isBlockAtLocation( + final IBlockAccess w, + final int x, + final int y, + final int z, + final IBlockDefinition def + ) { + for (final Block block : def.maybeBlock().asSet()) { + return block == w.getBlock(x, y, z); + } - num++; - final byte flags; - if( num == 5 ) - { - flags = num; - c.setCenter( te ); - } - else - { - if( num == 1 || num == 3 || num == 7 || num == 9 ) - { - flags = (byte) ( this.tqb.getCorner() | num ); - } - else - { - flags = num; - } - c.getRing()[ringNum] = te; - ringNum++; - } - - te.updateStatus( c, flags, true ); - } - } - } - } - - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileQuantumBridge; - } - - private boolean isBlockAtLocation( final IBlockAccess w, final int x, final int y, final int z, final IBlockDefinition def ) - { - for( final Block block : def.maybeBlock().asSet() ) - { - return block == w.getBlock( x, y, z ); - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java b/src/main/java/appeng/me/cluster/implementations/QuantumCluster.java index dd9d6f49..ee05bc33 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 appeng.api.AEApi; import appeng.api.events.LocatableEventAnnounce; @@ -40,267 +41,243 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.WorldEvent; -import java.util.Iterator; +public class QuantumCluster implements ILocatable, IAECluster { + private final WorldCoord min; + private final WorldCoord max; + private boolean isDestroyed = false; + private boolean updateStatus = true; + private TileQuantumBridge[] Ring; + private boolean registered = false; + private ConnectionWrapper connection; + private long thisSide; + private long otherSide; + private TileQuantumBridge center; + public QuantumCluster(final WorldCoord min, final WorldCoord max) { + this.min = min; + this.max = max; + this.setRing(new TileQuantumBridge[8]); + } -public class QuantumCluster implements ILocatable, IAECluster -{ + @SubscribeEvent + public void onUnload(final WorldEvent.Unload e) { + if (this.center.getWorldObj() == e.world) { + this.setUpdateStatus(false); + this.destroy(); + } + } - private final WorldCoord min; - private final WorldCoord max; - private boolean isDestroyed = false; - private boolean updateStatus = true; - private TileQuantumBridge[] Ring; - private boolean registered = false; - private ConnectionWrapper connection; - private long thisSide; - private long otherSide; - private TileQuantumBridge center; + @Override + public void updateStatus(final boolean updateGrid) { + final long qe = this.center.getQEFrequency(); - public QuantumCluster( final WorldCoord min, final WorldCoord max ) - { - this.min = min; - this.max = max; - this.setRing( new TileQuantumBridge[8] ); - } + if (this.thisSide != qe && this.thisSide != -qe) { + if (qe != 0) { + if (this.thisSide != 0) { + MinecraftForge.EVENT_BUS.post( + new LocatableEventAnnounce(this, LocatableEvent.Unregister) + ); + } - @SubscribeEvent - public void onUnload( final WorldEvent.Unload e ) - { - if( this.center.getWorldObj() == e.world ) - { - this.setUpdateStatus( false ); - this.destroy(); - } - } + if (this.canUseNode(-qe)) { + this.otherSide = qe; + this.thisSide = -qe; + } else if (this.canUseNode(qe)) { + this.thisSide = qe; + this.otherSide = -qe; + } - @Override - public void updateStatus( final boolean updateGrid ) - { - final long qe = this.center.getQEFrequency(); + MinecraftForge.EVENT_BUS.post( + new LocatableEventAnnounce(this, LocatableEvent.Register) + ); + } else { + MinecraftForge.EVENT_BUS.post( + new LocatableEventAnnounce(this, LocatableEvent.Unregister) + ); - if( this.thisSide != qe && this.thisSide != -qe ) - { - if( qe != 0 ) - { - if( this.thisSide != 0 ) - { - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - } + this.otherSide = 0; + this.thisSide = 0; + } + } - if( this.canUseNode( -qe ) ) - { - this.otherSide = qe; - this.thisSide = -qe; - } - else if( this.canUseNode( qe ) ) - { - this.thisSide = qe; - this.otherSide = -qe; - } + final ILocatable myOtherSide = this.otherSide == 0 + ? null + : AEApi.instance().registries().locatable().getLocatableBy(this.otherSide); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Register ) ); - } - else - { - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); + boolean shutdown = false; - this.otherSide = 0; - this.thisSide = 0; - } - } + if (myOtherSide instanceof QuantumCluster) { + final QuantumCluster sideA = this; + final QuantumCluster sideB = (QuantumCluster) myOtherSide; - final ILocatable myOtherSide = this.otherSide == 0 ? null : AEApi.instance().registries().locatable().getLocatableBy( this.otherSide ); + if (sideA.isActive() && sideB.isActive()) { + if (this.connection != null && this.connection.getConnection() != null) { + final IGridNode a = this.connection.getConnection().a(); + final IGridNode b = this.connection.getConnection().b(); + final IGridNode sa = sideA.getNode(); + final IGridNode sb = sideB.getNode(); + if ((a == sa || b == sa) && (a == sb || b == sb)) { + return; + } + } - boolean shutdown = false; + try { + if (sideA.connection != null) { + if (sideA.connection.getConnection() != null) { + sideA.connection.getConnection().destroy(); + sideA.connection = new ConnectionWrapper(null); + } + } - if( myOtherSide instanceof QuantumCluster ) - { - final QuantumCluster sideA = this; - final QuantumCluster sideB = (QuantumCluster) myOtherSide; + if (sideB.connection != null) { + if (sideB.connection.getConnection() != null) { + sideB.connection.getConnection().destroy(); + sideB.connection = new ConnectionWrapper(null); + } + } - if( sideA.isActive() && sideB.isActive() ) - { - if( this.connection != null && this.connection.getConnection() != null ) - { - final IGridNode a = this.connection.getConnection().a(); - final IGridNode b = this.connection.getConnection().b(); - final IGridNode sa = sideA.getNode(); - final IGridNode sb = sideB.getNode(); - if( ( a == sa || b == sa ) && ( a == sb || b == sb ) ) - { - return; - } - } + sideA.connection = sideB.connection + = new ConnectionWrapper(AEApi.instance().createGridConnection( + sideA.getNode(), sideB.getNode() + )); + } catch (final FailedConnection e) { + // :( + } + } else { + shutdown = true; + } + } else { + shutdown = true; + } - try - { - if( sideA.connection != null ) - { - if( sideA.connection.getConnection() != null ) - { - sideA.connection.getConnection().destroy(); - sideA.connection = new ConnectionWrapper( null ); - } - } + if (shutdown && this.connection != null) { + if (this.connection.getConnection() != null) { + this.connection.getConnection().destroy(); + this.connection.setConnection(null); + this.connection = new ConnectionWrapper(null); + } + } + } - if( sideB.connection != null ) - { - if( sideB.connection.getConnection() != null ) - { - sideB.connection.getConnection().destroy(); - sideB.connection = new ConnectionWrapper( null ); - } - } + private boolean canUseNode(final long qe) { + final QuantumCluster qc + = (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy(qe + ); + if (qc != null) { + final World theWorld = qc.center.getWorldObj(); + if (!qc.isDestroyed) { + final Chunk c = theWorld.getChunkFromBlockCoords( + qc.center.xCoord, qc.center.zCoord + ); + if (c.isChunkLoaded) { + final int id = theWorld.provider.dimensionId; + final World cur = DimensionManager.getWorld(id); - sideA.connection = sideB.connection = new ConnectionWrapper( AEApi.instance().createGridConnection( sideA.getNode(), sideB.getNode() ) ); - } - catch( final FailedConnection e ) - { - // :( - } - } - else - { - shutdown = true; - } - } - else - { - shutdown = true; - } + final TileEntity te = theWorld.getTileEntity( + qc.center.xCoord, qc.center.yCoord, qc.center.zCoord + ); + return te != qc.center || theWorld != cur; + } + } + } + return true; + } - if( shutdown && this.connection != null ) - { - if( this.connection.getConnection() != null ) - { - this.connection.getConnection().destroy(); - this.connection.setConnection( null ); - this.connection = new ConnectionWrapper( null ); - } - } - } + private boolean isActive() { + if (this.isDestroyed || !this.registered) { + return false; + } - private boolean canUseNode( final long qe ) - { - final QuantumCluster qc = (QuantumCluster) AEApi.instance().registries().locatable().getLocatableBy( qe ); - if( qc != null ) - { - final World theWorld = qc.center.getWorldObj(); - if( !qc.isDestroyed ) - { - final Chunk c = theWorld.getChunkFromBlockCoords( qc.center.xCoord, qc.center.zCoord ); - if( c.isChunkLoaded ) - { - final int id = theWorld.provider.dimensionId; - final World cur = DimensionManager.getWorld( id ); + return this.center.isPowered() && this.hasQES(); + } - final TileEntity te = theWorld.getTileEntity( qc.center.xCoord, qc.center.yCoord, qc.center.zCoord ); - return te != qc.center || theWorld != cur; - } - } - } - return true; - } + private IGridNode getNode() { + return this.center.getGridNode(ForgeDirection.UNKNOWN); + } - private boolean isActive() - { - if( this.isDestroyed || !this.registered ) - { - return false; - } + private boolean hasQES() { + return this.thisSide != 0; + } - return this.center.isPowered() && this.hasQES(); - } + @Override + public void destroy() { + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; - private IGridNode getNode() - { - return this.center.getGridNode( ForgeDirection.UNKNOWN ); - } + if (this.registered) { + MinecraftForge.EVENT_BUS.unregister(this); + this.registered = false; + } - private boolean hasQES() - { - return this.thisSide != 0; - } + if (this.thisSide != 0) { + this.updateStatus(true); + MinecraftForge.EVENT_BUS.post( + new LocatableEventAnnounce(this, LocatableEvent.Unregister) + ); + } - @Override - public void destroy() - { - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; + this.center.updateStatus(null, (byte) -1, this.isUpdateStatus()); - if( this.registered ) - { - MinecraftForge.EVENT_BUS.unregister( this ); - this.registered = false; - } + for (final TileQuantumBridge r : this.getRing()) { + r.updateStatus(null, (byte) -1, this.isUpdateStatus()); + } - if( this.thisSide != 0 ) - { - this.updateStatus( true ); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - } + this.center = null; + this.setRing(new TileQuantumBridge[8]); + } - this.center.updateStatus( null, (byte) -1, this.isUpdateStatus() ); + @Override + public Iterator getTiles() { + return new ChainedIterator( + this.getRing()[0], + this.getRing()[1], + this.getRing()[2], + this.getRing()[3], + this.getRing()[4], + this.getRing()[5], + this.getRing()[6], + this.getRing()[7], + this.center + ); + } - for( final TileQuantumBridge r : this.getRing() ) - { - r.updateStatus( null, (byte) -1, this.isUpdateStatus() ); - } + public boolean isCorner(final TileQuantumBridge tileQuantumBridge) { + return this.getRing()[0] == tileQuantumBridge + || this.getRing()[2] == tileQuantumBridge + || this.getRing()[4] == tileQuantumBridge + || this.getRing()[6] == tileQuantumBridge; + } - this.center = null; - this.setRing( new TileQuantumBridge[8] ); - } + @Override + public long getLocatableSerial() { + return this.thisSide; + } - @Override - public Iterator getTiles() - { - return new ChainedIterator( this.getRing()[0], this.getRing()[1], this.getRing()[2], this.getRing()[3], this.getRing()[4], this.getRing()[5], this.getRing()[6], this.getRing()[7], this.center ); - } + public TileQuantumBridge getCenter() { + return this.center; + } - public boolean isCorner( final TileQuantumBridge tileQuantumBridge ) - { - return this.getRing()[0] == tileQuantumBridge || this.getRing()[2] == tileQuantumBridge || this.getRing()[4] == tileQuantumBridge || this.getRing()[6] == tileQuantumBridge; - } + void setCenter(final TileQuantumBridge c) { + this.registered = true; + MinecraftForge.EVENT_BUS.register(this); + this.center = c; + } - @Override - public long getLocatableSerial() - { - return this.thisSide; - } + private boolean isUpdateStatus() { + return this.updateStatus; + } - public TileQuantumBridge getCenter() - { - return this.center; - } + public void setUpdateStatus(final boolean updateStatus) { + this.updateStatus = updateStatus; + } - void setCenter( final TileQuantumBridge c ) - { - this.registered = true; - MinecraftForge.EVENT_BUS.register( this ); - this.center = c; - } + TileQuantumBridge[] getRing() { + return this.Ring; + } - private boolean isUpdateStatus() - { - return this.updateStatus; - } - - public void setUpdateStatus( final boolean updateStatus ) - { - this.updateStatus = updateStatus; - } - - TileQuantumBridge[] getRing() - { - return this.Ring; - } - - private void setRing( final TileQuantumBridge[] ring ) - { - this.Ring = ring; - } + private void setRing(final TileQuantumBridge[] ring) { + this.Ring = ring; + } } diff --git a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java index 68b73eda..320583ea 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCalculator.java @@ -18,7 +18,6 @@ package appeng.me.cluster.implementations; - import appeng.api.util.DimensionalCoord; import appeng.api.util.WorldCoord; import appeng.me.cluster.IAECluster; @@ -28,81 +27,73 @@ import appeng.tile.spatial.TileSpatialPylon; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public class SpatialPylonCalculator extends MBCalculator { + private final TileSpatialPylon tqb; -public class SpatialPylonCalculator extends MBCalculator -{ + public SpatialPylonCalculator(final IAEMultiBlock t) { + super(t); + this.tqb = (TileSpatialPylon) t; + } - private final TileSpatialPylon tqb; + @Override + public boolean checkMultiblockScale(final WorldCoord min, final 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); + } - public SpatialPylonCalculator( final IAEMultiBlock t ) - { - super( t ); - this.tqb = (TileSpatialPylon) t; - } + @Override + public IAECluster + createCluster(final World w, final WorldCoord min, final 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 boolean checkMultiblockScale( final WorldCoord min, final 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 boolean + verifyInternalStructure(final World w, final WorldCoord min, final WorldCoord max) { + 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++) { + final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity(x, y, z); - @Override - public IAECluster createCluster( final World w, final WorldCoord min, final WorldCoord max ) - { - return new SpatialPylonCluster( new DimensionalCoord( w, min.x, min.y, min.z ), new DimensionalCoord( w, max.x, max.y, max.z ) ); - } + if (!te.isValid()) { + return false; + } + } + } + } - @Override - public boolean verifyInternalStructure( final World w, final WorldCoord min, final WorldCoord max ) - { + return true; + } - 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++ ) - { - final IAEMultiBlock te = (IAEMultiBlock) w.getTileEntity( x, y, z ); + @Override + public void disconnect() { + this.tqb.disconnect(true); + } - if( !te.isValid() ) - { - return false; - } - } - } - } + @Override + public void updateTiles( + final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max + ) { + final SpatialPylonCluster c = (SpatialPylonCluster) cl; - return true; - } + 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++) { + final TileSpatialPylon te + = (TileSpatialPylon) w.getTileEntity(x, y, z); + te.updateStatus(c); + c.getLine().add((te)); + } + } + } + } - @Override - public void disconnect() - { - this.tqb.disconnect( true ); - } - - @Override - public void updateTiles( final IAECluster cl, final World w, final WorldCoord min, final WorldCoord max ) - { - final 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++ ) - { - final TileSpatialPylon te = (TileSpatialPylon) w.getTileEntity( x, y, z ); - te.updateStatus( c ); - c.getLine().add( ( te ) ); - } - } - } - } - - @Override - public boolean isValidTile( final TileEntity te ) - { - return te instanceof TileSpatialPylon; - } + @Override + public boolean isValidTile(final 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 fd57add5..d498f269 100644 --- a/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java +++ b/src/main/java/appeng/me/cluster/implementations/SpatialPylonCluster.java @@ -18,124 +18,94 @@ package appeng.me.cluster.implementations; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import appeng.api.networking.IGridHost; import appeng.api.util.DimensionalCoord; import appeng.me.cluster.IAECluster; import appeng.tile.spatial.TileSpatialPylon; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +public class SpatialPylonCluster implements IAECluster { + private final DimensionalCoord min; + private final DimensionalCoord max; + private final List line = new ArrayList(); + private boolean isDestroyed = false; + private Axis currentAxis = Axis.UNFORMED; + private boolean isValid; -public class SpatialPylonCluster implements IAECluster -{ + public SpatialPylonCluster(final DimensionalCoord min, final DimensionalCoord max) { + this.min = min.copy(); + this.max = max.copy(); - private final DimensionalCoord min; - private final DimensionalCoord max; - private final List line = new ArrayList(); - private boolean isDestroyed = false; + if (this.getMin().x != this.getMax().x) { + this.setCurrentAxis(Axis.X); + } else if (this.getMin().y != this.getMax().y) { + this.setCurrentAxis(Axis.Y); + } else if (this.getMin().z != this.getMax().z) { + this.setCurrentAxis(Axis.Z); + } else { + this.setCurrentAxis(Axis.UNFORMED); + } + } - private Axis currentAxis = Axis.UNFORMED; - private boolean isValid; + @Override + public void updateStatus(final boolean updateGrid) { + for (final TileSpatialPylon r : this.getLine()) { + r.recalculateDisplay(); + } + } - public SpatialPylonCluster( final DimensionalCoord min, final DimensionalCoord max ) - { - this.min = min.copy(); - this.max = max.copy(); + @Override + public void destroy() { + if (this.isDestroyed) { + return; + } + this.isDestroyed = true; - if( this.getMin().x != this.getMax().x ) - { - this.setCurrentAxis( Axis.X ); - } - else if( this.getMin().y != this.getMax().y ) - { - this.setCurrentAxis( Axis.Y ); - } - else if( this.getMin().z != this.getMax().z ) - { - this.setCurrentAxis( Axis.Z ); - } - else - { - this.setCurrentAxis( Axis.UNFORMED ); - } - } + for (final TileSpatialPylon r : this.getLine()) { + r.updateStatus(null); + } + } - @Override - public void updateStatus( final boolean updateGrid ) - { - for( final TileSpatialPylon r : this.getLine() ) - { - r.recalculateDisplay(); - } - } + @Override + public Iterator getTiles() { + return (Iterator) this.getLine().iterator(); + } - @Override - public void destroy() - { + public int tileCount() { + return this.getLine().size(); + } - if( this.isDestroyed ) - { - return; - } - this.isDestroyed = true; + public Axis getCurrentAxis() { + return this.currentAxis; + } - for( final TileSpatialPylon r : this.getLine() ) - { - r.updateStatus( null ); - } - } + private void setCurrentAxis(final Axis currentAxis) { + this.currentAxis = currentAxis; + } - @Override - public Iterator getTiles() - { - return (Iterator) this.getLine().iterator(); - } + public boolean isValid() { + return this.isValid; + } - public int tileCount() - { - return this.getLine().size(); - } + public void setValid(final boolean isValid) { + this.isValid = isValid; + } - public Axis getCurrentAxis() - { - return this.currentAxis; - } + public DimensionalCoord getMax() { + return this.max; + } - private void setCurrentAxis( final Axis currentAxis ) - { - this.currentAxis = currentAxis; - } + public DimensionalCoord getMin() { + return this.min; + } - public boolean isValid() - { - return this.isValid; - } + List getLine() { + return this.line; + } - public void setValid( final boolean isValid ) - { - this.isValid = isValid; - } - - public DimensionalCoord getMax() - { - return this.max; - } - - public DimensionalCoord getMin() - { - return this.min; - } - - List getLine() - { - return this.line; - } - - public enum Axis - { - X, Y, Z, UNFORMED - } + 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 3bf4d055..b305e05b 100644 --- a/src/main/java/appeng/me/energy/EnergyThreshold.java +++ b/src/main/java/appeng/me/energy/EnergyThreshold.java @@ -18,52 +18,40 @@ package appeng.me.energy; - import appeng.api.networking.energy.IEnergyWatcher; import appeng.util.ItemSorters; +public class EnergyThreshold implements Comparable { + private final double Limit; + private final IEnergyWatcher watcher; + private final int hash; -public class EnergyThreshold implements Comparable -{ + public EnergyThreshold(final double lim, final IEnergyWatcher wat) { + this.Limit = lim; + this.watcher = wat; - private final double Limit; - private final IEnergyWatcher watcher; - private final int hash; + if (this.getWatcher() != null) { + this.hash = this.getWatcher().hashCode() ^ ((Double) lim).hashCode(); + } else { + this.hash = ((Double) lim).hashCode(); + } + } - public EnergyThreshold( final double lim, final IEnergyWatcher wat ) - { - this.Limit = lim; - this.watcher = wat; + @Override + public int hashCode() { + return this.hash; + } - if( this.getWatcher() != null ) - { - this.hash = this.getWatcher().hashCode() ^ ( (Double) lim ).hashCode(); - } - else - { - this.hash = ( (Double) lim ).hashCode(); - } - } + @Override + public int compareTo(final EnergyThreshold o) { + return ItemSorters.compareDouble(this.getLimit(), o.getLimit()); + } - @Override - public int hashCode() - { - return this.hash; - } + double getLimit() { + return this.Limit; + } - @Override - public int compareTo( final EnergyThreshold o ) - { - return ItemSorters.compareDouble( this.getLimit(), o.getLimit() ); - } - - double getLimit() - { - return this.Limit; - } - - public IEnergyWatcher getWatcher() - { - return this.watcher; - } + public IEnergyWatcher getWatcher() { + return this.watcher; + } } diff --git a/src/main/java/appeng/me/energy/EnergyWatcher.java b/src/main/java/appeng/me/energy/EnergyWatcher.java index 34d93df6..bed9a9a6 100644 --- a/src/main/java/appeng/me/energy/EnergyWatcher.java +++ b/src/main/java/appeng/me/energy/EnergyWatcher.java @@ -18,187 +18,158 @@ package appeng.me.energy; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; import appeng.api.networking.energy.IEnergyWatcher; import appeng.api.networking.energy.IEnergyWatcherHost; import appeng.me.cache.EnergyGridCache; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; - - /** - * Maintain my interests, and a global watch list, they should always be fully synchronized. + * Maintain my interests, and a global watch list, they should always be fully + * synchronized. */ -public class EnergyWatcher implements IEnergyWatcher -{ +public class EnergyWatcher implements IEnergyWatcher { + private final EnergyGridCache gsc; + private final IEnergyWatcherHost myObject; + private final HashSet myInterests = new HashSet(); - private final EnergyGridCache gsc; - private final IEnergyWatcherHost myObject; - private final HashSet myInterests = new HashSet(); + public EnergyWatcher(final EnergyGridCache cache, final IEnergyWatcherHost host) { + this.gsc = cache; + this.myObject = host; + } - public EnergyWatcher( final EnergyGridCache cache, final IEnergyWatcherHost host ) - { - this.gsc = cache; - this.myObject = host; - } + public void post(final EnergyGridCache energyGridCache) { + this.myObject.onThresholdPass(energyGridCache); + } - public void post( final EnergyGridCache energyGridCache ) - { - this.myObject.onThresholdPass( energyGridCache ); - } + public IEnergyWatcherHost getHost() { + return this.myObject; + } - public IEnergyWatcherHost getHost() - { - return this.myObject; - } + @Override + public int size() { + return this.myInterests.size(); + } - @Override - public int size() - { - return this.myInterests.size(); - } + @Override + public boolean isEmpty() { + return this.myInterests.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } + @Override + public boolean contains(final Object o) { + return this.myInterests.contains(o); + } - @Override - public boolean contains( final Object o ) - { - return this.myInterests.contains( o ); - } + @Override + public Iterator iterator() { + return new EnergyWatcherIterator(this, this.myInterests.iterator()); + } - @Override - public Iterator iterator() - { - return new EnergyWatcherIterator( this, this.myInterests.iterator() ); - } + @Override + public Object[] toArray() { + return this.myInterests.toArray(); + } - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } + @Override + public T[] toArray(final T[] a) { + return this.myInterests.toArray(a); + } - @Override - public T[] toArray( final T[] a ) - { - return this.myInterests.toArray( a ); - } + @Override + public boolean add(final Double e) { + if (this.myInterests.contains(e)) { + return false; + } - @Override - public boolean add( final Double e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } + final EnergyThreshold eh = new EnergyThreshold(e, this); + return this.gsc.getInterests().add(eh) && this.myInterests.add(eh); + } - final EnergyThreshold eh = new EnergyThreshold( e, this ); - return this.gsc.getInterests().add( eh ) && this.myInterests.add( eh ); - } + @Override + public boolean remove(final Object o) { + final EnergyThreshold eh = new EnergyThreshold((Double) o, this); + return this.myInterests.remove(eh) && this.gsc.getInterests().remove(eh); + } - @Override - public boolean remove( final Object o ) - { - final EnergyThreshold eh = new EnergyThreshold( (Double) o, this ); - return this.myInterests.remove( eh ) && this.gsc.getInterests().remove( eh ); - } + @Override + public boolean containsAll(final Collection c) { + return this.myInterests.containsAll(c); + } - @Override - public boolean containsAll( final Collection c ) - { - return this.myInterests.containsAll( c ); - } + @Override + public boolean addAll(final Collection c) { + boolean didChange = false; - @Override - public boolean addAll( final Collection c ) - { - boolean didChange = false; + for (final Double o : c) { + didChange = this.add(o) || didChange; + } - for( final Double o : c ) - { - didChange = this.add( o ) || didChange; - } + return didChange; + } - return didChange; - } + @Override + public boolean removeAll(final Collection c) { + boolean didSomething = false; + for (final Object o : c) { + didSomething = this.remove(o) || didSomething; + } + return didSomething; + } - @Override - public boolean removeAll( final Collection c ) - { - boolean didSomething = false; - for( final Object o : c ) - { - didSomething = this.remove( o ) || didSomething; - } - return didSomething; - } + @Override + public boolean retainAll(final Collection c) { + boolean changed = false; + final Iterator i = this.iterator(); - @Override - public boolean retainAll( final Collection c ) - { - boolean changed = false; - final Iterator i = this.iterator(); + while (i.hasNext()) { + if (!c.contains(i.next())) { + i.remove(); + changed = true; + } + } - while( i.hasNext() ) - { - if( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } + return changed; + } - return changed; - } + @Override + public void clear() { + final Iterator i = this.myInterests.iterator(); + while (i.hasNext()) { + this.gsc.getInterests().remove(i.next()); + i.remove(); + } + } - @Override - public void clear() - { - final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterests().remove( i.next() ); - i.remove(); - } - } + private class EnergyWatcherIterator implements Iterator { + private final EnergyWatcher watcher; + private final Iterator interestIterator; + private EnergyThreshold myLast; - private class EnergyWatcherIterator implements Iterator - { + public EnergyWatcherIterator( + final EnergyWatcher parent, final Iterator i + ) { + this.watcher = parent; + this.interestIterator = i; + } - private final EnergyWatcher watcher; - private final Iterator interestIterator; - private EnergyThreshold myLast; + @Override + public boolean hasNext() { + return this.interestIterator.hasNext(); + } - public EnergyWatcherIterator( final EnergyWatcher parent, final Iterator i ) - { - this.watcher = parent; - this.interestIterator = i; - } + @Override + public Double next() { + this.myLast = this.interestIterator.next(); + return this.myLast.getLimit(); + } - @Override - public boolean hasNext() - { - return this.interestIterator.hasNext(); - } - - @Override - public Double next() - { - this.myLast = this.interestIterator.next(); - return this.myLast.getLimit(); - } - - @Override - public void remove() - { - EnergyWatcher.this.gsc.getInterests().remove( this.myLast ); - this.interestIterator.remove(); - } - } + @Override + public void remove() { + EnergyWatcher.this.gsc.getInterests().remove(this.myLast); + this.interestIterator.remove(); + } + } } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxy.java b/src/main/java/appeng/me/helpers/AENetworkProxy.java index 1b06f5b1..1d8a0f1a 100644 --- a/src/main/java/appeng/me/helpers/AENetworkProxy.java +++ b/src/main/java/appeng/me/helpers/AENetworkProxy.java @@ -18,6 +18,8 @@ package appeng.me.helpers; +import java.util.Collections; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.networking.*; @@ -44,400 +46,325 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; +public class AENetworkProxy implements IGridBlock { + private final IGridProxyable gp; + private final boolean worldNode; + private final String nbtName; // name + private AEColor myColor = AEColor.Transparent; + private NBTTagCompound data = null; // input + private ItemStack myRepInstance; + private boolean isReady = false; + private IGridNode node = null; + private EnumSet validSides; + private EnumSet flags = EnumSet.noneOf(GridFlags.class); + private double idleDraw = 1.0; + private EntityPlayer owner; + public AENetworkProxy( + final IGridProxyable te, + final String nbtName, + final ItemStack visual, + final boolean inWorld + ) { + this.gp = te; + this.nbtName = nbtName; + this.worldNode = inWorld; + this.myRepInstance = visual; + this.validSides = EnumSet.allOf(ForgeDirection.class); + } -public class AENetworkProxy implements IGridBlock -{ + public void setVisualRepresentation(final ItemStack is) { + this.myRepInstance = is; + } - private final IGridProxyable gp; - private final boolean worldNode; - private final String nbtName; // name - private AEColor myColor = AEColor.Transparent; - private NBTTagCompound data = null; // input - private ItemStack myRepInstance; - private boolean isReady = false; - private IGridNode node = null; - private EnumSet validSides; - private EnumSet flags = EnumSet.noneOf( GridFlags.class ); - private double idleDraw = 1.0; - private EntityPlayer owner; + public void writeToNBT(final NBTTagCompound tag) { + if (this.node != null) { + this.node.saveToNBT(this.nbtName, tag); + } + } - public AENetworkProxy( final IGridProxyable te, final String nbtName, final ItemStack visual, final boolean inWorld ) - { - this.gp = te; - this.nbtName = nbtName; - this.worldNode = inWorld; - this.myRepInstance = visual; - this.validSides = EnumSet.allOf( ForgeDirection.class ); - } + public void setValidSides(final EnumSet validSides) { + this.validSides = validSides; + if (this.node != null) { + this.node.updateState(); + } + } - public void setVisualRepresentation( final ItemStack is ) - { - this.myRepInstance = is; - } + public void validate() { + if (this.gp instanceof AEBaseTile) { + TickHandler.INSTANCE.addInit((AEBaseTile) this.gp); + } + } - public void writeToNBT( final NBTTagCompound tag ) - { - if( this.node != null ) - { - this.node.saveToNBT( this.nbtName, tag ); - } - } + public void onChunkUnload() { + this.isReady = false; + this.invalidate(); + } - public void setValidSides( final EnumSet validSides ) - { - this.validSides = validSides; - if( this.node != null ) - { - this.node.updateState(); - } - } + public void invalidate() { + this.isReady = false; + if (this.node != null) { + this.node.destroy(); + this.node = null; + } + } - public void validate() - { - if( this.gp instanceof AEBaseTile ) - { - TickHandler.INSTANCE.addInit( (AEBaseTile) this.gp ); - } - } + public void onReady() { + this.isReady = true; - public void onChunkUnload() - { - this.isReady = false; - this.invalidate(); - } + // send orientation based directionality to the node. + if (this.gp instanceof IOrientable) { + final IOrientable ori = (IOrientable) this.gp; + if (ori.canBeRotated()) { + ori.setOrientation(ori.getForward(), ori.getUp()); + } + } - public void invalidate() - { - this.isReady = false; - if( this.node != null ) - { - this.node.destroy(); - this.node = null; - } - } + this.getNode(); + } - public void onReady() - { - this.isReady = true; + public IGridNode getNode() { + if (this.node == null && Platform.isServer() && this.isReady) { + this.node = AEApi.instance().createGridNode(this); + this.readFromNBT(this.data); + this.node.updateState(); + } - // send orientation based directionality to the node. - if( this.gp instanceof IOrientable ) - { - final IOrientable ori = (IOrientable) this.gp; - if( ori.canBeRotated() ) - { - ori.setOrientation( ori.getForward(), ori.getUp() ); - } - } + return this.node; + } - this.getNode(); - } + public void readFromNBT(final NBTTagCompound tag) { + this.data = tag; + 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) { + final GameProfile profile = this.owner.getGameProfile(); + final int playerID = WorldData.instance().playerData().getPlayerID(profile); - public IGridNode getNode() - { - if( this.node == null && Platform.isServer() && this.isReady ) - { - this.node = AEApi.instance().createGridNode( this ); - this.readFromNBT( this.data ); - this.node.updateState(); - } + this.node.setPlayerID(playerID); + this.owner = null; + } + } - return this.node; - } + public IPathingGrid getPath() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final IPathingGrid pg = grid.getCache(IPathingGrid.class); + if (pg == null) { + throw new GridAccessException(); + } + return pg; + } - public void readFromNBT( final NBTTagCompound tag ) - { - this.data = tag; - 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 ) - { - final GameProfile profile = this.owner.getGameProfile(); - final int playerID = WorldData.instance().playerData().getPlayerID( profile ); + /** + * 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(); + } + final IGrid grid = this.node.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + return grid; + } - this.node.setPlayerID( playerID ); - this.owner = null; - } - } + public ITickManager getTick() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final ITickManager pg = grid.getCache(ITickManager.class); + if (pg == null) { + throw new GridAccessException(); + } + return pg; + } - public IPathingGrid getPath() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final IPathingGrid pg = grid.getCache( IPathingGrid.class ); - if( pg == null ) - { - throw new GridAccessException(); - } - return pg; - } + public IStorageGrid getStorage() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - /** - * 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(); - } - final IGrid grid = this.node.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - return grid; - } + final IStorageGrid pg = grid.getCache(IStorageGrid.class); - public ITickManager getTick() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final ITickManager pg = grid.getCache( ITickManager.class ); - if( pg == null ) - { - throw new GridAccessException(); - } - return pg; - } + if (pg == null) { + throw new GridAccessException(); + } - public IStorageGrid getStorage() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + return pg; + } - final IStorageGrid pg = grid.getCache( IStorageGrid.class ); + public P2PCache getP2P() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - if( pg == null ) - { - throw new GridAccessException(); - } + final P2PCache pg = grid.getCache(P2PCache.class); - return pg; - } + if (pg == null) { + throw new GridAccessException(); + } - public P2PCache getP2P() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + return pg; + } - final P2PCache pg = grid.getCache( P2PCache.class ); + public ISecurityGrid getSecurity() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - if( pg == null ) - { - throw new GridAccessException(); - } + final ISecurityGrid sg = grid.getCache(ISecurityGrid.class); - return pg; - } + if (sg == null) { + throw new GridAccessException(); + } - public ISecurityGrid getSecurity() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + return sg; + } - final ISecurityGrid sg = grid.getCache( ISecurityGrid.class ); + public ICraftingGrid getCrafting() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } - if( sg == null ) - { - throw new GridAccessException(); - } + final ICraftingGrid sg = grid.getCache(ICraftingGrid.class); - return sg; - } + if (sg == null) { + throw new GridAccessException(); + } - public ICraftingGrid getCrafting() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } + return sg; + } - final ICraftingGrid sg = grid.getCache( ICraftingGrid.class ); + @Override + public double getIdlePowerUsage() { + return this.idleDraw; + } - if( sg == null ) - { - throw new GridAccessException(); - } + @Override + public EnumSet getFlags() { + return this.flags; + } - return sg; - } + @Override + public boolean isWorldAccessible() { + return this.worldNode; + } - @Override - public double getIdlePowerUsage() - { - return this.idleDraw; - } + @Override + public DimensionalCoord getLocation() { + return this.gp.getLocation(); + } - @Override - public EnumSet getFlags() - { - return this.flags; - } + @Override + public AEColor getGridColor() { + return this.getColor(); + } - @Override - public boolean isWorldAccessible() - { - return this.worldNode; - } + @Override + public void onGridNotification(final GridNotification notification) { + if (this.gp instanceof PartCable) { + ((PartCable) this.gp).markForUpdate(); + } + } - @Override - public DimensionalCoord getLocation() - { - return this.gp.getLocation(); - } + @Override + public void setNetworkStatus(final IGrid grid, final int channelsInUse) {} - @Override - public AEColor getGridColor() - { - return this.getColor(); - } + @Override + public EnumSet getConnectableSides() { + return this.validSides; + } - @Override - public void onGridNotification( final GridNotification notification ) - { - if( this.gp instanceof PartCable ) - { - ( (PartCable) this.gp ).markForUpdate(); - } - } + @Override + public IGridHost getMachine() { + return this.gp; + } - @Override - public void setNetworkStatus( final IGrid grid, final int channelsInUse ) - { + @Override + public void gridChanged() { + this.gp.gridChanged(); + } - } + @Override + public ItemStack getMachineRepresentation() { + return this.myRepInstance; + } - @Override - public EnumSet getConnectableSides() - { - return this.validSides; - } + public void setFlags(final GridFlags... requireChannel) { + final EnumSet flags = EnumSet.noneOf(GridFlags.class); - @Override - public IGridHost getMachine() - { - return this.gp; - } + Collections.addAll(flags, requireChannel); - @Override - public void gridChanged() - { - this.gp.gridChanged(); - } + this.flags = flags; + } - @Override - public ItemStack getMachineRepresentation() - { - return this.myRepInstance; - } + public void setIdlePowerUsage(final double idle) { + this.idleDraw = idle; - public void setFlags( final GridFlags... requireChannel ) - { - final EnumSet flags = EnumSet.noneOf( GridFlags.class ); + if (this.node != null) { + try { + final IGrid g = this.getGrid(); + g.postEvent(new MENetworkPowerIdleChange(this.node)); + } catch (final GridAccessException e) { + // not ready for this yet.. + } + } + } - Collections.addAll( flags, requireChannel ); + public boolean isReady() { + return this.isReady; + } - this.flags = flags; - } + public boolean isActive() { + if (this.node == null) { + return false; + } - public void setIdlePowerUsage( final double idle ) - { - this.idleDraw = idle; + return this.node.isActive(); + } - if( this.node != null ) - { - try - { - final IGrid g = this.getGrid(); - g.postEvent( new MENetworkPowerIdleChange( this.node ) ); - } - catch( final GridAccessException e ) - { - // not ready for this yet.. - } - } - } + public boolean isPowered() { + try { + return this.getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + return false; + } + } - public boolean isReady() - { - return this.isReady; - } + public IEnergyGrid getEnergy() throws GridAccessException { + final IGrid grid = this.getGrid(); + if (grid == null) { + throw new GridAccessException(); + } + final IEnergyGrid eg = grid.getCache(IEnergyGrid.class); + if (eg == null) { + throw new GridAccessException(); + } + return eg; + } - public boolean isActive() - { - if( this.node == null ) - { - return false; - } + public void setOwner(final EntityPlayer player) { + this.owner = player; + } - return this.node.isActive(); - } + public AEColor getColor() { + return this.myColor; + } - public boolean isPowered() - { - try - { - return this.getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - return false; - } - } - - public IEnergyGrid getEnergy() throws GridAccessException - { - final IGrid grid = this.getGrid(); - if( grid == null ) - { - throw new GridAccessException(); - } - final IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); - if( eg == null ) - { - throw new GridAccessException(); - } - return eg; - } - - public void setOwner( final EntityPlayer player ) - { - this.owner = player; - } - - public AEColor getColor() - { - return this.myColor; - } - - public void setColor( final AEColor myColor ) - { - this.myColor = myColor; - } + public void setColor(final AEColor myColor) { + this.myColor = myColor; + } } diff --git a/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java b/src/main/java/appeng/me/helpers/AENetworkProxyMultiblock.java index 6272ef99..2adec71f 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 appeng.api.networking.IGridMultiblock; import appeng.api.networking.IGridNode; @@ -27,30 +28,26 @@ import appeng.util.iterators.ChainedIterator; import appeng.util.iterators.ProxyNodeIterator; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public class AENetworkProxyMultiblock extends AENetworkProxy implements IGridMultiblock { + public AENetworkProxyMultiblock( + final IGridProxyable te, + final String nbtName, + final ItemStack itemStack, + final boolean inWorld + ) { + super(te, nbtName, itemStack, inWorld); + } + @Override + public Iterator getMultiblockNodes() { + if (this.getCluster() == null) { + return new ChainedIterator(); + } -public class AENetworkProxyMultiblock extends AENetworkProxy implements IGridMultiblock -{ + return new ProxyNodeIterator(this.getCluster().getTiles()); + } - public AENetworkProxyMultiblock( final IGridProxyable te, final String nbtName, final ItemStack itemStack, final boolean inWorld ) - { - super( te, nbtName, itemStack, inWorld ); - } - - @Override - public Iterator getMultiblockNodes() - { - if( this.getCluster() == null ) - { - return new ChainedIterator(); - } - - return new ProxyNodeIterator( this.getCluster().getTiles() ); - } - - private IAECluster getCluster() - { - return ( (IAEMultiBlock) this.getMachine() ).getCluster(); - } + private 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 8ca76443..f73c5349 100644 --- a/src/main/java/appeng/me/helpers/ChannelPowerSrc.java +++ b/src/main/java/appeng/me/helpers/ChannelPowerSrc.java @@ -18,32 +18,27 @@ 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 { + private final IGridNode node; + private final IEnergySource realSrc; -public class ChannelPowerSrc implements IEnergySource -{ + public ChannelPowerSrc(final IGridNode networkNode, final IEnergySource src) { + this.node = networkNode; + this.realSrc = src; + } - private final IGridNode node; - private final IEnergySource realSrc; - - public ChannelPowerSrc( final IGridNode networkNode, final IEnergySource src ) - { - this.node = networkNode; - this.realSrc = src; - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier ) - { - if( this.node.isActive() ) - { - return this.realSrc.extractAEPower( amt, mode, usePowerMultiplier ); - } - return 0.0; - } + @Override + public double extractAEPower( + final double amt, final Actionable mode, final PowerMultiplier usePowerMultiplier + ) { + 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 4c99e54b..971fb7ea 100644 --- a/src/main/java/appeng/me/helpers/GenericInterestManager.java +++ b/src/main/java/appeng/me/helpers/GenericInterestManager.java @@ -18,107 +18,83 @@ package appeng.me.helpers; +import java.util.Collection; +import java.util.LinkedList; import appeng.api.storage.data.IAEStack; import com.google.common.collect.Multimap; -import java.util.Collection; -import java.util.LinkedList; +public class GenericInterestManager { + private final Multimap container; + private LinkedList transactions = null; + private int transDepth = 0; + public GenericInterestManager(final Multimap interests) { + this.container = interests; + } -public class GenericInterestManager -{ + public void enableTransactions() { + if (this.transDepth == 0) { + this.transactions = new LinkedList(); + } - private final Multimap container; - private LinkedList transactions = null; - private int transDepth = 0; + this.transDepth++; + } - public GenericInterestManager( final Multimap interests ) - { - this.container = interests; - } + public void disableTransactions() { + this.transDepth--; - public void enableTransactions() - { - if( this.transDepth == 0 ) - { - this.transactions = new LinkedList(); - } + if (this.transDepth == 0) { + final LinkedList myActions = this.transactions; + this.transactions = null; - this.transDepth++; - } + for (final SavedTransactions t : myActions) { + if (t.put) { + this.put(t.stack, t.iw); + } else { + this.remove(t.stack, t.iw); + } + } + } + } - public void disableTransactions() - { - this.transDepth--; + public boolean put(final IAEStack stack, final T iw) { + if (this.transactions != null) { + this.transactions.add(new SavedTransactions(true, stack, iw)); + return true; + } else { + return this.container.put(stack, iw); + } + } - if( this.transDepth == 0 ) - { - final LinkedList myActions = this.transactions; - this.transactions = null; + public boolean remove(final IAEStack stack, final T iw) { + if (this.transactions != null) { + this.transactions.add(new SavedTransactions(true, stack, iw)); + return true; + } else { + return this.container.remove(stack, iw); + } + } - for( final SavedTransactions t : myActions ) - { - if( t.put ) - { - this.put( t.stack, t.iw ); - } - else - { - this.remove( t.stack, t.iw ); - } - } - } - } + public boolean containsKey(final IAEStack stack) { + return this.container.containsKey(stack); + } - public boolean put( final IAEStack stack, final T iw ) - { - if( this.transactions != null ) - { - this.transactions.add( new SavedTransactions( true, stack, iw ) ); - return true; - } - else - { - return this.container.put( stack, iw ); - } - } + public Collection get(final IAEStack stack) { + return this.container.get(stack); + } - public boolean remove( final IAEStack stack, final T iw ) - { - if( this.transactions != null ) - { - this.transactions.add( new SavedTransactions( true, stack, iw ) ); - return true; - } - else - { - return this.container.remove( stack, iw ); - } - } + private class SavedTransactions { + private final boolean put; + private final IAEStack stack; + private final T iw; - public boolean containsKey( final IAEStack stack ) - { - return this.container.containsKey( stack ); - } - - public Collection get( final IAEStack stack ) - { - return this.container.get( stack ); - } - - private class SavedTransactions - { - - private final boolean put; - private final IAEStack stack; - private final T iw; - - public SavedTransactions( final boolean putOperation, final IAEStack myStack, final T watcher ) - { - this.put = putOperation; - this.stack = myStack; - this.iw = watcher; - } - } + public SavedTransactions( + final boolean putOperation, final IAEStack myStack, final 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 916a5659..3ef41bca 100644 --- a/src/main/java/appeng/me/helpers/IGridProxyable.java +++ b/src/main/java/appeng/me/helpers/IGridProxyable.java @@ -18,17 +18,13 @@ package appeng.me.helpers; - import appeng.api.networking.IGridHost; import appeng.api.util.DimensionalCoord; +public interface IGridProxyable extends IGridHost { + AENetworkProxy getProxy(); -public interface IGridProxyable extends IGridHost -{ + DimensionalCoord getLocation(); - AENetworkProxy getProxy(); - - DimensionalCoord getLocation(); - - void gridChanged(); + void gridChanged(); } diff --git a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java index 8a0afab1..23f981c7 100644 --- a/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/AdHocChannelUpdater.java @@ -18,40 +18,33 @@ 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 { + private final int usedChannels; -public class AdHocChannelUpdater implements IGridConnectionVisitor -{ + public AdHocChannelUpdater(final int used) { + this.usedChannels = used; + } - private final int usedChannels; + @Override + public boolean visitNode(final IGridNode n) { + final GridNode gn = (GridNode) n; + gn.setControllerRoute(null, true); + gn.incrementChannelCount(this.usedChannels); + gn.finalizeChannels(); + return true; + } - public AdHocChannelUpdater( final int used ) - { - this.usedChannels = used; - } - - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - gn.setControllerRoute( null, true ); - gn.incrementChannelCount( this.usedChannels ); - gn.finalizeChannels(); - return true; - } - - @Override - public void visitConnection( final IGridConnection gcc ) - { - final GridConnection gc = (GridConnection) gcc; - gc.setControllerRoute( null, true ); - gc.incrementChannelCount( this.usedChannels ); - gc.finalizeChannels(); - } + @Override + public void visitConnection(final IGridConnection gcc) { + final GridConnection gc = (GridConnection) gcc; + gc.setControllerRoute(null, true); + gc.incrementChannelCount(this.usedChannels); + gc.finalizeChannels(); + } } diff --git a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java index f6bb4ff7..45234483 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java +++ b/src/main/java/appeng/me/pathfinding/ControllerChannelUpdater.java @@ -18,29 +18,23 @@ 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(final IGridNode n) { + final GridNode gn = (GridNode) n; + gn.finalizeChannels(); + return true; + } -public class ControllerChannelUpdater implements IGridConnectionVisitor -{ - - @Override - public boolean visitNode( final IGridNode n ) - { - final GridNode gn = (GridNode) n; - gn.finalizeChannels(); - return true; - } - - @Override - public void visitConnection( final IGridConnection gcc ) - { - final GridConnection gc = (GridConnection) gcc; - gc.finalizeChannels(); - } + @Override + public void visitConnection(final IGridConnection gcc) { + final 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 7b7cb4c0..145b393c 100644 --- a/src/main/java/appeng/me/pathfinding/ControllerValidator.java +++ b/src/main/java/appeng/me/pathfinding/ControllerValidator.java @@ -18,83 +18,70 @@ 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 { + private boolean isValid = true; + private int found = 0; + private int minX; + private int minY; + private int minZ; + private int maxX; + private int maxY; + private int maxZ; -public class ControllerValidator implements IGridVisitor -{ + public ControllerValidator(final int x, final int y, final int z) { + this.minX = x; + this.minY = y; + this.minZ = z; + this.maxX = x; + this.maxY = y; + this.maxZ = z; + } - private boolean isValid = true; - private int found = 0; - private int minX; - private int minY; - private int minZ; - private int maxX; - private int maxY; - private int maxZ; + @Override + public boolean visitNode(final IGridNode n) { + final IGridHost host = n.getMachine(); + if (this.isValid() && host instanceof TileController) { + final TileController c = (TileController) host; - public ControllerValidator( final int x, final int y, final int z ) - { - this.minX = x; - this.minY = y; - this.minZ = z; - this.maxX = x; - this.maxY = y; - this.maxZ = z; - } + this.minX = Math.min(c.xCoord, this.minX); + this.maxX = Math.max(c.xCoord, this.maxX); + this.minY = Math.min(c.yCoord, this.minY); + this.maxY = Math.max(c.yCoord, this.maxY); + this.minZ = Math.min(c.zCoord, this.minZ); + this.maxZ = Math.max(c.zCoord, this.maxZ); - @Override - public boolean visitNode( final IGridNode n ) - { - final IGridHost host = n.getMachine(); - if( this.isValid() && host instanceof TileController ) - { - final TileController c = (TileController) host; + if (this.maxX - this.minX < 7 && this.maxY - this.minY < 7 + && this.maxZ - this.minZ < 7) { + this.setFound(this.getFound() + 1); + return true; + } - this.minX = Math.min( c.xCoord, this.minX ); - this.maxX = Math.max( c.xCoord, this.maxX ); - this.minY = Math.min( c.yCoord, this.minY ); - this.maxY = Math.max( c.yCoord, this.maxY ); - this.minZ = Math.min( c.zCoord, this.minZ ); - this.maxZ = Math.max( c.zCoord, this.maxZ ); + this.setValid(false); + } else { + return false; + } - if( this.maxX - this.minX < 7 && this.maxY - this.minY < 7 && this.maxZ - this.minZ < 7 ) - { - this.setFound( this.getFound() + 1 ); - return true; - } + return this.isValid(); + } - this.setValid( false ); - } - else - { - return false; - } + public boolean isValid() { + return this.isValid; + } - return this.isValid(); - } + private void setValid(final boolean isValid) { + this.isValid = isValid; + } - public boolean isValid() - { - return this.isValid; - } + public int getFound() { + return this.found; + } - private void setValid( final boolean isValid ) - { - this.isValid = isValid; - } - - public int getFound() - { - return this.found; - } - - private void setFound( final int found ) - { - this.found = found; - } + private void setFound(final int found) { + this.found = found; + } } diff --git a/src/main/java/appeng/me/pathfinding/IPathItem.java b/src/main/java/appeng/me/pathfinding/IPathItem.java index e05e8037..85ce174e 100644 --- a/src/main/java/appeng/me/pathfinding/IPathItem.java +++ b/src/main/java/appeng/me/pathfinding/IPathItem.java @@ -18,44 +18,40 @@ package appeng.me.pathfinding; +import java.util.EnumSet; import appeng.api.networking.GridFlags; import appeng.api.util.IReadOnlyCollection; -import java.util.EnumSet; +public interface IPathItem { + IPathItem getControllerRoute(); + void setControllerRoute(IPathItem fast, boolean zeroOut); -public interface IPathItem -{ + /** + * used to determine if the finder can continue. + */ + boolean canSupportMoreChannels(); - IPathItem getControllerRoute(); + /** + * find possible choices for other pathing. + */ + IReadOnlyCollection getPossibleOptions(); - void setControllerRoute( IPathItem fast, boolean zeroOut ); + /** + * add one to the channel count, this is mostly for cables. + */ + void incrementChannelCount(int usedChannels); - /** - * used to determine if the finder can continue. - */ - boolean canSupportMoreChannels(); + /** + * get the grid flags for this IPathItem. + * + * @return the flag set. + */ + EnumSet getFlags(); - /** - * find possible choices for other pathing. - */ - IReadOnlyCollection getPossibleOptions(); - - /** - * add one to the channel count, this is mostly for cables. - */ - void incrementChannelCount( int usedChannels ); - - /** - * get the grid flags for this IPathItem. - * - * @return the flag set. - */ - EnumSet getFlags(); - - /** - * channels are done, wrap it up. - */ - void finalizeChannels(); + /** + * 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 68b95b0a..d7debc7e 100644 --- a/src/main/java/appeng/me/pathfinding/PathSegment.java +++ b/src/main/java/appeng/me/pathfinding/PathSegment.java @@ -18,150 +18,129 @@ package appeng.me.pathfinding; +import java.util.*; import appeng.api.networking.GridFlags; import appeng.api.networking.IGridMultiblock; import appeng.api.networking.IGridNode; import appeng.me.cache.PathGridCache; -import java.util.*; +public class PathSegment { + private final PathGridCache pgc; + private final Set semiOpen; + private final Set closed; + private boolean isDead; + private List open; + public PathSegment( + final PathGridCache myPGC, + final List open, + final Set semiOpen, + final Set closed + ) { + this.open = open; + this.semiOpen = semiOpen; + this.closed = closed; + this.pgc = myPGC; + this.setDead(false); + } -public class PathSegment -{ + public boolean step() { + final List oldOpen = this.open; + this.open = new LinkedList(); - private final PathGridCache pgc; - private final Set semiOpen; - private final Set closed; - private boolean isDead; - private List open; + for (final IPathItem i : oldOpen) { + for (final IPathItem pi : i.getPossibleOptions()) { + final EnumSet flags = pi.getFlags(); - public PathSegment( final PathGridCache myPGC, final List open, final Set semiOpen, final Set closed ) - { - this.open = open; - this.semiOpen = semiOpen; - this.closed = closed; - this.pgc = myPGC; - this.setDead( false ); - } + if (!this.closed.contains(pi)) { + pi.setControllerRoute(i, true); - public boolean step() - { - final List oldOpen = this.open; - this.open = new LinkedList(); + if (flags.contains(GridFlags.REQUIRE_CHANNEL)) { + // close the semi open. + if (!this.semiOpen.contains(pi)) { + final boolean worked; - for( final IPathItem i : oldOpen ) - { - for( final IPathItem pi : i.getPossibleOptions() ) - { - final EnumSet flags = pi.getFlags(); + if (flags.contains(GridFlags.COMPRESSED_CHANNEL)) { + worked = this.useDenseChannel(pi); + } else { + worked = this.useChannel(pi); + } - if( !this.closed.contains( pi ) ) - { - pi.setControllerRoute( i, true ); + if (worked && flags.contains(GridFlags.MULTIBLOCK)) { + final Iterator oni + = ((IGridMultiblock) ((IGridNode) pi).getGridBlock()) + .getMultiblockNodes(); + while (oni.hasNext()) { + final IGridNode otherNodes = oni.next(); + if (otherNodes != pi) { + this.semiOpen.add((IPathItem) otherNodes); + } + } + } + } else { + pi.incrementChannelCount(1); // give a channel. + this.semiOpen.remove(pi); + } + } - if( flags.contains( GridFlags.REQUIRE_CHANNEL ) ) - { - // close the semi open. - if( !this.semiOpen.contains( pi ) ) - { - final boolean worked; + this.closed.add(pi); + this.open.add(pi); + } + } + } - if( flags.contains( GridFlags.COMPRESSED_CHANNEL ) ) - { - worked = this.useDenseChannel( pi ); - } - else - { - worked = this.useChannel( pi ); - } + return this.open.isEmpty(); + } - if( worked && flags.contains( GridFlags.MULTIBLOCK ) ) - { - final Iterator oni = ( (IGridMultiblock) ( (IGridNode) pi ).getGridBlock() ).getMultiblockNodes(); - while( oni.hasNext() ) - { - final IGridNode otherNodes = oni.next(); - if( otherNodes != pi ) - { - this.semiOpen.add( (IPathItem) otherNodes ); - } - } - } - } - else - { - pi.incrementChannelCount( 1 ); // give a channel. - this.semiOpen.remove( pi ); - } - } + private boolean useDenseChannel(final IPathItem start) { + IPathItem pi = start; + while (pi != null) { + if (!pi.canSupportMoreChannels() + || pi.getFlags().contains(GridFlags.CANNOT_CARRY_COMPRESSED)) { + return false; + } - this.closed.add( pi ); - this.open.add( pi ); - } - } - } + pi = pi.getControllerRoute(); + } - return this.open.isEmpty(); - } + pi = start; + while (pi != null) { + this.pgc.setChannelsByBlocks(this.pgc.getChannelsByBlocks() + 1); + pi.incrementChannelCount(1); + pi = pi.getControllerRoute(); + } - private boolean useDenseChannel( final IPathItem start ) - { - IPathItem pi = start; - while( pi != null ) - { - if( !pi.canSupportMoreChannels() || pi.getFlags().contains( GridFlags.CANNOT_CARRY_COMPRESSED ) ) - { - return false; - } + this.pgc.setChannelsInUse(this.pgc.getChannelsInUse() + 1); + return true; + } - pi = pi.getControllerRoute(); - } + private boolean useChannel(final IPathItem start) { + IPathItem pi = start; + while (pi != null) { + if (!pi.canSupportMoreChannels()) { + return false; + } - pi = start; - while( pi != null ) - { - this.pgc.setChannelsByBlocks( this.pgc.getChannelsByBlocks() + 1 ); - pi.incrementChannelCount( 1 ); - pi = pi.getControllerRoute(); - } + pi = pi.getControllerRoute(); + } - this.pgc.setChannelsInUse( this.pgc.getChannelsInUse() + 1 ); - return true; - } + pi = start; + while (pi != null) { + this.pgc.setChannelsByBlocks(this.pgc.getChannelsByBlocks() + 1); + pi.incrementChannelCount(1); + pi = pi.getControllerRoute(); + } - private boolean useChannel( final IPathItem start ) - { - IPathItem pi = start; - while( pi != null ) - { - if( !pi.canSupportMoreChannels() ) - { - return false; - } + this.pgc.setChannelsInUse(this.pgc.getChannelsInUse() + 1); + return true; + } - pi = pi.getControllerRoute(); - } + public boolean isDead() { + return this.isDead; + } - pi = start; - while( pi != null ) - { - this.pgc.setChannelsByBlocks( this.pgc.getChannelsByBlocks() + 1 ); - pi.incrementChannelCount( 1 ); - pi = pi.getControllerRoute(); - } - - this.pgc.setChannelsInUse( this.pgc.getChannelsInUse() + 1 ); - return true; - } - - public boolean isDead() - { - return this.isDead; - } - - public void setDead( final boolean isDead ) - { - this.isDead = isDead; - } + public void setDead(final boolean isDead) { + this.isDead = isDead; + } } diff --git a/src/main/java/appeng/me/storage/AEExternalHandler.java b/src/main/java/appeng/me/storage/AEExternalHandler.java index 4d23b434..8247ee92 100644 --- a/src/main/java/appeng/me/storage/AEExternalHandler.java +++ b/src/main/java/appeng/me/storage/AEExternalHandler.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.implementations.tiles.ITileStorageMonitorable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageHandler; @@ -31,60 +30,55 @@ import appeng.tile.misc.TileCondenser; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class AEExternalHandler implements IExternalStorageHandler { + @Override + public boolean canHandle( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource mySrc + ) { + if (channel == StorageChannel.ITEMS && te instanceof ITileStorageMonitorable) { + return ((ITileStorageMonitorable) te).getMonitorable(d, mySrc) != null; + } -public class AEExternalHandler implements IExternalStorageHandler -{ + return te instanceof TileCondenser; + } - @Override - public boolean canHandle( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource mySrc ) - { - if( channel == StorageChannel.ITEMS && te instanceof ITileStorageMonitorable ) - { - return ( (ITileStorageMonitorable) te ).getMonitorable( d, mySrc ) != null; - } + @Override + public IMEInventory getInventory( + final TileEntity te, + final ForgeDirection d, + final StorageChannel channel, + final BaseActionSource src + ) { + if (te instanceof TileCondenser) { + if (channel == StorageChannel.ITEMS) { + return new VoidItemInventory((TileCondenser) te); + } else { + return new VoidFluidInventory((TileCondenser) te); + } + } - return te instanceof TileCondenser; - } + if (te instanceof ITileStorageMonitorable) { + final ITileStorageMonitorable iface = (ITileStorageMonitorable) te; + final IStorageMonitorable sm = iface.getMonitorable(d, src); - @Override - public IMEInventory getInventory( final TileEntity te, final ForgeDirection d, final StorageChannel channel, final BaseActionSource src ) - { - if( te instanceof TileCondenser ) - { - if( channel == StorageChannel.ITEMS ) - { - return new VoidItemInventory( (TileCondenser) te ); - } - else - { - return new VoidFluidInventory( (TileCondenser) te ); - } - } + if (channel == StorageChannel.ITEMS && sm != null) { + final IMEInventory ii = sm.getItemInventory(); + if (ii != null) { + return ii; + } + } - if( te instanceof ITileStorageMonitorable ) - { - final ITileStorageMonitorable iface = (ITileStorageMonitorable) te; - final IStorageMonitorable sm = iface.getMonitorable( d, src ); + if (channel == StorageChannel.FLUIDS && sm != null) { + final IMEInventory fi = sm.getFluidInventory(); + if (fi != null) { + return fi; + } + } + } - if( channel == StorageChannel.ITEMS && sm != null ) - { - final IMEInventory ii = sm.getItemInventory(); - if( ii != null ) - { - return ii; - } - } - - if( channel == StorageChannel.FLUIDS && sm != null ) - { - final IMEInventory fi = sm.getFluidInventory(); - if( fi != null ) - { - return fi; - } - } - } - - return null; - } + return null; + } } diff --git a/src/main/java/appeng/me/storage/CellInventory.java b/src/main/java/appeng/me/storage/CellInventory.java index a8ffdfeb..6de40600 100644 --- a/src/main/java/appeng/me/storage/CellInventory.java +++ b/src/main/java/appeng/me/storage/CellInventory.java @@ -18,6 +18,8 @@ package appeng.me.storage; +import java.util.HashSet; +import java.util.Set; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -38,575 +40,500 @@ import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.OreDictionary; -import java.util.HashSet; -import java.util.Set; - - -public class CellInventory implements ICellInventory -{ - public static final int cellItemType = AEConfig.instance.ItemTypeLimit; - private static final String ITEM_TYPE_TAG = "it"; - private static final String ITEM_COUNT_TAG = "ic"; - private static final String ITEM_SLOT = "#"; - private static final String ITEM_SLOT_COUNT = "@"; - private static final Set BLACK_LIST = new HashSet(); - private static String[] itemSlots; - private static String[] itemSlotCount; - private final NBTTagCompound tagCompound; - private final ISaveProvider container; - private int maxItemTypes = cellItemType; - private short storedItems = 0; - private int storedItemCount = 0; - private IItemList cellItems; - private final ItemStack cellItem; - private IStorageCell cellType; - - private CellInventory( final ItemStack o, final ISaveProvider container ) throws AppEngException - { - if( itemSlots == null ) - { - itemSlots = new String[this.maxItemTypes]; - itemSlotCount = new String[this.maxItemTypes]; - - for( int x = 0; x < this.maxItemTypes; x++ ) - { - itemSlots[x] = ITEM_SLOT + x; - itemSlotCount[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.cellItem = o; - - final Item type = this.cellItem.getItem(); - - if( type instanceof IStorageCell ) - { - this.cellType = (IStorageCell) this.cellItem.getItem(); - this.maxItemTypes = this.cellType.getTotalTypes( this.cellItem ); - } - - if( this.cellType == null ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - if( !this.cellType.isStorageCell( this.cellItem ) ) - { - throw new AppEngException( "ItemStack was used as a cell, but was not a cell!" ); - } - - if( this.maxItemTypes > cellItemType ) - { - this.maxItemTypes = cellItemType; - } - if( this.maxItemTypes < 1 ) - { - this.maxItemTypes = 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( final ItemStack o, final ISaveProvider container2 ) - { - try - { - return new CellInventoryHandler( new CellInventory( o, container2 ) ); - } - catch( final AppEngException e ) - { - return null; - } - } - - private static boolean isStorageCell( final ItemStack itemStack ) - { - if( itemStack == null ) - { - return false; - } - - try - { - final Item type = itemStack.getItem(); - - if( type instanceof IStorageCell ) - { - return !( (IStorageCell) type ).storableInStorageCell(); - } - } - catch( final Throwable err ) - { - return true; - } - - return false; - } - - public static boolean isCell( final ItemStack itemStack ) - { - if( itemStack == null ) - { - return false; - } - - final Item type = itemStack.getItem(); - - if( type instanceof IStorageCell ) - { - return ( (IStorageCell) type ).isStorageCell( itemStack ); - } - - return false; - } - - public static void addBasicBlackList( final int itemID, final int meta ) - { - BLACK_LIST.add( ( meta << Platform.DEF_OFFSET ) | itemID ); - } - - private static boolean isBlackListed( final 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( final IMEInventory meInventory ) - { - return meInventory.getAvailableItems( AEApi.instance().storage().createItemList() ).isEmpty(); - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( input == null ) - { - return null; - } - - if( input.getStackSize() == 0 ) - { - return null; - } - - if( isBlackListed( input ) || this.cellType.isBlackListed( this.cellItem, input ) ) - { - return input; - } - - final ItemStack sharedItemStack = input.getItemStack(); - - if( CellInventory.isStorageCell( sharedItemStack ) ) - { - final IMEInventory meInventory = getCell( sharedItemStack, null ); - - if( meInventory != null && !this.isEmpty( meInventory ) ) - { - return input; - } - } - - final IAEItemStack l = this.getCellItems().findPrecise( input ); - - if( l != null ) - { - final long remainingItemSlots = this.getRemainingItemCount(); - - if( remainingItemSlots < 0 ) - { - return input; - } - - if( input.getStackSize() > remainingItemSlots ) - { - final IAEItemStack r = input.copy(); - r.setStackSize( r.getStackSize() - remainingItemSlots ); - - if( mode == Actionable.MODULATE ) - { - 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! - { - final int remainingItemCount = (int) this.getRemainingItemCount() - this.getBytesPerType() * 8; - - if( remainingItemCount > 0 ) - { - if( input.getStackSize() > remainingItemCount ) - { - final ItemStack toReturn = Platform.cloneItemStack( sharedItemStack ); - toReturn.stackSize = sharedItemStack.stackSize - remainingItemCount; - - if( mode == Actionable.MODULATE ) - { - final 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( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( request == null ) - { - return null; - } - - final long size = Math.min( Integer.MAX_VALUE, request.getStackSize() ); - - IAEItemStack results = null; - - final 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(); - } - } - } - - return results; - } - - private IItemList getCellItems() - { - if( this.cellItems == null ) - { - this.loadCellItems(); - } - - return this.cellItems; - } - - private void updateItemCount( final long delta ) - { - this.storedItemCount += delta; - this.tagCompound.setInteger( ITEM_COUNT_TAG, this.storedItemCount ); - } - - private void saveChanges() - { - // cellItems.clean(); - int itemCount = 0; - - // add new pretty stuff... - int x = 0; - - for( final IAEItemStack v : this.cellItems ) - { - itemCount += v.getStackSize(); - - final NBTBase c = this.tagCompound.getTag( itemSlots[x] ); - - if( c instanceof NBTTagCompound ) - { - v.writeToNBT( (NBTTagCompound) c ); - } - else - { - final NBTTagCompound g = new NBTTagCompound(); - v.writeToNBT( g ); - this.tagCompound.setTag( itemSlots[x], g ); - } - - /* - * NBTBase tagSlotCount = tagCompound.getTag( itemSlotCount[x] ); if ( tagSlotCount instanceof - * NBTTagInt ) ((NBTTagInt) tagSlotCount).data = (int) v.getStackSize(); else - */ - this.tagCompound.setInteger( itemSlotCount[x], (int) v.getStackSize() ); - - x++; - } - - // NBTBase tagType = tagCompound.getTag( ITEM_TYPE_TAG ); - // NBTBase tagCount = tagCompound.getTag( ITEM_COUNT_TAG ); - final short oldStoredItems = this.storedItems; - - /* - * if ( tagType instanceof NBTTagShort ) ((NBTTagShort) tagType).data = storedItems = (short) cellItems.size(); - * else - */ - this.storedItems = (short) this.cellItems.size(); - - if( this.cellItems.isEmpty() ) - { - this.tagCompound.removeTag( ITEM_TYPE_TAG ); - } - else - { - this.tagCompound.setShort( ITEM_TYPE_TAG, this.storedItems ); - } - - /* - * if ( tagCount instanceof NBTTagInt ) ((NBTTagInt) tagCount).data = storedItemCount = itemCount; else - */ - this.storedItemCount = itemCount; - - if( itemCount == 0 ) - { - this.tagCompound.removeTag( ITEM_COUNT_TAG ); - } - else - { - this.tagCompound.setInteger( ITEM_COUNT_TAG, itemCount ); - } - - // clean any old crusty stuff... - for( ; x < oldStoredItems && x < this.maxItemTypes; x++ ) - { - this.tagCompound.removeTag( itemSlots[x] ); - this.tagCompound.removeTag( itemSlotCount[x] ); - } - - if( this.container != null ) - { - this.container.saveChanges( this ); - } - } - - private void loadCellItems() - { - if( this.cellItems == null ) - { - this.cellItems = AEApi.instance().storage().createItemList(); - } - - this.cellItems.resetStatus(); // clears totals and stuff. - - final int types = (int) this.getStoredItemTypes(); - - for( int x = 0; x < types; x++ ) - { - final ItemStack t = ItemStack.loadItemStackFromNBT( this.tagCompound.getCompoundTag( itemSlots[x] ) ); - - if( t != null ) - { - t.stackSize = this.tagCompound.getInteger( itemSlotCount[x] ); - - if( t.stackSize > 0 ) - { - this.cellItems.add( AEItemStack.create( t ) ); - } - } - } - - // cellItems.clean(); - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack i : this.getCellItems() ) - { - out.add( i ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public ItemStack getItemStack() - { - return this.cellItem; - } - - @Override - public double getIdleDrain() - { - return this.cellType.getIdleDrain(); - } - - @Override - public FuzzyMode getFuzzyMode() - { - return this.cellType.getFuzzyMode( this.cellItem ); - } - - @Override - public IInventory getConfigInventory() - { - return this.cellType.getConfigInventory( this.cellItem ); - } - - @Override - public IInventory getUpgradesInventory() - { - return this.cellType.getUpgradesInventory( this.cellItem ); - } - - @Override - public int getBytesPerType() - { - return this.cellType.getBytesPerType( this.cellItem ); - } - - @Override - public boolean canHoldNewItem() - { - final 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.cellItem ); - } - - @Override - public long getFreeBytes() - { - return this.getTotalBytes() - this.getUsedBytes(); - } - - @Override - public long getUsedBytes() - { - final long bytesForItemCount = ( this.getStoredItemCount() + this.getUnusedItemCount() ) / 8; - - return bytesForItemCount; - } - - @Override - public long getTotalItemTypes() - { - return this.maxItemTypes; - } - - @Override - public long getStoredItemCount() - { - return this.storedItemCount; - } - - @Override - public long getStoredItemTypes() - { - return this.storedItems; - } - - @Override - public long getRemainingItemTypes() - { - final long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); - final long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); - - return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; - } - - @Override - public long getRemainingItemCount() - { - final long remaining = this.getFreeBytes() * 8 + this.getUnusedItemCount(); - - return remaining > 0 ? remaining : 0; - } - - @Override - public int getUnusedItemCount() - { - final 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; - } +public class CellInventory implements ICellInventory { + public static final int cellItemType = AEConfig.instance.ItemTypeLimit; + private static final String ITEM_TYPE_TAG = "it"; + private static final String ITEM_COUNT_TAG = "ic"; + private static final String ITEM_SLOT = "#"; + private static final String ITEM_SLOT_COUNT = "@"; + private static final Set BLACK_LIST = new HashSet(); + private static String[] itemSlots; + private static String[] itemSlotCount; + private final NBTTagCompound tagCompound; + private final ISaveProvider container; + private int maxItemTypes = cellItemType; + private short storedItems = 0; + private int storedItemCount = 0; + private IItemList cellItems; + private final ItemStack cellItem; + private IStorageCell cellType; + + private CellInventory(final ItemStack o, final ISaveProvider container) + throws AppEngException { + if (itemSlots == null) { + itemSlots = new String[this.maxItemTypes]; + itemSlotCount = new String[this.maxItemTypes]; + + for (int x = 0; x < this.maxItemTypes; x++) { + itemSlots[x] = ITEM_SLOT + x; + itemSlotCount[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.cellItem = o; + + final Item type = this.cellItem.getItem(); + + if (type instanceof IStorageCell) { + this.cellType = (IStorageCell) this.cellItem.getItem(); + this.maxItemTypes = this.cellType.getTotalTypes(this.cellItem); + } + + if (this.cellType == null) { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!" + ); + } + + if (!this.cellType.isStorageCell(this.cellItem)) { + throw new AppEngException("ItemStack was used as a cell, but was not a cell!" + ); + } + + if (this.maxItemTypes > cellItemType) { + this.maxItemTypes = cellItemType; + } + if (this.maxItemTypes < 1) { + this.maxItemTypes = 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(final ItemStack o, final ISaveProvider container2) { + try { + return new CellInventoryHandler(new CellInventory(o, container2)); + } catch (final AppEngException e) { + return null; + } + } + + private static boolean isStorageCell(final ItemStack itemStack) { + if (itemStack == null) { + return false; + } + + try { + final Item type = itemStack.getItem(); + + if (type instanceof IStorageCell) { + return !((IStorageCell) type).storableInStorageCell(); + } + } catch (final Throwable err) { + return true; + } + + return false; + } + + public static boolean isCell(final ItemStack itemStack) { + if (itemStack == null) { + return false; + } + + final Item type = itemStack.getItem(); + + if (type instanceof IStorageCell) { + return ((IStorageCell) type).isStorageCell(itemStack); + } + + return false; + } + + public static void addBasicBlackList(final int itemID, final int meta) { + BLACK_LIST.add((meta << Platform.DEF_OFFSET) | itemID); + } + + private static boolean isBlackListed(final 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(final IMEInventory meInventory) { + return meInventory.getAvailableItems(AEApi.instance().storage().createItemList()) + .isEmpty(); + } + + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + if (input == null) { + return null; + } + + if (input.getStackSize() == 0) { + return null; + } + + if (isBlackListed(input) || this.cellType.isBlackListed(this.cellItem, input)) { + return input; + } + + final ItemStack sharedItemStack = input.getItemStack(); + + if (CellInventory.isStorageCell(sharedItemStack)) { + final IMEInventory meInventory = getCell(sharedItemStack, null); + + if (meInventory != null && !this.isEmpty(meInventory)) { + return input; + } + } + + final IAEItemStack l = this.getCellItems().findPrecise(input); + + if (l != null) { + final long remainingItemSlots = this.getRemainingItemCount(); + + if (remainingItemSlots < 0) { + return input; + } + + if (input.getStackSize() > remainingItemSlots) { + final IAEItemStack r = input.copy(); + r.setStackSize(r.getStackSize() - remainingItemSlots); + + if (mode == Actionable.MODULATE) { + 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! + { + final int remainingItemCount + = (int) this.getRemainingItemCount() - this.getBytesPerType() * 8; + + if (remainingItemCount > 0) { + if (input.getStackSize() > remainingItemCount) { + final ItemStack toReturn = Platform.cloneItemStack(sharedItemStack); + toReturn.stackSize = sharedItemStack.stackSize - remainingItemCount; + + if (mode == Actionable.MODULATE) { + final 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( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + if (request == null) { + return null; + } + + final long size = Math.min(Integer.MAX_VALUE, request.getStackSize()); + + IAEItemStack results = null; + + final 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(); + } + } + } + + return results; + } + + private IItemList getCellItems() { + if (this.cellItems == null) { + this.loadCellItems(); + } + + return this.cellItems; + } + + private void updateItemCount(final long delta) { + this.storedItemCount += delta; + this.tagCompound.setInteger(ITEM_COUNT_TAG, this.storedItemCount); + } + + private void saveChanges() { + // cellItems.clean(); + int itemCount = 0; + + // add new pretty stuff... + int x = 0; + + for (final IAEItemStack v : this.cellItems) { + itemCount += v.getStackSize(); + + final NBTBase c = this.tagCompound.getTag(itemSlots[x]); + + if (c instanceof NBTTagCompound) { + v.writeToNBT((NBTTagCompound) c); + } else { + final NBTTagCompound g = new NBTTagCompound(); + v.writeToNBT(g); + this.tagCompound.setTag(itemSlots[x], g); + } + + /* + * NBTBase tagSlotCount = tagCompound.getTag( itemSlotCount[x] ); if ( + * tagSlotCount instanceof NBTTagInt ) ((NBTTagInt) tagSlotCount).data = (int) + * v.getStackSize(); else + */ + this.tagCompound.setInteger(itemSlotCount[x], (int) v.getStackSize()); + + x++; + } + + // NBTBase tagType = tagCompound.getTag( ITEM_TYPE_TAG ); + // NBTBase tagCount = tagCompound.getTag( ITEM_COUNT_TAG ); + final short oldStoredItems = this.storedItems; + + /* + * if ( tagType instanceof NBTTagShort ) ((NBTTagShort) tagType).data = + * storedItems = (short) cellItems.size(); else + */ + this.storedItems = (short) this.cellItems.size(); + + if (this.cellItems.isEmpty()) { + this.tagCompound.removeTag(ITEM_TYPE_TAG); + } else { + this.tagCompound.setShort(ITEM_TYPE_TAG, this.storedItems); + } + + /* + * if ( tagCount instanceof NBTTagInt ) ((NBTTagInt) tagCount).data = + * storedItemCount = itemCount; else + */ + this.storedItemCount = itemCount; + + if (itemCount == 0) { + this.tagCompound.removeTag(ITEM_COUNT_TAG); + } else { + this.tagCompound.setInteger(ITEM_COUNT_TAG, itemCount); + } + + // clean any old crusty stuff... + for (; x < oldStoredItems && x < this.maxItemTypes; x++) { + this.tagCompound.removeTag(itemSlots[x]); + this.tagCompound.removeTag(itemSlotCount[x]); + } + + if (this.container != null) { + this.container.saveChanges(this); + } + } + + private void loadCellItems() { + if (this.cellItems == null) { + this.cellItems = AEApi.instance().storage().createItemList(); + } + + this.cellItems.resetStatus(); // clears totals and stuff. + + final int types = (int) this.getStoredItemTypes(); + + for (int x = 0; x < types; x++) { + final ItemStack t = ItemStack.loadItemStackFromNBT( + this.tagCompound.getCompoundTag(itemSlots[x]) + ); + + if (t != null) { + t.stackSize = this.tagCompound.getInteger(itemSlotCount[x]); + + if (t.stackSize > 0) { + this.cellItems.add(AEItemStack.create(t)); + } + } + } + + // cellItems.clean(); + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack i : this.getCellItems()) { + out.add(i); + } + + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public ItemStack getItemStack() { + return this.cellItem; + } + + @Override + public double getIdleDrain() { + return this.cellType.getIdleDrain(); + } + + @Override + public FuzzyMode getFuzzyMode() { + return this.cellType.getFuzzyMode(this.cellItem); + } + + @Override + public IInventory getConfigInventory() { + return this.cellType.getConfigInventory(this.cellItem); + } + + @Override + public IInventory getUpgradesInventory() { + return this.cellType.getUpgradesInventory(this.cellItem); + } + + @Override + public int getBytesPerType() { + return this.cellType.getBytesPerType(this.cellItem); + } + + @Override + public boolean canHoldNewItem() { + final 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.cellItem); + } + + @Override + public long getFreeBytes() { + return this.getTotalBytes() - this.getUsedBytes(); + } + + @Override + public long getUsedBytes() { + final long bytesForItemCount + = (this.getStoredItemCount() + this.getUnusedItemCount()) / 8; + + return bytesForItemCount; + } + + @Override + public long getTotalItemTypes() { + return this.maxItemTypes; + } + + @Override + public long getStoredItemCount() { + return this.storedItemCount; + } + + @Override + public long getStoredItemTypes() { + return this.storedItems; + } + + @Override + public long getRemainingItemTypes() { + final long basedOnStorage = this.getFreeBytes() / this.getBytesPerType(); + final long baseOnTotal = this.getTotalItemTypes() - this.getStoredItemTypes(); + + return basedOnStorage > baseOnTotal ? baseOnTotal : basedOnStorage; + } + + @Override + public long getRemainingItemCount() { + final long remaining = this.getFreeBytes() * 8 + this.getUnusedItemCount(); + + return remaining > 0 ? remaining : 0; + } + + @Override + public int getUnusedItemCount() { + final 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 d85c4e96..793b6363 100644 --- a/src/main/java/appeng/me/storage/CellInventoryHandler.java +++ b/src/main/java/appeng/me/storage/CellInventoryHandler.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.config.IncludeExclude; @@ -36,114 +35,100 @@ import appeng.util.prioitylist.PrecisePriorityList; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class CellInventoryHandler + extends MEInventoryHandler implements ICellInventoryHandler { + CellInventoryHandler(final IMEInventory c) { + super(c, StorageChannel.ITEMS); -public class CellInventoryHandler extends MEInventoryHandler implements ICellInventoryHandler -{ + final ICellInventory ci = this.getCellInv(); - CellInventoryHandler( final IMEInventory c ) - { - super( c, StorageChannel.ITEMS ); + if (ci != null) { + final IItemList priorityList + = AEApi.instance().storage().createItemList(); - final ICellInventory ci = this.getCellInv(); + final IInventory upgrades = ci.getUpgradesInventory(); + final IInventory config = ci.getConfigInventory(); + final FuzzyMode fzMode = ci.getFuzzyMode(); - if( ci != null ) - { - final IItemList priorityList = AEApi.instance().storage().createItemList(); + boolean hasInverter = false; + boolean hasFuzzy = false; - final IInventory upgrades = ci.getUpgradesInventory(); - final IInventory config = ci.getConfigInventory(); - final FuzzyMode fzMode = ci.getFuzzyMode(); + for (int x = 0; x < upgrades.getSizeInventory(); x++) { + final ItemStack is = upgrades.getStackInSlot(x); + if (is != null && is.getItem() instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) is.getItem()).getType(is); + if (u != null) { + switch (u) { + case FUZZY: + hasFuzzy = true; + break; + case INVERTER: + hasInverter = true; + break; + default: + } + } + } + } - boolean hasInverter = false; - boolean hasFuzzy = false; + for (int x = 0; x < config.getSizeInventory(); x++) { + final ItemStack is = config.getStackInSlot(x); + if (is != null) { + priorityList.add(AEItemStack.create(is)); + } + } - for( int x = 0; x < upgrades.getSizeInventory(); x++ ) - { - final ItemStack is = upgrades.getStackInSlot( x ); - if( is != null && is.getItem() instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) is.getItem() ).getType( is ); - if( u != null ) - { - switch( u ) - { - case FUZZY: - hasFuzzy = true; - break; - case INVERTER: - hasInverter = true; - break; - default: - } - } - } - } + this.setWhitelist( + hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST + ); - for( int x = 0; x < config.getSizeInventory(); x++ ) - { - final ItemStack is = config.getStackInSlot( x ); - if( is != null ) - { - priorityList.add( AEItemStack.create( is ) ); - } - } + if (!priorityList.isEmpty()) { + if (hasFuzzy) { + this.setPartitionList( + new FuzzyPriorityList(priorityList, fzMode) + ); + } else { + this.setPartitionList( + new PrecisePriorityList(priorityList) + ); + } + } + } + } - this.setWhitelist( hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); + @Override + public ICellInventory getCellInv() { + Object o = this.getInternal(); - if( !priorityList.isEmpty() ) - { - if( hasFuzzy ) - { - this.setPartitionList( new FuzzyPriorityList( priorityList, fzMode ) ); - } - else - { - this.setPartitionList( new PrecisePriorityList( priorityList ) ); - } - } - } - } + if (o instanceof MEPassThrough) { + o = ((MEPassThrough) o).getInternal(); + } - @Override - public ICellInventory getCellInv() - { - Object o = this.getInternal(); + return (ICellInventory) (o instanceof ICellInventory ? o : null); + } - if( o instanceof MEPassThrough ) - { - o = ( (MEPassThrough) o ).getInternal(); - } + @Override + public boolean isPreformatted() { + return !this.getPartitionList().isEmpty(); + } - return (ICellInventory) ( o instanceof ICellInventory ? o : null ); - } + @Override + public boolean isFuzzy() { + return this.getPartitionList() instanceof FuzzyPriorityList; + } - @Override - public boolean isPreformatted() - { - return !this.getPartitionList().isEmpty(); - } + @Override + public IncludeExclude getIncludeExcludeMode() { + return this.getWhitelist(); + } - @Override - public boolean isFuzzy() - { - return this.getPartitionList() instanceof FuzzyPriorityList; - } + public int getStatusForCell() { + int val = this.getCellInv().getStatusForCell(); - @Override - public IncludeExclude getIncludeExcludeMode() - { - return this.getWhitelist(); - } + if (val == 1 && this.isPreformatted()) { + val = 2; + } - public int getStatusForCell() - { - int val = this.getCellInv().getStatusForCell(); - - if( val == 1 && this.isPreformatted() ) - { - val = 2; - } - - return val; - } + return val; + } } diff --git a/src/main/java/appeng/me/storage/CreativeCellInventory.java b/src/main/java/appeng/me/storage/CreativeCellInventory.java index 0dc41277..8ecbc55b 100644 --- a/src/main/java/appeng/me/storage/CreativeCellInventory.java +++ b/src/main/java/appeng/me/storage/CreativeCellInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -31,104 +30,89 @@ import appeng.items.contents.CellConfig; import appeng.util.item.AEItemStack; import net.minecraft.item.ItemStack; +public class CreativeCellInventory implements IMEInventoryHandler { + private final IItemList itemListCache + = AEApi.instance().storage().createItemList(); -public class CreativeCellInventory implements IMEInventoryHandler -{ + protected CreativeCellInventory(final ItemStack o) { + final CellConfig cc = new CellConfig(o); + for (final ItemStack is : cc) { + if (is != null) { + final IAEItemStack i = AEItemStack.create(is); + i.setStackSize(Integer.MAX_VALUE); + this.itemListCache.add(i); + } + } + } - private final IItemList itemListCache = AEApi.instance().storage().createItemList(); + public static IMEInventoryHandler getCell(final ItemStack o) { + return new CellInventoryHandler(new CreativeCellInventory(o)); + } - protected CreativeCellInventory( final ItemStack o ) - { - final CellConfig cc = new CellConfig( o ); - for( final ItemStack is : cc ) - { - if( is != null ) - { - final IAEItemStack i = AEItemStack.create( is ); - i.setStackSize( Integer.MAX_VALUE ); - this.itemListCache.add( i ); - } - } - } + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + final IAEItemStack local = this.itemListCache.findPrecise(input); + if (local == null) { + return input; + } - public static IMEInventoryHandler getCell( final ItemStack o ) - { - return new CellInventoryHandler( new CreativeCellInventory( o ) ); - } + return null; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - final IAEItemStack local = this.itemListCache.findPrecise( input ); - if( local == null ) - { - return input; - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + final IAEItemStack local = this.itemListCache.findPrecise(request); + if (local == null) { + return null; + } - return null; - } + return request.copy(); + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - final IAEItemStack local = this.itemListCache.findPrecise( request ); - if( local == null ) - { - return null; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack ais : this.itemListCache) { + out.add(ais); + } + return out; + } - return request.copy(); - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack ais : this.itemListCache ) - { - out.add( ais ); - } - return out; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return this.itemListCache.findPrecise(input) != null; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public boolean canAccept(final IAEItemStack input) { + return this.itemListCache.findPrecise(input) != null; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return this.itemListCache.findPrecise( input ) != null; - } + @Override + public int getPriority() { + return 0; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - return this.itemListCache.findPrecise( input ) != null; - } + @Override + public int getSlot() { + return 0; + } - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final 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 108f096d..6c8c0cce 100644 --- a/src/main/java/appeng/me/storage/DriveWatcher.java +++ b/src/main/java/appeng/me/storage/DriveWatcher.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.Actionable; import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.networking.security.BaseActionSource; @@ -27,58 +26,57 @@ import appeng.api.storage.IMEInventory; import appeng.api.storage.data.IAEStack; import net.minecraft.item.ItemStack; +public class DriveWatcher> extends MEInventoryHandler { + private final int oldStatus = 0; + private final ItemStack is; + private final ICellHandler handler; + private final IChestOrDrive cord; -public class DriveWatcher> extends MEInventoryHandler -{ + public DriveWatcher( + final IMEInventory i, + final ItemStack is, + final ICellHandler han, + final IChestOrDrive cod + ) { + super(i, i.getChannel()); + this.is = is; + this.handler = han; + this.cord = cod; + } - private final int oldStatus = 0; - private final ItemStack is; - private final ICellHandler handler; - private final IChestOrDrive cord; + @Override + public T + injectItems(final T input, final Actionable type, final BaseActionSource src) { + final long size = input.getStackSize(); - public DriveWatcher( final IMEInventory i, final ItemStack is, final ICellHandler han, final IChestOrDrive cod ) - { - super( i, i.getChannel() ); - this.is = is; - this.handler = han; - this.cord = cod; - } + final T a = super.injectItems(input, type, src); - @Override - public T injectItems( final T input, final Actionable type, final BaseActionSource src ) - { - final long size = input.getStackSize(); + if (a == null || a.getStackSize() != size) { + final int newStatus + = this.handler.getStatusForCell(this.is, this.getInternal()); - final T a = super.injectItems( input, type, src ); + if (newStatus != this.oldStatus) { + this.cord.blinkCell(this.getSlot()); + } + } - if( a == null || a.getStackSize() != size ) - { - final int newStatus = this.handler.getStatusForCell( this.is, this.getInternal() ); + return a; + } - if( newStatus != this.oldStatus ) - { - this.cord.blinkCell( this.getSlot() ); - } - } + @Override + public T + extractItems(final T request, final Actionable type, final BaseActionSource src) { + final T a = super.extractItems(request, type, src); - return a; - } + if (a != null) { + final int newStatus + = this.handler.getStatusForCell(this.is, this.getInternal()); - @Override - public T extractItems( final T request, final Actionable type, final BaseActionSource src ) - { - final T a = super.extractItems( request, type, src ); + if (newStatus != this.oldStatus) { + this.cord.blinkCell(this.getSlot()); + } + } - if( a != null ) - { - final int newStatus = this.handler.getStatusForCell( this.is, this.getInternal() ); - - if( newStatus != this.oldStatus ) - { - this.cord.blinkCell( this.getSlot() ); - } - } - - return a; - } + return a; + } } diff --git a/src/main/java/appeng/me/storage/ItemWatcher.java b/src/main/java/appeng/me/storage/ItemWatcher.java index 7788167f..2663639b 100644 --- a/src/main/java/appeng/me/storage/ItemWatcher.java +++ b/src/main/java/appeng/me/storage/ItemWatcher.java @@ -18,180 +18,152 @@ package appeng.me.storage; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; import appeng.api.networking.storage.IStackWatcher; import appeng.api.networking.storage.IStackWatcherHost; import appeng.api.storage.data.IAEStack; import appeng.me.cache.GridStorageCache; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; - - /** - * Maintain my interests, and a global watch list, they should always be fully synchronized. + * Maintain my interests, and a global watch list, they should always be fully + * synchronized. */ -public class ItemWatcher implements IStackWatcher -{ +public class ItemWatcher implements IStackWatcher { + private final GridStorageCache gsc; + private final IStackWatcherHost myObject; + private final HashSet myInterests = new HashSet(); - private final GridStorageCache gsc; - private final IStackWatcherHost myObject; - private final HashSet myInterests = new HashSet(); + public ItemWatcher(final GridStorageCache cache, final IStackWatcherHost host) { + this.gsc = cache; + this.myObject = host; + } - public ItemWatcher( final GridStorageCache cache, final IStackWatcherHost host ) - { - this.gsc = cache; - this.myObject = host; - } + public IStackWatcherHost getHost() { + return this.myObject; + } - public IStackWatcherHost getHost() - { - return this.myObject; - } + @Override + public int size() { + return this.myInterests.size(); + } - @Override - public int size() - { - return this.myInterests.size(); - } + @Override + public boolean isEmpty() { + return this.myInterests.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.myInterests.isEmpty(); - } + @Override + public boolean contains(final Object o) { + return this.myInterests.contains(o); + } - @Override - public boolean contains( final Object o ) - { - return this.myInterests.contains( o ); - } + @Override + public Iterator iterator() { + return new ItemWatcherIterator(this, this.myInterests.iterator()); + } - @Override - public Iterator iterator() - { - return new ItemWatcherIterator( this, this.myInterests.iterator() ); - } + @Override + public Object[] toArray() { + return this.myInterests.toArray(); + } - @Override - public Object[] toArray() - { - return this.myInterests.toArray(); - } + @Override + public T[] toArray(final T[] a) { + return this.myInterests.toArray(a); + } - @Override - public T[] toArray( final T[] a ) - { - return this.myInterests.toArray( a ); - } + @Override + public boolean add(final IAEStack e) { + if (this.myInterests.contains(e)) { + return false; + } - @Override - public boolean add( final IAEStack e ) - { - if( this.myInterests.contains( e ) ) - { - return false; - } + return this.myInterests.add(e.copy()) + && this.gsc.getInterestManager().put(e, this); + } - return this.myInterests.add( e.copy() ) && this.gsc.getInterestManager().put( e, this ); - } + @Override + public boolean remove(final Object o) { + return this.myInterests.remove(o) + && this.gsc.getInterestManager().remove((IAEStack) o, this); + } - @Override - public boolean remove( final Object o ) - { - return this.myInterests.remove( o ) && this.gsc.getInterestManager().remove( (IAEStack) o, this ); - } + @Override + public boolean containsAll(final Collection c) { + return this.myInterests.containsAll(c); + } - @Override - public boolean containsAll( final Collection c ) - { - return this.myInterests.containsAll( c ); - } + @Override + public boolean addAll(final Collection c) { + boolean didChange = false; - @Override - public boolean addAll( final Collection c ) - { - boolean didChange = false; + for (final IAEStack o : c) { + didChange = this.add(o) || didChange; + } - for( final IAEStack o : c ) - { - didChange = this.add( o ) || didChange; - } + return didChange; + } - return didChange; - } + @Override + public boolean removeAll(final Collection c) { + boolean didSomething = false; + for (final Object o : c) { + didSomething = this.remove(o) || didSomething; + } + return didSomething; + } - @Override - public boolean removeAll( final Collection c ) - { - boolean didSomething = false; - for( final Object o : c ) - { - didSomething = this.remove( o ) || didSomething; - } - return didSomething; - } + @Override + public boolean retainAll(final Collection c) { + boolean changed = false; + final Iterator i = this.iterator(); - @Override - public boolean retainAll( final Collection c ) - { - boolean changed = false; - final Iterator i = this.iterator(); + while (i.hasNext()) { + if (!c.contains(i.next())) { + i.remove(); + changed = true; + } + } - while( i.hasNext() ) - { - if( !c.contains( i.next() ) ) - { - i.remove(); - changed = true; - } - } + return changed; + } - return changed; - } + @Override + public void clear() { + final Iterator i = this.myInterests.iterator(); + while (i.hasNext()) { + this.gsc.getInterestManager().remove(i.next(), this); + i.remove(); + } + } - @Override - public void clear() - { - final Iterator i = this.myInterests.iterator(); - while( i.hasNext() ) - { - this.gsc.getInterestManager().remove( i.next(), this ); - i.remove(); - } - } + private class ItemWatcherIterator implements Iterator { + private final ItemWatcher watcher; + private final Iterator interestIterator; + private IAEStack myLast; - private class ItemWatcherIterator implements Iterator - { + public ItemWatcherIterator(final ItemWatcher parent, final Iterator i) { + this.watcher = parent; + this.interestIterator = i; + } - private final ItemWatcher watcher; - private final Iterator interestIterator; - private IAEStack myLast; + @Override + public boolean hasNext() { + return this.interestIterator.hasNext(); + } - public ItemWatcherIterator( final ItemWatcher parent, final Iterator i ) - { - this.watcher = parent; - this.interestIterator = i; - } + @Override + public IAEStack next() { + return this.myLast = this.interestIterator.next(); + } - @Override - public boolean hasNext() - { - return this.interestIterator.hasNext(); - } - - @Override - public IAEStack next() - { - return this.myLast = this.interestIterator.next(); - } - - @Override - public void remove() - { - ItemWatcher.this.gsc.getInterestManager().remove( this.myLast, this.watcher ); - this.interestIterator.remove(); - } - } + @Override + public void remove() { + ItemWatcher.this.gsc.getInterestManager().remove(this.myLast, this.watcher); + this.interestIterator.remove(); + } + } } diff --git a/src/main/java/appeng/me/storage/MEIInventoryWrapper.java b/src/main/java/appeng/me/storage/MEIInventoryWrapper.java index 5177d520..e5283c22 100644 --- a/src/main/java/appeng/me/storage/MEIInventoryWrapper.java +++ b/src/main/java/appeng/me/storage/MEIInventoryWrapper.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IMEInventory; @@ -31,194 +30,165 @@ import appeng.util.item.AEItemStack; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public class MEIInventoryWrapper implements IMEInventory { + private final IInventory target; + private final InventoryAdaptor adaptor; -public class MEIInventoryWrapper implements IMEInventory -{ + public MEIInventoryWrapper(final IInventory m, final InventoryAdaptor ia) { + this.target = m; + this.adaptor = ia; + } - private final IInventory target; - private final InventoryAdaptor adaptor; + @Override + public IAEItemStack injectItems( + final IAEItemStack iox, final Actionable mode, final BaseActionSource src + ) { + final ItemStack input = iox.getItemStack(); - public MEIInventoryWrapper( final IInventory m, final InventoryAdaptor ia ) - { - this.target = m; - this.adaptor = ia; - } + if (this.adaptor != null) { + final ItemStack is = mode == Actionable.SIMULATE + ? this.adaptor.simulateAdd(input) + : this.adaptor.addItems(input); + if (is == null) { + return null; + } + return AEItemStack.create(is); + } - @Override - public IAEItemStack injectItems( final IAEItemStack iox, final Actionable mode, final BaseActionSource src ) - { - final ItemStack input = iox.getItemStack(); + final ItemStack out = Platform.cloneItemStack(input); - if( this.adaptor != null ) - { - final ItemStack is = mode == Actionable.SIMULATE ? this.adaptor.simulateAdd( input ) : this.adaptor.addItems( input ); - if( is == null ) - { - return null; - } - return AEItemStack.create( is ); - } + if (mode + == Actionable + .MODULATE) // absolutely no need for a first run in simulate mode. + { + for (int x = 0; x < this.target.getSizeInventory(); x++) { + final ItemStack t = this.target.getStackInSlot(x); - final ItemStack out = Platform.cloneItemStack( input ); + if (Platform.isSameItem(t, input)) { + final int oriStack = t.stackSize; + t.stackSize += out.stackSize; - if( mode == Actionable.MODULATE ) // absolutely no need for a first run in simulate mode. - { - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - final ItemStack t = this.target.getStackInSlot( x ); + this.target.setInventorySlotContents(x, t); - if( Platform.isSameItem( t, input ) ) - { - final int oriStack = t.stackSize; - t.stackSize += out.stackSize; + if (t.stackSize > this.target.getInventoryStackLimit()) { + t.stackSize = this.target.getInventoryStackLimit(); + } - this.target.setInventorySlotContents( x, t ); + if (t.stackSize > t.getMaxStackSize()) { + t.stackSize = t.getMaxStackSize(); + } - if( t.stackSize > this.target.getInventoryStackLimit() ) - { - t.stackSize = this.target.getInventoryStackLimit(); - } + out.stackSize -= t.stackSize - oriStack; - if( t.stackSize > t.getMaxStackSize() ) - { - t.stackSize = t.getMaxStackSize(); - } + if (out.stackSize <= 0) { + return null; + } + } + } + } - out.stackSize -= t.stackSize - oriStack; + for (int x = 0; x < this.target.getSizeInventory(); x++) { + ItemStack t = this.target.getStackInSlot(x); - if( out.stackSize <= 0 ) - { - return null; - } - } - } - } + if (t == null) { + t = Platform.cloneItemStack(input); + t.stackSize = out.stackSize; - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - ItemStack t = this.target.getStackInSlot( x ); + if (t.stackSize > this.target.getInventoryStackLimit()) { + t.stackSize = this.target.getInventoryStackLimit(); + } - if( t == null ) - { - t = Platform.cloneItemStack( input ); - t.stackSize = out.stackSize; + out.stackSize -= t.stackSize; + if (mode == Actionable.MODULATE) { + this.target.setInventorySlotContents(x, t); + } - if( t.stackSize > this.target.getInventoryStackLimit() ) - { - t.stackSize = this.target.getInventoryStackLimit(); - } + if (out.stackSize <= 0) { + return null; + } + } + } - out.stackSize -= t.stackSize; - if( mode == Actionable.MODULATE ) - { - this.target.setInventorySlotContents( x, t ); - } + return AEItemStack.create(out); + } - if( out.stackSize <= 0 ) - { - return null; - } - } - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + final ItemStack Req = request.getItemStack(); - return AEItemStack.create( out ); - } + int request_stackSize = Req.stackSize; - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - final ItemStack Req = request.getItemStack(); + if (request_stackSize > Req.getMaxStackSize()) { + request_stackSize = Req.getMaxStackSize(); + } - int request_stackSize = Req.stackSize; + Req.stackSize = request_stackSize; - if( request_stackSize > Req.getMaxStackSize() ) - { - request_stackSize = Req.getMaxStackSize(); - } + ItemStack Gathered = null; + if (this.adaptor != null) { + Gathered = this.adaptor.removeItems(Req.stackSize, Req, null); + } else { + Gathered = request.getItemStack(); + Gathered.stackSize = 0; - Req.stackSize = request_stackSize; + // try to find matching inventories that already have it... + for (int x = 0; x < this.target.getSizeInventory(); x++) { + final ItemStack sub = this.target.getStackInSlot(x); - ItemStack Gathered = null; - if( this.adaptor != null ) - { - Gathered = this.adaptor.removeItems( Req.stackSize, Req, null ); - } - else - { - Gathered = request.getItemStack(); - Gathered.stackSize = 0; + if (Platform.isSameItem(sub, Req)) { + int reqNum = Req.stackSize; - // try to find matching inventories that already have it... - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - final ItemStack sub = this.target.getStackInSlot( x ); + if (reqNum > sub.stackSize) { + reqNum = Req.stackSize; + } - if( Platform.isSameItem( sub, Req ) ) - { - int reqNum = Req.stackSize; + ItemStack retrieved = null; - if( reqNum > sub.stackSize ) - { - reqNum = Req.stackSize; - } + if (sub.stackSize < Req.stackSize) { + retrieved = Platform.cloneItemStack(sub); + sub.stackSize = 0; + } else { + retrieved = sub.splitStack(Req.stackSize); + } - ItemStack retrieved = null; + if (sub.stackSize <= 0) { + this.target.setInventorySlotContents(x, null); + } else { + this.target.setInventorySlotContents(x, sub); + } - if( sub.stackSize < Req.stackSize ) - { - retrieved = Platform.cloneItemStack( sub ); - sub.stackSize = 0; - } - else - { - retrieved = sub.splitStack( Req.stackSize ); - } + if (retrieved != null) { + Gathered.stackSize += retrieved.stackSize; + Req.stackSize -= retrieved.stackSize; + } - if( sub.stackSize <= 0 ) - { - this.target.setInventorySlotContents( x, null ); - } - else - { - this.target.setInventorySlotContents( x, sub ); - } + if (request_stackSize == Gathered.stackSize) { + return AEItemStack.create(Gathered); + } + } + } - if( retrieved != null ) - { - Gathered.stackSize += retrieved.stackSize; - Req.stackSize -= retrieved.stackSize; - } + if (Gathered.stackSize == 0) { + return null; + } + } - if( request_stackSize == Gathered.stackSize ) - { - return AEItemStack.create( Gathered ); - } - } - } + return AEItemStack.create(Gathered); + } - if( Gathered.stackSize == 0 ) - { - return null; - } - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (int x = 0; x < this.target.getSizeInventory(); x++) { + out.addStorage(AEItemStack.create(this.target.getStackInSlot(x))); + } - return AEItemStack.create( Gathered ); - } + return out; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( int x = 0; x < this.target.getSizeInventory(); x++ ) - { - out.addStorage( AEItemStack.create( this.target.getStackInSlot( x ) ) ); - } - - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @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 062f02c3..2317677a 100644 --- a/src/main/java/appeng/me/storage/MEInventoryHandler.java +++ b/src/main/java/appeng/me/storage/MEInventoryHandler.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.IncludeExclude; @@ -31,169 +30,145 @@ import appeng.api.storage.data.IItemList; import appeng.util.prioitylist.DefaultPriorityList; import appeng.util.prioitylist.IPartitionList; +public class MEInventoryHandler> implements IMEInventoryHandler { + private final IMEInventoryHandler internal; + private int myPriority; + private IncludeExclude myWhitelist; + private AccessRestriction myAccess; + private IPartitionList myPartitionList; -public class MEInventoryHandler> implements IMEInventoryHandler -{ + private AccessRestriction cachedAccessRestriction; + private boolean hasReadAccess; + private boolean hasWriteAccess; - private final IMEInventoryHandler internal; - private int myPriority; - private IncludeExclude myWhitelist; - private AccessRestriction myAccess; - private IPartitionList myPartitionList; + public MEInventoryHandler(final IMEInventory i, final StorageChannel channel) { + if (i instanceof IMEInventoryHandler) { + this.internal = (IMEInventoryHandler) i; + } else { + this.internal = new MEPassThrough(i, channel); + } - private AccessRestriction cachedAccessRestriction; - private boolean hasReadAccess; - private boolean hasWriteAccess; + this.myPriority = 0; + this.myWhitelist = IncludeExclude.WHITELIST; + this.setBaseAccess(AccessRestriction.READ_WRITE); + this.myPartitionList = new DefaultPriorityList(); + } - public MEInventoryHandler( final IMEInventory i, final StorageChannel channel ) - { - if( i instanceof IMEInventoryHandler ) - { - this.internal = (IMEInventoryHandler) i; - } - else - { - this.internal = new MEPassThrough( i, channel ); - } + IncludeExclude getWhitelist() { + return this.myWhitelist; + } - this.myPriority = 0; - this.myWhitelist = IncludeExclude.WHITELIST; - this.setBaseAccess( AccessRestriction.READ_WRITE ); - this.myPartitionList = new DefaultPriorityList(); - } + public void setWhitelist(final IncludeExclude myWhitelist) { + this.myWhitelist = myWhitelist; + } - IncludeExclude getWhitelist() - { - return this.myWhitelist; - } + public AccessRestriction getBaseAccess() { + return this.myAccess; + } - public void setWhitelist( final IncludeExclude myWhitelist ) - { - this.myWhitelist = myWhitelist; - } + public void setBaseAccess(final AccessRestriction myAccess) { + this.myAccess = myAccess; + this.cachedAccessRestriction + = this.myAccess.restrictPermissions(this.internal.getAccess()); + this.hasReadAccess + = this.cachedAccessRestriction.hasPermission(AccessRestriction.READ); + this.hasWriteAccess + = this.cachedAccessRestriction.hasPermission(AccessRestriction.WRITE); + } - public AccessRestriction getBaseAccess() - { - return this.myAccess; - } + IPartitionList getPartitionList() { + return this.myPartitionList; + } - public void setBaseAccess( final AccessRestriction myAccess ) - { - this.myAccess = myAccess; - this.cachedAccessRestriction = this.myAccess.restrictPermissions( this.internal.getAccess() ); - this.hasReadAccess = this.cachedAccessRestriction.hasPermission( AccessRestriction.READ ); - this.hasWriteAccess = this.cachedAccessRestriction.hasPermission( AccessRestriction.WRITE ); - } + public void setPartitionList(final IPartitionList myPartitionList) { + this.myPartitionList = myPartitionList; + } - IPartitionList getPartitionList() - { - return this.myPartitionList; - } + @Override + public T + injectItems(final T input, final Actionable type, final BaseActionSource src) { + if (!this.canAccept(input)) { + return input; + } - public void setPartitionList( final IPartitionList myPartitionList ) - { - this.myPartitionList = myPartitionList; - } + return this.internal.injectItems(input, type, src); + } - @Override - public T injectItems( final T input, final Actionable type, final BaseActionSource src ) - { - if( !this.canAccept( input ) ) - { - return input; - } + @Override + public T + extractItems(final T request, final Actionable type, final BaseActionSource src) { + if (!this.hasReadAccess) { + return null; + } - return this.internal.injectItems( input, type, src ); - } + return this.internal.extractItems(request, type, src); + } - @Override - public T extractItems( final T request, final Actionable type, final BaseActionSource src ) - { - if( !this.hasReadAccess ) - { - return null; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + if (!this.hasReadAccess) { + return out; + } - return this.internal.extractItems( request, type, src ); - } + return this.internal.getAvailableItems(out); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - if( !this.hasReadAccess ) - { - return out; - } + @Override + public StorageChannel getChannel() { + return this.internal.getChannel(); + } - return this.internal.getAvailableItems( out ); - } + @Override + public AccessRestriction getAccess() { + return this.cachedAccessRestriction; + } - @Override - public StorageChannel getChannel() - { - return this.internal.getChannel(); - } + @Override + public boolean isPrioritized(final T input) { + if (this.myWhitelist == IncludeExclude.WHITELIST) { + return this.myPartitionList.isListed(input) + || this.internal.isPrioritized(input); + } + return false; + } - @Override - public AccessRestriction getAccess() - { - return this.cachedAccessRestriction; - } + @Override + public boolean canAccept(final T input) { + if (!this.hasWriteAccess) { + return false; + } - @Override - public boolean isPrioritized( final T input ) - { - if( this.myWhitelist == IncludeExclude.WHITELIST ) - { - return this.myPartitionList.isListed( input ) || this.internal.isPrioritized( input ); - } - return false; - } + if (this.myWhitelist == IncludeExclude.BLACKLIST + && this.myPartitionList.isListed(input)) { + return false; + } + if (this.myPartitionList.isEmpty() + || this.myWhitelist == IncludeExclude.BLACKLIST) { + return this.internal.canAccept(input); + } + return this.myPartitionList.isListed(input) && this.internal.canAccept(input); + } - @Override - public boolean canAccept( final T input ) - { - if( !this.hasWriteAccess ) - { - return false; - } + @Override + public int getPriority() { + return this.myPriority; + } - if( this.myWhitelist == IncludeExclude.BLACKLIST && this.myPartitionList.isListed( input ) ) - { - return false; - } - if( this.myPartitionList.isEmpty() || this.myWhitelist == IncludeExclude.BLACKLIST ) - { - return this.internal.canAccept( input ); - } - return this.myPartitionList.isListed( input ) && this.internal.canAccept( input ); - } + public void setPriority(final int myPriority) { + this.myPriority = myPriority; + } - @Override - public int getPriority() - { - return this.myPriority; - } + @Override + public int getSlot() { + return this.internal.getSlot(); + } - public void setPriority( final int myPriority ) - { - this.myPriority = myPriority; - } + @Override + public boolean validForPass(final int i) { + return true; + } - @Override - public int getSlot() - { - return this.internal.getSlot(); - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } - - public IMEInventory getInternal() - { - return this.internal; - } + 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 96fb4e81..3fd02009 100644 --- a/src/main/java/appeng/me/storage/MEMonitorIInventory.java +++ b/src/main/java/appeng/me/storage/MEMonitorIInventory.java @@ -18,6 +18,12 @@ package appeng.me.storage; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.concurrent.ConcurrentSkipListMap; import appeng.api.AEApi; import appeng.api.config.AccessRestriction; @@ -35,322 +41,274 @@ import appeng.util.Platform; import appeng.util.inv.ItemSlot; import net.minecraft.item.ItemStack; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.concurrent.ConcurrentSkipListMap; +public class MEMonitorIInventory implements IMEMonitor { + private final InventoryAdaptor adaptor; + private final IItemList list + = AEApi.instance().storage().createItemList(); + private final HashMap, Object> listeners + = new HashMap, Object>(); + private final NavigableMap memory; + private BaseActionSource mySource; + private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; + public MEMonitorIInventory(final InventoryAdaptor adaptor) { + this.adaptor = adaptor; + this.memory = new ConcurrentSkipListMap(); + } -public class MEMonitorIInventory implements IMEMonitor -{ + @Override + public void addListener( + final IMEMonitorHandlerReceiver l, final Object verificationToken + ) { + this.listeners.put(l, verificationToken); + } - private final InventoryAdaptor adaptor; - private final IItemList list = AEApi.instance().storage().createItemList(); - private final HashMap, Object> listeners = new HashMap, Object>(); - private final NavigableMap memory; - private BaseActionSource mySource; - private StorageFilter mode = StorageFilter.EXTRACTABLE_ONLY; + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - public MEMonitorIInventory( final InventoryAdaptor adaptor ) - { - this.adaptor = adaptor; - this.memory = new ConcurrentSkipListMap(); - } + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable type, final BaseActionSource src + ) { + ItemStack out = null; - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + if (type == Actionable.SIMULATE) { + out = this.adaptor.simulateAdd(input.getItemStack()); + } else { + out = this.adaptor.addItems(input.getItemStack()); + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + if (type == Actionable.MODULATE) { + this.onTick(); + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - ItemStack out = null; + if (out == null) { + return null; + } - if( type == Actionable.SIMULATE ) - { - out = this.adaptor.simulateAdd( input.getItemStack() ); - } - else - { - out = this.adaptor.addItems( input.getItemStack() ); - } + // better then doing construction from scratch :3 + final IAEItemStack o = input.copy(); + o.setStackSize(out.stackSize); + return o; + } - if( type == Actionable.MODULATE ) - { - this.onTick(); - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable type, final BaseActionSource src + ) { + ItemStack out = null; - if( out == null ) - { - return 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 + ); + } - // better then doing construction from scratch :3 - final IAEItemStack o = input.copy(); - o.setStackSize( out.stackSize ); - return o; - } + if (out == null) { + return null; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable type, final BaseActionSource src ) - { - ItemStack out = null; + // better then doing construction from scratch :3 + final IAEItemStack o = request.copy(); + o.setStackSize(out.stackSize); - 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 (type == Actionable.MODULATE) { + this.onTick(); + } - if( out == null ) - { - return null; - } + return o; + } - // better then doing construction from scratch :3 - final IAEItemStack o = request.copy(); - o.setStackSize( out.stackSize ); + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } - if( type == Actionable.MODULATE ) - { - this.onTick(); - } + public TickRateModulation onTick() { + final LinkedList changes = new LinkedList(); - return o; - } + this.list.resetStatus(); + int high = 0; + boolean changed = false; + for (final ItemSlot is : this.adaptor) { + final CachedItemStack old = this.memory.get(is.getSlot()); + high = Math.max(high, is.getSlot()); - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + final ItemStack newIS + = !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY + ? null + : is.getItemStack(); + final ItemStack oldIS = old == null ? null : old.itemStack; - public TickRateModulation onTick() - { + if (this.isDifferent(newIS, oldIS)) { + final CachedItemStack cis = new CachedItemStack(is.getItemStack()); + this.memory.put(is.getSlot(), cis); - final LinkedList changes = new LinkedList(); + if (old != null && old.aeStack != null) { + old.aeStack.setStackSize(-old.aeStack.getStackSize()); + changes.add(old.aeStack); + } - this.list.resetStatus(); - int high = 0; - boolean changed = false; - for( final ItemSlot is : this.adaptor ) - { - final CachedItemStack old = this.memory.get( is.getSlot() ); - high = Math.max( high, is.getSlot() ); + if (cis.aeStack != null) { + changes.add(cis.aeStack); + this.list.add(cis.aeStack); + } - final ItemStack newIS = !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? null : is.getItemStack(); - final ItemStack oldIS = old == null ? null : old.itemStack; + changed = true; + } else { + final int newSize = (newIS == null ? 0 : newIS.stackSize); + final int diff = newSize - (oldIS == null ? 0 : oldIS.stackSize); - if( this.isDifferent( newIS, oldIS ) ) - { - final CachedItemStack cis = new CachedItemStack( is.getItemStack() ); - this.memory.put( is.getSlot(), cis ); + final 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( old != null && old.aeStack != null ) - { - old.aeStack.setStackSize( -old.aeStack.getStackSize() ); - changes.add( old.aeStack ); - } + if (diff != 0 && stack != null) { + final CachedItemStack cis = new CachedItemStack(is.getItemStack()); + this.memory.put(is.getSlot(), cis); - if( cis.aeStack != null ) - { - changes.add( cis.aeStack ); - this.list.add( cis.aeStack ); - } + final IAEItemStack a = stack.copy(); + a.setStackSize(diff); + changes.add(a); + changed = true; + } + } + } - changed = true; - } - else - { - final int newSize = ( newIS == null ? 0 : newIS.stackSize ); - final int diff = newSize - ( oldIS == null ? 0 : oldIS.stackSize ); + // detect dropped items; should fix non IISided Inventory Changes. + final NavigableMap end + = this.memory.tailMap(high, false); + if (!end.isEmpty()) { + for (final CachedItemStack cis : end.values()) { + if (cis != null && cis.aeStack != null) { + final IAEItemStack a = cis.aeStack.copy(); + a.setStackSize(-a.getStackSize()); + changes.add(a); + changed = true; + } + } + end.clear(); + } - final 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 (!changes.isEmpty()) { + this.postDifference(changes); + } - if( diff != 0 && stack != null ) - { - final CachedItemStack cis = new CachedItemStack( is.getItemStack() ); - this.memory.put( is.getSlot(), cis ); + return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; + } - final IAEItemStack a = stack.copy(); - a.setStackSize( diff ); - changes.add( a ); - changed = true; - } - } - } + private boolean isDifferent(final ItemStack a, final ItemStack b) { + if (a == b && b == null) { + return false; + } - // detect dropped items; should fix non IISided Inventory Changes. - final NavigableMap end = this.memory.tailMap( high, false ); - if( !end.isEmpty() ) - { - for( final CachedItemStack cis : end.values() ) - { - if( cis != null && cis.aeStack != null ) - { - final IAEItemStack a = cis.aeStack.copy(); - a.setStackSize( -a.getStackSize() ); - changes.add( a ); - changed = true; - } - } - end.clear(); - } + if ((a == null && b != null) || (a != null && b == null)) { + return true; + } - if( !changes.isEmpty() ) - { - this.postDifference( changes ); - } + return !Platform.isSameItemPrecise(a, b); + } - return changed ? TickRateModulation.URGENT : TickRateModulation.SLOWER; - } + private void postDifference(final Iterable a) { + // AELog.info( a.getItemStack().getUnlocalizedName() + " @ " + a.getStackSize() ); + if (a != null) { + final Iterator, Object>> i + = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> l = i.next(); + final IMEMonitorHandlerReceiver key = l.getKey(); + if (key.isValid(l.getValue())) { + key.postChange(this, a, this.getActionSource()); + } else { + i.remove(); + } + } + } + } - private boolean isDifferent( final ItemStack a, final ItemStack b ) - { - if( a == b && b == null ) - { - return false; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - if( ( a == null && b != null ) || ( a != null && b == null ) ) - { - return true; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } - return !Platform.isSameItemPrecise( a, b ); - } + @Override + public boolean canAccept(final IAEItemStack input) { + return true; + } - private void postDifference( final Iterable a ) - { - // AELog.info( a.getItemStack().getUnlocalizedName() + " @ " + a.getStackSize() ); - if( a != null ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> l = i.next(); - final IMEMonitorHandlerReceiver key = l.getKey(); - if( key.isValid( l.getValue() ) ) - { - key.postChange( this, a, this.getActionSource() ); - } - else - { - i.remove(); - } - } - } - } + @Override + public int getPriority() { + return 0; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public int getSlot() { + return 0; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } + @Override + public boolean validForPass(final int i) { + return true; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - return true; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final CachedItemStack is : this.memory.values()) { + out.addStorage(is.aeStack); + } - @Override - public int getPriority() - { - return 0; - } + return out; + } - @Override - public int getSlot() - { - return 0; - } + @Override + public IItemList getStorageList() { + return this.list; + } - @Override - public boolean validForPass( final int i ) - { - return true; - } + private StorageFilter getMode() { + return this.mode; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final CachedItemStack is : this.memory.values() ) - { - out.addStorage( is.aeStack ); - } + public void setMode(final StorageFilter mode) { + this.mode = mode; + } - return out; - } + private BaseActionSource getActionSource() { + return this.mySource; + } - @Override - public IItemList getStorageList() - { - return this.list; - } + public void setActionSource(final BaseActionSource mySource) { + this.mySource = mySource; + } - private StorageFilter getMode() - { - return this.mode; - } + private static class CachedItemStack { + private final ItemStack itemStack; + private final IAEItemStack aeStack; - public void setMode( final StorageFilter mode ) - { - this.mode = mode; - } - - private BaseActionSource getActionSource() - { - return this.mySource; - } - - public void setActionSource( final BaseActionSource mySource ) - { - this.mySource = mySource; - } - - private static class CachedItemStack - { - - private final ItemStack itemStack; - private final IAEItemStack aeStack; - - public CachedItemStack( final ItemStack is ) - { - if( is == null ) - { - this.itemStack = null; - this.aeStack = null; - } - else - { - this.itemStack = is.copy(); - this.aeStack = AEApi.instance().storage().createItemStack( is ); - } - } - } + public CachedItemStack(final ItemStack is) { + if (is == null) { + this.itemStack = null; + this.aeStack = null; + } else { + this.itemStack = is.copy(); + this.aeStack = AEApi.instance().storage().createItemStack(is); + } + } + } } diff --git a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java index cdef158f..02b08483 100644 --- a/src/main/java/appeng/me/storage/MEMonitorPassThrough.java +++ b/src/main/java/appeng/me/storage/MEMonitorPassThrough.java @@ -18,6 +18,9 @@ package appeng.me.storage; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IBaseMonitor; @@ -30,136 +33,122 @@ import appeng.api.storage.data.IItemList; import appeng.util.Platform; import appeng.util.inv.ItemListIgnoreCrafting; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; +public class MEMonitorPassThrough> + extends MEPassThrough implements IMEMonitor, IMEMonitorHandlerReceiver { + private final HashMap, Object> listeners + = new HashMap, Object>(); + private BaseActionSource changeSource; + private IMEMonitor monitor; + public MEMonitorPassThrough(final IMEInventory i, final StorageChannel channel) { + super(i, channel); + if (i instanceof IMEMonitor) { + this.monitor = (IMEMonitor) i; + } + } -public class MEMonitorPassThrough> extends MEPassThrough implements IMEMonitor, IMEMonitorHandlerReceiver -{ + @Override + public void setInternal(final IMEInventory i) { + if (this.monitor != null) { + this.monitor.removeListener(this); + } - private final HashMap, Object> listeners = new HashMap, Object>(); - private BaseActionSource changeSource; - private IMEMonitor monitor; + this.monitor = null; + final IItemList before = this.getInternal() == null + ? this.getWrappedChannel().createList() + : this.getInternal().getAvailableItems( + new ItemListIgnoreCrafting(this.getWrappedChannel().createList()) + ); - public MEMonitorPassThrough( final IMEInventory i, final StorageChannel channel ) - { - super( i, channel ); - if( i instanceof IMEMonitor ) - { - this.monitor = (IMEMonitor) i; - } - } + super.setInternal(i); + if (i instanceof IMEMonitor) { + this.monitor = (IMEMonitor) i; + } - @Override - public void setInternal( final IMEInventory i ) - { - if( this.monitor != null ) - { - this.monitor.removeListener( this ); - } + final IItemList after = this.getInternal() == null + ? this.getWrappedChannel().createList() + : this.getInternal().getAvailableItems( + new ItemListIgnoreCrafting(this.getWrappedChannel().createList()) + ); - this.monitor = null; - final IItemList before = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) ); + if (this.monitor != null) { + this.monitor.addListener(this, this.monitor); + } - super.setInternal( i ); - if( i instanceof IMEMonitor ) - { - this.monitor = (IMEMonitor) i; - } + Platform.postListChanges(before, after, this, this.getChangeSource()); + } - final IItemList after = this.getInternal() == null ? this.getWrappedChannel().createList() : this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( this.getWrappedChannel().createList() ) ); + @Override + public IItemList getAvailableItems(final IItemList out) { + super.getAvailableItems(new ItemListIgnoreCrafting(out)); + return out; + } - if( this.monitor != null ) - { - this.monitor.addListener( this, this.monitor ); - } + @Override + public void + addListener(final IMEMonitorHandlerReceiver l, final Object verificationToken) { + this.listeners.put(l, verificationToken); + } - Platform.postListChanges( before, after, this, this.getChangeSource() ); - } + @Override + public void removeListener(final IMEMonitorHandlerReceiver l) { + this.listeners.remove(l); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - super.getAvailableItems( new ItemListIgnoreCrafting( out ) ); - return out; - } + @Override + public IItemList getStorageList() { + if (this.monitor == null) { + final IItemList out = this.getWrappedChannel().createList(); + this.getInternal().getAvailableItems(new ItemListIgnoreCrafting(out)); + return out; + } + return this.monitor.getStorageList(); + } - @Override - public void addListener( final IMEMonitorHandlerReceiver l, final Object verificationToken ) - { - this.listeners.put( l, verificationToken ); - } + @Override + public boolean isValid(final Object verificationToken) { + return verificationToken == this.monitor; + } - @Override - public void removeListener( final IMEMonitorHandlerReceiver l ) - { - this.listeners.remove( l ); - } + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource source + ) { + final Iterator, Object>> i + = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> e = i.next(); + final IMEMonitorHandlerReceiver receiver = e.getKey(); + if (receiver.isValid(e.getValue())) { + receiver.postChange(this, change, source); + } else { + i.remove(); + } + } + } - @Override - public IItemList getStorageList() - { - if( this.monitor == null ) - { - final IItemList out = this.getWrappedChannel().createList(); - this.getInternal().getAvailableItems( new ItemListIgnoreCrafting( out ) ); - return out; - } - return this.monitor.getStorageList(); - } + @Override + public void onListUpdate() { + final Iterator, Object>> i + = this.listeners.entrySet().iterator(); + while (i.hasNext()) { + final Entry, Object> e = i.next(); + final IMEMonitorHandlerReceiver receiver = e.getKey(); + if (receiver.isValid(e.getValue())) { + receiver.onListUpdate(); + } else { + i.remove(); + } + } + } - @Override - public boolean isValid( final Object verificationToken ) - { - return verificationToken == this.monitor; - } + private BaseActionSource getChangeSource() { + return this.changeSource; + } - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> e = i.next(); - final IMEMonitorHandlerReceiver receiver = e.getKey(); - if( receiver.isValid( e.getValue() ) ) - { - receiver.postChange( this, change, source ); - } - else - { - i.remove(); - } - } - } - - @Override - public void onListUpdate() - { - final Iterator, Object>> i = this.listeners.entrySet().iterator(); - while( i.hasNext() ) - { - final Entry, Object> e = i.next(); - final IMEMonitorHandlerReceiver receiver = e.getKey(); - if( receiver.isValid( e.getValue() ) ) - { - receiver.onListUpdate(); - } - else - { - i.remove(); - } - } - } - - private BaseActionSource getChangeSource() - { - return this.changeSource; - } - - public void setChangeSource( final BaseActionSource changeSource ) - { - this.changeSource = changeSource; - } + public void setChangeSource(final BaseActionSource changeSource) { + this.changeSource = changeSource; + } } diff --git a/src/main/java/appeng/me/storage/MEPassThrough.java b/src/main/java/appeng/me/storage/MEPassThrough.java index b6c3cdfb..d697aaa6 100644 --- a/src/main/java/appeng/me/storage/MEPassThrough.java +++ b/src/main/java/appeng/me/storage/MEPassThrough.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -28,91 +27,76 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public class MEPassThrough> implements IMEInventoryHandler { + private final StorageChannel wrappedChannel; + private IMEInventory internal; -public class MEPassThrough> implements IMEInventoryHandler -{ + public MEPassThrough(final IMEInventory i, final StorageChannel channel) { + this.wrappedChannel = channel; + this.setInternal(i); + } - private final StorageChannel wrappedChannel; - private IMEInventory internal; + protected IMEInventory getInternal() { + return this.internal; + } - public MEPassThrough( final IMEInventory i, final StorageChannel channel ) - { - this.wrappedChannel = channel; - this.setInternal( i ); - } + public void setInternal(final IMEInventory i) { + this.internal = i; + } - protected IMEInventory getInternal() - { - return this.internal; - } + @Override + public T + injectItems(final T input, final Actionable type, final BaseActionSource src) { + return this.internal.injectItems(input, type, src); + } - public void setInternal( final IMEInventory i ) - { - this.internal = i; - } + @Override + public T + extractItems(final T request, final Actionable type, final BaseActionSource src) { + return this.internal.extractItems(request, type, src); + } - @Override - public T injectItems( final T input, final Actionable type, final BaseActionSource src ) - { - return this.internal.injectItems( input, type, src ); - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return this.internal.getAvailableItems(out); + } - @Override - public T extractItems( final T request, final Actionable type, final BaseActionSource src ) - { - return this.internal.extractItems( request, type, src ); - } + @Override + public StorageChannel getChannel() { + return this.internal.getChannel(); + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return this.internal.getAvailableItems( out ); - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public StorageChannel getChannel() - { - return this.internal.getChannel(); - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public boolean canAccept(final T input) { + return true; + } - @Override - public boolean isPrioritized( final T input ) - { - return false; - } + @Override + public int getPriority() { + return 0; + } - @Override - public boolean canAccept( final T input ) - { - return true; - } + @Override + public int getSlot() { + return 0; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public boolean validForPass(final int i) { + return true; + } - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } - - StorageChannel getWrappedChannel() - { - return this.wrappedChannel; - } + StorageChannel getWrappedChannel() { + return this.wrappedChannel; + } } diff --git a/src/main/java/appeng/me/storage/NetworkInventoryHandler.java b/src/main/java/appeng/me/storage/NetworkInventoryHandler.java index 48dfbf18..986e9731 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.*; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -35,300 +36,266 @@ import appeng.api.storage.data.IItemList; import appeng.me.cache.SecurityCache; import appeng.util.ItemSorters; -import java.util.*; +public class NetworkInventoryHandler> + implements IMEInventoryHandler { + private static final ThreadLocal DEPTH_MOD + = new ThreadLocal(); + private static final ThreadLocal DEPTH_SIM + = new ThreadLocal(); + private static final Comparator PRIORITY_SORTER = new Comparator() { + @Override + public int compare(final Integer o1, final Integer o2) { + return ItemSorters.compareInt(o2, o1); + } + }; + private static int currentPass = 0; + private final StorageChannel myChannel; + private final SecurityCache security; + // final TreeMultimap> priorityInventory; + private final NavigableMap>> priorityInventory; + private int myPass = 0; + public NetworkInventoryHandler( + final StorageChannel chan, final SecurityCache security + ) { + this.myChannel = chan; + this.security = security; + this.priorityInventory + = new TreeMap>>(PRIORITY_SORTER + ); // TreeMultimap.create( + // prioritySorter, + // hashSorter ); + } -public class NetworkInventoryHandler> implements IMEInventoryHandler -{ + public void addNewStorage(final IMEInventoryHandler h) { + final int priority = h.getPriority(); + List> list = this.priorityInventory.get(priority); + if (list == null) { + this.priorityInventory.put( + priority, list = new ArrayList>() + ); + } - private static final ThreadLocal DEPTH_MOD = new ThreadLocal(); - private static final ThreadLocal DEPTH_SIM = new ThreadLocal(); - private static final Comparator PRIORITY_SORTER = new Comparator() - { + list.add(h); + } - @Override - public int compare( final Integer o1, final Integer o2 ) - { - return ItemSorters.compareInt( o2, o1 ); - } - }; - private static int currentPass = 0; - private final StorageChannel myChannel; - private final SecurityCache security; - // final TreeMultimap> priorityInventory; - private final NavigableMap>> priorityInventory; - private int myPass = 0; + @Override + public T injectItems(T input, final Actionable type, final BaseActionSource src) { + if (this.diveList(this, type)) { + return input; + } - public NetworkInventoryHandler( final StorageChannel chan, final SecurityCache security ) - { - this.myChannel = chan; - this.security = security; - this.priorityInventory = new TreeMap>>( PRIORITY_SORTER ); // TreeMultimap.create( - // prioritySorter, - // hashSorter ); - } + if (this.testPermission(src, SecurityPermissions.INJECT)) { + this.surface(this, type); + return input; + } - public void addNewStorage( final IMEInventoryHandler h ) - { - final int priority = h.getPriority(); - List> list = this.priorityInventory.get( priority ); - if( list == null ) - { - this.priorityInventory.put( priority, list = new ArrayList>() ); - } + for (final List> invList : + this.priorityInventory.values()) { + Iterator> ii = invList.iterator(); + while (ii.hasNext() && input != null) { + final IMEInventoryHandler inv = ii.next(); - list.add( h ); - } + if (inv.validForPass(1) && inv.canAccept(input) + && (inv.isPrioritized(input) + || inv.extractItems(input, Actionable.SIMULATE, src) != null)) { + input = inv.injectItems(input, type, src); + } + } - @Override - public T injectItems( T input, final Actionable type, final BaseActionSource src ) - { - if( this.diveList( this, type ) ) - { - return input; - } + // We need to ignore prioritized inventories in the second pass. If they were + // not able to store everything during the first pass, they will do so in the + // second, but as this is stateless we will just report twice the amount of + // storable items. ignores craftingcache on the second pass. + ii = invList.iterator(); + while (ii.hasNext() && input != null) { + final IMEInventoryHandler inv = ii.next(); - if( this.testPermission( src, SecurityPermissions.INJECT ) ) - { - this.surface( this, type ); - return input; - } + if (inv.validForPass(2) && inv.canAccept(input) + && !inv.isPrioritized(input)) { + input = inv.injectItems(input, type, src); + } + } + } - for( final List> invList : this.priorityInventory.values() ) - { - Iterator> ii = invList.iterator(); - while( ii.hasNext() && input != null ) - { - final IMEInventoryHandler inv = ii.next(); + this.surface(this, type); - if( inv.validForPass( 1 ) && inv.canAccept( input ) && ( inv.isPrioritized( input ) || inv.extractItems( input, Actionable.SIMULATE, src ) != null ) ) - { - input = inv.injectItems( input, type, src ); - } - } + return input; + } - // We need to ignore prioritized inventories in the second pass. If they were not able to store everything - // during the first pass, they will do so in the second, but as this is stateless we will just report twice - // the amount of storable items. - // ignores craftingcache on the second pass. - ii = invList.iterator(); - while( ii.hasNext() && input != null ) - { - final IMEInventoryHandler inv = ii.next(); + private boolean diveList( + final NetworkInventoryHandler networkInventoryHandler, final Actionable type + ) { + final LinkedList cDepth = this.getDepth(type); + if (cDepth.contains(networkInventoryHandler)) { + return true; + } - if( inv.validForPass( 2 ) && inv.canAccept( input ) && !inv.isPrioritized( input ) ) - { - input = inv.injectItems( input, type, src ); - } - } - } + cDepth.push(this); + return false; + } - this.surface( this, type ); + private boolean + testPermission(final BaseActionSource src, final SecurityPermissions permission) { + if (src.isPlayer()) { + if (!this.security.hasPermission(((PlayerSource) src).player, permission)) { + return true; + } + } else if (src.isMachine()) { + if (this.security.isAvailable()) { + final IGridNode n = ((MachineSource) src).via.getActionableNode(); + if (n == null) { + return true; + } - return input; - } + final IGrid gn = n.getGrid(); + if (gn != this.security.getGrid()) { + final ISecurityGrid sg = gn.getCache(ISecurityGrid.class); + final int playerID = sg.getOwner(); - private boolean diveList( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - final LinkedList cDepth = this.getDepth( type ); - if( cDepth.contains( networkInventoryHandler ) ) - { - return true; - } + if (!this.security.hasPermission(playerID, permission)) { + return true; + } + } + } + } - cDepth.push( this ); - return false; - } + return false; + } - private boolean testPermission( final BaseActionSource src, final SecurityPermissions permission ) - { - if( src.isPlayer() ) - { - if( !this.security.hasPermission( ( (PlayerSource) src ).player, permission ) ) - { - return true; - } - } - else if( src.isMachine() ) - { - if( this.security.isAvailable() ) - { - final IGridNode n = ( (MachineSource) src ).via.getActionableNode(); - if( n == null ) - { - return true; - } + private void surface( + final NetworkInventoryHandler networkInventoryHandler, final Actionable type + ) { + if (this.getDepth(type).pop() != this) { + throw new IllegalStateException( + "Invalid Access to Networked Storage API detected." + ); + } + } - final IGrid gn = n.getGrid(); - if( gn != this.security.getGrid() ) - { + private LinkedList getDepth(final Actionable type) { + final ThreadLocal depth + = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; - final ISecurityGrid sg = gn.getCache( ISecurityGrid.class ); - final int playerID = sg.getOwner(); + LinkedList s = depth.get(); - if( !this.security.hasPermission( playerID, permission ) ) - { - return true; - } - } - } - } + if (s == null) { + depth.set(s = new LinkedList()); + } - return false; - } + return s; + } - private void surface( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - if( this.getDepth( type ).pop() != this ) - { - throw new IllegalStateException( "Invalid Access to Networked Storage API detected." ); - } - } + @Override + public T extractItems(T request, final Actionable mode, final BaseActionSource src) { + if (this.diveList(this, mode)) { + return null; + } - private LinkedList getDepth( final Actionable type ) - { - final ThreadLocal depth = type == Actionable.MODULATE ? DEPTH_MOD : DEPTH_SIM; + if (this.testPermission(src, SecurityPermissions.EXTRACT)) { + this.surface(this, mode); + return null; + } - LinkedList s = depth.get(); + final Iterator>> i + = this.priorityInventory.descendingMap().values().iterator( + ); // priorityInventory.asMap().descendingMap().entrySet().iterator(); - if( s == null ) - { - depth.set( s = new LinkedList() ); - } + final T output = request.copy(); + request = request.copy(); + output.setStackSize(0); + final long req = request.getStackSize(); - return s; - } + while (i.hasNext()) { + final List> invList = i.next(); - @Override - public T extractItems( T request, final Actionable mode, final BaseActionSource src ) - { - if( this.diveList( this, mode ) ) - { - return null; - } + final Iterator> ii = invList.iterator(); + while (ii.hasNext() && output.getStackSize() < req) { + final IMEInventoryHandler inv = ii.next(); - if( this.testPermission( src, SecurityPermissions.EXTRACT ) ) - { - this.surface( this, mode ); - return null; - } + request.setStackSize(req - output.getStackSize()); + output.add(inv.extractItems(request, mode, src)); + } + } - final Iterator>> i = this.priorityInventory.descendingMap().values().iterator();// priorityInventory.asMap().descendingMap().entrySet().iterator(); + this.surface(this, mode); - final T output = request.copy(); - request = request.copy(); - output.setStackSize( 0 ); - final long req = request.getStackSize(); + if (output.getStackSize() <= 0) { + return null; + } - while( i.hasNext() ) - { - final List> invList = i.next(); + return output; + } - final Iterator> ii = invList.iterator(); - while( ii.hasNext() && output.getStackSize() < req ) - { - final IMEInventoryHandler inv = ii.next(); + @Override + public IItemList getAvailableItems(IItemList out) { + if (this.diveIteration(this, Actionable.SIMULATE)) { + return out; + } - request.setStackSize( req - output.getStackSize() ); - output.add( inv.extractItems( request, mode, src ) ); - } - } + // for (Entry> h : priorityInventory.entries()) + for (final List> i : this.priorityInventory.values()) { + for (final IMEInventoryHandler j : i) { + out = j.getAvailableItems(out); + } + } - this.surface( this, mode ); + this.surface(this, Actionable.SIMULATE); - if( output.getStackSize() <= 0 ) - { - return null; - } + return out; + } - return output; - } + private boolean diveIteration( + final NetworkInventoryHandler networkInventoryHandler, final Actionable type + ) { + final LinkedList cDepth = this.getDepth(type); + if (cDepth.isEmpty()) { + currentPass++; + this.myPass = currentPass; + } else { + if (currentPass == this.myPass) { + return true; + } else { + this.myPass = currentPass; + } + } - @Override - public IItemList getAvailableItems( IItemList out ) - { - if( this.diveIteration( this, Actionable.SIMULATE ) ) - { - return out; - } + cDepth.push(this); + return false; + } - // for (Entry> h : priorityInventory.entries()) - for( final List> i : this.priorityInventory.values() ) - { - for( final IMEInventoryHandler j : i ) - { - out = j.getAvailableItems( out ); - } - } + @Override + public StorageChannel getChannel() { + return this.myChannel; + } - this.surface( this, Actionable.SIMULATE ); + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - return out; - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - private boolean diveIteration( final NetworkInventoryHandler networkInventoryHandler, final Actionable type ) - { - final LinkedList cDepth = this.getDepth( type ); - if( cDepth.isEmpty() ) - { - currentPass++; - this.myPass = currentPass; - } - else - { - if( currentPass == this.myPass ) - { - return true; - } - else - { - this.myPass = currentPass; - } - } + @Override + public boolean canAccept(final T input) { + return true; + } - cDepth.push( this ); - return false; - } + @Override + public int getPriority() { + return 0; + } - @Override - public StorageChannel getChannel() - { - return this.myChannel; - } + @Override + public int getSlot() { + return 0; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public boolean isPrioritized( final T input ) - { - return false; - } - - @Override - public boolean canAccept( final T input ) - { - return true; - } - - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } + @Override + public boolean validForPass(final 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 f674a192..13cf3754 100644 --- a/src/main/java/appeng/me/storage/NullInventory.java +++ b/src/main/java/appeng/me/storage/NullInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -27,67 +26,56 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public class NullInventory> implements IMEInventoryHandler { + @Override + public T + injectItems(final T input, final Actionable mode, final BaseActionSource src) { + return input; + } -public class NullInventory> implements IMEInventoryHandler -{ + @Override + public T + extractItems(final T request, final Actionable mode, final BaseActionSource src) { + return null; + } - @Override - public T injectItems( final T input, final Actionable mode, final BaseActionSource src ) - { - return input; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public T extractItems( final T request, final Actionable mode, final BaseActionSource src ) - { - return null; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public boolean isPrioritized(final T input) { + return false; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ; - } + @Override + public boolean canAccept(final T input) { + return false; + } - @Override - public boolean isPrioritized( final T input ) - { - return false; - } + @Override + public int getPriority() { + return 0; + } - @Override - public boolean canAccept( final T input ) - { - return false; - } + @Override + public int getSlot() { + return 0; + } - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } + @Override + public boolean validForPass(final 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 2471e674..05098073 100644 --- a/src/main/java/appeng/me/storage/SecurityInventory.java +++ b/src/main/java/appeng/me/storage/SecurityInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -34,165 +33,140 @@ import appeng.me.GridAccessException; import appeng.tile.misc.TileSecurity; import com.mojang.authlib.GameProfile; +public class SecurityInventory implements IMEInventoryHandler { + private final IItemList storedItems + = AEApi.instance().storage().createItemList(); + private final TileSecurity securityTile; -public class SecurityInventory implements IMEInventoryHandler -{ + public SecurityInventory(final TileSecurity ts) { + this.securityTile = ts; + } - private final IItemList storedItems = AEApi.instance().storage().createItemList(); - private final TileSecurity securityTile; + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable type, final BaseActionSource src + ) { + if (this.hasPermission(src)) { + if (AEApi.instance().definitions().items().biometricCard().isSameAs( + input.getItemStack() + )) { + if (this.canAccept(input)) { + if (type == Actionable.SIMULATE) { + return null; + } - public SecurityInventory( final TileSecurity ts ) - { - this.securityTile = ts; - } + this.getStoredItems().add(input); + this.securityTile.inventoryChanged(); + return null; + } + } + } + return input; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( this.hasPermission( src ) ) - { - if( AEApi.instance().definitions().items().biometricCard().isSameAs( input.getItemStack() ) ) - { - if( this.canAccept( input ) ) - { - if( type == Actionable.SIMULATE ) - { - return null; - } + private boolean hasPermission(final BaseActionSource src) { + if (src.isPlayer()) { + try { + return this.securityTile.getProxy().getSecurity().hasPermission( + ((PlayerSource) src).player, SecurityPermissions.SECURITY + ); + } catch (final GridAccessException e) { + // :P + } + } + return false; + } - this.getStoredItems().add( input ); - this.securityTile.inventoryChanged(); - return null; - } - } - } - return input; - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + if (this.hasPermission(src)) { + final IAEItemStack target = this.getStoredItems().findPrecise(request); + if (target != null) { + final IAEItemStack output = target.copy(); - private boolean hasPermission( final BaseActionSource src ) - { - if( src.isPlayer() ) - { - try - { - return this.securityTile.getProxy().getSecurity().hasPermission( ( (PlayerSource) src ).player, SecurityPermissions.SECURITY ); - } - catch( final GridAccessException e ) - { - // :P - } - } - return false; - } + if (mode == Actionable.SIMULATE) { + return output; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - if( this.hasPermission( src ) ) - { - final IAEItemStack target = this.getStoredItems().findPrecise( request ); - if( target != null ) - { - final IAEItemStack output = target.copy(); + target.setStackSize(0); + this.securityTile.inventoryChanged(); + return output; + } + } + return null; + } - if( mode == Actionable.SIMULATE ) - { - return output; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + for (final IAEItemStack ais : this.getStoredItems()) { + out.add(ais); + } - target.setStackSize( 0 ); - this.securityTile.inventoryChanged(); - return output; - } - } - return null; - } + return out; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - for( final IAEItemStack ais : this.getStoredItems() ) - { - out.add( ais ); - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } - return out; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.READ_WRITE; - } + @Override + public boolean canAccept(final IAEItemStack input) { + if (input.getItem() instanceof IBiometricCard) { + final IBiometricCard tbc = (IBiometricCard) input.getItem(); + final GameProfile newUser = tbc.getProfile(input.getItemStack()); - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } + final int PlayerID = AEApi.instance().registries().players().getID(newUser); + if (this.securityTile.getOwner() == PlayerID) { + return false; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - if( input.getItem() instanceof IBiometricCard ) - { - final IBiometricCard tbc = (IBiometricCard) input.getItem(); - final GameProfile newUser = tbc.getProfile( input.getItemStack() ); + for (final IAEItemStack ais : this.getStoredItems()) { + if (ais.isMeaningful()) { + final GameProfile thisUser = tbc.getProfile(ais.getItemStack()); + if (thisUser == newUser) { + return false; + } - final int PlayerID = AEApi.instance().registries().players().getID( newUser ); - if( this.securityTile.getOwner() == PlayerID ) - { - return false; - } + if (thisUser != null && thisUser.equals(newUser)) { + return false; + } + } + } - for( final IAEItemStack ais : this.getStoredItems() ) - { - if( ais.isMeaningful() ) - { - final GameProfile thisUser = tbc.getProfile( ais.getItemStack() ); - if( thisUser == newUser ) - { - return false; - } + return true; + } + return false; + } - if( thisUser != null && thisUser.equals( newUser ) ) - { - return false; - } - } - } + @Override + public int getPriority() { + return 0; + } - return true; - } - return false; - } + @Override + public int getSlot() { + return 0; + } - @Override - public int getPriority() - { - return 0; - } + @Override + public boolean validForPass(final int i) { + return true; + } - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return true; - } - - public IItemList getStoredItems() - { - return this.storedItems; - } + public IItemList getStoredItems() { + return this.storedItems; + } } diff --git a/src/main/java/appeng/me/storage/VoidFluidInventory.java b/src/main/java/appeng/me/storage/VoidFluidInventory.java index af98dc6e..b518d8d9 100644 --- a/src/main/java/appeng/me/storage/VoidFluidInventory.java +++ b/src/main/java/appeng/me/storage/VoidFluidInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -28,83 +27,71 @@ import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; import appeng.tile.misc.TileCondenser; +public class VoidFluidInventory implements IMEInventoryHandler { + private final TileCondenser target; -public class VoidFluidInventory implements IMEInventoryHandler -{ + public VoidFluidInventory(final TileCondenser te) { + this.target = te; + } - private final TileCondenser target; + @Override + public IAEFluidStack injectItems( + final IAEFluidStack input, final Actionable mode, final BaseActionSource src + ) { + if (mode == Actionable.SIMULATE) { + return null; + } - public VoidFluidInventory( final TileCondenser te ) - { - this.target = te; - } + if (input != null) { + this.target.addPower(input.getStackSize() / 1000.0); + } + return null; + } - @Override - public IAEFluidStack injectItems( final IAEFluidStack input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return null; - } + @Override + public IAEFluidStack extractItems( + final IAEFluidStack request, final Actionable mode, final BaseActionSource src + ) { + return null; + } - if( input != null ) - { - this.target.addPower( input.getStackSize() / 1000.0 ); - } - return null; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public IAEFluidStack extractItems( final IAEFluidStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.WRITE; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.FLUIDS; - } + @Override + public boolean isPrioritized(final IAEFluidStack input) { + return false; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } + @Override + public boolean canAccept(final IAEFluidStack input) { + return true; + } - @Override - public boolean isPrioritized( final IAEFluidStack input ) - { - return false; - } + @Override + public int getPriority() { + return 0; + } - @Override - public boolean canAccept( final IAEFluidStack input ) - { - return true; - } + @Override + public int getSlot() { + return 0; + } - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } + @Override + public boolean validForPass(final int i) { + return i == 2; + } } diff --git a/src/main/java/appeng/me/storage/VoidItemInventory.java b/src/main/java/appeng/me/storage/VoidItemInventory.java index 57ed06fc..0d01742d 100644 --- a/src/main/java/appeng/me/storage/VoidItemInventory.java +++ b/src/main/java/appeng/me/storage/VoidItemInventory.java @@ -18,7 +18,6 @@ package appeng.me.storage; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -28,83 +27,71 @@ import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import appeng.tile.misc.TileCondenser; +public class VoidItemInventory implements IMEInventoryHandler { + private final TileCondenser target; -public class VoidItemInventory implements IMEInventoryHandler -{ + public VoidItemInventory(final TileCondenser te) { + this.target = te; + } - private final TileCondenser target; + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable mode, final BaseActionSource src + ) { + if (mode == Actionable.SIMULATE) { + return null; + } - public VoidItemInventory( final TileCondenser te ) - { - this.target = te; - } + if (input != null) { + this.target.addPower(input.getStackSize()); + } + return null; + } - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable mode, final BaseActionSource src ) - { - if( mode == Actionable.SIMULATE ) - { - return null; - } + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + return null; + } - if( input != null ) - { - this.target.addPower( input.getStackSize() ); - } - return null; - } + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } + @Override + public AccessRestriction getAccess() { + return AccessRestriction.WRITE; + } - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } + @Override + public boolean isPrioritized(final IAEItemStack input) { + return false; + } - @Override - public AccessRestriction getAccess() - { - return AccessRestriction.WRITE; - } + @Override + public boolean canAccept(final IAEItemStack input) { + return true; + } - @Override - public boolean isPrioritized( final IAEItemStack input ) - { - return false; - } + @Override + public int getPriority() { + return 0; + } - @Override - public boolean canAccept( final IAEItemStack input ) - { - return true; - } + @Override + public int getSlot() { + return 0; + } - @Override - public int getPriority() - { - return 0; - } - - @Override - public int getSlot() - { - return 0; - } - - @Override - public boolean validForPass( final int i ) - { - return i == 2; - } + @Override + public boolean validForPass(final int i) { + return i == 2; + } } diff --git a/src/main/java/appeng/parts/AEBasePart.java b/src/main/java/appeng/parts/AEBasePart.java index c94f8a25..d4578a51 100644 --- a/src/main/java/appeng/parts/AEBasePart.java +++ b/src/main/java/appeng/parts/AEBasePart.java @@ -18,6 +18,11 @@ package appeng.parts; +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; import appeng.api.AEApi; import appeng.api.config.Upgrades; @@ -60,523 +65,461 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.player.PlayerInteractEvent; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; - - -public abstract class AEBasePart implements IPart, IGridProxyable, IActionHost, IUpgradeableHost, ICustomNameObject -{ - - private final AENetworkProxy proxy; - private final ItemStack is; - private ISimplifiedBundle renderCache = null; - private TileEntity tile = null; - private IPartHost host = null; - private ForgeDirection side = null; - - public AEBasePart( final ItemStack is ) - { - Preconditions.checkNotNull( 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 - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.proxy.getNode(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.GLASS; - } - - @Override - public void securityBreak() - { - if( this.getItemStack().stackSize > 0 && this.getGridNode() != null ) - { - final List items = new ArrayList<>(); - items.add( this.getItemStack().copy() ); - this.host.removePart( this.getSide(), false ); - Platform.spawnDrops( this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord, items ); - this.getItemStack().stackSize = 0; - } - } - - protected AEColor getColor() - { - if( this.host == null ) - { - return AEColor.Transparent; - } - return this.host.getColor(); - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return 0; - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 1, 1, 1, 15, 15, 15 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 1, 1, 1, 15, 15, 15 ); - rh.renderInventoryBox( renderer ); - } - - @Override - 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.getItemStack().getDisplayName(); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 1, 1, 1, 15, 15, 15 ); - rh.renderBlock( x, y, z, renderer ); - } - - @Override - public boolean hasCustomName() - { - return this.getItemStack().hasDisplayName(); - } - - public void addEntityCrashInfo( final CrashReportCategory crashreportcategory ) - { - crashreportcategory.addCrashSection( "Part Side", this.getSide() ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - - } - - @Override - public ItemStack getItemStack( final PartItemStack type ) - { - if( type == PartItemStack.Network ) - { - final ItemStack copy = this.is.copy(); - copy.setTagCompound( null ); - return copy; - } - return this.is; - } - - @Override - public boolean isSolid() - { - return false; - } - - @Override - public void onNeighborChanged() - { - - } - - @Override - public boolean canConnectRedstone() - { - return false; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - this.proxy.readFromNBT( data ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - this.proxy.writeToNBT( data ); - } - - @Override - public int isProvidingStrongPower() - { - return 0; - } - - @Override - public int isProvidingWeakPower() - { - return 0; - } - - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - - } - - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - return false; - } - - @Override - public IGridNode getGridNode() - { - return this.proxy.getNode(); - } - - @Override - public void onEntityCollision( final Entity entity ) - { - - } - - @Override - public void removeFromWorld() - { - this.proxy.invalidate(); - } - - @Override - public void addToWorld() - { - this.proxy.onReady(); - } - - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - this.setSide( side ); - this.tile = tile; - this.host = host; - } - - @Override - public IGridNode getExternalFacingNode() - { - return null; - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - - } - - @Override - public int getLightLevel() - { - return 0; - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - - } - - @Override - public int cableConnectionRenderTo() - { - return 3; - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return false; - } - - @Override - public IConfigManager getConfigManager() - { - return null; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - return null; - } - - /** - * 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 - */ - private void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( compound != null ) - { - final IConfigManager cm = this.getConfigManager(); - if( cm != null ) - { - cm.readFromNBT( compound ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - pHost.setPriority( compound.getInteger( "priority" ) ); - } - - final IInventory inv = this.getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; - final 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 - */ - private NBTTagCompound downloadSettings( final SettingsFrom from ) - { - final NBTTagCompound output = new NBTTagCompound(); - - final IConfigManager cm = this.getConfigManager(); - if( cm != null ) - { - cm.writeToNBT( output ); - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - output.setInteger( "priority", pHost.getPriority() ); - } - - final IInventory inv = this.getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); - } - - return output.hasNoTags() ? null : output; - } - - public boolean useStandardMemoryCard() - { - return true; - } - - private boolean useMemoryCard( final EntityPlayer player ) - { - final ItemStack memCardIS = player.inventory.getCurrentItem(); - if( ForgeEventFactory.onItemUseStart( player, memCardIS, 1 ) <= 0 ) - return false; - - if( memCardIS != null && this.useStandardMemoryCard() && memCardIS.getItem() instanceof IMemoryCard ) - { - final IMemoryCard memoryCard = (IMemoryCard) memCardIS.getItem(); - - ItemStack is = this.getItemStack( PartItemStack.Network ); - - // Blocks and parts share the same soul! - final IDefinitions definitions = AEApi.instance().definitions(); - if( definitions.parts().iface().isSameAs( is ) ) - { - for( final ItemStack iface : definitions.blocks().iface().maybeStack( 1 ).asSet() ) - { - is = iface; - } - } - - final String name = is.getUnlocalizedName(); - - if( player.isSneaking() ) - { - final NBTTagCompound data = this.downloadSettings( SettingsFrom.MEMORY_CARD ); - if( data != null ) - { - memoryCard.setMemoryCardContents( memCardIS, name, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - } - } - else - { - final String storedName = memoryCard.getSettingsName( memCardIS ); - final NBTTagCompound data = memoryCard.getData( memCardIS ); - if( name.equals( storedName ) ) - { - this.uploadSettings( SettingsFrom.MEMORY_CARD, data ); - memoryCard.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - } - else - { - memoryCard.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - } - return true; - } - return false; - } - - @Override - public final boolean onActivate( final EntityPlayer player, final Vec3 pos ) - { - // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; - int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; - PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, 0, player.getEntityWorld() ); - if( event.isCanceled() ) - return false; - - if( this.useMemoryCard( player ) ) - { - return true; - } - - return onPartActivate( player, pos ); - } - - @Override - public final boolean onShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; - int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; - PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( player, PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, x, y, z, 0, player.getEntityWorld() ); - if( event.isCanceled() ) - return false; - - if( this.useMemoryCard( player ) ) - { - return true; - } - - return this.onPartShiftActivate( player, pos ); - } - - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - public boolean onPartShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - this.proxy.setOwner( player ); - } - - @Override - public boolean canBePlacedOn( final BusSupport what ) - { - return what == BusSupport.CABLE; - } - - @Override - public boolean requireDynamicRender() - { - return false; - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return null; - } - - public ForgeDirection getSide() - { - return this.side; - } - - private void setSide( final ForgeDirection side ) - { - this.side = side; - } - - public ItemStack getItemStack() - { - return this.is; - } - - public ISimplifiedBundle getRenderCache() - { - return this.renderCache; - } - - public void setRenderCache( final ISimplifiedBundle renderCache ) - { - this.renderCache = renderCache; - } +public abstract class AEBasePart + implements IPart, IGridProxyable, IActionHost, IUpgradeableHost, ICustomNameObject { + private final AENetworkProxy proxy; + private final ItemStack is; + private ISimplifiedBundle renderCache = null; + private TileEntity tile = null; + private IPartHost host = null; + private ForgeDirection side = null; + + public AEBasePart(final ItemStack is) { + Preconditions.checkNotNull(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 + public IGridNode getGridNode(final ForgeDirection dir) { + return this.proxy.getNode(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.GLASS; + } + + @Override + public void securityBreak() { + if (this.getItemStack().stackSize > 0 && this.getGridNode() != null) { + final List items = new ArrayList<>(); + items.add(this.getItemStack().copy()); + this.host.removePart(this.getSide(), false); + Platform.spawnDrops( + this.tile.getWorldObj(), + this.tile.xCoord, + this.tile.yCoord, + this.tile.zCoord, + items + ); + this.getItemStack().stackSize = 0; + } + } + + protected AEColor getColor() { + if (this.host == null) { + return AEColor.Transparent; + } + return this.host.getColor(); + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) {} + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return 0; + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setBounds(1, 1, 1, 15, 15, 15); + rh.renderInventoryBox(renderer); + + rh.setBounds(1, 1, 1, 15, 15, 15); + rh.renderInventoryBox(renderer); + } + + @Override + 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.getItemStack().getDisplayName(); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + rh.setBounds(1, 1, 1, 15, 15, 15); + rh.renderBlock(x, y, z, renderer); + } + + @Override + public boolean hasCustomName() { + return this.getItemStack().hasDisplayName(); + } + + public void addEntityCrashInfo(final CrashReportCategory crashreportcategory) { + crashreportcategory.addCrashSection("Part Side", this.getSide()); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic( + final double x, + final double y, + final double z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) {} + + @Override + public ItemStack getItemStack(final PartItemStack type) { + if (type == PartItemStack.Network) { + final ItemStack copy = this.is.copy(); + copy.setTagCompound(null); + return copy; + } + return this.is; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public void onNeighborChanged() {} + + @Override + public boolean canConnectRedstone() { + return false; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + this.proxy.readFromNBT(data); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + this.proxy.writeToNBT(data); + } + + @Override + public int isProvidingStrongPower() { + return 0; + } + + @Override + public int isProvidingWeakPower() { + return 0; + } + + @Override + public void writeToStream(final ByteBuf data) throws IOException {} + + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + return false; + } + + @Override + public IGridNode getGridNode() { + return this.proxy.getNode(); + } + + @Override + public void onEntityCollision(final Entity entity) {} + + @Override + public void removeFromWorld() { + this.proxy.invalidate(); + } + + @Override + public void addToWorld() { + this.proxy.onReady(); + } + + @Override + public void setPartHostInfo( + final ForgeDirection side, final IPartHost host, final TileEntity tile + ) { + this.setSide(side); + this.tile = tile; + this.host = host; + } + + @Override + public IGridNode getExternalFacingNode() { + return null; + } + + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World world, final int x, final int y, final int z, final Random r + ) {} + + @Override + public int getLightLevel() { + return 0; + } + + @Override + public void getDrops(final List drops, final boolean wrenched) {} + + @Override + public int cableConnectionRenderTo() { + return 3; + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + return false; + } + + @Override + public IConfigManager getConfigManager() { + return null; + } + + @Override + public IInventory getInventoryByName(final String name) { + return null; + } + + /** + * 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 + */ + private void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (compound != null) { + final IConfigManager cm = this.getConfigManager(); + if (cm != null) { + cm.readFromNBT(compound); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + pHost.setPriority(compound.getInteger("priority")); + } + + final IInventory inv = this.getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; + final 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 + */ + private NBTTagCompound downloadSettings(final SettingsFrom from) { + final NBTTagCompound output = new NBTTagCompound(); + + final IConfigManager cm = this.getConfigManager(); + if (cm != null) { + cm.writeToNBT(output); + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + output.setInteger("priority", pHost.getPriority()); + } + + final IInventory inv = this.getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + ((AppEngInternalAEInventory) inv).writeToNBT(output, "config"); + } + + return output.hasNoTags() ? null : output; + } + + public boolean useStandardMemoryCard() { + return true; + } + + private boolean useMemoryCard(final EntityPlayer player) { + final ItemStack memCardIS = player.inventory.getCurrentItem(); + if (ForgeEventFactory.onItemUseStart(player, memCardIS, 1) <= 0) + return false; + + if (memCardIS != null && this.useStandardMemoryCard() + && memCardIS.getItem() instanceof IMemoryCard) { + final IMemoryCard memoryCard = (IMemoryCard) memCardIS.getItem(); + + ItemStack is = this.getItemStack(PartItemStack.Network); + + // Blocks and parts share the same soul! + final IDefinitions definitions = AEApi.instance().definitions(); + if (definitions.parts().iface().isSameAs(is)) { + for (final ItemStack iface : + definitions.blocks().iface().maybeStack(1).asSet()) { + is = iface; + } + } + + final String name = is.getUnlocalizedName(); + + if (player.isSneaking()) { + final NBTTagCompound data + = this.downloadSettings(SettingsFrom.MEMORY_CARD); + if (data != null) { + memoryCard.setMemoryCardContents(memCardIS, name, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + } + } else { + final String storedName = memoryCard.getSettingsName(memCardIS); + final NBTTagCompound data = memoryCard.getData(memCardIS); + if (name.equals(storedName)) { + this.uploadSettings(SettingsFrom.MEMORY_CARD, data); + memoryCard.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + } else { + memoryCard.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } + } + return true; + } + return false; + } + + @Override + public final boolean onActivate(final EntityPlayer player, final Vec3 pos) { + // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; + int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; + PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( + player, + PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + 0, + player.getEntityWorld() + ); + if (event.isCanceled()) + return false; + + if (this.useMemoryCard(player)) { + return true; + } + + return onPartActivate(player, pos); + } + + @Override + public final boolean onShiftActivate(final EntityPlayer player, final Vec3 pos) { + // int x = (int) pos.xCoord, y = (int) pos.yCoord, z = (int) pos.zCoord; + int x = this.tile.xCoord, y = this.tile.yCoord, z = this.tile.zCoord; + PlayerInteractEvent event = ForgeEventFactory.onPlayerInteract( + player, + PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK, + x, + y, + z, + 0, + player.getEntityWorld() + ); + if (event.isCanceled()) + return false; + + if (this.useMemoryCard(player)) { + return true; + } + + return this.onPartShiftActivate(player, pos); + } + + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } + + public boolean onPartShiftActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } + + @Override + public void onPlacement( + final EntityPlayer player, final ItemStack held, final ForgeDirection side + ) { + this.proxy.setOwner(player); + } + + @Override + public boolean canBePlacedOn(final BusSupport what) { + return what == BusSupport.CABLE; + } + + @Override + public boolean requireDynamicRender() { + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return null; + } + + public ForgeDirection getSide() { + return this.side; + } + + private void setSide(final ForgeDirection side) { + this.side = side; + } + + public ItemStack getItemStack() { + return this.is; + } + + public ISimplifiedBundle getRenderCache() { + return this.renderCache; + } + + public void setRenderCache(final ISimplifiedBundle renderCache) { + this.renderCache = renderCache; + } } diff --git a/src/main/java/appeng/parts/BusCollisionHelper.java b/src/main/java/appeng/parts/BusCollisionHelper.java index 32c6c907..b55f85f2 100644 --- a/src/main/java/appeng/parts/BusCollisionHelper.java +++ b/src/main/java/appeng/parts/BusCollisionHelper.java @@ -18,159 +18,156 @@ package appeng.parts; +import java.util.List; import appeng.api.parts.IPartCollisionHelper; import net.minecraft.entity.Entity; import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; +public class BusCollisionHelper implements IPartCollisionHelper { + private final List boxes; + private final ForgeDirection x; + private final ForgeDirection y; + private final ForgeDirection z; -public class BusCollisionHelper implements IPartCollisionHelper -{ + private final Entity entity; + private final boolean isVisual; - private final List boxes; + public BusCollisionHelper( + final List boxes, + final ForgeDirection x, + final ForgeDirection y, + final ForgeDirection z, + final Entity e, + final boolean visual + ) { + this.boxes = boxes; + this.x = x; + this.y = y; + this.z = z; + this.entity = e; + this.isVisual = visual; + } - private final ForgeDirection x; - private final ForgeDirection y; - private final ForgeDirection z; + public BusCollisionHelper( + final List boxes, + final ForgeDirection s, + final Entity e, + final boolean visual + ) { + this.boxes = boxes; + this.entity = e; + this.isVisual = visual; - private final Entity entity; - private final boolean isVisual; + 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; + } + } - public BusCollisionHelper( final List boxes, final ForgeDirection x, final ForgeDirection y, final ForgeDirection z, final Entity e, final boolean visual ) - { - this.boxes = boxes; - this.x = x; - this.y = y; - this.z = z; - this.entity = e; - this.isVisual = visual; - } + /** + * pretty much useless... + */ + public Entity getEntity() { + return this.entity; + } - public BusCollisionHelper( final List boxes, final ForgeDirection s, final Entity e, final boolean visual ) - { - this.boxes = boxes; - this.entity = e; - this.isVisual = visual; + @Override + public void + addBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + minX /= 16.0; + minY /= 16.0; + minZ /= 16.0; + maxX /= 16.0; + maxY /= 16.0; + maxZ /= 16.0; - 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; - } - } + double aX = minX * this.x.offsetX + minY * this.y.offsetX + minZ * this.z.offsetX; + double aY = minX * this.x.offsetY + minY * this.y.offsetY + minZ * this.z.offsetY; + double aZ = minX * this.x.offsetZ + minY * this.y.offsetZ + minZ * this.z.offsetZ; - /** - * pretty much useless... - */ - public Entity getEntity() - { - return this.entity; - } + double bX = maxX * this.x.offsetX + maxY * this.y.offsetX + maxZ * this.z.offsetX; + 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; - @Override - public void addBox( double minX, double minY, double minZ, double maxX, double maxY, double maxZ ) - { - minX /= 16.0; - minY /= 16.0; - minZ /= 16.0; - maxX /= 16.0; - maxY /= 16.0; - maxZ /= 16.0; + if (this.x.offsetX + this.y.offsetX + this.z.offsetX < 0) { + aX += 1; + bX += 1; + } - double aX = minX * this.x.offsetX + minY * this.y.offsetX + minZ * this.z.offsetX; - double aY = minX * this.x.offsetY + minY * this.y.offsetY + minZ * this.z.offsetY; - double aZ = minX * this.x.offsetZ + minY * this.y.offsetZ + minZ * this.z.offsetZ; + if (this.x.offsetY + this.y.offsetY + this.z.offsetY < 0) { + aY += 1; + bY += 1; + } - double bX = maxX * this.x.offsetX + maxY * this.y.offsetX + maxZ * this.z.offsetX; - 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.offsetZ + this.y.offsetZ + this.z.offsetZ < 0) { + aZ += 1; + bZ += 1; + } - if( this.x.offsetX + this.y.offsetX + this.z.offsetX < 0 ) - { - aX += 1; - bX += 1; - } + minX = Math.min(aX, bX); + minY = Math.min(aY, bY); + minZ = Math.min(aZ, bZ); + maxX = Math.max(aX, bX); + maxY = Math.max(aY, bY); + maxZ = Math.max(aZ, bZ); - if( this.x.offsetY + this.y.offsetY + this.z.offsetY < 0 ) - { - aY += 1; - bY += 1; - } + this.boxes.add(AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ)); + } - if( this.x.offsetZ + this.y.offsetZ + this.z.offsetZ < 0 ) - { - aZ += 1; - bZ += 1; - } + @Override + public ForgeDirection getWorldX() { + return this.x; + } - minX = Math.min( aX, bX ); - minY = Math.min( aY, bY ); - minZ = Math.min( aZ, bZ ); - maxX = Math.max( aX, bX ); - maxY = Math.max( aY, bY ); - maxZ = Math.max( aZ, bZ ); + @Override + public ForgeDirection getWorldY() { + return this.y; + } - this.boxes.add( AxisAlignedBB.getBoundingBox( minX, minY, minZ, maxX, maxY, maxZ ) ); - } + @Override + public ForgeDirection getWorldZ() { + return this.z; + } - @Override - public ForgeDirection getWorldX() - { - return this.x; - } - - @Override - public ForgeDirection getWorldY() - { - return this.y; - } - - @Override - public ForgeDirection getWorldZ() - { - return this.z; - } - - @Override - public boolean isBBCollision() - { - return !this.isVisual; - } + @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 8a44d1ff..a1a6c6bd 100644 --- a/src/main/java/appeng/parts/CableBusContainer.java +++ b/src/main/java/appeng/parts/CableBusContainer.java @@ -18,6 +18,8 @@ package appeng.parts; +import java.io.IOException; +import java.util.*; import appeng.api.AEApi; import appeng.api.config.YesNo; @@ -53,1082 +55,909 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.*; +public class CableBusContainer + extends CableBusStorage implements AEMultiTile, ICableBusContainer { + private static final ThreadLocal IS_LOADING = new ThreadLocal(); + private final EnumSet myLayerFlags = EnumSet.noneOf(LayerFlags.class); + private YesNo hasRedstone = YesNo.UNDECIDED; + private IPartHost tcb; + private boolean requiresDynamicRender = false; + private boolean inWorld = false; + public CableBusContainer(final IPartHost host) { + this.tcb = host; + } -public class CableBusContainer extends CableBusStorage implements AEMultiTile, ICableBusContainer -{ + public static boolean isLoading() { + final Boolean is = IS_LOADING.get(); + return is != null && is; + } - private static final ThreadLocal IS_LOADING = new ThreadLocal(); - private final EnumSet myLayerFlags = EnumSet.noneOf( LayerFlags.class ); - private YesNo hasRedstone = YesNo.UNDECIDED; - private IPartHost tcb; - private boolean requiresDynamicRender = false; - private boolean inWorld = false; + public void setHost(final IPartHost host) { + this.tcb.clearContainer(); + this.tcb = host; + } - public CableBusContainer( final IPartHost host ) - { - this.tcb = host; - } + public void rotateLeft() { + final IPart[] newSides = new IPart[6]; - public static boolean isLoading() - { - final Boolean is = IS_LOADING.get(); - return is != null && is; - } + newSides[ForgeDirection.UP.ordinal()] = this.getSide(ForgeDirection.UP); + newSides[ForgeDirection.DOWN.ordinal()] = this.getSide(ForgeDirection.DOWN); - public void setHost( final IPartHost host ) - { - this.tcb.clearContainer(); - this.tcb = host; - } + newSides[ForgeDirection.EAST.ordinal()] = this.getSide(ForgeDirection.NORTH); + newSides[ForgeDirection.SOUTH.ordinal()] = this.getSide(ForgeDirection.EAST); + newSides[ForgeDirection.WEST.ordinal()] = this.getSide(ForgeDirection.SOUTH); + newSides[ForgeDirection.NORTH.ordinal()] = this.getSide(ForgeDirection.WEST); - public void rotateLeft() - { - final IPart[] newSides = new IPart[6]; + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + this.setSide(dir, newSides[dir.ordinal()]); + } - newSides[ForgeDirection.UP.ordinal()] = this.getSide( ForgeDirection.UP ); - newSides[ForgeDirection.DOWN.ordinal()] = this.getSide( ForgeDirection.DOWN ); + this.getFacadeContainer().rotateLeft(); + } - newSides[ForgeDirection.EAST.ordinal()] = this.getSide( ForgeDirection.NORTH ); - newSides[ForgeDirection.SOUTH.ordinal()] = this.getSide( ForgeDirection.EAST ); - newSides[ForgeDirection.WEST.ordinal()] = this.getSide( ForgeDirection.SOUTH ); - newSides[ForgeDirection.NORTH.ordinal()] = this.getSide( ForgeDirection.WEST ); + @Override + public IFacadeContainer getFacadeContainer() { + return new FacadeContainer(this); + } - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - this.setSide( dir, newSides[dir.ordinal()] ); - } + @Override + public boolean canAddPart(ItemStack is, final ForgeDirection side) { + if (PartPlacement.isFacade(is, side) != null) { + return true; + } - this.getFacadeContainer().rotateLeft(); - } + if (is.getItem() instanceof IPartItem) { + final IPartItem bi = (IPartItem) is.getItem(); - @Override - public IFacadeContainer getFacadeContainer() - { - return new FacadeContainer( this ); - } + is = is.copy(); + is.stackSize = 1; - @Override - public boolean canAddPart( ItemStack is, final ForgeDirection side ) - { - if( PartPlacement.isFacade( is, side ) != null ) - { - return true; - } + final IPart bp = bi.createPartFromItemStack(is); + if (bp != null) { + if (bp instanceof IPartCable) { + boolean canPlace = true; + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(d) != null + && !this.getPart(d).canBePlacedOn( + ((IPartCable) bp).supportsBuses() + )) { + canPlace = false; + } + } - if( is.getItem() instanceof IPartItem ) - { - final IPartItem bi = (IPartItem) is.getItem(); + if (!canPlace) { + return false; + } - is = is.copy(); - is.stackSize = 1; + return this.getPart(ForgeDirection.UNKNOWN) == null; + } else if (!(bp instanceof IPartCable) && side != ForgeDirection.UNKNOWN) { + final IPart cable = this.getPart(ForgeDirection.UNKNOWN); + if (cable != null + && !bp.canBePlacedOn(((IPartCable) cable).supportsBuses())) { + return false; + } - final IPart bp = bi.createPartFromItemStack( is ); - if( bp != null ) - { - if( bp instanceof IPartCable ) - { - boolean canPlace = true; - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) - { - canPlace = false; - } - } + return this.getPart(side) == null; + } + } + } + return false; + } - if( !canPlace ) - { - return false; - } + @Override + public ForgeDirection + addPart(ItemStack is, final ForgeDirection side, final EntityPlayer player) { + if (this.canAddPart(is, side)) { + if (is.getItem() instanceof IPartItem) { + final IPartItem bi = (IPartItem) is.getItem(); - return this.getPart( ForgeDirection.UNKNOWN ) == null; - } - else if( !( bp instanceof IPartCable ) && side != ForgeDirection.UNKNOWN ) - { - final IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) - { - return false; - } + is = is.copy(); + is.stackSize = 1; - return this.getPart( side ) == null; - } - } - } - return false; - } + final IPart bp = bi.createPartFromItemStack(is); + if (bp instanceof IPartCable) { + boolean canPlace = true; + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(d) != null + && !this.getPart(d).canBePlacedOn( + ((IPartCable) bp).supportsBuses() + )) { + canPlace = false; + } + } - @Override - public ForgeDirection addPart( ItemStack is, final ForgeDirection side, final EntityPlayer player ) - { - if( this.canAddPart( is, side ) ) - { - if( is.getItem() instanceof IPartItem ) - { - final IPartItem bi = (IPartItem) is.getItem(); + if (!canPlace) { + return null; + } - is = is.copy(); - is.stackSize = 1; + if (this.getPart(ForgeDirection.UNKNOWN) != null) { + return null; + } - final IPart bp = bi.createPartFromItemStack( is ); - if( bp instanceof IPartCable ) - { - boolean canPlace = true; - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( d ) != null && !this.getPart( d ).canBePlacedOn( ( (IPartCable) bp ).supportsBuses() ) ) - { - canPlace = false; - } - } + this.setCenter((IPartCable) bp); + bp.setPartHostInfo(ForgeDirection.UNKNOWN, this, this.tcb.getTile()); - if( !canPlace ) - { - return null; - } + if (player != null) { + bp.onPlacement(player, is, side); + } - if( this.getPart( ForgeDirection.UNKNOWN ) != null ) - { - return null; - } + if (this.inWorld) { + bp.addToWorld(); + } - this.setCenter( (IPartCable) bp ); - bp.setPartHostInfo( ForgeDirection.UNKNOWN, this, this.tcb.getTile() ); + final IGridNode cn = this.getCenter().getGridNode(); + if (cn != null) { + for (final ForgeDirection ins : ForgeDirection.VALID_DIRECTIONS) { + final IPart sbp = this.getPart(ins); + if (sbp != null) { + final IGridNode sn = sbp.getGridNode(); + if (sn != null) { + try { + new GridConnection( + cn, sn, ForgeDirection.UNKNOWN + ); + } catch (final FailedConnection e) { + // ekk! - if( player != null ) - { - bp.onPlacement( player, is, side ); - } + bp.removeFromWorld(); + this.setCenter(null); + return null; + } + } + } + } + } - if( this.inWorld ) - { - bp.addToWorld(); - } - - final IGridNode cn = this.getCenter().getGridNode(); - if( cn != null ) - { - for( final ForgeDirection ins : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart sbp = this.getPart( ins ); - if( sbp != null ) - { - final IGridNode sn = sbp.getGridNode(); - if( sn != null ) - { - try - { - new GridConnection( cn, sn, ForgeDirection.UNKNOWN ); - } - catch( final FailedConnection e ) - { - // ekk! - - bp.removeFromWorld(); - this.setCenter( null ); - return null; - } - } - } - } - } - - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - return ForgeDirection.UNKNOWN; - } + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + return ForgeDirection.UNKNOWN; + } else if( bp != null && !( bp instanceof IPartCable ) && side != ForgeDirection.UNKNOWN ) { - final IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if( cable != null && !bp.canBePlacedOn( ( (IPartCable) cable ).supportsBuses() ) ) - { - return null; - } - - this.setSide( side, bp ); - bp.setPartHostInfo( side, this, this.getTile() ); - - if( player != null ) - { - bp.onPlacement( player, is, side ); - } - - if( this.inWorld ) - { - bp.addToWorld(); - } - - if( this.getCenter() != null ) - { - final IGridNode cn = this.getCenter().getGridNode(); - final IGridNode sn = bp.getGridNode(); - - if( cn != null && sn != null ) - { - try - { - new GridConnection( cn, sn, ForgeDirection.UNKNOWN ); - } - catch( final FailedConnection e ) - { - // ekk! - - bp.removeFromWorld(); - this.setSide( side, null ); - return null; - } - } - } - - this.updateDynamicRender(); - this.updateConnections(); - this.markForUpdate(); - this.markForSave(); - this.partChanged(); - return side; - } - } - } - return null; - } - - @Override - public IPart getPart( final ForgeDirection side ) - { - if( side == ForgeDirection.UNKNOWN ) - { - return this.getCenter(); - } - return this.getSide( side ); - } - - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - 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(); - } - } - - @Override - public void markForUpdate() - { - this.tcb.markForUpdate(); - } - - @Override - public DimensionalCoord getLocation() - { - return this.tcb.getLocation(); - } - - @Override - public TileEntity getTile() - { - return this.tcb.getTile(); - } - - @Override - public AEColor getColor() - { - if( this.getCenter() != null ) - { - final IPartCable c = this.getCenter(); - return c.getCableColor(); - } - return AEColor.Transparent; - } - - @Override - public void clearContainer() - { - throw new UnsupportedOperationException( "Now that is silly!" ); - } - - @Override - public boolean isBlocked( final ForgeDirection side ) - { - return this.tcb.isBlocked( side ); - } - - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - final List boxes = new LinkedList(); - - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - p.getBoxes( bch ); - for( AxisAlignedBB bb : boxes ) - { - bb = bb.expand( 0.002, 0.002, 0.002 ); - if( bb.isVecInside( pos ) ) - { - return new SelectedPart( p, side ); - } - } - } - } - - if( AEApi.instance().partHelper().getCableRenderMode().opaqueFacades ) - { - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - final IFacadePart p = fc.getFacade( side ); - if( p != null ) - { - final List boxes = new LinkedList(); - - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, side, null, true ); - p.getBoxes( bch, null ); - for( AxisAlignedBB bb : boxes ) - { - bb = bb.expand( 0.01, 0.01, 0.01 ); - if( bb.isVecInside( pos ) ) - { - return new SelectedPart( p, side ); - } - } - } - } - } - - return new SelectedPart(); - } - - @Override - public void markForSave() - { - this.tcb.markForSave(); - } - - @Override - public void partChanged() - { - if( this.getCenter() == null ) - { - final List facades = new LinkedList(); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - final IFacadePart fp = fc.getFacade( d ); - if( fp != null ) - { - facades.add( fp.getItemStack() ); - fc.removeFacade( this.tcb, d ); - } - } - - if( !facades.isEmpty() ) - { - final TileEntity te = this.tcb.getTile(); - Platform.spawnDrops( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, facades ); - } - } - - this.tcb.partChanged(); - } - - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - if( this.hasRedstone == YesNo.UNDECIDED ) - { - this.updateRedstone(); - } - - return this.hasRedstone == YesNo.YES; - } - - @Override - public boolean isEmpty() - { - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - return false; - } - - if( s != ForgeDirection.UNKNOWN ) - { - final IFacadePart fp = fc.getFacade( s ); - if( fp != null ) - { - return false; - } - } - } - return true; - } - - @Override - public Set getLayerFlags() - { - return this.myLayerFlags; - } - - @Override - public void cleanup() - { - this.tcb.cleanup(); - } - - @Override - public void notifyNeighbors() - { - this.tcb.notifyNeighbors(); - } - - @Override - public boolean isInWorld() - { - return this.inWorld; - } - - private void updateRedstone() - { - final TileEntity te = this.getTile(); - this.hasRedstone = te.getWorldObj().isBlockIndirectlyGettingPowered( te.xCoord, te.yCoord, te.zCoord ) ? YesNo.YES : YesNo.NO; - } - - private void updateDynamicRender() - { - this.setRequiresDynamicRender( false ); - for( final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart p = this.getPart( s ); - if( p != null ) - { - this.setRequiresDynamicRender( this.isRequiresDynamicRender() || p.requireDynamicRender() ); - } - } - } - - /** - * use for FMP - */ - public void updateConnections() - { - if( this.getCenter() != null ) - { - final EnumSet sides = EnumSet.allOf( ForgeDirection.class ); - - for( final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( s ) != null || this.isBlocked( s ) ) - { - sides.remove( s ); - } - } - - this.getCenter().setValidSides( sides ); - final IGridNode n = this.getCenter().getGridNode(); - if( n != null ) - { - n.updateState(); - } - } - } - - public void addToWorld() - { - if( this.inWorld ) - { - return; - } - - this.inWorld = true; - IS_LOADING.set( true ); - - final TileEntity te = this.getTile(); - - // start with the center, then install the side parts into the grid. - for( int x = 6; x >= 0; x-- ) - { - final ForgeDirection s = ForgeDirection.getOrientation( x ); - final IPart part = this.getPart( s ); - - if( part != null ) - { - part.setPartHostInfo( s, this, te ); - part.addToWorld(); - - if( s != ForgeDirection.UNKNOWN ) - { - final IGridNode sn = part.getGridNode(); - if( sn != null ) - { - // this is a really stupid if statement, why was this - // here? - // if ( !sn.getConnections().iterator().hasNext() ) - - final IPart center = this.getPart( ForgeDirection.UNKNOWN ); - if( center != null ) - { - final IGridNode cn = center.getGridNode(); - if( cn != null ) - { - try - { - AEApi.instance().createGridConnection( cn, sn ); - } - catch( final FailedConnection e ) - { - // ekk - } - } - } - } - } - } - } - - this.partChanged(); - - IS_LOADING.set( false ); - } - - public void removeFromWorld() - { - if( !this.inWorld ) - { - return; - } - - this.inWorld = false; - - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.removeFromWorld(); - } - } - - this.partChanged(); - } - - @Override - public IGridNode getGridNode( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part != null ) - { - final IGridNode n = part.getExternalFacingNode(); - if( n != null ) - { - return n; - } - } - - if( this.getCenter() != null ) - { - return this.getCenter().getGridNode(); - } - - return null; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) part ).getCableConnectionType( dir ); - if( t != null && t != AECableType.NONE ) - { - return t; - } - } - - if( this.getCenter() != null ) - { - final IPartCable c = this.getCenter(); - return c.getCableConnectionType(); - } - return AECableType.NONE; - } - - @Override - public void securityBreak() - { - for( final ForgeDirection d : ForgeDirection.values() ) - { - final IPart p = this.getPart( d ); - if( p instanceof IGridHost ) - { - ( (IGridHost) p ).securityBreak(); - } - } - } - - public Iterable getSelectedBoundingBoxesFromPool( final boolean ignoreConnections, final boolean includeFacades, final Entity e, final boolean visual ) - { - final List boxes = new LinkedList(); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPartCollisionHelper bch = new BusCollisionHelper( boxes, s, e, visual ); - - final IPart part = this.getPart( s ); - if( part != null ) - { - if( ignoreConnections && 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 ) - { - final IFacadePart fp = fc.getFacade( s ); - if( fp != null ) - { - fp.getBoxes( bch, e ); - } - } - } - } - - return boxes; - } - - @Override - public int isProvidingStrongPower( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - return part != null ? part.isProvidingStrongPower() : 0; - } - - @Override - public int isProvidingWeakPower( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - return part != null ? part.isProvidingWeakPower() : 0; - } - - @Override - public boolean canConnectRedstone( final EnumSet enumSet ) - { - for( final ForgeDirection dir : enumSet ) - { - final IPart part = this.getPart( dir ); - if( part != null && part.canConnectRedstone() ) - { - return true; - } - } - return false; - } - - @Override - public void onEntityCollision( final Entity entity ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.onEntityCollision( entity ); - } - } - } - - @Override - public boolean activate( final EntityPlayer player, final Vec3 pos ) - { - final 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( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.onNeighborChanged(); - } - } - } - - @Override - public boolean isSolidOnSide( final ForgeDirection side ) - { - if( side == null || side == ForgeDirection.UNKNOWN ) - { - return false; - } - - // facades are solid.. - final IFacadePart fp = this.getFacadeContainer().getFacade( side ); - if( fp != null ) - { - return true; - } - - // buses can be too. - final IPart part = this.getPart( side ); - return part != null && part.isSolid(); - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - if( p.isLadder( entity ) ) - { - return true; - } - } - } - - return false; - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - for( final ForgeDirection side : ForgeDirection.values() ) - { - final IPart p = this.getPart( side ); - if( p != null ) - { - p.randomDisplayTick( world, x, y, z, r ); - } - } - } - - @Override - public int getLightValue() - { - int light = 0; - - for( final ForgeDirection d : ForgeDirection.values() ) - { - final IPart p = this.getPart( d ); - if( p != null ) - { - light = Math.max( p.getLightLevel(), light ); - } - } - - if( light > 0 && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.CLApi ) ) - { - return ( (ICLApi) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.CLApi ) ).colorLight( this.getColor(), light ); - } - - return light; - } - - @SideOnly( Side.CLIENT ) - public void renderStatic( final double x, final double y, final double z ) - { - CableRenderHelper.getInstance().renderStatic( this, this.getFacadeContainer() ); - } - - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z ) - { - CableRenderHelper.getInstance().renderDynamic( this, x, y, z ); - } - - public void writeToStream( final ByteBuf data ) throws IOException - { - int sides = 0; - for( int x = 0; x < 7; x++ ) - { - final IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); - if( p != null ) - { - sides |= ( 1 << x ); - } - } - - data.writeByte( (byte) sides ); - - for( int x = 0; x < 7; x++ ) - { - final IPart p = this.getPart( ForgeDirection.getOrientation( x ) ); - if( p != null ) - { - final ItemStack 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( final ByteBuf data ) throws IOException - { - final 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 ); - - final short itemID = data.readShort(); - final short dmgValue = data.readShort(); - - final Item myItem = Item.getItemById( itemID ); - - final 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 IllegalStateException( "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( final NBTTagCompound data ) - { - data.setInteger( "hasRedstone", this.hasRedstone.ordinal() ); - - final IFacadeContainer fc = this.getFacadeContainer(); - for( final ForgeDirection s : ForgeDirection.values() ) - { - fc.writeToNBT( data ); - - final IPart part = this.getPart( s ); - if( part != null ) - { - final NBTTagCompound def = new NBTTagCompound(); - part.getItemStack( PartItemStack.World ).writeToNBT( def ); - - final NBTTagCompound extra = new NBTTagCompound(); - part.writeToNBT( extra ); - - data.setTag( "def:" + this.getSide( part ).ordinal(), def ); - data.setTag( "extra:" + this.getSide( part ).ordinal(), extra ); - } - } - } - - private ForgeDirection getSide( final IPart part ) - { - if( this.getCenter() == part ) - { - return ForgeDirection.UNKNOWN; - } - else - { - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getSide( side ) == part ) - { - return side; - } - } - } - - throw new IllegalStateException( "Uhh Bad Part (" + part + ") on Side." ); - } - - public void readFromNBT( final 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 ); - - final NBTTagCompound def = data.getCompoundTag( "def:" + side.ordinal() ); - final NBTTagCompound extra = data.getCompoundTag( "extra:" + side.ordinal() ); - if( def != null && extra != null ) - { - IPart p = this.getPart( side ); - final ItemStack iss = ItemStack.loadItemStackFromNBT( def ); - if( iss == null ) - { - continue; - } - - final 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.warn( "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( final List drops ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - drops.add( part.getItemStack( PartItemStack.Break ) ); - part.getDrops( drops, false ); - } - - if( s != ForgeDirection.UNKNOWN ) - { - final IFacadePart fp = this.getFacadeContainer().getFacade( s ); - if( fp != null ) - { - drops.add( fp.getItemStack() ); - } - } - } - - return drops; - } - - public List getNoDrops( final List drops ) - { - for( final ForgeDirection s : ForgeDirection.values() ) - { - final IPart part = this.getPart( s ); - if( part != null ) - { - part.getDrops( drops, false ); - } - } - - return drops; - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - final IPart cable = this.getPart( ForgeDirection.UNKNOWN ); - if( cable != null ) - { - final IPartCable pc = (IPartCable) cable; - return pc.changeColor( colour, who ); - } - return false; - } - - public boolean isRequiresDynamicRender() - { - return this.requiresDynamicRender; - } - - private void setRequiresDynamicRender( final boolean requiresDynamicRender ) - { - this.requiresDynamicRender = requiresDynamicRender; - } + final IPart cable = this.getPart(ForgeDirection.UNKNOWN); + if (cable != null + && !bp.canBePlacedOn(((IPartCable) cable).supportsBuses())) { + return null; + } + + this.setSide(side, bp); + bp.setPartHostInfo(side, this, this.getTile()); + + if (player != null) { + bp.onPlacement(player, is, side); + } + + if (this.inWorld) { + bp.addToWorld(); + } + + if (this.getCenter() != null) { + final IGridNode cn = this.getCenter().getGridNode(); + final IGridNode sn = bp.getGridNode(); + + if (cn != null && sn != null) { + try { + new GridConnection(cn, sn, ForgeDirection.UNKNOWN); + } catch (final FailedConnection e) { + // ekk! + + bp.removeFromWorld(); + this.setSide(side, null); + return null; + } + } + } + + this.updateDynamicRender(); + this.updateConnections(); + this.markForUpdate(); + this.markForSave(); + this.partChanged(); + return side; + } + } + } + return null; + } + + @Override + public IPart getPart(final ForgeDirection side) { + if (side == ForgeDirection.UNKNOWN) { + return this.getCenter(); + } + return this.getSide(side); + } + + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + 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(); + } + } + + @Override + public void markForUpdate() { + this.tcb.markForUpdate(); + } + + @Override + public DimensionalCoord getLocation() { + return this.tcb.getLocation(); + } + + @Override + public TileEntity getTile() { + return this.tcb.getTile(); + } + + @Override + public AEColor getColor() { + if (this.getCenter() != null) { + final IPartCable c = this.getCenter(); + return c.getCableColor(); + } + return AEColor.Transparent; + } + + @Override + public void clearContainer() { + throw new UnsupportedOperationException("Now that is silly!"); + } + + @Override + public boolean isBlocked(final ForgeDirection side) { + return this.tcb.isBlocked(side); + } + + @Override + public SelectedPart selectPart(final Vec3 pos) { + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = this.getPart(side); + if (p != null) { + final List boxes = new LinkedList(); + + final IPartCollisionHelper bch + = new BusCollisionHelper(boxes, side, null, true); + p.getBoxes(bch); + for (AxisAlignedBB bb : boxes) { + bb = bb.expand(0.002, 0.002, 0.002); + if (bb.isVecInside(pos)) { + return new SelectedPart(p, side); + } + } + } + } + + if (AEApi.instance().partHelper().getCableRenderMode().opaqueFacades) { + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final IFacadePart p = fc.getFacade(side); + if (p != null) { + final List boxes = new LinkedList(); + + final IPartCollisionHelper bch + = new BusCollisionHelper(boxes, side, null, true); + p.getBoxes(bch, null); + for (AxisAlignedBB bb : boxes) { + bb = bb.expand(0.01, 0.01, 0.01); + if (bb.isVecInside(pos)) { + return new SelectedPart(p, side); + } + } + } + } + } + + return new SelectedPart(); + } + + @Override + public void markForSave() { + this.tcb.markForSave(); + } + + @Override + public void partChanged() { + if (this.getCenter() == null) { + final List facades = new LinkedList(); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + final IFacadePart fp = fc.getFacade(d); + if (fp != null) { + facades.add(fp.getItemStack()); + fc.removeFacade(this.tcb, d); + } + } + + if (!facades.isEmpty()) { + final TileEntity te = this.tcb.getTile(); + Platform.spawnDrops( + te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord, facades + ); + } + } + + this.tcb.partChanged(); + } + + @Override + public boolean hasRedstone(final ForgeDirection side) { + if (this.hasRedstone == YesNo.UNDECIDED) { + this.updateRedstone(); + } + + return this.hasRedstone == YesNo.YES; + } + + @Override + public boolean isEmpty() { + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + return false; + } + + if (s != ForgeDirection.UNKNOWN) { + final IFacadePart fp = fc.getFacade(s); + if (fp != null) { + return false; + } + } + } + return true; + } + + @Override + public Set getLayerFlags() { + return this.myLayerFlags; + } + + @Override + public void cleanup() { + this.tcb.cleanup(); + } + + @Override + public void notifyNeighbors() { + this.tcb.notifyNeighbors(); + } + + @Override + public boolean isInWorld() { + return this.inWorld; + } + + private void updateRedstone() { + final TileEntity te = this.getTile(); + this.hasRedstone = te.getWorldObj().isBlockIndirectlyGettingPowered( + te.xCoord, te.yCoord, te.zCoord + ) + ? YesNo.YES + : YesNo.NO; + } + + private void updateDynamicRender() { + this.setRequiresDynamicRender(false); + for (final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) { + final IPart p = this.getPart(s); + if (p != null) { + this.setRequiresDynamicRender( + this.isRequiresDynamicRender() || p.requireDynamicRender() + ); + } + } + } + + /** + * use for FMP + */ + public void updateConnections() { + if (this.getCenter() != null) { + final EnumSet sides = EnumSet.allOf(ForgeDirection.class); + + for (final ForgeDirection s : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(s) != null || this.isBlocked(s)) { + sides.remove(s); + } + } + + this.getCenter().setValidSides(sides); + final IGridNode n = this.getCenter().getGridNode(); + if (n != null) { + n.updateState(); + } + } + } + + public void addToWorld() { + if (this.inWorld) { + return; + } + + this.inWorld = true; + IS_LOADING.set(true); + + final TileEntity te = this.getTile(); + + // start with the center, then install the side parts into the grid. + for (int x = 6; x >= 0; x--) { + final ForgeDirection s = ForgeDirection.getOrientation(x); + final IPart part = this.getPart(s); + + if (part != null) { + part.setPartHostInfo(s, this, te); + part.addToWorld(); + + if (s != ForgeDirection.UNKNOWN) { + final IGridNode sn = part.getGridNode(); + if (sn != null) { + // this is a really stupid if statement, why was this + // here? + // if ( !sn.getConnections().iterator().hasNext() ) + + final IPart center = this.getPart(ForgeDirection.UNKNOWN); + if (center != null) { + final IGridNode cn = center.getGridNode(); + if (cn != null) { + try { + AEApi.instance().createGridConnection(cn, sn); + } catch (final FailedConnection e) { + // ekk + } + } + } + } + } + } + } + + this.partChanged(); + + IS_LOADING.set(false); + } + + public void removeFromWorld() { + if (!this.inWorld) { + return; + } + + this.inWorld = false; + + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.removeFromWorld(); + } + } + + this.partChanged(); + } + + @Override + public IGridNode getGridNode(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part != null) { + final IGridNode n = part.getExternalFacingNode(); + if (n != null) { + return n; + } + } + + if (this.getCenter() != null) { + return this.getCenter().getGridNode(); + } + + return null; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + final IPart part = this.getPart(dir); + if (part instanceof IGridHost) { + final AECableType t = ((IGridHost) part).getCableConnectionType(dir); + if (t != null && t != AECableType.NONE) { + return t; + } + } + + if (this.getCenter() != null) { + final IPartCable c = this.getCenter(); + return c.getCableConnectionType(); + } + return AECableType.NONE; + } + + @Override + public void securityBreak() { + for (final ForgeDirection d : ForgeDirection.values()) { + final IPart p = this.getPart(d); + if (p instanceof IGridHost) { + ((IGridHost) p).securityBreak(); + } + } + } + + public Iterable getSelectedBoundingBoxesFromPool( + final boolean ignoreConnections, + final boolean includeFacades, + final Entity e, + final boolean visual + ) { + final List boxes = new LinkedList(); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection s : ForgeDirection.values()) { + final IPartCollisionHelper bch = new BusCollisionHelper(boxes, s, e, visual); + + final IPart part = this.getPart(s); + if (part != null) { + if (ignoreConnections && 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) { + final IFacadePart fp = fc.getFacade(s); + if (fp != null) { + fp.getBoxes(bch, e); + } + } + } + } + + return boxes; + } + + @Override + public int isProvidingStrongPower(final ForgeDirection side) { + final IPart part = this.getPart(side); + return part != null ? part.isProvidingStrongPower() : 0; + } + + @Override + public int isProvidingWeakPower(final ForgeDirection side) { + final IPart part = this.getPart(side); + return part != null ? part.isProvidingWeakPower() : 0; + } + + @Override + public boolean canConnectRedstone(final EnumSet enumSet) { + for (final ForgeDirection dir : enumSet) { + final IPart part = this.getPart(dir); + if (part != null && part.canConnectRedstone()) { + return true; + } + } + return false; + } + + @Override + public void onEntityCollision(final Entity entity) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.onEntityCollision(entity); + } + } + } + + @Override + public boolean activate(final EntityPlayer player, final Vec3 pos) { + final 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 (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.onNeighborChanged(); + } + } + } + + @Override + public boolean isSolidOnSide(final ForgeDirection side) { + if (side == null || side == ForgeDirection.UNKNOWN) { + return false; + } + + // facades are solid.. + final IFacadePart fp = this.getFacadeContainer().getFacade(side); + if (fp != null) { + return true; + } + + // buses can be too. + final IPart part = this.getPart(side); + return part != null && part.isSolid(); + } + + @Override + public boolean isLadder(final EntityLivingBase entity) { + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = this.getPart(side); + if (p != null) { + if (p.isLadder(entity)) { + return true; + } + } + } + + return false; + } + + @Override + public void randomDisplayTick( + final World world, final int x, final int y, final int z, final Random r + ) { + for (final ForgeDirection side : ForgeDirection.values()) { + final IPart p = this.getPart(side); + if (p != null) { + p.randomDisplayTick(world, x, y, z, r); + } + } + } + + @Override + public int getLightValue() { + int light = 0; + + for (final ForgeDirection d : ForgeDirection.values()) { + final IPart p = this.getPart(d); + if (p != null) { + light = Math.max(p.getLightLevel(), light); + } + } + + if (light > 0 && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.CLApi)) { + return ((ICLApi + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.CLApi)) + .colorLight(this.getColor(), light); + } + + return light; + } + + @SideOnly(Side.CLIENT) + public void renderStatic(final double x, final double y, final double z) { + CableRenderHelper.getInstance().renderStatic(this, this.getFacadeContainer()); + } + + @SideOnly(Side.CLIENT) + public void renderDynamic(final double x, final double y, final double z) { + CableRenderHelper.getInstance().renderDynamic(this, x, y, z); + } + + public void writeToStream(final ByteBuf data) throws IOException { + int sides = 0; + for (int x = 0; x < 7; x++) { + final IPart p = this.getPart(ForgeDirection.getOrientation(x)); + if (p != null) { + sides |= (1 << x); + } + } + + data.writeByte((byte) sides); + + for (int x = 0; x < 7; x++) { + final IPart p = this.getPart(ForgeDirection.getOrientation(x)); + if (p != null) { + final ItemStack 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(final ByteBuf data) throws IOException { + final 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); + + final short itemID = data.readShort(); + final short dmgValue = data.readShort(); + + final Item myItem = Item.getItemById(itemID); + + final 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 IllegalStateException( + "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(final NBTTagCompound data) { + data.setInteger("hasRedstone", this.hasRedstone.ordinal()); + + final IFacadeContainer fc = this.getFacadeContainer(); + for (final ForgeDirection s : ForgeDirection.values()) { + fc.writeToNBT(data); + + final IPart part = this.getPart(s); + if (part != null) { + final NBTTagCompound def = new NBTTagCompound(); + part.getItemStack(PartItemStack.World).writeToNBT(def); + + final NBTTagCompound extra = new NBTTagCompound(); + part.writeToNBT(extra); + + data.setTag("def:" + this.getSide(part).ordinal(), def); + data.setTag("extra:" + this.getSide(part).ordinal(), extra); + } + } + } + + private ForgeDirection getSide(final IPart part) { + if (this.getCenter() == part) { + return ForgeDirection.UNKNOWN; + } else { + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (this.getSide(side) == part) { + return side; + } + } + } + + throw new IllegalStateException("Uhh Bad Part (" + part + ") on Side."); + } + + public void readFromNBT(final 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); + + final NBTTagCompound def = data.getCompoundTag("def:" + side.ordinal()); + final NBTTagCompound extra = data.getCompoundTag("extra:" + side.ordinal()); + if (def != null && extra != null) { + IPart p = this.getPart(side); + final ItemStack iss = ItemStack.loadItemStackFromNBT(def); + if (iss == null) { + continue; + } + + final 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.warn( + "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(final List drops) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + drops.add(part.getItemStack(PartItemStack.Break)); + part.getDrops(drops, false); + } + + if (s != ForgeDirection.UNKNOWN) { + final IFacadePart fp = this.getFacadeContainer().getFacade(s); + if (fp != null) { + drops.add(fp.getItemStack()); + } + } + } + + return drops; + } + + public List getNoDrops(final List drops) { + for (final ForgeDirection s : ForgeDirection.values()) { + final IPart part = this.getPart(s); + if (part != null) { + part.getDrops(drops, false); + } + } + + return drops; + } + + @Override + public boolean recolourBlock( + final ForgeDirection side, final AEColor colour, final EntityPlayer who + ) { + final IPart cable = this.getPart(ForgeDirection.UNKNOWN); + if (cable != null) { + final IPartCable pc = (IPartCable) cable; + return pc.changeColor(colour, who); + } + return false; + } + + public boolean isRequiresDynamicRender() { + return this.requiresDynamicRender; + } + + private void setRequiresDynamicRender(final boolean requiresDynamicRender) { + this.requiresDynamicRender = requiresDynamicRender; + } } diff --git a/src/main/java/appeng/parts/CableBusStorage.java b/src/main/java/appeng/parts/CableBusStorage.java index cbed6da0..3822acce 100644 --- a/src/main/java/appeng/parts/CableBusStorage.java +++ b/src/main/java/appeng/parts/CableBusStorage.java @@ -18,129 +18,105 @@ package appeng.parts; +import javax.annotation.Nullable; import appeng.api.implementations.parts.IPartCable; import appeng.api.parts.IFacadePart; import appeng.api.parts.IPart; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; - - /** * Thin data storage to optimize memory usage for cables. */ -public class CableBusStorage -{ +public class CableBusStorage { + private IPartCable center; + private IPart[] sides; + private IFacadePart[] facades; - private IPartCable center; - private IPart[] sides; - private IFacadePart[] facades; + protected IPartCable getCenter() { + return this.center; + } - protected IPartCable getCenter() - { - return this.center; - } + protected void setCenter(final IPartCable center) { + this.center = center; + } - protected void setCenter( final IPartCable center ) - { - this.center = center; - } + protected IPart getSide(final ForgeDirection side) { + final int x = side.ordinal(); + if (this.sides != null && this.sides.length > x) { + return this.sides[x]; + } - protected IPart getSide( final ForgeDirection side ) - { - final int x = side.ordinal(); - if( this.sides != null && this.sides.length > x ) - { - return this.sides[x]; - } + return null; + } - return null; - } + protected void setSide(final ForgeDirection side, final IPart part) { + final int x = side.ordinal(); - protected void setSide( final ForgeDirection side, final IPart part ) - { - final int x = side.ordinal(); + 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) { + this.sides = this.grow(this.sides, x, true); + this.sides[x] = part; + } + } - 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 ) - { - this.sides = this.grow( this.sides, x, true ); - this.sides[x] = part; - } - } + private T[] shrink(final T[] in, final boolean parts) { + int newSize = -1; + for (int x = 0; x < in.length; x++) { + if (in[x] != null) { + newSize = x; + } + } - private T[] shrink( final T[] in, final boolean parts ) - { - int newSize = -1; - for( int x = 0; x < in.length; x++ ) - { - if( in[x] != null ) - { - newSize = x; - } - } + if (newSize == -1) { + return null; + } - if( newSize == -1 ) - { - return null; - } + newSize++; + if (newSize == in.length) { + return in; + } - newSize++; - if( newSize == in.length ) - { - return in; - } + final T[] newArray + = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); + System.arraycopy(in, 0, newArray, 0, newSize); - final T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); - System.arraycopy( in, 0, newArray, 0, newSize ); + return newArray; + } - return newArray; - } + private T[] grow(final T[] in, final int newValue, final boolean parts) { + if (in != null && in.length > newValue) { + return in; + } - private T[] grow( final T[] in, final int newValue, final boolean parts ) - { - if( in != null && in.length > newValue ) - { - return in; - } + final int newSize = newValue + 1; - final int newSize = newValue + 1; + final T[] newArray + = (T[]) (parts ? new IPart[newSize] : new IFacadePart[newSize]); + if (in != null) { + System.arraycopy(in, 0, newArray, 0, in.length); + } - final T[] newArray = (T[]) ( parts ? new IPart[newSize] : new IFacadePart[newSize] ); - if( in != null ) - { - System.arraycopy( in, 0, newArray, 0, in.length ); - } + return newArray; + } - return newArray; - } + public IFacadePart getFacade(final int x) { + if (this.facades != null && this.facades.length > x) { + return this.facades[x]; + } - public IFacadePart getFacade( final int x ) - { - if( this.facades != null && this.facades.length > x ) - { - return this.facades[x]; - } + return null; + } - return null; - } - - public void setFacade( final int x, @Nullable final IFacadePart facade ) - { - if( this.facades != null && this.facades.length > x && facade == null ) - { - this.facades[x] = null; - this.facades = this.shrink( this.facades, false ); - } - else - { - this.facades = this.grow( this.facades, x, false ); - this.facades[x] = facade; - } - } + public void setFacade(final int x, @Nullable final IFacadePart facade) { + if (this.facades != null && this.facades.length > x && facade == null) { + this.facades[x] = null; + this.facades = this.shrink(this.facades, false); + } else { + this.facades = this.grow(this.facades, x, false); + this.facades[x] = facade; + } + } } diff --git a/src/main/java/appeng/parts/ICableBusContainer.java b/src/main/java/appeng/parts/ICableBusContainer.java index 1384afc9..9223f71b 100644 --- a/src/main/java/appeng/parts/ICableBusContainer.java +++ b/src/main/java/appeng/parts/ICableBusContainer.java @@ -18,6 +18,8 @@ package appeng.parts; +import java.util.EnumSet; +import java.util.Random; import appeng.api.parts.SelectedPart; import appeng.api.util.AEColor; @@ -30,37 +32,31 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; +public interface ICableBusContainer { + int isProvidingStrongPower(ForgeDirection opposite); + int isProvidingWeakPower(ForgeDirection opposite); -public interface ICableBusContainer -{ + boolean canConnectRedstone(EnumSet of); - int isProvidingStrongPower( ForgeDirection opposite ); + void onEntityCollision(Entity e); - int isProvidingWeakPower( ForgeDirection opposite ); + boolean activate(EntityPlayer player, Vec3 vecFromPool); - boolean canConnectRedstone( EnumSet of ); + void onNeighborChanged(); - void onEntityCollision( Entity e ); + boolean isSolidOnSide(ForgeDirection side); - boolean activate( EntityPlayer player, Vec3 vecFromPool ); + boolean isEmpty(); - void onNeighborChanged(); + SelectedPart selectPart(Vec3 v3); - boolean isSolidOnSide( ForgeDirection side ); + boolean recolourBlock(ForgeDirection side, AEColor colour, EntityPlayer who); - boolean isEmpty(); + boolean isLadder(EntityLivingBase entity); - SelectedPart selectPart( Vec3 v3 ); + @SideOnly(Side.CLIENT) + void randomDisplayTick(World world, int x, int y, int z, Random r); - boolean recolourBlock( ForgeDirection side, AEColor colour, EntityPlayer who ); - - boolean isLadder( EntityLivingBase entity ); - - @SideOnly( Side.CLIENT ) - void randomDisplayTick( World world, int x, int y, int z, Random r ); - - int getLightValue(); + int getLightValue(); } diff --git a/src/main/java/appeng/parts/NullCableBusContainer.java b/src/main/java/appeng/parts/NullCableBusContainer.java index 42a02a5f..5150f5ff 100644 --- a/src/main/java/appeng/parts/NullCableBusContainer.java +++ b/src/main/java/appeng/parts/NullCableBusContainer.java @@ -18,6 +18,8 @@ package appeng.parts; +import java.util.EnumSet; +import java.util.Random; import appeng.api.parts.SelectedPart; import appeng.api.util.AEColor; @@ -28,88 +30,67 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Random; +public class NullCableBusContainer implements ICableBusContainer { + @Override + public int isProvidingStrongPower(final ForgeDirection opposite) { + return 0; + } + @Override + public int isProvidingWeakPower(final ForgeDirection opposite) { + return 0; + } -public class NullCableBusContainer implements ICableBusContainer -{ + @Override + public boolean canConnectRedstone(final EnumSet of) { + return false; + } - @Override - public int isProvidingStrongPower( final ForgeDirection opposite ) - { - return 0; - } + @Override + public void onEntityCollision(final Entity e) {} - @Override - public int isProvidingWeakPower( final ForgeDirection opposite ) - { - return 0; - } + @Override + public boolean activate(final EntityPlayer player, final Vec3 vecFromPool) { + return false; + } - @Override - public boolean canConnectRedstone( final EnumSet of ) - { - return false; - } + @Override + public void onNeighborChanged() {} - @Override - public void onEntityCollision( final Entity e ) - { + @Override + public boolean isSolidOnSide(final ForgeDirection side) { + return false; + } - } + @Override + public boolean isEmpty() { + return true; + } - @Override - public boolean activate( final EntityPlayer player, final Vec3 vecFromPool ) - { - return false; - } + @Override + public SelectedPart selectPart(final Vec3 v3) { + return new SelectedPart(); + } - @Override - public void onNeighborChanged() - { + @Override + public boolean recolourBlock( + final ForgeDirection side, final AEColor colour, final EntityPlayer who + ) { + return false; + } - } + @Override + public boolean isLadder(final EntityLivingBase entity) { + return false; + } - @Override - public boolean isSolidOnSide( final ForgeDirection side ) - { - return false; - } + @Override + public void randomDisplayTick( + final World world, final int x, final int y, final int z, final Random r + ) {} - @Override - public boolean isEmpty() - { - return true; - } - - @Override - public SelectedPart selectPart( final Vec3 v3 ) - { - return new SelectedPart(); - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - return false; - } - - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return false; - } - - @Override - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - - } - - @Override - public int getLightValue() - { - return 0; - } + @Override + public int getLightValue() { + return 0; + } } diff --git a/src/main/java/appeng/parts/PartBasicState.java b/src/main/java/appeng/parts/PartBasicState.java index e3f2c21e..01e81149 100644 --- a/src/main/java/appeng/parts/PartBasicState.java +++ b/src/main/java/appeng/parts/PartBasicState.java @@ -18,6 +18,7 @@ package appeng.parts; +import java.io.IOException; import appeng.api.implementations.IPowerChannelState; import appeng.api.networking.GridFlags; @@ -36,138 +37,148 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; +public abstract class PartBasicState extends AEBasePart implements IPowerChannelState { + protected static final int POWERED_FLAG = 1; + protected static final int CHANNEL_FLAG = 2; + private int clientFlags = 0; // sent as byte. -public abstract class PartBasicState extends AEBasePart implements IPowerChannelState -{ + public PartBasicState(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } - protected static final int POWERED_FLAG = 1; - protected static final int CHANNEL_FLAG = 2; + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } - private int clientFlags = 0; // sent as byte. + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - public PartBasicState( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } + @SideOnly(Side.CLIENT) + public void renderLights( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + rh.normalRendering(); + this.setColors( + (this.getClientFlags() & (POWERED_FLAG | CHANNEL_FLAG)) + == (POWERED_FLAG | CHANNEL_FLAG), + (this.getClientFlags() & POWERED_FLAG) == POWERED_FLAG + ); + rh.renderFace( + x, + y, + z, + CableBusTextures.PartMonitorSidesStatusLights.getIcon(), + ForgeDirection.EAST, + renderer + ); + rh.renderFace( + x, + y, + z, + CableBusTextures.PartMonitorSidesStatusLights.getIcon(), + ForgeDirection.WEST, + renderer + ); + rh.renderFace( + x, + y, + z, + CableBusTextures.PartMonitorSidesStatusLights.getIcon(), + ForgeDirection.UP, + renderer + ); + rh.renderFace( + x, + y, + z, + CableBusTextures.PartMonitorSidesStatusLights.getIcon(), + ForgeDirection.DOWN, + renderer + ); + } - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } + public void setColors(final boolean hasChan, final boolean hasPower) { + if (hasChan) { + final int l = 14; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().blackVariant); + } else if (hasPower) { + final int l = 9; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().whiteVariant); + } else { + Tessellator.instance.setBrightness(0); + Tessellator.instance.setColorOpaque_I(0x000000); + } + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); - @SideOnly( Side.CLIENT ) - public void renderLights( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.normalRendering(); - this.setColors( ( this.getClientFlags() & ( POWERED_FLAG | CHANNEL_FLAG ) ) == ( POWERED_FLAG | CHANNEL_FLAG ), ( this.getClientFlags() & POWERED_FLAG ) == POWERED_FLAG ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.EAST, renderer ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.WEST, renderer ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.UP, renderer ); - rh.renderFace( x, y, z, CableBusTextures.PartMonitorSidesStatusLights.getIcon(), ForgeDirection.DOWN, renderer ); - } + this.setClientFlags(0); - public void setColors( final boolean hasChan, final boolean hasPower ) - { - if( hasChan ) - { - final int l = 14; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); - } - else if( hasPower ) - { - final int l = 9; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().whiteVariant ); - } - else - { - Tessellator.instance.setBrightness( 0 ); - Tessellator.instance.setColorOpaque_I( 0x000000 ); - } - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.setClientFlags(this.getClientFlags() | POWERED_FLAG); + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.setClientFlags(this.getClientFlags() | CHANNEL_FLAG); + } - this.setClientFlags( 0 ); + this.setClientFlags(this.populateFlags(this.getClientFlags())); + } catch (final GridAccessException e) { + // meh + } - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.setClientFlags( this.getClientFlags() | POWERED_FLAG ); - } + data.writeByte((byte) this.getClientFlags()); + } - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.setClientFlags( this.getClientFlags() | CHANNEL_FLAG ); - } + protected int populateFlags(final int cf) { + return cf; + } - this.setClientFlags( this.populateFlags( this.getClientFlags() ) ); - } - catch( final GridAccessException e ) - { - // meh - } + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + final boolean eh = super.readFromStream(data); - data.writeByte( (byte) this.getClientFlags() ); - } + final int old = this.getClientFlags(); + this.setClientFlags(data.readByte()); - protected int populateFlags( final int cf ) - { - return cf; - } + return eh || old != this.getClientFlags(); + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - final boolean eh = super.readFromStream( data ); + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return CableBusTextures.PartTransitionPlaneBack.getIcon(); + } - final int old = this.getClientFlags(); - this.setClientFlags( data.readByte() ); + @Override + public boolean isPowered() { + return (this.getClientFlags() & POWERED_FLAG) == POWERED_FLAG; + } - return eh || old != this.getClientFlags(); - } + @Override + public boolean isActive() { + return (this.getClientFlags() & CHANNEL_FLAG) == CHANNEL_FLAG; + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return CableBusTextures.PartTransitionPlaneBack.getIcon(); - } + public int getClientFlags() { + return this.clientFlags; + } - @Override - public boolean isPowered() - { - return ( this.getClientFlags() & POWERED_FLAG ) == POWERED_FLAG; - } - - @Override - public boolean isActive() - { - return ( this.getClientFlags() & CHANNEL_FLAG ) == CHANNEL_FLAG; - } - - public int getClientFlags() - { - return this.clientFlags; - } - - private void setClientFlags( final int clientFlags ) - { - this.clientFlags = clientFlags; - } + private void setClientFlags(final int clientFlags) { + this.clientFlags = clientFlags; + } } diff --git a/src/main/java/appeng/parts/PartPlacement.java b/src/main/java/appeng/parts/PartPlacement.java index d7fc2f9c..4b6302aa 100644 --- a/src/main/java/appeng/parts/PartPlacement.java +++ b/src/main/java/appeng/parts/PartPlacement.java @@ -18,6 +18,8 @@ package appeng.parts; +import java.util.LinkedList; +import java.util.List; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -57,462 +59,493 @@ import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent.Action; import net.minecraftforge.event.world.BlockEvent; -import java.util.LinkedList; -import java.util.List; - - -public class PartPlacement -{ - - private static float eyeHeight = 0.0f; - private final ThreadLocal placing = new ThreadLocal(); - private boolean wasCanceled = false; - - public static boolean place( final ItemStack held, final int x, final int y, final int z, final int face, final EntityPlayer player, final World world, PlaceType pass, final int depth ) - { - if( depth > 3 ) - { - return false; - } - - ForgeDirection side = ForgeDirection.getOrientation( face ); - - if( held != null && Platform.isWrench( player, held, x, y, z ) && player.isSneaking() ) - { - if( !Platform.hasPermissions( new DimensionalCoord( world, x, y, z ), player ) ) - { - return false; - } - - final Block block = world.getBlock( x, y, z ); - final TileEntity tile = world.getTileEntity( x, y, z ); - IPartHost host = null; - - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - if( host != null ) - { - if( !world.isRemote ) - { - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.getA(), dir.getB() ); - if( mop != null ) - { - final List is = new LinkedList(); - final SelectedPart sp = selectPart( player, host, mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ) ); - - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, world, block, world.getBlockMetadata( x, y, z ), player ); - MinecraftForge.EVENT_BUS.post( event ); - if( event.isCanceled() ) - { - return false; - } - - 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 ) - { - is.add( sp.facade.getItemStack() ); - host.getFacadeContainer().removeFacade( host, sp.side ); - Platform.notifyBlocksOfNeighbors( world, x, y, z ); - } - - if( host.isEmpty() ) - { - host.cleanup(); - } - - if( !is.isEmpty() ) - { - Platform.spawnDrops( world, x, y, z, is ); - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - } - return true; - } - - return false; - } - - TileEntity tile = world.getTileEntity( x, y, z ); - IPartHost host = null; - - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - if( held != null ) - { - final IFacadePart fp = isFacade( held, side ); - if( fp != null ) - { - if( host != null ) - { - if( !world.isRemote ) - { - if( host.getPart( ForgeDirection.UNKNOWN ) == null ) - { - return false; - } - - if( host.canAddPart( held, side ) ) - { - if( host.getFacadeContainer().addFacade( fp ) ) - { - host.markForSave(); - host.markForUpdate(); - if( !player.capabilities.isCreativeMode ) - { - held.stackSize--; - if( held.stackSize == 0 ) - { - player.inventory.mainInventory[player.inventory.currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); - } - } - return true; - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - return true; - } - } - return false; - } - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - host = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getOrCreateHost( tile ); - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.ImmibisMicroblocks ) ) - { - host = ( (IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.ImmibisMicroblocks ) ).getOrCreateHost( player, face, tile ); - } - - // if ( held == null ) - { - final Block block = world.getBlock( x, y, z ); - if( host != null && player.isSneaking() && block != null ) - { - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.getA(), dir.getB() ); - if( mop != null ) - { - mop.hitVec = mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ); - final SelectedPart sPart = selectPart( player, host, mop.hitVec ); - if( sPart != null && sPart.part != null ) - { - if( sPart.part.onShiftActivate( player, mop.hitVec ) ) - { - if( world.isRemote ) - { - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - } - return true; - } - } - } - } - } - - if( held == null || !( held.getItem() instanceof IPartItem ) ) - { - return false; - } - - int te_x = x; - int te_y = y; - int te_z = z; - - final IBlockDefinition multiPart = AEApi.instance().definitions().blocks().multiPart(); - if( host == null && pass == PlaceType.PLACE_ITEM ) - { - ForgeDirection offset = ForgeDirection.UNKNOWN; - - final Block blkID = world.getBlock( x, y, z ); - if( blkID != null && !blkID.isReplaceable( world, x, y, z ) ) - { - offset = side; - if( Platform.isServer() ) - { - side = side.getOpposite(); - } - } - - te_x = x + offset.offsetX; - te_y = y + offset.offsetY; - te_z = z + offset.offsetZ; - - tile = world.getTileEntity( te_x, te_y, te_z ); - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - host = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getOrCreateHost( tile ); - } - - if( host == null && tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.ImmibisMicroblocks ) ) - { - host = ( (IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.ImmibisMicroblocks ) ).getOrCreateHost( player, face, tile ); - } - - final Optional maybeMultiPartStack = multiPart.maybeStack( 1 ); - final Optional maybeMultiPartBlock = multiPart.maybeBlock(); - final Optional maybeMultiPartItemBlock = multiPart.maybeItemBlock(); - - final boolean hostIsNotPresent = host == null; - 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( !world.isRemote ) - { - tile = world.getTileEntity( te_x, te_y, te_z ); - - if( tile instanceof IPartHost ) - { - host = (IPartHost) tile; - } - - pass = PlaceType.INTERACT_SECOND_PASS; - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - return true; - } - } - else if( host != null && !host.canAddPart( held, side ) ) - { - return false; - } - } - - if( host == null ) - { - return false; - } - - if( !host.canAddPart( held, side ) ) - { - if( pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM ) - { - te_x = x + side.offsetX; - te_y = y + side.offsetY; - te_z = z + side.offsetZ; - - final Block blkID = world.getBlock( te_x, te_y, te_z ); - tile = world.getTileEntity( te_x, te_y, te_z ); - - if( tile != null && IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FMP ) ) - { - host = ( (IFMP) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FMP ) ).getOrCreateHost( tile ); - } - - 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 ) - { - final Block block = world.getBlock( x, y, z ); - final LookDirection dir = Platform.getPlayerRay( player, getEyeOffset( player ) ); - final MovingObjectPosition mop = block.collisionRayTrace( world, x, y, z, dir.getA(), dir.getB() ); - if( mop != null ) - { - final SelectedPart sp = selectPart( player, host, mop.hitVec.addVector( -mop.blockX, -mop.blockY, -mop.blockZ ) ); - - if( sp.part != null ) - { - if( !player.isSneaking() && sp.part.onActivate( player, mop.hitVec ) ) - { - return false; - } - } - } - - final DimensionalCoord dc = host.getLocation(); - if( !Platform.hasPermissions( dc, player ) ) - { - return false; - } - - BlockEvent.PlaceEvent event = new BlockEvent.PlaceEvent( BlockSnapshot.getBlockSnapshot( world, x, y, z ), world.getBlock( x, y, z ), player ); - MinecraftForge.EVENT_BUS.post( event ); - if( event.isCanceled() ) - { - return false; - } - final ForgeDirection mySide = host.addPart( held, side, player ); - if( mySide != null ) - { - for( final 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 ) - { - held.stackSize--; - if( held.stackSize == 0 ) - { - player.inventory.mainInventory[player.inventory.currentItem] = null; - MinecraftForge.EVENT_BUS.post( new PlayerDestroyItemEvent( player, held ) ); - } - } - } - } - else - { - player.swingItem(); - NetworkHandler.instance.sendToServer( new PacketPartPlacement( x, y, z, face, getEyeOffset( player ) ) ); - } - return true; - } - - private static float getEyeOffset( final EntityPlayer p ) - { - if( p.worldObj.isRemote ) - { - return Platform.getEyeOffset( p ); - } - - return getEyeHeight(); - } - - private static SelectedPart selectPart( final EntityPlayer player, final IPartHost host, final Vec3 pos ) - { - CommonHelper.proxy.updateRenderMode( player ); - final SelectedPart sp = host.selectPart( pos ); - CommonHelper.proxy.updateRenderMode( null ); - - return sp; - } - - public static IFacadePart isFacade( final ItemStack held, final ForgeDirection side ) - { - if( held.getItem() instanceof IFacadeItem ) - { - return ( (IFacadeItem) held.getItem() ).createPartFromItemStack( held, side ); - } - - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( bc.isFacade( held ) ) - { - return bc.createFacadePart( held, side ); - } - } - - return null; - } - - private static float getEyeHeight() - { - return eyeHeight; - } - - public static void setEyeHeight( final float eyeHeight ) - { - PartPlacement.eyeHeight = eyeHeight; - } - - @SubscribeEvent - public void playerInteract( final TickEvent.ClientTickEvent event ) - { - this.wasCanceled = false; - } - - @SubscribeEvent - public void playerInteract( final PlayerInteractEvent event ) - { - 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... - final MovingObjectPosition mop = Platform.rayTrace( event.entityPlayer, true, false ); - final Minecraft mc = Minecraft.getMinecraft(); - - final float f = 1.0F; - final double d0 = mc.playerController.getBlockReachDistance(); - final Vec3 vec3 = mc.renderViewEntity.getPosition( f ); - - if( mop != null && mop.hitVec.distanceTo( vec3 ) < d0 ) - { - final World w = event.entity.worldObj; - final TileEntity te = w.getTileEntity( mop.blockX, mop.blockY, mop.blockZ ); - if( te instanceof IPartHost && this.wasCanceled ) - { - event.setCanceled( true ); - } - } - else - { - final ItemStack held = event.entityPlayer.getHeldItem(); - final IItems items = AEApi.instance().definitions().items(); - - boolean supportedItem = items.memoryCard().isSameAs( held ); - supportedItem |= items.colorApplicator().isSameAs( held ); - - 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 ) - { - if( this.placing.get() != null ) - { - return; - } - - this.placing.set( event ); - - final 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 ) ) - { - event.setCanceled( true ); - this.wasCanceled = true; - } - - this.placing.set( null ); - } - } - - public enum PlaceType - { - PLACE_ITEM, INTERACT_FIRST_PASS, INTERACT_SECOND_PASS - } +public class PartPlacement { + private static float eyeHeight = 0.0f; + private final ThreadLocal placing = new ThreadLocal(); + private boolean wasCanceled = false; + + public static boolean place( + final ItemStack held, + final int x, + final int y, + final int z, + final int face, + final EntityPlayer player, + final World world, + PlaceType pass, + final int depth + ) { + if (depth > 3) { + return false; + } + + ForgeDirection side = ForgeDirection.getOrientation(face); + + if (held != null && Platform.isWrench(player, held, x, y, z) + && player.isSneaking()) { + if (!Platform.hasPermissions(new DimensionalCoord(world, x, y, z), player)) { + return false; + } + + final Block block = world.getBlock(x, y, z); + final TileEntity tile = world.getTileEntity(x, y, z); + IPartHost host = null; + + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + if (host != null) { + if (!world.isRemote) { + final LookDirection dir + = Platform.getPlayerRay(player, getEyeOffset(player)); + final MovingObjectPosition mop + = block.collisionRayTrace(world, x, y, z, dir.getA(), dir.getB()); + if (mop != null) { + final List is = new LinkedList(); + final SelectedPart sp = selectPart( + player, + host, + mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ) + ); + + BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( + x, y, z, world, block, world.getBlockMetadata(x, y, z), player + ); + MinecraftForge.EVENT_BUS.post(event); + if (event.isCanceled()) { + return false; + } + + 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) { + is.add(sp.facade.getItemStack()); + host.getFacadeContainer().removeFacade(host, sp.side); + Platform.notifyBlocksOfNeighbors(world, x, y, z); + } + + if (host.isEmpty()) { + host.cleanup(); + } + + if (!is.isEmpty()) { + Platform.spawnDrops(world, x, y, z, is); + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer( + new PacketPartPlacement(x, y, z, face, getEyeOffset(player)) + ); + } + return true; + } + + return false; + } + + TileEntity tile = world.getTileEntity(x, y, z); + IPartHost host = null; + + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + if (held != null) { + final IFacadePart fp = isFacade(held, side); + if (fp != null) { + if (host != null) { + if (!world.isRemote) { + if (host.getPart(ForgeDirection.UNKNOWN) == null) { + return false; + } + + if (host.canAddPart(held, side)) { + if (host.getFacadeContainer().addFacade(fp)) { + host.markForSave(); + host.markForUpdate(); + if (!player.capabilities.isCreativeMode) { + held.stackSize--; + if (held.stackSize == 0) { + player.inventory + .mainInventory[player.inventory.currentItem] + = null; + MinecraftForge.EVENT_BUS.post( + new PlayerDestroyItemEvent(player, held) + ); + } + } + return true; + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer( + new PacketPartPlacement(x, y, z, face, getEyeOffset(player)) + ); + return true; + } + } + return false; + } + } + + if (host == null && tile != null + && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + host = ((IFMP) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)) + .getOrCreateHost(tile); + } + + if (host == null && tile != null + && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.ImmibisMicroblocks + )) { + host = ((IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( + IntegrationType.ImmibisMicroblocks + )) + .getOrCreateHost(player, face, tile); + } + + // if ( held == null ) + { + final Block block = world.getBlock(x, y, z); + if (host != null && player.isSneaking() && block != null) { + final LookDirection dir + = Platform.getPlayerRay(player, getEyeOffset(player)); + final MovingObjectPosition mop + = block.collisionRayTrace(world, x, y, z, dir.getA(), dir.getB()); + if (mop != null) { + mop.hitVec + = mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ); + final SelectedPart sPart = selectPart(player, host, mop.hitVec); + if (sPart != null && sPart.part != null) { + if (sPart.part.onShiftActivate(player, mop.hitVec)) { + if (world.isRemote) { + NetworkHandler.instance.sendToServer( + new PacketPartPlacement( + x, y, z, face, getEyeOffset(player) + ) + ); + } + return true; + } + } + } + } + } + + if (held == null || !(held.getItem() instanceof IPartItem)) { + return false; + } + + int te_x = x; + int te_y = y; + int te_z = z; + + final IBlockDefinition multiPart + = AEApi.instance().definitions().blocks().multiPart(); + if (host == null && pass == PlaceType.PLACE_ITEM) { + ForgeDirection offset = ForgeDirection.UNKNOWN; + + final Block blkID = world.getBlock(x, y, z); + if (blkID != null && !blkID.isReplaceable(world, x, y, z)) { + offset = side; + if (Platform.isServer()) { + side = side.getOpposite(); + } + } + + te_x = x + offset.offsetX; + te_y = y + offset.offsetY; + te_z = z + offset.offsetZ; + + tile = world.getTileEntity(te_x, te_y, te_z); + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + if (host == null && tile != null + && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + host = ((IFMP + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP)) + .getOrCreateHost(tile); + } + + if (host == null && tile != null + && IntegrationRegistry.INSTANCE.isEnabled( + IntegrationType.ImmibisMicroblocks + )) { + host = ((IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( + IntegrationType.ImmibisMicroblocks + )) + .getOrCreateHost(player, face, tile); + } + + final Optional maybeMultiPartStack = multiPart.maybeStack(1); + final Optional maybeMultiPartBlock = multiPart.maybeBlock(); + final Optional maybeMultiPartItemBlock + = multiPart.maybeItemBlock(); + + final boolean hostIsNotPresent = host == null; + 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 (!world.isRemote) { + tile = world.getTileEntity(te_x, te_y, te_z); + + if (tile instanceof IPartHost) { + host = (IPartHost) tile; + } + + pass = PlaceType.INTERACT_SECOND_PASS; + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer( + new PacketPartPlacement(x, y, z, face, getEyeOffset(player)) + ); + return true; + } + } else if (host != null && !host.canAddPart(held, side)) { + return false; + } + } + + if (host == null) { + return false; + } + + if (!host.canAddPart(held, side)) { + if (pass == PlaceType.INTERACT_FIRST_PASS || pass == PlaceType.PLACE_ITEM) { + te_x = x + side.offsetX; + te_y = y + side.offsetY; + te_z = z + side.offsetZ; + + final Block blkID = world.getBlock(te_x, te_y, te_z); + tile = world.getTileEntity(te_x, te_y, te_z); + + if (tile != null + && IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FMP)) { + host = ((IFMP + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FMP + )) + .getOrCreateHost(tile); + } + + 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) { + final Block block = world.getBlock(x, y, z); + final LookDirection dir = Platform.getPlayerRay(player, getEyeOffset(player)); + final MovingObjectPosition mop + = block.collisionRayTrace(world, x, y, z, dir.getA(), dir.getB()); + if (mop != null) { + final SelectedPart sp = selectPart( + player, + host, + mop.hitVec.addVector(-mop.blockX, -mop.blockY, -mop.blockZ) + ); + + if (sp.part != null) { + if (!player.isSneaking() && sp.part.onActivate(player, mop.hitVec)) { + return false; + } + } + } + + final DimensionalCoord dc = host.getLocation(); + if (!Platform.hasPermissions(dc, player)) { + return false; + } + + BlockEvent.PlaceEvent event = new BlockEvent.PlaceEvent( + BlockSnapshot.getBlockSnapshot(world, x, y, z), + world.getBlock(x, y, z), + player + ); + MinecraftForge.EVENT_BUS.post(event); + if (event.isCanceled()) { + return false; + } + final ForgeDirection mySide = host.addPart(held, side, player); + if (mySide != null) { + for (final 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) { + held.stackSize--; + if (held.stackSize == 0) { + player.inventory.mainInventory[player.inventory.currentItem] + = null; + MinecraftForge.EVENT_BUS.post( + new PlayerDestroyItemEvent(player, held) + ); + } + } + } + } else { + player.swingItem(); + NetworkHandler.instance.sendToServer( + new PacketPartPlacement(x, y, z, face, getEyeOffset(player)) + ); + } + return true; + } + + private static float getEyeOffset(final EntityPlayer p) { + if (p.worldObj.isRemote) { + return Platform.getEyeOffset(p); + } + + return getEyeHeight(); + } + + private static SelectedPart + selectPart(final EntityPlayer player, final IPartHost host, final Vec3 pos) { + CommonHelper.proxy.updateRenderMode(player); + final SelectedPart sp = host.selectPart(pos); + CommonHelper.proxy.updateRenderMode(null); + + return sp; + } + + public static IFacadePart isFacade(final ItemStack held, final ForgeDirection side) { + if (held.getItem() instanceof IFacadeItem) { + return ((IFacadeItem) held.getItem()).createPartFromItemStack(held, side); + } + + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + final IBuildCraftTransport bc = (IBuildCraftTransport + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport + ); + if (bc.isFacade(held)) { + return bc.createFacadePart(held, side); + } + } + + return null; + } + + private static float getEyeHeight() { + return eyeHeight; + } + + public static void setEyeHeight(final float eyeHeight) { + PartPlacement.eyeHeight = eyeHeight; + } + + @SubscribeEvent + public void playerInteract(final TickEvent.ClientTickEvent event) { + this.wasCanceled = false; + } + + @SubscribeEvent + public void playerInteract(final PlayerInteractEvent event) { + 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... + final MovingObjectPosition mop + = Platform.rayTrace(event.entityPlayer, true, false); + final Minecraft mc = Minecraft.getMinecraft(); + + final float f = 1.0F; + final double d0 = mc.playerController.getBlockReachDistance(); + final Vec3 vec3 = mc.renderViewEntity.getPosition(f); + + if (mop != null && mop.hitVec.distanceTo(vec3) < d0) { + final World w = event.entity.worldObj; + final TileEntity te = w.getTileEntity(mop.blockX, mop.blockY, mop.blockZ); + if (te instanceof IPartHost && this.wasCanceled) { + event.setCanceled(true); + } + } else { + final ItemStack held = event.entityPlayer.getHeldItem(); + final IItems items = AEApi.instance().definitions().items(); + + boolean supportedItem = items.memoryCard().isSameAs(held); + supportedItem |= items.colorApplicator().isSameAs(held); + + 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) { + if (this.placing.get() != null) { + return; + } + + this.placing.set(event); + + final 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 + )) { + event.setCanceled(true); + this.wasCanceled = true; + } + + this.placing.set(null); + } + } + + public enum PlaceType { PLACE_ITEM, INTERACT_FIRST_PASS, INTERACT_SECOND_PASS } } \ No newline at end of file diff --git a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java index 6504026e..4c755cee 100644 --- a/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/BlockUpgradeInventory.java @@ -1,6 +1,5 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.tile.inventory.IAEAppEngInventory; import net.minecraft.block.Block; @@ -8,33 +7,30 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; +public class BlockUpgradeInventory extends UpgradeInventory { + private final Block block; -public class BlockUpgradeInventory extends UpgradeInventory -{ - private final Block block; + public BlockUpgradeInventory( + final Block block, final IAEAppEngInventory parent, final int s + ) { + super(parent, s); + this.block = block; + } - public BlockUpgradeInventory( final Block block, final IAEAppEngInventory parent, final int s ) - { - super( parent, s ); - this.block = block; - } + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + for (final ItemStack is : upgrades.getSupported().keySet()) { + final Item encodedItem = is.getItem(); - for( final ItemStack is : upgrades.getSupported().keySet() ) - { - final Item encodedItem = is.getItem(); + if (encodedItem instanceof ItemBlock + && Block.getBlockFromItem(encodedItem) == this.block) { + max = upgrades.getSupported().get(is); + break; + } + } - if( encodedItem instanceof ItemBlock && Block.getBlockFromItem( encodedItem ) == this.block ) - { - max = upgrades.getSupported().get( is ); - break; - } - } - - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java index ba5436d2..b556e555 100644 --- a/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/DefinitionUpgradeInventory.java @@ -1,37 +1,32 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.api.definitions.IItemDefinition; import appeng.tile.inventory.IAEAppEngInventory; import net.minecraft.item.ItemStack; +public final class DefinitionUpgradeInventory extends UpgradeInventory { + private final IItemDefinition definition; -public final class DefinitionUpgradeInventory extends UpgradeInventory -{ - private final IItemDefinition definition; + public DefinitionUpgradeInventory( + final IItemDefinition definition, final IAEAppEngInventory parent, final int s + ) { + super(parent, s); - public DefinitionUpgradeInventory( final IItemDefinition definition, final IAEAppEngInventory parent, final int s ) - { - super( parent, s ); + this.definition = definition; + } - this.definition = definition; - } + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + for (final ItemStack stack : upgrades.getSupported().keySet()) { + if (this.definition.isSameAs(stack)) { + max = upgrades.getSupported().get(stack); + break; + } + } - for( final ItemStack stack : upgrades.getSupported().keySet() ) - { - if( this.definition.isSameAs( stack ) ) - { - max = upgrades.getSupported().get( stack ); - break; - } - } - - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java index 380571c4..00d47ff1 100644 --- a/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java +++ b/src/main/java/appeng/parts/automation/PartAnnihilationPlane.java @@ -18,6 +18,7 @@ package appeng.parts.automation; +import java.util.List; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -69,537 +70,623 @@ import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.world.BlockEvent; -import java.util.List; - - -public class PartAnnihilationPlane extends PartBasicState implements IGridTickable, IWorldCallable -{ - private static final IIcon SIDE_ICON = CableBusTextures.PartPlaneSides.getIcon(); - private static final IIcon BACK_ICON = CableBusTextures.PartTransitionPlaneBack.getIcon(); - private static final IIcon STATUS_ICON = CableBusTextures.PartMonitorSidesStatus.getIcon(); - private static final IIcon ACTIVE_ICON = CableBusTextures.BlockAnnihilationPlaneOn.getIcon(); - private static final int MAX_CACHE_TIME = 60; - - private final BaseActionSource mySrc = new MachineSource( this ); - private EntityPlayer owner = null; - private boolean isAccepting = true; - private boolean breaking = false; - private YesNo permissionCache = YesNo.UNDECIDED; - private int cacheTime = 0; - - public PartAnnihilationPlane( final ItemStack is ) - { - super( is ); - } - - @Override - public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.owner = player; - } - - @Override - public TickRateModulation call( final World world ) throws Exception - { - this.breaking = false; - return this.breakBlock( true ); - } - - @Override - public void getBoxes( final 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.getSide() ) ) - { - minX = 0; - } - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - } - - bch.addBox( 5, 5, 14, 11, 11, 15 ); - // The smaller collision hitbox here is needed to allow for the entity collision event - bch.addBox( minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( SIDE_ICON, SIDE_ICON, BACK_ICON, this.getItemStack().getIconIndex(), SIDE_ICON, SIDE_ICON ); - - rh.setBounds( 1, 1, 15, 15, 15, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.renderStaticWithIcon( x, y, z, rh, renderer, ACTIVE_ICON ); - } - - protected void renderStaticWithIcon( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final IIcon activeIcon ) - { - int minX = 1; - - final ForgeDirection e = rh.getWorldX(); - final ForgeDirection u = rh.getWorldY(); - - final TileEntity te = this.getHost().getTile(); - - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.getSide() ) ) - { - minX = 0; - } - - int maxX = 15; - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - int minY = 1; - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - int maxY = 15; - if( this.isAnnihilationPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - - final boolean isActive = ( this.getClientFlags() & ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ) ) == ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ); - - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( SIDE_ICON, SIDE_ICON, BACK_ICON, isActive ? activeIcon : this.getItemStack().getIconIndex(), SIDE_ICON, SIDE_ICON ); - - rh.setBounds( minX, minY, 15, maxX, maxY, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( STATUS_ICON, STATUS_ICON, BACK_ICON, isActive ? activeIcon : this.getItemStack().getIconIndex(), STATUS_ICON, STATUS_ICON ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void onNeighborChanged() - { - this.isAccepting = true; - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public void onEntityCollision( final Entity entity ) - { - if( this.isAccepting && entity instanceof EntityItem && !entity.isDead && Platform.isServer() && this.getProxy().isActive() ) - { - boolean capture = false; - - // This is the middle point of the entities BB, which is better suited for comparisons that don't rely on it "touching" the plane - double posYMiddle = (entity.boundingBox.minY + entity.boundingBox.maxY) / 2.0D; - - switch( this.getSide() ) - { - case DOWN: - case UP: - if( entity.posX > this.getTile().xCoord && entity.posX < this.getTile().xCoord + 1 ) - { - if( entity.posZ > this.getTile().zCoord && entity.posZ < this.getTile().zCoord + 1 ) - { - if( ( entity.posY > this.getTile().yCoord + 0.9 && this.getSide() == ForgeDirection.UP ) || ( entity.posY < this.getTile().yCoord + 0.1 && this.getSide() == ForgeDirection.DOWN ) ) - { - capture = true; - } - } - } - break; - case SOUTH: - case NORTH: - if( entity.posX > this.getTile().xCoord && entity.posX < this.getTile().xCoord + 1 ) - { - if( posYMiddle > this.getTile().yCoord && posYMiddle < this.getTile().yCoord + 1 ) - { - if( ( entity.posZ > this.getTile().zCoord + 0.9 && this.getSide() == ForgeDirection.SOUTH ) || ( entity.posZ < this.getTile().zCoord + 0.1 && this.getSide() == ForgeDirection.NORTH ) ) - { - capture = true; - } - } - } - break; - case EAST: - case WEST: - if( entity.posZ > this.getTile().zCoord && entity.posZ < this.getTile().zCoord + 1 ) - { - if( posYMiddle > this.getTile().yCoord && posYMiddle < this.getTile().yCoord + 1 ) - { - if( ( entity.posX > this.getTile().xCoord + 0.9 && this.getSide() == ForgeDirection.EAST ) || ( entity.posX < this.getTile().xCoord + 0.1 && this.getSide() == ForgeDirection.WEST ) ) - { - capture = true; - } - } - } - break; - default: - // umm? - break; - } - - if( capture ) - { - final boolean changed = this.storeEntityItem( (EntityItem) entity ); - - if( changed ) - { - ServerHelper.proxy.sendToAllNearExcept( null, this.getTile().xCoord, this.getTile().yCoord, this.getTile().zCoord, 64, this.getTile().getWorldObj(), new PacketTransitionEffect( entity.posX, entity.posY, entity.posZ, this.getSide(), false ) ); - } - } - } - } - - @Override - public int cableConnectionRenderTo() - { - return 1; - } - - /** - * Stores an {@link EntityItem} inside the network and either marks it as dead or sets it to the leftover stackSize. - * - * @param entityItem {@link EntityItem} to store - */ - private boolean storeEntityItem( final EntityItem entityItem ) - { - if( !entityItem.isDead ) - { - final IAEItemStack overflow = this.storeItemStack( entityItem.getEntityItem() ); - - return this.handleOverflow( entityItem, overflow ); - } - - return false; - } - - /** - * Stores an {@link ItemStack} inside the network. - * - * @param item {@link ItemStack} to store - * @return the leftover items, which could not be stored inside the network - */ - private IAEItemStack storeItemStack( final ItemStack item ) - { - final IAEItemStack itemToStore = AEItemStack.create( item ); - try - { - final IStorageGrid storage = this.getProxy().getStorage(); - final IEnergyGrid energy = this.getProxy().getEnergy(); - final IAEItemStack overflow = Platform.poweredInsert( energy, storage.getItemInventory(), itemToStore, this.mySrc ); - - this.isAccepting = overflow == null; - - return overflow; - } - catch( final GridAccessException e1 ) - { - // :P - } - - return null; - } - - /** - * Handles a possible overflow or none at all. - * It will update the entity to match the leftover stack size as well as mark it as dead without any leftover - * amount. - * - * @param entityItem the entity to update or destroy - * @param overflow the leftover {@link IAEItemStack} - * @return true, if the entity was changed otherwise false. - */ - private boolean handleOverflow( final EntityItem entityItem, final IAEItemStack overflow ) - { - if( overflow == null || overflow.getStackSize() == 0 ) - { - entityItem.setDead(); - return true; - } - - final int oldStackSize = entityItem.getEntityItem().stackSize; - final int newStackSize = (int) overflow.getStackSize(); - final boolean changed = oldStackSize != newStackSize; - - entityItem.getEntityItem().stackSize = newStackSize; - - return changed; - } - - /** - * Spawns an overflow item as new {@link EntityItem} into the {@link World} - * - * @param overflow the item to spawn - */ - private void spawnOverflow( final IAEItemStack overflow ) - { - if( overflow == null ) - { - return; - } - - final TileEntity te = this.getTile(); - final WorldServer w = (WorldServer) te.getWorldObj(); - final double x = te.xCoord + this.getSide().offsetX + .5d; - final double y = te.yCoord + this.getSide().offsetY + .5d; - final double z = te.zCoord + this.getSide().offsetZ + .5d; - - final EntityItem overflowEntity = new EntityItem( w, x, y, z, overflow.getItemStack() ); - overflowEntity.motionX = 0; - overflowEntity.motionY = 0; - overflowEntity.motionZ = 0; - - w.spawnEntityInWorld( overflowEntity ); - } - - protected boolean isAnnihilationPlane( final TileEntity blockTileEntity, final ForgeDirection side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && p.getClass() == this.getClass(); - } - return false; - } - - @Override - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.onNeighborChanged(); - this.getHost().markForUpdate(); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.onNeighborChanged(); - this.getHost().markForUpdate(); - } - - private TickRateModulation breakBlock( final boolean modulate ) - { - if( this.isAccepting && this.getProxy().isActive() ) - { - try - { - final TileEntity te = this.getTile(); - final WorldServer w = (WorldServer) te.getWorldObj(); - - final int x = te.xCoord + this.getSide().offsetX; - final int y = te.yCoord + this.getSide().offsetY; - final int z = te.zCoord + this.getSide().offsetZ; - - final IEnergyGrid energy = this.getProxy().getEnergy(); - - if( this.canHandleBlock( w, x, y, z ) ) - { - final List items = this.obtainBlockDrops( w, x, y, z ); - final float requiredPower = this.calculateEnergyUsage( w, x, y, z, items ); - - final boolean hasPower = energy.extractAEPower( requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > requiredPower - 0.1; - final boolean canStore = this.canStoreItemStacks( items ); - - if( hasPower && canStore ) - { - if( modulate ) - { - energy.extractAEPower( requiredPower, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.breakBlockAndStoreItems( w, x, y, z, items ); - ServerHelper.proxy.sendToAllNearExcept( null, x, y, z, 64, w, new PacketTransitionEffect( x, y, z, this.getSide(), true ) ); - } - else - { - this.breaking = true; - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this ); - } - return TickRateModulation.URGENT; - } - } - } - catch( final GridAccessException e1 ) - { - // :P - } - } - - // nothing to do here :) - return TickRateModulation.IDLE; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.AnnihilationPlane.getMin(), TickRates.AnnihilationPlane.getMax(), false, true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.breaking ) - { - return TickRateModulation.URGENT; - } - - if( ticksSinceLastCall == 120 || cacheTime >= MAX_CACHE_TIME ) - { - cacheTime = 0; - permissionCache = YesNo.UNDECIDED; - } - cacheTime += ticksSinceLastCall - 120; - this.isAccepting = true; - return this.breakBlock( false ); - } - - /** - * Checks if this plane can handle the block at the specific coordinates. - */ - private boolean canHandleBlock( final WorldServer w, final int x, final int y, final int z ) - { - final Block block = w.getBlock( x, y, z ); - final Material material = block.getMaterial(); - final float hardness = block.getBlockHardness( w, x, y, z ); - final boolean ignoreMaterials = material == Material.air || material == Material.lava || material == Material.water || material.isLiquid(); - final boolean ignoreBlocks = block == Blocks.bedrock || block == Blocks.end_portal || block == Blocks.end_portal_frame || block == Blocks.command_block; - final EntityPlayer player = owner == null ? Platform.getPlayer( w ) : owner; - if( permissionCache == YesNo.UNDECIDED ) - { - BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( x, y, z, w, block, w.getBlockMetadata( x, y, z ), player ); - MinecraftForge.EVENT_BUS.post( event ); - permissionCache = ( event.isCanceled() ) ? YesNo.NO : YesNo.YES; - } - return permissionCache == YesNo.YES && !ignoreMaterials && !ignoreBlocks && !w.isAirBlock( x, y, z ) && w.blockExists( x, y, z ) && w.canMineBlock( player , x, y, z ) && hardness >= 0f; - } - - protected List obtainBlockDrops( final WorldServer w, final int x, final int y, final int z ) - { - final ItemStack[] out = Platform.getBlockDrops( w, x, y, z ); - return Lists.newArrayList( out ); - } - - /** - * Checks if this plane can handle the block at the specific coordinates. - */ - protected float calculateEnergyUsage( final WorldServer w, final int x, final int y, final int z, final List items ) - { - final Block block = w.getBlock( x, y, z ); - final float hardness = block.getBlockHardness( w, x, y, z ); - - float requiredEnergy = 1 + hardness; - for( final ItemStack is : items ) - { - requiredEnergy += is.stackSize; - } - - return requiredEnergy; - } - - /** - * Checks if the network can store the possible drops. - *

- * It also sets isAccepting to false, if the item can not be stored. - * - * @param itemStacks an array of {@link ItemStack} to test - * @return true, if the network can store at least a single item of all drops or no drops are reported - */ - private boolean canStoreItemStacks( final List itemStacks ) - { - boolean canStore = itemStacks.isEmpty(); - - try - { - final IStorageGrid storage = this.getProxy().getStorage(); - - 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() ) - { - canStore = true; - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - this.isAccepting = canStore; - return canStore; - } - - private void breakBlockAndStoreItems( final WorldServer w, final int x, final int y, final int z, final List items ) - { - w.setBlock( x, y, z, Platform.AIR_BLOCK, 0, 3 ); - - 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 ) ) - { - if( ei instanceof EntityItem ) - { - final EntityItem entityItem = (EntityItem) ei; - this.storeEntityItem( entityItem ); - } - } - - for( final ItemStack snaggedItem : items ) - { - final IAEItemStack overflow = this.storeItemStack( snaggedItem ); - this.spawnOverflow( overflow ); - } - } +public class PartAnnihilationPlane + extends PartBasicState implements IGridTickable, IWorldCallable { + private static final IIcon SIDE_ICON = CableBusTextures.PartPlaneSides.getIcon(); + private static final IIcon BACK_ICON + = CableBusTextures.PartTransitionPlaneBack.getIcon(); + private static final IIcon STATUS_ICON + = CableBusTextures.PartMonitorSidesStatus.getIcon(); + private static final IIcon ACTIVE_ICON + = CableBusTextures.BlockAnnihilationPlaneOn.getIcon(); + private static final int MAX_CACHE_TIME = 60; + + private final BaseActionSource mySrc = new MachineSource(this); + private EntityPlayer owner = null; + private boolean isAccepting = true; + private boolean breaking = false; + private YesNo permissionCache = YesNo.UNDECIDED; + private int cacheTime = 0; + + public PartAnnihilationPlane(final ItemStack is) { + super(is); + } + + @Override + public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) { + super.onPlacement(player, held, side); + this.owner = player; + } + + @Override + public TickRateModulation call(final World world) throws Exception { + this.breaking = false; + return this.breakBlock(true); + } + + @Override + public void getBoxes(final 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.getSide() + )) { + minX = 0; + } + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity( + x + e.offsetX, y + e.offsetY, z + e.offsetZ + ), + this.getSide() + )) { + maxX = 16; + } + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity( + x - u.offsetX, y - u.offsetY, z - u.offsetZ + ), + this.getSide() + )) { + minY = 0; + } + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity( + x + u.offsetX, y + u.offsetY, z + u.offsetZ + ), + this.getSide() + )) { + maxY = 16; + } + } + + bch.addBox(5, 5, 14, 11, 11, 15); + // The smaller collision hitbox here is needed to allow for the entity collision + // event + bch.addBox(minX, minY, 15, maxX, maxY, bch.isBBCollision() ? 15 : 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + SIDE_ICON, + SIDE_ICON, + BACK_ICON, + this.getItemStack().getIconIndex(), + SIDE_ICON, + SIDE_ICON + ); + + rh.setBounds(1, 1, 15, 15, 15, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.renderStaticWithIcon(x, y, z, rh, renderer, ACTIVE_ICON); + } + + protected void renderStaticWithIcon( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final IIcon activeIcon + ) { + int minX = 1; + + final ForgeDirection e = rh.getWorldX(); + final ForgeDirection u = rh.getWorldY(); + + final TileEntity te = this.getHost().getTile(); + + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity( + x - e.offsetX, y - e.offsetY, z - e.offsetZ + ), + this.getSide() + )) { + minX = 0; + } + + int maxX = 15; + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity( + x + e.offsetX, y + e.offsetY, z + e.offsetZ + ), + this.getSide() + )) { + maxX = 16; + } + + int minY = 1; + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity( + x - u.offsetX, y - u.offsetY, z - u.offsetZ + ), + this.getSide() + )) { + minY = 0; + } + + int maxY = 15; + if (this.isAnnihilationPlane( + te.getWorldObj().getTileEntity( + x + u.offsetX, y + u.offsetY, z + u.offsetZ + ), + this.getSide() + )) { + maxY = 16; + } + + final boolean isActive + = (this.getClientFlags() + & (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG)) + == (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG); + + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture( + SIDE_ICON, + SIDE_ICON, + BACK_ICON, + isActive ? activeIcon : this.getItemStack().getIconIndex(), + SIDE_ICON, + SIDE_ICON + ); + + rh.setBounds(minX, minY, 15, maxX, maxY, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + STATUS_ICON, + STATUS_ICON, + BACK_ICON, + isActive ? activeIcon : this.getItemStack().getIconIndex(), + STATUS_ICON, + STATUS_ICON + ); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void onNeighborChanged() { + this.isAccepting = true; + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public void onEntityCollision(final Entity entity) { + if (this.isAccepting && entity instanceof EntityItem && !entity.isDead + && Platform.isServer() && this.getProxy().isActive()) { + boolean capture = false; + + // This is the middle point of the entities BB, which is better suited for + // comparisons that don't rely on it "touching" the plane + double posYMiddle + = (entity.boundingBox.minY + entity.boundingBox.maxY) / 2.0D; + + switch (this.getSide()) { + case DOWN: + case UP: + if (entity.posX > this.getTile().xCoord + && entity.posX < this.getTile().xCoord + 1) { + if (entity.posZ > this.getTile().zCoord + && entity.posZ < this.getTile().zCoord + 1) { + if ((entity.posY > this.getTile().yCoord + 0.9 + && this.getSide() == ForgeDirection.UP) + || (entity.posY < this.getTile().yCoord + 0.1 + && this.getSide() == ForgeDirection.DOWN)) { + capture = true; + } + } + } + break; + case SOUTH: + case NORTH: + if (entity.posX > this.getTile().xCoord + && entity.posX < this.getTile().xCoord + 1) { + if (posYMiddle > this.getTile().yCoord + && posYMiddle < this.getTile().yCoord + 1) { + if ((entity.posZ > this.getTile().zCoord + 0.9 + && this.getSide() == ForgeDirection.SOUTH) + || (entity.posZ < this.getTile().zCoord + 0.1 + && this.getSide() == ForgeDirection.NORTH)) { + capture = true; + } + } + } + break; + case EAST: + case WEST: + if (entity.posZ > this.getTile().zCoord + && entity.posZ < this.getTile().zCoord + 1) { + if (posYMiddle > this.getTile().yCoord + && posYMiddle < this.getTile().yCoord + 1) { + if ((entity.posX > this.getTile().xCoord + 0.9 + && this.getSide() == ForgeDirection.EAST) + || (entity.posX < this.getTile().xCoord + 0.1 + && this.getSide() == ForgeDirection.WEST)) { + capture = true; + } + } + } + break; + default: + // umm? + break; + } + + if (capture) { + final boolean changed = this.storeEntityItem((EntityItem) entity); + + if (changed) { + ServerHelper.proxy.sendToAllNearExcept( + null, + this.getTile().xCoord, + this.getTile().yCoord, + this.getTile().zCoord, + 64, + this.getTile().getWorldObj(), + new PacketTransitionEffect( + entity.posX, entity.posY, entity.posZ, this.getSide(), false + ) + ); + } + } + } + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + /** + * Stores an {@link EntityItem} inside the network and either marks it as dead or sets + * it to the leftover stackSize. + * + * @param entityItem {@link EntityItem} to store + */ + private boolean storeEntityItem(final EntityItem entityItem) { + if (!entityItem.isDead) { + final IAEItemStack overflow = this.storeItemStack(entityItem.getEntityItem()); + + return this.handleOverflow(entityItem, overflow); + } + + return false; + } + + /** + * Stores an {@link ItemStack} inside the network. + * + * @param item {@link ItemStack} to store + * @return the leftover items, which could not be stored inside the network + */ + private IAEItemStack storeItemStack(final ItemStack item) { + final IAEItemStack itemToStore = AEItemStack.create(item); + try { + final IStorageGrid storage = this.getProxy().getStorage(); + final IEnergyGrid energy = this.getProxy().getEnergy(); + final IAEItemStack overflow = Platform.poweredInsert( + energy, storage.getItemInventory(), itemToStore, this.mySrc + ); + + this.isAccepting = overflow == null; + + return overflow; + } catch (final GridAccessException e1) { + // :P + } + + return null; + } + + /** + * Handles a possible overflow or none at all. + * It will update the entity to match the leftover stack size as well as mark it as + * dead without any leftover amount. + * + * @param entityItem the entity to update or destroy + * @param overflow the leftover {@link IAEItemStack} + * @return true, if the entity was changed otherwise false. + */ + private boolean + handleOverflow(final EntityItem entityItem, final IAEItemStack overflow) { + if (overflow == null || overflow.getStackSize() == 0) { + entityItem.setDead(); + return true; + } + + final int oldStackSize = entityItem.getEntityItem().stackSize; + final int newStackSize = (int) overflow.getStackSize(); + final boolean changed = oldStackSize != newStackSize; + + entityItem.getEntityItem().stackSize = newStackSize; + + return changed; + } + + /** + * Spawns an overflow item as new {@link EntityItem} into the {@link World} + * + * @param overflow the item to spawn + */ + private void spawnOverflow(final IAEItemStack overflow) { + if (overflow == null) { + return; + } + + final TileEntity te = this.getTile(); + final WorldServer w = (WorldServer) te.getWorldObj(); + final double x = te.xCoord + this.getSide().offsetX + .5d; + final double y = te.yCoord + this.getSide().offsetY + .5d; + final double z = te.zCoord + this.getSide().offsetZ + .5d; + + final EntityItem overflowEntity + = new EntityItem(w, x, y, z, overflow.getItemStack()); + overflowEntity.motionX = 0; + overflowEntity.motionY = 0; + overflowEntity.motionZ = 0; + + w.spawnEntityInWorld(overflowEntity); + } + + protected boolean + isAnnihilationPlane(final TileEntity blockTileEntity, final ForgeDirection side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && p.getClass() == this.getClass(); + } + return false; + } + + @Override + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.onNeighborChanged(); + this.getHost().markForUpdate(); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.onNeighborChanged(); + this.getHost().markForUpdate(); + } + + private TickRateModulation breakBlock(final boolean modulate) { + if (this.isAccepting && this.getProxy().isActive()) { + try { + final TileEntity te = this.getTile(); + final WorldServer w = (WorldServer) te.getWorldObj(); + + final int x = te.xCoord + this.getSide().offsetX; + final int y = te.yCoord + this.getSide().offsetY; + final int z = te.zCoord + this.getSide().offsetZ; + + final IEnergyGrid energy = this.getProxy().getEnergy(); + + if (this.canHandleBlock(w, x, y, z)) { + final List items = this.obtainBlockDrops(w, x, y, z); + final float requiredPower + = this.calculateEnergyUsage(w, x, y, z, items); + + final boolean hasPower + = energy.extractAEPower( + requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG + ) + > requiredPower - 0.1; + final boolean canStore = this.canStoreItemStacks(items); + + if (hasPower && canStore) { + if (modulate) { + energy.extractAEPower( + requiredPower, Actionable.MODULATE, PowerMultiplier.CONFIG + ); + this.breakBlockAndStoreItems(w, x, y, z, items); + ServerHelper.proxy.sendToAllNearExcept( + null, + x, + y, + z, + 64, + w, + new PacketTransitionEffect(x, y, z, this.getSide(), true) + ); + } else { + this.breaking = true; + TickHandler.INSTANCE.addCallable( + this.getTile().getWorldObj(), this + ); + } + return TickRateModulation.URGENT; + } + } + } catch (final GridAccessException e1) { + // :P + } + } + + // nothing to do here :) + return TickRateModulation.IDLE; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.AnnihilationPlane.getMin(), + TickRates.AnnihilationPlane.getMax(), + false, + true + ); + } + + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.breaking) { + return TickRateModulation.URGENT; + } + + if (ticksSinceLastCall == 120 || cacheTime >= MAX_CACHE_TIME) { + cacheTime = 0; + permissionCache = YesNo.UNDECIDED; + } + cacheTime += ticksSinceLastCall - 120; + this.isAccepting = true; + return this.breakBlock(false); + } + + /** + * Checks if this plane can handle the block at the specific coordinates. + */ + private boolean + canHandleBlock(final WorldServer w, final int x, final int y, final int z) { + final Block block = w.getBlock(x, y, z); + final Material material = block.getMaterial(); + final float hardness = block.getBlockHardness(w, x, y, z); + final boolean ignoreMaterials = material == Material.air + || material == Material.lava || material == Material.water + || material.isLiquid(); + final boolean ignoreBlocks = block == Blocks.bedrock || block == Blocks.end_portal + || block == Blocks.end_portal_frame || block == Blocks.command_block; + final EntityPlayer player = owner == null ? Platform.getPlayer(w) : owner; + if (permissionCache == YesNo.UNDECIDED) { + BlockEvent.BreakEvent event = new BlockEvent.BreakEvent( + x, y, z, w, block, w.getBlockMetadata(x, y, z), player + ); + MinecraftForge.EVENT_BUS.post(event); + permissionCache = (event.isCanceled()) ? YesNo.NO : YesNo.YES; + } + return permissionCache == YesNo.YES && !ignoreMaterials && !ignoreBlocks + && !w.isAirBlock(x, y, z) && w.blockExists(x, y, z) + && w.canMineBlock(player, x, y, z) && hardness >= 0f; + } + + protected List + obtainBlockDrops(final WorldServer w, final int x, final int y, final int z) { + final ItemStack[] out = Platform.getBlockDrops(w, x, y, z); + return Lists.newArrayList(out); + } + + /** + * Checks if this plane can handle the block at the specific coordinates. + */ + protected float calculateEnergyUsage( + final WorldServer w, + final int x, + final int y, + final int z, + final List items + ) { + final Block block = w.getBlock(x, y, z); + final float hardness = block.getBlockHardness(w, x, y, z); + + float requiredEnergy = 1 + hardness; + for (final ItemStack is : items) { + requiredEnergy += is.stackSize; + } + + return requiredEnergy; + } + + /** + * Checks if the network can store the possible drops. + *

+ * It also sets isAccepting to false, if the item can not be stored. + * + * @param itemStacks an array of {@link ItemStack} to test + * @return true, if the network can store at least a single item of all drops or no + * drops are reported + */ + private boolean canStoreItemStacks(final List itemStacks) { + boolean canStore = itemStacks.isEmpty(); + + try { + final IStorageGrid storage = this.getProxy().getStorage(); + + 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()) { + canStore = true; + } + } + } catch (final GridAccessException e) { + // :P + } + + this.isAccepting = canStore; + return canStore; + } + + private void breakBlockAndStoreItems( + final WorldServer w, + final int x, + final int y, + final int z, + final List items + ) { + w.setBlock(x, y, z, Platform.AIR_BLOCK, 0, 3); + + 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)) { + if (ei instanceof EntityItem) { + final EntityItem entityItem = (EntityItem) ei; + this.storeEntityItem(entityItem); + } + } + + for (final ItemStack snaggedItem : items) { + final IAEItemStack overflow = this.storeItemStack(snaggedItem); + this.spawnOverflow(overflow); + } + } } diff --git a/src/main/java/appeng/parts/automation/PartExportBus.java b/src/main/java/appeng/parts/automation/PartExportBus.java index 2b916a8a..55d53607 100644 --- a/src/main/java/appeng/parts/automation/PartExportBus.java +++ b/src/main/java/appeng/parts/automation/PartExportBus.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.*; import appeng.api.networking.IGridNode; import appeng.api.networking.crafting.ICraftingGrid; @@ -54,321 +53,349 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; +public class PartExportBus extends PartSharedItemBus implements ICraftingRequester { + private final MultiCraftingTracker craftingTracker + = new MultiCraftingTracker(this, 9); + private final BaseActionSource mySrc; + private long itemToSend = 1; + private boolean didSomething = false; + private int nextSlot = 0; -public class PartExportBus extends PartSharedItemBus implements ICraftingRequester -{ - private final MultiCraftingTracker craftingTracker = new MultiCraftingTracker( this, 9 ); - private final BaseActionSource mySrc; - private long itemToSend = 1; - private boolean didSomething = false; - private int nextSlot = 0; + @Reflected + public PartExportBus(final ItemStack is) { + super(is); - @Reflected - public PartExportBus( final ItemStack is ) - { - super( is ); + this.getConfigManager().registerSetting( + Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE + ); + this.getConfigManager().registerSetting( + Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); + this.getConfigManager().registerSetting(Settings.CRAFT_ONLY, YesNo.NO); + this.getConfigManager().registerSetting( + Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT + ); + this.mySrc = new MachineSource(this); + } - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.CRAFT_ONLY, YesNo.NO ); - this.getConfigManager().registerSetting( Settings.SCHEDULING_MODE, SchedulingMode.DEFAULT ); - this.mySrc = new MachineSource( this ); - } + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.craftingTracker.readFromNBT(extra); + this.nextSlot = extra.getInteger("nextSlot"); + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.craftingTracker.readFromNBT( extra ); - this.nextSlot = extra.getInteger( "nextSlot" ); - } + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.craftingTracker.writeToNBT(extra); + extra.setInteger("nextSlot", this.nextSlot); + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.craftingTracker.writeToNBT( extra ); - extra.setInteger( "nextSlot", this.nextSlot ); - } + @Override + protected TickRateModulation doBusWork() { + if (!this.getProxy().isActive() || !this.canDoBusWork()) { + return TickRateModulation.IDLE; + } - @Override - protected TickRateModulation doBusWork() - { - if( !this.getProxy().isActive() || !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } + this.itemToSend = this.calculateItemsToSend(); + this.didSomething = false; - this.itemToSend = this.calculateItemsToSend(); - this.didSomething = false; + try { + final InventoryAdaptor destination = this.getHandler(); + final IMEMonitor inv + = this.getProxy().getStorage().getItemInventory(); + final IEnergyGrid energy = this.getProxy().getEnergy(); + final ICraftingGrid cg = this.getProxy().getCrafting(); + final FuzzyMode fzMode + = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); + final SchedulingMode schedulingMode + = (SchedulingMode) this.getConfigManager().getSetting( + Settings.SCHEDULING_MODE + ); - try - { - final InventoryAdaptor destination = this.getHandler(); - final IMEMonitor inv = this.getProxy().getStorage().getItemInventory(); - final IEnergyGrid energy = this.getProxy().getEnergy(); - final ICraftingGrid cg = this.getProxy().getCrafting(); - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - final SchedulingMode schedulingMode = (SchedulingMode) this.getConfigManager().getSetting( Settings.SCHEDULING_MODE ); + if (destination != null) { + int x = 0; - if( destination != null ) - { - int x = 0; + for (x = 0; x < this.availableSlots() && this.itemToSend > 0; x++) { + final int slotToExport = this.getStartingSlot(schedulingMode, x); - for( x = 0; x < this.availableSlots() && this.itemToSend > 0; x++ ) - { - final int slotToExport = this.getStartingSlot( schedulingMode, x ); + final IAEItemStack ais + = this.getConfig().getAEStackInSlot(slotToExport); - final IAEItemStack ais = this.getConfig().getAEStackInSlot( slotToExport ); + if (ais == null || this.itemToSend <= 0 || this.craftOnly()) { + if (this.isCraftingEnabled()) { + this.didSomething = this.craftingTracker.handleCrafting( + slotToExport, + this.itemToSend, + ais, + destination, + this.getTile().getWorldObj(), + this.getProxy().getGrid(), + cg, + this.mySrc + ) + || this.didSomething; + } + continue; + } - if( ais == null || this.itemToSend <= 0 || this.craftOnly() ) - { - if( this.isCraftingEnabled() ) - { - this.didSomething = this.craftingTracker.handleCrafting( slotToExport, this.itemToSend, ais, destination, this.getTile().getWorldObj(), this.getProxy().getGrid(), cg, this.mySrc ) || this.didSomething; - } - continue; - } + final long before = this.itemToSend; - final long before = this.itemToSend; + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + for (final IAEItemStack o : ImmutableList.copyOf( + inv.getStorageList().findFuzzy(ais, fzMode) + )) { + this.pushItemIntoTarget(destination, energy, inv, o); + if (this.itemToSend <= 0) { + break; + } + } + } else { + this.pushItemIntoTarget(destination, energy, inv, ais); + } - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - for( final IAEItemStack o : ImmutableList.copyOf( inv.getStorageList().findFuzzy( ais, fzMode ) ) ) - { - this.pushItemIntoTarget( destination, energy, inv, o ); - if( this.itemToSend <= 0 ) - { - break; - } - } - } - else - { - this.pushItemIntoTarget( destination, energy, inv, ais ); - } + if (this.itemToSend == before && this.isCraftingEnabled()) { + this.didSomething = this.craftingTracker.handleCrafting( + slotToExport, + this.itemToSend, + ais, + destination, + this.getTile().getWorldObj(), + this.getProxy().getGrid(), + cg, + this.mySrc + ) + || this.didSomething; + } + } - if( this.itemToSend == before && this.isCraftingEnabled() ) - { - this.didSomething = this.craftingTracker.handleCrafting( slotToExport, this.itemToSend, ais, destination, this.getTile().getWorldObj(), this.getProxy().getGrid(), cg, this.mySrc ) || this.didSomething; - } - } + this.updateSchedulingMode(schedulingMode, x); + } else { + return TickRateModulation.SLEEP; + } + } catch (final GridAccessException e) { + // :P + } - this.updateSchedulingMode( schedulingMode, x ); - } - else - { - return TickRateModulation.SLEEP; - } - } - catch( final GridAccessException e ) - { - // :P - } + return this.didSomething ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } - return this.didSomething ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } + @Override + public void getBoxes(final 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 void getBoxes( final 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(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon() + ); - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon() ); + rh.setBounds(4, 4, 12, 12, 12, 14); + rh.renderInventoryBox(renderer); - rh.setBounds( 4, 4, 12, 12, 12, 14 ); - rh.renderInventoryBox( renderer ); + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderInventoryBox( renderer ); + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderInventoryBox(renderer); + } - rh.setBounds( 6, 6, 15, 10, 10, 16 ); - rh.renderInventoryBox( renderer ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture( + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartExportSides.getIcon(), + CableBusTextures.PartExportSides.getIcon() + ); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartExportSides.getIcon(), CableBusTextures.PartExportSides.getIcon() ); + rh.setBounds(4, 4, 12, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 4, 4, 12, 12, 12, 14 ); - rh.renderBlock( x, y, z, renderer ); + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderBlock( x, y, z, renderer ); + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 6, 6, 15, 10, 10, 16 ); - rh.renderBlock( x, y, z, renderer ); + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon() + ); - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); + rh.setBounds(6, 6, 11, 10, 10, 12); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 6, 6, 11, 10, 10, 12 ); - rh.renderBlock( x, y, z, renderer ); + this.renderLights(x, y, z, rh, renderer); + } - this.renderLights( x, y, z, rh, renderer ); - } + @Override + public int cableConnectionRenderTo() { + return 5; + } - @Override - public int cableConnectionRenderTo() - { - return 5; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + Platform.openGUI( + player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS + ); + return true; + } - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS ); - return true; - } + return false; + } - return false; - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.ExportBus.getMin(), + TickRates.ExportBus.getMax(), + this.isSleeping(), + false + ); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ExportBus.getMin(), TickRates.ExportBus.getMax(), this.isSleeping(), false ); - } + @Override + public RedstoneMode getRSMode() { + return (RedstoneMode) this.getConfigManager().getSetting( + Settings.REDSTONE_CONTROLLED + ); + } - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doBusWork(); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doBusWork(); - } + @Override + public ImmutableSet getRequestedJobs() { + return this.craftingTracker.getRequestedJobs(); + } - @Override - public ImmutableSet getRequestedJobs() - { - return this.craftingTracker.getRequestedJobs(); - } + @Override + public IAEItemStack injectCraftedItems( + final ICraftingLink link, final IAEItemStack items, final Actionable mode + ) { + final InventoryAdaptor d = this.getHandler(); - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - final InventoryAdaptor d = this.getHandler(); + try { + if (d != null && this.getProxy().isActive()) { + final IEnergyGrid energy = this.getProxy().getEnergy(); + final double power = items.getStackSize(); - try - { - if( d != null && this.getProxy().isActive() ) - { - final IEnergyGrid energy = this.getProxy().getEnergy(); - final double power = items.getStackSize(); + if (energy.extractAEPower(power, mode, PowerMultiplier.CONFIG) + > power - 0.01) { + if (mode == Actionable.MODULATE) { + return AEItemStack.create(d.addItems(items.getItemStack())); + } + return AEItemStack.create(d.simulateAdd(items.getItemStack())); + } + } + } catch (final GridAccessException e) { + AELog.debug(e); + } - if( energy.extractAEPower( power, mode, PowerMultiplier.CONFIG ) > power - 0.01 ) - { - if( mode == Actionable.MODULATE ) - { - return AEItemStack.create( d.addItems( items.getItemStack() ) ); - } - return AEItemStack.create( d.simulateAdd( items.getItemStack() ) ); - } - } - } - catch( final GridAccessException e ) - { - AELog.debug( e ); - } + return items; + } - return items; - } + @Override + public void jobStateChange(final ICraftingLink link) { + this.craftingTracker.jobStateChange(link); + } - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.craftingTracker.jobStateChange( link ); - } + @Override + protected boolean isSleeping() { + return this.getHandler() == null || super.isSleeping(); + } - @Override - protected boolean isSleeping() - { - return this.getHandler() == null || super.isSleeping(); - } + private boolean craftOnly() { + return this.getConfigManager().getSetting(Settings.CRAFT_ONLY) == YesNo.YES; + } - private boolean craftOnly() - { - return this.getConfigManager().getSetting( Settings.CRAFT_ONLY ) == YesNo.YES; - } + private boolean isCraftingEnabled() { + return this.getInstalledUpgrades(Upgrades.CRAFTING) > 0; + } - private boolean isCraftingEnabled() - { - return this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0; - } + private void pushItemIntoTarget( + final InventoryAdaptor d, + final IEnergyGrid energy, + final IMEInventory inv, + IAEItemStack ais + ) { + final ItemStack is = ais.getItemStack(); + is.stackSize = (int) this.itemToSend; - private void pushItemIntoTarget( final InventoryAdaptor d, final IEnergyGrid energy, final IMEInventory inv, IAEItemStack ais ) - { - final ItemStack is = ais.getItemStack(); - is.stackSize = (int) this.itemToSend; + final ItemStack o = d.simulateAdd(is); + final long canFit = o == null ? this.itemToSend : this.itemToSend - o.stackSize; - final ItemStack o = d.simulateAdd( is ); - final long canFit = o == null ? this.itemToSend : this.itemToSend - o.stackSize; + if (canFit > 0) { + ais = ais.copy(); + ais.setStackSize(canFit); + final IAEItemStack itemsToAdd + = Platform.poweredExtraction(energy, inv, ais, this.mySrc); - if( canFit > 0 ) - { - ais = ais.copy(); - ais.setStackSize( canFit ); - final IAEItemStack itemsToAdd = Platform.poweredExtraction( energy, inv, ais, this.mySrc ); + if (itemsToAdd != null) { + this.itemToSend -= itemsToAdd.getStackSize(); - if( itemsToAdd != null ) - { - this.itemToSend -= itemsToAdd.getStackSize(); + final ItemStack failed = d.addItems(itemsToAdd.getItemStack()); + if (failed != null) { + ais.setStackSize(failed.stackSize); + inv.injectItems(ais, Actionable.MODULATE, this.mySrc); + } else { + this.didSomething = true; + } + } + } + } - final ItemStack failed = d.addItems( itemsToAdd.getItemStack() ); - if( failed != null ) - { - ais.setStackSize( failed.stackSize ); - inv.injectItems( ais, Actionable.MODULATE, this.mySrc ); - } - else - { - this.didSomething = true; - } - } - } - } + private int getStartingSlot(final SchedulingMode schedulingMode, final int x) { + if (schedulingMode == SchedulingMode.RANDOM) { + return Platform.getRandom().nextInt(this.availableSlots()); + } - private int getStartingSlot( final SchedulingMode schedulingMode, final int x ) - { - if( schedulingMode == SchedulingMode.RANDOM ) - { - return Platform.getRandom().nextInt( this.availableSlots() ); - } + if (schedulingMode == SchedulingMode.ROUNDROBIN) { + return (this.nextSlot + x) % this.availableSlots(); + } - if( schedulingMode == SchedulingMode.ROUNDROBIN ) - { - return ( this.nextSlot + x ) % this.availableSlots(); - } + return x; + } - return x; - } - - private void updateSchedulingMode( final SchedulingMode schedulingMode, final int x ) - { - if( schedulingMode == SchedulingMode.ROUNDROBIN ) - { - this.nextSlot = ( this.nextSlot + x ) % this.availableSlots(); - } - } + private void updateSchedulingMode(final SchedulingMode schedulingMode, final int x) { + if (schedulingMode == SchedulingMode.ROUNDROBIN) { + this.nextSlot = (this.nextSlot + x) % this.availableSlots(); + } + } } diff --git a/src/main/java/appeng/parts/automation/PartFormationPlane.java b/src/main/java/appeng/parts/automation/PartFormationPlane.java index 8c065dfd..6f0b643e 100644 --- a/src/main/java/appeng/parts/automation/PartFormationPlane.java +++ b/src/main/java/appeng/parts/automation/PartFormationPlane.java @@ -18,6 +18,8 @@ package appeng.parts.automation; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.*; @@ -66,536 +68,634 @@ import net.minecraftforge.common.util.BlockSnapshot; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.ArrayList; -import java.util.List; - - -public class PartFormationPlane extends PartUpgradeable implements ICellContainer, IPriorityHost, IMEInventory -{ - private final MEInventoryHandler myHandler = new MEInventoryHandler( this, StorageChannel.ITEMS ); - private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory( this, 63 ); - private EntityPlayer owner = null; - private int priority = 0; - private boolean wasActive = false; - private boolean blocked = false; - - public PartFormationPlane( final ItemStack is ) - { - super( is ); - - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.PLACE_BLOCK, YesNo.YES ); - this.updateHandler(); - } - - @Override - public void onPlacement( EntityPlayer player, ItemStack held, ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.owner = player; - } - - private void updateHandler() - { - this.myHandler.setBaseAccess( AccessRestriction.WRITE ); - this.myHandler.setWhitelist( this.getInstalledUpgrades( Upgrades.INVERTER ) > 0 ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST ); - this.myHandler.setPriority( this.priority ); - - final IItemList priorityList = AEApi.instance().storage().createItemList(); - - final int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for( int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++ ) - { - final IAEItemStack is = this.Config.getAEStackInSlot( x ); - if( is != null ) - { - priorityList.add( is ); - } - } - - 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 ) ); - } - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - protected int getUpgradeSlots() - { - return 5; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.updateHandler(); - this.getHost().markForSave(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final 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( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.Config.readFromNBT( data, "config" ); - this.priority = data.getInteger( "priority" ); - this.updateHandler(); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.Config; - } - - return super.getInventoryByName( name ); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - this.updateHandler();// proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); - this.getHost().markForUpdate(); - } - } - - @MENetworkEventSubscribe - public void updateChannels( final MENetworkChannelsChanged changedChannels ) - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - this.updateHandler();// proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); - this.getHost().markForUpdate(); - } - } - - @Override - public void getBoxes( final 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.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.getSide() ) ) - { - minX = 0; - } - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - } - - bch.addBox( 5, 5, 14, 11, 11, 15 ); - bch.addBox( minX, minY, 15, maxX, maxY, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartTransitionPlaneBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon() ); - - rh.setBounds( 1, 1, 15, 15, 15, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - int minX = 1; - - final ForgeDirection e = rh.getWorldX(); - final ForgeDirection u = rh.getWorldY(); - - final TileEntity te = this.getHost().getTile(); - - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - e.offsetX, y - e.offsetY, z - e.offsetZ ), this.getSide() ) ) - { - minX = 0; - } - - int maxX = 15; - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + e.offsetX, y + e.offsetY, z + e.offsetZ ), this.getSide() ) ) - { - maxX = 16; - } - - int minY = 1; - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x - u.offsetX, y - u.offsetY, z - u.offsetZ ), this.getSide() ) ) - { - minY = 0; - } - - int maxY = 15; - if( this.isTransitionPlane( te.getWorldObj().getTileEntity( x + u.offsetX, y + u.offsetY, z + u.offsetZ ), this.getSide() ) ) - { - maxY = 16; - } - - final boolean isActive = ( this.getClientFlags() & ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ) ) == ( PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG ); - - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartTransitionPlaneBack.getIcon(), isActive ? CableBusTextures.BlockFormPlaneOn.getIcon() : this.getItemStack().getIconIndex(), CableBusTextures.PartPlaneSides.getIcon(), CableBusTextures.PartPlaneSides.getIcon() ); - - rh.setBounds( minX, minY, 15, maxX, maxY, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartTransitionPlaneBack.getIcon(), isActive ? CableBusTextures.BlockFormPlaneOn.getIcon() : this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 5, 5, 14, 11, 11, 15 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void onNeighborChanged() - { - final TileEntity te = this.getHost().getTile(); - final World w = te.getWorldObj(); - final ForgeDirection side = this.getSide(); - - final int x = te.xCoord + side.offsetX; - final int y = te.yCoord + side.offsetY; - final int z = te.zCoord + side.offsetZ; - - this.blocked = !w.getBlock( x, y, z ).isReplaceable( w, x, y, z ); - } - - @Override - public int cableConnectionRenderTo() - { - return 1; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_FORMATION_PLANE ); - return true; - } - - return false; - } - - private boolean isTransitionPlane( final TileEntity blockTileEntity, final ForgeDirection side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p instanceof PartFormationPlane; - } - return false; - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - if( this.getProxy().isActive() && channel == StorageChannel.ITEMS ) - { - final List Handler = new ArrayList( 1 ); - Handler.add( this.myHandler ); - return Handler; - } - return new ArrayList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.getHost().markForSave(); - this.updateHandler(); - } - - @Override - public void blinkCell( final int slot ) - { - // :P - } - - @Override - public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final BaseActionSource src ) - { - if( this.blocked || input == null || input.getStackSize() <= 0 ) - { - return input; - } - - final YesNo placeBlock = (YesNo) this.getConfigManager().getSetting( Settings.PLACE_BLOCK ); - - final ItemStack is = input.getItemStack(); - final Item i = is.getItem(); - - long maxStorage = Math.min( input.getStackSize(), is.getMaxStackSize() ); - boolean worked = false; - - final TileEntity te = this.getHost().getTile(); - final World w = te.getWorldObj(); - final ForgeDirection side = this.getSide(); - - final int x = te.xCoord + side.offsetX; - final int y = te.yCoord + side.offsetY; - final int z = te.zCoord + side.offsetZ; - - 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 ) ) - { - final EntityPlayer player = Platform.getPlayer( (WorldServer) w ); - Platform.configurePlayer( player, side, this.getTile() ); - - if( i instanceof ItemFirework ) - { - final Chunk c = w.getChunkFromBlockCoords( x, z ); - int sum = 0; - for( final List Z : c.entityLists ) - { - sum += Z.size(); - } - if( sum > 32 ) - { - return input; - } - } - maxStorage = is.stackSize; - worked = true; - if( type == Actionable.MODULATE ) - { - if( i instanceof IPlantable || i instanceof ItemSkull || i instanceof ItemReed ) - { - boolean Worked = false; - - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) >= 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 ) - { - 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 ) - { - Worked = i.onItemUse( is, player, w, x, y - 1, z, ForgeDirection.UP.ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - } - - if( !Worked ) - { - i.onItemUse( is, player, w, x, y, z, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - } - - maxStorage -= is.stackSize; - } - } - else - { - Block block = null; - player.setCurrentItemOrArmor( 0, is.copy() ); - if( i instanceof ItemBlock ) - block = ( (ItemBlock) i ).field_150939_a; - if( i instanceof IPartItem ) - block = AEApi.instance().definitions().blocks().multiPart().maybeBlock().orNull(); - if( block == null || - !ForgeEventFactory.onPlayerBlockPlace( - owner == null ? player : owner, - new BlockSnapshot( w, x, y, z, block, i.getMetadata( is.getItemDamage() ) ), - side.getOpposite() - ).isCanceled() ) - { - i.onItemUse( is, player, w, x, y, z, side.getOpposite().ordinal(), side.offsetX, side.offsetY, side.offsetZ ); - maxStorage -= is.stackSize; - } - } - } - else - { - maxStorage = 1; - } - } - else - { - worked = true; - final Chunk c = w.getChunkFromBlockCoords( x, z ); - int sum = 0; - for( final List Z : c.entityLists ) - { - sum += Z.size(); - } - - if( sum < AEConfig.instance.formationPlaneEntityLimit ) - { - if( type == Actionable.MODULATE ) - { - - is.stackSize = (int) maxStorage; - final EntityItem ei = new EntityItem( w, - ( ( side.offsetX != 0 ? 0.0 : 0.7 ) * ( Platform.getRandomFloat() - 0.5f ) ) + 0.5 + side.offsetX * -0.3 + x, - ( ( side.offsetY != 0 ? 0.0 : 0.7 ) * ( Platform.getRandomFloat() - 0.5f ) ) + 0.5 + side.offsetY * -0.3 + y, - ( ( side.offsetZ != 0 ? 0.0 : 0.7 ) * ( Platform.getRandomFloat() - 0.5f ) ) + 0.5 + side.offsetZ * -0.3 + z, - is.copy() ); - - Entity result = ei; - - ei.motionX = side.offsetX * 0.2; - ei.motionY = side.offsetY * 0.2; - ei.motionZ = side.offsetZ * 0.2; - - if( is.getItem().hasCustomEntity( is ) ) - { - result = is.getItem().createEntity( w, ei, is ); - if( result != null ) - { - ei.setDead(); - } - else - { - result = ei; - } - } - - if( !w.spawnEntityInWorld( result ) ) - { - result.setDead(); - worked = false; - } - } - } - else - { - worked = false; - } - } - } - - this.blocked = !w.getBlock( x, y, z ).isReplaceable( w, x, y, z ); - - if( worked ) - { - final IAEItemStack out = input.copy(); - out.decStackSize( maxStorage ); - if( out.getStackSize() == 0 ) - { - return null; - } - return out; - } - - return input; - } - - @Override - public IAEItemStack extractItems( final IAEItemStack request, final Actionable mode, final BaseActionSource src ) - { - return null; - } - - @Override - public IItemList getAvailableItems( final IItemList out ) - { - return out; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - // nope! - } +public class PartFormationPlane extends PartUpgradeable + implements ICellContainer, IPriorityHost, IMEInventory { + private final MEInventoryHandler myHandler + = new MEInventoryHandler(this, StorageChannel.ITEMS); + private final AppEngInternalAEInventory Config + = new AppEngInternalAEInventory(this, 63); + private EntityPlayer owner = null; + private int priority = 0; + private boolean wasActive = false; + private boolean blocked = false; + + public PartFormationPlane(final ItemStack is) { + super(is); + + this.getConfigManager().registerSetting( + Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); + this.getConfigManager().registerSetting(Settings.PLACE_BLOCK, YesNo.YES); + this.updateHandler(); + } + + @Override + public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) { + super.onPlacement(player, held, side); + this.owner = player; + } + + private void updateHandler() { + this.myHandler.setBaseAccess(AccessRestriction.WRITE); + this.myHandler.setWhitelist( + this.getInstalledUpgrades(Upgrades.INVERTER) > 0 ? IncludeExclude.BLACKLIST + : IncludeExclude.WHITELIST + ); + this.myHandler.setPriority(this.priority); + + final IItemList priorityList + = AEApi.instance().storage().createItemList(); + + final int slotsToUse = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++) { + final IAEItemStack is = this.Config.getAEStackInSlot(x); + if (is != null) { + priorityList.add(is); + } + } + + 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)); + } + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + protected int getUpgradeSlots() { + return 5; + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + this.updateHandler(); + this.getHost().markForSave(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final 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(final NBTTagCompound data) { + super.readFromNBT(data); + this.Config.readFromNBT(data, "config"); + this.priority = data.getInteger("priority"); + this.updateHandler(); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.Config.writeToNBT(data, "config"); + data.setInteger("priority", this.priority); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.Config; + } + + return super.getInventoryByName(name); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + this.updateHandler( + ); // proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); + this.getHost().markForUpdate(); + } + } + + @MENetworkEventSubscribe + public void updateChannels(final MENetworkChannelsChanged changedChannels) { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + this.updateHandler( + ); // proxy.getGrid().postEvent( new MENetworkCellArrayUpdate() ); + this.getHost().markForUpdate(); + } + } + + @Override + public void getBoxes(final 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.isTransitionPlane( + te.getWorldObj().getTileEntity( + x - e.offsetX, y - e.offsetY, z - e.offsetZ + ), + this.getSide() + )) { + minX = 0; + } + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity( + x + e.offsetX, y + e.offsetY, z + e.offsetZ + ), + this.getSide() + )) { + maxX = 16; + } + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity( + x - u.offsetX, y - u.offsetY, z - u.offsetZ + ), + this.getSide() + )) { + minY = 0; + } + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity( + x + u.offsetX, y + u.offsetY, z + u.offsetZ + ), + this.getSide() + )) { + maxY = 16; + } + } + + bch.addBox(5, 5, 14, 11, 11, 15); + bch.addBox(minX, minY, 15, maxX, maxY, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartTransitionPlaneBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon() + ); + + rh.setBounds(1, 1, 15, 15, 15, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + int minX = 1; + + final ForgeDirection e = rh.getWorldX(); + final ForgeDirection u = rh.getWorldY(); + + final TileEntity te = this.getHost().getTile(); + + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity( + x - e.offsetX, y - e.offsetY, z - e.offsetZ + ), + this.getSide() + )) { + minX = 0; + } + + int maxX = 15; + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity( + x + e.offsetX, y + e.offsetY, z + e.offsetZ + ), + this.getSide() + )) { + maxX = 16; + } + + int minY = 1; + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity( + x - u.offsetX, y - u.offsetY, z - u.offsetZ + ), + this.getSide() + )) { + minY = 0; + } + + int maxY = 15; + if (this.isTransitionPlane( + te.getWorldObj().getTileEntity( + x + u.offsetX, y + u.offsetY, z + u.offsetZ + ), + this.getSide() + )) { + maxY = 16; + } + + final boolean isActive + = (this.getClientFlags() + & (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG)) + == (PartBasicState.POWERED_FLAG | PartBasicState.CHANNEL_FLAG); + + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture( + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartTransitionPlaneBack.getIcon(), + isActive ? CableBusTextures.BlockFormPlaneOn.getIcon() + : this.getItemStack().getIconIndex(), + CableBusTextures.PartPlaneSides.getIcon(), + CableBusTextures.PartPlaneSides.getIcon() + ); + + rh.setBounds(minX, minY, 15, maxX, maxY, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartTransitionPlaneBack.getIcon(), + isActive ? CableBusTextures.BlockFormPlaneOn.getIcon() + : this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon() + ); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void onNeighborChanged() { + final TileEntity te = this.getHost().getTile(); + final World w = te.getWorldObj(); + final ForgeDirection side = this.getSide(); + + final int x = te.xCoord + side.offsetX; + final int y = te.yCoord + side.offsetY; + final int z = te.zCoord + side.offsetZ; + + this.blocked = !w.getBlock(x, y, z).isReplaceable(w, x, y, z); + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI( + player, + this.getHost().getTile(), + this.getSide(), + GuiBridge.GUI_FORMATION_PLANE + ); + return true; + } + + return false; + } + + private boolean + isTransitionPlane(final TileEntity blockTileEntity, final ForgeDirection side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p instanceof PartFormationPlane; + } + return false; + } + + @Override + public List getCellArray(final StorageChannel channel) { + if (this.getProxy().isActive() && channel == StorageChannel.ITEMS) { + final List Handler + = new ArrayList(1); + Handler.add(this.myHandler); + return Handler; + } + return new ArrayList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.getHost().markForSave(); + this.updateHandler(); + } + + @Override + public void blinkCell(final int slot) { + // :P + } + + @Override + public IAEItemStack injectItems( + final IAEItemStack input, final Actionable type, final BaseActionSource src + ) { + if (this.blocked || input == null || input.getStackSize() <= 0) { + return input; + } + + final YesNo placeBlock + = (YesNo) this.getConfigManager().getSetting(Settings.PLACE_BLOCK); + + final ItemStack is = input.getItemStack(); + final Item i = is.getItem(); + + long maxStorage = Math.min(input.getStackSize(), is.getMaxStackSize()); + boolean worked = false; + + final TileEntity te = this.getHost().getTile(); + final World w = te.getWorldObj(); + final ForgeDirection side = this.getSide(); + + final int x = te.xCoord + side.offsetX; + final int y = te.yCoord + side.offsetY; + final int z = te.zCoord + side.offsetZ; + + 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)) { + final EntityPlayer player = Platform.getPlayer((WorldServer) w); + Platform.configurePlayer(player, side, this.getTile()); + + if (i instanceof ItemFirework) { + final Chunk c = w.getChunkFromBlockCoords(x, z); + int sum = 0; + for (final List Z : c.entityLists) { + sum += Z.size(); + } + if (sum > 32) { + return input; + } + } + maxStorage = is.stackSize; + worked = true; + if (type == Actionable.MODULATE) { + if (i instanceof IPlantable || i instanceof ItemSkull + || i instanceof ItemReed) { + boolean Worked = false; + + if (ForgeEventFactory.onItemUseStart(player, is, 1) >= 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) { + 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) { + Worked = i.onItemUse( + is, + player, + w, + x, + y - 1, + z, + ForgeDirection.UP.ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ + ); + } + + if (!Worked) { + i.onItemUse( + is, + player, + w, + x, + y, + z, + side.getOpposite().ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ + ); + } + + maxStorage -= is.stackSize; + } + } else { + Block block = null; + player.setCurrentItemOrArmor(0, is.copy()); + if (i instanceof ItemBlock) + block = ((ItemBlock) i).field_150939_a; + if (i instanceof IPartItem) + block = AEApi.instance() + .definitions() + .blocks() + .multiPart() + .maybeBlock() + .orNull(); + if (block == null + || !ForgeEventFactory + .onPlayerBlockPlace( + owner == null ? player : owner, + new BlockSnapshot( + w, + x, + y, + z, + block, + i.getMetadata(is.getItemDamage()) + ), + side.getOpposite() + ) + .isCanceled()) { + i.onItemUse( + is, + player, + w, + x, + y, + z, + side.getOpposite().ordinal(), + side.offsetX, + side.offsetY, + side.offsetZ + ); + maxStorage -= is.stackSize; + } + } + } else { + maxStorage = 1; + } + } else { + worked = true; + final Chunk c = w.getChunkFromBlockCoords(x, z); + int sum = 0; + for (final List Z : c.entityLists) { + sum += Z.size(); + } + + if (sum < AEConfig.instance.formationPlaneEntityLimit) { + if (type == Actionable.MODULATE) { + is.stackSize = (int) maxStorage; + final EntityItem ei = new EntityItem( + w, + ((side.offsetX != 0 ? 0.0 : 0.7) + * (Platform.getRandomFloat() - 0.5f)) + + 0.5 + side.offsetX * -0.3 + x, + ((side.offsetY != 0 ? 0.0 : 0.7) + * (Platform.getRandomFloat() - 0.5f)) + + 0.5 + side.offsetY * -0.3 + y, + ((side.offsetZ != 0 ? 0.0 : 0.7) + * (Platform.getRandomFloat() - 0.5f)) + + 0.5 + side.offsetZ * -0.3 + z, + is.copy() + ); + + Entity result = ei; + + ei.motionX = side.offsetX * 0.2; + ei.motionY = side.offsetY * 0.2; + ei.motionZ = side.offsetZ * 0.2; + + if (is.getItem().hasCustomEntity(is)) { + result = is.getItem().createEntity(w, ei, is); + if (result != null) { + ei.setDead(); + } else { + result = ei; + } + } + + if (!w.spawnEntityInWorld(result)) { + result.setDead(); + worked = false; + } + } + } else { + worked = false; + } + } + } + + this.blocked = !w.getBlock(x, y, z).isReplaceable(w, x, y, z); + + if (worked) { + final IAEItemStack out = input.copy(); + out.decStackSize(maxStorage); + if (out.getStackSize() == 0) { + return null; + } + return out; + } + + return input; + } + + @Override + public IAEItemStack extractItems( + final IAEItemStack request, final Actionable mode, final BaseActionSource src + ) { + return null; + } + + @Override + public IItemList getAvailableItems(final IItemList out) { + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public void saveChanges(final IMEInventory cellInventory) { + // nope! + } } diff --git a/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java b/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java index a9883786..7fd003af 100644 --- a/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java +++ b/src/main/java/appeng/parts/automation/PartIdentityAnnihilationPlane.java @@ -18,6 +18,8 @@ package appeng.parts.automation; +import java.util.ArrayList; +import java.util.List; import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; @@ -36,74 +38,73 @@ import net.minecraft.util.IIcon; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.List; +public class PartIdentityAnnihilationPlane extends PartAnnihilationPlane { + private static final IIcon ACTIVE_ICON + = CableBusTextures.BlockIdentityAnnihilationPlaneOn.getIcon(); + private static final float SILK_TOUCH_FACTOR = 16; -public class PartIdentityAnnihilationPlane extends PartAnnihilationPlane -{ - private static final IIcon ACTIVE_ICON = CableBusTextures.BlockIdentityAnnihilationPlaneOn.getIcon(); + public PartIdentityAnnihilationPlane(final ItemStack is) { + super(is); + } - private static final float SILK_TOUCH_FACTOR = 16; + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.renderStaticWithIcon(x, y, z, rh, renderer, ACTIVE_ICON); + } - public PartIdentityAnnihilationPlane( final ItemStack is ) - { - super( is ); - } + @Override + protected boolean + isAnnihilationPlane(final TileEntity blockTileEntity, final ForgeDirection side) { + if (blockTileEntity instanceof IPartHost) { + final IPart p = ((IPartHost) blockTileEntity).getPart(side); + return p != null && p.getClass() == this.getClass(); + } + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.renderStaticWithIcon( x, y, z, rh, renderer, ACTIVE_ICON ); - } + @Override + protected float calculateEnergyUsage( + final WorldServer w, + final int x, + final int y, + final int z, + final List items + ) { + final float requiredEnergy = super.calculateEnergyUsage(w, x, y, z, items); - @Override - protected boolean isAnnihilationPlane( final TileEntity blockTileEntity, final ForgeDirection side ) - { - if( blockTileEntity instanceof IPartHost ) - { - final IPart p = ( (IPartHost) blockTileEntity ).getPart( side ); - return p != null && p.getClass() == this.getClass(); - } - return false; - } + return requiredEnergy * SILK_TOUCH_FACTOR; + } - @Override - protected float calculateEnergyUsage( final WorldServer w, final int x, final int y, final int z, final List items ) - { - final float requiredEnergy = super.calculateEnergyUsage( w, x, y, z, items ); + @Override + protected List + obtainBlockDrops(final WorldServer w, final int x, final int y, final int z) { + final EntityPlayer fakePlayer = Platform.getPlayer(w); + final Block block = w.getBlock(x, y, z); + final int blockMeta = w.getBlockMetadata(x, y, z); - return requiredEnergy * SILK_TOUCH_FACTOR; - } + if (block.canSilkHarvest(w, fakePlayer, x, y, z, blockMeta)) { + final List out = new ArrayList(1); + final Item item = Item.getItemFromBlock(block); - @Override - protected List obtainBlockDrops( final WorldServer w, final int x, final int y, final int z ) - { - final EntityPlayer fakePlayer = Platform.getPlayer( w ); - final Block block = w.getBlock( x, y, z ); - final int blockMeta = w.getBlockMetadata( x, y, z ); - - if( block.canSilkHarvest( w, fakePlayer, x, y, z, blockMeta ) ) - { - final List out = new ArrayList( 1 ); - final Item item = Item.getItemFromBlock( block ); - - if( item != null ) - { - int meta = 0; - if( item.getHasSubtypes() ) - { - meta = blockMeta; - } - final ItemStack itemstack = new ItemStack( item, 1, meta ); - out.add( itemstack ); - } - return out; - } - else - { - return super.obtainBlockDrops( w, x, y, z ); - } - } + if (item != null) { + int meta = 0; + if (item.getHasSubtypes()) { + meta = blockMeta; + } + final ItemStack itemstack = new ItemStack(item, 1, meta); + out.add(itemstack); + } + return out; + } else { + return super.obtainBlockDrops(w, x, y, z); + } + } } diff --git a/src/main/java/appeng/parts/automation/PartImportBus.java b/src/main/java/appeng/parts/automation/PartImportBus.java index 0b04bd76..b0e4ba7c 100644 --- a/src/main/java/appeng/parts/automation/PartImportBus.java +++ b/src/main/java/appeng/parts/automation/PartImportBus.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.AEApi; import appeng.api.config.*; import appeng.api.networking.IGridNode; @@ -49,285 +48,330 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.Vec3; +public class PartImportBus extends PartSharedItemBus implements IInventoryDestination { + private final BaseActionSource source; + private IMEInventory destination = null; + private IAEItemStack lastItemChecked = null; + private int itemToSend; // used in tickingRequest + private boolean worked; // used in tickingRequest -public class PartImportBus extends PartSharedItemBus implements IInventoryDestination -{ - private final BaseActionSource source; - private IMEInventory destination = null; - private IAEItemStack lastItemChecked = null; - private int itemToSend; // used in tickingRequest - private boolean worked; // used in tickingRequest + @Reflected + public PartImportBus(final ItemStack is) { + super(is); - @Reflected - public PartImportBus( final ItemStack is ) - { - super( is ); + this.getConfigManager().registerSetting( + Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE + ); + this.getConfigManager().registerSetting( + Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); + this.source = new MachineSource(this); + } - this.getConfigManager().registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.source = new MachineSource( this ); - } + @Override + public boolean canInsert(final ItemStack stack) { + if (stack == null || stack.getItem() == null) { + return false; + } - @Override - public boolean canInsert( final ItemStack stack ) - { - if( stack == null || stack.getItem() == null ) - { - return false; - } + final IAEItemStack out = this.destination.injectItems( + this.lastItemChecked = AEApi.instance().storage().createItemStack(stack), + Actionable.SIMULATE, + this.source + ); + if (out == null) { + return true; + } + return out.getStackSize() != stack.stackSize; + } - final IAEItemStack out = this.destination.injectItems( this.lastItemChecked = AEApi.instance().storage().createItemStack( stack ), Actionable.SIMULATE, this.source ); - if( out == null ) - { - return true; - } - return out.getStackSize() != stack.stackSize; - } + @Override + public void getBoxes(final 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 void getBoxes( final 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(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon() + ); - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon() ); + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderInventoryBox(renderer); - rh.setBounds( 3, 3, 15, 13, 13, 16 ); - rh.renderInventoryBox( renderer ); + rh.setBounds(4, 4, 14, 12, 12, 15); + rh.renderInventoryBox(renderer); - rh.setBounds( 4, 4, 14, 12, 12, 15 ); - rh.renderInventoryBox( renderer ); + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderInventoryBox(renderer); + } - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderInventoryBox( renderer ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture( + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartImportSides.getIcon(), + CableBusTextures.PartImportSides.getIcon() + ); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartImportSides.getIcon(), CableBusTextures.PartImportSides.getIcon() ); + rh.setBounds(4, 4, 14, 12, 12, 16); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 4, 4, 14, 12, 12, 16 ); - rh.renderBlock( x, y, z, renderer ); + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderBlock( x, y, z, renderer ); + rh.setBounds(6, 6, 12, 10, 10, 13); + rh.renderBlock(x, y, z, renderer); + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon() + ); - rh.setBounds( 6, 6, 12, 10, 10, 13 ); - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); + rh.setBounds(6, 6, 11, 10, 10, 12); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 6, 6, 11, 10, 10, 12 ); - rh.renderBlock( x, y, z, renderer ); + this.renderLights(x, y, z, rh, renderer); + } - this.renderLights( x, y, z, rh, renderer ); - } + @Override + public int cableConnectionRenderTo() { + return 5; + } - @Override - public int cableConnectionRenderTo() - { - return 5; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + Platform.openGUI( + player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS + ); + return true; + } - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_BUS ); - return true; - } + return false; + } - return false; - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.ImportBus.getMin(), + TickRates.ImportBus.getMax(), + this.getHandler() == null, + false + ); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ImportBus.getMin(), TickRates.ImportBus.getMax(), this.getHandler() == null, false ); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doBusWork(); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doBusWork(); - } + @Override + protected TickRateModulation doBusWork() { + if (!this.getProxy().isActive() || !this.canDoBusWork()) { + return TickRateModulation.IDLE; + } - @Override - protected TickRateModulation doBusWork() - { - if( !this.getProxy().isActive() || !this.canDoBusWork() ) - { - return TickRateModulation.IDLE; - } + this.worked = false; - this.worked = false; + final InventoryAdaptor myAdaptor = this.getHandler(); + final FuzzyMode fzMode + = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); - final InventoryAdaptor myAdaptor = this.getHandler(); - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); + if (myAdaptor != null) { + try { + this.itemToSend = this.calculateItemsToSend(); + this.itemToSend = Math.min( + this.itemToSend, + (int + ) (0.01 + + this.getProxy().getEnergy().extractAEPower( + this.itemToSend, Actionable.SIMULATE, PowerMultiplier.CONFIG + )) + ); - if( myAdaptor != null ) - { - try - { - this.itemToSend = this.calculateItemsToSend(); - this.itemToSend = Math.min( this.itemToSend, (int) ( 0.01 + this.getProxy().getEnergy().extractAEPower( this.itemToSend, Actionable.SIMULATE, PowerMultiplier.CONFIG ) ) ); + final IMEMonitor inv + = this.getProxy().getStorage().getItemInventory(); + final IEnergyGrid energy = this.getProxy().getEnergy(); - final IMEMonitor inv = this.getProxy().getStorage().getItemInventory(); - final IEnergyGrid energy = this.getProxy().getEnergy(); + boolean Configured = false; + for (int x = 0; x < this.availableSlots(); x++) { + final IAEItemStack ais = this.getConfig().getAEStackInSlot(x); + if (ais != null && this.itemToSend > 0) { + Configured = true; + while (this.itemToSend > 0) { + if (this.importStuff(myAdaptor, ais, inv, energy, fzMode)) { + break; + } + } + } + } - boolean Configured = false; - for( int x = 0; x < this.availableSlots(); x++ ) - { - final IAEItemStack ais = this.getConfig().getAEStackInSlot( x ); - if( ais != null && this.itemToSend > 0 ) - { - Configured = true; - while( this.itemToSend > 0 ) - { - if( this.importStuff( myAdaptor, ais, inv, energy, fzMode ) ) - { - break; - } - } - } - } + if (!Configured) { + while (this.itemToSend > 0) { + if (this.importStuff(myAdaptor, null, inv, energy, fzMode)) { + break; + } + } + } + } catch (final GridAccessException e) { + // :3 + } + } else { + return TickRateModulation.SLEEP; + } - if( !Configured ) - { - while( this.itemToSend > 0 ) - { - if( this.importStuff( myAdaptor, null, inv, energy, fzMode ) ) - { - break; - } - } - } - } - catch( final GridAccessException e ) - { - // :3 - } - } - else - { - return TickRateModulation.SLEEP; - } + return this.worked ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } - return this.worked ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } + private boolean importStuff( + final InventoryAdaptor myAdaptor, + final IAEItemStack whatToImport, + final IMEMonitor inv, + final IEnergySource energy, + final FuzzyMode fzMode + ) { + final int toSend + = this.calculateMaximumAmountToImport(myAdaptor, whatToImport, inv, fzMode); + final ItemStack newItems; - private boolean importStuff( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final IEnergySource energy, final FuzzyMode fzMode ) - { - final int toSend = this.calculateMaximumAmountToImport( myAdaptor, whatToImport, inv, fzMode ); - final ItemStack newItems; + 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( 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) { + newItems.stackSize = (int + ) (Math.min( + newItems.stackSize, + energy.extractAEPower( + newItems.stackSize, Actionable.SIMULATE, PowerMultiplier.CONFIG + ) + ) + + 0.01); + this.itemToSend -= newItems.stackSize; - 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)) { + this.lastItemChecked + = AEApi.instance().storage().createItemStack(newItems); + } else { + this.lastItemChecked.setStackSize(newItems.stackSize); + } - if( this.lastItemChecked == null || !this.lastItemChecked.isSameType( newItems ) ) - { - this.lastItemChecked = AEApi.instance().storage().createItemStack( newItems ); - } - else - { - this.lastItemChecked.setStackSize( newItems.stackSize ); - } + final IAEItemStack failed = Platform.poweredInsert( + energy, this.destination, this.lastItemChecked, this.source + ); - final IAEItemStack failed = Platform.poweredInsert( energy, this.destination, this.lastItemChecked, this.source ); + if (failed != null) { + myAdaptor.addItems(failed.getItemStack()); + return true; + } else { + this.worked = true; + } + } else { + return true; + } - if( failed != null ) - { - myAdaptor.addItems( failed.getItemStack() ); - return true; - } - else - { - this.worked = true; - } - } - else - { - return true; - } + return false; + } - return false; - } + private int calculateMaximumAmountToImport( + final InventoryAdaptor myAdaptor, + final IAEItemStack whatToImport, + final IMEMonitor inv, + final FuzzyMode fzMode + ) { + final int toSend = Math.min(this.itemToSend, 64); + final ItemStack itemStackToImport; - private int calculateMaximumAmountToImport( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor inv, final FuzzyMode fzMode ) - { - final int toSend = Math.min( this.itemToSend, 64 ); - final ItemStack itemStackToImport; + if (whatToImport == null) { + itemStackToImport = null; + } else { + itemStackToImport = whatToImport.getItemStack(); + } - if( whatToImport == null ) - { - itemStackToImport = null; - } - else - { - itemStackToImport = whatToImport.getItemStack(); - } + final IAEItemStack itemAmountNotStorable; + final ItemStack simResult; + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + simResult = myAdaptor.simulateSimilarRemove( + toSend, itemStackToImport, fzMode, this.configDestination(inv) + ); + itemAmountNotStorable = this.destination.injectItems( + AEItemStack.create(simResult), Actionable.SIMULATE, this.source + ); + } else { + simResult = myAdaptor.simulateRemove( + toSend, itemStackToImport, this.configDestination(inv) + ); + itemAmountNotStorable = this.destination.injectItems( + AEItemStack.create(simResult), Actionable.SIMULATE, this.source + ); + } - final IAEItemStack itemAmountNotStorable; - final ItemStack simResult; - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - simResult = myAdaptor.simulateSimilarRemove( toSend, itemStackToImport, fzMode, this.configDestination( inv ) ); - itemAmountNotStorable = this.destination.injectItems( AEItemStack.create( simResult ), Actionable.SIMULATE, this.source ); - } - else - { - simResult = myAdaptor.simulateRemove( toSend, itemStackToImport, this.configDestination( inv ) ); - itemAmountNotStorable = this.destination.injectItems( AEItemStack.create( simResult ), Actionable.SIMULATE, this.source ); - } + if (itemAmountNotStorable != null) { + return (int) Math.min( + simResult.stackSize - itemAmountNotStorable.getStackSize(), toSend + ); + } - if( itemAmountNotStorable != null ) - { - return (int) Math.min( simResult.stackSize - itemAmountNotStorable.getStackSize(), toSend ); - } + return toSend; + } - return toSend; - } + private IInventoryDestination + configDestination(final IMEMonitor itemInventory) { + this.destination = itemInventory; + return this; + } - private IInventoryDestination configDestination( final IMEMonitor itemInventory ) - { - this.destination = itemInventory; - return this; - } + @Override + protected boolean isSleeping() { + return this.getHandler() == null || super.isSleeping(); + } - @Override - protected boolean isSleeping() - { - return this.getHandler() == null || super.isSleeping(); - } - - @Override - public RedstoneMode getRSMode() - { - return (RedstoneMode) this.getConfigManager().getSetting( Settings.REDSTONE_CONTROLLED ); - } + @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 6cab7d26..228e0770 100644 --- a/src/main/java/appeng/parts/automation/PartLevelEmitter.java +++ b/src/main/java/appeng/parts/automation/PartLevelEmitter.java @@ -18,6 +18,8 @@ package appeng.parts.automation; +import java.util.Collection; +import java.util.Random; import appeng.api.config.*; import appeng.api.networking.crafting.*; @@ -64,674 +66,715 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collection; -import java.util.Random; - - public class PartLevelEmitter extends PartUpgradeable - implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, IMEMonitorHandlerReceiver, ICraftingProvider -{ - - private static final int FLAG_ON = 4; - - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 1 ); - - private boolean prevState = false; - - private long lastReportedValue = 0; - private long reportingValue = 0; - - private IStackWatcher myWatcher; - private IEnergyWatcher myEnergyWatcher; - private ICraftingWatcher myCraftingWatcher; - private double centerX; - private double centerY; - private double centerZ; - - @Reflected - public PartLevelEmitter( final ItemStack is ) - { - super( is ); - - this.getConfigManager().registerSetting( Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL ); - this.getConfigManager().registerSetting( Settings.CRAFT_VIA_REDSTONE, YesNo.NO ); - } - - public long getReportingValue() - { - return this.reportingValue; - } - - public void setReportingValue( final long v ) - { - this.reportingValue = v; - if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) - { - this.configureWatchers(); - } - else - { - this.updateState(); - } - } - - @MENetworkEventSubscribe - public void powerChanged( final MENetworkPowerStatusChange c ) - { - this.updateState(); - } - - private void updateState() - { - final boolean isOn = this.isLevelEmitterOn(); - if( this.prevState != isOn ) - { - this.getHost().markForUpdate(); - final TileEntity te = this.getHost().getTile(); - this.prevState = isOn; - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); - } - } - - private boolean isLevelEmitterOn() - { - if( Platform.isClient() ) - { - return ( this.getClientFlags() & FLAG_ON ) == FLAG_ON; - } - - if( !this.getProxy().isActive() ) - { - return false; - } - - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - try - { - return this.getProxy().getCrafting().isRequesting( this.config.getAEStackInSlot( 0 ) ); - } - catch( final GridAccessException e ) - { - // :P - } - - return this.prevState; - } - - final boolean flipState = this.getConfigManager().getSetting( Settings.REDSTONE_EMITTER ) == RedstoneMode.LOW_SIGNAL; - return flipState ? this.reportingValue >= this.lastReportedValue + 1 : this.reportingValue < this.lastReportedValue + 1; - } - - @MENetworkEventSubscribe - public void channelChanged( final MENetworkChannelsChanged c ) - { - this.updateState(); - } - - @Override - protected int populateFlags( final int cf ) - { - return cf | ( this.prevState ? FLAG_ON : 0 ); - } - - @Override - public IIcon getBreakingTexture() - { - return this.getItemStack().getIconIndex(); - } - - @Override - public void updateWatcher( final ICraftingWatcher newWatcher ) - { - this.myCraftingWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onRequestChange( final ICraftingGrid craftingGrid, final IAEItemStack what ) - { - this.updateState(); - } - - // update the system... - private void configureWatchers() - { - final IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - - if( this.myWatcher != null ) - { - this.myWatcher.clear(); - } - - if( this.myEnergyWatcher != null ) - { - this.myEnergyWatcher.clear(); - } - - if( this.myCraftingWatcher != null ) - { - this.myCraftingWatcher.clear(); - } - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCraftingPatternChange( this, this.getProxy().getNode() ) ); - } - catch( final GridAccessException e1 ) - { - // :/ - } - - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - if( this.myCraftingWatcher != null && myStack != null ) - { - this.myCraftingWatcher.add( myStack ); - } - - return; - } - - if( this.getConfigManager().getSetting( Settings.LEVEL_TYPE ) == LevelType.ENERGY_LEVEL ) - { - if( this.myEnergyWatcher != null ) - { - this.myEnergyWatcher.add( (double) this.reportingValue ); - } - - try - { - // update to power... - this.lastReportedValue = (long) this.getProxy().getEnergy().getStoredPower(); - this.updateState(); - - // no more item stuff.. - this.getProxy().getStorage().getItemInventory().removeListener( this ); - } - catch( final GridAccessException e ) - { - // :P - } - - return; - } - - try - { - if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 || myStack == null ) - { - this.getProxy().getStorage().getItemInventory().addListener( this, this.getProxy().getGrid() ); - } - else - { - this.getProxy().getStorage().getItemInventory().removeListener( this ); - - if( this.myWatcher != null ) - { - this.myWatcher.add( myStack ); - } - } - - this.updateReportingValue( this.getProxy().getStorage().getItemInventory() ); - } - catch( final GridAccessException e ) - { - // >.> - } - } - - private void updateReportingValue( final IMEMonitor monitor ) - { - final IAEItemStack myStack = this.config.getAEStackInSlot( 0 ); - - if( myStack == null ) - { - this.lastReportedValue = 0; - for( final IAEItemStack st : monitor.getStorageList() ) - { - this.lastReportedValue += st.getStackSize(); - } - } - else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) - { - this.lastReportedValue = 0; - final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE ); - final Collection fuzzyList = monitor.getStorageList().findFuzzy( myStack, fzMode ); - for( final IAEItemStack st : fuzzyList ) - { - this.lastReportedValue += st.getStackSize(); - } - } - else - { - final IAEItemStack r = monitor.getStorageList().findPrecise( myStack ); - if( r == null ) - { - this.lastReportedValue = 0; - } - else - { - this.lastReportedValue = r.getStackSize(); - } - } - - this.updateState(); - } - - @Override - public void updateWatcher( final IStackWatcher newWatcher ) - { - this.myWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final BaseActionSource src, final StorageChannel chan ) - { - 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( final IEnergyWatcher newWatcher ) - { - this.myEnergyWatcher = newWatcher; - this.configureWatchers(); - } - - @Override - public void onThresholdPass( final IEnergyGrid energyGrid ) - { - this.lastReportedValue = (long) energyGrid.getStoredPower(); - this.updateState(); - } - - @Override - public boolean isValid( final Object effectiveGrid ) - { - try - { - return this.getProxy().getGrid() == effectiveGrid; - } - catch( final GridAccessException e ) - { - return false; - } - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource actionSource ) - { - this.updateReportingValue( (IMEMonitor) monitor ); - } - - @Override - public void onListUpdate() - { - try - { - this.updateReportingValue( this.getProxy().getStorage().getItemInventory() ); - } - catch( final GridAccessException e ) - { - // ;P - } - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 7, 7, 11, 9, 9, 16 ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( this.getItemStack().getIconIndex() ); - Tessellator.instance.startDrawingQuads(); - this.renderTorchAtAngle( 0, -0.5, 0 ); - Tessellator.instance.draw(); - // rh.setBounds( 7, 7, 10, 9, 9, 15 ); - // rh.renderInventoryBox( renderer ); - } - - private void renderTorchAtAngle( double baseX, double baseY, double baseZ ) - { - final boolean isOn = this.isLevelEmitterOn(); - final IIcon offTexture = this.getItemStack().getIconIndex(); - final IIcon IIcon = ( isOn ? CableBusTextures.LevelEmitterTorchOn.getIcon() : offTexture ); - // - this.centerX = baseX + 0.5; - this.centerY = baseY + 0.5; - this.centerZ = baseZ + 0.5; - - baseY += 7.0 / 16.0; - - // double par11 = 0; - - /* - * double d5 = (double)IIcon.func_94209_e(); double d6 = (double)IIcon.func_94206_g(); double d7 = - * (double)IIcon.func_94212_f(); double d8 = (double)IIcon.func_94210_h(); double d9 = - * (double)IIcon.func_94214_a(7.0D); double d10 = (double)IIcon.func_94207_b(6.0D); double d11 = - * (double)IIcon.func_94214_a(9.0D); double d12 = (double)IIcon.func_94207_b(8.0D); double d13 = - * (double)IIcon.func_94214_a(7.0D); double d14 = (double)IIcon.func_94207_b(13.0D); double d15 = - * (double)IIcon.func_94214_a(9.0D); double d16 = (double)IIcon.func_94207_b(15.0D); - */ - - final float var16 = IIcon.getMinU(); - final float var17 = IIcon.getMaxU(); - final float var18 = IIcon.getMinV(); - final float var19 = IIcon.getMaxV(); - /* - * float var16 = (float)var14 / 256.0F; float var17 = ((float)var14 + 15.99F) / 256.0F; float var18 = - * (float)var15 / 256.0F; float var19 = ((float)var15 + 15.99F) / 256.0F; - */ - final double var20b = offTexture.getInterpolatedU( 7.0D ); - final double var24b = offTexture.getInterpolatedU( 9.0D ); - - final double var20 = IIcon.getInterpolatedU( 7.0D ); - final double var24 = IIcon.getInterpolatedU( 9.0D ); - final double var22 = IIcon.getInterpolatedV( 6.0D + ( isOn ? 0 : 1.0D ) ); - final double var26 = IIcon.getInterpolatedV( 8.0D + ( isOn ? 0 : 1.0D ) ); - final double var28 = IIcon.getInterpolatedU( 7.0D ); - final double var30 = IIcon.getInterpolatedV( 13.0D ); - final double var32 = IIcon.getInterpolatedU( 9.0D ); - final double var34 = IIcon.getInterpolatedV( 15.0D ); - - final double var22b = IIcon.getInterpolatedV( 9.0D ); - final double var26b = IIcon.getInterpolatedV( 11.0D ); - - baseX += 0.5D; - baseZ += 0.5D; - final double var36 = baseX - 0.5D; - final double var38 = baseX + 0.5D; - final double var40 = baseZ - 0.5D; - final double var42 = baseZ + 0.5D; - - double toff = 0.0d; - - if( !isOn ) - { - toff = 1.0d / 16.0d; - } - - final Tessellator var12 = Tessellator.instance; - if( isOn ) - { - var12.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - var12.setBrightness( 11 << 20 | 11 << 4 ); - } - - final double TorchLen = 0.625D; - final double var44 = 0.0625D; - final double Zero = 0; - final double par10 = 0; - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var20, var22 ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var20, var26 ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var24, var26 ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + TorchLen - toff, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var24, var22 ); - - final double var422 = 0.1915D + 1.0 / 16.0; - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var24b, var22b ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) + var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var24b, var26b ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) + var44, var20b, var26b ); - this.addVertexWithUV( baseX + Zero * ( 1.0D - TorchLen ) - var44, baseY + var422, baseZ + par10 * ( 1.0D - TorchLen ) - var44, var20b, var22b ); - - this.addVertexWithUV( baseX + var44 + Zero, baseY, baseZ - var44 + par10, var32, var30 ); - this.addVertexWithUV( baseX + var44 + Zero, baseY, baseZ + var44 + par10, var32, var34 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY, baseZ + var44 + par10, var28, var34 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY, baseZ - var44 + par10, var28, var30 ); - - this.addVertexWithUV( baseX - var44, baseY + 1.0D, var40, var16, var18 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY + 0.0D, var40 + par10, var16, var19 ); - this.addVertexWithUV( baseX - var44 + Zero, baseY + 0.0D, var42 + par10, var17, var19 ); - this.addVertexWithUV( baseX - var44, baseY + 1.0D, var42, var17, var18 ); - - this.addVertexWithUV( baseX + var44, baseY + 1.0D, var42, var16, var18 ); - this.addVertexWithUV( baseX + Zero + var44, baseY + 0.0D, var42 + par10, var16, var19 ); - this.addVertexWithUV( baseX + Zero + var44, baseY + 0.0D, var40 + par10, var17, var19 ); - this.addVertexWithUV( baseX + var44, baseY + 1.0D, var40, var17, var18 ); - - this.addVertexWithUV( var36, baseY + 1.0D, baseZ + var44, var16, var18 ); - this.addVertexWithUV( var36 + Zero, baseY + 0.0D, baseZ + var44 + par10, var16, var19 ); - this.addVertexWithUV( var38 + Zero, baseY + 0.0D, baseZ + var44 + par10, var17, var19 ); - this.addVertexWithUV( var38, baseY + 1.0D, baseZ + var44, var17, var18 ); - - this.addVertexWithUV( var38, baseY + 1.0D, baseZ - var44, var16, var18 ); - this.addVertexWithUV( var38 + Zero, baseY + 0.0D, baseZ - var44 + par10, var16, var19 ); - this.addVertexWithUV( var36 + Zero, baseY + 0.0D, baseZ - var44 + par10, var17, var19 ); - this.addVertexWithUV( var36, baseY + 1.0D, baseZ - var44, var17, var18 ); - } - - private void addVertexWithUV( double x, double y, double z, final double u, final double v ) - { - final Tessellator var12 = Tessellator.instance; - - x -= this.centerX; - y -= this.centerY; - z -= this.centerZ; - - if( this.getSide() == ForgeDirection.DOWN ) - { - y = -y; - z = -z; - } - - if( this.getSide() == ForgeDirection.EAST ) - { - final double m = x; - x = y; - y = m; - y = -y; - } - - if( this.getSide() == ForgeDirection.WEST ) - { - final double m = x; - x = -y; - y = m; - } - - if( this.getSide() == ForgeDirection.SOUTH ) - { - final double m = z; - z = y; - y = m; - y = -y; - } - - if( this.getSide() == ForgeDirection.NORTH ) - { - final double m = z; - z = -y; - y = m; - } - - x += this.centerX;// + orientation.offsetX * 0.4; - y += this.centerY;// + orientation.offsetY * 0.4; - z += this.centerZ;// + orientation.offsetZ * 0.4; - - var12.addVertexWithUV( x, y, z, u, v ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( this.getItemStack().getIconIndex() ); - // rh.setTexture( CableBusTextures.ItemPartLevelEmitterOn.getIcon() ); - - // rh.setBounds( 2, 2, 14, 14, 14, 16 ); - // rh.renderBlock( x, y, z, renderer ); - - // rh.setBounds( 7, 7, 10, 9, 9, 15 ); - // rh.renderBlock( x, y, z, renderer ); - - renderer.renderAllFaces = true; - - final Tessellator tess = Tessellator.instance; - tess.setBrightness( rh.getBlock().getMixedBrightnessForBlock( this.getHost().getTile().getWorldObj(), x, y, z ) ); - tess.setColorOpaque_F( 1.0F, 1.0F, 1.0F ); - - this.renderTorchAtAngle( x, y, z ); - - renderer.renderAllFaces = false; - - rh.setBounds( 7, 7, 11, 9, 9, 12 ); - this.renderLights( x, y, z, rh, renderer ); - - // 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 randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - if( this.isLevelEmitterOn() ) - { - final ForgeDirection d = this.getSide(); - - final double d0 = d.offsetX * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d1 = d.offsetY * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - final double d2 = d.offsetZ * 0.45F + ( r.nextFloat() - 0.5F ) * 0.2D; - - world.spawnParticle( "reddust", 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D ); - } - } - - @Override - public int cableConnectionRenderTo() - { - return 16; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_LEVEL_EMITTER ); - return true; - } - - return false; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.configureWatchers(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final 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() - { - return true; - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.lastReportedValue = data.getLong( "lastReportedValue" ); - this.reportingValue = data.getLong( "reportingValue" ); - this.prevState = data.getBoolean( "prevState" ); - this.config.readFromNBT( data, "config" ); - } - - @Override - public void writeToNBT( final 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( final String name ) - { - if( name.equals( "config" ) ) - { - return this.config; - } - - return super.getInventoryByName( name ); - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return false; - } - - @Override - public boolean isBusy() - { - return true; - } - - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - if( this.getInstalledUpgrades( Upgrades.CRAFTING ) > 0 ) - { - if( this.getConfigManager().getSetting( Settings.CRAFT_VIA_REDSTONE ) == YesNo.YES ) - { - final IAEItemStack what = this.config.getAEStackInSlot( 0 ); - if( what != null ) - { - craftingTracker.setEmitable( what ); - } - } - } - } + implements IEnergyWatcherHost, IStackWatcherHost, ICraftingWatcherHost, + IMEMonitorHandlerReceiver, ICraftingProvider { + private static final int FLAG_ON = 4; + + private final AppEngInternalAEInventory config + = new AppEngInternalAEInventory(this, 1); + + private boolean prevState = false; + + private long lastReportedValue = 0; + private long reportingValue = 0; + + private IStackWatcher myWatcher; + private IEnergyWatcher myEnergyWatcher; + private ICraftingWatcher myCraftingWatcher; + private double centerX; + private double centerY; + private double centerZ; + + @Reflected + public PartLevelEmitter(final ItemStack is) { + super(is); + + this.getConfigManager().registerSetting( + Settings.REDSTONE_EMITTER, RedstoneMode.HIGH_SIGNAL + ); + this.getConfigManager().registerSetting( + Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); + this.getConfigManager().registerSetting( + Settings.LEVEL_TYPE, LevelType.ITEM_LEVEL + ); + this.getConfigManager().registerSetting(Settings.CRAFT_VIA_REDSTONE, YesNo.NO); + } + + public long getReportingValue() { + return this.reportingValue; + } + + public void setReportingValue(final long v) { + this.reportingValue = v; + if (this.getConfigManager().getSetting(Settings.LEVEL_TYPE) + == LevelType.ENERGY_LEVEL) { + this.configureWatchers(); + } else { + this.updateState(); + } + } + + @MENetworkEventSubscribe + public void powerChanged(final MENetworkPowerStatusChange c) { + this.updateState(); + } + + private void updateState() { + final boolean isOn = this.isLevelEmitterOn(); + if (this.prevState != isOn) { + this.getHost().markForUpdate(); + final TileEntity te = this.getHost().getTile(); + this.prevState = isOn; + Platform.notifyBlocksOfNeighbors( + te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord + ); + Platform.notifyBlocksOfNeighbors( + te.getWorldObj(), + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ + ); + } + } + + private boolean isLevelEmitterOn() { + if (Platform.isClient()) { + return (this.getClientFlags() & FLAG_ON) == FLAG_ON; + } + + if (!this.getProxy().isActive()) { + return false; + } + + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + try { + return this.getProxy().getCrafting().isRequesting( + this.config.getAEStackInSlot(0) + ); + } catch (final GridAccessException e) { + // :P + } + + return this.prevState; + } + + final boolean flipState + = this.getConfigManager().getSetting(Settings.REDSTONE_EMITTER) + == RedstoneMode.LOW_SIGNAL; + return flipState ? this.reportingValue >= this.lastReportedValue + 1 + : this.reportingValue < this.lastReportedValue + 1; + } + + @MENetworkEventSubscribe + public void channelChanged(final MENetworkChannelsChanged c) { + this.updateState(); + } + + @Override + protected int populateFlags(final int cf) { + return cf | (this.prevState ? FLAG_ON : 0); + } + + @Override + public IIcon getBreakingTexture() { + return this.getItemStack().getIconIndex(); + } + + @Override + public void updateWatcher(final ICraftingWatcher newWatcher) { + this.myCraftingWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void + onRequestChange(final ICraftingGrid craftingGrid, final IAEItemStack what) { + this.updateState(); + } + + // update the system... + private void configureWatchers() { + final IAEItemStack myStack = this.config.getAEStackInSlot(0); + + if (this.myWatcher != null) { + this.myWatcher.clear(); + } + + if (this.myEnergyWatcher != null) { + this.myEnergyWatcher.clear(); + } + + if (this.myCraftingWatcher != null) { + this.myCraftingWatcher.clear(); + } + + try { + this.getProxy().getGrid().postEvent( + new MENetworkCraftingPatternChange(this, this.getProxy().getNode()) + ); + } catch (final GridAccessException e1) { + // :/ + } + + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + if (this.myCraftingWatcher != null && myStack != null) { + this.myCraftingWatcher.add(myStack); + } + + return; + } + + if (this.getConfigManager().getSetting(Settings.LEVEL_TYPE) + == LevelType.ENERGY_LEVEL) { + if (this.myEnergyWatcher != null) { + this.myEnergyWatcher.add((double) this.reportingValue); + } + + try { + // update to power... + this.lastReportedValue + = (long) this.getProxy().getEnergy().getStoredPower(); + this.updateState(); + + // no more item stuff.. + this.getProxy().getStorage().getItemInventory().removeListener(this); + } catch (final GridAccessException e) { + // :P + } + + return; + } + + try { + if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0 || myStack == null) { + this.getProxy().getStorage().getItemInventory().addListener( + this, this.getProxy().getGrid() + ); + } else { + this.getProxy().getStorage().getItemInventory().removeListener(this); + + if (this.myWatcher != null) { + this.myWatcher.add(myStack); + } + } + + this.updateReportingValue(this.getProxy().getStorage().getItemInventory()); + } catch (final GridAccessException e) { + // >.> + } + } + + private void updateReportingValue(final IMEMonitor monitor) { + final IAEItemStack myStack = this.config.getAEStackInSlot(0); + + if (myStack == null) { + this.lastReportedValue = 0; + for (final IAEItemStack st : monitor.getStorageList()) { + this.lastReportedValue += st.getStackSize(); + } + } else if (this.getInstalledUpgrades(Upgrades.FUZZY) > 0) { + this.lastReportedValue = 0; + final FuzzyMode fzMode + = (FuzzyMode) this.getConfigManager().getSetting(Settings.FUZZY_MODE); + final Collection fuzzyList + = monitor.getStorageList().findFuzzy(myStack, fzMode); + for (final IAEItemStack st : fuzzyList) { + this.lastReportedValue += st.getStackSize(); + } + } else { + final IAEItemStack r = monitor.getStorageList().findPrecise(myStack); + if (r == null) { + this.lastReportedValue = 0; + } else { + this.lastReportedValue = r.getStackSize(); + } + } + + this.updateState(); + } + + @Override + public void updateWatcher(final IStackWatcher newWatcher) { + this.myWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onStackChange( + final IItemList o, + final IAEStack fullStack, + final IAEStack diffStack, + final BaseActionSource src, + final StorageChannel chan + ) { + 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(final IEnergyWatcher newWatcher) { + this.myEnergyWatcher = newWatcher; + this.configureWatchers(); + } + + @Override + public void onThresholdPass(final IEnergyGrid energyGrid) { + this.lastReportedValue = (long) energyGrid.getStoredPower(); + this.updateState(); + } + + @Override + public boolean isValid(final Object effectiveGrid) { + try { + return this.getProxy().getGrid() == effectiveGrid; + } catch (final GridAccessException e) { + return false; + } + } + + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource actionSource + ) { + this.updateReportingValue((IMEMonitor) monitor); + } + + @Override + public void onListUpdate() { + try { + this.updateReportingValue(this.getProxy().getStorage().getItemInventory()); + } catch (final GridAccessException e) { + // ;P + } + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(7, 7, 11, 9, 9, 16); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture(this.getItemStack().getIconIndex()); + Tessellator.instance.startDrawingQuads(); + this.renderTorchAtAngle(0, -0.5, 0); + Tessellator.instance.draw(); + // rh.setBounds( 7, 7, 10, 9, 9, 15 ); + // rh.renderInventoryBox( renderer ); + } + + private void renderTorchAtAngle(double baseX, double baseY, double baseZ) { + final boolean isOn = this.isLevelEmitterOn(); + final IIcon offTexture = this.getItemStack().getIconIndex(); + final IIcon IIcon + = (isOn ? CableBusTextures.LevelEmitterTorchOn.getIcon() : offTexture); + // + this.centerX = baseX + 0.5; + this.centerY = baseY + 0.5; + this.centerZ = baseZ + 0.5; + + baseY += 7.0 / 16.0; + + // double par11 = 0; + + /* + * double d5 = (double)IIcon.func_94209_e(); double d6 = + * (double)IIcon.func_94206_g(); double d7 = (double)IIcon.func_94212_f(); double + * d8 = (double)IIcon.func_94210_h(); double d9 = + * (double)IIcon.func_94214_a(7.0D); double d10 = + * (double)IIcon.func_94207_b(6.0D); double d11 = + * (double)IIcon.func_94214_a(9.0D); double d12 = + * (double)IIcon.func_94207_b(8.0D); double d13 = + * (double)IIcon.func_94214_a(7.0D); double d14 = + * (double)IIcon.func_94207_b(13.0D); double d15 = + * (double)IIcon.func_94214_a(9.0D); double d16 = + * (double)IIcon.func_94207_b(15.0D); + */ + + final float var16 = IIcon.getMinU(); + final float var17 = IIcon.getMaxU(); + final float var18 = IIcon.getMinV(); + final float var19 = IIcon.getMaxV(); + /* + * float var16 = (float)var14 / 256.0F; float var17 = ((float)var14 + 15.99F) / + * 256.0F; float var18 = (float)var15 / 256.0F; float var19 = ((float)var15 + * + 15.99F) / 256.0F; + */ + final double var20b = offTexture.getInterpolatedU(7.0D); + final double var24b = offTexture.getInterpolatedU(9.0D); + + final double var20 = IIcon.getInterpolatedU(7.0D); + final double var24 = IIcon.getInterpolatedU(9.0D); + final double var22 = IIcon.getInterpolatedV(6.0D + (isOn ? 0 : 1.0D)); + final double var26 = IIcon.getInterpolatedV(8.0D + (isOn ? 0 : 1.0D)); + final double var28 = IIcon.getInterpolatedU(7.0D); + final double var30 = IIcon.getInterpolatedV(13.0D); + final double var32 = IIcon.getInterpolatedU(9.0D); + final double var34 = IIcon.getInterpolatedV(15.0D); + + final double var22b = IIcon.getInterpolatedV(9.0D); + final double var26b = IIcon.getInterpolatedV(11.0D); + + baseX += 0.5D; + baseZ += 0.5D; + final double var36 = baseX - 0.5D; + final double var38 = baseX + 0.5D; + final double var40 = baseZ - 0.5D; + final double var42 = baseZ + 0.5D; + + double toff = 0.0d; + + if (!isOn) { + toff = 1.0d / 16.0d; + } + + final Tessellator var12 = Tessellator.instance; + if (isOn) { + var12.setColorOpaque_F(1.0F, 1.0F, 1.0F); + var12.setBrightness(11 << 20 | 11 << 4); + } + + final double TorchLen = 0.625D; + final double var44 = 0.0625D; + final double Zero = 0; + final double par10 = 0; + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) - var44, + var20, + var22 + ); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) + var44, + var20, + var26 + ); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) + var44, + var24, + var26 + ); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + TorchLen - toff, + baseZ + par10 * (1.0D - TorchLen) - var44, + var24, + var22 + ); + + final double var422 = 0.1915D + 1.0 / 16.0; + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) - var44, + var24b, + var22b + ); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) + var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) + var44, + var24b, + var26b + ); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) + var44, + var20b, + var26b + ); + this.addVertexWithUV( + baseX + Zero * (1.0D - TorchLen) - var44, + baseY + var422, + baseZ + par10 * (1.0D - TorchLen) - var44, + var20b, + var22b + ); + + this.addVertexWithUV( + baseX + var44 + Zero, baseY, baseZ - var44 + par10, var32, var30 + ); + this.addVertexWithUV( + baseX + var44 + Zero, baseY, baseZ + var44 + par10, var32, var34 + ); + this.addVertexWithUV( + baseX - var44 + Zero, baseY, baseZ + var44 + par10, var28, var34 + ); + this.addVertexWithUV( + baseX - var44 + Zero, baseY, baseZ - var44 + par10, var28, var30 + ); + + this.addVertexWithUV(baseX - var44, baseY + 1.0D, var40, var16, var18); + this.addVertexWithUV( + baseX - var44 + Zero, baseY + 0.0D, var40 + par10, var16, var19 + ); + this.addVertexWithUV( + baseX - var44 + Zero, baseY + 0.0D, var42 + par10, var17, var19 + ); + this.addVertexWithUV(baseX - var44, baseY + 1.0D, var42, var17, var18); + + this.addVertexWithUV(baseX + var44, baseY + 1.0D, var42, var16, var18); + this.addVertexWithUV( + baseX + Zero + var44, baseY + 0.0D, var42 + par10, var16, var19 + ); + this.addVertexWithUV( + baseX + Zero + var44, baseY + 0.0D, var40 + par10, var17, var19 + ); + this.addVertexWithUV(baseX + var44, baseY + 1.0D, var40, var17, var18); + + this.addVertexWithUV(var36, baseY + 1.0D, baseZ + var44, var16, var18); + this.addVertexWithUV( + var36 + Zero, baseY + 0.0D, baseZ + var44 + par10, var16, var19 + ); + this.addVertexWithUV( + var38 + Zero, baseY + 0.0D, baseZ + var44 + par10, var17, var19 + ); + this.addVertexWithUV(var38, baseY + 1.0D, baseZ + var44, var17, var18); + + this.addVertexWithUV(var38, baseY + 1.0D, baseZ - var44, var16, var18); + this.addVertexWithUV( + var38 + Zero, baseY + 0.0D, baseZ - var44 + par10, var16, var19 + ); + this.addVertexWithUV( + var36 + Zero, baseY + 0.0D, baseZ - var44 + par10, var17, var19 + ); + this.addVertexWithUV(var36, baseY + 1.0D, baseZ - var44, var17, var18); + } + + private void + addVertexWithUV(double x, double y, double z, final double u, final double v) { + final Tessellator var12 = Tessellator.instance; + + x -= this.centerX; + y -= this.centerY; + z -= this.centerZ; + + if (this.getSide() == ForgeDirection.DOWN) { + y = -y; + z = -z; + } + + if (this.getSide() == ForgeDirection.EAST) { + final double m = x; + x = y; + y = m; + y = -y; + } + + if (this.getSide() == ForgeDirection.WEST) { + final double m = x; + x = -y; + y = m; + } + + if (this.getSide() == ForgeDirection.SOUTH) { + final double m = z; + z = y; + y = m; + y = -y; + } + + if (this.getSide() == ForgeDirection.NORTH) { + final double m = z; + z = -y; + y = m; + } + + x += this.centerX; // + orientation.offsetX * 0.4; + y += this.centerY; // + orientation.offsetY * 0.4; + z += this.centerZ; // + orientation.offsetZ * 0.4; + + var12.addVertexWithUV(x, y, z, u, v); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + rh.setTexture(this.getItemStack().getIconIndex()); + // rh.setTexture( CableBusTextures.ItemPartLevelEmitterOn.getIcon() ); + + // rh.setBounds( 2, 2, 14, 14, 14, 16 ); + // rh.renderBlock( x, y, z, renderer ); + + // rh.setBounds( 7, 7, 10, 9, 9, 15 ); + // rh.renderBlock( x, y, z, renderer ); + + renderer.renderAllFaces = true; + + final Tessellator tess = Tessellator.instance; + tess.setBrightness(rh.getBlock().getMixedBrightnessForBlock( + this.getHost().getTile().getWorldObj(), x, y, z + )); + tess.setColorOpaque_F(1.0F, 1.0F, 1.0F); + + this.renderTorchAtAngle(x, y, z); + + renderer.renderAllFaces = false; + + rh.setBounds(7, 7, 11, 9, 9, 12); + this.renderLights(x, y, z, rh, renderer); + + // 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 randomDisplayTick( + final World world, final int x, final int y, final int z, final Random r + ) { + if (this.isLevelEmitterOn()) { + final ForgeDirection d = this.getSide(); + + final double d0 = d.offsetX * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d1 = d.offsetY * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + final double d2 = d.offsetZ * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + + world.spawnParticle( + "reddust", 0.5 + x + d0, 0.5 + y + d1, 0.5 + z + d2, 0.0D, 0.0D, 0.0D + ); + } + } + + @Override + public int cableConnectionRenderTo() { + return 16; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI( + player, + this.getHost().getTile(), + this.getSide(), + GuiBridge.GUI_LEVEL_EMITTER + ); + return true; + } + + return false; + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + this.configureWatchers(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final 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() { + return true; + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.lastReportedValue = data.getLong("lastReportedValue"); + this.reportingValue = data.getLong("reportingValue"); + this.prevState = data.getBoolean("prevState"); + this.config.readFromNBT(data, "config"); + } + + @Override + public void writeToNBT(final 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(final String name) { + if (name.equals("config")) { + return this.config; + } + + return super.getInventoryByName(name); + } + + @Override + public boolean pushPattern( + final ICraftingPatternDetails patternDetails, final InventoryCrafting table + ) { + return false; + } + + @Override + public boolean isBusy() { + return true; + } + + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + if (this.getInstalledUpgrades(Upgrades.CRAFTING) > 0) { + if (this.getConfigManager().getSetting(Settings.CRAFT_VIA_REDSTONE) + == YesNo.YES) { + final IAEItemStack what = this.config.getAEStackInSlot(0); + 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 7653dfa8..cf41c237 100644 --- a/src/main/java/appeng/parts/automation/PartSharedItemBus.java +++ b/src/main/java/appeng/parts/automation/PartSharedItemBus.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.RedstoneMode; import appeng.api.config.Upgrades; import appeng.api.networking.ticking.IGridTickable; @@ -32,158 +31,141 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public abstract class PartSharedItemBus extends PartUpgradeable implements IGridTickable { + private final AppEngInternalAEInventory config + = new AppEngInternalAEInventory(this, 9); + private int adaptorHash = 0; + private InventoryAdaptor adaptor; + private boolean lastRedstone = false; -public abstract class PartSharedItemBus extends PartUpgradeable implements IGridTickable -{ + public PartSharedItemBus(final ItemStack is) { + super(is); + } - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 9 ); - private int adaptorHash = 0; - private InventoryAdaptor adaptor; - private boolean lastRedstone = false; + @Override + public void upgradesChanged() { + this.updateState(); + } - public PartSharedItemBus( final ItemStack is ) - { - super( is ); - } + @Override + public void readFromNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.readFromNBT(extra); + this.getConfig().readFromNBT(extra, "config"); + } - @Override - public void upgradesChanged() - { - this.updateState(); - } + @Override + public void writeToNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.writeToNBT(extra); + this.getConfig().writeToNBT(extra, "config"); + } - @Override - public void readFromNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.getConfig().readFromNBT( extra, "config" ); - } + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.getConfig(); + } - @Override - public void writeToNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.getConfig().writeToNBT( extra, "config" ); - } + return super.getInventoryByName(name); + } - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.getConfig(); - } + @Override + public void onNeighborChanged() { + this.updateState(); + if (this.lastRedstone != this.getHost().hasRedstone(this.getSide())) { + this.lastRedstone = !this.lastRedstone; + if (this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE) { + this.doBusWork(); + } + } + } - return super.getInventoryByName( name ); - } + protected InventoryAdaptor getHandler() { + final TileEntity self = this.getHost().getTile(); + final TileEntity target = this.getTileEntity( + self, + self.xCoord + this.getSide().offsetX, + self.yCoord + this.getSide().offsetY, + self.zCoord + this.getSide().offsetZ + ); - @Override - public void onNeighborChanged() - { - this.updateState(); - if( this.lastRedstone != this.getHost().hasRedstone( this.getSide() ) ) - { - this.lastRedstone = !this.lastRedstone; - if( this.lastRedstone && this.getRSMode() == RedstoneMode.SIGNAL_PULSE ) - { - this.doBusWork(); - } - } - } + final int newAdaptorHash = Platform.generateTileHash(target); - protected InventoryAdaptor getHandler() - { - final TileEntity self = this.getHost().getTile(); - final TileEntity target = this.getTileEntity( self, self.xCoord + this.getSide().offsetX, self.yCoord + this.getSide().offsetY, self.zCoord + this.getSide().offsetZ ); + if (this.adaptorHash == newAdaptorHash && newAdaptorHash != 0) { + return this.adaptor; + } - final int newAdaptorHash = Platform.generateTileHash( target ); + this.adaptorHash = newAdaptorHash; + this.adaptor = InventoryAdaptor.getAdaptor(target, this.getSide().getOpposite()); - if( this.adaptorHash == newAdaptorHash && newAdaptorHash != 0 ) - { - return this.adaptor; - } + return this.adaptor; + } - this.adaptorHash = newAdaptorHash; - this.adaptor = InventoryAdaptor.getAdaptor( target, this.getSide().getOpposite() ); + protected int availableSlots() { + return Math.min( + 1 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 4, + this.getConfig().getSizeInventory() + ); + } - return this.adaptor; - } + protected int calculateItemsToSend() { + switch (this.getInstalledUpgrades(Upgrades.SPEED)) { + default: + case 0: + return 1; + case 1: + return 8; + case 2: + return 32; + case 3: + return 64; + case 4: + return 96; + } + } - protected int availableSlots() - { - return Math.min( 1 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 4, this.getConfig().getSizeInventory() ); - } + /** + * Checks if the bus can actually do something. + *

+ * Currently this tests if the chunk for the target is actually loaded. + * + * @return true, if the the bus should do its work. + */ + protected boolean canDoBusWork() { + final TileEntity self = this.getHost().getTile(); + final World world = self.getWorldObj(); + final int xCoordinate = self.xCoord + this.getSide().offsetX; + final int zCoordinate = self.zCoord + this.getSide().offsetZ; - protected int calculateItemsToSend() - { - switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) - { - default: - case 0: - return 1; - case 1: - return 8; - case 2: - return 32; - case 3: - return 64; - case 4: - return 96; - } - } + return world != null + && world.getChunkProvider().chunkExists(xCoordinate >> 4, zCoordinate >> 4); + } - /** - * Checks if the bus can actually do something. - *

- * Currently this tests if the chunk for the target is actually loaded. - * - * @return true, if the the bus should do its work. - */ - protected boolean canDoBusWork() - { - final TileEntity self = this.getHost().getTile(); - final World world = self.getWorldObj(); - final int xCoordinate = self.xCoord + this.getSide().offsetX; - final int zCoordinate = self.zCoord + this.getSide().offsetZ; + private void updateState() { + try { + if (!this.isSleeping()) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } - return world != null && world.getChunkProvider().chunkExists( xCoordinate >> 4, zCoordinate >> 4 ); - } + private TileEntity + getTileEntity(final TileEntity self, final int x, final int y, final int z) { + final World w = self.getWorldObj(); - private void updateState() - { - try - { - if( !this.isSleeping() ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } + if (w.getChunkProvider().chunkExists(x >> 4, z >> 4)) { + return w.getTileEntity(x, y, z); + } - private TileEntity getTileEntity( final TileEntity self, final int x, final int y, final int z ) - { - final World w = self.getWorldObj(); + return null; + } - if( w.getChunkProvider().chunkExists( x >> 4, z >> 4 ) ) - { - return w.getTileEntity( x, y, z ); - } + protected abstract TickRateModulation doBusWork(); - return null; - } - - protected abstract TickRateModulation doBusWork(); - - AppEngInternalAEInventory getConfig() - { - return this.config; - } + AppEngInternalAEInventory getConfig() { + return this.config; + } } diff --git a/src/main/java/appeng/parts/automation/PartUpgradeable.java b/src/main/java/appeng/parts/automation/PartUpgradeable.java index b73582af..8efafb79 100644 --- a/src/main/java/appeng/parts/automation/PartUpgradeable.java +++ b/src/main/java/appeng/parts/automation/PartUpgradeable.java @@ -18,6 +18,7 @@ package appeng.parts.automation; +import java.util.List; import appeng.api.config.RedstoneMode; import appeng.api.config.Upgrades; @@ -30,142 +31,123 @@ import appeng.util.IConfigManagerHost; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.List; +public abstract class PartUpgradeable + extends PartBasicState implements IAEAppEngInventory, IConfigManagerHost { + private final IConfigManager manager; + private final UpgradeInventory upgrades; + public PartUpgradeable(final ItemStack is) { + super(is); + this.upgrades = new StackUpgradeInventory( + this.getItemStack(), this, this.getUpgradeSlots() + ); + this.upgrades.setMaxStackSize(1); + this.manager = new ConfigManager(this); + } -public abstract class PartUpgradeable extends PartBasicState implements IAEAppEngInventory, IConfigManagerHost -{ - private final IConfigManager manager; - private final UpgradeInventory upgrades; + protected int getUpgradeSlots() { + return 4; + } - public PartUpgradeable( final ItemStack is ) - { - super( is ); - this.upgrades = new StackUpgradeInventory( this.getItemStack(), this, this.getUpgradeSlots() ); - this.upgrades.setMaxStackSize( 1 ); - this.manager = new ConfigManager( this ); - } + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) {} - protected int getUpgradeSlots() - { - return 4; - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) { + if (inv == this.upgrades) { + this.upgradesChanged(); + } + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { + public void upgradesChanged() {} - } + protected boolean isSleeping() { + if (this.getInstalledUpgrades(Upgrades.REDSTONE) > 0) { + switch (this.getRSMode()) { + case IGNORE: + return false; - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.upgrades ) - { - this.upgradesChanged(); - } - } + case HIGH_SIGNAL: + if (this.getHost().hasRedstone(this.getSide())) { + return false; + } - public void upgradesChanged() - { + break; - } + case LOW_SIGNAL: + if (!this.getHost().hasRedstone(this.getSide())) { + return false; + } - protected boolean isSleeping() - { - if( this.getInstalledUpgrades( Upgrades.REDSTONE ) > 0 ) - { - switch( this.getRSMode() ) - { - case IGNORE: - return false; + break; - case HIGH_SIGNAL: - if( this.getHost().hasRedstone( this.getSide() ) ) - { - return false; - } + case SIGNAL_PULSE: + default: + break; + } - break; + return true; + } - case LOW_SIGNAL: - if( !this.getHost().hasRedstone( this.getSide() ) ) - { - return false; - } + return false; + } - break; + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } - case SIGNAL_PULSE: - default: - break; - } + @Override + public boolean canConnectRedstone() { + return this.upgrades.getMaxInstalled(Upgrades.REDSTONE) > 0; + } - return true; - } + @Override + public void readFromNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.readFromNBT(extra); + this.manager.readFromNBT(extra); + this.upgrades.readFromNBT(extra, "upgrades"); + } - return false; - } + @Override + public void writeToNBT(final net.minecraft.nbt.NBTTagCompound extra) { + super.writeToNBT(extra); + this.manager.writeToNBT(extra); + this.upgrades.writeToNBT(extra, "upgrades"); + } - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } + @Override + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.upgrades) { + if (is != null) { + drops.add(is); + } + } + } - @Override - public boolean canConnectRedstone() - { - return this.upgrades.getMaxInstalled( Upgrades.REDSTONE ) > 0; - } + @Override + public IConfigManager getConfigManager() { + return this.manager; + } - @Override - public void readFromNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.manager.readFromNBT( extra ); - this.upgrades.readFromNBT( extra, "upgrades" ); - } + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } - @Override - public void writeToNBT( final net.minecraft.nbt.NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.manager.writeToNBT( extra ); - this.upgrades.writeToNBT( extra, "upgrades" ); - } + return null; + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.upgrades ) - { - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - public RedstoneMode getRSMode() - { - return null; - } + 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 1ffebfa2..364ec3a1 100644 --- a/src/main/java/appeng/parts/automation/StackUpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/StackUpgradeInventory.java @@ -1,36 +1,31 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.tile.inventory.IAEAppEngInventory; import appeng.util.Platform; import net.minecraft.item.ItemStack; +public class StackUpgradeInventory extends UpgradeInventory { + private final ItemStack stack; -public class StackUpgradeInventory extends UpgradeInventory -{ - private final ItemStack stack; + public StackUpgradeInventory( + final ItemStack stack, final IAEAppEngInventory inventory, final int s + ) { + super(inventory, s); + this.stack = stack; + } - public StackUpgradeInventory( final ItemStack stack, final IAEAppEngInventory inventory, final int s ) - { - super( inventory, s ); - this.stack = stack; - } + @Override + public int getMaxInstalled(final Upgrades upgrades) { + int max = 0; - @Override - public int getMaxInstalled( final Upgrades upgrades ) - { - int max = 0; + for (final ItemStack is : upgrades.getSupported().keySet()) { + if (Platform.isSameItem(this.stack, is)) { + max = upgrades.getSupported().get(is); + break; + } + } - for( final ItemStack is : upgrades.getSupported().keySet() ) - { - if( Platform.isSameItem( this.stack, is ) ) - { - max = upgrades.getSupported().get( is ); - break; - } - } - - return max; - } + return max; + } } diff --git a/src/main/java/appeng/parts/automation/UpgradeInventory.java b/src/main/java/appeng/parts/automation/UpgradeInventory.java index b77def70..7bef44c4 100644 --- a/src/main/java/appeng/parts/automation/UpgradeInventory.java +++ b/src/main/java/appeng/parts/automation/UpgradeInventory.java @@ -18,7 +18,6 @@ package appeng.parts.automation; - import appeng.api.config.Upgrades; import appeng.api.implementations.items.IUpgradeModule; import appeng.tile.inventory.AppEngInternalInventory; @@ -30,151 +29,146 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; +public abstract class UpgradeInventory + extends AppEngInternalInventory implements IAEAppEngInventory { + private final IAEAppEngInventory parent; -public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory -{ - private final IAEAppEngInventory parent; + private boolean cached = false; + private int fuzzyUpgrades = 0; + private int speedUpgrades = 0; + private int redstoneUpgrades = 0; + private int capacityUpgrades = 0; + private int inverterUpgrades = 0; + private int craftingUpgrades = 0; - private boolean cached = false; - private int fuzzyUpgrades = 0; - private int speedUpgrades = 0; - private int redstoneUpgrades = 0; - private int capacityUpgrades = 0; - private int inverterUpgrades = 0; - private int craftingUpgrades = 0; + public UpgradeInventory(final IAEAppEngInventory parent, final int s) { + super(null, s); + this.setTileEntity(this); + this.parent = parent; + } - public UpgradeInventory( final IAEAppEngInventory parent, final int s ) - { - super( null, s ); - this.setTileEntity( this ); - this.parent = parent; - } + @Override + protected boolean eventsEnabled() { + return true; + } - @Override - protected boolean eventsEnabled() - { - return true; - } + @Override + public int getInventoryStackLimit() { + return 1; + } - @Override - public int getInventoryStackLimit() - { - return 1; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (itemstack == null) { + return false; + } + final Item it = itemstack.getItem(); + if (it instanceof IUpgradeModule) { + final Upgrades u = ((IUpgradeModule) it).getType(itemstack); + if (u != null) { + return this.getInstalledUpgrades(u) < this.getMaxInstalled(u); + } + } + return false; + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( itemstack == null ) - { - return false; - } - final Item it = itemstack.getItem(); - if( it instanceof IUpgradeModule ) - { - final Upgrades u = ( (IUpgradeModule) it ).getType( itemstack ); - if( u != null ) - { - return this.getInstalledUpgrades( u ) < this.getMaxInstalled( u ); - } - } - return false; - } + public int getInstalledUpgrades(final Upgrades u) { + if (!this.cached) { + this.updateUpgradeInfo(); + } - public int getInstalledUpgrades( final Upgrades u ) - { - if( !this.cached ) - { - this.updateUpgradeInfo(); - } + switch (u) { + case CAPACITY: + return this.capacityUpgrades; + case FUZZY: + return this.fuzzyUpgrades; + case REDSTONE: + return this.redstoneUpgrades; + case SPEED: + return this.speedUpgrades; + case INVERTER: + return this.inverterUpgrades; + case CRAFTING: + return this.craftingUpgrades; + default: + return 0; + } + } - switch( u ) - { - case CAPACITY: - return this.capacityUpgrades; - case FUZZY: - return this.fuzzyUpgrades; - case REDSTONE: - return this.redstoneUpgrades; - case SPEED: - return this.speedUpgrades; - case INVERTER: - return this.inverterUpgrades; - case CRAFTING: - return this.craftingUpgrades; - default: - return 0; - } - } + public abstract int getMaxInstalled(Upgrades upgrades); - public abstract int getMaxInstalled( Upgrades upgrades ); + private void updateUpgradeInfo() { + this.cached = true; + this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades + = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0; - private void updateUpgradeInfo() - { - this.cached = true; - this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0; + for (final ItemStack is : this) { + if (is == null || is.getItem() == null + || !(is.getItem() instanceof IUpgradeModule)) { + continue; + } - for( final ItemStack is : this ) - { - if( is == null || is.getItem() == null || !( is.getItem() instanceof IUpgradeModule ) ) - { - continue; - } + final Upgrades myUpgrade = ((IUpgradeModule) is.getItem()).getType(is); + switch (myUpgrade) { + case CAPACITY: + this.capacityUpgrades++; + break; + case FUZZY: + this.fuzzyUpgrades++; + break; + case REDSTONE: + this.redstoneUpgrades++; + break; + case SPEED: + this.speedUpgrades++; + break; + case INVERTER: + this.inverterUpgrades++; + break; + case CRAFTING: + this.craftingUpgrades++; + break; + default: + break; + } + } - final Upgrades myUpgrade = ( (IUpgradeModule) is.getItem() ).getType( is ); - switch( myUpgrade ) - { - case CAPACITY: - this.capacityUpgrades++; - break; - case FUZZY: - this.fuzzyUpgrades++; - break; - case REDSTONE: - this.redstoneUpgrades++; - break; - case SPEED: - this.speedUpgrades++; - break; - case INVERTER: - this.inverterUpgrades++; - break; - case CRAFTING: - this.craftingUpgrades++; - break; - default: - break; - } - } + this.capacityUpgrades + = Math.min(this.capacityUpgrades, this.getMaxInstalled(Upgrades.CAPACITY)); + this.fuzzyUpgrades + = Math.min(this.fuzzyUpgrades, this.getMaxInstalled(Upgrades.FUZZY)); + this.redstoneUpgrades + = Math.min(this.redstoneUpgrades, this.getMaxInstalled(Upgrades.REDSTONE)); + this.speedUpgrades + = Math.min(this.speedUpgrades, this.getMaxInstalled(Upgrades.SPEED)); + this.inverterUpgrades + = Math.min(this.inverterUpgrades, this.getMaxInstalled(Upgrades.INVERTER)); + this.craftingUpgrades + = Math.min(this.craftingUpgrades, this.getMaxInstalled(Upgrades.CRAFTING)); + } - this.capacityUpgrades = Math.min( this.capacityUpgrades, this.getMaxInstalled( Upgrades.CAPACITY ) ); - this.fuzzyUpgrades = Math.min( this.fuzzyUpgrades, this.getMaxInstalled( Upgrades.FUZZY ) ); - this.redstoneUpgrades = Math.min( this.redstoneUpgrades, this.getMaxInstalled( Upgrades.REDSTONE ) ); - this.speedUpgrades = Math.min( this.speedUpgrades, this.getMaxInstalled( Upgrades.SPEED ) ); - this.inverterUpgrades = Math.min( this.inverterUpgrades, this.getMaxInstalled( Upgrades.INVERTER ) ); - this.craftingUpgrades = Math.min( this.craftingUpgrades, this.getMaxInstalled( Upgrades.CRAFTING ) ); - } + @Override + public void readFromNBT(final NBTTagCompound target) { + super.readFromNBT(target); + this.updateUpgradeInfo(); + } - @Override - public void readFromNBT( final NBTTagCompound target ) - { - super.readFromNBT( target ); - this.updateUpgradeInfo(); - } + @Override + public void saveChanges() { + this.parent.saveChanges(); + } - @Override - public void saveChanges() - { - this.parent.saveChanges(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.cached = false; - if( this.parent != null && Platform.isServer() ) - { - this.parent.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) { + this.cached = false; + 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 1ffa285e..797151ad 100644 --- a/src/main/java/appeng/parts/layers/InvLayerData.java +++ b/src/main/java/appeng/parts/layers/InvLayerData.java @@ -18,128 +18,105 @@ package appeng.parts.layers; +import java.util.List; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; -import java.util.List; +public class InvLayerData { + // a simple empty array for empty stuff.. + private static final int[] NULL_SIDES = {}; + // cache of inventory state. + private final int[][] sides; + private final List inventories; + private final List slots; -public class InvLayerData -{ + public InvLayerData( + final int[][] a, final List b, final List c + ) { + this.sides = a; + this.inventories = b; + this.slots = c; + } - // a simple empty array for empty stuff.. - private static final int[] NULL_SIDES = {}; + ItemStack decreaseStackSize(final int slot, final int amount) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).decreaseStackSize(amount); + } - // cache of inventory state. - private final int[][] sides; - private final List inventories; - private final List slots; + return null; + } - public InvLayerData( final int[][] a, final List b, final List c ) - { - this.sides = a; - this.inventories = b; - this.slots = c; - } + /** + * check if a slot index is valid, prevent crashes from bad code :) + * + * @param slot slot index + * @return true, if the slot exists. + */ + private boolean isSlotValid(final int slot) { + return this.slots != null && slot >= 0 && slot < this.slots.size(); + } - ItemStack decreaseStackSize( final int slot, final int amount ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).decreaseStackSize( amount ); - } + int getSizeInventory() { + if (this.slots == null) { + return 0; + } - return null; - } + return this.slots.size(); + } - /** - * check if a slot index is valid, prevent crashes from bad code :) - * - * @param slot slot index - * @return true, if the slot exists. - */ - private boolean isSlotValid( final int slot ) - { - return this.slots != null && slot >= 0 && slot < this.slots.size(); - } + ItemStack getStackInSlot(final int slot) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).getStackInSlot(); + } - int getSizeInventory() - { - if( this.slots == null ) - { - return 0; - } + return null; + } - return this.slots.size(); - } + boolean isItemValidForSlot(final int slot, final ItemStack itemstack) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).isItemValidForSlot(itemstack); + } - ItemStack getStackInSlot( final int slot ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).getStackInSlot(); - } + return false; + } - return null; - } + void setInventorySlotContents(final int slot, final ItemStack itemstack) { + if (this.isSlotValid(slot)) { + this.slots.get(slot).setInventorySlotContents(itemstack); + } + } - boolean isItemValidForSlot( final int slot, final ItemStack itemstack ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).isItemValidForSlot( itemstack ); - } + boolean canExtractItem(final int slot, final ItemStack itemstack, final int side) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).canExtractItem(itemstack, side); + } - return false; - } + return false; + } - void setInventorySlotContents( final int slot, final ItemStack itemstack ) - { - if( this.isSlotValid( slot ) ) - { - this.slots.get( slot ).setInventorySlotContents( itemstack ); - } - } + boolean canInsertItem(final int slot, final ItemStack itemstack, final int side) { + if (this.isSlotValid(slot)) { + return this.slots.get(slot).canInsertItem(itemstack, side); + } - boolean canExtractItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).canExtractItem( itemstack, side ); - } + return false; + } - return false; - } + void markDirty() { + if (this.inventories != null) { + for (final IInventory inv : this.inventories) { + inv.markDirty(); + } + } + } - boolean canInsertItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.isSlotValid( slot ) ) - { - return this.slots.get( slot ).canInsertItem( itemstack, side ); - } - - return false; - } - - void markDirty() - { - if( this.inventories != null ) - { - for( final IInventory inv : this.inventories ) - { - inv.markDirty(); - } - } - } - - int[] getAccessibleSlotsFromSide( final int side ) - { - if( this.sides == null || side < 0 || side > 5 ) - { - return NULL_SIDES; - } - return this.sides[side]; - } + int[] getAccessibleSlotsFromSide(final int side) { + 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 7cc84985..5038b74d 100644 --- a/src/main/java/appeng/parts/layers/InvSot.java +++ b/src/main/java/appeng/parts/layers/InvSot.java @@ -18,50 +18,39 @@ package appeng.parts.layers; - import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; +public class InvSot { + private final ISidedInventory partInv; + private final int index; -public class InvSot -{ + public InvSot(final ISidedInventory part, final int slot) { + this.partInv = part; + this.index = slot; + } - private final ISidedInventory partInv; - private final int index; + ItemStack decreaseStackSize(final int j) { + return this.partInv.decrStackSize(this.index, j); + } - public InvSot( final ISidedInventory part, final int slot ) - { - this.partInv = part; - this.index = slot; - } + ItemStack getStackInSlot() { + return this.partInv.getStackInSlot(this.index); + } - ItemStack decreaseStackSize( final int j ) - { - return this.partInv.decrStackSize( this.index, j ); - } + boolean isItemValidForSlot(final ItemStack itemstack) { + return this.partInv.isItemValidForSlot(this.index, itemstack); + } - ItemStack getStackInSlot() - { - return this.partInv.getStackInSlot( this.index ); - } + void setInventorySlotContents(final ItemStack itemstack) { + this.partInv.setInventorySlotContents(this.index, itemstack); + } - boolean isItemValidForSlot( final ItemStack itemstack ) - { - return this.partInv.isItemValidForSlot( this.index, itemstack ); - } + boolean canExtractItem(final ItemStack itemstack, final int side) { + return this.partInv.canExtractItem(this.index, itemstack, side); + } - void setInventorySlotContents( final ItemStack itemstack ) - { - this.partInv.setInventorySlotContents( this.index, itemstack ); - } - - boolean canExtractItem( final ItemStack itemstack, final int side ) - { - return this.partInv.canExtractItem( this.index, itemstack, side ); - } - - boolean canInsertItem( final ItemStack itemstack, final int side ) - { - return this.partInv.canInsertItem( this.index, itemstack, side ); - } + boolean canInsertItem(final ItemStack itemstack, final 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 7f512027..7618e2d9 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergyHandler.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import cofh.api.energy.IEnergyConnection; @@ -27,67 +26,58 @@ import cofh.api.energy.IEnergyProvider; import cofh.api.energy.IEnergyReceiver; import net.minecraftforge.common.util.ForgeDirection; +public class LayerIEnergyHandler extends LayerBase implements IEnergyHandler { + @Override + public int receiveEnergy( + final ForgeDirection from, final int maxReceive, final boolean simulate + ) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyReceiver) { + return ((IEnergyReceiver) part).receiveEnergy(from, maxReceive, simulate); + } -public class LayerIEnergyHandler extends LayerBase implements IEnergyHandler -{ + return 0; + } - @Override - public int receiveEnergy( final ForgeDirection from, final int maxReceive, final boolean simulate ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyReceiver ) - { - return ( (IEnergyReceiver) part ).receiveEnergy( from, maxReceive, simulate ); - } + @Override + public int extractEnergy( + final ForgeDirection from, final int maxExtract, final boolean simulate + ) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyProvider) { + return ((IEnergyProvider) part).extractEnergy(from, maxExtract, simulate); + } - return 0; - } + return 0; + } - @Override - public int extractEnergy( final ForgeDirection from, final int maxExtract, final boolean simulate ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyProvider ) - { - return ( (IEnergyProvider) part ).extractEnergy( from, maxExtract, simulate ); - } + @Override + public int getEnergyStored(final ForgeDirection from) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyProvider) { + return ((IEnergyProvider) part).getEnergyStored(from); + } - return 0; - } + return 0; + } - @Override - public int getEnergyStored( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyProvider ) - { - return ( (IEnergyProvider) part ).getEnergyStored( from ); - } + @Override + public int getMaxEnergyStored(final ForgeDirection from) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyProvider) { + return ((IEnergyProvider) part).getMaxEnergyStored(from); + } - return 0; - } + return 0; + } - @Override - public int getMaxEnergyStored( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyProvider ) - { - return ( (IEnergyProvider) part ).getMaxEnergyStored( from ); - } + @Override + public boolean canConnectEnergy(final ForgeDirection from) { + final IPart part = this.getPart(from); + if (part instanceof IEnergyConnection) { + return ((IEnergyConnection) part).canConnectEnergy(from); + } - return 0; - } - - @Override - public boolean canConnectEnergy( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IEnergyConnection ) - { - return ( (IEnergyConnection) part ).canConnectEnergy( from ); - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergySink.java b/src/main/java/appeng/parts/layers/LayerIEnergySink.java index 5e9bf45e..3ea90e33 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergySink.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergySink.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.LayerBase; @@ -32,170 +31,144 @@ import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; +public class LayerIEnergySink extends LayerBase implements IEnergySink { + private TileEntity getEnergySinkTile() { + final IPartHost host = (IPartHost) this; + return host.getTile(); + } -public class LayerIEnergySink extends LayerBase implements IEnergySink -{ + private World getEnergySinkWorld() { + if (this.getEnergySinkTile() == null) { + return null; + } - private TileEntity getEnergySinkTile() - { - final IPartHost host = (IPartHost) this; - return host.getTile(); - } + return this.getEnergySinkTile().getWorldObj(); + } - private World getEnergySinkWorld() - { - if( this.getEnergySinkTile() == null ) - { - return null; - } + private boolean isTileValid() { + final TileEntity te = this.getEnergySinkTile(); - return this.getEnergySinkTile().getWorldObj(); - } + if (te == null) { + return false; + } - private boolean isTileValid() - { - final TileEntity te = this.getEnergySinkTile(); + return !te.isInvalid() + && te.getWorldObj().blockExists(te.xCoord, te.yCoord, te.zCoord); + } - if( te == null ) - { - return false; - } + private void addToENet() { + if (this.getEnergySinkWorld() == null) { + return; + } - return !te.isInvalid() && te.getWorldObj().blockExists( te.xCoord, te.yCoord, te.zCoord ); - } + // re-add + this.removeFromENet(); - private void addToENet() - { - if( this.getEnergySinkWorld() == null ) - { - return; - } + if (!this.isInIC2() && Platform.isServer() && this.isTileValid()) { + this.getLayerFlags().add(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post(new ic2.api.energy.event.EnergyTileLoadEvent( + (IEnergyTile) this.getEnergySinkTile() + )); + } + } - // re-add - this.removeFromENet(); + private void removeFromENet() { + if (this.getEnergySinkWorld() == null) { + return; + } - if( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) - { - this.getLayerFlags().add( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergyTile) this.getEnergySinkTile() ) ); - } - } + if (this.isInIC2() && Platform.isServer()) { + this.getLayerFlags().remove(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post(new ic2.api.energy.event.EnergyTileUnloadEvent( + (IEnergyTile) this.getEnergySinkTile() + )); + } + } - private void removeFromENet() - { - if( this.getEnergySinkWorld() == null ) - { - return; - } + private boolean interestedInIC2() { + if (!((IPartHost) this).isInWorld()) { + return false; + } - if( this.isInIC2() && Platform.isServer() ) - { - this.getLayerFlags().remove( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergyTile) this.getEnergySinkTile() ) ); - } - } + int interested = 0; + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergyTile) { + interested++; + } + } + return interested + == 1; // if more then one tile is interested we need to abandon... + } - private boolean interestedInIC2() - { - if( !( (IPartHost) this ).isInWorld() ) - { - return false; - } + @Override + public void partChanged() { + super.partChanged(); - int interested = 0; - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergyTile ) - { - interested++; - } - } - return interested == 1;// if more then one tile is interested we need to abandon... - } + if (this.interestedInIC2()) { + this.addToENet(); + } else { + this.removeFromENet(); + } + } - @Override - public void partChanged() - { - super.partChanged(); + @Override + public boolean + acceptsEnergyFrom(final TileEntity emitter, final ForgeDirection direction) { + if (!this.isInIC2()) { + return false; + } - if( this.interestedInIC2() ) - { - this.addToENet(); - } - else - { - this.removeFromENet(); - } - } + final IPart part = this.getPart(direction); + if (part instanceof IEnergySink) { + return ((IEnergyAcceptor) part).acceptsEnergyFrom(emitter, direction); + } + return false; + } - @Override - public boolean acceptsEnergyFrom( final TileEntity emitter, final ForgeDirection direction ) - { - if( !this.isInIC2() ) - { - return false; - } + private boolean isInIC2() { + return this.getLayerFlags().contains(LayerFlags.IC2_ENET); + } - final IPart part = this.getPart( direction ); - if( part instanceof IEnergySink ) - { - return ( (IEnergyAcceptor) part ).acceptsEnergyFrom( emitter, direction ); - } - return false; - } + @Override + public double getDemandedEnergy() { + if (!this.isInIC2()) { + return 0; + } - private boolean isInIC2() - { - return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); - } + // this is a flawed implementation, that requires a change to the IC2 API. - @Override - public double getDemandedEnergy() - { - if( !this.isInIC2() ) - { - return 0; - } + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySink) { + // use lower number cause ic2 deletes power it sends that isn't received. + return ((IEnergySink) part).getDemandedEnergy(); + } + } - // this is a flawed implementation, that requires a change to the IC2 API. + return 0; + } - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySink ) - { - // use lower number cause ic2 deletes power it sends that isn't received. - return ( (IEnergySink) part ).getDemandedEnergy(); - } - } + @Override + public int getSinkTier() { + return Integer.MAX_VALUE; // no real options here... + } - return 0; - } + @Override + public double injectEnergy( + final ForgeDirection directionFrom, final double amount, final double voltage + ) { + if (!this.isInIC2()) { + return amount; + } - @Override - public int getSinkTier() - { - return Integer.MAX_VALUE; // no real options here... - } + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySink) { + return ((IEnergySink) part).injectEnergy(directionFrom, amount, voltage); + } + } - @Override - public double injectEnergy( final ForgeDirection directionFrom, final double amount, final double voltage ) - { - if( !this.isInIC2() ) - { - return amount; - } - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySink ) - { - return ( (IEnergySink) part ).injectEnergy( directionFrom, amount, voltage ); - } - } - - return amount; - } + return amount; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIEnergySource.java b/src/main/java/appeng/parts/layers/LayerIEnergySource.java index face5309..b18f66d0 100644 --- a/src/main/java/appeng/parts/layers/LayerIEnergySource.java +++ b/src/main/java/appeng/parts/layers/LayerIEnergySource.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import appeng.api.parts.LayerBase; @@ -33,174 +32,144 @@ import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; +public class LayerIEnergySource extends LayerBase implements IEnergySource { + private TileEntity getEnergySourceTile() { + final IPartHost host = (IPartHost) this; + return host.getTile(); + } -public class LayerIEnergySource extends LayerBase implements IEnergySource -{ + private World getEnergySourceWorld() { + if (this.getEnergySourceTile() == null) { + return null; + } + return this.getEnergySourceTile().getWorldObj(); + } - private TileEntity getEnergySourceTile() - { - final IPartHost host = (IPartHost) this; - return host.getTile(); - } + private boolean isTileValid() { + final TileEntity te = this.getEnergySourceTile(); + if (te == null) { + return false; + } + return !te.isInvalid(); + } - private World getEnergySourceWorld() - { - if( this.getEnergySourceTile() == null ) - { - return null; - } - return this.getEnergySourceTile().getWorldObj(); - } + private void addToENet() { + if (this.getEnergySourceWorld() == null) { + return; + } - private boolean isTileValid() - { - final TileEntity te = this.getEnergySourceTile(); - if( te == null ) - { - return false; - } - return !te.isInvalid(); - } + // re-add + this.removeFromENet(); - private void addToENet() - { - if( this.getEnergySourceWorld() == null ) - { - return; - } + if (!this.isInIC2() && Platform.isServer() && this.isTileValid()) { + this.getLayerFlags().add(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post(new ic2.api.energy.event.EnergyTileLoadEvent( + (IEnergyTile) this.getEnergySourceTile() + )); + } + } - // re-add - this.removeFromENet(); + private void removeFromENet() { + if (this.getEnergySourceWorld() == null) { + return; + } - if( !this.isInIC2() && Platform.isServer() && this.isTileValid() ) - { - this.getLayerFlags().add( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileLoadEvent( (IEnergyTile) this.getEnergySourceTile() ) ); - } - } + if (this.isInIC2() && Platform.isServer()) { + this.getLayerFlags().remove(LayerFlags.IC2_ENET); + MinecraftForge.EVENT_BUS.post(new ic2.api.energy.event.EnergyTileUnloadEvent( + (IEnergyTile) this.getEnergySourceTile() + )); + } + } - private void removeFromENet() - { - if( this.getEnergySourceWorld() == null ) - { - return; - } + private boolean interestedInIC2() { + if (!((IPartHost) this).isInWorld()) { + return false; + } - if( this.isInIC2() && Platform.isServer() ) - { - this.getLayerFlags().remove( LayerFlags.IC2_ENET ); - MinecraftForge.EVENT_BUS.post( new ic2.api.energy.event.EnergyTileUnloadEvent( (IEnergyTile) this.getEnergySourceTile() ) ); - } - } + int interested = 0; + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergyTile) { + interested++; + } + } + return interested + == 1; // if more then one tile is interested we need to abandon... + } - private boolean interestedInIC2() - { - if( !( (IPartHost) this ).isInWorld() ) - { - return false; - } + @Override + public void partChanged() { + super.partChanged(); - int interested = 0; - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergyTile ) - { - interested++; - } - } - return interested == 1;// if more then one tile is interested we need to abandon... - } + if (this.interestedInIC2()) { + this.addToENet(); + } else { + this.removeFromENet(); + } + } - @Override - public void partChanged() - { - super.partChanged(); + @Override + public boolean + emitsEnergyTo(final TileEntity receiver, final ForgeDirection direction) { + if (!this.isInIC2()) { + return false; + } - if( this.interestedInIC2() ) - { - this.addToENet(); - } - else - { - this.removeFromENet(); - } - } + final IPart part = this.getPart(direction); + if (part instanceof IEnergySink) { + return ((IEnergyEmitter) part).emitsEnergyTo(receiver, direction); + } + return false; + } - @Override - public boolean emitsEnergyTo( final TileEntity receiver, final ForgeDirection direction ) - { - if( !this.isInIC2() ) - { - return false; - } + private boolean isInIC2() { + return this.getLayerFlags().contains(LayerFlags.IC2_ENET); + } - final IPart part = this.getPart( direction ); - if( part instanceof IEnergySink ) - { - return ( (IEnergyEmitter) part ).emitsEnergyTo( receiver, direction ); - } - return false; - } + @Override + public double getOfferedEnergy() { + if (!this.isInIC2()) { + return 0; + } - private boolean isInIC2() - { - return this.getLayerFlags().contains( LayerFlags.IC2_ENET ); - } + // this is a flawed implementation, that requires a change to the IC2 API. - @Override - public double getOfferedEnergy() - { - if( !this.isInIC2() ) - { - return 0; - } + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySource) { + // use lower number cause ic2 deletes power it sends that isn't received. + return ((IEnergySource) part).getOfferedEnergy(); + } + } - // this is a flawed implementation, that requires a change to the IC2 API. + return 0; + } - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySource ) - { - // use lower number cause ic2 deletes power it sends that isn't received. - return ( (IEnergySource) part ).getOfferedEnergy(); - } - } + @Override + public void drawEnergy(final double amount) { + // this is a flawed implementation, that requires a change to the IC2 API. - return 0; - } + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySource) { + ((IEnergySource) part).drawEnergy(amount); + return; + } + } + } - @Override - public void drawEnergy( final double amount ) - { - // this is a flawed implementation, that requires a change to the IC2 API. + @Override + public int getSourceTier() { + // this is a flawed implementation, that requires a change to the IC2 API. - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySource ) - { - ( (IEnergySource) part ).drawEnergy( amount ); - return; - } - } - } + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getPart(dir); + if (part instanceof IEnergySource) { + return ((IEnergySource) part).getSourceTier(); + } + } - @Override - public int getSourceTier() - { - // this is a flawed implementation, that requires a change to the IC2 API. - - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getPart( dir ); - if( part instanceof IEnergySource ) - { - return ( (IEnergySource) part ).getSourceTier(); - } - } - - return 0; - } + return 0; + } } diff --git a/src/main/java/appeng/parts/layers/LayerIFluidHandler.java b/src/main/java/appeng/parts/layers/LayerIFluidHandler.java index c3b53e8a..1426a723 100644 --- a/src/main/java/appeng/parts/layers/LayerIFluidHandler.java +++ b/src/main/java/appeng/parts/layers/LayerIFluidHandler.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import net.minecraftforge.common.util.ForgeDirection; @@ -26,75 +25,65 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; +public class LayerIFluidHandler extends LayerBase implements IFluidHandler { + private static final FluidTankInfo[] EMPTY_LIST = new FluidTankInfo[0]; -public class LayerIFluidHandler extends LayerBase implements IFluidHandler -{ + @Override + public int + fill(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).fill(from, resource, doFill); + } + return 0; + } - private static final FluidTankInfo[] EMPTY_LIST = new FluidTankInfo[0]; + @Override + public FluidStack + drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).drain(from, resource, doDrain); + } + return null; + } - @Override - public int fill( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).fill( from, resource, doFill ); - } - return 0; - } + @Override + public FluidStack + drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).drain(from, maxDrain, doDrain); + } + return null; + } - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).drain( from, resource, doDrain ); - } - return null; - } + @Override + public boolean + canFill(final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).canFill(from, fluid); + } + return false; + } - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).drain( from, maxDrain, doDrain ); - } - return null; - } + @Override + public boolean + canDrain(final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid) { + final IPart part = this.getPart(from); + if (part instanceof IFluidHandler) { + return ((IFluidHandler) part).canDrain(from, fluid); + } + return false; + } - @Override - public boolean canFill( final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).canFill( from, fluid ); - } - return false; - } - - @Override - public boolean canDrain( final ForgeDirection from, final net.minecraftforge.fluids.Fluid fluid ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).canDrain( from, fluid ); - } - return false; - } - - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - final IPart part = this.getPart( from ); - if( part instanceof IFluidHandler ) - { - return ( (IFluidHandler) part ).getTankInfo( from ); - } - return EMPTY_LIST; - } + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + final IPart part = this.getPart(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 d0daa084..07f192ab 100644 --- a/src/main/java/appeng/parts/layers/LayerIPipeConnection.java +++ b/src/main/java/appeng/parts/layers/LayerIPipeConnection.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import appeng.helpers.Reflected; @@ -26,19 +25,15 @@ import buildcraft.api.transport.IPipeConnection; import buildcraft.api.transport.IPipeTile.PipeType; import net.minecraftforge.common.util.ForgeDirection; - @Reflected -public class LayerIPipeConnection extends LayerBase implements IPipeConnection -{ - - @Override - public ConnectOverride overridePipeConnection( final PipeType type, final ForgeDirection with ) - { - final IPart part = this.getPart( with ); - if( part instanceof IPipeConnection ) - { - return ( (IPipeConnection) part ).overridePipeConnection( type, with ); - } - return ConnectOverride.DEFAULT; - } +public class LayerIPipeConnection extends LayerBase implements IPipeConnection { + @Override + public ConnectOverride + overridePipeConnection(final PipeType type, final ForgeDirection with) { + final IPart part = this.getPart(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 928baabf..f2a0297b 100644 --- a/src/main/java/appeng/parts/layers/LayerISidedInventory.java +++ b/src/main/java/appeng/parts/layers/LayerISidedInventory.java @@ -18,6 +18,9 @@ package appeng.parts.layers; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; @@ -28,239 +31,195 @@ import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - /** * Inventory wrapper for parts, *

- * this is considerably more complicated then the other wrappers as it requires creating a "unified inventory". - *

- * You must use {@link ISidedInventory} instead of {@link IInventory}. - *

- * If your inventory changes in between placement and removal, you must trigger a PartChange on the {@link IPartHost} so - * it can recalculate the inventory wrapper. + * this is considerably more complicated then the other wrappers as it requires creating a + * "unified inventory".

You must use {@link ISidedInventory} instead of {@link + * IInventory}.

If your inventory changes in between placement and removal, you must + * trigger a PartChange on the {@link IPartHost} so it can recalculate the inventory + * wrapper. */ -public class LayerISidedInventory extends LayerBase implements ISidedInventory -{ +public class LayerISidedInventory extends LayerBase implements ISidedInventory { + // a simple empty array for empty stuff.. + private static final int[] NULL_SIDES = {}; - // a simple empty array for empty stuff.. - private static final int[] NULL_SIDES = {}; + private InvLayerData invLayer = null; - private InvLayerData invLayer = null; + /** + * Recalculate inventory wrapper cache. + */ + @Override + public void notifyNeighbors() { + // cache of inventory state. - /** - * Recalculate inventory wrapper cache. - */ - @Override - public void notifyNeighbors() - { - // cache of inventory state. + List inventories = new ArrayList(); + int slotCount = 0; - List inventories = new ArrayList(); - int slotCount = 0; + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + final IPart bp = this.getPart(side); + if (bp instanceof ISidedInventory) { + final ISidedInventory part = (ISidedInventory) bp; + slotCount += part.getSizeInventory(); + inventories.add(part); + } + } - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart bp = this.getPart( side ); - if( bp instanceof ISidedInventory ) - { - final ISidedInventory part = (ISidedInventory) bp; - slotCount += part.getSizeInventory(); - inventories.add( part ); - } - } + List slots = null; + int[][] sideData = null; + if (inventories.isEmpty() || slotCount == 0) { + inventories = null; + } else { + sideData = new int[][] { NULL_SIDES, NULL_SIDES, NULL_SIDES, + NULL_SIDES, NULL_SIDES, NULL_SIDES }; + slots = new ArrayList(Collections.nCopies(slotCount, (InvSot) null)); - List slots = null; - int[][] sideData = null; - if( inventories.isEmpty() || slotCount == 0 ) - { - inventories = null; - } - else - { - sideData = new int[][] { NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES, NULL_SIDES }; - slots = new ArrayList( Collections.nCopies( slotCount, (InvSot) null ) ); + int offsetForLayer = 0; + int offsetForPart = 0; + for (final ISidedInventory sides : inventories) { + offsetForPart = 0; + slotCount = sides.getSizeInventory(); - int offsetForLayer = 0; - int offsetForPart = 0; - for( final ISidedInventory sides : inventories ) - { - offsetForPart = 0; - slotCount = sides.getSizeInventory(); + ForgeDirection currentSide = ForgeDirection.UNKNOWN; + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (this.getPart(side) == sides) { + currentSide = side; + break; + } + } - ForgeDirection currentSide = ForgeDirection.UNKNOWN; - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( this.getPart( side ) == sides ) - { - currentSide = side; - break; - } - } + final int[] cSidesList = sideData[currentSide.ordinal()] + = new int[slotCount]; + for (int cSlot = 0; cSlot < slotCount; cSlot++) { + cSidesList[cSlot] = offsetForLayer; + slots.set(offsetForLayer, new InvSot(sides, offsetForPart)); + offsetForLayer++; + offsetForPart++; + } + } + } - final int[] cSidesList = sideData[currentSide.ordinal()] = new int[slotCount]; - for( int cSlot = 0; cSlot < slotCount; cSlot++ ) - { - cSidesList[cSlot] = offsetForLayer; - slots.set( offsetForLayer, new InvSot( sides, offsetForPart ) ); - offsetForLayer++; - offsetForPart++; - } - } - } + if (sideData == null || slots == null) { + this.invLayer = null; + } else { + this.invLayer = new InvLayerData(sideData, inventories, slots); + } - if( sideData == null || slots == null ) - { - this.invLayer = null; - } - else - { - this.invLayer = new InvLayerData( sideData, inventories, slots ); - } + // make sure inventory is updated before we call FMP. + super.notifyNeighbors(); + } - // make sure inventory is updated before we call FMP. - super.notifyNeighbors(); - } + @Override + public int getSizeInventory() { + if (this.invLayer == null) { + return 0; + } - @Override - public int getSizeInventory() - { - if( this.invLayer == null ) - { - return 0; - } + return this.invLayer.getSizeInventory(); + } - return this.invLayer.getSizeInventory(); - } + @Override + public ItemStack getStackInSlot(final int slot) { + if (this.invLayer == null) { + return null; + } - @Override - public ItemStack getStackInSlot( final int slot ) - { - if( this.invLayer == null ) - { - return null; - } + return this.invLayer.getStackInSlot(slot); + } - return this.invLayer.getStackInSlot( slot ); - } + @Override + public ItemStack decrStackSize(final int slot, final int amount) { + if (this.invLayer == null) { + return null; + } - @Override - public ItemStack decrStackSize( final int slot, final int amount ) - { - if( this.invLayer == null ) - { - return null; - } + return this.invLayer.decreaseStackSize(slot, amount); + } - return this.invLayer.decreaseStackSize( slot, amount ); - } + @Override + public ItemStack getStackInSlotOnClosing(final int slot) { + return null; + } - @Override - public ItemStack getStackInSlotOnClosing( final int slot ) - { - return null; - } + @Override + public void setInventorySlotContents(final int slot, final ItemStack itemstack) { + if (this.invLayer == null) { + return; + } - @Override - public void setInventorySlotContents( final int slot, final ItemStack itemstack ) - { - if( this.invLayer == null ) - { - return; - } + this.invLayer.setInventorySlotContents(slot, itemstack); + } - this.invLayer.setInventorySlotContents( slot, itemstack ); - } + @Override + public String getInventoryName() { + return "AEMultiPart"; + } - @Override - public String getInventoryName() - { - return "AEMultiPart"; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public int getInventoryStackLimit() { + return 64; // no options here. + } - @Override - public int getInventoryStackLimit() - { - return 64; // no options here. - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } + @Override + public void openInventory() {} - @Override - public void openInventory() - { - } + @Override + public void closeInventory() {} - @Override - public void closeInventory() - { - } + @Override + public boolean isItemValidForSlot(final int slot, final ItemStack itemstack) { + if (this.invLayer == null) { + return false; + } - @Override - public boolean isItemValidForSlot( final int slot, final ItemStack itemstack ) - { - if( this.invLayer == null ) - { - return false; - } + return this.invLayer.isItemValidForSlot(slot, itemstack); + } - return this.invLayer.isItemValidForSlot( slot, itemstack ); - } + @Override + public void markDirty() { + if (this.invLayer != null) { + this.invLayer.markDirty(); + } - @Override - public void markDirty() - { - if( this.invLayer != null ) - { - this.invLayer.markDirty(); - } + super.markForSave(); + } - super.markForSave(); - } + @Override + public int[] getAccessibleSlotsFromSide(final int side) { + if (this.invLayer != null) { + return this.invLayer.getAccessibleSlotsFromSide(side); + } - @Override - public int[] getAccessibleSlotsFromSide( final int side ) - { - if( this.invLayer != null ) - { - return this.invLayer.getAccessibleSlotsFromSide( side ); - } + return NULL_SIDES; + } - return NULL_SIDES; - } + @Override + public boolean + canInsertItem(final int slot, final ItemStack itemstack, final int side) { + if (this.invLayer == null) { + return false; + } - @Override - public boolean canInsertItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.invLayer == null ) - { - return false; - } + return this.invLayer.canInsertItem(slot, itemstack, side); + } - return this.invLayer.canInsertItem( slot, itemstack, side ); - } + @Override + public boolean + canExtractItem(final int slot, final ItemStack itemstack, final int side) { + if (this.invLayer == null) { + return false; + } - @Override - public boolean canExtractItem( final int slot, final ItemStack itemstack, final int side ) - { - if( this.invLayer == null ) - { - return false; - } - - return this.invLayer.canExtractItem( slot, itemstack, side ); - } + 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 7d2df96c..91de234d 100644 --- a/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java +++ b/src/main/java/appeng/parts/layers/LayerITileStorageMonitorable.java @@ -18,7 +18,6 @@ package appeng.parts.layers; - import appeng.api.implementations.tiles.ITileStorageMonitorable; import appeng.api.networking.security.BaseActionSource; import appeng.api.parts.IPart; @@ -26,18 +25,15 @@ import appeng.api.parts.LayerBase; import appeng.api.storage.IStorageMonitorable; import net.minecraftforge.common.util.ForgeDirection; - -public class LayerITileStorageMonitorable extends LayerBase implements ITileStorageMonitorable -{ - - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - final IPart part = this.getPart( side ); - if( part instanceof ITileStorageMonitorable ) - { - return ( (ITileStorageMonitorable) part ).getMonitorable( side, src ); - } - return null; - } +public class LayerITileStorageMonitorable + extends LayerBase implements ITileStorageMonitorable { + @Override + public IStorageMonitorable + getMonitorable(final ForgeDirection side, final BaseActionSource src) { + final IPart part = this.getPart(side); + if (part instanceof ITileStorageMonitorable) { + return ((ITileStorageMonitorable) part).getMonitorable(side, src); + } + return null; + } } diff --git a/src/main/java/appeng/parts/layers/LayerPressure.java b/src/main/java/appeng/parts/layers/LayerPressure.java index a3ce8158..bec0b7b7 100644 --- a/src/main/java/appeng/parts/layers/LayerPressure.java +++ b/src/main/java/appeng/parts/layers/LayerPressure.java @@ -18,6 +18,7 @@ package appeng.parts.layers; +import javax.annotation.Nullable; import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; @@ -25,23 +26,15 @@ import net.minecraftforge.common.util.ForgeDirection; import pneumaticCraft.api.tileentity.IAirHandler; import pneumaticCraft.api.tileentity.ISidedPneumaticMachine; -import javax.annotation.Nullable; - - -public class LayerPressure extends LayerBase implements ISidedPneumaticMachine -{ - - @Nullable - @Override - public IAirHandler getAirHandler( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part instanceof ISidedPneumaticMachine ) - { - return ( (ISidedPneumaticMachine) part ).getAirHandler( side ); - } - - return null; - } +public class LayerPressure extends LayerBase implements ISidedPneumaticMachine { + @Nullable + @Override + public IAirHandler getAirHandler(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part instanceof ISidedPneumaticMachine) { + return ((ISidedPneumaticMachine) part).getAirHandler(side); + } + return null; + } } diff --git a/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java b/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java index 15c5a5a9..dcbdd76b 100644 --- a/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java +++ b/src/main/java/appeng/parts/layers/LayerSidedEnvironment.java @@ -18,6 +18,7 @@ package appeng.parts.layers; +import javax.annotation.Nullable; import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; @@ -28,35 +29,27 @@ import li.cil.oc.api.network.Node; import li.cil.oc.api.network.SidedEnvironment; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; - - /** * Reflected in {@link Registration#initialize(FMLInitializationEvent)} */ @Reflected -public class LayerSidedEnvironment extends LayerBase implements SidedEnvironment -{ - @Nullable - @Override - public Node sidedNode( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part instanceof SidedEnvironment ) - { - return ( (SidedEnvironment) part ).sidedNode( side ); - } - return null; - } +public class LayerSidedEnvironment extends LayerBase implements SidedEnvironment { + @Nullable + @Override + public Node sidedNode(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part instanceof SidedEnvironment) { + return ((SidedEnvironment) part).sidedNode(side); + } + return null; + } - @Override - public boolean canConnect( final ForgeDirection side ) - { - final IPart part = this.getPart( side ); - if( part instanceof SidedEnvironment ) - { - return ( (SidedEnvironment) part ).canConnect( side ); - } - return false; - } + @Override + public boolean canConnect(final ForgeDirection side) { + final IPart part = this.getPart(side); + if (part instanceof SidedEnvironment) { + return ((SidedEnvironment) part).canConnect(side); + } + return false; + } } diff --git a/src/main/java/appeng/parts/misc/PartCableAnchor.java b/src/main/java/appeng/parts/misc/PartCableAnchor.java index 64866130..b4c2b3f0 100644 --- a/src/main/java/appeng/parts/misc/PartCableAnchor.java +++ b/src/main/java/appeng/parts/misc/PartCableAnchor.java @@ -18,6 +18,9 @@ package appeng.parts.misc; +import java.io.IOException; +import java.util.List; +import java.util.Random; import appeng.api.networking.IGridNode; import appeng.api.parts.*; @@ -36,234 +39,189 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; -import java.util.Random; +public class PartCableAnchor implements IPart { + private ISimplifiedBundle renderCache = null; + private ItemStack is = null; + private IPartHost host = null; + private ForgeDirection mySide = ForgeDirection.UP; + public PartCableAnchor(final ItemStack is) { + this.is = is; + } -public class PartCableAnchor implements IPart -{ + @Override + public void getBoxes(final IPartCollisionHelper bch) { + if (this.host != null + && this.host.getFacadeContainer().getFacade(this.mySide) != null) { + bch.addBox(7, 7, 10, 9, 9, 14); + } else { + bch.addBox(7, 7, 10, 9, 9, 16); + } + } - private ISimplifiedBundle renderCache = null; - private ItemStack is = null; - private IPartHost host = null; - private ForgeDirection mySide = ForgeDirection.UP; + @Override + public ItemStack getItemStack(final PartItemStack wrenched) { + return this.is; + } - public PartCableAnchor( final ItemStack is ) - { - this.is = is; - } + @Override + @SideOnly(Side.CLIENT) + public void + renderInventory(final IPartRenderHelper instance, final RenderBlocks renderer) { + instance.setTexture(this.is.getIconIndex()); + instance.setBounds(7, 7, 4, 9, 9, 14); + instance.renderInventoryBox(renderer); + instance.setTexture(null); + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - if( this.host != null && this.host.getFacadeContainer().getFacade( this.mySide ) != null ) - { - bch.addBox( 7, 7, 10, 9, 9, 14 ); - } - else - { - bch.addBox( 7, 7, 10, 9, 9, 16 ); - } - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.renderCache = rh.useSimplifiedRendering(x, y, z, this, this.renderCache); + final 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 { + rh.setBounds(7, 7, 10, 9, 9, 16); + } + rh.renderBlock(x, y, z, renderer); + rh.setTexture(null); + } - @Override - public ItemStack getItemStack( final PartItemStack wrenched ) - { - return this.is; - } + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic( + final double x, + final double y, + final double z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) {} - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper instance, final RenderBlocks renderer ) - { - instance.setTexture( this.is.getIconIndex() ); - instance.setBounds( 7, 7, 4, 9, 9, 14 ); - instance.renderInventoryBox( renderer ); - instance.setTexture( null ); - } + @Override + public IIcon getBreakingTexture() { + return null; + } - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.renderCache = rh.useSimplifiedRendering( x, y, z, this, this.renderCache ); - final 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 - { - rh.setBounds( 7, 7, 10, 9, 9, 16 ); - } - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( null ); - } + @Override + public boolean requireDynamicRender() { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { + @Override + public boolean isSolid() { + return false; + } - } + @Override + public boolean canConnectRedstone() { + return false; + } - @Override - public IIcon getBreakingTexture() - { - return null; - } + @Override + public void writeToNBT(final NBTTagCompound data) {} - @Override - public boolean requireDynamicRender() - { - return false; - } + @Override + public void readFromNBT(final NBTTagCompound data) {} - @Override - public boolean isSolid() - { - return false; - } + @Override + public int getLightLevel() { + return 0; + } - @Override - public boolean canConnectRedstone() - { - return false; - } + @Override + public boolean isLadder(final EntityLivingBase entity) { + return this.mySide.offsetY == 0 + && (entity.isCollidedHorizontally || !entity.onGround); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { + @Override + public void onNeighborChanged() {} - } + @Override + public int isProvidingStrongPower() { + return 0; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { + @Override + public int isProvidingWeakPower() { + return 0; + } - } + @Override + public void writeToStream(final ByteBuf data) throws IOException {} - @Override - public int getLightLevel() - { - return 0; - } + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + return false; + } - @Override - public boolean isLadder( final EntityLivingBase entity ) - { - return this.mySide.offsetY == 0 && ( entity.isCollidedHorizontally || !entity.onGround ); - } + @Override + public IGridNode getGridNode() { + return null; + } - @Override - public void onNeighborChanged() - { + @Override + public void onEntityCollision(final Entity entity) {} - } + @Override + public void removeFromWorld() {} - @Override - public int isProvidingStrongPower() - { - return 0; - } + @Override + public void addToWorld() {} - @Override - public int isProvidingWeakPower() - { - return 0; - } + @Override + public IGridNode getExternalFacingNode() { + return null; + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { + @Override + public void setPartHostInfo( + final ForgeDirection side, final IPartHost host, final TileEntity tile + ) { + this.host = host; + this.mySide = side; + } - } + @Override + public boolean onActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - return false; - } + @Override + public boolean onShiftActivate(final EntityPlayer player, final Vec3 pos) { + return false; + } - @Override - public IGridNode getGridNode() - { - return null; - } + @Override + public void getDrops(final List drops, final boolean wrenched) {} - @Override - public void onEntityCollision( final Entity entity ) - { + @Override + public int cableConnectionRenderTo() { + return 0; + } - } + @Override + @SideOnly(Side.CLIENT) + public void randomDisplayTick( + final World world, final int x, final int y, final int z, final Random r + ) {} - @Override - public void removeFromWorld() - { + @Override + public void onPlacement( + final EntityPlayer player, final ItemStack held, final ForgeDirection side + ) {} - } - - @Override - public void addToWorld() - { - - } - - @Override - public IGridNode getExternalFacingNode() - { - return null; - } - - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - this.host = host; - this.mySide = side; - } - - @Override - public boolean onActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - @Override - public boolean onShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - return false; - } - - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - - } - - @Override - public int cableConnectionRenderTo() - { - return 0; - } - - @Override - @SideOnly( Side.CLIENT ) - public void randomDisplayTick( final World world, final int x, final int y, final int z, final Random r ) - { - - } - - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - - } - - @Override - public boolean canBePlacedOn( final BusSupport what ) - { - return what == BusSupport.CABLE || what == BusSupport.DENSE_CABLE; - } + @Override + public boolean canBePlacedOn(final BusSupport what) { + return what == BusSupport.CABLE || what == BusSupport.DENSE_CABLE; + } } diff --git a/src/main/java/appeng/parts/misc/PartInterface.java b/src/main/java/appeng/parts/misc/PartInterface.java index 981273f8..a51d653f 100644 --- a/src/main/java/appeng/parts/misc/PartInterface.java +++ b/src/main/java/appeng/parts/misc/PartInterface.java @@ -18,6 +18,8 @@ package appeng.parts.misc; +import java.util.EnumSet; +import java.util.List; import appeng.api.config.Actionable; import appeng.api.config.Upgrades; @@ -66,360 +68,353 @@ import net.minecraft.util.IIcon; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; - - public class PartInterface extends PartBasicState - implements IGridTickable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, ISidedInventory, IAEAppEngInventory, ITileStorageMonitorable, IPriorityHost -{ + implements IGridTickable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, + ISidedInventory, IAEAppEngInventory, ITileStorageMonitorable, + IPriorityHost { + private final DualityInterface duality = new DualityInterface(this.getProxy(), this); - private final DualityInterface duality = new DualityInterface( this.getProxy(), this ); + @Reflected + public PartInterface(final ItemStack is) { + super(is); + } - @Reflected - public PartInterface( final ItemStack is ) - { - super( is ); - } + @MENetworkEventSubscribe + public void stateChange(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + } - @MENetworkEventSubscribe - public void stateChange( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - } + @MENetworkEventSubscribe + public void stateChange(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + } - @MENetworkEventSubscribe - public void stateChange( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 12, 11, 11, 14); + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 5, 5, 12, 11, 11, 14 ); - } + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon() + ); - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderInventoryBox( renderer ); + rh.setBounds(5, 5, 12, 11, 11, 13); + rh.renderInventoryBox(renderer); - rh.setBounds( 5, 5, 12, 11, 11, 13 ); - rh.renderInventoryBox( renderer ); + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderInventoryBox(renderer); + } - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderInventoryBox( renderer ); - } + @Override + public void gridChanged() { + this.duality.gridChanged(); + } - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture( + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon() + ); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); + rh.setTexture( + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSides.getIcon(), + CableBusTextures.PartMonitorSides.getIcon() + ); - rh.setTexture( CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSides.getIcon(), CableBusTextures.PartMonitorSides.getIcon() ); + rh.setBounds(5, 5, 12, 11, 11, 13); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 5, 5, 12, 11, 11, 13 ); - rh.renderBlock( x, y, z, renderer ); + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon() + ); - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderBlock( x, y, z, renderer ); + this.renderLights(x, y, z, rh, renderer); + } - this.renderLights( x, y, z, rh, renderer ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.duality.readFromNBT(data); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.duality.readFromNBT( data ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.duality.writeToNBT(data); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.duality.writeToNBT( data ); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.duality.initialize(); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.duality.initialize(); - } + @Override + public void getDrops(final List drops, final boolean wrenched) { + this.duality.addDrops(drops); + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - this.duality.addDrops( drops ); - } + @Override + public int cableConnectionRenderTo() { + return 4; + } - @Override - public int cableConnectionRenderTo() - { - return 4; - } + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } + @Override + public IInventory getInventoryByName(final String name) { + return this.duality.getInventoryByName(name); + } - @Override - public IInventory getInventoryByName( final String name ) - { - return this.duality.getInventoryByName( name ); - } + @Override + public boolean onPartActivate(final EntityPlayer p, final Vec3 pos) { + if (p.isSneaking()) { + return false; + } - @Override - public boolean onPartActivate( final EntityPlayer p, final Vec3 pos ) - { - if( p.isSneaking() ) - { - return false; - } + if (Platform.isServer()) { + Platform.openGUI( + p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_INTERFACE + ); + } - if( Platform.isServer() ) - { - Platform.openGUI( p, this.getTileEntity(), this.getSide(), GuiBridge.GUI_INTERFACE ); - } + return true; + } - return true; - } + @Override + public IIcon getBreakingTexture() { + return this.getItemStack().getIconIndex(); + } - @Override - public IIcon getBreakingTexture() - { - return this.getItemStack().getIconIndex(); - } + @Override + public boolean canInsert(final ItemStack stack) { + return this.duality.canInsert(stack); + } - @Override - public boolean canInsert( final ItemStack stack ) - { - return this.duality.canInsert( stack ); - } + @Override + public IMEMonitor getItemInventory() { + return this.duality.getItemInventory(); + } - @Override - public IMEMonitor getItemInventory() - { - return this.duality.getItemInventory(); - } + @Override + public IMEMonitor getFluidInventory() { + return this.duality.getFluidInventory(); + } - @Override - public IMEMonitor getFluidInventory() - { - return this.duality.getFluidInventory(); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return this.duality.getTickingRequest(node); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } + @Override + public int getSizeInventory() { + return this.duality.getStorage().getSizeInventory(); + } - @Override - public int getSizeInventory() - { - return this.duality.getStorage().getSizeInventory(); - } + @Override + public ItemStack getStackInSlot(final int i) { + return this.duality.getStorage().getStackInSlot(i); + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.duality.getStorage().getStackInSlot( i ); - } + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.duality.getStorage().decrStackSize(i, j); + } - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.duality.getStorage().decrStackSize( i, j ); - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return this.duality.getStorage().getStackInSlotOnClosing(i); + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return this.duality.getStorage().getStackInSlotOnClosing( i ); - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.duality.getStorage().setInventorySlotContents(i, itemstack); + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.duality.getStorage().setInventorySlotContents( i, itemstack ); - } + @Override + public String getInventoryName() { + return this.duality.getStorage().getInventoryName(); + } - @Override - public String getInventoryName() - { - return this.duality.getStorage().getInventoryName(); - } + @Override + public boolean hasCustomInventoryName() { + return this.duality.getStorage().hasCustomInventoryName(); + } - @Override - public boolean hasCustomInventoryName() - { - return this.duality.getStorage().hasCustomInventoryName(); - } + @Override + public int getInventoryStackLimit() { + return this.duality.getStorage().getInventoryStackLimit(); + } - @Override - public int getInventoryStackLimit() - { - return this.duality.getStorage().getInventoryStackLimit(); - } + @Override + public void markDirty() { + this.duality.getStorage().markDirty(); + } - @Override - public void markDirty() - { - this.duality.getStorage().markDirty(); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return this.duality.getStorage().isUseableByPlayer(entityplayer); + } - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return this.duality.getStorage().isUseableByPlayer( entityplayer ); - } + @Override + public void openInventory() { + this.duality.getStorage().openInventory(); + } - @Override - public void openInventory() - { - this.duality.getStorage().openInventory(); - } + @Override + public void closeInventory() { + this.duality.getStorage().closeInventory(); + } - @Override - public void closeInventory() - { - this.duality.getStorage().closeInventory(); - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return this.duality.getStorage().isItemValidForSlot(i, itemstack); + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.duality.getStorage().isItemValidForSlot( i, itemstack ); - } + @Override + public int[] getAccessibleSlotsFromSide(final int s) { + return this.duality.getAccessibleSlotsFromSide(s); + } - @Override - public int[] getAccessibleSlotsFromSide( final int s ) - { - return this.duality.getAccessibleSlotsFromSide( s ); - } + @Override + public boolean canInsertItem(final int i, final ItemStack itemstack, final int j) { + return true; + } - @Override - public boolean canInsertItem( final int i, final ItemStack itemstack, final int j ) - { - return true; - } + @Override + public boolean canExtractItem(final int i, final ItemStack itemstack, final int j) { + return true; + } - @Override - public boolean canExtractItem( final int i, final ItemStack itemstack, final int j ) - { - return true; - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) { + this.duality.onChangeInventory(inv, slot, mc, removedStack, newStack); + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.duality.onChangeInventory( inv, slot, mc, removedStack, newStack ); - } + @Override + public DualityInterface getInterfaceDuality() { + return this.duality; + } - @Override - public DualityInterface getInterfaceDuality() - { - return this.duality; - } + @Override + public EnumSet getTargets() { + return EnumSet.of(this.getSide()); + } - @Override - public EnumSet getTargets() - { - return EnumSet.of( this.getSide() ); - } + @Override + public TileEntity getTileEntity() { + return super.getHost().getTile(); + } - @Override - public TileEntity getTileEntity() - { - return super.getHost().getTile(); - } + @Override + public IStorageMonitorable + getMonitorable(final ForgeDirection side, final BaseActionSource src) { + return this.duality.getMonitorable(side, src, this); + } - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - return this.duality.getMonitorable( side, src, this ); - } + @Override + public boolean pushPattern( + final ICraftingPatternDetails patternDetails, final InventoryCrafting table + ) { + return this.duality.pushPattern(patternDetails, table); + } - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return this.duality.pushPattern( patternDetails, table ); - } + @Override + public boolean isBusy() { + return this.duality.isBusy(); + } - @Override - public boolean isBusy() - { - return this.duality.isBusy(); - } + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + this.duality.provideCrafting(craftingTracker); + } - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - this.duality.provideCrafting( craftingTracker ); - } + @Override + public ImmutableSet getRequestedJobs() { + return this.duality.getRequestedJobs(); + } - @Override - public ImmutableSet getRequestedJobs() - { - return this.duality.getRequestedJobs(); - } + @Override + public IAEItemStack injectCraftedItems( + final ICraftingLink link, final IAEItemStack items, final Actionable mode + ) { + return this.duality.injectCraftedItems(link, items, mode); + } - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - return this.duality.injectCraftedItems( link, items, mode ); - } + @Override + public void jobStateChange(final ICraftingLink link) { + this.duality.jobStateChange(link); + } - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.duality.jobStateChange( link ); - } + @Override + public int getPriority() { + return this.duality.getPriority(); + } - @Override - public int getPriority() - { - return this.duality.getPriority(); - } - - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } + @Override + public void setPriority(final int newValue) { + this.duality.setPriority(newValue); + } } diff --git a/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java b/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java index 2b63295c..a9e8d299 100644 --- a/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java +++ b/src/main/java/appeng/parts/misc/PartInvertedToggleBus.java @@ -18,26 +18,21 @@ package appeng.parts.misc; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartInvertedToggleBus extends PartToggleBus { + @Reflected + public PartInvertedToggleBus(final ItemStack is) { + super(is); + this.getProxy().setIdlePowerUsage(0.0); + this.getOuterProxy().setIdlePowerUsage(0.0); + this.getProxy().setFlags(); + this.getOuterProxy().setFlags(); + } -public class PartInvertedToggleBus extends PartToggleBus -{ - @Reflected - public PartInvertedToggleBus( final ItemStack is ) - { - super( is ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getOuterProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setFlags(); - this.getOuterProxy().setFlags(); - } - - @Override - protected boolean getIntention() - { - return !super.getIntention(); - } + @Override + protected boolean getIntention() { + return !super.getIntention(); + } } diff --git a/src/main/java/appeng/parts/misc/PartStorageBus.java b/src/main/java/appeng/parts/misc/PartStorageBus.java index d232deb4..ba1d424e 100644 --- a/src/main/java/appeng/parts/misc/PartStorageBus.java +++ b/src/main/java/appeng/parts/misc/PartStorageBus.java @@ -18,6 +18,9 @@ package appeng.parts.misc; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.*; @@ -72,496 +75,508 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - - -@Interface( iname = IntegrationType.BuildCraftTransport, iface = "buildcraft.api.transport.IPipeConnection" ) +@Interface( + iname = IntegrationType.BuildCraftTransport, + iface = "buildcraft.api.transport.IPipeConnection" +) public class PartStorageBus extends PartUpgradeable - implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, IPipeConnection, IPriorityHost -{ - private final BaseActionSource mySrc; - private final AppEngInternalAEInventory Config = new AppEngInternalAEInventory( this, 63 ); - private int priority = 0; - private boolean cached = false; - private MEMonitorIInventory monitor = null; - private MEInventoryHandler handler = null; - private int handlerHash = 0; - private boolean wasActive = false; - private byte resetCacheLogic = 0; - - @Reflected - public PartStorageBus( final ItemStack is ) - { - super( is ); - this.getConfigManager().registerSetting( Settings.ACCESS, AccessRestriction.READ_WRITE ); - this.getConfigManager().registerSetting( Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL ); - this.getConfigManager().registerSetting( Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY ); - this.mySrc = new MachineSource( this ); - } - - @Override - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.updateStatus(); - } - - private void updateStatus() - { - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - this.getHost().markForUpdate(); - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - @MENetworkEventSubscribe - public void updateChannels( final MENetworkChannelsChanged changedChannels ) - { - this.updateStatus(); - } - - @Override - protected int getUpgradeSlots() - { - return 5; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.resetCache( true ); - this.getHost().markForSave(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final 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 - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.Config.readFromNBT( data, "config" ); - this.priority = data.getInteger( "priority" ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.Config.writeToNBT( data, "config" ); - data.setInteger( "priority", this.priority ); - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.Config; - } - - return super.getInventoryByName( name ); - } - - private void resetCache( final boolean fullReset ) - { - if( this.getHost() == null || this.getHost().getTile() == null || this.getHost().getTile().getWorldObj() == null || this.getHost().getTile().getWorldObj().isRemote ) - { - return; - } - - if( fullReset ) - { - this.resetCacheLogic = 2; - } - else - { - this.resetCacheLogic = 1; - } - - try - { - this.getProxy().getTick().alertDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public boolean isValid( final Object verificationToken ) - { - return this.handler == verificationToken; - } - - @Override - public void postChange( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - try - { - if( this.getProxy().isActive() ) - { - this.getProxy().getStorage().postAlterationOfStoredItems( StorageChannel.ITEMS, change, this.mySrc ); - } - } - catch( final GridAccessException e ) - { - // :( - } - } - - @Override - public void onListUpdate() - { - // not used here. - } - - @Override - public void getBoxes( final 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( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setTexture( CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon() ); - - rh.setBounds( 3, 3, 15, 13, 13, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 2, 2, 14, 14, 14, 15 ); - rh.renderInventoryBox( renderer ); - - rh.setBounds( 5, 5, 12, 11, 11, 14 ); - rh.renderInventoryBox( renderer ); - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon() ); - - rh.setBounds( 3, 3, 15, 13, 13, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 2, 2, 14, 14, 14, 15 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartStorageSides.getIcon(), CableBusTextures.PartStorageSides.getIcon() ); - - rh.setBounds( 5, 5, 12, 11, 11, 13 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); - - rh.setBounds( 5, 5, 13, 11, 11, 14 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public void onNeighborChanged() - { - this.resetCache( false ); - } - - @Override - public int cableConnectionRenderTo() - { - return 4; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } - - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS ); - return true; - } - - return false; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.StorageBus.getMin(), TickRates.StorageBus.getMax(), this.monitor == null, true ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.resetCacheLogic != 0 ) - { - this.resetCache(); - } - - if( this.monitor != null ) - { - return this.monitor.onTick(); - } - - return TickRateModulation.SLEEP; - } - - private void resetCache() - { - final boolean fullReset = this.resetCacheLogic == 2; - this.resetCacheLogic = 0; - - final IMEInventory in = this.getInternalHandler(); - IItemList before = AEApi.instance().storage().createItemList(); - if( in != null ) - { - before = in.getAvailableItems( before ); - } - - this.cached = false; - if( fullReset ) - { - this.handlerHash = 0; - } - - final IMEInventory out = this.getInternalHandler(); - - if( this.monitor != null ) - { - this.monitor.onTick(); - } - - IItemList after = AEApi.instance().storage().createItemList(); - if( out != null ) - { - after = out.getAvailableItems( after ); - } - - Platform.postListChanges( before, after, this, this.mySrc ); - } - - public MEInventoryHandler getInternalHandler() - { - if( this.cached ) - { - return this.handler; - } - - final boolean wasSleeping = this.monitor == null; - - this.cached = true; - final TileEntity self = this.getHost().getTile(); - final TileEntity target = self.getWorldObj().getTileEntity( self.xCoord + this.getSide().offsetX, self.yCoord + this.getSide().offsetY, self.zCoord + this.getSide().offsetZ ); - - final int newHandlerHash = Platform.generateTileHash( target ); - - if( this.handlerHash == newHandlerHash && this.handlerHash != 0 ) - { - return this.handler; - } - - this.handlerHash = newHandlerHash; - this.handler = null; - this.monitor = null; - if( target != null ) - { - final IExternalStorageHandler esh = AEApi.instance().registries().externalStorage().getHandler( target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc ); - if( esh != null ) - { - final IMEInventory inv = esh.getInventory( target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc ); - - if( inv instanceof MEMonitorIInventory ) - { - final MEMonitorIInventory h = (MEMonitorIInventory) inv; - h.setMode( (StorageFilter) this.getConfigManager().getSetting( Settings.STORAGE_FILTER ) ); - h.setActionSource( new MachineSource( this ) ); - } - - if( inv instanceof MEMonitorIInventory ) - { - this.monitor = (MEMonitorIInventory) inv; - } - - if( inv != null ) - { - this.checkInterfaceVsStorageBus( target, this.getSide().getOpposite() ); - - this.handler = new MEInventoryHandler( inv, StorageChannel.ITEMS ); - - 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 ); - - final IItemList priorityList = AEApi.instance().storage().createItemList(); - - final int slotsToUse = 18 + this.getInstalledUpgrades( Upgrades.CAPACITY ) * 9; - for( int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; x++ ) - { - final IAEItemStack is = this.Config.getAEStackInSlot( x ); - if( is != null ) - { - priorityList.add( is ); - } - } - - 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 ) - { - ( (IBaseMonitor) inv ).addListener( this, this.handler ); - } - } - } - } - - // update sleep state... - if( wasSleeping != ( this.monitor == null ) ) - { - try - { - final ITickManager tm = this.getProxy().getTick(); - if( this.monitor == null ) - { - tm.sleepDevice( this.getProxy().getNode() ); - } - else - { - tm.wakeDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :( - } - } - - try - { - // force grid to update handlers... - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :3 - } - - return this.handler; - } - - private void checkInterfaceVsStorageBus( final TileEntity target, final ForgeDirection side ) - { - IInterfaceHost achievement = null; - - if( target instanceof IInterfaceHost ) - { - achievement = (IInterfaceHost) target; - } - - if( target instanceof IPartHost ) - { - final Object part = ( (IPartHost) target ).getPart( side ); - if( part instanceof IInterfaceHost ) - { - achievement = (IInterfaceHost) part; - } - } - - if( achievement != null && achievement.getActionableNode() != null ) - { - Platform.addStat( achievement.getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement() ); - // Platform.addStat( getActionableNode().getPlayerID(), Achievements.Recursive.getAchievement() ); - } - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - if( channel == StorageChannel.ITEMS ) - { - final IMEInventoryHandler out = this.getProxy().isActive() ? this.getInternalHandler() : null; - if( out != null ) - { - return Collections.singletonList( out ); - } - } - return Arrays.asList( new IMEInventoryHandler[] {} ); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.getHost().markForSave(); - this.resetCache( true ); - } - - @Override - public void blinkCell( final int slot ) - { - } - - @Override - @Method( iname = IntegrationType.BuildCraftTransport ) - public ConnectOverride overridePipeConnection( final PipeType type, final ForgeDirection with ) - { - return type == PipeType.ITEM && with == this.getSide() ? ConnectOverride.CONNECT : ConnectOverride.DISCONNECT; - } - - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - // nope! - } + implements IGridTickable, ICellContainer, IMEMonitorHandlerReceiver, + IPipeConnection, IPriorityHost { + private final BaseActionSource mySrc; + private final AppEngInternalAEInventory Config + = new AppEngInternalAEInventory(this, 63); + private int priority = 0; + private boolean cached = false; + private MEMonitorIInventory monitor = null; + private MEInventoryHandler handler = null; + private int handlerHash = 0; + private boolean wasActive = false; + private byte resetCacheLogic = 0; + + @Reflected + public PartStorageBus(final ItemStack is) { + super(is); + this.getConfigManager().registerSetting( + Settings.ACCESS, AccessRestriction.READ_WRITE + ); + this.getConfigManager().registerSetting( + Settings.FUZZY_MODE, FuzzyMode.IGNORE_ALL + ); + this.getConfigManager().registerSetting( + Settings.STORAGE_FILTER, StorageFilter.EXTRACTABLE_ONLY + ); + this.mySrc = new MachineSource(this); + } + + @Override + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.updateStatus(); + } + + private void updateStatus() { + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + this.getHost().markForUpdate(); + } catch (final GridAccessException e) { + // :P + } + } + } + + @MENetworkEventSubscribe + public void updateChannels(final MENetworkChannelsChanged changedChannels) { + this.updateStatus(); + } + + @Override + protected int getUpgradeSlots() { + return 5; + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + this.resetCache(true); + this.getHost().markForSave(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final 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 + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.Config.readFromNBT(data, "config"); + this.priority = data.getInteger("priority"); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.Config.writeToNBT(data, "config"); + data.setInteger("priority", this.priority); + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.Config; + } + + return super.getInventoryByName(name); + } + + private void resetCache(final boolean fullReset) { + if (this.getHost() == null || this.getHost().getTile() == null + || this.getHost().getTile().getWorldObj() == null + || this.getHost().getTile().getWorldObj().isRemote) { + return; + } + + if (fullReset) { + this.resetCacheLogic = 2; + } else { + this.resetCacheLogic = 1; + } + + try { + this.getProxy().getTick().alertDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public boolean isValid(final Object verificationToken) { + return this.handler == verificationToken; + } + + @Override + public void postChange( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource source + ) { + try { + if (this.getProxy().isActive()) { + this.getProxy().getStorage().postAlterationOfStoredItems( + StorageChannel.ITEMS, change, this.mySrc + ); + } + } catch (final GridAccessException e) { + // :( + } + } + + @Override + public void onListUpdate() { + // not used here. + } + + @Override + public void getBoxes(final 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(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture( + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon() + ); + + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(2, 2, 14, 14, 14, 15); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 12, 11, 11, 14); + rh.renderInventoryBox(renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture( + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon() + ); + + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(2, 2, 14, 14, 14, 15); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartStorageSides.getIcon(), + CableBusTextures.PartStorageSides.getIcon() + ); + + rh.setBounds(5, 5, 12, 11, 11, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon() + ); + + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public void onNeighborChanged() { + this.resetCache(false); + } + + @Override + public int cableConnectionRenderTo() { + return 4; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } + + Platform.openGUI( + player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_STORAGEBUS + ); + return true; + } + + return false; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.StorageBus.getMin(), + TickRates.StorageBus.getMax(), + this.monitor == null, + true + ); + } + + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.resetCacheLogic != 0) { + this.resetCache(); + } + + if (this.monitor != null) { + return this.monitor.onTick(); + } + + return TickRateModulation.SLEEP; + } + + private void resetCache() { + final boolean fullReset = this.resetCacheLogic == 2; + this.resetCacheLogic = 0; + + final IMEInventory in = this.getInternalHandler(); + IItemList before = AEApi.instance().storage().createItemList(); + if (in != null) { + before = in.getAvailableItems(before); + } + + this.cached = false; + if (fullReset) { + this.handlerHash = 0; + } + + final IMEInventory out = this.getInternalHandler(); + + if (this.monitor != null) { + this.monitor.onTick(); + } + + IItemList after = AEApi.instance().storage().createItemList(); + if (out != null) { + after = out.getAvailableItems(after); + } + + Platform.postListChanges(before, after, this, this.mySrc); + } + + public MEInventoryHandler getInternalHandler() { + if (this.cached) { + return this.handler; + } + + final boolean wasSleeping = this.monitor == null; + + this.cached = true; + final TileEntity self = this.getHost().getTile(); + final TileEntity target = self.getWorldObj().getTileEntity( + self.xCoord + this.getSide().offsetX, + self.yCoord + this.getSide().offsetY, + self.zCoord + this.getSide().offsetZ + ); + + final int newHandlerHash = Platform.generateTileHash(target); + + if (this.handlerHash == newHandlerHash && this.handlerHash != 0) { + return this.handler; + } + + this.handlerHash = newHandlerHash; + this.handler = null; + this.monitor = null; + if (target != null) { + final IExternalStorageHandler esh + = AEApi.instance().registries().externalStorage().getHandler( + target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc + ); + if (esh != null) { + final IMEInventory inv = esh.getInventory( + target, this.getSide().getOpposite(), StorageChannel.ITEMS, this.mySrc + ); + + if (inv instanceof MEMonitorIInventory) { + final MEMonitorIInventory h = (MEMonitorIInventory) inv; + h.setMode((StorageFilter) this.getConfigManager().getSetting( + Settings.STORAGE_FILTER + )); + h.setActionSource(new MachineSource(this)); + } + + if (inv instanceof MEMonitorIInventory) { + this.monitor = (MEMonitorIInventory) inv; + } + + if (inv != null) { + this.checkInterfaceVsStorageBus(target, this.getSide().getOpposite()); + + this.handler = new MEInventoryHandler(inv, StorageChannel.ITEMS); + + 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); + + final IItemList priorityList + = AEApi.instance().storage().createItemList(); + + final int slotsToUse + = 18 + this.getInstalledUpgrades(Upgrades.CAPACITY) * 9; + for (int x = 0; x < this.Config.getSizeInventory() && x < slotsToUse; + x++) { + final IAEItemStack is = this.Config.getAEStackInSlot(x); + if (is != null) { + priorityList.add(is); + } + } + + 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) { + ((IBaseMonitor) inv).addListener(this, this.handler); + } + } + } + } + + // update sleep state... + if (wasSleeping != (this.monitor == null)) { + try { + final ITickManager tm = this.getProxy().getTick(); + if (this.monitor == null) { + tm.sleepDevice(this.getProxy().getNode()); + } else { + tm.wakeDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :( + } + } + + try { + // force grid to update handlers... + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :3 + } + + return this.handler; + } + + private void + checkInterfaceVsStorageBus(final TileEntity target, final ForgeDirection side) { + IInterfaceHost achievement = null; + + if (target instanceof IInterfaceHost) { + achievement = (IInterfaceHost) target; + } + + if (target instanceof IPartHost) { + final Object part = ((IPartHost) target).getPart(side); + if (part instanceof IInterfaceHost) { + achievement = (IInterfaceHost) part; + } + } + + if (achievement != null && achievement.getActionableNode() != null) { + Platform.addStat( + achievement.getActionableNode().getPlayerID(), + Achievements.Recursive.getAchievement() + ); + // Platform.addStat( getActionableNode().getPlayerID(), + // Achievements.Recursive.getAchievement() ); + } + } + + @Override + public List getCellArray(final StorageChannel channel) { + if (channel == StorageChannel.ITEMS) { + final IMEInventoryHandler out + = this.getProxy().isActive() ? this.getInternalHandler() : null; + if (out != null) { + return Collections.singletonList(out); + } + } + return Arrays.asList(new IMEInventoryHandler[] {}); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.getHost().markForSave(); + this.resetCache(true); + } + + @Override + public void blinkCell(final int slot) {} + + @Override + @Method(iname = IntegrationType.BuildCraftTransport) + public ConnectOverride + overridePipeConnection(final PipeType type, final ForgeDirection with) { + return type == PipeType.ITEM && with == this.getSide() + ? ConnectOverride.CONNECT + : ConnectOverride.DISCONNECT; + } + + @Override + public void saveChanges(final IMEInventory cellInventory) { + // nope! + } } diff --git a/src/main/java/appeng/parts/misc/PartToggleBus.java b/src/main/java/appeng/parts/misc/PartToggleBus.java index 3e355940..79523cfa 100644 --- a/src/main/java/appeng/parts/misc/PartToggleBus.java +++ b/src/main/java/appeng/parts/misc/PartToggleBus.java @@ -18,6 +18,7 @@ package appeng.parts.misc; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.exceptions.FailedConnection; @@ -42,207 +43,197 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; +public class PartToggleBus extends PartBasicState { + private static final int REDSTONE_FLAG = 4; + private final AENetworkProxy outerProxy + = new AENetworkProxy(this, "outer", null, true); + private IGridConnection connection; + private boolean hasRedstone = false; + @Reflected + public PartToggleBus(final ItemStack is) { + super(is); -public class PartToggleBus extends PartBasicState -{ - private static final int REDSTONE_FLAG = 4; - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", null, true ); - private IGridConnection connection; - private boolean hasRedstone = false; + this.getProxy().setIdlePowerUsage(0.0); + this.getOuterProxy().setIdlePowerUsage(0.0); + this.getProxy().setFlags(); + this.getOuterProxy().setFlags(); + } - @Reflected - public PartToggleBus( final ItemStack is ) - { - super( is ); + @Override + public void setColors(final boolean hasChan, final boolean hasPower) { + this.hasRedstone = (this.getClientFlags() & REDSTONE_FLAG) == REDSTONE_FLAG; + super.setColors(hasChan && this.hasRedstone, hasPower && this.hasRedstone); + } - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getOuterProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setFlags(); - this.getOuterProxy().setFlags(); - } + @Override + protected int populateFlags(final int cf) { + return cf | (this.getIntention() ? REDSTONE_FLAG : 0); + } - @Override - public void setColors( final boolean hasChan, final boolean hasPower ) - { - this.hasRedstone = ( this.getClientFlags() & REDSTONE_FLAG ) == REDSTONE_FLAG; - super.setColors( hasChan && this.hasRedstone, hasPower && this.hasRedstone ); - } + protected boolean getIntention() { + return this.getHost().hasRedstone(this.getSide()); + } - @Override - protected int populateFlags( final int cf ) - { - return cf | ( this.getIntention() ? REDSTONE_FLAG : 0 ); - } + @Override + public IIcon getBreakingTexture() { + return this.getItemStack().getIconIndex(); + } - protected boolean getIntention() - { - return this.getHost().hasRedstone( this.getSide() ); - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.GLASS; + } - @Override - public IIcon getBreakingTexture() - { - return this.getItemStack().getIconIndex(); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 11, 10, 10, 16); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.GLASS; - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.2, -0.3, 0.0); - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 11, 10, 10, 16 ); - } + rh.setTexture(this.getItemStack().getIconIndex()); + rh.setBounds(6, 6, 14 - 4, 10, 10, 16 - 4); + rh.renderInventoryBox(renderer); - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.2, -0.3, 0.0 ); + rh.setBounds(6, 6, 11 - 4, 10, 10, 13 - 4); + rh.renderInventoryBox(renderer); - rh.setTexture( this.getItemStack().getIconIndex() ); - rh.setBounds( 6, 6, 14 - 4, 10, 10, 16 - 4 ); - rh.renderInventoryBox( renderer ); + rh.setBounds(6, 6, 13 - 4, 10, 10, 14 - 4); + rh.setTexture(CableBusTextures.PartMonitorSidesStatus.getIcon()); + rh.renderInventoryBox(renderer); - rh.setBounds( 6, 6, 11 - 4, 10, 10, 13 - 4 ); - rh.renderInventoryBox( renderer ); + rh.setTexture(CableBusTextures.PartMonitorSidesStatusLights.getIcon()); + rh.setInvColor(0x000000); + rh.renderInventoryBox(renderer); + rh.setInvColor(0xffffff); - rh.setBounds( 6, 6, 13 - 4, 10, 10, 14 - 4 ); - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon() ); - rh.renderInventoryBox( renderer ); + rh.setTexture(null); + } - rh.setTexture( CableBusTextures.PartMonitorSidesStatusLights.getIcon() ); - rh.setInvColor( 0x000000 ); - rh.renderInventoryBox( renderer ); - rh.setInvColor( 0xffffff ); + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture(this.getItemStack().getIconIndex()); - rh.setTexture( null ); - } + rh.setBounds(6, 6, 14, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getItemStack().getIconIndex() ); + rh.setBounds(6, 6, 11, 10, 10, 13); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 6, 6, 14, 10, 10, 16 ); - rh.renderBlock( x, y, z, renderer ); + rh.setTexture( + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorBack.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartMonitorSidesStatus.getIcon(), + CableBusTextures.PartMonitorSidesStatus.getIcon() + ); - rh.setBounds( 6, 6, 11, 10, 10, 13 ); - rh.renderBlock( x, y, z, renderer ); + rh.setBounds(6, 6, 13, 10, 10, 14); + rh.renderBlock(x, y, z, renderer); - rh.setTexture( CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorBack.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartMonitorSidesStatus.getIcon(), CableBusTextures.PartMonitorSidesStatus.getIcon() ); + this.renderLights(x, y, z, rh, renderer); + } - rh.setBounds( 6, 6, 13, 10, 10, 14 ); - rh.renderBlock( x, y, z, renderer ); + @Override + public void onNeighborChanged() { + final boolean oldHasRedstone = this.hasRedstone; + this.hasRedstone = this.getHost().hasRedstone(this.getSide()); - this.renderLights( x, y, z, rh, renderer ); - } + if (this.hasRedstone != oldHasRedstone) { + this.updateInternalState(); + this.getHost().markForUpdate(); + } + } - @Override - public void onNeighborChanged() - { - final boolean oldHasRedstone = this.hasRedstone; - this.hasRedstone = this.getHost().hasRedstone( this.getSide() ); + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.getOuterProxy().readFromNBT(extra); + } - if( this.hasRedstone != oldHasRedstone ) - { - this.updateInternalState(); - this.getHost().markForUpdate(); - } - } + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.getOuterProxy().writeToNBT(extra); + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.getOuterProxy().readFromNBT( extra ); - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.getOuterProxy().invalidate(); + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.getOuterProxy().writeToNBT( extra ); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.getOuterProxy().onReady(); + this.hasRedstone = this.getHost().hasRedstone(this.getSide()); + this.updateInternalState(); + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.getOuterProxy().invalidate(); - } + @Override + public void setPartHostInfo( + final ForgeDirection side, final IPartHost host, final TileEntity tile + ) { + super.setPartHostInfo(side, host, tile); + this.getOuterProxy().setValidSides(EnumSet.of(side)); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.getOuterProxy().onReady(); - this.hasRedstone = this.getHost().hasRedstone( this.getSide() ); - this.updateInternalState(); - } + @Override + public IGridNode getExternalFacingNode() { + return this.getOuterProxy().getNode(); + } - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.getOuterProxy().setValidSides( EnumSet.of( side ) ); - } + @Override + public int cableConnectionRenderTo() { + return 5; + } - @Override - public IGridNode getExternalFacingNode() - { - return this.getOuterProxy().getNode(); - } + @Override + public void onPlacement( + final EntityPlayer player, final ItemStack held, final ForgeDirection side + ) { + super.onPlacement(player, held, side); + this.getOuterProxy().setOwner(player); + } - @Override - public int cableConnectionRenderTo() - { - return 5; - } + private void updateInternalState() { + final boolean intention = this.getIntention(); + if (intention == (this.connection == null)) { + if (this.getProxy().getNode() != null + && this.getOuterProxy().getNode() != null) { + if (intention) { + try { + this.connection = AEApi.instance().createGridConnection( + this.getProxy().getNode(), this.getOuterProxy().getNode() + ); + } catch (final FailedConnection e) { + // :( + } + } else { + this.connection.destroy(); + this.connection = null; + } + } + } + } - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.getOuterProxy().setOwner( player ); - } - - private void updateInternalState() - { - final boolean intention = this.getIntention(); - if( intention == ( this.connection == null ) ) - { - if( this.getProxy().getNode() != null && this.getOuterProxy().getNode() != null ) - { - if( intention ) - { - try - { - this.connection = AEApi.instance().createGridConnection( this.getProxy().getNode(), this.getOuterProxy().getNode() ); - } - catch( final FailedConnection e ) - { - // :( - } - } - else - { - this.connection.destroy(); - this.connection = null; - } - } - } - } - - AENetworkProxy getOuterProxy() - { - return this.outerProxy; - } + AENetworkProxy getOuterProxy() { + return this.outerProxy; + } } diff --git a/src/main/java/appeng/parts/networking/PartCable.java b/src/main/java/appeng/parts/networking/PartCable.java index 2607ca9b..da0e8704 100644 --- a/src/main/java/appeng/parts/networking/PartCable.java +++ b/src/main/java/appeng/parts/networking/PartCable.java @@ -18,6 +18,8 @@ package appeng.parts.networking; +import java.io.IOException; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; @@ -40,7 +42,6 @@ import appeng.items.parts.ItemMultiPart; import appeng.me.GridAccessException; import appeng.parts.AEBasePart; import appeng.util.Platform; -import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; @@ -54,1013 +55,1027 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.io.IOException; -import java.util.EnumSet; +public class PartCable extends AEBasePart implements IPartCable { + private final int[] channelsOnSide = { 0, 0, 0, 0, 0, 0 }; + private EnumSet connections = EnumSet.noneOf(ForgeDirection.class); + private boolean powered = false; -public class PartCable extends AEBasePart implements IPartCable -{ + public PartCable(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.PREFERRED); + this.getProxy().setIdlePowerUsage(0.0); + this.getProxy().setColor(AEColor.values( + )[((ItemMultiPart) is.getItem()).variantOf(is.getItemDamage())]); + } - private final int[] channelsOnSide = { 0, 0, 0, 0, 0, 0 }; + @Override + public BusSupport supportsBuses() { + return BusSupport.CABLE; + } - private EnumSet connections = EnumSet.noneOf( ForgeDirection.class ); - private boolean powered = false; + @Override + public AEColor getCableColor() { + return this.getProxy().getColor(); + } - public PartCable( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.PREFERRED ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.getProxy().setColor( AEColor.values()[( (ItemMultiPart) is.getItem() ).variantOf( is.getItemDamage() )] ); - } + @Override + public AECableType getCableConnectionType() { + return AECableType.GLASS; + } - @Override - public BusSupport supportsBuses() - { - return BusSupport.CABLE; - } + @Override + public boolean changeColor(final AEColor newColor, final EntityPlayer who) { + if (this.getCableColor() != newColor) { + ItemStack newPart = null; - @Override - public AEColor getCableColor() - { - return this.getProxy().getColor(); - } + final IParts parts = AEApi.instance().definitions().parts(); - @Override - public AECableType getCableConnectionType() - { - return AECableType.GLASS; - } + 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); + } - @Override - public boolean changeColor( final AEColor newColor, final EntityPlayer who ) - { - if( this.getCableColor() != newColor ) - { - ItemStack newPart = null; + boolean hasPermission = true; - final IParts parts = AEApi.instance().definitions().parts(); + try { + hasPermission = this.getProxy().getSecurity().hasPermission( + who, SecurityPermissions.BUILD + ); + } catch (final GridAccessException e) { + // :P + } - 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 ); - } + if (newPart != null && hasPermission) { + if (Platform.isClient()) { + return true; + } - boolean hasPermission = true; + this.getHost().removePart(ForgeDirection.UNKNOWN, true); + this.getHost().addPart(newPart, ForgeDirection.UNKNOWN, who); + return true; + } + } + return false; + } - try - { - hasPermission = this.getProxy().getSecurity().hasPermission( who, SecurityPermissions.BUILD ); - } - catch( final GridAccessException e ) - { - // :P - } + @Override + public void setValidSides(final EnumSet sides) { + this.getProxy().setValidSides(sides); + } - if( newPart != null && hasPermission ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean isConnected(final ForgeDirection side) { + return this.getConnections().contains(side); + } - this.getHost().removePart( ForgeDirection.UNKNOWN, true ); - this.getHost().addPart( newPart, ForgeDirection.UNKNOWN, who ); - return true; - } - } - return false; - } + public void markForUpdate() { + this.getHost().markForUpdate(); + } - @Override - public void setValidSides( final EnumSet sides ) - { - this.getProxy().setValidSides( sides ); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6.0, 6.0, 6.0, 10.0, 10.0, 10.0); - @Override - public boolean isConnected( final ForgeDirection side ) - { - return this.getConnections().contains( side ); - } + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - public void markForUpdate() - { - this.getHost().markForUpdate(); - } + final IPartHost ph = this.getHost(); + if (ph != null) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart p = ph.getPart(dir); + if (p instanceof IGridHost) { + final double dist = p.cableConnectionRenderTo(); - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6.0, 6.0, 6.0, 10.0, 10.0, 10.0 ); + if (dist > 8) { + continue; + } - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + 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: + } + } + } + } - final IPartHost ph = this.getHost(); - if( ph != null ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart p = ph.getPart( dir ); - if( p instanceof IGridHost ) - { - final double dist = p.cableConnectionRenderTo(); + for (final ForgeDirection of : this.getConnections()) { + 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: + } + } + } - if( dist > 8 ) - { - continue; - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); - 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: - } - } - } - } + 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); + } - for( final ForgeDirection of : this.getConnections() ) - { - 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: - } - } - } + public IIcon getTexture(final AEColor c) { + return this.getGlassTexture(c); + } - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); + public IIcon getGlassTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MECable_Black.getIcon(); + case Blue: + return CableBusTextures.MECable_Blue.getIcon(); + case Brown: + return CableBusTextures.MECable_Brown.getIcon(); + case Cyan: + return CableBusTextures.MECable_Cyan.getIcon(); + case Gray: + return CableBusTextures.MECable_Grey.getIcon(); + case Green: + return CableBusTextures.MECable_Green.getIcon(); + case LightBlue: + return CableBusTextures.MECable_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MECable_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MECable_Lime.getIcon(); + case Magenta: + return CableBusTextures.MECable_Magenta.getIcon(); + case Orange: + return CableBusTextures.MECable_Orange.getIcon(); + case Pink: + return CableBusTextures.MECable_Pink.getIcon(); + case Purple: + return CableBusTextures.MECable_Purple.getIcon(); + case Red: + return CableBusTextures.MECable_Red.getIcon(); + case White: + return CableBusTextures.MECable_White.getIcon(); + case Yellow: + return CableBusTextures.MECable_Yellow.getIcon(); + default: + } - 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 ); - } + final AEColoredItemDefinition glassCable + = AEApi.instance().definitions().parts().cableGlass(); + final ItemStack glassCableStack = glassCable.stack(AEColor.Transparent, 1); - public IIcon getTexture( final AEColor c ) - { - return this.getGlassTexture( c ); - } + return glassCable.item(AEColor.Transparent).getIconIndex(glassCableStack); + } - public IIcon getGlassTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MECable_Black.getIcon(); - case Blue: - return CableBusTextures.MECable_Blue.getIcon(); - case Brown: - return CableBusTextures.MECable_Brown.getIcon(); - case Cyan: - return CableBusTextures.MECable_Cyan.getIcon(); - case Gray: - return CableBusTextures.MECable_Grey.getIcon(); - case Green: - return CableBusTextures.MECable_Green.getIcon(); - case LightBlue: - return CableBusTextures.MECable_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MECable_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MECable_Lime.getIcon(); - case Magenta: - return CableBusTextures.MECable_Magenta.getIcon(); - case Orange: - return CableBusTextures.MECable_Orange.getIcon(); - case Pink: - return CableBusTextures.MECable_Pink.getIcon(); - case Purple: - return CableBusTextures.MECable_Purple.getIcon(); - case Red: - return CableBusTextures.MECable_Red.getIcon(); - case White: - return CableBusTextures.MECable_White.getIcon(); - case Yellow: - return CableBusTextures.MECable_Yellow.getIcon(); - default: - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + boolean useCovered = false; + boolean requireDetailed = false; - final AEColoredItemDefinition glassCable = AEApi.instance().definitions().parts().cableGlass(); - final ItemStack glassCableStack = glassCable.stack( AEColor.Transparent, 1 ); + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final IPart p = this.getHost().getPart(dir); + if (p instanceof IGridHost) { + final IGridHost igh = (IGridHost) p; + final AECableType type = igh.getCableConnectionType(dir.getOpposite()); + if (type == AECableType.COVERED || type == AECableType.SMART) { + useCovered = true; + break; + } + } else if (this.getConnections().contains(dir)) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ + ); + final IPartHost partHost + = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; + if (partHost == null && gh != null + && gh.getCableConnectionType(dir) != AECableType.GLASS) { + requireDetailed = true; + } + } + } - return glassCable.item( AEColor.Transparent ).getIconIndex( glassCableStack ); - } + if (useCovered) { + rh.setTexture(this.getCoveredTexture(this.getCableColor())); + } else { + rh.setTexture(this.getTexture(this.getCableColor())); + } - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - boolean useCovered = false; - boolean requireDetailed = false; + final IPartHost ph = this.getHost(); + for (final ForgeDirection of : EnumSet.complementOf(this.getConnections())) { + final IPart bp = ph.getPart(of); + if (bp instanceof IGridHost) { + final 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); + } + } + } - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart p = this.getHost().getPart( dir ); - if( p instanceof IGridHost ) - { - final IGridHost igh = (IGridHost) p; - final AECableType type = igh.getCableConnectionType( dir.getOpposite() ); - if( type == AECableType.COVERED || type == AECableType.SMART ) - { - useCovered = true; - break; - } - } - else if( this.getConnections().contains( dir ) ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + dir.offsetX, y + dir.offsetY, z + dir.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; - if( partHost == null && gh != null && gh.getCableConnectionType( dir ) != AECableType.GLASS ) - { - requireDetailed = true; - } - } - } + if (this.getConnections().size() != 2 || !this.nonLinear(this.getConnections()) + || 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); + } - if( useCovered ) - { - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } + for (final ForgeDirection of : this.getConnections()) { + this.renderGlassConnection(x, y, z, rh, renderer, of); + } + } else { + final IIcon def = this.getTexture(this.getCableColor()); + rh.setTexture(def); - final IPartHost ph = this.getHost(); - for( final ForgeDirection of : EnumSet.complementOf( this.getConnections() ) ) - { - final IPart bp = ph.getPart( of ); - if( bp instanceof IGridHost ) - { - final 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 ); - } - } - } + for (final ForgeDirection of : this.getConnections()) { + 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: + } + } - if( this.getConnections().size() != 2 || !this.nonLinear( this.getConnections() ) || 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 ); - } + rh.renderBlockCurrentBounds(x, y, z, renderer); + } - for( final ForgeDirection of : this.getConnections() ) - { - this.renderGlassConnection( x, y, z, rh, renderer, of ); - } - } - else - { - final IIcon def = this.getTexture( this.getCableColor() ); - rh.setTexture( def ); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + rh.setTexture(null); + } - for( final ForgeDirection of : this.getConnections() ) - { - 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: - } - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); - rh.renderBlockCurrentBounds( x, y, z, renderer ); - } + if (Platform.isServer()) { + final IGridNode node = this.getGridNode(); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - rh.setTexture( null ); - } + if (node != null) { + int howMany = 0; + for (final IGridConnection gc : node.getConnections()) { + howMany = Math.max(gc.getUsedChannels(), howMany); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); + data.setByte("usedChannels", (byte) howMany); + } + } + } - if( Platform.isServer() ) - { - final IGridNode node = this.getGridNode(); + @Override + public void writeToStream(final ByteBuf data) throws IOException { + int flags = 0; + boolean[] writeSide = new boolean[ForgeDirection.VALID_DIRECTIONS.length]; + int[] channelsPerSide = new int[ForgeDirection.VALID_DIRECTIONS.length]; - if( node != null ) - { - int howMany = 0; - for( final IGridConnection gc : node.getConnections() ) - { - howMany = Math.max( gc.getUsedChannels(), howMany ); - } + for (final ForgeDirection thisSide : ForgeDirection.VALID_DIRECTIONS) { + final IPart part = this.getHost().getPart(thisSide); + if (part != null) { + writeSide[thisSide.ordinal()] = true; + int channels = 0; + if (part.getGridNode() != null) { + final IReadOnlyCollection set + = part.getGridNode().getConnections(); + for (final IGridConnection gc : set) { + channels = Math.max(channels, gc.getUsedChannels()); + } + } + channelsPerSide[thisSide.ordinal()] = channels; + } + } - data.setByte( "usedChannels", (byte) howMany ); - } - } - } + IGridNode n = this.getGridNode(); + if (n != null) { + for (final IGridConnection gc : n.getConnections()) { + final ForgeDirection side = gc.getDirection(n); + if (side != ForgeDirection.UNKNOWN) { + writeSide[side.ordinal()] = true; + channelsPerSide[side.ordinal()] = gc.getUsedChannels(); + flags |= (1 << side.ordinal()); + } + } + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - int flags = 0; - boolean[] writeSide = new boolean[ForgeDirection.VALID_DIRECTIONS.length]; - int[] channelsPerSide = new int[ForgeDirection.VALID_DIRECTIONS.length]; + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + flags |= (1 << ForgeDirection.UNKNOWN.ordinal()); + } + } catch (final GridAccessException e) { + // aww... + } - for( final ForgeDirection thisSide : ForgeDirection.VALID_DIRECTIONS ) - { - final IPart part = this.getHost().getPart( thisSide ); - if( part != null ) - { - writeSide[thisSide.ordinal()] = true; - int channels = 0; - if( part.getGridNode() != null ) - { - final IReadOnlyCollection set = part.getGridNode().getConnections(); - for( final IGridConnection gc : set ) - { - channels = Math.max( channels, gc.getUsedChannels() ); - } - } - channelsPerSide[thisSide.ordinal()] = channels; - } - } + data.writeByte((byte) flags); + // Only write the used channels for sides where we have a part or another cable + for (int i = 0; i < writeSide.length; i++) { + if (writeSide[i]) { + data.writeByte(channelsPerSide[i]); + } + } + } - IGridNode n = this.getGridNode(); - if( n != null ) - { - for( final IGridConnection gc : n.getConnections() ) - { - final ForgeDirection side = gc.getDirection( n ); - if( side != ForgeDirection.UNKNOWN ) - { - writeSide[side.ordinal()] = true; - channelsPerSide[side.ordinal()] = gc.getUsedChannels(); - flags |= ( 1 << side.ordinal() ); - } - } - } + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + int cs = data.readByte(); + final EnumSet myC = this.getConnections().clone(); + final boolean wasPowered = this.powered; + this.powered = false; + boolean channelsChanged = false; - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - flags |= ( 1 << ForgeDirection.UNKNOWN.ordinal() ); - } - } - catch( final GridAccessException e ) - { - // aww... - } + for (final ForgeDirection d : ForgeDirection.values()) { + if (d == ForgeDirection.UNKNOWN) { + final int id = 1 << d.ordinal(); + if (id == (cs & id)) { + this.powered = true; + } + } else { + boolean conOnSide = (cs & (1 << d.ordinal())) != 0; + if (conOnSide) { + this.getConnections().add(d); + } else { + this.getConnections().remove(d); + } - data.writeByte( (byte) flags ); - // Only write the used channels for sides where we have a part or another cable - for( int i = 0; i < writeSide.length; i++ ) - { - if( writeSide[i] ) - { - data.writeByte( channelsPerSide[i] ); - } - } - } + int ch = 0; - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - int cs = data.readByte(); - final EnumSet myC = this.getConnections().clone(); - final boolean wasPowered = this.powered; - this.powered = false; - boolean channelsChanged = false; + // Only read channels if there's a part on this side or a cable connection + // This works only because cables are always read *last* from the packet + // update for a cable bus + if (conOnSide || getHost().getPart(d) != null) { + ch = ((int) data.readByte()) & 0xFF; + } - for( final ForgeDirection d : ForgeDirection.values() ) - { - if( d == ForgeDirection.UNKNOWN ) - { - final int id = 1 << d.ordinal(); - if( id == ( cs & id ) ) - { - this.powered = true; - } - } - else - { - boolean conOnSide = ( cs & ( 1 << d.ordinal() ) ) != 0; - if( conOnSide ) - { - this.getConnections().add( d ); - } - else - { - this.getConnections().remove( d ); - } + if (ch != this.channelsOnSide[d.ordinal()]) { + channelsChanged = true; + this.channelsOnSide[d.ordinal()] = ch; + } + } + } - int ch = 0; + return !myC.equals(this.getConnections()) || wasPowered != this.powered + || channelsChanged; + } - // Only read channels if there's a part on this side or a cable connection - // This works only because cables are always read *last* from the packet update for - // a cable bus - if( conOnSide || getHost().getPart( d ) != null ) - { - ch = ( (int) data.readByte() ) & 0xFF; - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return this.getTexture(this.getCableColor()); + } - if( ch != this.channelsOnSide[d.ordinal()] ) - { - channelsChanged = true; - this.channelsOnSide[d.ordinal()] = ch; - } - } - } + public IIcon getCoveredTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MECovered_Black.getIcon(); + case Blue: + return CableBusTextures.MECovered_Blue.getIcon(); + case Brown: + return CableBusTextures.MECovered_Brown.getIcon(); + case Cyan: + return CableBusTextures.MECovered_Cyan.getIcon(); + case Gray: + return CableBusTextures.MECovered_Gray.getIcon(); + case Green: + return CableBusTextures.MECovered_Green.getIcon(); + case LightBlue: + return CableBusTextures.MECovered_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MECovered_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MECovered_Lime.getIcon(); + case Magenta: + return CableBusTextures.MECovered_Magenta.getIcon(); + case Orange: + return CableBusTextures.MECovered_Orange.getIcon(); + case Pink: + return CableBusTextures.MECovered_Pink.getIcon(); + case Purple: + return CableBusTextures.MECovered_Purple.getIcon(); + case Red: + return CableBusTextures.MECovered_Red.getIcon(); + case White: + return CableBusTextures.MECovered_White.getIcon(); + case Yellow: + return CableBusTextures.MECovered_Yellow.getIcon(); + default: + } - return !myC.equals( this.getConnections() ) || wasPowered != this.powered || channelsChanged; - } + final AEColoredItemDefinition coveredCable + = AEApi.instance().definitions().parts().cableCovered(); + final ItemStack coveredCableStack = coveredCable.stack(AEColor.Transparent, 1); - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return this.getTexture( this.getCableColor() ); - } + return coveredCable.item(AEColor.Transparent).getIconIndex(coveredCableStack); + } - public IIcon getCoveredTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MECovered_Black.getIcon(); - case Blue: - return CableBusTextures.MECovered_Blue.getIcon(); - case Brown: - return CableBusTextures.MECovered_Brown.getIcon(); - case Cyan: - return CableBusTextures.MECovered_Cyan.getIcon(); - case Gray: - return CableBusTextures.MECovered_Gray.getIcon(); - case Green: - return CableBusTextures.MECovered_Green.getIcon(); - case LightBlue: - return CableBusTextures.MECovered_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MECovered_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MECovered_Lime.getIcon(); - case Magenta: - return CableBusTextures.MECovered_Magenta.getIcon(); - case Orange: - return CableBusTextures.MECovered_Orange.getIcon(); - case Pink: - return CableBusTextures.MECovered_Pink.getIcon(); - case Purple: - return CableBusTextures.MECovered_Purple.getIcon(); - case Red: - return CableBusTextures.MECovered_Red.getIcon(); - case White: - return CableBusTextures.MECovered_White.getIcon(); - case Yellow: - return CableBusTextures.MECovered_Yellow.getIcon(); - default: - } + protected boolean nonLinear(final 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)); + } - final AEColoredItemDefinition coveredCable = AEApi.instance().definitions().parts().cableCovered(); - final ItemStack coveredCableStack = coveredCable.stack( AEColor.Transparent, 1 ); + @SideOnly(Side.CLIENT) + private void renderGlassConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final ForgeDirection of + ) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + x + of.offsetX, y + of.offsetY, z + of.offsetZ + ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost gh = te instanceof IGridHost ? (IGridHost) te : null; - return coveredCable.item( AEColor.Transparent ).getIconIndex( coveredCableStack ); - } + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of))); - protected boolean nonLinear( final 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 ) - private void renderGlassConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final 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() ) ); - } + 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.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() ) ); - } + 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; - } + 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 ) ); - } + rh.renderBlock(x, y, z, renderer); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + } - @SideOnly( Side.CLIENT ) void renderCoveredConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final int channels, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + @SideOnly(Side.CLIENT) + void renderCoveredConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final int channels, + final ForgeDirection of + ) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + x + of.offsetX, y + of.offsetY, z + of.offsetZ + ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final 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() ) ); - } + 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.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.renderBlock(x, y, z, renderer); - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } + 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() ) ); - } + 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; - } + 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 ) ); - } + rh.renderBlock(x, y, z, renderer); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + } - @SideOnly( Side.CLIENT ) void renderSmartConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final int channels, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; - AEColor myColor = this.getCableColor(); + @SideOnly(Side.CLIENT) + void renderSmartConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final int channels, + final ForgeDirection of + ) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + x + of.offsetX, y + of.offsetY, z + of.offsetZ + ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + AEColor myColor = this.getCableColor(); - rh.setFacesToRender( EnumSet.complementOf( EnumSet.of( of ) ) ); + rh.setFacesToRender(EnumSet.complementOf(EnumSet.of(of))); - boolean isGlass = false; - 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() ) ); - } + boolean isGlass = false; + 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 ); + 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 ); - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); + this.setSmartConnectionRotations(of, renderer); + final IIcon firstIcon + = new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon secondIcon + = new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); - if( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) - { - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - } + if (of == ForgeDirection.EAST || of == ForgeDirection.WEST) { + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final 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.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 ); + 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; + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest + = 0; - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } + 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() ) ); - } + 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; - } + 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.renderBlock(x, y, z, renderer); + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); - if( !isGlass ) - { - this.setSmartConnectionRotations( of, renderer ); + if (!isGlass) { + this.setSmartConnectionRotations(of, renderer); - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); + final IIcon firstIcon + = new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final 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.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 ); + 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; - } - } + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest + = 0; + } + } - IIcon getSmartTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MESmart_Black.getIcon(); - case Blue: - return CableBusTextures.MESmart_Blue.getIcon(); - case Brown: - return CableBusTextures.MESmart_Brown.getIcon(); - case Cyan: - return CableBusTextures.MESmart_Cyan.getIcon(); - case Gray: - return CableBusTextures.MESmart_Gray.getIcon(); - case Green: - return CableBusTextures.MESmart_Green.getIcon(); - case LightBlue: - return CableBusTextures.MESmart_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MESmart_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MESmart_Lime.getIcon(); - case Magenta: - return CableBusTextures.MESmart_Magenta.getIcon(); - case Orange: - return CableBusTextures.MESmart_Orange.getIcon(); - case Pink: - return CableBusTextures.MESmart_Pink.getIcon(); - case Purple: - return CableBusTextures.MESmart_Purple.getIcon(); - case Red: - return CableBusTextures.MESmart_Red.getIcon(); - case White: - return CableBusTextures.MESmart_White.getIcon(); - case Yellow: - return CableBusTextures.MESmart_Yellow.getIcon(); - default: - } + IIcon getSmartTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MESmart_Black.getIcon(); + case Blue: + return CableBusTextures.MESmart_Blue.getIcon(); + case Brown: + return CableBusTextures.MESmart_Brown.getIcon(); + case Cyan: + return CableBusTextures.MESmart_Cyan.getIcon(); + case Gray: + return CableBusTextures.MESmart_Gray.getIcon(); + case Green: + return CableBusTextures.MESmart_Green.getIcon(); + case LightBlue: + return CableBusTextures.MESmart_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MESmart_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MESmart_Lime.getIcon(); + case Magenta: + return CableBusTextures.MESmart_Magenta.getIcon(); + case Orange: + return CableBusTextures.MESmart_Orange.getIcon(); + case Pink: + return CableBusTextures.MESmart_Pink.getIcon(); + case Purple: + return CableBusTextures.MESmart_Purple.getIcon(); + case Red: + return CableBusTextures.MESmart_Red.getIcon(); + case White: + return CableBusTextures.MESmart_White.getIcon(); + case Yellow: + return CableBusTextures.MESmart_Yellow.getIcon(); + default: + } - final IParts parts = AEApi.instance().definitions().parts(); - final ItemStack smartCableStack = parts.cableSmart().stack( AEColor.Transparent, 1 ); + final IParts parts = AEApi.instance().definitions().parts(); + final ItemStack smartCableStack + = parts.cableSmart().stack(AEColor.Transparent, 1); - return parts.cableCovered().item( AEColor.Transparent ).getIconIndex( smartCableStack ); - } + return parts.cableCovered() + .item(AEColor.Transparent) + .getIconIndex(smartCableStack); + } - @SideOnly( Side.CLIENT ) - protected void setSmartConnectionRotations( final ForgeDirection of, final RenderBlocks renderer ) - { - switch( of ) - { - case UP: - case DOWN: - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; - break; - case NORTH: - case SOUTH: - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateWest = 1; - break; - case EAST: - case WEST: - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateTop = 1; - renderer.uvRotateSouth = 3; - renderer.uvRotateNorth = 0; - break; - default: - break; - } - } + @SideOnly(Side.CLIENT) + protected void + setSmartConnectionRotations(final ForgeDirection of, final RenderBlocks renderer) { + switch (of) { + case UP: + case DOWN: + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; + break; + case NORTH: + case SOUTH: + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateWest = 1; + break; + case EAST: + case WEST: + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateTop = 1; + renderer.uvRotateSouth = 3; + renderer.uvRotateNorth = 0; + break; + default: + break; + } + } - protected CableBusTextures getChannelTex( int i, final boolean b ) - { - if( !this.powered ) - { - i = 0; - } + protected CableBusTextures getChannelTex(int i, final 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; - } - } - } + 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( final AEBaseBlock blk, final int x, final int y, final int z, final IPartRenderHelper rh, final 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.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 ); - rh.renderFace( x, y, z, blk.getRendererInstance().getTexture( ForgeDirection.SOUTH ), ForgeDirection.SOUTH, renderer ); - 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 ); - } + @SideOnly(Side.CLIENT) + protected void renderAllFaces( + final AEBaseBlock blk, + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final 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.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 + ); + rh.renderFace( + x, + y, + z, + blk.getRendererInstance().getTexture(ForgeDirection.SOUTH), + ForgeDirection.SOUTH, + renderer + ); + 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 + ); + } - int[] getChannelsOnSide() - { - return this.channelsOnSide; - } + int[] getChannelsOnSide() { + return this.channelsOnSide; + } - EnumSet getConnections() - { - return this.connections; - } + EnumSet getConnections() { + return this.connections; + } - void setConnections( final EnumSet connections ) - { - this.connections = connections; - } + void setConnections(final EnumSet connections) { + this.connections = connections; + } } diff --git a/src/main/java/appeng/parts/networking/PartCableCovered.java b/src/main/java/appeng/parts/networking/PartCableCovered.java index 64c8fefc..94aec5ff 100644 --- a/src/main/java/appeng/parts/networking/PartCableCovered.java +++ b/src/main/java/appeng/parts/networking/PartCableCovered.java @@ -18,6 +18,7 @@ package appeng.parts.networking; +import java.util.EnumSet; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -41,220 +42,209 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; +public class PartCableCovered extends PartCable { + @Reflected + public PartCableCovered(final ItemStack is) { + super(is); + } + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } -public class PartCableCovered extends PartCable -{ - @Reflected - public PartCableCovered( final ItemStack is ) - { - super( is ); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } + @Override + public AECableType getCableConnectionType() { + return AECableType.COVERED; + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5.0, 5.0, 5.0, 11.0, 11.0, 11.0); - @Override - public AECableType getCableConnectionType() - { - return AECableType.COVERED; - } + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); + for (final ForgeDirection of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); - for( final ForgeDirection of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } + rh.setBounds(5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f); + float offU = 0; + float offV = 9; - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); + OffsetIcon main + = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); - rh.setBounds( 5.0f, 5.0f, 2.0f, 11.0f, 11.0f, 14.0f ); - float offU = 0; - float offV = 9; + for (final ForgeDirection side : + EnumSet.of(ForgeDirection.UP, ForgeDirection.DOWN)) { + rh.renderInventoryFace(main, side, renderer); + } - OffsetIcon main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); + offU = 9; + offV = 0; + main = new OffsetIcon(this.getTexture(this.getCableColor()), offU, offV); - for( final ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } + for (final ForgeDirection side : + EnumSet.of(ForgeDirection.EAST, ForgeDirection.WEST)) { + rh.renderInventoryFace(main, side, renderer); + } - offU = 9; - offV = 0; - main = new OffsetIcon( this.getTexture( this.getCableColor() ), offU, offV ); + main = new OffsetIcon(this.getTexture(this.getCableColor()), 0, 0); - for( final ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } + for (final ForgeDirection side : + EnumSet.of(ForgeDirection.SOUTH, ForgeDirection.NORTH)) { + rh.renderInventoryFace(main, side, renderer); + } - main = new OffsetIcon( this.getTexture( this.getCableColor() ), 0, 0 ); + rh.setTexture(null); + } - for( final ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) - { - rh.renderInventoryFace( main, side, renderer ); - } + @Override + public IIcon getTexture(final AEColor c) { + return this.getCoveredTexture(c); + } - rh.setTexture( null ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture(this.getTexture(this.getCableColor())); - @Override - public IIcon getTexture( final AEColor c ) - { - return this.getCoveredTexture( c ); - } + final EnumSet sides = this.getConnections().clone(); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); + boolean hasBuses = false; + final IPartHost ph = this.getHost(); + for (final ForgeDirection of : EnumSet.complementOf(this.getConnections())) { + final IPart bp = ph.getPart(of); + if (bp instanceof IGridHost) { + if (of != ForgeDirection.UNKNOWN) { + sides.add(of); + hasBuses = true; + } - final EnumSet sides = this.getConnections().clone(); + final int len = bp.cableConnectionRenderTo(); + if (len < 8) { + switch (of) { + case DOWN: + rh.setBounds(6, len, 6, 10, 5, 10); + break; + case EAST: + rh.setBounds(11, 6, 6, 16 - len, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, len, 10, 10, 5); + break; + case SOUTH: + rh.setBounds(6, 6, 11, 10, 10, 16 - len); + break; + case UP: + rh.setBounds(6, 11, 6, 10, 16 - len, 10); + break; + case WEST: + rh.setBounds(len, 6, 6, 5, 10, 10); + break; + default: + continue; + } + rh.renderBlock(x, y, z, renderer); + } + } + } - boolean hasBuses = false; - final IPartHost ph = this.getHost(); - for( final ForgeDirection of : EnumSet.complementOf( this.getConnections() ) ) - { - final IPart bp = ph.getPart( of ); - if( bp instanceof IGridHost ) - { - if( of != ForgeDirection.UNKNOWN ) - { - sides.add( of ); - hasBuses = true; - } + if (sides.size() != 2 || !this.nonLinear(sides) || hasBuses) { + for (final ForgeDirection of : this.getConnections()) { + this.renderCoveredConnection( + x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of + ); + } - final int len = bp.cableConnectionRenderTo(); - if( len < 8 ) - { - switch( of ) - { - case DOWN: - rh.setBounds( 6, len, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16 - len, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, len, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 - len ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16 - len, 10 ); - break; - case WEST: - rh.setBounds( len, 6, 6, 5, 10, 10 ); - break; - default: - continue; - } - rh.renderBlock( x, y, z, renderer ); - } - } - } + rh.setTexture(this.getTexture(this.getCableColor())); + rh.setBounds(5, 5, 5, 11, 11, 11); + rh.renderBlock(x, y, z, renderer); + } else { + final IIcon def = this.getTexture(this.getCableColor()); + final IIcon off = new OffsetIcon(def, 0, -12); + for (final ForgeDirection of : this.getConnections()) { + switch (of) { + case DOWN: + case UP: + rh.setTexture(def, def, off, off, off, off); + renderer.setRenderBounds( + 5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0 + ); + break; + case EAST: + case WEST: + rh.setTexture(off, off, off, off, def, def); + renderer.uvRotateEast = renderer.uvRotateWest = 1; + renderer.uvRotateBottom = renderer.uvRotateTop = 1; + renderer.setRenderBounds( + 0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0 + ); + break; + case NORTH: + case SOUTH: + rh.setTexture(off, off, def, def, off, off); + renderer.uvRotateNorth = renderer.uvRotateSouth = 1; + renderer.setRenderBounds( + 5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0 + ); + break; + default: + } + } - if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) - { - for( final ForgeDirection of : this.getConnections() ) - { - this.renderCoveredConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } + rh.renderBlockCurrentBounds(x, y, z, renderer); + } - rh.setTexture( this.getTexture( this.getCableColor() ) ); - rh.setBounds( 5, 5, 5, 11, 11, 11 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - final IIcon def = this.getTexture( this.getCableColor() ); - final IIcon off = new OffsetIcon( def, 0, -12 ); - for( final ForgeDirection of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - case UP: - rh.setTexture( def, def, off, off, off, off ); - renderer.setRenderBounds( 5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0 ); - break; - case EAST: - case WEST: - rh.setTexture( off, off, off, off, def, def ); - renderer.uvRotateEast = renderer.uvRotateWest = 1; - renderer.uvRotateBottom = renderer.uvRotateTop = 1; - renderer.setRenderBounds( 0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0 ); - break; - case NORTH: - case SOUTH: - rh.setTexture( off, off, def, def, off, off ); - renderer.uvRotateNorth = renderer.uvRotateSouth = 1; - renderer.setRenderBounds( 5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0 ); - break; - default: - } - } - - rh.renderBlockCurrentBounds( x, y, z, renderer ); - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - rh.setTexture( null ); - } + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + rh.setTexture(null); + } } diff --git a/src/main/java/appeng/parts/networking/PartCableGlass.java b/src/main/java/appeng/parts/networking/PartCableGlass.java index d9d738f2..33573414 100644 --- a/src/main/java/appeng/parts/networking/PartCableGlass.java +++ b/src/main/java/appeng/parts/networking/PartCableGlass.java @@ -18,16 +18,12 @@ package appeng.parts.networking; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; - -public class PartCableGlass extends PartCable -{ - @Reflected - public PartCableGlass( final ItemStack is ) - { - super( is ); - } +public class PartCableGlass extends PartCable { + @Reflected + public PartCableGlass(final ItemStack is) { + super(is); + } } diff --git a/src/main/java/appeng/parts/networking/PartCableSmart.java b/src/main/java/appeng/parts/networking/PartCableSmart.java index f3e6e684..a7e02e97 100644 --- a/src/main/java/appeng/parts/networking/PartCableSmart.java +++ b/src/main/java/appeng/parts/networking/PartCableSmart.java @@ -18,6 +18,7 @@ package appeng.parts.networking; +import java.util.EnumSet; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; @@ -45,330 +46,417 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; +public class PartCableSmart extends PartCable { + @Reflected + public PartCableSmart(final ItemStack is) { + super(is); + } + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } -public class PartCableSmart extends PartCable -{ - @Reflected - public PartCableSmart( final ItemStack is ) - { - super( is ); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } + @Override + public AECableType getCableConnectionType() { + return AECableType.SMART; + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(5.0, 5.0, 5.0, 11.0, 11.0, 11.0); - @Override - public AECableType getCableConnectionType() - { - return AECableType.SMART; - } + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 5.0, 5.0, 5.0, 11.0, 11.0, 11.0 ); + for (final ForgeDirection of : this.getConnections()) { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); - for( final ForgeDirection of : this.getConnections() ) - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } + float offU = 0; + float offV = 9; - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); + 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); - float offU = 0; - float offV = 9; + for (final 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); + } - 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 ); + 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( final 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 ); - } + for (final 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); + } - 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 ); + 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( final 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 ); - } + for (final 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); + } - 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 ); + rh.setTexture(null); + } - for( final 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 ); - } + @Override + public IIcon getTexture(final AEColor c) { + return this.getSmartTexture(c); + } - rh.setTexture( null ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture(this.getTexture(this.getCableColor())); - @Override - public IIcon getTexture( final AEColor c ) - { - return this.getSmartTexture( c ); - } + final EnumSet sides = this.getConnections().clone(); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); + boolean hasBuses = false; + final IPartHost ph = this.getHost(); + for (final ForgeDirection of : EnumSet.complementOf(this.getConnections())) { + final IPart bp = ph.getPart(of); + if (bp instanceof IGridHost) { + if (of != ForgeDirection.UNKNOWN) { + sides.add(of); + hasBuses = true; + } - final EnumSet sides = this.getConnections().clone(); + final int len = bp.cableConnectionRenderTo(); + if (len < 8) { + switch (of) { + case DOWN: + rh.setBounds(6, len, 6, 10, 5, 10); + break; + case EAST: + rh.setBounds(11, 6, 6, 16 - len, 10, 10); + break; + case NORTH: + rh.setBounds(6, 6, len, 10, 10, 5); + break; + case SOUTH: + rh.setBounds(6, 6, 11, 10, 10, 16 - len); + break; + case UP: + rh.setBounds(6, 11, 6, 10, 16 - len, 10); + break; + case WEST: + rh.setBounds(len, 6, 6, 5, 10, 10); + break; + default: + continue; + } + rh.renderBlock(x, y, z, renderer); - boolean hasBuses = false; - final IPartHost ph = this.getHost(); - for( final ForgeDirection of : EnumSet.complementOf( this.getConnections() ) ) - { - final IPart bp = ph.getPart( of ); - if( bp instanceof IGridHost ) - { - if( of != ForgeDirection.UNKNOWN ) - { - sides.add( of ); - hasBuses = true; - } + this.setSmartConnectionRotations(of, renderer); + final IIcon firstIcon = new TaughtIcon( + this.getChannelTex(this.getChannelsOnSide()[of.ordinal()], false) + .getIcon(), + -0.2f + ); + final IIcon secondIcon = new TaughtIcon( + this.getChannelTex(this.getChannelsOnSide()[of.ordinal()], true) + .getIcon(), + -0.2f + ); - final int len = bp.cableConnectionRenderTo(); - if( len < 8 ) - { - switch( of ) - { - case DOWN: - rh.setBounds( 6, len, 6, 10, 5, 10 ); - break; - case EAST: - rh.setBounds( 11, 6, 6, 16 - len, 10, 10 ); - break; - case NORTH: - rh.setBounds( 6, 6, len, 10, 10, 5 ); - break; - case SOUTH: - rh.setBounds( 6, 6, 11, 10, 10, 16 - len ); - break; - case UP: - rh.setBounds( 6, 11, 6, 10, 16 - len, 10 ); - break; - case WEST: - rh.setBounds( len, 6, 6, 5, 10, 10 ); - break; - default: - continue; - } - rh.renderBlock( x, y, z, renderer ); + if (of == ForgeDirection.EAST || of == ForgeDirection.WEST) { + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico + = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); + } - this.setSmartConnectionRotations( of, renderer ); - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( this.getChannelsOnSide()[of.ordinal()], false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( this.getChannelsOnSide()[of.ordinal()], true ).getIcon(), -0.2f ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().blackVariant + ); + rh.setTexture( + firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - if( of == ForgeDirection.EAST || of == ForgeDirection.WEST ) - { - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); - } + Tessellator.instance.setColorOpaque_I( + this.getCableColor().whiteVariant + ); + rh.setTexture( + secondIcon, + secondIcon, + secondIcon, + secondIcon, + secondIcon, + secondIcon + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + renderer.uvRotateBottom = renderer.uvRotateEast + = renderer.uvRotateNorth = renderer.uvRotateSouth + = renderer.uvRotateTop = renderer.uvRotateWest = 0; - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + rh.setTexture(this.getTexture(this.getCableColor())); + } + } + } - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + if (sides.size() != 2 || !this.nonLinear(sides) || hasBuses) { + for (final ForgeDirection of : this.getConnections()) { + this.renderSmartConnection( + x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of + ); + } - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } - } - } + rh.setTexture(this.getCoveredTexture(this.getCableColor())); + rh.setBounds(5, 5, 5, 11, 11, 11); + rh.renderBlock(x, y, z, renderer); + } else { + ForgeDirection selectedSide = ForgeDirection.UNKNOWN; - if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) - { - for( final ForgeDirection of : this.getConnections() ) - { - this.renderSmartConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } + for (final ForgeDirection of : this.getConnections()) { + selectedSide = of; + break; + } - rh.setTexture( this.getCoveredTexture( this.getCableColor() ) ); - rh.setBounds( 5, 5, 5, 11, 11, 11 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - ForgeDirection selectedSide = ForgeDirection.UNKNOWN; + final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; + final IIcon def = this.getTexture(this.getCableColor()); + final IIcon off = new OffsetIcon(def, 0, -12); - for( final ForgeDirection of : this.getConnections() ) - { - selectedSide = of; - break; - } + final IIcon firstTaughtIcon + = new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon firstOffsetIcon = new OffsetIcon(firstTaughtIcon, 0, -12); - final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; - final IIcon def = this.getTexture( this.getCableColor() ); - final IIcon off = new OffsetIcon( def, 0, -12 ); + final IIcon secondTaughtIcon + = new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); + final IIcon secondOffsetIcon = new OffsetIcon(secondTaughtIcon, 0, -12); - final IIcon firstTaughtIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon firstOffsetIcon = new OffsetIcon( firstTaughtIcon, 0, -12 ); + switch (selectedSide) { + case DOWN: + case UP: + renderer.setRenderBounds( + 5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0 + ); + rh.setTexture(def, def, off, off, off, off); + rh.renderBlockCurrentBounds(x, y, z, renderer); - final IIcon secondTaughtIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - final IIcon secondOffsetIcon = new OffsetIcon( secondTaughtIcon, 0, -12 ); + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; - switch( selectedSide ) - { - case DOWN: - case UP: - renderer.setRenderBounds( 5 / 16.0, 0, 5 / 16.0, 11 / 16.0, 16 / 16.0, 11 / 16.0 ); - rh.setTexture( def, def, off, off, off, off ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; + Tessellator.instance.setColorOpaque_I( + this.getCableColor().blackVariant + ); + rh.setTexture( + firstTaughtIcon, + firstTaughtIcon, + firstOffsetIcon, + firstOffsetIcon, + firstOffsetIcon, + firstOffsetIcon + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().whiteVariant + ); + rh.setTexture( + secondTaughtIcon, + secondTaughtIcon, + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); + break; + case EAST: + case WEST: + rh.setTexture(off, off, off, off, def, def); + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateTop = 1; + renderer.uvRotateSouth = 0; + renderer.uvRotateNorth = 0; - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstTaughtIcon, firstTaughtIcon, firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico + = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondTaughtIcon, secondTaughtIcon, secondOffsetIcon, secondOffsetIcon, secondOffsetIcon, secondOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case EAST: - case WEST: - rh.setTexture( off, off, off, off, def, def ); - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateTop = 1; - renderer.uvRotateSouth = 0; - renderer.uvRotateNorth = 0; + renderer.setRenderBounds( + 0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0 + ); + rh.renderBlockCurrentBounds(x, y, z, renderer); - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); - renderer.setRenderBounds( 0, 5 / 16.0, 5 / 16.0, 16 / 16.0, 11 / 16.0, 11 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); + FlippableIcon fpA = new FlippableIcon(firstTaughtIcon); + FlippableIcon fpB = new FlippableIcon(secondTaughtIcon); - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + fpA = new FlippableIcon(firstTaughtIcon); + fpB = new FlippableIcon(secondTaughtIcon); - FlippableIcon fpA = new FlippableIcon( firstTaughtIcon ); - FlippableIcon fpB = new FlippableIcon( secondTaughtIcon ); + fpA.setFlip(true, false); + fpB.setFlip(true, false); - fpA = new FlippableIcon( firstTaughtIcon ); - fpB = new FlippableIcon( secondTaughtIcon ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().blackVariant + ); + rh.setTexture( + firstOffsetIcon, + firstOffsetIcon, + firstOffsetIcon, + firstOffsetIcon, + firstTaughtIcon, + fpA + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - fpA.setFlip( true, false ); - fpB.setFlip( true, false ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().whiteVariant + ); + rh.setTexture( + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon, + secondOffsetIcon, + secondTaughtIcon, + fpB + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); + break; + case NORTH: + case SOUTH: + rh.setTexture(off, off, def, def, off, off); + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateWest = 1; + renderer.setRenderBounds( + 5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0 + ); + rh.renderBlockCurrentBounds(x, y, z, renderer); - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstOffsetIcon, firstTaughtIcon, fpA ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffsetIcon, secondOffsetIcon, secondOffsetIcon, secondOffsetIcon, secondTaughtIcon, fpB ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case NORTH: - case SOUTH: - rh.setTexture( off, off, def, def, off, off ); - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateWest = 1; - renderer.setRenderBounds( 5 / 16.0, 5 / 16.0, 0, 11 / 16.0, 11 / 16.0, 16 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().blackVariant + ); + rh.setTexture( + firstOffsetIcon, + firstOffsetIcon, + firstTaughtIcon, + firstTaughtIcon, + firstOffsetIcon, + firstOffsetIcon + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().whiteVariant + ); + rh.setTexture( + secondOffsetIcon, + secondOffsetIcon, + secondTaughtIcon, + secondTaughtIcon, + secondOffsetIcon, + secondOffsetIcon + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); + break; + default: + break; + } + } - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffsetIcon, firstOffsetIcon, firstTaughtIcon, firstTaughtIcon, firstOffsetIcon, firstOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffsetIcon, secondOffsetIcon, secondTaughtIcon, secondTaughtIcon, secondOffsetIcon, secondOffsetIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - default: - break; - } - } - - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - rh.setTexture( null ); - } + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + rh.setTexture(null); + } } diff --git a/src/main/java/appeng/parts/networking/PartDenseCable.java b/src/main/java/appeng/parts/networking/PartDenseCable.java index c6113780..ebc8b8f0 100644 --- a/src/main/java/appeng/parts/networking/PartDenseCable.java +++ b/src/main/java/appeng/parts/networking/PartDenseCable.java @@ -18,6 +18,7 @@ package appeng.parts.networking; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.networking.GridFlags; @@ -49,481 +50,560 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; +public class PartDenseCable extends PartCable { + @Reflected + public PartDenseCable(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED); + } -public class PartDenseCable extends PartCable -{ - @Reflected - public PartDenseCable( final ItemStack is ) - { - super( is ); + @Override + public BusSupport supportsBuses() { + return BusSupport.DENSE_CABLE; + } - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY, GridFlags.PREFERRED ); - } + @Override + public AECableType getCableConnectionType() { + return AECableType.DENSE; + } - @Override - public BusSupport supportsBuses() - { - return BusSupport.DENSE_CABLE; - } + @Override + public void getBoxes(final IPartCollisionHelper bch) { + final boolean noLadder = !bch.isBBCollision(); + final double min = noLadder ? 3.0 : 4.9; + final double max = noLadder ? 13.0 : 11.1; - @Override - public AECableType getCableConnectionType() - { - return AECableType.DENSE; - } + bch.addBox(min, min, min, max, max, max); - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - final boolean noLadder = !bch.isBBCollision(); - final double min = noLadder ? 3.0 : 4.9; - final double max = noLadder ? 13.0 : 11.1; + if (Platform.isServer()) { + final IGridNode n = this.getGridNode(); + if (n != null) { + this.setConnections(n.getConnectedSides()); + } else { + this.getConnections().clear(); + } + } - bch.addBox( min, min, min, max, max, max ); + for (final ForgeDirection of : this.getConnections()) { + if (this.isDense(of)) { + switch (of) { + case DOWN: + bch.addBox(min, 0.0, min, max, min, max); + break; + case EAST: + bch.addBox(max, min, min, 16.0, max, max); + break; + case NORTH: + bch.addBox(min, min, 0.0, max, max, min); + break; + case SOUTH: + bch.addBox(min, min, max, max, max, 16.0); + break; + case UP: + bch.addBox(min, max, min, max, 16.0, max); + break; + case WEST: + bch.addBox(0.0, min, min, min, max, max); + break; + default: + } + } else { + switch (of) { + case DOWN: + bch.addBox(5.0, 0.0, 5.0, 11.0, 5.0, 11.0); + break; + case EAST: + bch.addBox(11.0, 5.0, 5.0, 16.0, 11.0, 11.0); + break; + case NORTH: + bch.addBox(5.0, 5.0, 0.0, 11.0, 11.0, 5.0); + break; + case SOUTH: + bch.addBox(5.0, 5.0, 11.0, 11.0, 11.0, 16.0); + break; + case UP: + bch.addBox(5.0, 11.0, 5.0, 11.0, 16.0, 11.0); + break; + case WEST: + bch.addBox(0.0, 5.0, 5.0, 5.0, 11.0, 11.0); + break; + default: + } + } + } + } - if( Platform.isServer() ) - { - final IGridNode n = this.getGridNode(); - if( n != null ) - { - this.setConnections( n.getConnectedSides() ); - } - else - { - this.getConnections().clear(); - } - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.0, -0.0, 0.3); + rh.setBounds(4.0f, 4.0f, 2.0f, 12.0f, 12.0f, 14.0f); - for( final ForgeDirection of : this.getConnections() ) - { - if( this.isDense( of ) ) - { - switch( of ) - { - case DOWN: - bch.addBox( min, 0.0, min, max, min, max ); - break; - case EAST: - bch.addBox( max, min, min, 16.0, max, max ); - break; - case NORTH: - bch.addBox( min, min, 0.0, max, max, min ); - break; - case SOUTH: - bch.addBox( min, min, max, max, max, 16.0 ); - break; - case UP: - bch.addBox( min, max, min, max, 16.0, max ); - break; - case WEST: - bch.addBox( 0.0, min, min, min, max, max ); - break; - default: - } - } - else - { - switch( of ) - { - case DOWN: - bch.addBox( 5.0, 0.0, 5.0, 11.0, 5.0, 11.0 ); - break; - case EAST: - bch.addBox( 11.0, 5.0, 5.0, 16.0, 11.0, 11.0 ); - break; - case NORTH: - bch.addBox( 5.0, 5.0, 0.0, 11.0, 11.0, 5.0 ); - break; - case SOUTH: - bch.addBox( 5.0, 5.0, 11.0, 11.0, 11.0, 16.0 ); - break; - case UP: - bch.addBox( 5.0, 11.0, 5.0, 11.0, 16.0, 11.0 ); - break; - case WEST: - bch.addBox( 0.0, 5.0, 5.0, 5.0, 11.0, 11.0 ); - break; - default: - } - } - } - } + float offU = 0; + float offV = 9; - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.0, -0.0, 0.3 ); - rh.setBounds( 4.0f, 4.0f, 2.0f, 12.0f, 12.0f, 14.0f ); + 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); - float offU = 0; - float offV = 9; + for (final ForgeDirection side : + EnumSet.of(ForgeDirection.UP, ForgeDirection.DOWN)) { + rh.renderInventoryFace(main, side, renderer); + rh.renderInventoryFace(ch1, side, renderer); + rh.renderInventoryFace(ch2, side, renderer); + } - 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 ); + 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( final ForgeDirection side : EnumSet.of( ForgeDirection.UP, ForgeDirection.DOWN ) ) - { - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } + for (final ForgeDirection side : + EnumSet.of(ForgeDirection.EAST, ForgeDirection.WEST)) { + 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 ); + 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( final ForgeDirection side : EnumSet.of( ForgeDirection.EAST, ForgeDirection.WEST ) ) - { - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } + for (final ForgeDirection side : + EnumSet.of(ForgeDirection.SOUTH, ForgeDirection.NORTH)) { + 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 ); + rh.setTexture(null); + } - for( final ForgeDirection side : EnumSet.of( ForgeDirection.SOUTH, ForgeDirection.NORTH ) ) - { - rh.renderInventoryFace( main, side, renderer ); - rh.renderInventoryFace( ch1, side, renderer ); - rh.renderInventoryFace( ch2, side, renderer ); - } + @Override + public IIcon getTexture(final AEColor c) { + if (c == AEColor.Transparent) { + return AEApi.instance() + .definitions() + .parts() + .cableSmart() + .stack(AEColor.Transparent, 1) + .getIconIndex(); + } - rh.setTexture( null ); - } + return this.getSmartTexture(c); + } - @Override - public IIcon getTexture( final AEColor c ) - { - if( c == AEColor.Transparent ) - { - return AEApi.instance().definitions().parts().cableSmart().stack( AEColor.Transparent, 1 ).getIconIndex(); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture(this.getTexture(this.getCableColor())); - return this.getSmartTexture( c ); - } + final EnumSet sides = this.getConnections().clone(); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTexture( this.getCableColor() ) ); + boolean hasBuses = false; + for (final ForgeDirection of : this.getConnections()) { + if (!this.isDense(of)) { + hasBuses = true; + } + } - final EnumSet sides = this.getConnections().clone(); + if (sides.size() != 2 || !this.nonLinear(sides) || hasBuses) { + for (final ForgeDirection of : this.getConnections()) { + if (this.isDense(of)) { + this.renderDenseConnection( + x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of + ); + } else if (this.isSmart(of)) { + this.renderSmartConnection( + x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of + ); + } else { + this.renderCoveredConnection( + x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of + ); + } + } - boolean hasBuses = false; - for( final ForgeDirection of : this.getConnections() ) - { - if( !this.isDense( of ) ) - { - hasBuses = true; - } - } + rh.setTexture(this.getDenseTexture(this.getCableColor())); + rh.setBounds(3, 3, 3, 13, 13, 13); + rh.renderBlock(x, y, z, renderer); + } else { + ForgeDirection selectedSide = ForgeDirection.UNKNOWN; - if( sides.size() != 2 || !this.nonLinear( sides ) || hasBuses ) - { - for( final ForgeDirection of : this.getConnections() ) - { - if( this.isDense( of ) ) - { - this.renderDenseConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - else if( this.isSmart( of ) ) - { - this.renderSmartConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - else - { - this.renderCoveredConnection( x, y, z, rh, renderer, this.getChannelsOnSide()[of.ordinal()], of ); - } - } + for (final ForgeDirection of : this.getConnections()) { + selectedSide = of; + break; + } - rh.setTexture( this.getDenseTexture( this.getCableColor() ) ); - rh.setBounds( 3, 3, 3, 13, 13, 13 ); - rh.renderBlock( x, y, z, renderer ); - } - else - { - ForgeDirection selectedSide = ForgeDirection.UNKNOWN; + final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; + final IIcon def = this.getTexture(this.getCableColor()); + final IIcon off = new OffsetIcon(def, 0, -12); - for( final ForgeDirection of : this.getConnections() ) - { - selectedSide = of; - break; - } + final IIcon firstIcon + = new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon firstOffset = new OffsetIcon(firstIcon, 0, -12); - final int channels = this.getChannelsOnSide()[selectedSide.ordinal()]; - final IIcon def = this.getTexture( this.getCableColor() ); - final IIcon off = new OffsetIcon( def, 0, -12 ); + final IIcon secondIcon + = new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); + final IIcon secondOffset = new OffsetIcon(secondIcon, 0, -12); - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon firstOffset = new OffsetIcon( firstIcon, 0, -12 ); + switch (selectedSide) { + case DOWN: + case UP: + renderer.setRenderBounds( + 3 / 16.0, 0, 3 / 16.0, 13 / 16.0, 16 / 16.0, 13 / 16.0 + ); + rh.setTexture(def, def, off, off, off, off); + rh.renderBlockCurrentBounds(x, y, z, renderer); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); - final IIcon secondOffset = new OffsetIcon( secondIcon, 0, -12 ); + renderer.uvRotateTop = 0; + renderer.uvRotateBottom = 0; + renderer.uvRotateSouth = 3; + renderer.uvRotateEast = 3; - switch( selectedSide ) - { - case DOWN: - case UP: - renderer.setRenderBounds( 3 / 16.0, 0, 3 / 16.0, 13 / 16.0, 16 / 16.0, 13 / 16.0 ); - rh.setTexture( def, def, off, off, off, off ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); - renderer.uvRotateTop = 0; - renderer.uvRotateBottom = 0; - renderer.uvRotateSouth = 3; - renderer.uvRotateEast = 3; + Tessellator.instance.setColorOpaque_I( + this.getCableColor().blackVariant + ); + rh.setTexture( + firstIcon, + firstIcon, + firstOffset, + firstOffset, + firstOffset, + firstOffset + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().whiteVariant + ); + rh.setTexture( + secondIcon, + secondIcon, + secondOffset, + secondOffset, + secondOffset, + secondOffset + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); + break; + case EAST: + case WEST: + rh.setTexture(off, off, off, off, def, def); + renderer.uvRotateEast = 2; + renderer.uvRotateWest = 1; + renderer.uvRotateBottom = 2; + renderer.uvRotateTop = 1; + renderer.uvRotateSouth = 0; + renderer.uvRotateNorth = 0; - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstIcon, firstIcon, firstOffset, firstOffset, firstOffset, firstOffset ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); + final FlippableIcon ico + = blk.getRendererInstance().getTexture(ForgeDirection.EAST); + ico.setFlip(false, true); - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondOffset, secondOffset, secondOffset, secondOffset ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case EAST: - case WEST: - rh.setTexture( off, off, off, off, def, def ); - renderer.uvRotateEast = 2; - renderer.uvRotateWest = 1; - renderer.uvRotateBottom = 2; - renderer.uvRotateTop = 1; - renderer.uvRotateSouth = 0; - renderer.uvRotateNorth = 0; + renderer.setRenderBounds( + 0, 3 / 16.0, 3 / 16.0, 16 / 16.0, 13 / 16.0, 13 / 16.0 + ); + rh.renderBlockCurrentBounds(x, y, z, renderer); - final AEBaseBlock blk = (AEBaseBlock) rh.getBlock(); - final FlippableIcon ico = blk.getRendererInstance().getTexture( ForgeDirection.EAST ); - ico.setFlip( false, true ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); - renderer.setRenderBounds( 0, 3 / 16.0, 3 / 16.0, 16 / 16.0, 13 / 16.0, 13 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); + final FlippableIcon fpA = new FlippableIcon(firstIcon); + final FlippableIcon fpB = new FlippableIcon(secondIcon); - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + fpA.setFlip(true, false); + fpB.setFlip(true, false); - final FlippableIcon fpA = new FlippableIcon( firstIcon ); - final FlippableIcon fpB = new FlippableIcon( secondIcon ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().blackVariant + ); + rh.setTexture( + firstOffset, firstOffset, firstOffset, firstOffset, firstIcon, fpA + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - fpA.setFlip( true, false ); - fpB.setFlip( true, false ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().whiteVariant + ); + rh.setTexture( + secondOffset, + secondOffset, + secondOffset, + secondOffset, + secondIcon, + fpB + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); + break; + case NORTH: + case SOUTH: + rh.setTexture(off, off, def, def, off, off); + renderer.uvRotateTop = 3; + renderer.uvRotateBottom = 3; + renderer.uvRotateNorth = 1; + renderer.uvRotateSouth = 2; + renderer.uvRotateWest = 1; + renderer.setRenderBounds( + 3 / 16.0, 3 / 16.0, 0, 13 / 16.0, 13 / 16.0, 16 / 16.0 + ); + rh.renderBlockCurrentBounds(x, y, z, renderer); - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffset, firstOffset, firstOffset, firstOffset, firstIcon, fpA ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffset, secondOffset, secondOffset, secondOffset, secondIcon, fpB ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - case NORTH: - case SOUTH: - rh.setTexture( off, off, def, def, off, off ); - renderer.uvRotateTop = 3; - renderer.uvRotateBottom = 3; - renderer.uvRotateNorth = 1; - renderer.uvRotateSouth = 2; - renderer.uvRotateWest = 1; - renderer.setRenderBounds( 3 / 16.0, 3 / 16.0, 0, 13 / 16.0, 13 / 16.0, 16 / 16.0 ); - rh.renderBlockCurrentBounds( x, y, z, renderer ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().blackVariant + ); + rh.setTexture( + firstOffset, + firstOffset, + firstIcon, + firstIcon, + firstOffset, + firstOffset + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); - Tessellator.instance.setBrightness( 15 << 20 | 15 << 4 ); + Tessellator.instance.setColorOpaque_I( + this.getCableColor().whiteVariant + ); + rh.setTexture( + secondOffset, + secondOffset, + secondIcon, + secondIcon, + secondOffset, + secondOffset + ); + this.renderAllFaces( + (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer + ); + break; + default: + break; + } + } - Tessellator.instance.setColorOpaque_I( this.getCableColor().blackVariant ); - rh.setTexture( firstOffset, firstOffset, firstIcon, firstIcon, firstOffset, firstOffset ); - 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(null); + } - Tessellator.instance.setColorOpaque_I( this.getCableColor().whiteVariant ); - rh.setTexture( secondOffset, secondOffset, secondIcon, secondIcon, secondOffset, secondOffset ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); - break; - default: - break; - } - } + @SideOnly(Side.CLIENT) + private void renderDenseConnection( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer, + final int channels, + final ForgeDirection of + ) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + x + of.offsetX, y + of.offsetY, z + of.offsetZ + ); + final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; + final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; + AEColor myColor = this.getCableColor(); + /* + * ( ghh != null && partHost != null && ghh.getCableConnectionType( of ) == + * AECableType.GLASS && partHost.getPart( of.getOpposite() ) == null ) { isGlass = + * true; rh.setTexture( getGlassTexture( myColor = partHost.getColor() ) ); } else + * if ( partHost == null && ghh != null && ghh.getCableConnectionType( of ) != + * AECableType.GLASS ) { rh.setTexture( getSmartTexture( myColor ) ); switch (of) + * { case DOWN: rh.setBounds( 3, 0, 3, 13, 4, 13 ); break; case EAST: + * rh.setBounds( 12, 3, 3, 16, 13, 13 ); break; case NORTH: rh.setBounds( 3, 3, 0, + * 13, 13, 4 + * ); break; case SOUTH: rh.setBounds( 3, 3, 12, 13, 13, 16 ); break; case UP: + * rh.setBounds( 3, 12, 3, 13, 16, 13 ); break; case WEST: rh.setBounds( 0, 3, 3, + * 4, 13, 13 ); break; default: return; } rh.renderBlock( x, y, z, renderer ); if + * ( true ) { setSmartConnectionRotations( of, renderer ); IIcon firstIcon = new + * TaughtIcon( getChannelTex( channels, false ).getIcon(), -0.2f ); IIcon + * secondIcon = new TaughtIcon( 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 << 5 ); + * Tessellator.INSTANCE.setColorOpaque_I( myColor.mediumVariant ); rh.setTexture( + * firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); + * renderAllFaces( (AEBaseBlock) + * rh.getBlock(), x, y, z, renderer ); + * Tessellator.INSTANCE.setColorOpaque_I( myColor.whiteVariant ); rh.setTexture( + * secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); + * renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, renderer ); + * renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = + * renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; } + * rh.setTexture( getTexture( getCableColor() ) ); } + */ - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - rh.setTexture( null ); - } + 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) { + rh.setTexture(this.getTexture(myColor = partHost.getColor())); + } else { + rh.setTexture(this.getTexture(this.getCableColor())); + } - @SideOnly( Side.CLIENT ) - private void renderDenseConnection( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer, final int channels, final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( x + of.offsetX, y + of.offsetY, z + of.offsetZ ); - final IPartHost partHost = te instanceof IPartHost ? (IPartHost) te : null; - final IGridHost ghh = te instanceof IGridHost ? (IGridHost) te : null; - AEColor myColor = this.getCableColor(); - /* - * ( ghh != null && partHost != null && ghh.getCableConnectionType( of ) == AECableType.GLASS && - * partHost.getPart( - * of.getOpposite() ) == null ) { isGlass = true; rh.setTexture( getGlassTexture( myColor = partHost.getColor() - * ) ); - * } else if ( partHost == null && ghh != null && ghh.getCableConnectionType( of ) != AECableType.GLASS ) { - * rh.setTexture( getSmartTexture( myColor ) ); switch (of) { case DOWN: rh.setBounds( 3, 0, 3, 13, 4, 13 ); - * break; case EAST: rh.setBounds( 12, 3, 3, 16, 13, 13 ); break; case NORTH: rh.setBounds( 3, 3, 0, 13, 13, 4 - * ); break; case SOUTH: rh.setBounds( 3, 3, 12, 13, 13, 16 ); break; case UP: rh.setBounds( 3, 12, 3, 13, 16, - * 13 ); break; case WEST: rh.setBounds( 0, 3, 3, 4, 13, 13 ); break; default: return; } rh.renderBlock( x, y, - * z, renderer ); - * if ( true ) { setSmartConnectionRotations( of, renderer ); IIcon firstIcon = new TaughtIcon( getChannelTex( - * channels, false ).getIcon(), -0.2f ); IIcon secondIcon = new TaughtIcon( 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 << 5 ); Tessellator.INSTANCE.setColorOpaque_I( - * myColor.mediumVariant ); rh.setTexture( firstIcon, firstIcon, firstIcon, firstIcon, firstIcon, firstIcon ); - * renderAllFaces( (AEBaseBlock) - * rh.getBlock(), x, y, z, renderer ); - * Tessellator.INSTANCE.setColorOpaque_I( myColor.whiteVariant ); rh.setTexture( secondIcon, secondIcon, - * secondIcon, secondIcon, secondIcon, - * secondIcon ); renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, renderer ); - * renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = - * renderer.uvRotateTop = renderer.uvRotateWest = 0; } - * rh.setTexture( getTexture( getCableColor() ) ); } - */ + switch (of) { + case DOWN: + rh.setBounds(4, 0, 4, 12, 5, 12); + break; + case EAST: + rh.setBounds(11, 4, 4, 16, 12, 12); + break; + case NORTH: + rh.setBounds(4, 4, 0, 12, 12, 5); + break; + case SOUTH: + rh.setBounds(4, 4, 11, 12, 12, 16); + break; + case UP: + rh.setBounds(4, 11, 4, 12, 16, 12); + break; + case WEST: + rh.setBounds(0, 4, 4, 5, 12, 12); + break; + default: + return; + } - 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 ) - { - rh.setTexture( this.getTexture( myColor = partHost.getColor() ) ); - } - else - { - rh.setTexture( this.getTexture( this.getCableColor() ) ); - } + rh.renderBlock(x, y, z, renderer); - switch( of ) - { - case DOWN: - rh.setBounds( 4, 0, 4, 12, 5, 12 ); - break; - case EAST: - rh.setBounds( 11, 4, 4, 16, 12, 12 ); - break; - case NORTH: - rh.setBounds( 4, 4, 0, 12, 12, 5 ); - break; - case SOUTH: - rh.setBounds( 4, 4, 11, 12, 12, 16 ); - break; - case UP: - rh.setBounds( 4, 11, 4, 12, 16, 12 ); - break; - case WEST: - rh.setBounds( 0, 4, 4, 5, 12, 12 ); - break; - default: - return; - } + rh.setFacesToRender(EnumSet.allOf(ForgeDirection.class)); + final boolean isGlass = false; + if (!isGlass) { + this.setSmartConnectionRotations(of, renderer); - rh.renderBlock( x, y, z, renderer ); + final IIcon firstIcon + = new TaughtIcon(this.getChannelTex(channels, false).getIcon(), -0.2f); + final IIcon secondIcon + = new TaughtIcon(this.getChannelTex(channels, true).getIcon(), -0.2f); - rh.setFacesToRender( EnumSet.allOf( ForgeDirection.class ) ); - final boolean isGlass = false; - if( !isGlass ) - { - this.setSmartConnectionRotations( of, renderer ); + 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); - final IIcon firstIcon = new TaughtIcon( this.getChannelTex( channels, false ).getIcon(), -0.2f ); - final IIcon secondIcon = new TaughtIcon( this.getChannelTex( channels, true ).getIcon(), -0.2f ); + Tessellator.instance.setColorOpaque_I(myColor.whiteVariant); + rh.setTexture( + secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon + ); + this.renderAllFaces((AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer); - 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 ); + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest + = 0; + } + } - Tessellator.instance.setColorOpaque_I( myColor.whiteVariant ); - rh.setTexture( secondIcon, secondIcon, secondIcon, secondIcon, secondIcon, secondIcon ); - this.renderAllFaces( (AEBaseBlock) rh.getBlock(), x, y, z, rh, renderer ); + private boolean isSmart(final ForgeDirection of) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + this.getTile().xCoord + of.offsetX, + this.getTile().yCoord + of.offsetY, + this.getTile().zCoord + of.offsetZ + ); + if (te instanceof IGridHost) { + final AECableType t + = ((IGridHost) te).getCableConnectionType(of.getOpposite()); + return t == AECableType.SMART; + } + return false; + } - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - } - } + private IIcon getDenseTexture(final AEColor c) { + switch (c) { + case Black: + return CableBusTextures.MEDense_Black.getIcon(); + case Blue: + return CableBusTextures.MEDense_Blue.getIcon(); + case Brown: + return CableBusTextures.MEDense_Brown.getIcon(); + case Cyan: + return CableBusTextures.MEDense_Cyan.getIcon(); + case Gray: + return CableBusTextures.MEDense_Gray.getIcon(); + case Green: + return CableBusTextures.MEDense_Green.getIcon(); + case LightBlue: + return CableBusTextures.MEDense_LightBlue.getIcon(); + case LightGray: + return CableBusTextures.MEDense_LightGrey.getIcon(); + case Lime: + return CableBusTextures.MEDense_Lime.getIcon(); + case Magenta: + return CableBusTextures.MEDense_Magenta.getIcon(); + case Orange: + return CableBusTextures.MEDense_Orange.getIcon(); + case Pink: + return CableBusTextures.MEDense_Pink.getIcon(); + case Purple: + return CableBusTextures.MEDense_Purple.getIcon(); + case Red: + return CableBusTextures.MEDense_Red.getIcon(); + case White: + return CableBusTextures.MEDense_White.getIcon(); + case Yellow: + return CableBusTextures.MEDense_Yellow.getIcon(); + default: + } - private boolean isSmart( final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + of.offsetX, this.getTile().yCoord + of.offsetY, this.getTile().zCoord + of.offsetZ ); - if( te instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); - return t == AECableType.SMART; - } - return false; - } + return this.getItemStack().getIconIndex(); + } - private IIcon getDenseTexture( final AEColor c ) - { - switch( c ) - { - case Black: - return CableBusTextures.MEDense_Black.getIcon(); - case Blue: - return CableBusTextures.MEDense_Blue.getIcon(); - case Brown: - return CableBusTextures.MEDense_Brown.getIcon(); - case Cyan: - return CableBusTextures.MEDense_Cyan.getIcon(); - case Gray: - return CableBusTextures.MEDense_Gray.getIcon(); - case Green: - return CableBusTextures.MEDense_Green.getIcon(); - case LightBlue: - return CableBusTextures.MEDense_LightBlue.getIcon(); - case LightGray: - return CableBusTextures.MEDense_LightGrey.getIcon(); - case Lime: - return CableBusTextures.MEDense_Lime.getIcon(); - case Magenta: - return CableBusTextures.MEDense_Magenta.getIcon(); - case Orange: - return CableBusTextures.MEDense_Orange.getIcon(); - case Pink: - return CableBusTextures.MEDense_Pink.getIcon(); - case Purple: - return CableBusTextures.MEDense_Purple.getIcon(); - case Red: - return CableBusTextures.MEDense_Red.getIcon(); - case White: - return CableBusTextures.MEDense_White.getIcon(); - case Yellow: - return CableBusTextures.MEDense_Yellow.getIcon(); - default: - } + private boolean isDense(final ForgeDirection of) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + this.getTile().xCoord + of.offsetX, + this.getTile().yCoord + of.offsetY, + this.getTile().zCoord + of.offsetZ + ); + if (te instanceof IGridHost) { + final AECableType t + = ((IGridHost) te).getCableConnectionType(of.getOpposite()); + return t == AECableType.DENSE; + } + return false; + } - return this.getItemStack().getIconIndex(); - } + @MENetworkEventSubscribe + public void channelUpdated(final MENetworkChannelsChanged c) { + this.getHost().markForUpdate(); + } - private boolean isDense( final ForgeDirection of ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + of.offsetX, this.getTile().yCoord + of.offsetY, this.getTile().zCoord + of.offsetZ ); - if( te instanceof IGridHost ) - { - final AECableType t = ( (IGridHost) te ).getCableConnectionType( of.getOpposite() ); - return t == AECableType.DENSE; - } - return false; - } - - @MENetworkEventSubscribe - public void channelUpdated( final MENetworkChannelsChanged c ) - { - this.getHost().markForUpdate(); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } } diff --git a/src/main/java/appeng/parts/networking/PartQuartzFiber.java b/src/main/java/appeng/parts/networking/PartQuartzFiber.java index 574f36c1..81ffb8e3 100644 --- a/src/main/java/appeng/parts/networking/PartQuartzFiber.java +++ b/src/main/java/appeng/parts/networking/PartQuartzFiber.java @@ -18,6 +18,8 @@ package appeng.parts.networking; +import java.util.EnumSet; +import java.util.Set; import appeng.api.config.Actionable; import appeng.api.networking.GridFlags; @@ -42,199 +44,170 @@ import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; -import java.util.EnumSet; -import java.util.Set; +public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider { + private final AENetworkProxy outerProxy = new AENetworkProxy( + this, "outer", this.getProxy().getMachineRepresentation(), true + ); + public PartQuartzFiber(final ItemStack is) { + super(is); + this.getProxy().setIdlePowerUsage(0); + this.getProxy().setFlags(GridFlags.CANNOT_CARRY); + this.outerProxy.setIdlePowerUsage(0); + this.outerProxy.setFlags(GridFlags.CANNOT_CARRY); + } -public class PartQuartzFiber extends AEBasePart implements IEnergyGridProvider -{ + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.GLASS; + } - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", this.getProxy().getMachineRepresentation(), true ); + @Override + public void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(6, 6, 10, 10, 10, 16); + } - public PartQuartzFiber( final ItemStack is ) - { - super( is ); - this.getProxy().setIdlePowerUsage( 0 ); - this.getProxy().setFlags( GridFlags.CANNOT_CARRY ); - this.outerProxy.setIdlePowerUsage( 0 ); - this.outerProxy.setFlags( GridFlags.CANNOT_CARRY ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + GL11.glTranslated(-0.2, -0.3, 0.0); - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.GLASS; - } + rh.setTexture(this.getItemStack().getIconIndex()); + rh.setBounds(6.0f, 6.0f, 5.0f, 10.0f, 10.0f, 11.0f); + rh.renderInventoryBox(renderer); + rh.setTexture(null); + } - @Override - public void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 6, 6, 10, 10, 10, 16 ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + final IIcon myIcon = this.getItemStack().getIconIndex(); + rh.setTexture(myIcon); + rh.setBounds(6, 6, 10, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); + rh.setTexture(null); + } - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - GL11.glTranslated( -0.2, -0.3, 0.0 ); + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.outerProxy.readFromNBT(extra); + } - rh.setTexture( this.getItemStack().getIconIndex() ); - rh.setBounds( 6.0f, 6.0f, 5.0f, 10.0f, 10.0f, 11.0f ); - rh.renderInventoryBox( renderer ); - rh.setTexture( null ); - } + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.outerProxy.writeToNBT(extra); + } - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - final IIcon myIcon = this.getItemStack().getIconIndex(); - rh.setTexture( myIcon ); - rh.setBounds( 6, 6, 10, 10, 10, 16 ); - rh.renderBlock( x, y, z, renderer ); - rh.setTexture( null ); - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.outerProxy.invalidate(); + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.outerProxy.readFromNBT( extra ); - } + @Override + public void addToWorld() { + super.addToWorld(); + this.outerProxy.onReady(); + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.outerProxy.writeToNBT( extra ); - } + @Override + public void setPartHostInfo( + final ForgeDirection side, final IPartHost host, final TileEntity tile + ) { + super.setPartHostInfo(side, host, tile); + this.outerProxy.setValidSides(EnumSet.of(side)); + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.outerProxy.invalidate(); - } + @Override + public IGridNode getExternalFacingNode() { + return this.outerProxy.getNode(); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.outerProxy.onReady(); - } + @Override + public int cableConnectionRenderTo() { + return 16; + } - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side ) ); - } + @Override + public void onPlacement( + final EntityPlayer player, final ItemStack held, final ForgeDirection side + ) { + super.onPlacement(player, held, side); + this.outerProxy.setOwner(player); + } - @Override - public IGridNode getExternalFacingNode() - { - return this.outerProxy.getNode(); - } + @Override + public double + extractAEPower(final double amt, final Actionable mode, final Set seen) { + double acquiredPower = 0; - @Override - public int cableConnectionRenderTo() - { - return 16; - } + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + acquiredPower += eg.extractAEPower(amt - acquiredPower, mode, seen); + } catch (final GridAccessException e) { + // :P + } - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.outerProxy.setOwner( player ); - } + try { + final IEnergyGrid eg = this.outerProxy.getEnergy(); + acquiredPower += eg.extractAEPower(amt - acquiredPower, mode, seen); + } catch (final GridAccessException e) { + // :P + } - @Override - public double extractAEPower( final double amt, final Actionable mode, final Set seen ) - { - double acquiredPower = 0; + return acquiredPower; + } - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); - } - catch( final GridAccessException e ) - { - // :P - } + @Override + public double + injectAEPower(final double amt, final Actionable mode, final Set seen) { + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + if (!seen.contains(eg)) { + return eg.injectAEPower(amt, mode, seen); + } + } catch (final GridAccessException e) { + // :P + } - try - { - final IEnergyGrid eg = this.outerProxy.getEnergy(); - acquiredPower += eg.extractAEPower( amt - acquiredPower, mode, seen ); - } - catch( final GridAccessException e ) - { - // :P - } + try { + final IEnergyGrid eg = this.outerProxy.getEnergy(); + if (!seen.contains(eg)) { + return eg.injectAEPower(amt, mode, seen); + } + } catch (final GridAccessException e) { + // :P + } - return acquiredPower; - } + return amt; + } - @Override - public double injectAEPower( final double amt, final Actionable mode, final Set seen ) - { + @Override + public double getEnergyDemand(final double amt, final Set seen) { + double demand = 0; - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - if( !seen.contains( eg ) ) - { - return eg.injectAEPower( amt, mode, seen ); - } - } - catch( final GridAccessException e ) - { - // :P - } + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + demand += eg.getEnergyDemand(amt - demand, seen); + } catch (final GridAccessException e) { + // :P + } - try - { - final IEnergyGrid eg = this.outerProxy.getEnergy(); - if( !seen.contains( eg ) ) - { - return eg.injectAEPower( amt, mode, seen ); - } - } - catch( final GridAccessException e ) - { - // :P - } + try { + final IEnergyGrid eg = this.outerProxy.getEnergy(); + demand += eg.getEnergyDemand(amt - demand, seen); + } catch (final GridAccessException e) { + // :P + } - return amt; - } - - @Override - public double getEnergyDemand( final double amt, final Set seen ) - { - double demand = 0; - - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - demand += eg.getEnergyDemand( amt - demand, seen ); - } - catch( final GridAccessException e ) - { - // :P - } - - try - { - final IEnergyGrid eg = this.outerProxy.getEnergy(); - demand += eg.getEnergyDemand( amt - demand, seen ); - } - catch( final GridAccessException e ) - { - // :P - } - - return demand; - } + return demand; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java b/src/main/java/appeng/parts/p2p/PartP2PIC2Power.java index 55e8cc71..51bba258 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 appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; @@ -35,229 +36,188 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.LinkedList; - - @InterfaceList( value = { @Interface( iface = "ic2.api.energy.tile.IEnergySink", iname = IntegrationType.IC2 ), @Interface( iface = "ic2.api.energy.tile.IEnergySource", iname = IntegrationType.IC2 ) } ) public class PartP2PIC2Power extends PartP2PTunnel implements ic2.api.energy.tile.IEnergySink, ic2.api.energy.tile.IEnergySource { + // two packet buffering... + private double OutputEnergyA; + private double OutputEnergyB; + // two packet buffering... + private double OutputVoltageA; + private double OutputVoltageB; - // two packet buffering... - private double OutputEnergyA; - private double OutputEnergyB; - // two packet buffering... - private double OutputVoltageA; - private double OutputVoltageB; + public PartP2PIC2Power(final ItemStack is) { + super(is); + } - public PartP2PIC2Power( final ItemStack is ) - { - super( is ); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.diamond_block.getBlockTextureFromSide(0); + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.diamond_block.getBlockTextureFromSide( 0 ); - } + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + this.OutputEnergyA = tag.getDouble("OutputPacket"); + this.OutputEnergyB = tag.getDouble("OutputPacket2"); + this.OutputVoltageA = tag.getDouble("OutputVoltageA"); + this.OutputVoltageB = tag.getDouble("OutputVoltageB"); + } - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - this.OutputEnergyA = tag.getDouble( "OutputPacket" ); - this.OutputEnergyB = tag.getDouble( "OutputPacket2" ); - this.OutputVoltageA = tag.getDouble( "OutputVoltageA" ); - this.OutputVoltageB = tag.getDouble( "OutputVoltageB" ); - } + @Override + public void writeToNBT(final NBTTagCompound tag) { + 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 void writeToNBT( final NBTTagCompound tag ) - { - 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 void onTunnelConfigChange() { + this.getHost().partChanged(); + } - @Override - public void onTunnelConfigChange() - { - this.getHost().partChanged(); - } + @Override + public void onTunnelNetworkChange() { + this.getHost().notifyNeighbors(); + } - @Override - public void onTunnelNetworkChange() - { - this.getHost().notifyNeighbors(); - } + @Override + public boolean + acceptsEnergyFrom(final TileEntity emitter, final ForgeDirection direction) { + if (!this.isOutput()) { + return direction == this.getSide(); + } + return false; + } - @Override - public boolean acceptsEnergyFrom( final TileEntity emitter, final ForgeDirection direction ) - { - if( !this.isOutput() ) - { - return direction == this.getSide(); - } - return false; - } + @Override + public boolean + emitsEnergyTo(final TileEntity receiver, final ForgeDirection direction) { + if (this.isOutput()) { + return direction == this.getSide(); + } + return false; + } - @Override - public boolean emitsEnergyTo( final TileEntity receiver, final ForgeDirection direction ) - { - if( this.isOutput() ) - { - return direction == this.getSide(); - } - return false; - } + @Override + public double getDemandedEnergy() { + if (this.isOutput()) { + return 0; + } - @Override - public double getDemandedEnergy() - { - if( this.isOutput() ) - { - return 0; - } + try { + for (final PartP2PIC2Power t : this.getOutputs()) { + if (t.OutputEnergyA <= 0.0001 || t.OutputEnergyB <= 0.0001) { + return 2048; + } + } + } catch (final GridAccessException e) { + return 0; + } - try - { - for( final PartP2PIC2Power t : this.getOutputs() ) - { - if( t.OutputEnergyA <= 0.0001 || t.OutputEnergyB <= 0.0001 ) - { - return 2048; - } - } - } - catch( final GridAccessException e ) - { - return 0; - } + return 0; + } - return 0; - } + @Override + public int getSinkTier() { + return 4; + } - @Override - public int getSinkTier() - { - return 4; - } + @Override + public double injectEnergy( + final ForgeDirection directionFrom, final double amount, final double voltage + ) { + final TunnelCollection outs; + try { + outs = this.getOutputs(); + } catch (final GridAccessException e) { + return amount; + } - @Override - public double injectEnergy( final ForgeDirection directionFrom, final double amount, final double voltage ) - { - final TunnelCollection outs; - try - { - outs = this.getOutputs(); - } - catch( final GridAccessException e ) - { - return amount; - } + if (outs.isEmpty()) { + return amount; + } - if( outs.isEmpty() ) - { - return amount; - } + final LinkedList options = new LinkedList(); + for (final PartP2PIC2Power o : outs) { + if (o.OutputEnergyA <= 0.01) { + options.add(o); + } + } - final LinkedList options = new LinkedList(); - for( final PartP2PIC2Power o : outs ) - { - if( o.OutputEnergyA <= 0.01 ) - { - options.add( o ); - } - } + if (options.isEmpty()) { + for (final PartP2PIC2Power o : outs) { + if (o.OutputEnergyB <= 0.01) { + options.add(o); + } + } + } - if( options.isEmpty() ) - { - for( final PartP2PIC2Power o : outs ) - { - if( o.OutputEnergyB <= 0.01 ) - { - options.add( o ); - } - } - } + if (options.isEmpty()) { + for (final PartP2PIC2Power o : outs) { + options.add(o); + } + } - if( options.isEmpty() ) - { - for( final PartP2PIC2Power o : outs ) - { - options.add( o ); - } - } + if (options.isEmpty()) { + return amount; + } - if( options.isEmpty() ) - { - return amount; - } + final PartP2PIC2Power x = Platform.pickRandom(options); - final PartP2PIC2Power x = Platform.pickRandom( options ); + if (x != null && x.OutputEnergyA <= 0.001) { + this.queueTunnelDrain(PowerUnits.EU, amount); + x.OutputEnergyA = amount; + x.OutputVoltageA = voltage; + return 0; + } - if( x != null && x.OutputEnergyA <= 0.001 ) - { - this.queueTunnelDrain( PowerUnits.EU, amount ); - x.OutputEnergyA = amount; - x.OutputVoltageA = voltage; - return 0; - } + if (x != null && x.OutputEnergyB <= 0.001) { + this.queueTunnelDrain(PowerUnits.EU, amount); + x.OutputEnergyB = amount; + x.OutputVoltageB = voltage; + return 0; + } - if( x != null && x.OutputEnergyB <= 0.001 ) - { - this.queueTunnelDrain( PowerUnits.EU, amount ); - x.OutputEnergyB = amount; - x.OutputVoltageB = voltage; - return 0; - } + return amount; + } - return amount; - } + public float getPowerDrainPerTick() { + return 0.5f; + } - public float getPowerDrainPerTick() - { - return 0.5f; - } + @Override + public double getOfferedEnergy() { + if (this.isOutput()) { + return this.OutputEnergyA; + } + return 0; + } - @Override - public double getOfferedEnergy() - { - if( this.isOutput() ) - { - return this.OutputEnergyA; - } - return 0; - } + @Override + public void drawEnergy(final double amount) { + this.OutputEnergyA -= amount; + if (this.OutputEnergyA < 0.001) { + this.OutputEnergyA = this.OutputEnergyB; + this.OutputEnergyB = 0; - @Override - public void drawEnergy( final double amount ) - { - this.OutputEnergyA -= amount; - if( this.OutputEnergyA < 0.001 ) - { - this.OutputEnergyA = this.OutputEnergyB; - this.OutputEnergyB = 0; + this.OutputVoltageA = this.OutputVoltageB; + this.OutputVoltageB = 0; + } + } - this.OutputVoltageA = this.OutputVoltageB; - this.OutputVoltageB = 0; - } - } + @Override + public int getSourceTier() { + if (this.isOutput()) { + return this.calculateTierFromVoltage(this.OutputVoltageA); + } + return 4; + } - @Override - public int getSourceTier() - { - if( this.isOutput() ) - { - return this.calculateTierFromVoltage( this.OutputVoltageA ); - } - return 4; - } - - private int calculateTierFromVoltage( final double voltage ) - { - return ic2.api.energy.EnergyNet.instance.getTierFromPower( voltage ); - } + private int calculateTierFromVoltage(final 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 79499ad0..faada493 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PItems.java +++ b/src/main/java/appeng/parts/p2p/PartP2PItems.java @@ -18,6 +18,8 @@ package appeng.parts.p2p; +import java.util.LinkedList; +import java.util.List; import appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkBootingStatusChange; @@ -54,336 +56,284 @@ import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.LinkedList; -import java.util.List; +@Interface( + iface = "buildcraft.api.transport.IPipeConnection", + iname = IntegrationType.BuildCraftTransport +) +public class PartP2PItems extends PartP2PTunnel + implements IPipeConnection, ISidedInventory, IGridTickable { + private final LinkedList which = new LinkedList(); + private int oldSize = 0; + private boolean requested; + private IInventory cachedInv; + public PartP2PItems(final ItemStack is) { + super(is); + } -@Interface( iface = "buildcraft.api.transport.IPipeConnection", iname = IntegrationType.BuildCraftTransport ) -public class PartP2PItems extends PartP2PTunnel implements IPipeConnection, ISidedInventory, IGridTickable -{ + @Override + public void onNeighborChanged() { + this.cachedInv = null; + final PartP2PItems input = this.getInput(); + if (input != null && this.isOutput()) { + input.onTunnelNetworkChange(); + } + } - private final LinkedList which = new LinkedList(); - private int oldSize = 0; - private boolean requested; - private IInventory cachedInv; + private IInventory getDestination() { + this.requested = true; - public PartP2PItems( final ItemStack is ) - { - super( is ); - } + if (this.cachedInv != null) { + return this.cachedInv; + } - @Override - public void onNeighborChanged() - { - this.cachedInv = null; - final PartP2PItems input = this.getInput(); - if( input != null && this.isOutput() ) - { - input.onTunnelNetworkChange(); - } - } + final List outs = new LinkedList(); + final TunnelCollection itemTunnels; - private IInventory getDestination() - { - this.requested = true; + try { + itemTunnels = this.getOutputs(); + } catch (final GridAccessException e) { + return new AppEngNullInventory(); + } - if( this.cachedInv != null ) - { - return this.cachedInv; - } + for (final PartP2PItems t : itemTunnels) { + final IInventory inv = t.getOutputInv(); + if (inv != null) { + if (Platform.getRandomInt() % 2 == 0) { + outs.add(inv); + } else { + outs.add(0, inv); + } + } + } - final List outs = new LinkedList(); - final TunnelCollection itemTunnels; + return this.cachedInv = new WrapperChainedInventory(outs); + } - try - { - itemTunnels = this.getOutputs(); - } - catch( final GridAccessException e ) - { - return new AppEngNullInventory(); - } + private IInventory getOutputInv() { + IInventory output = null; - for( final PartP2PItems t : itemTunnels ) - { - final IInventory inv = t.getOutputInv(); - if( inv != null ) - { - if( Platform.getRandomInt() % 2 == 0 ) - { - outs.add( inv ); - } - else - { - outs.add( 0, inv ); - } - } - } + if (this.getProxy().isActive()) { + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + this.getTile().xCoord + this.getSide().offsetX, + this.getTile().yCoord + this.getSide().offsetY, + this.getTile().zCoord + this.getSide().offsetZ + ); - return this.cachedInv = new WrapperChainedInventory( outs ); - } + if (this.which.contains(this)) { + return null; + } - private IInventory getOutputInv() - { - IInventory output = null; + this.which.add(this); - if( this.getProxy().isActive() ) - { - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + this.getSide().offsetX, this.getTile().yCoord + this.getSide().offsetY, this.getTile().zCoord + this.getSide().offsetZ ); + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport + )) { + final IBuildCraftTransport buildcraft + = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( + IntegrationType.BuildCraftTransport + ); + if (buildcraft.isPipe(te, this.getSide().getOpposite())) { + try { + output = new WrapperBCPipe(te, this.getSide().getOpposite()); + } catch (final Throwable ignore) {} + } + } - if( this.which.contains( this ) ) - { - return null; - } + /* + * if ( AppEng.INSTANCE.isIntegrationEnabled( "TE" ) ) { ITE thermal = (ITE) + * AppEng.INSTANCE.getIntegration( "TE" ); if ( thermal != null ) { if ( + * thermal.isPipe( te, side.getOpposite() ) ) { try { output = new + * WrapperTEPipe( te, side.getOpposite() ); } catch (Throwable ignore) { } } } + * } + */ - this.which.add( this ); + if (output == null) { + if (te instanceof TileEntityChest) { + output = Platform.GetChestInv(te); + } else if (te instanceof ISidedInventory) { + output = new WrapperMCISidedInventory( + (ISidedInventory) te, this.getSide().getOpposite() + ); + } else if (te instanceof IInventory) { + output = (IInventory) te; + } + } - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - final IBuildCraftTransport buildcraft = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( buildcraft.isPipe( te, this.getSide().getOpposite() ) ) - { - try - { - output = new WrapperBCPipe( te, this.getSide().getOpposite() ); - } - catch( final Throwable ignore ) - { - } - } - } + this.which.pop(); + } - /* - * if ( AppEng.INSTANCE.isIntegrationEnabled( "TE" ) ) { ITE thermal = (ITE) AppEng.INSTANCE.getIntegration( - * "TE" ); if ( thermal != null ) { if ( thermal.isPipe( te, side.getOpposite() ) ) { try { output = new - * WrapperTEPipe( te, side.getOpposite() ); } catch (Throwable ignore) { } } } } - */ + return output; + } - if( output == null ) - { - if( te instanceof TileEntityChest ) - { - output = Platform.GetChestInv( te ); - } - else if( te instanceof ISidedInventory ) - { - output = new WrapperMCISidedInventory( (ISidedInventory) te, this.getSide().getOpposite() ); - } - else if( te instanceof IInventory ) - { - output = (IInventory) te; - } - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.ItemTunnel.getMin(), TickRates.ItemTunnel.getMax(), false, false + ); + } - this.which.pop(); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + final boolean wasReq = this.requested; - return output; - } + if (this.requested && this.cachedInv != null) { + ((WrapperChainedInventory) this.cachedInv).cycleOrder(); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.ItemTunnel.getMin(), TickRates.ItemTunnel.getMax(), false, false ); - } + this.requested = false; + return wasReq ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - final boolean wasReq = this.requested; + @MENetworkEventSubscribe + public void changeStateA(final MENetworkBootingStatusChange bs) { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } + } - if( this.requested && this.cachedInv != null ) - { - ( (WrapperChainedInventory) this.cachedInv ).cycleOrder(); - } + @MENetworkEventSubscribe + public void changeStateB(final MENetworkChannelsChanged bs) { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } + } - this.requested = false; - return wasReq ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } + @MENetworkEventSubscribe + public void changeStateC(final MENetworkPowerStatusChange bs) { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } + } - @MENetworkEventSubscribe - public void changeStateA( final MENetworkBootingStatusChange bs ) - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.hopper.getBlockTextureFromSide(0); + } - @MENetworkEventSubscribe - public void changeStateB( final MENetworkChannelsChanged bs ) - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - } + @Override + public void onTunnelNetworkChange() { + if (!this.isOutput()) { + this.cachedInv = null; + final int olderSize = this.oldSize; + this.oldSize = this.getDestination().getSizeInventory(); + if (olderSize != this.oldSize) { + this.getHost().notifyNeighbors(); + } + } else { + final PartP2PItems input = this.getInput(); + if (input != null) { + input.getHost().notifyNeighbors(); + } + } + } - @MENetworkEventSubscribe - public void changeStateC( final MENetworkPowerStatusChange bs ) - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - } + @Override + public int[] getAccessibleSlotsFromSide(final int var1) { + final int[] slots = new int[this.getSizeInventory()]; + for (int x = 0; x < this.getSizeInventory(); x++) { + slots[x] = x; + } + return slots; + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.hopper.getBlockTextureFromSide( 0 ); - } + @Override + public int getSizeInventory() { + return this.getDestination().getSizeInventory(); + } - @Override - public void onTunnelNetworkChange() - { - if( !this.isOutput() ) - { - this.cachedInv = null; - final int olderSize = this.oldSize; - this.oldSize = this.getDestination().getSizeInventory(); - if( olderSize != this.oldSize ) - { - this.getHost().notifyNeighbors(); - } - } - else - { - final PartP2PItems input = this.getInput(); - if( input != null ) - { - input.getHost().notifyNeighbors(); - } - } - } + @Override + public ItemStack getStackInSlot(final int i) { + return this.getDestination().getStackInSlot(i); + } - @Override - public int[] getAccessibleSlotsFromSide( final int var1 ) - { - final int[] slots = new int[this.getSizeInventory()]; - for( int x = 0; x < this.getSizeInventory(); x++ ) - { - slots[x] = x; - } - return slots; - } + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.getDestination().decrStackSize(i, j); + } - @Override - public int getSizeInventory() - { - return this.getDestination().getSizeInventory(); - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.getDestination().getStackInSlot( i ); - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.getDestination().setInventorySlotContents(i, itemstack); + } - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.getDestination().decrStackSize( i, j ); - } + @Override + public String getInventoryName() { + return null; + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.getDestination().setInventorySlotContents( i, itemstack ); - } + @Override + public int getInventoryStackLimit() { + return this.getDestination().getInventoryStackLimit(); + } - @Override - public String getInventoryName() - { - return null; - } + @Override + public void markDirty() { + // eh? + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } - @Override - public int getInventoryStackLimit() - { - return this.getDestination().getInventoryStackLimit(); - } + @Override + public void openInventory() {} - @Override - public void markDirty() - { - // eh? - } + @Override + public void closeInventory() {} - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } + @Override + public boolean + isItemValidForSlot(final int i, final net.minecraft.item.ItemStack itemstack) { + return this.getDestination().isItemValidForSlot(i, itemstack); + } - @Override - public void openInventory() - { - } + @Override + public boolean canInsertItem(final int i, final ItemStack itemstack, final int j) { + return this.getDestination().isItemValidForSlot(i, itemstack); + } - @Override - public void closeInventory() - { - } + @Override + public boolean canExtractItem(final int i, final ItemStack itemstack, final int j) { + return false; + } - @Override - public boolean isItemValidForSlot( final int i, final net.minecraft.item.ItemStack itemstack ) - { - return this.getDestination().isItemValidForSlot( i, itemstack ); - } + public float getPowerDrainPerTick() { + return 2.0f; + } - @Override - public boolean canInsertItem( final int i, final ItemStack itemstack, final int j ) - { - return this.getDestination().isItemValidForSlot( i, itemstack ); - } - - @Override - public boolean canExtractItem( final int i, final ItemStack itemstack, final int j ) - { - return false; - } - - public float getPowerDrainPerTick() - { - return 2.0f; - } - - @Override - @Method( iname = IntegrationType.BuildCraftTransport ) - public ConnectOverride overridePipeConnection( final PipeType type, final ForgeDirection with ) - { - return this.getSide() == with && type == PipeType.ITEM ? ConnectOverride.CONNECT : ConnectOverride.DEFAULT; - } + @Override + @Method(iname = IntegrationType.BuildCraftTransport) + public ConnectOverride + overridePipeConnection(final PipeType type, final ForgeDirection with) { + return this.getSide() == with && type == PipeType.ITEM ? ConnectOverride.CONNECT + : ConnectOverride.DEFAULT; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PLight.java b/src/main/java/appeng/parts/p2p/PartP2PLight.java index 88b593ae..36b20a7f 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 appeng.api.networking.IGridNode; import appeng.api.networking.events.MENetworkChannelsChanged; @@ -37,189 +38,162 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; -import java.io.IOException; +public class PartP2PLight extends PartP2PTunnel implements IGridTickable { + private int lastValue = 0; + private float opacity = -1; + public PartP2PLight(final ItemStack is) { + super(is); + } -public class PartP2PLight extends PartP2PTunnel implements IGridTickable -{ + @Override + public void chanRender(final MENetworkChannelsChanged c) { + this.onTunnelNetworkChange(); + super.chanRender(c); + } - private int lastValue = 0; - private float opacity = -1; + @Override + public void powerRender(final MENetworkPowerStatusChange c) { + this.onTunnelNetworkChange(); + super.powerRender(c); + } - public PartP2PLight( final ItemStack is ) - { - super( is ); - } + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeInt(this.isOutput() ? this.lastValue : 0); + } - @Override - public void chanRender( final MENetworkChannelsChanged c ) - { - this.onTunnelNetworkChange(); - super.chanRender( c ); - } + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + super.readFromStream(data); + this.lastValue = data.readInt(); + this.setOutput(this.lastValue > 0); + return false; + } - @Override - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.onTunnelNetworkChange(); - super.powerRender( c ); - } + private boolean doWork() { + if (this.isOutput()) { + return false; + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - data.writeInt( this.isOutput() ? this.lastValue : 0 ); - } + final TileEntity te = this.getTile(); + final World w = te.getWorldObj(); - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - super.readFromStream( data ); - this.lastValue = data.readInt(); - this.setOutput( this.lastValue > 0 ); - return false; - } + final int newLevel = w.getBlockLightValue( + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ + ); - private boolean doWork() - { - if( this.isOutput() ) - { - return false; - } + if (this.lastValue != newLevel && this.getProxy().isActive()) { + this.lastValue = newLevel; + try { + for (final PartP2PLight out : this.getOutputs()) { + out.setLightLevel(this.lastValue); + } + } catch (final GridAccessException e) { + // :P + } + return true; + } + return false; + } - final TileEntity te = this.getTile(); - final World w = te.getWorldObj(); + @Override + public void onNeighborChanged() { + this.opacity = -1; - final int newLevel = w.getBlockLightValue( te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); + this.doWork(); - if( this.lastValue != newLevel && this.getProxy().isActive() ) - { - this.lastValue = newLevel; - try - { - for( final PartP2PLight out : this.getOutputs() ) - { - out.setLightLevel( this.lastValue ); - } - } - catch( final GridAccessException e ) - { - // :P - } - return true; - } - return false; - } + if (this.isOutput()) { + this.getHost().markForUpdate(); + } + } - @Override - public void onNeighborChanged() - { - this.opacity = -1; + @Override + public int getLightLevel() { + if (this.isOutput() && this.isPowered()) { + return this.blockLight(this.lastValue); + } - this.doWork(); + return 0; + } - if( this.isOutput() ) - { - this.getHost().markForUpdate(); - } - } + private void setLightLevel(final int out) { + this.lastValue = out; + this.getHost().markForUpdate(); + } - @Override - public int getLightLevel() - { - if( this.isOutput() && this.isPowered() ) - { - return this.blockLight( this.lastValue ); - } + private int blockLight(final int emit) { + if (this.opacity < 0) { + final TileEntity te = this.getTile(); + this.opacity = 255 + - te.getWorldObj().getBlockLightOpacity( + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ + ); + } - return 0; - } + return (int) (emit * (this.opacity / 255.0f)); + } - private void setLightLevel( final int out ) - { - this.lastValue = out; - this.getHost().markForUpdate(); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.quartz_block.getBlockTextureFromSide(0); + } - private int blockLight( final int emit ) - { - if( this.opacity < 0 ) - { - final TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); - } + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + if (tag.hasKey("opacity")) { + this.opacity = tag.getFloat("opacity"); + } + this.lastValue = tag.getInteger("lastValue"); + } - return (int) ( emit * ( this.opacity / 255.0f ) ); - } + @Override + public void writeToNBT(final NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setFloat("opacity", this.opacity); + tag.setInteger("lastValue", this.lastValue); + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.quartz_block.getBlockTextureFromSide( 0 ); - } + @Override + public void onTunnelConfigChange() { + this.onTunnelNetworkChange(); + } - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - if( tag.hasKey( "opacity" ) ) - { - this.opacity = tag.getFloat( "opacity" ); - } - this.lastValue = tag.getInteger( "lastValue" ); - } + @Override + public void onTunnelNetworkChange() { + if (this.isOutput()) { + final PartP2PLight src = this.getInput(); + if (src != null && src.getProxy().isActive()) { + this.setLightLevel(src.lastValue); + } else { + this.getHost().markForUpdate(); + } + } else { + this.doWork(); + } + } - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setFloat( "opacity", this.opacity ); - tag.setInteger( "lastValue", this.lastValue ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.LightTunnel.getMin(), TickRates.LightTunnel.getMax(), false, false + ); + } - @Override - public void onTunnelConfigChange() - { - this.onTunnelNetworkChange(); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + } - @Override - public void onTunnelNetworkChange() - { - if( this.isOutput() ) - { - final PartP2PLight src = this.getInput(); - if( src != null && src.getProxy().isActive() ) - { - this.setLightLevel( src.lastValue ); - } - else - { - this.getHost().markForUpdate(); - } - } - else - { - this.doWork(); - } - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.LightTunnel.getMin(), TickRates.LightTunnel.getMax(), false, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.doWork() ? TickRateModulation.FASTER : TickRateModulation.SLOWER; - } - - public float getPowerDrainPerTick() - { - return 0.5f; - } + public float getPowerDrainPerTick() { + return 0.5f; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PLiquids.java b/src/main/java/appeng/parts/p2p/PartP2PLiquids.java index 370986ab..896b6e9e 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PLiquids.java +++ b/src/main/java/appeng/parts/p2p/PartP2PLiquids.java @@ -18,6 +18,10 @@ package appeng.parts.p2p; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Stack; import appeng.me.GridAccessException; import cpw.mods.fml.relauncher.Side; @@ -32,275 +36,223 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Stack; +public class PartP2PLiquids + extends PartP2PTunnel implements IFluidHandler { + private static final ThreadLocal> DEPTH + = new ThreadLocal>(); + private static final FluidTankInfo[] ACTIVE_TANK = { new FluidTankInfo(null, 10000) }; + private static final FluidTankInfo[] INACTIVE_TANK = { new FluidTankInfo(null, 0) }; + private IFluidHandler cachedTank; + private int tmpUsed; + public PartP2PLiquids(final ItemStack is) { + super(is); + } -public class PartP2PLiquids extends PartP2PTunnel implements IFluidHandler -{ + public float getPowerDrainPerTick() { + return 2.0f; + } - private static final ThreadLocal> DEPTH = new ThreadLocal>(); - private static final FluidTankInfo[] ACTIVE_TANK = { new FluidTankInfo( null, 10000 ) }; - private static final FluidTankInfo[] INACTIVE_TANK = { new FluidTankInfo( null, 0 ) }; - private IFluidHandler cachedTank; - private int tmpUsed; + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.lapis_block.getBlockTextureFromSide(0); + } - public PartP2PLiquids( final ItemStack is ) - { - super( is ); - } + @Override + public void onTunnelNetworkChange() { + this.cachedTank = null; + } - public float getPowerDrainPerTick() - { - return 2.0f; - } + @Override + public void onNeighborChanged() { + this.cachedTank = null; + if (this.isOutput()) { + final PartP2PLiquids in = this.getInput(); + if (in != null) { + in.onTunnelNetworkChange(); + } + } + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.lapis_block.getBlockTextureFromSide( 0 ); - } + @Override + public int + fill(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + final Stack stack = this.getDepth(); - @Override - public void onTunnelNetworkChange() - { - this.cachedTank = null; - } + for (final PartP2PLiquids t : stack) { + if (t == this) { + return 0; + } + } - @Override - public void onNeighborChanged() - { - this.cachedTank = null; - if( this.isOutput() ) - { - final PartP2PLiquids in = this.getInput(); - if( in != null ) - { - in.onTunnelNetworkChange(); - } - } - } + stack.push(this); - @Override - public int fill( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - final Stack stack = this.getDepth(); + final List list = this.getOutputs(resource.getFluid()); + int requestTotal = 0; - for( final PartP2PLiquids t : stack ) - { - if( t == this ) - { - return 0; - } - } + Iterator i = list.iterator(); + while (i.hasNext()) { + final PartP2PLiquids l = i.next(); + final IFluidHandler tank = l.getTarget(); + if (tank != null) { + l.tmpUsed = tank.fill(l.getSide().getOpposite(), resource.copy(), false); + } else { + l.tmpUsed = 0; + } - stack.push( this ); + if (l.tmpUsed <= 0) { + i.remove(); + } else { + requestTotal += l.tmpUsed; + } + } - final List list = this.getOutputs( resource.getFluid() ); - int requestTotal = 0; + if (requestTotal <= 0) { + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - Iterator i = list.iterator(); - while( i.hasNext() ) - { - final PartP2PLiquids l = i.next(); - final IFluidHandler tank = l.getTarget(); - if( tank != null ) - { - l.tmpUsed = tank.fill( l.getSide().getOpposite(), resource.copy(), false ); - } - else - { - l.tmpUsed = 0; - } + return 0; + } - if( l.tmpUsed <= 0 ) - { - i.remove(); - } - else - { - requestTotal += l.tmpUsed; - } - } + if (!doFill) { + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - if( requestTotal <= 0 ) - { - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + return Math.min(resource.amount, requestTotal); + } - return 0; - } + int available = resource.amount; - if( !doFill ) - { - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + i = list.iterator(); + int used = 0; - return Math.min( resource.amount, requestTotal ); - } + while (i.hasNext() && available > 0) { + final PartP2PLiquids l = i.next(); - int available = resource.amount; + final FluidStack insert = resource.copy(); + insert.amount = (int + ) Math.ceil(insert.amount * ((double) l.tmpUsed / (double) requestTotal)); + if (insert.amount > available) { + insert.amount = available; + } - i = list.iterator(); - int used = 0; + final IFluidHandler tank = l.getTarget(); + if (tank != null) { + l.tmpUsed = tank.fill(l.getSide().getOpposite(), insert.copy(), true); + } else { + l.tmpUsed = 0; + } - while( i.hasNext() && available > 0 ) - { - final PartP2PLiquids l = i.next(); + available -= insert.amount; + used += l.tmpUsed; + } - final FluidStack insert = resource.copy(); - insert.amount = (int) Math.ceil( insert.amount * ( (double) l.tmpUsed / (double) requestTotal ) ); - if( insert.amount > available ) - { - insert.amount = available; - } + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - final IFluidHandler tank = l.getTarget(); - if( tank != null ) - { - l.tmpUsed = tank.fill( l.getSide().getOpposite(), insert.copy(), true ); - } - else - { - l.tmpUsed = 0; - } + return used; + } - available -= insert.amount; - used += l.tmpUsed; - } + private Stack getDepth() { + Stack s = DEPTH.get(); - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + if (s == null) { + DEPTH.set(s = new Stack()); + } - return used; - } + return s; + } - private Stack getDepth() - { - Stack s = DEPTH.get(); + private List getOutputs(final Fluid input) { + final List outs = new LinkedList(); - if( s == null ) - { - DEPTH.set( s = new Stack() ); - } + try { + for (final PartP2PLiquids l : this.getOutputs()) { + final IFluidHandler handler = l.getTarget(); + if (handler != null) { + if (handler.canFill(l.getSide().getOpposite(), input)) { + outs.add(l); + } + } + } + } catch (final GridAccessException e) { + // :P + } - return s; - } + return outs; + } - private List getOutputs( final Fluid input ) - { - final List outs = new LinkedList(); + private IFluidHandler getTarget() { + if (!this.getProxy().isActive()) { + return null; + } - try - { - for( final PartP2PLiquids l : this.getOutputs() ) - { - final IFluidHandler handler = l.getTarget(); - if( handler != null ) - { - if( handler.canFill( l.getSide().getOpposite(), input ) ) - { - outs.add( l ); - } - } - } - } - catch( final GridAccessException e ) - { - // :P - } + if (this.cachedTank != null) { + return this.cachedTank; + } - return outs; - } + final TileEntity te = this.getTile().getWorldObj().getTileEntity( + this.getTile().xCoord + this.getSide().offsetX, + this.getTile().yCoord + this.getSide().offsetY, + this.getTile().zCoord + this.getSide().offsetZ + ); + if (te instanceof IFluidHandler) { + return this.cachedTank = (IFluidHandler) te; + } - private IFluidHandler getTarget() - { - if( !this.getProxy().isActive() ) - { - return null; - } + return null; + } - if( this.cachedTank != null ) - { - return this.cachedTank; - } + @Override + public FluidStack + drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + return null; + } - final TileEntity te = this.getTile().getWorldObj().getTileEntity( this.getTile().xCoord + this.getSide().offsetX, this.getTile().yCoord + this.getSide().offsetY, this.getTile().zCoord + this.getSide().offsetZ ); - if( te instanceof IFluidHandler ) - { - return this.cachedTank = (IFluidHandler) te; - } + @Override + public FluidStack + drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + return null; + } - return null; - } + @Override + public boolean canFill(final ForgeDirection from, final Fluid fluid) { + return !this.isOutput() && from == this.getSide() + && !this.getOutputs(fluid).isEmpty(); + } - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - return null; - } + @Override + public boolean canDrain(final ForgeDirection from, final Fluid fluid) { + return false; + } - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - return null; - } + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + if (from == this.getSide()) { + return this.getTank(); + } + return new FluidTankInfo[0]; + } - @Override - public boolean canFill( final ForgeDirection from, final Fluid fluid ) - { - return !this.isOutput() && from == this.getSide() && !this.getOutputs( fluid ).isEmpty(); - } - - @Override - public boolean canDrain( final ForgeDirection from, final Fluid fluid ) - { - return false; - } - - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - if( from == this.getSide() ) - { - return this.getTank(); - } - return new FluidTankInfo[0]; - } - - private FluidTankInfo[] getTank() - { - if( this.isOutput() ) - { - final PartP2PLiquids tun = this.getInput(); - if( tun != null ) - { - return ACTIVE_TANK; - } - } - else - { - try - { - if( !this.getOutputs().isEmpty() ) - { - return ACTIVE_TANK; - } - } - catch( final GridAccessException e ) - { - // :( - } - } - return INACTIVE_TANK; - } + private FluidTankInfo[] getTank() { + if (this.isOutput()) { + final PartP2PLiquids tun = this.getInput(); + if (tun != null) { + return ACTIVE_TANK; + } + } else { + try { + if (!this.getOutputs().isEmpty()) { + return ACTIVE_TANK; + } + } catch (final GridAccessException e) { + // :( + } + } + return INACTIVE_TANK; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java b/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java index 48c20892..51fc4f0f 100644 --- a/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java +++ b/src/main/java/appeng/parts/p2p/PartP2POpenComputers.java @@ -18,6 +18,7 @@ package appeng.parts.p2p; +import javax.annotation.Nullable; import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkChannelsChanged; @@ -38,147 +39,114 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; - - @InterfaceList( value = { @Interface( iface = "li.cil.oc.api.network.Environment", iname = IntegrationType.OpenComputers ), @Interface( iface = "li.cil.oc.api.network.SidedEnvironment", iname = IntegrationType.OpenComputers ) } ) public final class PartP2POpenComputers extends PartP2PTunnel implements Environment, SidedEnvironment { - @Nullable - private final Node node; + @Nullable + private final Node node; - public PartP2POpenComputers( final ItemStack is ) - { - super( is ); + public PartP2POpenComputers(final ItemStack is) { + super(is); - if( !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.OpenComputers ) ) - { - throw new RuntimeException( "OpenComputers is not installed!" ); - } + if (!IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.OpenComputers)) { + throw new RuntimeException("OpenComputers is not installed!"); + } - // Avoid NPE when called in pre-init phase (part population). - if( API.network != null ) - { - this.node = Network.newNode( this, Visibility.None ).create(); - } - else - { - this.node = null; // to satisfy final - } - } + // Avoid NPE when called in pre-init phase (part population). + if (API.network != null) { + this.node = Network.newNode(this, Visibility.None).create(); + } else { + this.node = null; // to satisfy final + } + } - @MENetworkEventSubscribe - public void changeStateA( final MENetworkBootingStatusChange bs ) - { - this.updateConnections(); - } + @MENetworkEventSubscribe + public void changeStateA(final MENetworkBootingStatusChange bs) { + this.updateConnections(); + } - @MENetworkEventSubscribe - public void changeStateB( final MENetworkChannelsChanged bs ) - { - this.updateConnections(); - } + @MENetworkEventSubscribe + public void changeStateB(final MENetworkChannelsChanged bs) { + this.updateConnections(); + } - @MENetworkEventSubscribe - public void changeStateC( final MENetworkPowerStatusChange bs ) - { - this.updateConnections(); - } + @MENetworkEventSubscribe + public void changeStateC(final MENetworkPowerStatusChange bs) { + this.updateConnections(); + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Items.get( "adapter" ).block().getBlockTextureFromSide( 2 ); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Items.get("adapter").block().getBlockTextureFromSide(2); + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - if( this.node != null ) - { - this.node.remove(); - } - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + if (this.node != null) { + this.node.remove(); + } + } - @Override - public void onTunnelNetworkChange() - { - this.updateConnections(); - } + @Override + public void onTunnelNetworkChange() { + this.updateConnections(); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( this.node != null ) - { - this.node.load( data ); - } - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (this.node != null) { + this.node.load(data); + } + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - if( this.node != null ) - { - this.node.save( data ); - } - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + if (this.node != null) { + this.node.save(data); + } + } - private void updateConnections() - { - if( this.getProxy().isPowered() && this.getProxy().isActive() ) - { - // Make sure we're connected to existing OC nodes in the world. - Network.joinOrCreateNetwork( this.getTile() ); + private void updateConnections() { + if (this.getProxy().isPowered() && this.getProxy().isActive()) { + // Make sure we're connected to existing OC nodes in the world. + Network.joinOrCreateNetwork(this.getTile()); - if( this.isOutput() && this.getInput() != null && this.node != null ) - { - Network.joinOrCreateNetwork( this.getInput().getTile() ); - this.node.connect( this.getInput().node() ); - } - } - else if( this.node != null ) - { - this.node.remove(); - } - } + if (this.isOutput() && this.getInput() != null && this.node != null) { + Network.joinOrCreateNetwork(this.getInput().getTile()); + this.node.connect(this.getInput().node()); + } + } else if (this.node != null) { + this.node.remove(); + } + } - @Nullable - @Override - public Node node() - { - return this.node; - } + @Nullable + @Override + public Node node() { + return this.node; + } - @Override - public void onConnect( final Node node ) - { - } + @Override + public void onConnect(final Node node) {} - @Override - public void onDisconnect( final Node node ) - { - } + @Override + public void onDisconnect(final Node node) {} - @Override - public void onMessage( final Message message ) - { - } + @Override + public void onMessage(final Message message) {} - @Nullable - @Override - public Node sidedNode( final ForgeDirection side ) - { - return side == this.getSide() ? this.node : null; - } + @Nullable + @Override + public Node sidedNode(final ForgeDirection side) { + return side == this.getSide() ? this.node : null; + } - @Override - public boolean canConnect( final ForgeDirection side ) - { - return side == this.getSide(); - } + @Override + public boolean canConnect(final ForgeDirection side) { + return side == this.getSide(); + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PPressure.java b/src/main/java/appeng/parts/p2p/PartP2PPressure.java index 2e83eaad..5a1329e1 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PPressure.java +++ b/src/main/java/appeng/parts/p2p/PartP2PPressure.java @@ -18,6 +18,8 @@ package appeng.parts.p2p; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.networking.IGridNode; import appeng.api.networking.ticking.IGridTickable; @@ -37,144 +39,134 @@ import pneumaticCraft.api.tileentity.AirHandlerSupplier; import pneumaticCraft.api.tileentity.IAirHandler; import pneumaticCraft.api.tileentity.ISidedPneumaticMachine; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +@Interface( + iface = "pneumaticCraft.api.tileentity.ISidedPneumaticMachine", + iname = IntegrationType.PneumaticCraft +) +public final class PartP2PPressure extends PartP2PTunnel + implements ISidedPneumaticMachine, IGridTickable { + private static final String PRESSURE_NBT_TAG = "pneumaticCraft"; + private static final String PRESSURE_TYPE_ICON_NAME = "compressedIronBlock"; + /** + * The pressure should never exceed 30f, thus preventing the tunnel from exploding. + */ + private static final float MAX_PRESSURE = 30f; + private static final int VOLUME = 1000; -@Interface( iface = "pneumaticCraft.api.tileentity.ISidedPneumaticMachine", iname = IntegrationType.PneumaticCraft ) -public final class PartP2PPressure extends PartP2PTunnel implements ISidedPneumaticMachine, IGridTickable -{ - private static final String PRESSURE_NBT_TAG = "pneumaticCraft"; - private static final String PRESSURE_TYPE_ICON_NAME = "compressedIronBlock"; + @Nonnull + private final IAirHandler handler; + private boolean isConnected = false; + private boolean isValid = false; - /** - * The pressure should never exceed 30f, thus preventing the tunnel from exploding. - */ - private static final float MAX_PRESSURE = 30f; - private static final int VOLUME = 1000; + public PartP2PPressure(final ItemStack is) { + super(is); + this.handler + = AirHandlerSupplier.getAirHandler(MAX_PRESSURE, MAX_PRESSURE, VOLUME); + } - @Nonnull - private final IAirHandler handler; - private boolean isConnected = false; - private boolean isValid = false; + @Override + protected IIcon getTypeTexture() { + return BlockSupplier.getBlock(PRESSURE_TYPE_ICON_NAME).getIcon(0, 0); + } - public PartP2PPressure( final ItemStack is ) - { - super( is ); - this.handler = AirHandlerSupplier.getAirHandler( MAX_PRESSURE, MAX_PRESSURE, VOLUME ); - } + @Nullable + @Override + public IAirHandler getAirHandler(final ForgeDirection side) { + if (side == this.getSide()) { + return this.getInternalHandler(); + } - @Override - protected IIcon getTypeTexture() - { - return BlockSupplier.getBlock( PRESSURE_TYPE_ICON_NAME ).getIcon( 0, 0 ); - } + return null; + } - @Nullable - @Override - public IAirHandler getAirHandler( final ForgeDirection side ) - { - if( side == this.getSide() ) - { - return this.getInternalHandler(); - } + @Override + public void onNeighborChanged() { + super.onNeighborChanged(); - return null; - } + if (this.isValid) { + this.getInternalHandler().onNeighborChange(); + } + } - @Override - public void onNeighborChanged() - { - super.onNeighborChanged(); + @Override + public void addToWorld() { + super.addToWorld(); - if( this.isValid ) - { - this.getInternalHandler().onNeighborChange(); - } - } + this.getInternalHandler().validateI(this.getTile()); + this.isValid = true; + } - @Override - public void addToWorld() - { - super.addToWorld(); + @Override + public void removeFromWorld() { + super.removeFromWorld(); - this.getInternalHandler().validateI( this.getTile() ); - this.isValid = true; - } + this.isValid = false; + if (this.isOutput() && this.getInput() != null) { + this.getInternalHandler().removeConnection(this.getInput().getInternalHandler( + )); + this.isConnected = false; + } + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.PressureTunnel.getMin(), + TickRates.PressureTunnel.getMax(), + false, + false + ); + } - this.isValid = false; - if( this.isOutput() && this.getInput() != null ) - { - this.getInternalHandler().removeConnection( this.getInput().getInternalHandler() ); - this.isConnected = false; - } - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int TicksSinceLastCall) { + if (this.getProxy().isPowered() && this.getProxy().isActive()) { + if (!this.isConnected) { + this.updateHandler(); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.PressureTunnel.getMin(), TickRates.PressureTunnel.getMax(), false, false ); - } + this.getInternalHandler().updateEntityI(); + return TickRateModulation.URGENT; + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int TicksSinceLastCall ) - { - if( this.getProxy().isPowered() && this.getProxy().isActive() ) - { - if( !this.isConnected ) - { - this.updateHandler(); - } + return TickRateModulation.IDLE; + } - this.getInternalHandler().updateEntityI(); - return TickRateModulation.URGENT; - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + final NBTTagCompound pneumaticNBT = new NBTTagCompound(); - return TickRateModulation.IDLE; - } + this.getInternalHandler().writeToNBTI(pneumaticNBT); + data.setTag(PRESSURE_NBT_TAG, pneumaticNBT); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - final NBTTagCompound pneumaticNBT = new NBTTagCompound(); + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.getInternalHandler().readFromNBTI(data.getCompoundTag(PRESSURE_NBT_TAG)); + } - this.getInternalHandler().writeToNBTI( pneumaticNBT ); - data.setTag( PRESSURE_NBT_TAG, pneumaticNBT ); - } + @Nonnull + private IAirHandler getInternalHandler() { + return this.handler; + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.getInternalHandler().readFromNBTI( data.getCompoundTag( PRESSURE_NBT_TAG ) ); - } - - @Nonnull - private IAirHandler getInternalHandler() - { - return this.handler; - } - - private void updateHandler() - { - if( this.getProxy().isPowered() && this.getProxy().isActive() ) - { - - if( this.isOutput() && this.getInput() != null ) - { - this.getInternalHandler().createConnection( this.getInput().getInternalHandler() ); - this.isConnected = true; - } - - final TileEntity te = this.getTile(); - Platform.notifyBlocksOfNeighbors( te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord ); - } - } + private void updateHandler() { + if (this.getProxy().isPowered() && this.getProxy().isActive()) { + if (this.isOutput() && this.getInput() != null) { + this.getInternalHandler().createConnection( + this.getInput().getInternalHandler() + ); + this.isConnected = true; + } + final TileEntity te = this.getTile(); + Platform.notifyBlocksOfNeighbors( + te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord + ); + } + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PRFPower.java b/src/main/java/appeng/parts/p2p/PartP2PRFPower.java index 63ea248b..5080ee7d 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PRFPower.java +++ b/src/main/java/appeng/parts/p2p/PartP2PRFPower.java @@ -18,6 +18,7 @@ package appeng.parts.p2p; +import java.util.Stack; import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; @@ -35,238 +36,205 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Stack; +@InterfaceList( + value + = { @Interface(iface = "cofh.api.energy.IEnergyReceiver", iname = IntegrationType.RF) } +) +public final class PartP2PRFPower + extends PartP2PTunnel implements IEnergyReceiver { + private static final ThreadLocal> THREAD_STACK + = new ThreadLocal>(); + /** + * Default element based on the null element pattern + */ + private static final IEnergyReceiver NULL_HANDLER = new NullRFHandler(); + private boolean cachedTarget = false; + private IEnergyReceiver outputTarget; + public PartP2PRFPower(final ItemStack is) { + super(is); + } -@InterfaceList( value = { @Interface( iface = "cofh.api.energy.IEnergyReceiver", iname = IntegrationType.RF ) } ) -public final class PartP2PRFPower extends PartP2PTunnel implements IEnergyReceiver -{ - private static final ThreadLocal> THREAD_STACK = new ThreadLocal>(); - /** - * Default element based on the null element pattern - */ - private static final IEnergyReceiver NULL_HANDLER = new NullRFHandler(); - private boolean cachedTarget = false; - private IEnergyReceiver outputTarget; + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.iron_block.getBlockTextureFromSide(0); + } - public PartP2PRFPower( final ItemStack is ) - { - super( is ); - } + @Override + public void onTunnelNetworkChange() { + this.getHost().notifyNeighbors(); + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.iron_block.getBlockTextureFromSide( 0 ); - } + @Override + public void onNeighborChanged() { + super.onNeighborChanged(); - @Override - public void onTunnelNetworkChange() - { - this.getHost().notifyNeighbors(); - } + this.cachedTarget = false; + } - @Override - public void onNeighborChanged() - { - super.onNeighborChanged(); + @Override + public int + receiveEnergy(final ForgeDirection from, int maxReceive, final boolean simulate) { + if (this.isOutput()) { + return 0; + } - this.cachedTarget = false; - } + if (this.isActive()) { + final Stack stack = this.getDepth(); - @Override - public int receiveEnergy( final ForgeDirection from, int maxReceive, final boolean simulate ) - { - if( this.isOutput() ) - { - return 0; - } + for (final PartP2PRFPower t : stack) { + if (t == this) { + return 0; + } + } - if( this.isActive() ) - { - final Stack stack = this.getDepth(); + stack.push(this); - for( final PartP2PRFPower t : stack ) - { - if( t == this ) - { - return 0; - } - } + int total = 0; - stack.push( this ); + try { + for (final PartP2PRFPower t : this.getOutputs()) { + if (Platform.getRandomInt() % 2 > 0) { + final int receiver = t.getOutput().receiveEnergy( + t.getSide().getOpposite(), maxReceive, simulate + ); + maxReceive -= receiver; + total += receiver; - int total = 0; + if (maxReceive <= 0) { + break; + } + } + } - try - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - if( Platform.getRandomInt() % 2 > 0 ) - { - final int receiver = t.getOutput().receiveEnergy( t.getSide().getOpposite(), maxReceive, simulate ); - maxReceive -= receiver; - total += receiver; + if (maxReceive > 0) { + for (final PartP2PRFPower t : this.getOutputs()) { + final int receiver = t.getOutput().receiveEnergy( + t.getSide().getOpposite(), maxReceive, simulate + ); + maxReceive -= receiver; + total += receiver; - if( maxReceive <= 0 ) - { - break; - } - } - } + if (maxReceive <= 0) { + break; + } + } + } - if( maxReceive > 0 ) - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - final int receiver = t.getOutput().receiveEnergy( t.getSide().getOpposite(), maxReceive, simulate ); - maxReceive -= receiver; - total += receiver; + this.queueTunnelDrain(PowerUnits.RF, total); + } catch (final GridAccessException ignored) {} - if( maxReceive <= 0 ) - { - break; - } - } - } + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - this.queueTunnelDrain( PowerUnits.RF, total ); - } - catch( final GridAccessException ignored ) - { - } + return total; + } - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + return 0; + } - return total; - } + private Stack getDepth() { + Stack s = THREAD_STACK.get(); - return 0; - } + if (s == null) { + THREAD_STACK.set(s = new Stack()); + } - private Stack getDepth() - { - Stack s = THREAD_STACK.get(); + return s; + } - if( s == null ) - { - THREAD_STACK.set( s = new Stack() ); - } + private IEnergyReceiver getOutput() { + if (this.isOutput()) { + if (!this.cachedTarget) { + final TileEntity self = this.getTile(); + final TileEntity te = self.getWorldObj().getTileEntity( + self.xCoord + this.getSide().offsetX, + self.yCoord + this.getSide().offsetY, + self.zCoord + this.getSide().offsetZ + ); + this.outputTarget + = te instanceof IEnergyReceiver ? (IEnergyReceiver) te : null; + this.cachedTarget = true; + } - return s; - } + if (this.outputTarget == null + || !this.outputTarget.canConnectEnergy(this.getSide().getOpposite())) { + return NULL_HANDLER; + } - private IEnergyReceiver getOutput() - { - if( this.isOutput() ) - { - if( !this.cachedTarget ) - { - final TileEntity self = this.getTile(); - final TileEntity te = self.getWorldObj().getTileEntity( self.xCoord + this.getSide().offsetX, self.yCoord + this.getSide().offsetY, self.zCoord + this.getSide().offsetZ ); - this.outputTarget = te instanceof IEnergyReceiver ? (IEnergyReceiver) te : null; - this.cachedTarget = true; - } + return this.outputTarget; + } + return NULL_HANDLER; + } - if( this.outputTarget == null || !this.outputTarget.canConnectEnergy( this.getSide().getOpposite() ) ) - { - return NULL_HANDLER; - } + @Override + public int getEnergyStored(final ForgeDirection from) { + if (this.isOutput() || !this.isActive()) { + return 0; + } - return this.outputTarget; - } - return NULL_HANDLER; - } + final Stack stack = this.getDepth(); - @Override - public int getEnergyStored( final ForgeDirection from ) - { - if( this.isOutput() || !this.isActive() ) - { - return 0; - } + for (final PartP2PRFPower t : stack) { + if (t == this) { + return 0; + } + } - final Stack stack = this.getDepth(); + stack.push(this); - for( final PartP2PRFPower t : stack ) - { - if( t == this ) - { - return 0; - } - } + int total = 0; + try { + for (final PartP2PRFPower t : this.getOutputs()) { + total += t.getOutput().getEnergyStored(t.getSide().getOpposite()); + } + } catch (final GridAccessException e) { + return 0; + } - stack.push( this ); + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - int total = 0; - try - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - total += t.getOutput().getEnergyStored( t.getSide().getOpposite() ); - } - } - catch( final GridAccessException e ) - { - return 0; - } + return total; + } - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } + @Override + public int getMaxEnergyStored(final ForgeDirection from) { + if (this.isOutput() || !this.isActive()) { + return 0; + } - return total; - } + final Stack stack = this.getDepth(); - @Override - public int getMaxEnergyStored( final ForgeDirection from ) - { - if( this.isOutput() || !this.isActive() ) - { - return 0; - } + for (final PartP2PRFPower t : stack) { + if (t == this) { + return 0; + } + } - final Stack stack = this.getDepth(); + stack.push(this); - for( final PartP2PRFPower t : stack ) - { - if( t == this ) - { - return 0; - } - } + int total = 0; + try { + for (final PartP2PRFPower t : this.getOutputs()) { + total += t.getOutput().getMaxEnergyStored(t.getSide().getOpposite()); + } + } catch (final GridAccessException e) { + return 0; + } - stack.push( this ); + if (stack.pop() != this) { + throw new IllegalStateException("Invalid Recursion detected."); + } - int total = 0; - try - { - for( final PartP2PRFPower t : this.getOutputs() ) - { - total += t.getOutput().getMaxEnergyStored( t.getSide().getOpposite() ); - } - } - catch( final GridAccessException e ) - { - return 0; - } + return total; + } - if( stack.pop() != this ) - { - throw new IllegalStateException( "Invalid Recursion detected." ); - } - - return total; - } - - @Override - public boolean canConnectEnergy( final ForgeDirection from ) - { - return true; - } + @Override + public boolean canConnectEnergy(final ForgeDirection from) { + return true; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java index d2b42156..beb2494b 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PRedstone.java +++ b/src/main/java/appeng/parts/p2p/PartP2PRedstone.java @@ -18,7 +18,6 @@ package appeng.parts.p2p; - import appeng.api.networking.events.MENetworkBootingStatusChange; import appeng.api.networking.events.MENetworkChannelsChanged; import appeng.api.networking.events.MENetworkEventSubscribe; @@ -35,177 +34,148 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; import net.minecraft.world.World; +public class PartP2PRedstone extends PartP2PTunnel { + private int power; + private boolean recursive = false; -public class PartP2PRedstone extends PartP2PTunnel -{ + public PartP2PRedstone(final ItemStack is) { + super(is); + } - private int power; - private boolean recursive = false; + @MENetworkEventSubscribe + public void changeStateA(final MENetworkBootingStatusChange bs) { + this.setNetworkReady(); + } - public PartP2PRedstone( final ItemStack is ) - { - super( is ); - } + private void setNetworkReady() { + if (this.isOutput()) { + final PartP2PRedstone in = this.getInput(); + if (in != null) { + this.putInput(in.power); + } + } + } - @MENetworkEventSubscribe - public void changeStateA( final MENetworkBootingStatusChange bs ) - { - this.setNetworkReady(); - } + private void putInput(final Object o) { + if (this.recursive) { + return; + } - private void setNetworkReady() - { - if( this.isOutput() ) - { - final PartP2PRedstone in = this.getInput(); - if( in != null ) - { - this.putInput( in.power ); - } - } - } + this.recursive = true; + if (this.isOutput() && this.getProxy().isActive()) { + final int newPower = (Integer) o; + if (this.power != newPower) { + this.power = newPower; + this.notifyNeighbors(); + } + } + this.recursive = false; + } - private void putInput( final Object o ) - { - if( this.recursive ) - { - return; - } + private void notifyNeighbors() { + final World worldObj = this.getTile().getWorldObj(); - this.recursive = true; - if( this.isOutput() && this.getProxy().isActive() ) - { - final int newPower = (Integer) o; - if( this.power != newPower ) - { - this.power = newPower; - this.notifyNeighbors(); - } - } - this.recursive = false; - } + final int xCoord = this.getTile().xCoord; + final int yCoord = this.getTile().yCoord; + final int zCoord = this.getTile().zCoord; - private void notifyNeighbors() - { - final World worldObj = this.getTile().getWorldObj(); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord, zCoord); - final int xCoord = this.getTile().xCoord; - final int yCoord = this.getTile().yCoord; - final int zCoord = this.getTile().zCoord; + // and this cause sometimes it can go thought walls. + Platform.notifyBlocksOfNeighbors(worldObj, xCoord - 1, yCoord, zCoord); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord - 1, zCoord); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord, zCoord - 1); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord, zCoord + 1); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord, yCoord + 1, zCoord); + Platform.notifyBlocksOfNeighbors(worldObj, xCoord + 1, yCoord, zCoord); + } - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord, zCoord ); + @MENetworkEventSubscribe + public void changeStateB(final MENetworkChannelsChanged bs) { + this.setNetworkReady(); + } - // and this cause sometimes it can go thought walls. - Platform.notifyBlocksOfNeighbors( worldObj, xCoord - 1, yCoord, zCoord ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord - 1, zCoord ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord, zCoord - 1 ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord, zCoord + 1 ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord, yCoord + 1, zCoord ); - Platform.notifyBlocksOfNeighbors( worldObj, xCoord + 1, yCoord, zCoord ); - } + @MENetworkEventSubscribe + public void changeStateC(final MENetworkPowerStatusChange bs) { + this.setNetworkReady(); + } - @MENetworkEventSubscribe - public void changeStateB( final MENetworkChannelsChanged bs ) - { - this.setNetworkReady(); - } + @Override + @SideOnly(Side.CLIENT) + public IIcon getTypeTexture() { + return Blocks.redstone_block.getBlockTextureFromSide(0); + } - @MENetworkEventSubscribe - public void changeStateC( final MENetworkPowerStatusChange bs ) - { - this.setNetworkReady(); - } + @Override + public void readFromNBT(final NBTTagCompound tag) { + super.readFromNBT(tag); + this.power = tag.getInteger("power"); + } - @Override - @SideOnly( Side.CLIENT ) - public IIcon getTypeTexture() - { - return Blocks.redstone_block.getBlockTextureFromSide( 0 ); - } + @Override + public void writeToNBT(final NBTTagCompound tag) { + super.writeToNBT(tag); + tag.setInteger("power", this.power); + } - @Override - public void readFromNBT( final NBTTagCompound tag ) - { - super.readFromNBT( tag ); - this.power = tag.getInteger( "power" ); - } + @Override + public void onTunnelNetworkChange() { + this.setNetworkReady(); + } - @Override - public void writeToNBT( final NBTTagCompound tag ) - { - super.writeToNBT( tag ); - tag.setInteger( "power", this.power ); - } + public float getPowerDrainPerTick() { + return 0.5f; + } - @Override - public void onTunnelNetworkChange() - { - this.setNetworkReady(); - } + @Override + public void onNeighborChanged() { + if (!this.isOutput()) { + final int x = this.getTile().xCoord + this.getSide().offsetX; + final int y = this.getTile().yCoord + this.getSide().offsetY; + final int z = this.getTile().zCoord + this.getSide().offsetZ; - public float getPowerDrainPerTick() - { - return 0.5f; - } + final Block b = this.getTile().getWorldObj().getBlock(x, y, z); + if (b != null && !this.isOutput()) { + int srcSide = this.getSide().ordinal(); + if (b instanceof BlockRedstoneWire) { + srcSide = 1; + } + this.power = b.isProvidingStrongPower( + this.getTile().getWorldObj(), x, y, z, srcSide + ); + this.power = Math.max( + this.power, + b.isProvidingWeakPower(this.getTile().getWorldObj(), x, y, z, srcSide) + ); + this.sendToOutput(this.power); + } else { + this.sendToOutput(0); + } + } + } - @Override - public void onNeighborChanged() - { - if( !this.isOutput() ) - { - final int x = this.getTile().xCoord + this.getSide().offsetX; - final int y = this.getTile().yCoord + this.getSide().offsetY; - final int z = this.getTile().zCoord + this.getSide().offsetZ; + @Override + public boolean canConnectRedstone() { + return true; + } - final Block b = this.getTile().getWorldObj().getBlock( x, y, z ); - if( b != null && !this.isOutput() ) - { - int srcSide = this.getSide().ordinal(); - if( b instanceof BlockRedstoneWire ) - { - srcSide = 1; - } - this.power = b.isProvidingStrongPower( this.getTile().getWorldObj(), x, y, z, srcSide ); - this.power = Math.max( this.power, b.isProvidingWeakPower( this.getTile().getWorldObj(), x, y, z, srcSide ) ); - this.sendToOutput( this.power ); - } - else - { - this.sendToOutput( 0 ); - } - } - } + @Override + public int isProvidingStrongPower() { + return this.isOutput() ? this.power : 0; + } - @Override - public boolean canConnectRedstone() - { - return true; - } + @Override + public int isProvidingWeakPower() { + return this.isOutput() ? this.power : 0; + } - @Override - public int isProvidingStrongPower() - { - return this.isOutput() ? this.power : 0; - } - - @Override - public int isProvidingWeakPower() - { - return this.isOutput() ? this.power : 0; - } - - private void sendToOutput( final int power ) - { - try - { - for( final PartP2PRedstone rs : this.getOutputs() ) - { - rs.putInput( power ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } + private void sendToOutput(final int power) { + try { + for (final PartP2PRedstone rs : this.getOutputs()) { + rs.putInput(power); + } + } catch (final GridAccessException e) { + // :P + } + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java index 87c81f09..c594ece2 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnel.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnel.java @@ -18,6 +18,8 @@ package appeng.parts.p2p; +import java.util.ArrayList; +import java.util.Collection; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -54,433 +56,410 @@ import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.event.ForgeEventFactory; -import java.util.ArrayList; -import java.util.Collection; - - -public abstract class PartP2PTunnel extends PartBasicState -{ - private final TunnelCollection type = new TunnelCollection( null, this.getClass() ); - private boolean output; - private long freq; - - public PartP2PTunnel( final ItemStack is ) - { - super( is ); - } - - public TunnelCollection getCollection( final Collection collection, final Class c ) - { - if( this.type.matches( c ) ) - { - this.type.setSource( collection ); - return this.type; - } - - return null; - } - - public T getInput() - { - if( this.getFrequency() == 0 ) - { - return null; - } - - try - { - final PartP2PTunnel tunnel = this.getProxy().getP2P().getInput( this.getFrequency() ); - if( this.getClass().isInstance( tunnel ) ) - { - return (T) tunnel; - } - } - catch( final GridAccessException e ) - { - // :P - } - return null; - } - - public TunnelCollection getOutputs() throws GridAccessException - { - if( this.getProxy().isActive() ) - { - return (TunnelCollection) this.getProxy().getP2P().getOutputs( this.getFrequency(), this.getClass() ); - } - return new TunnelCollection( new ArrayList(), this.getClass() ); - } - - @Override - public void getBoxes( final 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(final IPartRenderHelper rh, final RenderBlocks renderer) - { - rh.setTexture( this.getTypeTexture() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderInventoryBox( renderer ); - - rh.setTexture( CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.BlockP2PTunnel2.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderInventoryBox( renderer ); - } - - /** - * @return If enabled it returns the icon of an AE quartz block, else vanilla quartz block icon - */ - protected IIcon getTypeTexture() - { - final Optional maybeBlock = AEApi.instance().definitions().blocks().quartz().maybeBlock(); - if( maybeBlock.isPresent() ) - { - return maybeBlock.get().getIcon( 0, 0 ); - } - else - { - return Blocks.quartz_block.getIcon( 0, 0 ); - } - } - - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); - rh.setTexture( this.getTypeTexture() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.BlockP2PTunnel2.getIcon(), this.getItemStack().getIconIndex(), CableBusTextures.PartTunnelSides.getIcon(), CableBusTextures.PartTunnelSides.getIcon() ); - - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 3, 3, 13, 13, 13, 14 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setTexture( CableBusTextures.BlockP2PTunnel3.getIcon() ); - - rh.setBounds( 6, 5, 12, 10, 11, 13 ); - rh.renderBlock( x, y, z, renderer ); - - rh.setBounds( 5, 6, 12, 11, 10, 13 ); - rh.renderBlock( x, y, z, renderer ); - - this.renderLights( x, y, z, rh, renderer ); - } - - @Override - public ItemStack getItemStack( final PartItemStack type ) - { - 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() ) - { - return maybeMEStack.get(); - } - - return super.getItemStack( type ); - } - - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setOutput( data.getBoolean( "output" ) ); - this.setFrequency( data.getLong( "freq" ) ); - } - - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "output", this.isOutput() ); - data.setLong( "freq", this.getFrequency() ); - } - - @Override - public int cableConnectionRenderTo() - { - return 1; - } - - @Override - public boolean useStandardMemoryCard() - { - return false; - } - - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - final ItemStack is = player.inventory.getCurrentItem(); - - // UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); - // AELog.info( "ID:" + id.toString() + " : " + is.getItemDamage() ); - - final TunnelType tt = AEApi.instance().registries().p2pTunnel().getTunnelTypeByItem( is ); - if( is != null && is.getItem() instanceof IMemoryCard ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return false; - - final IMemoryCard mc = (IMemoryCard) is.getItem(); - final NBTTagCompound data = mc.getData( is ); - - final ItemStack newType = ItemStack.loadItemStackFromNBT( data ); - final long freq = data.getLong( "freq" ); - - if( newType != null ) - { - if( newType.getItem() instanceof IPartItem ) - { - final IPart testPart = ( (IPartItem) newType.getItem() ).createPartFromItemStack( newType ); - if( testPart instanceof PartP2PTunnel ) - { - this.getHost().removePart( this.getSide(), true ); - final ForgeDirection dir = this.getHost().addPart( newType, this.getSide(), player ); - final IPart newBus = this.getHost().getPart( dir ); - - if( newBus instanceof PartP2PTunnel ) - { - final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; - newTunnel.setOutput( true ); - - try - { - final P2PCache p2p = newTunnel.getProxy().getP2P(); - p2p.updateFreq( newTunnel, freq ); - } - catch( final GridAccessException e ) - { - // :P - } - - newTunnel.onTunnelNetworkChange(); - } - - mc.notifyUser( player, MemoryCardMessages.SETTINGS_LOADED ); - return true; - } - } - } - mc.notifyUser( player, MemoryCardMessages.INVALID_MACHINE ); - } - else if( tt != null ) // attunement - { - ItemStack newType = null; - - final IParts parts = AEApi.instance().definitions().parts(); - - switch( tt ) - { - case LIGHT: - for( final ItemStack stack : parts.p2PTunnelLight().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case RF_POWER: - for( final ItemStack stack : parts.p2PTunnelRF().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case FLUID: - for( final ItemStack stack : parts.p2PTunnelLiquids().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case IC2_POWER: - for( final ItemStack stack : parts.p2PTunnelEU().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case ITEM: - for( final ItemStack stack : parts.p2PTunnelItems().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case ME: - for( final ItemStack stack : parts.p2PTunnelME().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case REDSTONE: - for( final ItemStack stack : parts.p2PTunnelRedstone().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case COMPUTER_MESSAGE: - for( final ItemStack stack : parts.p2PTunnelOpenComputers().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - case PRESSURE: - for( final ItemStack stack : parts.p2PTunnelPneumaticCraft().maybeStack( 1 ).asSet() ) - { - newType = stack; - } - break; - - default: - break; - } - - if( newType != null && !Platform.isSameItem( newType, this.getItemStack() ) ) - { - final boolean oldOutput = this.isOutput(); - final long myFreq = this.getFrequency(); - - this.getHost().removePart( this.getSide(), false ); - final ForgeDirection dir = this.getHost().addPart( newType, this.getSide(), player ); - final IPart newBus = this.getHost().getPart( dir ); - - if( newBus instanceof PartP2PTunnel ) - { - final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; - newTunnel.setOutput( oldOutput ); - newTunnel.onTunnelNetworkChange(); - - try - { - final P2PCache p2p = newTunnel.getProxy().getP2P(); - p2p.updateFreq( newTunnel, myFreq ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - Platform.notifyBlocksOfNeighbors( this.getTile().getWorldObj(), this.getTile().xCoord, this.getTile().yCoord, this.getTile().zCoord ); - return true; - } - } - - return false; - } - - @Override - public boolean onPartShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - final ItemStack is = player.inventory.getCurrentItem(); - if( is != null && is.getItem() instanceof IMemoryCard ) - { - if( ForgeEventFactory.onItemUseStart( player, is, 1 ) <= 0 ) - return false; - - final IMemoryCard mc = (IMemoryCard) is.getItem(); - final NBTTagCompound data = new NBTTagCompound(); - - long newFreq = this.getFrequency(); - final boolean wasOutput = this.isOutput(); - this.setOutput( false ); - - if( wasOutput || this.getFrequency() == 0 ) - { - newFreq = System.currentTimeMillis(); - } - - try - { - this.getProxy().getP2P().updateFreq( this, newFreq ); - } - catch( final GridAccessException e ) - { - // :P - } - - this.onTunnelConfigChange(); - - final ItemStack p2pItem = this.getItemStack( PartItemStack.Wrench ); - final String type = p2pItem.getUnlocalizedName(); - - p2pItem.writeToNBT( data ); - data.setLong( "freq", this.getFrequency() ); - - mc.setMemoryCardContents( is, type + ".name", data ); - mc.notifyUser( player, MemoryCardMessages.SETTINGS_SAVED ); - return true; - } - return false; - } - - public void onTunnelConfigChange() - { - } - - public void onTunnelNetworkChange() - { - - } - - @Override - @SideOnly( Side.CLIENT ) - public IIcon getBreakingTexture() - { - return CableBusTextures.BlockP2PTunnel2.getIcon(); - } - - protected void queueTunnelDrain( final PowerUnits unit, final double f ) - { - final double ae_to_tax = unit.convertTo( PowerUnits.AE, f * AEConfig.TUNNEL_POWER_LOSS ); - - try - { - this.getProxy().getEnergy().extractAEPower( ae_to_tax, Actionable.MODULATE, PowerMultiplier.ONE ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - public long getFrequency() - { - return this.freq; - } - - public void setFrequency( final long freq ) - { - this.freq = freq; - } - - public boolean isOutput() - { - return this.output; - } - - void setOutput( final boolean output ) - { - this.output = output; - } +public abstract class PartP2PTunnel extends PartBasicState { + private final TunnelCollection type = new TunnelCollection(null, this.getClass()); + private boolean output; + private long freq; + + public PartP2PTunnel(final ItemStack is) { + super(is); + } + + public TunnelCollection getCollection( + final Collection collection, final Class c + ) { + if (this.type.matches(c)) { + this.type.setSource(collection); + return this.type; + } + + return null; + } + + public T getInput() { + if (this.getFrequency() == 0) { + return null; + } + + try { + final PartP2PTunnel tunnel + = this.getProxy().getP2P().getInput(this.getFrequency()); + if (this.getClass().isInstance(tunnel)) { + return (T) tunnel; + } + } catch (final GridAccessException e) { + // :P + } + return null; + } + + public TunnelCollection getOutputs() throws GridAccessException { + if (this.getProxy().isActive()) { + return (TunnelCollection) this.getProxy().getP2P().getOutputs( + this.getFrequency(), this.getClass() + ); + } + return new TunnelCollection(new ArrayList(), this.getClass()); + } + + @Override + public void getBoxes(final 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(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setTexture(this.getTypeTexture()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + rh.setTexture( + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.BlockP2PTunnel2.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon() + ); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + } + + /** + * @return If enabled it returns the icon of an AE quartz block, else vanilla quartz + * block icon + */ + protected IIcon getTypeTexture() { + final Optional maybeBlock + = AEApi.instance().definitions().blocks().quartz().maybeBlock(); + if (maybeBlock.isPresent()) { + return maybeBlock.get().getIcon(0, 0); + } else { + return Blocks.quartz_block.getIcon(0, 0); + } + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); + rh.setTexture(this.getTypeTexture()); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture( + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.BlockP2PTunnel2.getIcon(), + this.getItemStack().getIconIndex(), + CableBusTextures.PartTunnelSides.getIcon(), + CableBusTextures.PartTunnelSides.getIcon() + ); + + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(3, 3, 13, 13, 13, 14); + rh.renderBlock(x, y, z, renderer); + + rh.setTexture(CableBusTextures.BlockP2PTunnel3.getIcon()); + + rh.setBounds(6, 5, 12, 10, 11, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 6, 12, 11, 10, 13); + rh.renderBlock(x, y, z, renderer); + + this.renderLights(x, y, z, rh, renderer); + } + + @Override + public ItemStack getItemStack(final PartItemStack type) { + 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()) { + return maybeMEStack.get(); + } + + return super.getItemStack(type); + } + + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setOutput(data.getBoolean("output")); + this.setFrequency(data.getLong("freq")); + } + + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("output", this.isOutput()); + data.setLong("freq", this.getFrequency()); + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + @Override + public boolean useStandardMemoryCard() { + return false; + } + + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + final ItemStack is = player.inventory.getCurrentItem(); + + // UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); + // AELog.info( "ID:" + id.toString() + " : " + is.getItemDamage() ); + + final TunnelType tt + = AEApi.instance().registries().p2pTunnel().getTunnelTypeByItem(is); + if (is != null && is.getItem() instanceof IMemoryCard) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) + return false; + + final IMemoryCard mc = (IMemoryCard) is.getItem(); + final NBTTagCompound data = mc.getData(is); + + final ItemStack newType = ItemStack.loadItemStackFromNBT(data); + final long freq = data.getLong("freq"); + + if (newType != null) { + if (newType.getItem() instanceof IPartItem) { + final IPart testPart = ((IPartItem) newType.getItem()) + .createPartFromItemStack(newType); + if (testPart instanceof PartP2PTunnel) { + this.getHost().removePart(this.getSide(), true); + final ForgeDirection dir + = this.getHost().addPart(newType, this.getSide(), player); + final IPart newBus = this.getHost().getPart(dir); + + if (newBus instanceof PartP2PTunnel) { + final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; + newTunnel.setOutput(true); + + try { + final P2PCache p2p = newTunnel.getProxy().getP2P(); + p2p.updateFreq(newTunnel, freq); + } catch (final GridAccessException e) { + // :P + } + + newTunnel.onTunnelNetworkChange(); + } + + mc.notifyUser(player, MemoryCardMessages.SETTINGS_LOADED); + return true; + } + } + } + mc.notifyUser(player, MemoryCardMessages.INVALID_MACHINE); + } else if (tt != null) // attunement + { + ItemStack newType = null; + + final IParts parts = AEApi.instance().definitions().parts(); + + switch (tt) { + case LIGHT: + for (final ItemStack stack : + parts.p2PTunnelLight().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case RF_POWER: + for (final ItemStack stack : + parts.p2PTunnelRF().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case FLUID: + for (final ItemStack stack : + parts.p2PTunnelLiquids().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case IC2_POWER: + for (final ItemStack stack : + parts.p2PTunnelEU().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case ITEM: + for (final ItemStack stack : + parts.p2PTunnelItems().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case ME: + for (final ItemStack stack : + parts.p2PTunnelME().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case REDSTONE: + for (final ItemStack stack : + parts.p2PTunnelRedstone().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case COMPUTER_MESSAGE: + for (final ItemStack stack : + parts.p2PTunnelOpenComputers().maybeStack(1).asSet()) { + newType = stack; + } + break; + + case PRESSURE: + for (final ItemStack stack : + parts.p2PTunnelPneumaticCraft().maybeStack(1).asSet()) { + newType = stack; + } + break; + + default: + break; + } + + if (newType != null && !Platform.isSameItem(newType, this.getItemStack())) { + final boolean oldOutput = this.isOutput(); + final long myFreq = this.getFrequency(); + + this.getHost().removePart(this.getSide(), false); + final ForgeDirection dir + = this.getHost().addPart(newType, this.getSide(), player); + final IPart newBus = this.getHost().getPart(dir); + + if (newBus instanceof PartP2PTunnel) { + final PartP2PTunnel newTunnel = (PartP2PTunnel) newBus; + newTunnel.setOutput(oldOutput); + newTunnel.onTunnelNetworkChange(); + + try { + final P2PCache p2p = newTunnel.getProxy().getP2P(); + p2p.updateFreq(newTunnel, myFreq); + } catch (final GridAccessException e) { + // :P + } + } + + Platform.notifyBlocksOfNeighbors( + this.getTile().getWorldObj(), + this.getTile().xCoord, + this.getTile().yCoord, + this.getTile().zCoord + ); + return true; + } + } + + return false; + } + + @Override + public boolean onPartShiftActivate(final EntityPlayer player, final Vec3 pos) { + final ItemStack is = player.inventory.getCurrentItem(); + if (is != null && is.getItem() instanceof IMemoryCard) { + if (ForgeEventFactory.onItemUseStart(player, is, 1) <= 0) + return false; + + final IMemoryCard mc = (IMemoryCard) is.getItem(); + final NBTTagCompound data = new NBTTagCompound(); + + long newFreq = this.getFrequency(); + final boolean wasOutput = this.isOutput(); + this.setOutput(false); + + if (wasOutput || this.getFrequency() == 0) { + newFreq = System.currentTimeMillis(); + } + + try { + this.getProxy().getP2P().updateFreq(this, newFreq); + } catch (final GridAccessException e) { + // :P + } + + this.onTunnelConfigChange(); + + final ItemStack p2pItem = this.getItemStack(PartItemStack.Wrench); + final String type = p2pItem.getUnlocalizedName(); + + p2pItem.writeToNBT(data); + data.setLong("freq", this.getFrequency()); + + mc.setMemoryCardContents(is, type + ".name", data); + mc.notifyUser(player, MemoryCardMessages.SETTINGS_SAVED); + return true; + } + return false; + } + + public void onTunnelConfigChange() {} + + public void onTunnelNetworkChange() {} + + @Override + @SideOnly(Side.CLIENT) + public IIcon getBreakingTexture() { + return CableBusTextures.BlockP2PTunnel2.getIcon(); + } + + protected void queueTunnelDrain(final PowerUnits unit, final double f) { + final double ae_to_tax + = unit.convertTo(PowerUnits.AE, f * AEConfig.TUNNEL_POWER_LOSS); + + try { + this.getProxy().getEnergy().extractAEPower( + ae_to_tax, Actionable.MODULATE, PowerMultiplier.ONE + ); + } catch (final GridAccessException e) { + // :P + } + } + + public long getFrequency() { + return this.freq; + } + + public void setFrequency(final long freq) { + this.freq = freq; + } + + public boolean isOutput() { + return this.output; + } + + void setOutput(final boolean output) { + this.output = output; + } } diff --git a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java index 4ee7467a..d270ac9e 100644 --- a/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java +++ b/src/main/java/appeng/parts/p2p/PartP2PTunnelME.java @@ -18,6 +18,9 @@ package appeng.parts.p2p; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.LinkedList; import appeng.api.AEApi; import appeng.api.exceptions.FailedConnection; @@ -41,206 +44,188 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedList; +public class PartP2PTunnelME + extends PartP2PTunnel implements IGridTickable { + private final Connections connection = new Connections(this); + private final AENetworkProxy outerProxy + = new AENetworkProxy(this, "outer", null, true); + public PartP2PTunnelME(final ItemStack is) { + super(is); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL, GridFlags.COMPRESSED_CHANNEL); + this.outerProxy.setFlags( + GridFlags.DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED + ); + } -public class PartP2PTunnelME extends PartP2PTunnel implements IGridTickable -{ + @Override + public void readFromNBT(final NBTTagCompound extra) { + super.readFromNBT(extra); + this.outerProxy.readFromNBT(extra); + } - private final Connections connection = new Connections( this ); - private final AENetworkProxy outerProxy = new AENetworkProxy( this, "outer", null, true ); + @Override + public void writeToNBT(final NBTTagCompound extra) { + super.writeToNBT(extra); + this.outerProxy.writeToNBT(extra); + } - public PartP2PTunnelME( final ItemStack is ) - { - super( is ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.COMPRESSED_CHANNEL ); - this.outerProxy.setFlags( GridFlags.DENSE_CAPACITY, GridFlags.CANNOT_CARRY_COMPRESSED ); - } + @Override + public void onTunnelNetworkChange() { + super.onTunnelNetworkChange(); + if (!this.isOutput()) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // :P + } + } + } - @Override - public void readFromNBT( final NBTTagCompound extra ) - { - super.readFromNBT( extra ); - this.outerProxy.readFromNBT( extra ); - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.DENSE; + } - @Override - public void writeToNBT( final NBTTagCompound extra ) - { - super.writeToNBT( extra ); - this.outerProxy.writeToNBT( extra ); - } + @Override + public void removeFromWorld() { + super.removeFromWorld(); + this.outerProxy.invalidate(); + } - @Override - public void onTunnelNetworkChange() - { - super.onTunnelNetworkChange(); - if( !this.isOutput() ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - } + @Override + public void addToWorld() { + super.addToWorld(); + this.outerProxy.onReady(); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.DENSE; - } + @Override + public void setPartHostInfo( + final ForgeDirection side, final IPartHost host, final TileEntity tile + ) { + super.setPartHostInfo(side, host, tile); + this.outerProxy.setValidSides(EnumSet.of(side)); + } - @Override - public void removeFromWorld() - { - super.removeFromWorld(); - this.outerProxy.invalidate(); - } + @Override + public IGridNode getExternalFacingNode() { + return this.outerProxy.getNode(); + } - @Override - public void addToWorld() - { - super.addToWorld(); - this.outerProxy.onReady(); - } + @Override + public void onPlacement( + final EntityPlayer player, final ItemStack held, final ForgeDirection side + ) { + super.onPlacement(player, held, side); + this.outerProxy.setOwner(player); + } - @Override - public void setPartHostInfo( final ForgeDirection side, final IPartHost host, final TileEntity tile ) - { - super.setPartHostInfo( side, host, tile ); - this.outerProxy.setValidSides( EnumSet.of( side ) ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.METunnel.getMin(), TickRates.METunnel.getMax(), true, false + ); + } - @Override - public IGridNode getExternalFacingNode() - { - return this.outerProxy.getNode(); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + // just move on... + try { + if (!this.getProxy().getPath().isNetworkBooting()) { + if (!this.getProxy().getEnergy().isNetworkPowered()) { + this.connection.markDestroy(); + TickHandler.INSTANCE.addCallable( + this.getTile().getWorldObj(), this.connection + ); + } else { + if (this.getProxy().isActive()) { + this.connection.markCreate(); + TickHandler.INSTANCE.addCallable( + this.getTile().getWorldObj(), this.connection + ); + } else { + this.connection.markDestroy(); + TickHandler.INSTANCE.addCallable( + this.getTile().getWorldObj(), this.connection + ); + } + } - @Override - public void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); - this.outerProxy.setOwner( player ); - } + return TickRateModulation.SLEEP; + } + } catch (final GridAccessException e) { + // meh? + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.METunnel.getMin(), TickRates.METunnel.getMax(), true, false ); - } + return TickRateModulation.IDLE; + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - // just move on... - try - { - if( !this.getProxy().getPath().isNetworkBooting() ) - { - if( !this.getProxy().getEnergy().isNetworkPowered() ) - { - this.connection.markDestroy(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this.connection ); - } - else - { - if( this.getProxy().isActive() ) - { - this.connection.markCreate(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this.connection ); - } - else - { - this.connection.markDestroy(); - TickHandler.INSTANCE.addCallable( this.getTile().getWorldObj(), this.connection ); - } - } + public void updateConnections(final Connections connections) { + if (connections.isDestroy()) { + for (final TunnelConnection cw : this.connection.getConnections().values()) { + cw.getConnection().destroy(); + } - return TickRateModulation.SLEEP; - } - } - catch( final GridAccessException e ) - { - // meh? - } + this.connection.getConnections().clear(); + } else if (connections.isCreate()) { + final Iterator i + = this.connection.getConnections().values().iterator(); + while (i.hasNext()) { + final TunnelConnection cw = i.next(); + try { + if (cw.getTunnel().getProxy().getGrid() + != this.getProxy().getGrid()) { + cw.getConnection().destroy(); + i.remove(); + } else if (!cw.getTunnel().getProxy().isActive()) { + cw.getConnection().destroy(); + i.remove(); + } + } catch (final GridAccessException e) { + // :P + } + } - return TickRateModulation.IDLE; - } + final LinkedList newSides + = new LinkedList(); + try { + for (final PartP2PTunnelME me : this.getOutputs()) { + if (me.getProxy().isActive() + && connections.getConnections().get(me.getGridNode()) == null) { + newSides.add(me); + } + } - public void updateConnections( final Connections connections ) - { - if( connections.isDestroy() ) - { - for( final TunnelConnection cw : this.connection.getConnections().values() ) - { - cw.getConnection().destroy(); - } - - this.connection.getConnections().clear(); - } - else if( connections.isCreate() ) - { - - final Iterator i = this.connection.getConnections().values().iterator(); - while( i.hasNext() ) - { - final TunnelConnection cw = i.next(); - try - { - if( cw.getTunnel().getProxy().getGrid() != this.getProxy().getGrid() ) - { - cw.getConnection().destroy(); - i.remove(); - } - else if( !cw.getTunnel().getProxy().isActive() ) - { - cw.getConnection().destroy(); - i.remove(); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - final LinkedList newSides = new LinkedList(); - try - { - for( final PartP2PTunnelME me : this.getOutputs() ) - { - if( me.getProxy().isActive() && connections.getConnections().get( me.getGridNode() ) == null ) - { - newSides.add( me ); - } - } - - for( final PartP2PTunnelME me : newSides ) - { - try - { - connections.getConnections().put( me.getGridNode(), new TunnelConnection( me, AEApi.instance().createGridConnection( this.outerProxy.getNode(), me.outerProxy.getNode() ) ) ); - } - catch( final FailedConnection e ) - { - final TileEntity start = this.getTile(); - final TileEntity end = me.getTile(); - AELog.warn( "Failed to establish a ME P2P Tunnel between the tunnels at [x=%d, y=%d, z=%d] and [x=%d, y=%d, z=%d]", start.xCoord, start.yCoord, start.zCoord, end.xCoord, end.yCoord, end.zCoord ); - // :( - } - } - } - catch( final GridAccessException e ) - { - AELog.debug( e ); - } - } - } + for (final PartP2PTunnelME me : newSides) { + try { + connections.getConnections().put( + me.getGridNode(), + new TunnelConnection( + me, + AEApi.instance().createGridConnection( + this.outerProxy.getNode(), me.outerProxy.getNode() + ) + ) + ); + } catch (final FailedConnection e) { + final TileEntity start = this.getTile(); + final TileEntity end = me.getTile(); + AELog.warn( + "Failed to establish a ME P2P Tunnel between the tunnels at [x=%d, y=%d, z=%d] and [x=%d, y=%d, z=%d]", + start.xCoord, + start.yCoord, + start.zCoord, + end.xCoord, + end.yCoord, + end.zCoord + ); + // :( + } + } + } catch (final GridAccessException e) { + AELog.debug(e); + } + } + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java b/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java index 013777ae..8fe0c986 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartDisplay.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.parts.IPartRenderHelper; import appeng.client.texture.CableBusTextures; import cpw.mods.fml.relauncher.Side; @@ -29,124 +28,159 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; - /** * A more sophisticated part overlapping all 3 textures. *

* Subclass this if you need want a new part and need all 3 textures. - * For more concrete implementations, the direct abstract subclasses might be a better alternative. + * For more concrete implementations, the direct abstract subclasses might be a better + * alternative. * * @author AlgorithmX2 * @author yueh * @version rv3 * @since rv3 */ -public abstract class AbstractPartDisplay extends AbstractPartReporting -{ +public abstract class AbstractPartDisplay extends AbstractPartReporting { + public AbstractPartDisplay(final ItemStack is) { + super(is, true); + } - public AbstractPartDisplay( final ItemStack is ) - { - super( is, true ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setBounds(2, 2, 14, 14, 14, 16); - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 2, 2, 14, 14, 14, 16 ); + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + rh.setTexture( + sideTexture, + sideTexture, + backTexture, + this.getItemStack().getIconIndex(), + sideTexture, + sideTexture + ); + rh.renderInventoryBox(renderer); - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); - rh.renderInventoryBox( renderer ); + rh.setInvColor(this.getColor().whiteVariant); + rh.renderInventoryFace( + this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer + ); - rh.setInvColor( this.getColor().whiteVariant ); - rh.renderInventoryFace( this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); + rh.setInvColor(this.getColor().mediumVariant); + rh.renderInventoryFace( + this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer + ); - rh.setInvColor( this.getColor().mediumVariant ); - rh.renderInventoryFace( this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer ); + rh.setInvColor(this.getColor().blackVariant); + rh.renderInventoryFace( + this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer + ); - rh.setInvColor( this.getColor().blackVariant ); - rh.renderInventoryFace( this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer ); + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + } - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderInventoryBox( renderer ); - } + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + this.setRenderCache( + rh.useSimplifiedRendering(x, y, z, this, this.getRenderCache()) + ); - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - this.setRenderCache( rh.useSimplifiedRendering( x, y, z, this, this.getRenderCache() ) ); + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + rh.setTexture( + sideTexture, + sideTexture, + backTexture, + this.getItemStack().getIconIndex(), + sideTexture, + sideTexture + ); - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); + if (this.getLightLevel() > 0) { + final int l = 13; + Tessellator.instance.setBrightness(l << 20 | l << 4); + } - if( this.getLightLevel() > 0 ) - { - final int l = 13; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - } + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest + = this.getSpin(); - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = this.getSpin(); + Tessellator.instance.setColorOpaque_I(this.getColor().whiteVariant); + rh.renderFace( + x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer + ); - Tessellator.instance.setColorOpaque_I( this.getColor().whiteVariant ); - rh.renderFace( x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); + Tessellator.instance.setColorOpaque_I(this.getColor().mediumVariant); + rh.renderFace( + x, y, z, this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer + ); - Tessellator.instance.setColorOpaque_I( this.getColor().mediumVariant ); - rh.renderFace( x, y, z, this.getFrontDark().getIcon(), ForgeDirection.SOUTH, renderer ); + Tessellator.instance.setColorOpaque_I(this.getColor().blackVariant); + rh.renderFace( + x, y, z, this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer + ); - Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); - rh.renderFace( x, y, z, this.getFrontColored().getIcon(), ForgeDirection.SOUTH, renderer ); + renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; - renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest = 0; + final IIcon sideStatusTexture = CableBusTextures.PartMonitorSidesStatus.getIcon(); - final IIcon sideStatusTexture = CableBusTextures.PartMonitorSidesStatus.getIcon(); + rh.setTexture( + sideStatusTexture, + sideStatusTexture, + backTexture, + this.getItemStack().getIconIndex(), + sideStatusTexture, + sideStatusTexture + ); - rh.setTexture( sideStatusTexture, sideStatusTexture, backTexture, this.getItemStack().getIconIndex(), sideStatusTexture, sideStatusTexture ); + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderBlock( x, y, z, renderer ); + final boolean hasChan + = (this.getClientFlags() & (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) + == (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG); + final boolean hasPower + = (this.getClientFlags() & PartPanel.POWERED_FLAG) == PartPanel.POWERED_FLAG; - final boolean hasChan = ( this.getClientFlags() & ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) == ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ); - final boolean hasPower = ( this.getClientFlags() & PartPanel.POWERED_FLAG ) == PartPanel.POWERED_FLAG; + if (hasChan) { + final int l = 14; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().blackVariant); + } else if (hasPower) { + final int l = 9; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(this.getColor().whiteVariant); + } else { + Tessellator.instance.setBrightness(0); + Tessellator.instance.setColorOpaque_I(0x000000); + } - if( hasChan ) - { - final int l = 14; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().blackVariant ); - } - else if( hasPower ) - { - final int l = 9; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - Tessellator.instance.setColorOpaque_I( this.getColor().whiteVariant ); - } - else - { - Tessellator.instance.setBrightness( 0 ); - Tessellator.instance.setColorOpaque_I( 0x000000 ); - } + final IIcon sideStatusLightTexture + = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); - final IIcon sideStatusLightTexture = CableBusTextures.PartMonitorSidesStatusLights.getIcon(); - - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.EAST, renderer ); - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.WEST, renderer ); - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.UP, renderer ); - rh.renderFace( x, y, z, sideStatusLightTexture, ForgeDirection.DOWN, renderer ); - } - - @Override - public boolean isLightSource() - { - return false; - } + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.EAST, renderer); + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.WEST, renderer); + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.UP, renderer); + rh.renderFace(x, y, z, sideStatusLightTexture, ForgeDirection.DOWN, renderer); + } + @Override + public boolean isLightSource() { + return false; + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java b/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java index ff14669a..c7246f91 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartMonitor.java @@ -18,6 +18,7 @@ package appeng.parts.reporting; +import java.io.IOException; import appeng.api.implementations.parts.IPartStorageMonitor; import appeng.api.networking.security.BaseActionSource; @@ -57,9 +58,6 @@ import net.minecraftforge.common.util.ForgeDirection; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.io.IOException; - - /** * A basic subclass for any item monitor like display with an item icon and an amount. *

@@ -71,364 +69,324 @@ import java.io.IOException; * @version rv3 * @since rv3 */ -public abstract class AbstractPartMonitor extends AbstractPartDisplay implements IPartStorageMonitor, IStackWatcherHost -{ - private static final IWideReadableNumberConverter NUMBER_CONVERTER = ReadableNumberConverter.INSTANCE; - private IAEItemStack configuredItem; - private String lastHumanReadableText; - private boolean isLocked; - private IStackWatcher myWatcher; - @SideOnly( Side.CLIENT ) - private boolean updateList; - @SideOnly( Side.CLIENT ) - private Integer dspList; +public abstract class AbstractPartMonitor + extends AbstractPartDisplay implements IPartStorageMonitor, IStackWatcherHost { + private static final IWideReadableNumberConverter NUMBER_CONVERTER + = ReadableNumberConverter.INSTANCE; + private IAEItemStack configuredItem; + private String lastHumanReadableText; + private boolean isLocked; + private IStackWatcher myWatcher; + @SideOnly(Side.CLIENT) + private boolean updateList; + @SideOnly(Side.CLIENT) + private Integer dspList; - @Reflected - public AbstractPartMonitor( final ItemStack is ) - { - super( is ); - } + @Reflected + public AbstractPartMonitor(final ItemStack is) { + super(is); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); - this.isLocked = data.getBoolean( "isLocked" ); + this.isLocked = data.getBoolean("isLocked"); - final NBTTagCompound myItem = data.getCompoundTag( "configuredItem" ); - this.configuredItem = AEItemStack.loadItemStackFromNBT( myItem ); - } + final NBTTagCompound myItem = data.getCompoundTag("configuredItem"); + this.configuredItem = AEItemStack.loadItemStackFromNBT(myItem); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); - data.setBoolean( "isLocked", this.isLocked ); + data.setBoolean("isLocked", this.isLocked); - final NBTTagCompound myItem = new NBTTagCompound(); - if( this.configuredItem != null ) - { - this.configuredItem.writeToNBT( myItem ); - } + final NBTTagCompound myItem = new NBTTagCompound(); + if (this.configuredItem != null) { + this.configuredItem.writeToNBT(myItem); + } - data.setTag( "configuredItem", myItem ); - } + data.setTag("configuredItem", myItem); + } - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); - data.writeBoolean( this.isLocked ); - data.writeBoolean( this.configuredItem != null ); - if( this.configuredItem != null ) - { - this.configuredItem.writeToPacket( data ); - } - } + data.writeBoolean(this.isLocked); + data.writeBoolean(this.configuredItem != null); + if (this.configuredItem != null) { + this.configuredItem.writeToPacket(data); + } + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - boolean needRedraw = super.readFromStream( data ); + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + boolean needRedraw = super.readFromStream(data); - final boolean isLocked = data.readBoolean(); - needRedraw = this.isLocked != isLocked; + final boolean isLocked = data.readBoolean(); + needRedraw = this.isLocked != isLocked; - this.isLocked = isLocked; + this.isLocked = isLocked; - final boolean val = data.readBoolean(); - if( val ) - { - this.configuredItem = AEItemStack.loadItemStackFromPacket( data ); - } - else - { - this.configuredItem = null; - } + final boolean val = data.readBoolean(); + if (val) { + this.configuredItem = AEItemStack.loadItemStackFromPacket(data); + } else { + this.configuredItem = null; + } - this.updateList = true; + this.updateList = true; - return needRedraw; - } + return needRedraw; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( Platform.isClient() ) - { - return true; - } + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (Platform.isClient()) { + return true; + } - if( !this.getProxy().isActive() ) - { - return false; - } + if (!this.getProxy().isActive()) { + return false; + } - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } - final TileEntity te = this.getTile(); - final ItemStack eq = player.getCurrentEquippedItem(); + final TileEntity te = this.getTile(); + final ItemStack eq = player.getCurrentEquippedItem(); - if( Platform.isWrench( player, eq, te.xCoord, te.yCoord, te.zCoord ) ) - { - this.isLocked = !this.isLocked; - player.addChatMessage( ( this.isLocked ? PlayerMessages.isNowLocked : PlayerMessages.isNowUnlocked ).get() ); - this.getHost().markForUpdate(); - } - else if( !this.isLocked ) - { - this.configuredItem = AEItemStack.create( eq ); - this.configureWatchers(); - this.getHost().markForUpdate(); - } - else - { - this.extractItem( player ); - } + if (Platform.isWrench(player, eq, te.xCoord, te.yCoord, te.zCoord)) { + this.isLocked = !this.isLocked; + player.addChatMessage((this.isLocked ? PlayerMessages.isNowLocked + : PlayerMessages.isNowUnlocked) + .get()); + this.getHost().markForUpdate(); + } else if (!this.isLocked) { + this.configuredItem = AEItemStack.create(eq); + this.configureWatchers(); + this.getHost().markForUpdate(); + } else { + this.extractItem(player); + } - return true; - } + return true; + } - // update the system... - private void configureWatchers() - { - if( this.myWatcher != null ) - { - this.myWatcher.clear(); - } + // update the system... + private void configureWatchers() { + if (this.myWatcher != null) { + this.myWatcher.clear(); + } - try - { - if( this.configuredItem != null ) - { - if( this.myWatcher != null ) - { - this.myWatcher.add( this.configuredItem ); - } + try { + if (this.configuredItem != null) { + if (this.myWatcher != null) { + this.myWatcher.add(this.configuredItem); + } - this.updateReportingValue( this.getProxy().getStorage().getItemInventory() ); - } - } - catch( final GridAccessException e ) - { - // >.> - } - } + this.updateReportingValue(this.getProxy().getStorage().getItemInventory() + ); + } + } catch (final GridAccessException e) { + // >.> + } + } - protected void extractItem( final EntityPlayer player ) - { + protected void extractItem(final EntityPlayer player) {} - } + private void updateReportingValue(final IMEMonitor itemInventory) { + if (this.configuredItem != null) { + final IAEItemStack result + = itemInventory.getStorageList().findPrecise(this.configuredItem); + if (result == null) { + this.configuredItem.setStackSize(0); + } else { + this.configuredItem.setStackSize(result.getStackSize()); + } + } + } - private void updateReportingValue( final IMEMonitor itemInventory ) - { - if( this.configuredItem != null ) - { - final IAEItemStack result = itemInventory.getStorageList().findPrecise( this.configuredItem ); - if( result == null ) - { - this.configuredItem.setStackSize( 0 ); - } - else - { - this.configuredItem.setStackSize( result.getStackSize() ); - } - } - } + @Override + @SideOnly(Side.CLIENT) + protected void finalize() throws Throwable { + super.finalize(); - @Override - @SideOnly( Side.CLIENT ) - protected void finalize() throws Throwable - { - super.finalize(); + if (this.dspList != null) { + GLAllocation.deleteDisplayLists(this.dspList); + } + } - if( this.dspList != null ) - { - GLAllocation.deleteDisplayLists( this.dspList ); - } - } + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic( + final double x, + final double y, + final double z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + if (this.dspList == null) { + this.dspList = GLAllocation.generateDisplayLists(1); + } - @Override - @SideOnly( Side.CLIENT ) - public void renderDynamic( final double x, final double y, final double z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - if( this.dspList == null ) - { - this.dspList = GLAllocation.generateDisplayLists( 1 ); - } + final Tessellator tess = Tessellator.instance; - final Tessellator tess = Tessellator.instance; + if ((this.getClientFlags() & (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) + != (PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG)) { + return; + } - if( ( this.getClientFlags() & ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) != ( PartPanel.POWERED_FLAG | PartPanel.CHANNEL_FLAG ) ) - { - return; - } + final IAEItemStack ais = (IAEItemStack) this.getDisplayed(); - final IAEItemStack ais = (IAEItemStack) this.getDisplayed(); + if (ais != null) { + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); - if( ais != null ) - { - GL11.glPushMatrix(); - GL11.glTranslated( x + 0.5, y + 0.5, z + 0.5 ); + if (this.updateList) { + this.updateList = false; + GL11.glNewList(this.dspList, GL11.GL_COMPILE_AND_EXECUTE); + this.tesrRenderScreen(tess, ais); + GL11.glEndList(); + } else { + GL11.glCallList(this.dspList); + } - if( this.updateList ) - { - this.updateList = false; - GL11.glNewList( this.dspList, GL11.GL_COMPILE_AND_EXECUTE ); - this.tesrRenderScreen( tess, ais ); - GL11.glEndList(); - } - else - { - GL11.glCallList( this.dspList ); - } + GL11.glPopMatrix(); + } + } - GL11.glPopMatrix(); - } - } + @Override + public boolean requireDynamicRender() { + return true; + } - @Override - public boolean requireDynamicRender() - { - return true; - } + @Override + public IAEStack getDisplayed() { + return this.configuredItem; + } - @Override - public IAEStack getDisplayed() - { - return this.configuredItem; - } + private void tesrRenderScreen(final Tessellator tess, final IAEItemStack ais) { + // GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); - private void tesrRenderScreen( final Tessellator tess, final IAEItemStack ais ) - { - // GL11.glPushAttrib( GL11.GL_ALL_ATTRIB_BITS ); + final ForgeDirection d = this.getSide(); - final ForgeDirection d = this.getSide(); + GL11.glTranslated(d.offsetX * 0.77, d.offsetY * 0.77, d.offsetZ * 0.77); - GL11.glTranslated( d.offsetX * 0.77, d.offsetY * 0.77, d.offsetZ * 0.77 ); + switch (d) { + case UP: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(this.getSpin() * 90.0F, 0, 0, 1); + break; + case DOWN: + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(this.getSpin() * -90.0F, 0, 0, 1); + break; + case EAST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); + break; + case WEST: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); + break; + case NORTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + break; + case SOUTH: + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(180.0f, 0.0f, 1.0f, 0.0f); + break; - switch( d ) - { - case UP: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( 90.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( this.getSpin() * 90.0F, 0, 0, 1 ); - break; - case DOWN: - GL11.glScalef( 1.0f, -1.0f, 1.0f ); - GL11.glRotatef( -90.0f, 1.0f, 0.0f, 0.0f ); - GL11.glRotatef( this.getSpin() * -90.0F, 0, 0, 1 ); - break; - case EAST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( -90.0f, 0.0f, 1.0f, 0.0f ); - break; - case WEST: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 90.0f, 0.0f, 1.0f, 0.0f ); - break; - case NORTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - break; - case SOUTH: - GL11.glScalef( -1.0f, -1.0f, -1.0f ); - GL11.glRotatef( 180.0f, 0.0f, 1.0f, 0.0f ); - break; + default: + break; + } - default: - break; - } + try { + final ItemStack sis = ais.getItemStack(); + sis.stackSize = 1; - try - { - final ItemStack sis = ais.getItemStack(); - sis.stackSize = 1; + final int br = 16 << 20 | 16 << 4; + final int var11 = br % 65536; + final int var12 = br / 65536; + OpenGlHelper.setLightmapTextureCoords( + OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F + ); - final int br = 16 << 20 | 16 << 4; - final int var11 = br % 65536; - final int var12 = br / 65536; - OpenGlHelper.setLightmapTextureCoords( OpenGlHelper.lightmapTexUnit, var11 * 0.8F, var12 * 0.8F ); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - GL11.glColor4f( 1.0F, 1.0F, 1.0F, 1.0F ); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + // RenderHelper.enableGUIStandardItemLighting(); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); - GL11.glDisable( GL11.GL_LIGHTING ); - GL11.glDisable( GL12.GL_RESCALE_NORMAL ); - // RenderHelper.enableGUIStandardItemLighting(); - tess.setColorOpaque_F( 1.0f, 1.0f, 1.0f ); + ClientHelper.proxy.doRenderItem(sis, this.getTile().getWorldObj()); + } catch (final Exception e) { + AELog.debug(e); + } finally { + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } - ClientHelper.proxy.doRenderItem( sis, this.getTile().getWorldObj() ); - } - catch( final Exception e ) - { - AELog.debug( e ); - } - finally - { - GL11.glEnable( GL11.GL_LIGHTING ); - GL11.glEnable( GL12.GL_RESCALE_NORMAL ); - } + GL11.glTranslatef(0.0f, 0.14f, -0.24f); + GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); - GL11.glTranslatef( 0.0f, 0.14f, -0.24f ); - GL11.glScalef( 1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f ); + final long stackSize = ais.getStackSize(); + final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm(stackSize); - final long stackSize = ais.getStackSize(); - final String renderedStackSize = NUMBER_CONVERTER.toWideReadableForm( stackSize ); + final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + final int width = fr.getStringWidth(renderedStackSize); + GL11.glTranslatef(-0.5f * width, 0.0f, -1.0f); + fr.drawString(renderedStackSize, 0, 0, 0); - final FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - final int width = fr.getStringWidth( renderedStackSize ); - GL11.glTranslatef( -0.5f * width, 0.0f, -1.0f ); - fr.drawString( renderedStackSize, 0, 0, 0 ); + // GL11.glPopAttrib(); + } - // GL11.glPopAttrib(); - } + @Override + public boolean isLocked() { + return this.isLocked; + } - @Override - public boolean isLocked() - { - return this.isLocked; - } + @Override + public void updateWatcher(final IStackWatcher newWatcher) { + this.myWatcher = newWatcher; + this.configureWatchers(); + } - @Override - public void updateWatcher( final IStackWatcher newWatcher ) - { - this.myWatcher = newWatcher; - this.configureWatchers(); - } + @Override + public void onStackChange( + final IItemList o, + final IAEStack fullStack, + final IAEStack diffStack, + final BaseActionSource src, + final StorageChannel chan + ) { + if (this.configuredItem != null) { + if (fullStack == null) { + this.configuredItem.setStackSize(0); + } else { + this.configuredItem.setStackSize(fullStack.getStackSize()); + } - @Override - public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final BaseActionSource src, final StorageChannel chan ) - { - if( this.configuredItem != null ) - { - if( fullStack == null ) - { - this.configuredItem.setStackSize( 0 ); - } - else - { - this.configuredItem.setStackSize( fullStack.getStackSize() ); - } + final long stackSize = this.configuredItem.getStackSize(); + final String humanReadableText + = NUMBER_CONVERTER.toWideReadableForm(stackSize); - final long stackSize = this.configuredItem.getStackSize(); - final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize ); + if (!humanReadableText.equals(this.lastHumanReadableText)) { + this.lastHumanReadableText = humanReadableText; + this.getHost().markForUpdate(); + } + } + } - if( !humanReadableText.equals( this.lastHumanReadableText ) ) - { - this.lastHumanReadableText = humanReadableText; - this.getHost().markForUpdate(); - } - } - } - - @Override - public boolean showNetworkInfo( final MovingObjectPosition where ) - { - return false; - } + @Override + public boolean showNetworkInfo(final MovingObjectPosition where) { + return false; + } } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartPanel.java b/src/main/java/appeng/parts/reporting/AbstractPartPanel.java index 470c7d92..ee5ca949 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartPanel.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartPanel.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.api.parts.IPartRenderHelper; import appeng.api.util.AEColor; import appeng.client.texture.CableBusTextures; @@ -30,102 +29,119 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.common.util.ForgeDirection; - /** * A very simple part for emitting light. *

- * Opposed to the other subclass of {@link AbstractPartReporting}, it will only use the bright front texture. + * Opposed to the other subclass of {@link AbstractPartReporting}, it will only use the + * bright front texture. * * @author AlgorithmX2 * @author yueh * @version rv3 * @since rv3 */ -public abstract class AbstractPartPanel extends AbstractPartReporting -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartMonitor_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartMonitor_Colored; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartMonitor_Colored; +public abstract class AbstractPartPanel extends AbstractPartReporting { + private static final CableBusTextures FRONT_BRIGHT_ICON + = CableBusTextures.PartMonitor_Bright; + private static final CableBusTextures FRONT_DARK_ICON + = CableBusTextures.PartMonitor_Colored; + private static final CableBusTextures FRONT_COLORED_ICON + = CableBusTextures.PartMonitor_Colored; - public AbstractPartPanel( final ItemStack is ) - { - super( is, false ); - } + public AbstractPartPanel(final ItemStack is) { + super(is, false); + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } - @Override - public boolean isLightSource() - { - return true; - } + @Override + public boolean isLightSource() { + return true; + } - @Override - @SideOnly( Side.CLIENT ) - public void renderInventory( final IPartRenderHelper rh, final RenderBlocks renderer ) - { - rh.setBounds( 2, 2, 14, 14, 14, 16 ); + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(final IPartRenderHelper rh, final RenderBlocks renderer) { + rh.setBounds(2, 2, 14, 14, 14, 16); - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); - rh.renderInventoryBox( renderer ); + rh.setTexture( + sideTexture, + sideTexture, + backTexture, + this.getItemStack().getIconIndex(), + sideTexture, + sideTexture + ); + rh.renderInventoryBox(renderer); - rh.setInvColor( this.getBrightnessColor() ); - rh.renderInventoryFace( this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); + rh.setInvColor(this.getBrightnessColor()); + rh.renderInventoryFace( + this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer + ); - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderInventoryBox( renderer ); - } + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + } - @Override - @SideOnly( Side.CLIENT ) - public void renderStatic( final int x, final int y, final int z, final IPartRenderHelper rh, final RenderBlocks renderer ) - { - final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); - final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + @Override + @SideOnly(Side.CLIENT) + public void renderStatic( + final int x, + final int y, + final int z, + final IPartRenderHelper rh, + final RenderBlocks renderer + ) { + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); - rh.setTexture( sideTexture, sideTexture, backTexture, this.getItemStack().getIconIndex(), sideTexture, sideTexture ); + rh.setTexture( + sideTexture, + sideTexture, + backTexture, + this.getItemStack().getIconIndex(), + sideTexture, + sideTexture + ); - rh.setBounds( 2, 2, 14, 14, 14, 16 ); - rh.renderBlock( x, y, z, renderer ); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); - if( this.getLightLevel() > 0 ) - { - final int l = 13; - Tessellator.instance.setBrightness( l << 20 | l << 4 ); - } + if (this.getLightLevel() > 0) { + final int l = 13; + Tessellator.instance.setBrightness(l << 20 | l << 4); + } - Tessellator.instance.setColorOpaque_I( this.getBrightnessColor() ); - rh.renderFace( x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer ); + Tessellator.instance.setColorOpaque_I(this.getBrightnessColor()); + rh.renderFace( + x, y, z, this.getFrontBright().getIcon(), ForgeDirection.SOUTH, renderer + ); - rh.setBounds( 4, 4, 13, 12, 12, 14 ); - rh.renderBlock( x, y, z, renderer ); - } - - /** - * How bright the color the panel should appear. Usually it depends on a {@link AEColor} variant. - * This does not affect the actual light level of the part. - * - * @return the brightness to be used. - */ - protected abstract int getBrightnessColor(); + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); + } + /** + * How bright the color the panel should appear. Usually it depends on a {@link + * AEColor} variant. This does not affect the actual light level of the part. + * + * @return the brightness to be used. + */ + protected abstract int getBrightnessColor(); } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartReporting.java b/src/main/java/appeng/parts/reporting/AbstractPartReporting.java index 529d51ff..be91088b 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartReporting.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartReporting.java @@ -18,6 +18,7 @@ package appeng.parts.reporting; +import java.io.IOException; import appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.parts.IPartMonitor; @@ -39,285 +40,252 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; - - /** - * The most basic class for any part reporting information, like terminals or monitors. This can also include basic - * panels which just provide light. - *

- * It deals with the most basic functionalities like network data, grid registration or the rotation of the actual part. - *

- * The direct abstract subclasses are usually a better entry point for adding new concrete ones. - * But this might be an ideal starting point to completely new type, which does not resemble any existing one. + * The most basic class for any part reporting information, like terminals or monitors. + * This can also include basic panels which just provide light.

It deals with the most + * basic functionalities like network data, grid registration or the rotation of the + * actual part.

The direct abstract subclasses are usually a better entry point for + * adding new concrete ones. But this might be an ideal starting point to completely new + * type, which does not resemble any existing one. * * @author AlgorithmX2 * @author yueh * @version rv3 * @since rv3 */ -public abstract class AbstractPartReporting extends AEBasePart implements IPartMonitor, IPowerChannelState -{ +public abstract class AbstractPartReporting + extends AEBasePart implements IPartMonitor, IPowerChannelState { + protected static final int POWERED_FLAG = 4; + protected static final int CHANNEL_FLAG = 16; + private static final int BOOTING_FLAG = 8; - protected static final int POWERED_FLAG = 4; - protected static final int CHANNEL_FLAG = 16; - private static final int BOOTING_FLAG = 8; + private byte spin = 0; // 0-3 + private int clientFlags = 0; // sent as byte. + private float opacity = -1; - private byte spin = 0; // 0-3 - private int clientFlags = 0; // sent as byte. - private float opacity = -1; + public AbstractPartReporting(final ItemStack is) { + this(is, false); + } - public AbstractPartReporting( final ItemStack is ) - { - this( is, false ); - } + protected AbstractPartReporting(final ItemStack is, final boolean requireChannel) { + super(is); - protected AbstractPartReporting( final ItemStack is, final boolean requireChannel ) - { - super( is ); + if (requireChannel) { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(1.0 / 2.0); + } else { + this.getProxy().setIdlePowerUsage(1.0 / 16.0); // lights drain a little bit. + } + } - if( requireChannel ) - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setIdlePowerUsage( 1.0 / 2.0 ); - } - else - { - this.getProxy().setIdlePowerUsage( 1.0 / 16.0 ); // lights drain a little bit. - } - } + @MENetworkEventSubscribe + public final void bootingRender(final MENetworkBootingStatusChange c) { + if (!this.isLightSource()) { + this.getHost().markForUpdate(); + } + } - @MENetworkEventSubscribe - public final void bootingRender( final MENetworkBootingStatusChange c ) - { - if( !this.isLightSource() ) - { - this.getHost().markForUpdate(); - } - } + @MENetworkEventSubscribe + public final void powerRender(final MENetworkPowerStatusChange c) { + this.getHost().markForUpdate(); + } - @MENetworkEventSubscribe - public final void powerRender( final MENetworkPowerStatusChange c ) - { - this.getHost().markForUpdate(); - } + @Override + public final void getBoxes(final IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(4, 4, 13, 12, 12, 14); + } - @Override - public final void getBoxes( final IPartCollisionHelper bch ) - { - bch.addBox( 2, 2, 14, 14, 14, 16 ); - bch.addBox( 4, 4, 13, 12, 12, 14 ); - } + @Override + public void onNeighborChanged() { + this.opacity = -1; + this.getHost().markForUpdate(); + } - @Override - public void onNeighborChanged() - { - this.opacity = -1; - this.getHost().markForUpdate(); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("opacity")) { + this.opacity = data.getFloat("opacity"); + } + this.spin = data.getByte("spin"); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - if( data.hasKey( "opacity" ) ) - { - this.opacity = data.getFloat( "opacity" ); - } - this.spin = data.getByte( "spin" ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setFloat("opacity", this.opacity); + data.setByte("spin", this.getSpin()); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setFloat( "opacity", this.opacity ); - data.setByte( "spin", this.getSpin() ); - } + @Override + public void writeToStream(final ByteBuf data) throws IOException { + super.writeToStream(data); + this.clientFlags = this.getSpin() & 3; - @Override - public void writeToStream( final ByteBuf data ) throws IOException - { - super.writeToStream( data ); - this.clientFlags = this.getSpin() & 3; + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.clientFlags + = this.getClientFlags() | AbstractPartReporting.POWERED_FLAG; + } - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.POWERED_FLAG; - } + if (this.getProxy().getPath().isNetworkBooting()) { + this.clientFlags + = this.getClientFlags() | AbstractPartReporting.BOOTING_FLAG; + } - if( this.getProxy().getPath().isNetworkBooting() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.BOOTING_FLAG; - } + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.clientFlags + = this.getClientFlags() | AbstractPartReporting.CHANNEL_FLAG; + } + } catch (final GridAccessException e) { + // um.. nothing. + } - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.clientFlags = this.getClientFlags() | AbstractPartReporting.CHANNEL_FLAG; - } - } - catch( final GridAccessException e ) - { - // um.. nothing. - } + data.writeByte((byte) this.getClientFlags()); + } - data.writeByte( (byte) this.getClientFlags() ); - } + @Override + public boolean readFromStream(final ByteBuf data) throws IOException { + super.readFromStream(data); + final int oldFlags = this.getClientFlags(); + this.clientFlags = data.readByte(); + this.spin = (byte) (this.getClientFlags() & 3); + return this.getClientFlags() != oldFlags; + } - @Override - public boolean readFromStream( final ByteBuf data ) throws IOException - { - super.readFromStream( data ); - final int oldFlags = this.getClientFlags(); - this.clientFlags = data.readByte(); - this.spin = (byte) ( this.getClientFlags() & 3 ); - return this.getClientFlags() != oldFlags; - } + @Override + public final int getLightLevel() { + return this.blockLight(this.isPowered() ? (this.isLightSource() ? 15 : 9) : 0); + } - @Override - public final int getLightLevel() - { - return this.blockLight( this.isPowered() ? ( this.isLightSource() ? 15 : 9 ) : 0 ); - } + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + final TileEntity te = this.getTile(); - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - final TileEntity te = this.getTile(); + if (!player.isSneaking() + && Platform.isWrench( + player, player.inventory.getCurrentItem(), te.xCoord, te.yCoord, te.zCoord + )) { + if (Platform.isServer()) { + if (this.getSpin() > 3) { + this.spin = 0; + } - if( !player.isSneaking() && Platform.isWrench( player, player.inventory.getCurrentItem(), te.xCoord, te.yCoord, te.zCoord ) ) - { - if( Platform.isServer() ) - { - if( this.getSpin() > 3 ) - { - this.spin = 0; - } + switch (this.getSpin()) { + case 0: + this.spin = 1; + break; + case 1: + this.spin = 3; + break; + case 2: + this.spin = 0; + break; + case 3: + this.spin = 2; + break; + } - switch( this.getSpin() ) - { - 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.getHost().markForUpdate(); + this.saveChanges(); + } + return true; + } else { + return super.onPartActivate(player, pos); + } + } - this.getHost().markForUpdate(); - this.saveChanges(); - } - return true; - } - else - { - return super.onPartActivate( player, pos ); - } - } + @Override + public final void onPlacement( + final EntityPlayer player, final ItemStack held, final ForgeDirection side + ) { + super.onPlacement(player, held, side); - @Override - public final void onPlacement( final EntityPlayer player, final ItemStack held, final ForgeDirection side ) - { - super.onPlacement( player, held, side ); + final 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; + } + } - final 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; - } - } + private final int blockLight(final int emit) { + if (this.opacity < 0) { + final TileEntity te = this.getTile(); + this.opacity = 255 + - te.getWorldObj().getBlockLightOpacity( + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ + ); + } - private final int blockLight( final int emit ) - { - if( this.opacity < 0 ) - { - final TileEntity te = this.getTile(); - this.opacity = 255 - te.getWorldObj().getBlockLightOpacity( te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ ); - } + return (int) (emit * (this.opacity / 255.0f)); + } - return (int) ( emit * ( this.opacity / 255.0f ) ); - } + @Override + public final boolean isPowered() { + try { + if (Platform.isServer()) { + return this.getProxy().getEnergy().isNetworkPowered(); + } else { + return ( + (this.getClientFlags() & PartPanel.POWERED_FLAG) + == PartPanel.POWERED_FLAG + ); + } + } catch (final GridAccessException e) { + return false; + } + } - @Override - public final boolean isPowered() - { - try - { - if( Platform.isServer() ) - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - else - { - return ( ( this.getClientFlags() & PartPanel.POWERED_FLAG ) == PartPanel.POWERED_FLAG ); - } - } - catch( final GridAccessException e ) - { - return false; - } - } + @Override + public final boolean isActive() { + if (!this.isLightSource()) { + return ( + (this.getClientFlags() & (PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG) + ) + == (PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG) + ); + } else { + return this.isPowered(); + } + } - @Override - public final boolean isActive() - { - if( !this.isLightSource() ) - { - return ( ( this.getClientFlags() & ( PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG ) ) == ( PartPanel.CHANNEL_FLAG | PartPanel.POWERED_FLAG ) ); - } - else - { - return this.isPowered(); - } - } + public final int getClientFlags() { + return this.clientFlags; + } - public final int getClientFlags() - { - return this.clientFlags; - } + public final byte getSpin() { + return this.spin; + } - public final byte getSpin() - { - return this.spin; - } + /** + * The texture used for the bright front layer. + *

+ * The final texture can overlap any of the the texture in no particular order. + */ + public abstract CableBusTextures getFrontBright(); - /** - * The texture used for the bright front layer. - *

- * The final texture can overlap any of the the texture in no particular order. - */ - public abstract CableBusTextures getFrontBright(); + /** + * The texture used for the colored (medium) front layer. + *

+ * The final texture can overlap any of the the texture in no particular order. + */ + public abstract CableBusTextures getFrontColored(); - /** - * The texture used for the colored (medium) front layer. - *

- * The final texture can overlap any of the the texture in no particular order. - */ - public abstract CableBusTextures getFrontColored(); - - /** - * The texture used for the dark front layer. - *

- * The final texture can overlap any of the the texture in no particular order. - */ - public abstract CableBusTextures getFrontDark(); - - /** - * Should the part emit light. This actually only affects the light level, light source use a level of 15 and non - * light source 9. - */ - public abstract boolean isLightSource(); + /** + * The texture used for the dark front layer. + *

+ * The final texture can overlap any of the the texture in no particular order. + */ + public abstract CableBusTextures getFrontDark(); + /** + * Should the part emit light. This actually only affects the light level, light + * source use a level of 15 and non light source 9. + */ + public abstract boolean isLightSource(); } diff --git a/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java b/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java index 5b19542e..fbdbac8e 100644 --- a/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java +++ b/src/main/java/appeng/parts/reporting/AbstractPartTerminal.java @@ -18,6 +18,7 @@ package appeng.parts.reporting; +import java.util.List; import appeng.api.config.Settings; import appeng.api.config.SortDir; @@ -43,139 +44,120 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Vec3; -import java.util.List; - - /** * Anything resembling an network terminal with view cells can reuse this. *

- * Note this applies only to terminals like the ME Terminal. It does not apply for more specialized terminals like the - * Interface Terminal. + * Note this applies only to terminals like the ME Terminal. It does not apply for more + * specialized terminals like the Interface Terminal. * * @author AlgorithmX2 * @author yueh * @version rv3 * @since rv3 */ -public abstract class AbstractPartTerminal extends AbstractPartDisplay implements ITerminalHost, IConfigManagerHost, IViewCellStorage, IAEAppEngInventory -{ +public abstract class AbstractPartTerminal extends AbstractPartDisplay + implements ITerminalHost, IConfigManagerHost, IViewCellStorage, IAEAppEngInventory { + private final IConfigManager cm = new ConfigManager(this); + private final AppEngInternalInventory viewCell = new AppEngInternalInventory(this, 5); - private final IConfigManager cm = new ConfigManager( this ); - private final AppEngInternalInventory viewCell = new AppEngInternalInventory( this, 5 ); + public AbstractPartTerminal(final ItemStack is) { + super(is); - public AbstractPartTerminal( final ItemStack is ) - { - super( is ); + this.cm.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.cm.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.cm.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + } - 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 getDrops(final List drops, final boolean wrenched) { + super.getDrops(drops, wrenched); - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - super.getDrops( drops, wrenched ); + for (final ItemStack is : this.viewCell) { + if (is != null) { + drops.add(is); + } + } + } - for( final ItemStack is : this.viewCell ) - { - if( is != null ) - { - drops.add( is ); - } - } - } + @Override + public IConfigManager getConfigManager() { + return this.cm; + } - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.cm.readFromNBT(data); + this.viewCell.readFromNBT(data, "viewCell"); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.cm.readFromNBT( data ); - this.viewCell.readFromNBT( data, "viewCell" ); - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.cm.writeToNBT(data); + this.viewCell.writeToNBT(data, "viewCell"); + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.cm.writeToNBT( data ); - this.viewCell.writeToNBT( data, "viewCell" ); - } + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!super.onPartActivate(player, pos)) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !super.onPartActivate( player, pos ) ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + Platform.openGUI( + player, this.getHost().getTile(), this.getSide(), this.getGui(player) + ); - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), this.getGui( player ) ); + return true; + } + } + return false; + } - return true; - } - } - return false; - } + public GuiBridge getGui(final EntityPlayer player) { + return GuiBridge.GUI_ME; + } - public GuiBridge getGui( final EntityPlayer player ) - { - return GuiBridge.GUI_ME; - } + @Override + public IMEMonitor getItemInventory() { + try { + return this.getProxy().getStorage().getItemInventory(); + } catch (final GridAccessException e) { + // err nope? + } + return null; + } - @Override - public IMEMonitor getItemInventory() - { - try - { - return this.getProxy().getStorage().getItemInventory(); - } - catch( final GridAccessException e ) - { - // err nope? - } - return null; - } + @Override + public IMEMonitor getFluidInventory() { + try { + return this.getProxy().getStorage().getFluidInventory(); + } catch (final GridAccessException e) { + // err nope? + } + return null; + } - @Override - public IMEMonitor getFluidInventory() - { - try - { - return this.getProxy().getStorage().getFluidInventory(); - } - catch( final GridAccessException e ) - { - // err nope? - } - return null; - } + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) {} - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { + @Override + public IInventory getViewCellStorage() { + return this.viewCell; + } - } - - @Override - public IInventory getViewCellStorage() - { - return this.viewCell; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - this.getHost().markForSave(); - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) { + this.getHost().markForSave(); + } } diff --git a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java index 95c1f8ce..6afdd36a 100644 --- a/src/main/java/appeng/parts/reporting/PartConversionMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartConversionMonitor.java @@ -18,6 +18,8 @@ package appeng.parts.reporting; +import java.util.Collections; +import java.util.List; import appeng.api.networking.energy.IEnergySource; import appeng.api.networking.security.PlayerSource; @@ -35,151 +37,144 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Vec3; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.List; +public class PartConversionMonitor extends AbstractPartMonitor { + private static final CableBusTextures FRONT_BRIGHT_ICON + = CableBusTextures.PartConversionMonitor_Bright; + private static final CableBusTextures FRONT_DARK_ICON + = CableBusTextures.PartConversionMonitor_Dark; + private static final CableBusTextures FRONT_DARK_ICON_LOCKED + = CableBusTextures.PartConversionMonitor_Dark_Locked; + private static final CableBusTextures FRONT_COLORED_ICON + = CableBusTextures.PartConversionMonitor_Colored; + @Reflected + public PartConversionMonitor(final ItemStack is) { + super(is); + } -public class PartConversionMonitor extends AbstractPartMonitor -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartConversionMonitor_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartConversionMonitor_Dark; - private static final CableBusTextures FRONT_DARK_ICON_LOCKED = CableBusTextures.PartConversionMonitor_Dark_Locked; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartConversionMonitor_Colored; + @Override + public boolean onPartShiftActivate(final EntityPlayer player, final Vec3 pos) { + if (Platform.isClient()) { + return true; + } - @Reflected - public PartConversionMonitor( final ItemStack is ) - { - super( is ); - } + if (!this.getProxy().isActive()) { + return false; + } - @Override - public boolean onPartShiftActivate( final EntityPlayer player, final Vec3 pos ) - { - if( Platform.isClient() ) - { - return true; - } + if (!Platform.hasPermissions(this.getLocation(), player)) { + return false; + } - if( !this.getProxy().isActive() ) - { - return false; - } + boolean ModeB = false; - if( !Platform.hasPermissions( this.getLocation(), player ) ) - { - return false; - } + ItemStack item = player.getCurrentEquippedItem(); + if (item == null && this.getDisplayed() != null) { + ModeB = true; + item = ((IAEItemStack) this.getDisplayed()).getItemStack(); + } - boolean ModeB = false; + if (item != null) { + try { + if (!this.getProxy().isActive()) { + return false; + } - ItemStack item = player.getCurrentEquippedItem(); - if( item == null && this.getDisplayed() != null ) - { - ModeB = true; - item = ( (IAEItemStack) this.getDisplayed() ).getItemStack(); - } + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell + = this.getProxy().getStorage().getItemInventory(); + final IAEItemStack input = AEItemStack.create(item); - if( item != null ) - { - try - { - if( !this.getProxy().isActive() ) - { - return false; - } + if (ModeB) { + for (int x = 0; x < player.inventory.getSizeInventory(); x++) { + final ItemStack targetStack = player.inventory.getStackInSlot(x); + if (input.equals(targetStack)) { + final IAEItemStack insertItem = input.copy(); + insertItem.setStackSize(targetStack.stackSize); + final IAEItemStack failedToInsert = Platform.poweredInsert( + energy, cell, insertItem, new PlayerSource(player, this) + ); + player.inventory.setInventorySlotContents( + x, + failedToInsert == null ? null + : failedToInsert.getItemStack() + ); + } + } + } else { + final IAEItemStack failedToInsert = Platform.poweredInsert( + energy, cell, input, new PlayerSource(player, this) + ); + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + failedToInsert == null ? null : failedToInsert.getItemStack() + ); + } + } catch (final GridAccessException e) { + // :P + } + } + return true; + } - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy().getStorage().getItemInventory(); - final IAEItemStack input = AEItemStack.create( item ); + @Override + protected void extractItem(final EntityPlayer player) { + final IAEItemStack input = (IAEItemStack) this.getDisplayed(); + if (input != null) { + try { + if (!this.getProxy().isActive()) { + return; + } - if( ModeB ) - { - for( int x = 0; x < player.inventory.getSizeInventory(); x++ ) - { - final ItemStack targetStack = player.inventory.getStackInSlot( x ); - if( input.equals( targetStack ) ) - { - final IAEItemStack insertItem = input.copy(); - insertItem.setStackSize( targetStack.stackSize ); - final IAEItemStack failedToInsert = Platform.poweredInsert( energy, cell, insertItem, new PlayerSource( player, this ) ); - player.inventory.setInventorySlotContents( x, failedToInsert == null ? null : failedToInsert.getItemStack() ); - } - } - } - else - { - final IAEItemStack failedToInsert = Platform.poweredInsert( energy, cell, input, new PlayerSource( player, this ) ); - player.inventory.setInventorySlotContents( player.inventory.currentItem, failedToInsert == null ? null : failedToInsert.getItemStack() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - return true; - } + final IEnergySource energy = this.getProxy().getEnergy(); + final IMEMonitor cell + = this.getProxy().getStorage().getItemInventory(); - @Override - protected void extractItem( final EntityPlayer player ) - { - final IAEItemStack input = (IAEItemStack) this.getDisplayed(); - if( input != null ) - { - try - { - if( !this.getProxy().isActive() ) - { - return; - } + final ItemStack is = input.getItemStack(); + input.setStackSize(is.getMaxStackSize()); - final IEnergySource energy = this.getProxy().getEnergy(); - final IMEMonitor cell = this.getProxy().getStorage().getItemInventory(); + final IAEItemStack retrieved = Platform.poweredExtraction( + energy, cell, input, new PlayerSource(player, this) + ); + if (retrieved != null) { + ItemStack newItems = retrieved.getItemStack(); + final InventoryAdaptor adaptor + = InventoryAdaptor.getAdaptor(player, ForgeDirection.UNKNOWN); + newItems = adaptor.addItems(newItems); + if (newItems != null) { + final TileEntity te = this.getTile(); + final List list = Collections.singletonList(newItems); + Platform.spawnDrops( + player.worldObj, + te.xCoord + this.getSide().offsetX, + te.yCoord + this.getSide().offsetY, + te.zCoord + this.getSide().offsetZ, + list + ); + } - final ItemStack is = input.getItemStack(); - input.setStackSize( is.getMaxStackSize() ); + if (player.openContainer != null) { + player.openContainer.detectAndSendChanges(); + } + } + } catch (final GridAccessException e) { + // :P + } + } + } - final IAEItemStack retrieved = Platform.poweredExtraction( energy, cell, input, new PlayerSource( player, this ) ); - if( retrieved != null ) - { - ItemStack newItems = retrieved.getItemStack(); - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( player, ForgeDirection.UNKNOWN ); - newItems = adaptor.addItems( newItems ); - if( newItems != null ) - { - final TileEntity te = this.getTile(); - final List list = Collections.singletonList( newItems ); - Platform.spawnDrops( player.worldObj, te.xCoord + this.getSide().offsetX, te.yCoord + this.getSide().offsetY, te.zCoord + this.getSide().offsetZ, list ); - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - if( player.openContainer != null ) - { - player.openContainer.detectAndSendChanges(); - } - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return this.isLocked() ? FRONT_DARK_ICON_LOCKED : FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return this.isLocked() ? FRONT_DARK_ICON_LOCKED : FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java index e595dff2..c7bd4778 100644 --- a/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartCraftingTerminal.java @@ -18,6 +18,7 @@ package appeng.parts.reporting; +import java.util.List; import appeng.client.texture.CableBusTextures; import appeng.core.api.ICraftingTerminal; @@ -29,96 +30,85 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; +public class PartCraftingTerminal + extends AbstractPartTerminal implements ICraftingTerminal { + private static final CableBusTextures FRONT_BRIGHT_ICON + = CableBusTextures.PartCraftingTerm_Bright; + private static final CableBusTextures FRONT_DARK_ICON + = CableBusTextures.PartCraftingTerm_Dark; + private static final CableBusTextures FRONT_COLORED_ICON + = CableBusTextures.PartCraftingTerm_Colored; + private final AppEngInternalInventory craftingGrid + = new AppEngInternalInventory(this, 9); -public class PartCraftingTerminal extends AbstractPartTerminal implements ICraftingTerminal -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartCraftingTerm_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartCraftingTerm_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartCraftingTerm_Colored; + @Reflected + public PartCraftingTerminal(final ItemStack is) { + super(is); + } - private final AppEngInternalInventory craftingGrid = new AppEngInternalInventory( this, 9 ); + @Override + public void getDrops(final List drops, final boolean wrenched) { + super.getDrops(drops, wrenched); - @Reflected - public PartCraftingTerminal( final ItemStack is ) - { - super( is ); - } + for (final ItemStack is : this.craftingGrid) { + if (is != null) { + drops.add(is); + } + } + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - super.getDrops( drops, wrenched ); + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.craftingGrid.readFromNBT(data, "craftingGrid"); + } - for( final ItemStack is : this.craftingGrid ) - { - if( is != null ) - { - drops.add( is ); - } - } - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.craftingGrid.writeToNBT(data, "craftingGrid"); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.craftingGrid.readFromNBT( data, "craftingGrid" ); - } + @Override + public GuiBridge getGui(final EntityPlayer p) { + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (this.getHost().getTile() != null) { + x = this.getTile().xCoord; + y = this.getTile().yCoord; + z = this.getTile().zCoord; + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.craftingGrid.writeToNBT( data, "craftingGrid" ); - } + if (GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions( + this.getHost().getTile(), x, y, z, this.getSide(), p + )) { + return GuiBridge.GUI_CRAFTING_TERMINAL; + } + return GuiBridge.GUI_ME; + } - @Override - public GuiBridge getGui( final EntityPlayer p ) - { - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { - x = this.getTile().xCoord; - y = this.getTile().yCoord; - z = this.getTile().zCoord; - } + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("crafting")) { + return this.craftingGrid; + } + return super.getInventoryByName(name); + } - if( GuiBridge.GUI_CRAFTING_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { - return GuiBridge.GUI_CRAFTING_TERMINAL; - } - return GuiBridge.GUI_ME; - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { - return this.craftingGrid; - } - return super.getInventoryByName( name ); - } + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartDarkPanel.java b/src/main/java/appeng/parts/reporting/PartDarkPanel.java index e22bb175..f4813f49 100644 --- a/src/main/java/appeng/parts/reporting/PartDarkPanel.java +++ b/src/main/java/appeng/parts/reporting/PartDarkPanel.java @@ -18,23 +18,17 @@ package appeng.parts.reporting; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartDarkPanel extends AbstractPartPanel { + @Reflected + public PartDarkPanel(final ItemStack is) { + super(is); + } -public class PartDarkPanel extends AbstractPartPanel -{ - - @Reflected - public PartDarkPanel( final ItemStack is ) - { - super( is ); - } - - @Override - protected int getBrightnessColor() - { - return this.getColor().mediumVariant; - } + @Override + protected int getBrightnessColor() { + return this.getColor().mediumVariant; + } } diff --git a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java index f742b9cb..fed0a398 100644 --- a/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartInterfaceTerminal.java @@ -18,7 +18,6 @@ package appeng.parts.reporting; - import appeng.client.texture.CableBusTextures; import appeng.core.sync.GuiBridge; import appeng.util.Platform; @@ -26,54 +25,52 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.Vec3; +public class PartInterfaceTerminal extends AbstractPartDisplay { + private static final CableBusTextures FRONT_BRIGHT_ICON + = CableBusTextures.PartInterfaceTerm_Bright; + private static final CableBusTextures FRONT_DARK_ICON + = CableBusTextures.PartInterfaceTerm_Dark; + private static final CableBusTextures FRONT_COLORED_ICON + = CableBusTextures.PartInterfaceTerm_Colored; -public class PartInterfaceTerminal extends AbstractPartDisplay -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartInterfaceTerm_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartInterfaceTerm_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartInterfaceTerm_Colored; + public PartInterfaceTerminal(final ItemStack is) { + super(is); + } - public PartInterfaceTerminal( final ItemStack is ) - { - super( is ); - } + @Override + public boolean onPartActivate(final EntityPlayer player, final Vec3 pos) { + if (!super.onPartActivate(player, pos)) { + if (!player.isSneaking()) { + if (Platform.isClient()) { + return true; + } - @Override - public boolean onPartActivate( final EntityPlayer player, final Vec3 pos ) - { - if( !super.onPartActivate( player, pos ) ) - { - if( !player.isSneaking() ) - { - if( Platform.isClient() ) - { - return true; - } + Platform.openGUI( + player, + this.getHost().getTile(), + this.getSide(), + GuiBridge.GUI_INTERFACE_TERMINAL + ); - Platform.openGUI( player, this.getHost().getTile(), this.getSide(), GuiBridge.GUI_INTERFACE_TERMINAL ); + return true; + } + } - return true; - } - } + return false; + } - return false; - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartPanel.java b/src/main/java/appeng/parts/reporting/PartPanel.java index d12cd4dc..7303798f 100644 --- a/src/main/java/appeng/parts/reporting/PartPanel.java +++ b/src/main/java/appeng/parts/reporting/PartPanel.java @@ -18,24 +18,17 @@ package appeng.parts.reporting; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartPanel extends AbstractPartPanel { + @Reflected + public PartPanel(final ItemStack is) { + super(is); + } -public class PartPanel extends AbstractPartPanel -{ - - @Reflected - public PartPanel( final ItemStack is ) - { - super( is ); - } - - @Override - protected int getBrightnessColor() - { - return this.getColor().whiteVariant; - } - + @Override + protected int getBrightnessColor() { + return this.getColor().whiteVariant; + } } diff --git a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java index f013e48d..6c1256d3 100644 --- a/src/main/java/appeng/parts/reporting/PartPatternTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartPatternTerminal.java @@ -18,6 +18,7 @@ package appeng.parts.reporting; +import java.util.List; import appeng.api.implementations.ICraftingPatternItem; import appeng.api.networking.crafting.ICraftingPatternDetails; @@ -32,191 +33,176 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; +public class PartPatternTerminal extends AbstractPartTerminal { + private static final CableBusTextures FRONT_BRIGHT_ICON + = CableBusTextures.PartPatternTerm_Bright; + private static final CableBusTextures FRONT_DARK_ICON + = CableBusTextures.PartPatternTerm_Dark; + private static final CableBusTextures FRONT_COLORED_ICON + = CableBusTextures.PartPatternTerm_Colored; + private final AppEngInternalInventory crafting = new AppEngInternalInventory(this, 9); + private final AppEngInternalInventory output = new AppEngInternalInventory(this, 3); + private final AppEngInternalInventory pattern = new AppEngInternalInventory(this, 2); -public class PartPatternTerminal extends AbstractPartTerminal -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartPatternTerm_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartPatternTerm_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartPatternTerm_Colored; + private boolean craftingMode = true; + private boolean substitute = false; - private final AppEngInternalInventory crafting = new AppEngInternalInventory( this, 9 ); - private final AppEngInternalInventory output = new AppEngInternalInventory( this, 3 ); - private final AppEngInternalInventory pattern = new AppEngInternalInventory( this, 2 ); + @Reflected + public PartPatternTerminal(final ItemStack is) { + super(is); + } - private boolean craftingMode = true; - private boolean substitute = false; + @Override + public void getDrops(final List drops, final boolean wrenched) { + for (final ItemStack is : this.pattern) { + if (is != null) { + drops.add(is); + } + } + } - @Reflected - public PartPatternTerminal( final ItemStack is ) - { - super( is ); - } + @Override + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.setCraftingRecipe(data.getBoolean("craftingMode")); + this.setSubstitution(data.getBoolean("substitute")); + this.pattern.readFromNBT(data, "pattern"); + this.output.readFromNBT(data, "outputList"); + this.crafting.readFromNBT(data, "craftingGrid"); + } - @Override - public void getDrops( final List drops, final boolean wrenched ) - { - for( final ItemStack is : this.pattern ) - { - if( is != null ) - { - drops.add( is ); - } - } - } + @Override + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + data.setBoolean("craftingMode", this.craftingMode); + data.setBoolean("substitute", this.substitute); + this.pattern.writeToNBT(data, "pattern"); + this.output.writeToNBT(data, "outputList"); + this.crafting.writeToNBT(data, "craftingGrid"); + } - @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.setCraftingRecipe( data.getBoolean( "craftingMode" ) ); - this.setSubstitution( data.getBoolean( "substitute" ) ); - this.pattern.readFromNBT( data, "pattern" ); - this.output.readFromNBT( data, "outputList" ); - this.crafting.readFromNBT( data, "craftingGrid" ); - } + @Override + public GuiBridge getGui(final EntityPlayer p) { + int x = (int) p.posX; + int y = (int) p.posY; + int z = (int) p.posZ; + if (this.getHost().getTile() != null) { + x = this.getTile().xCoord; + y = this.getTile().yCoord; + z = this.getTile().zCoord; + } - @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - data.setBoolean( "craftingMode", this.craftingMode ); - data.setBoolean( "substitute", this.substitute ); - this.pattern.writeToNBT( data, "pattern" ); - this.output.writeToNBT( data, "outputList" ); - this.crafting.writeToNBT( data, "craftingGrid" ); - } + if (GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions( + this.getHost().getTile(), x, y, z, this.getSide(), p + )) { + return GuiBridge.GUI_PATTERN_TERMINAL; + } + return GuiBridge.GUI_ME; + } - @Override - public GuiBridge getGui( final EntityPlayer p ) - { - int x = (int) p.posX; - int y = (int) p.posY; - int z = (int) p.posZ; - if( this.getHost().getTile() != null ) - { - x = this.getTile().xCoord; - y = this.getTile().yCoord; - z = this.getTile().zCoord; - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) { + if (inv == this.pattern && slot == 1) { + final ItemStack is = this.pattern.getStackInSlot(1); + if (is != null && is.getItem() instanceof ICraftingPatternItem) { + final ICraftingPatternItem pattern = (ICraftingPatternItem) is.getItem(); + final ICraftingPatternDetails details = pattern.getPatternForItem( + is, this.getHost().getTile().getWorldObj() + ); + if (details != null) { + this.setCraftingRecipe(details.isCraftable()); + this.setSubstitution(details.canSubstitute()); - if( GuiBridge.GUI_PATTERN_TERMINAL.hasPermissions( this.getHost().getTile(), x, y, z, this.getSide(), p ) ) - { - return GuiBridge.GUI_PATTERN_TERMINAL; - } - return GuiBridge.GUI_ME; - } + for (int x = 0; x < this.crafting.getSizeInventory() + && x < details.getInputs().length; + x++) { + final IAEItemStack item = details.getInputs()[x]; + this.crafting.setInventorySlotContents( + x, item == null ? null : item.getItemStack() + ); + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.pattern && slot == 1 ) - { - final ItemStack is = this.pattern.getStackInSlot( 1 ); - if( is != null && is.getItem() instanceof ICraftingPatternItem ) - { - final ICraftingPatternItem pattern = (ICraftingPatternItem) is.getItem(); - final ICraftingPatternDetails details = pattern.getPatternForItem( is, this.getHost().getTile().getWorldObj() ); - if( details != null ) - { - this.setCraftingRecipe( details.isCraftable() ); - this.setSubstitution( details.canSubstitute() ); + for (int x = 0; x < this.output.getSizeInventory() + && x < details.getOutputs().length; + x++) { + final IAEItemStack item = details.getOutputs()[x]; + this.output.setInventorySlotContents( + x, item == null ? null : item.getItemStack() + ); + } + } + } + } else if (inv == this.crafting) { + this.fixCraftingRecipes(); + } - for( int x = 0; x < this.crafting.getSizeInventory() && x < details.getInputs().length; x++ ) - { - final IAEItemStack item = details.getInputs()[x]; - this.crafting.setInventorySlotContents( x, item == null ? null : item.getItemStack() ); - } + this.getHost().markForSave(); + } - for( int x = 0; x < this.output.getSizeInventory() && x < details.getOutputs().length; x++ ) - { - final IAEItemStack item = details.getOutputs()[x]; - this.output.setInventorySlotContents( x, item == null ? null : item.getItemStack() ); - } - } - } - } - else if( inv == this.crafting ) - { - this.fixCraftingRecipes(); - } + private void fixCraftingRecipes() { + if (this.craftingMode) { + for (int x = 0; x < this.crafting.getSizeInventory(); x++) { + final ItemStack is = this.crafting.getStackInSlot(x); + if (is != null) { + is.stackSize = 1; + } + } + } + } - this.getHost().markForSave(); - } + public boolean isCraftingRecipe() { + return this.craftingMode; + } - private void fixCraftingRecipes() - { - if( this.craftingMode ) - { - for( int x = 0; x < this.crafting.getSizeInventory(); x++ ) - { - final ItemStack is = this.crafting.getStackInSlot( x ); - if( is != null ) - { - is.stackSize = 1; - } - } - } - } + public void setCraftingRecipe(final boolean craftingMode) { + this.craftingMode = craftingMode; + this.fixCraftingRecipes(); + } - public boolean isCraftingRecipe() - { - return this.craftingMode; - } + public boolean isSubstitution() { + return this.substitute; + } - public void setCraftingRecipe( final boolean craftingMode ) - { - this.craftingMode = craftingMode; - this.fixCraftingRecipes(); - } + public void setSubstitution(boolean canSubstitute) { + this.substitute = canSubstitute; + } - public boolean isSubstitution() - { - return this.substitute; - } + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("crafting")) { + return this.crafting; + } - public void setSubstitution( boolean canSubstitute ) - { - this.substitute = canSubstitute; - } + if (name.equals("output")) { + return this.output; + } - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "crafting" ) ) - { - return this.crafting; - } + if (name.equals("pattern")) { + return this.pattern; + } - if( name.equals( "output" ) ) - { - return this.output; - } + return super.getInventoryByName(name); + } - if( name.equals( "pattern" ) ) - { - return this.pattern; - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - return super.getInventoryByName( name ); - } + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java b/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java index aee42e1a..19e08e03 100644 --- a/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java +++ b/src/main/java/appeng/parts/reporting/PartSemiDarkPanel.java @@ -18,25 +18,21 @@ package appeng.parts.reporting; - import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; +public class PartSemiDarkPanel extends AbstractPartPanel { + @Reflected + public PartSemiDarkPanel(final ItemStack is) { + super(is); + } -public class PartSemiDarkPanel extends AbstractPartPanel -{ - - @Reflected - public PartSemiDarkPanel( final ItemStack is ) - { - super( is ); - } - - @Override - protected int getBrightnessColor() - { - final int light = this.getColor().whiteVariant; - final int dark = this.getColor().mediumVariant; - return ( ( ( ( ( light >> 16 ) & 0xff ) + ( ( dark >> 16 ) & 0xff ) ) / 2 ) << 16 ) | ( ( ( ( ( light >> 8 ) & 0xff ) + ( ( dark >> 8 ) & 0xff ) ) / 2 ) << 8 ) | ( ( ( ( light ) & 0xff ) + ( ( dark ) & 0xff ) ) / 2 ); - } + @Override + protected int getBrightnessColor() { + final int light = this.getColor().whiteVariant; + final int dark = this.getColor().mediumVariant; + return (((((light >> 16) & 0xff) + ((dark >> 16) & 0xff)) / 2) << 16) + | (((((light >> 8) & 0xff) + ((dark >> 8) & 0xff)) / 2) << 8) + | ((((light) &0xff) + ((dark) &0xff)) / 2); + } } diff --git a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java index 764bf131..80da5239 100644 --- a/src/main/java/appeng/parts/reporting/PartStorageMonitor.java +++ b/src/main/java/appeng/parts/reporting/PartStorageMonitor.java @@ -18,46 +18,43 @@ package appeng.parts.reporting; - import appeng.client.texture.CableBusTextures; import appeng.helpers.Reflected; import net.minecraft.item.ItemStack; - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class PartStorageMonitor extends AbstractPartMonitor -{ - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartStorageMonitor_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartStorageMonitor_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartStorageMonitor_Colored; - private static final CableBusTextures FRONT_COLORED_ICON_LOCKED = CableBusTextures.PartStorageMonitor_Colored_Locked; +public class PartStorageMonitor extends AbstractPartMonitor { + private static final CableBusTextures FRONT_BRIGHT_ICON + = CableBusTextures.PartStorageMonitor_Bright; + private static final CableBusTextures FRONT_DARK_ICON + = CableBusTextures.PartStorageMonitor_Dark; + private static final CableBusTextures FRONT_COLORED_ICON + = CableBusTextures.PartStorageMonitor_Colored; + private static final CableBusTextures FRONT_COLORED_ICON_LOCKED + = CableBusTextures.PartStorageMonitor_Colored_Locked; - @Reflected - public PartStorageMonitor( final ItemStack is ) - { - super( is ); - } + @Reflected + public PartStorageMonitor(final ItemStack is) { + super(is); + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - @Override - public CableBusTextures getFrontColored() - { - return this.isLocked() ? FRONT_COLORED_ICON_LOCKED : FRONT_COLORED_ICON; - } + @Override + public CableBusTextures getFrontColored() { + return this.isLocked() ? FRONT_COLORED_ICON_LOCKED : FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/parts/reporting/PartTerminal.java b/src/main/java/appeng/parts/reporting/PartTerminal.java index f3db2dce..b1769764 100644 --- a/src/main/java/appeng/parts/reporting/PartTerminal.java +++ b/src/main/java/appeng/parts/reporting/PartTerminal.java @@ -18,38 +18,33 @@ package appeng.parts.reporting; - import appeng.client.texture.CableBusTextures; import net.minecraft.item.ItemStack; +public class PartTerminal extends AbstractPartTerminal { + public PartTerminal(final ItemStack is) { + super(is); + } -public class PartTerminal extends AbstractPartTerminal -{ + private static final CableBusTextures FRONT_BRIGHT_ICON + = CableBusTextures.PartTerminal_Bright; + private static final CableBusTextures FRONT_DARK_ICON + = CableBusTextures.PartTerminal_Dark; + private static final CableBusTextures FRONT_COLORED_ICON + = CableBusTextures.PartTerminal_Colored; - public PartTerminal( final ItemStack is ) - { - super( is ); - } + @Override + public CableBusTextures getFrontBright() { + return FRONT_BRIGHT_ICON; + } - private static final CableBusTextures FRONT_BRIGHT_ICON = CableBusTextures.PartTerminal_Bright; - private static final CableBusTextures FRONT_DARK_ICON = CableBusTextures.PartTerminal_Dark; - private static final CableBusTextures FRONT_COLORED_ICON = CableBusTextures.PartTerminal_Colored; + @Override + public CableBusTextures getFrontColored() { + return FRONT_COLORED_ICON; + } - @Override - public CableBusTextures getFrontBright() - { - return FRONT_BRIGHT_ICON; - } - - @Override - public CableBusTextures getFrontColored() - { - return FRONT_COLORED_ICON; - } - - @Override - public CableBusTextures getFrontDark() - { - return FRONT_DARK_ICON; - } + @Override + public CableBusTextures getFrontDark() { + return FRONT_DARK_ICON; + } } diff --git a/src/main/java/appeng/recipes/AEItemResolver.java b/src/main/java/appeng/recipes/AEItemResolver.java index 401cc855..b4376985 100644 --- a/src/main/java/appeng/recipes/AEItemResolver.java +++ b/src/main/java/appeng/recipes/AEItemResolver.java @@ -18,7 +18,6 @@ package appeng.recipes; - import appeng.api.AEApi; import appeng.api.definitions.IDefinitions; import appeng.api.definitions.IItems; @@ -36,151 +35,148 @@ import appeng.items.parts.ItemMultiPart; import appeng.items.parts.PartType; import net.minecraft.item.ItemStack; +public class AEItemResolver implements ISubItemResolver { + @Override + public Object resolveItemByName(final String nameSpace, final String itemName) { + if (nameSpace.equals(AppEng.MOD_ID)) { + final IDefinitions definitions = AEApi.instance().definitions(); + final IItems items = definitions.items(); + final IParts parts = definitions.parts(); -public class AEItemResolver implements ISubItemResolver -{ + if (itemName.startsWith("PaintBall.")) { + return this.paintBall( + items.coloredPaintBall(), + itemName.substring(itemName.indexOf('.') + 1), + false + ); + } - @Override - public Object resolveItemByName( final String nameSpace, final String itemName ) - { + if (itemName.startsWith("LumenPaintBall.")) { + return this.paintBall( + items.coloredLumenPaintBall(), + itemName.substring(itemName.indexOf('.') + 1), + true + ); + } - if( nameSpace.equals( AppEng.MOD_ID ) ) - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IItems items = definitions.items(); - final IParts parts = definitions.parts(); + if (itemName.equals("CableGlass")) { + return new ResolverResultSet( + "CableGlass", parts.cableGlass().allStacks(1) + ); + } - if( itemName.startsWith( "PaintBall." ) ) - { - return this.paintBall( items.coloredPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), false ); - } + if (itemName.startsWith("CableGlass.")) { + return this.cableItem( + parts.cableGlass(), itemName.substring(itemName.indexOf('.') + 1) + ); + } - if( itemName.startsWith( "LumenPaintBall." ) ) - { - return this.paintBall( items.coloredLumenPaintBall(), itemName.substring( itemName.indexOf( '.' ) + 1 ), true ); - } + if (itemName.equals("CableCovered")) { + return new ResolverResultSet( + "CableCovered", parts.cableCovered().allStacks(1) + ); + } - if( itemName.equals( "CableGlass" ) ) - { - return new ResolverResultSet( "CableGlass", parts.cableGlass().allStacks( 1 ) ); - } + if (itemName.startsWith("CableCovered.")) { + return this.cableItem( + parts.cableCovered(), itemName.substring(itemName.indexOf('.') + 1) + ); + } - if( itemName.startsWith( "CableGlass." ) ) - { - return this.cableItem( parts.cableGlass(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.equals("CableSmart")) { + return new ResolverResultSet( + "CableSmart", parts.cableSmart().allStacks(1) + ); + } - if( itemName.equals( "CableCovered" ) ) - { - return new ResolverResultSet( "CableCovered", parts.cableCovered().allStacks( 1 ) ); - } + if (itemName.startsWith("CableSmart.")) { + return this.cableItem( + parts.cableSmart(), itemName.substring(itemName.indexOf('.') + 1) + ); + } - if( itemName.startsWith( "CableCovered." ) ) - { - return this.cableItem( parts.cableCovered(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.equals("CableDense")) { + return new ResolverResultSet( + "CableDense", parts.cableDense().allStacks(1) + ); + } - if( itemName.equals( "CableSmart" ) ) - { - return new ResolverResultSet( "CableSmart", parts.cableSmart().allStacks( 1 ) ); - } + if (itemName.startsWith("CableDense.")) { + return this.cableItem( + parts.cableDense(), itemName.substring(itemName.indexOf('.') + 1) + ); + } - if( itemName.startsWith( "CableSmart." ) ) - { - return this.cableItem( parts.cableSmart(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.startsWith("ItemCrystalSeed.")) { + if (itemName.equalsIgnoreCase("ItemCrystalSeed.Certus")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.CERTUS); + } + if (itemName.equalsIgnoreCase("ItemCrystalSeed.Nether")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.NETHER); + } + if (itemName.equalsIgnoreCase("ItemCrystalSeed.Fluix")) { + return ItemCrystalSeed.getResolver(ItemCrystalSeed.FLUIX); + } - if( itemName.equals( "CableDense" ) ) - { - return new ResolverResultSet( "CableDense", parts.cableDense().allStacks( 1 ) ); - } + return null; + } - if( itemName.startsWith( "CableDense." ) ) - { - return this.cableItem( parts.cableDense(), itemName.substring( itemName.indexOf( '.' ) + 1 ) ); - } + if (itemName.startsWith("ItemMaterial.")) { + final String materialName = itemName.substring(itemName.indexOf('.') + 1); + final MaterialType mt = MaterialType.valueOf(materialName); + // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); + if (mt.getItemInstance() == ItemMultiMaterial.instance + && mt.getDamageValue() >= 0 && mt.isRegistered()) { + return new ResolverResult("ItemMultiMaterial", mt.getDamageValue()); + } + } - if( itemName.startsWith( "ItemCrystalSeed." ) ) - { - if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Certus" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.CERTUS ); - } - if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Nether" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.NETHER ); - } - if( itemName.equalsIgnoreCase( "ItemCrystalSeed.Fluix" ) ) - { - return ItemCrystalSeed.getResolver( ItemCrystalSeed.FLUIX ); - } + if (itemName.startsWith("ItemPart.")) { + final String partName = itemName.substring(itemName.indexOf('.') + 1); + final PartType pt = PartType.valueOf(partName); + // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); + final int dVal = ItemMultiPart.instance.getDamageByType(pt); + if (dVal >= 0) { + return new ResolverResult("ItemMultiPart", dVal); + } + } + } - return null; - } + return null; + } - if( itemName.startsWith( "ItemMaterial." ) ) - { - final String materialName = itemName.substring( itemName.indexOf( '.' ) + 1 ); - final MaterialType mt = MaterialType.valueOf( materialName ); - // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); - if( mt.getItemInstance() == ItemMultiMaterial.instance && mt.getDamageValue() >= 0 && mt.isRegistered() ) - { - return new ResolverResult( "ItemMultiMaterial", mt.getDamageValue() ); - } - } + private Object paintBall( + final AEColoredItemDefinition partType, + final String substring, + final boolean lumen + ) { + AEColor col; - if( itemName.startsWith( "ItemPart." ) ) - { - final String partName = itemName.substring( itemName.indexOf( '.' ) + 1 ); - final PartType pt = PartType.valueOf( partName ); - // itemName = itemName.substring( 0, itemName.indexOf( "." ) ); - final int dVal = ItemMultiPart.instance.getDamageByType( pt ); - if( dVal >= 0 ) - { - return new ResolverResult( "ItemMultiPart", dVal ); - } - } - } + try { + col = AEColor.valueOf(substring); + } catch (final Throwable t) { + col = AEColor.Transparent; + } - return null; - } + if (col == AEColor.Transparent) { + return null; + } - private Object paintBall( final AEColoredItemDefinition partType, final String substring, final boolean lumen ) - { - AEColor col; + final ItemStack is = partType.stack(col, 1); + return new ResolverResult("ItemPaintBall", (lumen ? 20 : 0) + is.getItemDamage()); + } - try - { - col = AEColor.valueOf( substring ); - } - catch( final Throwable t ) - { - col = AEColor.Transparent; - } + private Object + cableItem(final AEColoredItemDefinition partType, final String substring) { + AEColor col; - if( col == AEColor.Transparent ) - { - return null; - } + try { + col = AEColor.valueOf(substring); + } catch (final Throwable t) { + col = AEColor.Transparent; + } - final ItemStack is = partType.stack( col, 1 ); - return new ResolverResult( "ItemPaintBall", ( lumen ? 20 : 0 ) + is.getItemDamage() ); - } - - private Object cableItem( final AEColoredItemDefinition partType, final String substring ) - { - AEColor col; - - try - { - col = AEColor.valueOf( substring ); - } - catch( final Throwable t ) - { - col = AEColor.Transparent; - } - - final ItemStack is = partType.stack( col, 1 ); - return new ResolverResult( "ItemMultiPart", is.getItemDamage() ); - } + final ItemStack is = partType.stack(col, 1); + return new ResolverResult("ItemMultiPart", is.getItemDamage()); + } } diff --git a/src/main/java/appeng/recipes/CustomRecipeConfig.java b/src/main/java/appeng/recipes/CustomRecipeConfig.java index 08829ca9..36c1587c 100644 --- a/src/main/java/appeng/recipes/CustomRecipeConfig.java +++ b/src/main/java/appeng/recipes/CustomRecipeConfig.java @@ -18,13 +18,11 @@ package appeng.recipes; - /** * @author thatsIch * @version rv3 - 22.08.2015 * @since rv3 22.08.2015 */ -public interface CustomRecipeConfig -{ - boolean isEnabled(); +public interface CustomRecipeConfig { + boolean isEnabled(); } diff --git a/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java b/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java index 0d92ed95..46a456af 100644 --- a/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java +++ b/src/main/java/appeng/recipes/CustomRecipeForgeConfiguration.java @@ -18,32 +18,32 @@ package appeng.recipes; +import javax.annotation.Nonnull; import com.google.common.base.Preconditions; import net.minecraftforge.common.config.Configuration; -import javax.annotation.Nonnull; - - /** * @author thatsIch * @version rv3 - 23.08.2015 * @since rv3 23.08.2015 */ -public class CustomRecipeForgeConfiguration implements CustomRecipeConfig -{ - private final boolean isEnabled; +public class CustomRecipeForgeConfiguration implements CustomRecipeConfig { + private final boolean isEnabled; - public CustomRecipeForgeConfiguration( @Nonnull final Configuration config ) - { - Preconditions.checkNotNull( config ); + public CustomRecipeForgeConfiguration(@Nonnull final Configuration config) { + Preconditions.checkNotNull(config); - this.isEnabled = config.getBoolean( "enabled", "general", true, "If true, the custom recipes are enabled. Acts as a master switch." ); - } + this.isEnabled = config.getBoolean( + "enabled", + "general", + true, + "If true, the custom recipes are enabled. Acts as a master switch." + ); + } - @Override - public final boolean isEnabled() - { - return this.isEnabled; - } + @Override + public final boolean isEnabled() { + return this.isEnabled; + } } diff --git a/src/main/java/appeng/recipes/GroupIngredient.java b/src/main/java/appeng/recipes/GroupIngredient.java index cbb48388..21bd3bfd 100644 --- a/src/main/java/appeng/recipes/GroupIngredient.java +++ b/src/main/java/appeng/recipes/GroupIngredient.java @@ -18,6 +18,9 @@ package appeng.recipes; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -27,134 +30,111 @@ import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; +public class GroupIngredient implements IIngredient { + private final String name; + private final List ingredients; + private final int qty; + private ItemStack[] baked; + private boolean isInside = false; + public GroupIngredient( + final String myName, final List ingredients, final int qty + ) throws RecipeError { + Preconditions.checkNotNull(myName); + Preconditions.checkNotNull(ingredients); + Preconditions.checkState(!ingredients.isEmpty()); + Preconditions.checkState(qty > 0); -public class GroupIngredient implements IIngredient -{ + this.name = myName; + this.qty = qty; - private final String name; - private final List ingredients; - private final int qty; - private ItemStack[] baked; - private boolean isInside = false; + for (final IIngredient ingredient : ingredients) { + if (ingredient.isAir()) { + throw new RecipeError("Cannot include air in a group."); + } + } - public GroupIngredient( final String myName, final List ingredients, final int qty ) throws RecipeError - { - Preconditions.checkNotNull( myName ); - Preconditions.checkNotNull( ingredients ); - Preconditions.checkState( !ingredients.isEmpty() ); - Preconditions.checkState( qty > 0 ); + this.ingredients = ingredients; + } - this.name = myName; - this.qty = qty; + IIngredient copy(final int qty) throws RecipeError { + Preconditions.checkState(qty > 0); + return new GroupIngredient(this.name, this.ingredients, qty); + } - for( final IIngredient ingredient : ingredients ) - { - if( ingredient.isAir() ) - { - throw new RecipeError( "Cannot include air in a group." ); - } - } + @Override + public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { + throw new RegistrationError( + "Cannot pass group of items to a recipe which desires a single recipe item." + ); + } - this.ingredients = ingredients; - } + @Override + public ItemStack[] getItemStackSet() + throws RegistrationError, MissingIngredientError { + if (this.baked != null) { + return this.baked; + } - IIngredient copy( final int qty ) throws RecipeError - { - Preconditions.checkState( qty > 0 ); - return new GroupIngredient( this.name, this.ingredients, qty ); - } + if (this.isInside) { + return new ItemStack[0]; + } - @Override - public ItemStack getItemStack() throws RegistrationError, MissingIngredientError - { - throw new RegistrationError( "Cannot pass group of items to a recipe which desires a single recipe item." ); - } + final List out = new LinkedList(); + this.isInside = true; + try { + for (final IIngredient i : this.ingredients) { + try { + out.addAll(Arrays.asList(i.getItemStackSet())); + } catch (final MissingIngredientError mir) { + // oh well this is a group! + } + } + } finally { + this.isInside = false; + } - @Override - public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError - { - if( this.baked != null ) - { - return this.baked; - } + if (out.isEmpty()) { + throw new MissingIngredientError( + this.toString() + " - group could not be resolved to any items." + ); + } - if( this.isInside ) - { - return new ItemStack[0]; - } + for (final ItemStack is : out) { + is.stackSize = this.qty; + } - final List out = new LinkedList(); - this.isInside = true; - try - { - for( final IIngredient i : this.ingredients ) - { - try - { - out.addAll( Arrays.asList( i.getItemStackSet() ) ); - } - catch( final MissingIngredientError mir ) - { - // oh well this is a group! - } - } - } - finally - { - this.isInside = false; - } + return out.toArray(new ItemStack[out.size()]); + } - if( out.isEmpty() ) - { - throw new MissingIngredientError( this.toString() + " - group could not be resolved to any items." ); - } + @Override + public boolean isAir() { + return false; + } - for( final ItemStack is : out ) - { - is.stackSize = this.qty; - } + @Override + public String getNameSpace() { + return ""; + } - return out.toArray( new ItemStack[out.size()] ); - } + @Override + public String getItemName() { + return this.name; + } - @Override - public boolean isAir() - { - return false; - } + @Override + public int getDamageValue() { + return OreDictionary.WILDCARD_VALUE; + } - @Override - public String getNameSpace() - { - return ""; - } + @Override + public int getQty() { + return this.qty; + } - @Override - public String getItemName() - { - return this.name; - } - - @Override - public int getDamageValue() - { - return OreDictionary.WILDCARD_VALUE; - } - - @Override - public int getQty() - { - return this.qty; - } - - @Override - public void bake() throws RegistrationError, MissingIngredientError - { - this.baked = null; - this.baked = this.getItemStackSet(); - } + @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 a7b3db09..224a1e9e 100644 --- a/src/main/java/appeng/recipes/Ingredient.java +++ b/src/main/java/appeng/recipes/Ingredient.java @@ -18,6 +18,7 @@ package appeng.recipes; +import java.util.List; import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; @@ -34,241 +35,211 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.OreDictionary; -import java.util.List; +public class Ingredient implements IIngredient { + private final boolean isAir; + private final String nameSpace; + private final String itemName; + private final int meta; + private final int qty; + private NBTTagCompound nbt = null; + private ItemStack[] baked; + public Ingredient(final RecipeHandler handler, final String input, final int qty) + throws RecipeError, MissedIngredientSet { + Preconditions.checkNotNull(handler); + Preconditions.checkNotNull(input); + Preconditions.checkState(qty > 0); -public class Ingredient implements IIngredient -{ + // works no matter wat! + this.qty = qty; - private final boolean isAir; - private final String nameSpace; - private final String itemName; - private final int meta; - private final int qty; - private NBTTagCompound nbt = null; - private ItemStack[] baked; + if (input.equals("_")) { + this.isAir = true; + this.nameSpace = ""; + this.itemName = ""; + this.meta = OreDictionary.WILDCARD_VALUE; + return; + } - public Ingredient( final RecipeHandler handler, final String input, final int qty ) throws RecipeError, MissedIngredientSet - { - Preconditions.checkNotNull( handler ); - Preconditions.checkNotNull( input ); - Preconditions.checkState( qty > 0 ); + this.isAir = false; + final String[] parts = input.split(":"); + if (parts.length >= 2) { + this.nameSpace = handler.alias(parts[0]); + String tmpName = handler.alias(parts[1]); - // works no matter wat! - this.qty = qty; + if (parts.length != 3) { + int sel = 0; - if( input.equals( "_" ) ) - { - this.isAir = true; - this.nameSpace = ""; - this.itemName = ""; - this.meta = OreDictionary.WILDCARD_VALUE; - return; - } + if (this.nameSpace.equals("oreDictionary")) { + if (parts.length == 3) { + throw new RecipeError( + "Cannot specify meta when using ore dictionary." + ); + } + sel = OreDictionary.WILDCARD_VALUE; + } else { + try { + final Object ro + = AEApi.instance().registries().recipes().resolveItem( + this.nameSpace, tmpName + ); + if (ro instanceof ResolverResult) { + final ResolverResult rr = (ResolverResult) ro; + tmpName = rr.itemName; + sel = rr.damageValue; + this.nbt = rr.compound; + } else if (ro instanceof ResolverResultSet) { + throw new MissedIngredientSet((ResolverResultSet) ro); + } + } catch (final IllegalArgumentException e) { + throw new RecipeError( + tmpName + " is not a valid ae2 item definition." + ); + } + } - this.isAir = false; - final String[] parts = input.split( ":" ); - if( parts.length >= 2 ) - { - this.nameSpace = handler.alias( parts[0] ); - String tmpName = handler.alias( parts[1] ); + this.meta = sel; + } else { + if (parts[2].equals("*")) { + this.meta = OreDictionary.WILDCARD_VALUE; + } else { + try { + this.meta = Integer.parseInt(parts[2]); + } catch (final NumberFormatException e) { + throw new RecipeError("Invalid Metadata."); + } + } + } + this.itemName = tmpName; + } else { + throw new RecipeError(input + " : Needs at least Namespace and Name."); + } - if( parts.length != 3 ) - { - int sel = 0; + handler.getData().knownItem.add(this.toString()); + } - if( this.nameSpace.equals( "oreDictionary" ) ) - { - if( parts.length == 3 ) - { - throw new RecipeError( "Cannot specify meta when using ore dictionary." ); - } - sel = OreDictionary.WILDCARD_VALUE; - } - else - { - try - { - final Object ro = AEApi.instance().registries().recipes().resolveItem( this.nameSpace, tmpName ); - if( ro instanceof ResolverResult ) - { - final ResolverResult rr = (ResolverResult) ro; - tmpName = rr.itemName; - sel = rr.damageValue; - this.nbt = rr.compound; - } - else if( ro instanceof ResolverResultSet ) - { - throw new MissedIngredientSet( (ResolverResultSet) ro ); - } - } - catch( final IllegalArgumentException e ) - { - throw new RecipeError( tmpName + " is not a valid ae2 item definition." ); - } - } + @Override + public String toString() { + return this.nameSpace + ':' + this.itemName + ':' + this.meta; + } - this.meta = sel; - } - else - { - if( parts[2].equals( "*" ) ) - { - this.meta = OreDictionary.WILDCARD_VALUE; - } - else - { - try - { - this.meta = Integer.parseInt( parts[2] ); - } - catch( final NumberFormatException e ) - { - throw new RecipeError( "Invalid Metadata." ); - } - } - } - this.itemName = tmpName; - } - else - { - throw new RecipeError( input + " : Needs at least Namespace and Name." ); - } + @Override + public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { + if (this.isAir) { + throw new RegistrationError("Found blank item and expected a real item."); + } - handler.getData().knownItem.add( this.toString() ); - } + if (this.nameSpace.equalsIgnoreCase("oreDictionary")) { + throw new RegistrationError( + "Recipe format expected a single item, but got a set of items." + ); + } - @Override - public String toString() - { - return this.nameSpace + ':' + this.itemName + ':' + this.meta; - } + Block blk = GameRegistry.findBlock(this.nameSpace, this.itemName); + if (blk == null) { + blk = GameRegistry.findBlock(this.nameSpace, "tile." + this.itemName); + } - @Override - public ItemStack getItemStack() throws RegistrationError, MissingIngredientError - { - if( this.isAir ) - { - throw new RegistrationError( "Found blank item and expected a real item." ); - } + if (blk != null) { + final Item it = Item.getItemFromBlock(blk); + if (it != null) { + return this.makeItemStack(it, this.qty, this.meta, this.nbt); + } + } - if( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) - { - throw new RegistrationError( "Recipe format expected a single item, but got a set of items." ); - } + Item it = GameRegistry.findItem(this.nameSpace, this.itemName); + if (it == null) { + it = GameRegistry.findItem(this.nameSpace, "item." + this.itemName); + } - Block blk = GameRegistry.findBlock( this.nameSpace, this.itemName ); - if( blk == null ) - { - blk = GameRegistry.findBlock( this.nameSpace, "tile." + this.itemName ); - } + if (it != null) { + return this.makeItemStack(it, this.qty, this.meta, this.nbt); + } - if( blk != null ) - { - final Item it = Item.getItemFromBlock( blk ); - if( it != null ) - { - return this.makeItemStack( it, this.qty, this.meta, this.nbt ); - } - } + /* + * Object o = Item.itemRegistry.getObject( nameSpace + ":" + itemName ); if ( o + * instanceof Item ) return new ItemStack( (Item) o, qty, meta ); if ( o + * instanceof Block ) return new ItemStack( (Block) o, qty, meta ); o = + * Item.itemRegistry.getObject( nameSpace + ":item." + itemName ); if ( o + * instanceof Item ) return new ItemStack( (Item) o, qty, meta ); o = + * Block.blockRegistry.getObject( nameSpace + ":tile." + itemName ); if ( o + * instanceof Block && (!(o instanceof BlockAir)) ) return new ItemStack( (Block) + * o, qty, meta ); + */ - Item it = GameRegistry.findItem( this.nameSpace, this.itemName ); - if( it == null ) - { - it = GameRegistry.findItem( this.nameSpace, "item." + this.itemName ); - } + throw new MissingIngredientError("Unable to find item: " + this.toString()); + } - if( it != null ) - { - return this.makeItemStack( it, this.qty, this.meta, this.nbt ); - } + private ItemStack makeItemStack( + final Item it, + final int quantity, + final int damageValue, + final NBTTagCompound compound + ) { + final ItemStack is = new ItemStack(it, quantity, damageValue); + is.setTagCompound(compound); + return is; + } - /* - * Object o = Item.itemRegistry.getObject( nameSpace + ":" + itemName ); if ( o instanceof Item ) return new - * ItemStack( (Item) o, qty, meta ); - * if ( o instanceof Block ) return new ItemStack( (Block) o, qty, meta ); - * o = Item.itemRegistry.getObject( nameSpace + ":item." + itemName ); if ( o instanceof Item ) return new - * ItemStack( (Item) o, qty, meta ); - * o = Block.blockRegistry.getObject( nameSpace + ":tile." + itemName ); if ( o instanceof Block && (!(o - * instanceof BlockAir)) ) return new ItemStack( (Block) o, qty, meta ); - */ + @Override + public ItemStack[] getItemStackSet() + throws RegistrationError, MissingIngredientError { + if (this.baked != null) { + return this.baked; + } - throw new MissingIngredientError( "Unable to find item: " + this.toString() ); - } + if (this.nameSpace.equalsIgnoreCase("oreDictionary")) { + final List ores = OreDictionary.getOres(this.itemName); + final ItemStack[] set = ores.toArray(new ItemStack[ores.size()]); - private ItemStack makeItemStack( final Item it, final int quantity, final int damageValue, final NBTTagCompound compound ) - { - final ItemStack is = new ItemStack( it, quantity, damageValue ); - is.setTagCompound( compound ); - return is; - } + // clone and set qty. + for (int x = 0; x < set.length; x++) { + final ItemStack is = set[x].copy(); + is.stackSize = this.qty; + set[x] = is; + } - @Override - public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError - { - if( this.baked != null ) - { - return this.baked; - } + if (set.length == 0) { + throw new MissingIngredientError( + this.itemName + + " - ore dictionary could not be resolved to any items." + ); + } - if( this.nameSpace.equalsIgnoreCase( "oreDictionary" ) ) - { - final List ores = OreDictionary.getOres( this.itemName ); - final ItemStack[] set = ores.toArray( new ItemStack[ores.size()] ); + return set; + } - // clone and set qty. - for( int x = 0; x < set.length; x++ ) - { - final ItemStack is = set[x].copy(); - is.stackSize = this.qty; - set[x] = is; - } + return new ItemStack[] { this.getItemStack() }; + } - if( set.length == 0 ) - { - throw new MissingIngredientError( this.itemName + " - ore dictionary could not be resolved to any items." ); - } + @Override + public String getNameSpace() { + return this.nameSpace; + } - return set; - } + @Override + public String getItemName() { + return this.itemName; + } - return new ItemStack[] { this.getItemStack() }; - } + @Override + public int getDamageValue() { + return this.meta; + } - @Override - public String getNameSpace() - { - return this.nameSpace; - } + @Override + public int getQty() { + return this.qty; + } - @Override - public String getItemName() - { - return this.itemName; - } + @Override + public boolean isAir() { + return this.isAir; + } - @Override - public int getDamageValue() - { - return this.meta; - } - - @Override - public int getQty() - { - return this.qty; - } - - @Override - public boolean isAir() - { - return this.isAir; - } - - @Override - public void bake() throws RegistrationError, MissingIngredientError - { - this.baked = null; - this.baked = this.getItemStackSet(); - } + @Override + public void bake() throws RegistrationError, MissingIngredientError { + 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 407c8aa9..d748b246 100644 --- a/src/main/java/appeng/recipes/IngredientSet.java +++ b/src/main/java/appeng/recipes/IngredientSet.java @@ -18,6 +18,8 @@ package appeng.recipes; +import java.util.LinkedList; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; @@ -27,100 +29,86 @@ import com.google.common.base.Preconditions; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.LinkedList; -import java.util.List; +public class IngredientSet implements IIngredient { + private final int qty; + private final String name; + private final List items; + private final boolean isInside = false; + private ItemStack[] baked; + public IngredientSet(final ResolverResultSet rr, final int qty) { + Preconditions.checkNotNull(rr); + Preconditions.checkNotNull(rr.name); + Preconditions.checkNotNull(rr.results); + Preconditions.checkState(qty > 0); -public class IngredientSet implements IIngredient -{ + this.name = rr.name; + this.items = rr.results; + this.qty = qty; + } - private final int qty; - private final String name; - private final List items; - private final boolean isInside = false; - private ItemStack[] baked; + @Override + public ItemStack getItemStack() throws RegistrationError, MissingIngredientError { + throw new RegistrationError( + "Cannot pass group of items to a recipe which desires a single recipe item." + ); + } - public IngredientSet( final ResolverResultSet rr, final int qty ) - { - Preconditions.checkNotNull( rr ); - Preconditions.checkNotNull( rr.name ); - Preconditions.checkNotNull( rr.results ); - Preconditions.checkState( qty > 0 ); + @Override + public ItemStack[] getItemStackSet() + throws RegistrationError, MissingIngredientError { + if (this.baked != null) { + return this.baked; + } - this.name = rr.name; - this.items = rr.results; - this.qty = qty; - } + if (this.isInside) { + return new ItemStack[0]; + } - @Override - public ItemStack getItemStack() throws RegistrationError, MissingIngredientError - { - throw new RegistrationError( "Cannot pass group of items to a recipe which desires a single recipe item." ); - } + final List out = new LinkedList(); + out.addAll(this.items); - @Override - public ItemStack[] getItemStackSet() throws RegistrationError, MissingIngredientError - { - if( this.baked != null ) - { - return this.baked; - } + if (out.isEmpty()) { + throw new MissingIngredientError( + this.toString() + " - group could not be resolved to any items." + ); + } - if( this.isInside ) - { - return new ItemStack[0]; - } + for (final ItemStack is : out) { + is.stackSize = this.qty; + } - final List out = new LinkedList(); - out.addAll( this.items ); + return out.toArray(new ItemStack[out.size()]); + } - if( out.isEmpty() ) - { - throw new MissingIngredientError( this.toString() + " - group could not be resolved to any items." ); - } + @Override + public boolean isAir() { + return false; + } - for( final ItemStack is : out ) - { - is.stackSize = this.qty; - } + @Override + public String getNameSpace() { + return ""; + } - return out.toArray( new ItemStack[out.size()] ); - } + @Override + public String getItemName() { + return this.name; + } - @Override - public boolean isAir() - { - return false; - } + @Override + public int getDamageValue() { + return OreDictionary.WILDCARD_VALUE; + } - @Override - public String getNameSpace() - { - return ""; - } + @Override + public int getQty() { + return this.qty; + } - @Override - public String getItemName() - { - return this.name; - } - - @Override - public int getDamageValue() - { - return OreDictionary.WILDCARD_VALUE; - } - - @Override - public int getQty() - { - return this.qty; - } - - @Override - public void bake() throws RegistrationError, MissingIngredientError - { - this.baked = null; - this.baked = this.getItemStackSet(); - } + @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 41f398e2..2861f143 100644 --- a/src/main/java/appeng/recipes/MissedIngredientSet.java +++ b/src/main/java/appeng/recipes/MissedIngredientSet.java @@ -18,23 +18,17 @@ package appeng.recipes; - import appeng.api.recipes.ResolverResultSet; +public class MissedIngredientSet extends Throwable { + private static final long serialVersionUID = 2672951714376345807L; + private final ResolverResultSet resolverResultSet; -public class MissedIngredientSet extends Throwable -{ + public MissedIngredientSet(final ResolverResultSet ro) { + this.resolverResultSet = ro; + } - private static final long serialVersionUID = 2672951714376345807L; - private final ResolverResultSet resolverResultSet; - - public MissedIngredientSet( final ResolverResultSet ro ) - { - this.resolverResultSet = ro; - } - - ResolverResultSet getResolverResultSet() - { - return this.resolverResultSet; - } + ResolverResultSet getResolverResultSet() { + return this.resolverResultSet; + } } diff --git a/src/main/java/appeng/recipes/RecipeData.java b/src/main/java/appeng/recipes/RecipeData.java index 36b8934f..2536f307 100644 --- a/src/main/java/appeng/recipes/RecipeData.java +++ b/src/main/java/appeng/recipes/RecipeData.java @@ -18,21 +18,17 @@ package appeng.recipes; +import java.util.*; import appeng.api.recipes.ICraftHandler; -import java.util.*; +public class RecipeData { + final Map aliases = new HashMap(); + final Map groups = new HashMap(); - -public class RecipeData -{ - - final Map aliases = new HashMap(); - final Map groups = new HashMap(); - - final List handlers = new LinkedList(); - final Set knownItem = new HashSet(); - boolean crash = true; - boolean exceptions = true; - boolean errorOnMissing = true; + final List handlers = new LinkedList(); + final Set knownItem = new HashSet(); + boolean crash = true; + boolean exceptions = true; + boolean errorOnMissing = true; } diff --git a/src/main/java/appeng/recipes/RecipeHandler.java b/src/main/java/appeng/recipes/RecipeHandler.java index 79f1d244..7b5eb2c4 100644 --- a/src/main/java/appeng/recipes/RecipeHandler.java +++ b/src/main/java/appeng/recipes/RecipeHandler.java @@ -18,6 +18,15 @@ package appeng.recipes; +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.definitions.IBlocks; @@ -49,733 +58,578 @@ import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import javax.annotation.Nonnull; -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.*; -import java.util.Map.Entry; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv3 - 10.08.2015 * @since rv0 */ -public class RecipeHandler implements IRecipeHandler -{ - private final RecipeData data; - private final List tokens = new LinkedList(); - - public RecipeHandler() - { - this.data = new RecipeData(); - } - - /** - * Called recursively from parent - * - * @param parent owner of this handler - */ - private RecipeHandler( final RecipeHandler parent ) - { - Preconditions.checkNotNull( parent ); - this.data = parent.data; - } - - private void addCrafting( final ICraftHandler ch ) - { - this.data.handlers.add( ch ); - } - - public String getName( @Nonnull final IIngredient i ) - { - try - { - for( final ItemStack is : i.getItemStackSet() ) - { - return this.getName( is ); - } - } - catch( final RecipeError ignored ) - { - } - catch( final Throwable t ) - { - t.printStackTrace(); - // :P - } - - return i.getNameSpace() + ':' + i.getItemName(); - } - - private String getName( final ItemStack is ) throws RecipeError - { - Preconditions.checkNotNull( is ); - - final UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor( is.getItem() ); - String realName = id.modId + ':' + id.name; - - if( !id.modId.equals( AppEng.MOD_ID ) && !id.modId.equals( "minecraft" ) ) - { - throw new RecipeError( "Not applicable for website" ); - } - - final IDefinitions definitions = AEApi.instance().definitions(); - final IItems items = definitions.items(); - final IBlocks blocks = definitions.blocks(); - - final Optional maybeCrystalSeedItem = items.crystalSeed().maybeItem(); - final Optional maybeSkyStoneItem = blocks.skyStone().maybeItem(); - final Optional maybeCStorageItem = blocks.craftingStorage1k().maybeItem(); - final Optional maybeCUnitItem = blocks.craftingUnit().maybeItem(); - final Optional maybeSkyChestItem = blocks.skyChest().maybeItem(); - - if( maybeCrystalSeedItem.isPresent() && is.getItem() == maybeCrystalSeedItem.get() ) - { - final int dmg = is.getItemDamage(); - if( dmg < ItemCrystalSeed.NETHER ) - { - realName += ".Certus"; - } - else if( dmg < ItemCrystalSeed.FLUIX ) - { - realName += ".Nether"; - } - else if( dmg < ItemCrystalSeed.FINAL_STAGE ) - { - realName += ".Fluix"; - } - } - else if( maybeSkyStoneItem.isPresent() && is.getItem() == maybeSkyStoneItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName += ".Block"; - break; - case 2: - realName += ".Brick"; - break; - case 3: - realName += ".SmallBrick"; - break; - default: - } - } - else if( maybeCStorageItem.isPresent() && is.getItem() == maybeCStorageItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName += "4k"; - break; - case 2: - realName += "16k"; - break; - case 3: - realName += "64k"; - break; - default: - } - } - else if( maybeCUnitItem.isPresent() && is.getItem() == maybeCUnitItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName = realName.replace( "Unit", "Accelerator" ); - break; - default: - } - } - else if( maybeSkyChestItem.isPresent() && is.getItem() == maybeSkyChestItem.get() ) - { - switch( is.getItemDamage() ) - { - case 1: - realName += ".Block"; - break; - default: - } - } - else if( is.getItem() instanceof ItemMultiMaterial ) - { - realName = realName.replace( "ItemMultiMaterial", "ItemMaterial" ); - realName += '.' + ( (ItemMultiMaterial) is.getItem() ).getTypeByStack( is ).name(); - } - else if( is.getItem() instanceof ItemMultiPart ) - { - realName = realName.replace( "ItemMultiPart", "ItemPart" ); - realName += '.' + ( (ItemMultiPart) is.getItem() ).getTypeByStack( is ).name(); - } - else if( is.getItemDamage() > 0 ) - { - realName += "." + is.getItemDamage(); - } - - return realName; - } - - String alias( final String in ) - { - Preconditions.checkNotNull( in ); - - final String out = this.data.aliases.get( in ); - - if( out != null ) - { - return out; - } - - return in; - } - - @Override - public void parseRecipes( final IRecipeLoader loader, final String path ) - { - Preconditions.checkNotNull( loader ); - Preconditions.checkNotNull( path ); - - try - { - BufferedReader reader = null; - try - { - reader = loader.getFile( path ); - } - catch( final Exception err ) - { - AELog.warn( "Error Loading Recipe File:" + path ); - if( this.data.exceptions ) - { - AELog.debug( err ); - } - return; - } - - boolean inQuote = false; - boolean inComment = false; - - String token = ""; - int line = 0; - - int val = -1; - while( ( val = reader.read() ) != -1 ) - { - final char c = (char) val; - - if( c == '\n' ) - { - line++; - } - - if( inComment ) - { - if( c == '\n' || c == '\r' ) - { - inComment = false; - } - } - else if( inQuote ) - { - switch( c ) - { - case '"': - inQuote = !inQuote; - break; - default: - token += c; - } - } - else - { - switch( c ) - { - case '"': - inQuote = !inQuote; - break; - case ',': - - if( token.length() > 0 ) - { - this.tokens.add( token ); - this.tokens.add( "," ); - } - token = ""; - break; - - case '=': - - this.processTokens( loader, path, line ); - - if( token.length() > 0 ) - { - this.tokens.add( token ); - } - token = ""; - - break; - - case '#': - inComment = true; - // then add a token if you can... - - case '\n': - case '\t': - case '\r': - case ' ': - - if( token.length() > 0 ) - { - this.tokens.add( token ); - } - token = ""; - - break; - default: - token += c; - } - } - } - - if( token.length() > 0 ) - { - this.tokens.add( token ); - } - - reader.close(); - this.processTokens( loader, path, line ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - if( this.data.crash ) - { - throw new IllegalStateException( e ); - } - } - } - - @Override - public void injectRecipes() - { - if( cpw.mods.fml.common.Loader.instance().hasReachedState( LoaderState.POSTINITIALIZATION ) ) - { - throw new IllegalStateException( "Recipes must now be loaded in Init." ); - } - - final Map processed = new HashMap(); - try - { - for( final ICraftHandler ch : this.data.handlers ) - { - try - { - ch.register(); - - final Class clz = ch.getClass(); - final Integer i = processed.get( clz ); - if( i == null ) - { - processed.put( clz, 1 ); - } - else - { - processed.put( clz, i + 1 ); - } - } - catch( final RegistrationError e ) - { - AELog.warn( "Unable to register a recipe: " + e.getMessage() ); - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw e; - } - } - catch( final MissingIngredientError e ) - { - if( this.data.errorOnMissing ) - { - AELog.warn( "Unable to register a recipe:" + e.getMessage() ); - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw e; - } - } - } - } - } - catch( final Throwable e ) - { - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw new IllegalStateException( e ); - } - } - - for( final Entry e : processed.entrySet() ) - { - AELog.info( "Recipes Loading: " + e.getKey().getSimpleName() + ": " + e.getValue() + " loaded." ); - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.WebsiteRecipes ) ) - { - try - { - final ZipOutputStream out = new ZipOutputStream( new FileOutputStream( "recipes.zip" ) ); - - final HashMultimap combined = HashMultimap.create(); - - for( final String s : this.data.knownItem ) - { - try - { - - final IIngredient i = new Ingredient( this, s, 1 ); - - for( final ItemStack is : i.getItemStackSet() ) - { - final String realName = this.getName( is ); - final List recipes = this.findRecipe( is ); - if( !recipes.isEmpty() ) - { - combined.putAll( realName, recipes ); - } - } - } - catch( final RecipeError ignored ) - { - - } - catch( final MissedIngredientSet ignored ) - { - - } - catch( final RegistrationError ignored ) - { - - } - catch( final MissingIngredientError ignored ) - { - - } - } - - for( final String realName : combined.keySet() ) - { - int offset = 0; - - for( final IWebsiteSerializer ws : combined.get( realName ) ) - { - final 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( final FileNotFoundException e1 ) - { - AELog.debug( e1 ); - } - catch( final IOException e1 ) - { - AELog.debug( e1 ); - } - } - } - - private List findRecipe( final ItemStack output ) - { - final List out = new LinkedList(); - - for( final ICraftHandler ch : this.data.handlers ) - { - try - { - if( ch instanceof IWebsiteSerializer && ( (IWebsiteSerializer) ch ).canCraft( output ) ) - { - out.add( (IWebsiteSerializer) ch ); - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - return out; - } - - RecipeData getData() - { - return this.data; - } - - private void processTokens( final IRecipeLoader loader, final String file, final int line ) throws RecipeError - { - try - { - final IRecipeHandlerRegistry cr = AEApi.instance().registries().recipes(); - - if( this.tokens.isEmpty() ) - { - return; - } - - final int split = this.tokens.indexOf( "->" ); - if( split != -1 ) - { - final String operation = this.tokens.remove( 0 ).toLowerCase( Locale.ENGLISH ); - - if( operation.equals( "alias" ) ) - { - 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" ) ) - { - final List pre = this.tokens.subList( 0, split - 1 ); - final List post = this.tokens.subList( split, this.tokens.size() ); - - final List> inputs = this.parseLines( pre ); - - 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 ), 1 ) ); - } - else - { - throw new RecipeError( "Group must have exactly 1 output, and 1 or more inputs." ); - } - } - else if( operation.equals( "ore" ) ) - { - final List pre = this.tokens.subList( 0, split - 1 ); - final List post = this.tokens.subList( split, this.tokens.size() ); - - final List> inputs = this.parseLines( pre ); - - if( inputs.size() == 1 && inputs.get( 0 ).size() > 0 && post.size() == 1 ) - { - final ICraftHandler ch = new OreRegistration( inputs.get( 0 ), post.get( 0 ) ); - this.addCrafting( ch ); - } - else - { - throw new RecipeError( "Group must have exactly 1 output, and 1 or more inputs in a single row." ); - } - } - else - { - final List pre = this.tokens.subList( 0, split - 1 ); - final List post = this.tokens.subList( split, this.tokens.size() ); - - final List> inputs = this.parseLines( pre ); - final List> outputs = this.parseLines( post ); - - final ICraftHandler ch = cr.getCraftHandlerFor( operation ); - - if( ch != null ) - { - ch.setup( inputs, outputs ); - this.addCrafting( ch ); - } - else - { - throw new RecipeError( "Invalid crafting type: " + operation ); - } - } - } - else - { - final String operation = this.tokens.remove( 0 ).toLowerCase(); - - if( operation.equals( "exceptions" ) && ( this.tokens.get( 0 ).equals( "true" ) || this.tokens.get( 0 ).equals( "false" ) ) ) - { - 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." ); - } - } +public class RecipeHandler implements IRecipeHandler { + private final RecipeData data; + private final List tokens = new LinkedList(); + + public RecipeHandler() { + this.data = new RecipeData(); + } + + /** + * Called recursively from parent + * + * @param parent owner of this handler + */ + private RecipeHandler(final RecipeHandler parent) { + Preconditions.checkNotNull(parent); + this.data = parent.data; + } + + private void addCrafting(final ICraftHandler ch) { + this.data.handlers.add(ch); + } + + public String getName(@Nonnull final IIngredient i) { + try { + for (final ItemStack is : i.getItemStackSet()) { + return this.getName(is); + } + } catch (final RecipeError ignored) { + } catch (final Throwable t) { + t.printStackTrace(); + // :P + } + + return i.getNameSpace() + ':' + i.getItemName(); + } + + private String getName(final ItemStack is) throws RecipeError { + Preconditions.checkNotNull(is); + + final UniqueIdentifier id = GameRegistry.findUniqueIdentifierFor(is.getItem()); + String realName = id.modId + ':' + id.name; + + if (!id.modId.equals(AppEng.MOD_ID) && !id.modId.equals("minecraft")) { + throw new RecipeError("Not applicable for website"); + } + + final IDefinitions definitions = AEApi.instance().definitions(); + final IItems items = definitions.items(); + final IBlocks blocks = definitions.blocks(); + + final Optional maybeCrystalSeedItem = items.crystalSeed().maybeItem(); + final Optional maybeSkyStoneItem = blocks.skyStone().maybeItem(); + final Optional maybeCStorageItem = blocks.craftingStorage1k().maybeItem(); + final Optional maybeCUnitItem = blocks.craftingUnit().maybeItem(); + final Optional maybeSkyChestItem = blocks.skyChest().maybeItem(); + + if (maybeCrystalSeedItem.isPresent() + && is.getItem() == maybeCrystalSeedItem.get()) { + final int dmg = is.getItemDamage(); + if (dmg < ItemCrystalSeed.NETHER) { + realName += ".Certus"; + } else if (dmg < ItemCrystalSeed.FLUIX) { + realName += ".Nether"; + } else if (dmg < ItemCrystalSeed.FINAL_STAGE) { + realName += ".Fluix"; + } + } else if (maybeSkyStoneItem.isPresent() && is.getItem() == maybeSkyStoneItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName += ".Block"; + break; + case 2: + realName += ".Brick"; + break; + case 3: + realName += ".SmallBrick"; + break; + default: + } + } else if (maybeCStorageItem.isPresent() && is.getItem() == maybeCStorageItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName += "4k"; + break; + case 2: + realName += "16k"; + break; + case 3: + realName += "64k"; + break; + default: + } + } else if (maybeCUnitItem.isPresent() && is.getItem() == maybeCUnitItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName = realName.replace("Unit", "Accelerator"); + break; + default: + } + } else if (maybeSkyChestItem.isPresent() && is.getItem() == maybeSkyChestItem.get()) { + switch (is.getItemDamage()) { + case 1: + realName += ".Block"; + break; + default: + } + } else if (is.getItem() instanceof ItemMultiMaterial) { + realName = realName.replace("ItemMultiMaterial", "ItemMaterial"); + realName + += '.' + ((ItemMultiMaterial) is.getItem()).getTypeByStack(is).name(); + } else if (is.getItem() instanceof ItemMultiPart) { + realName = realName.replace("ItemMultiPart", "ItemPart"); + realName += '.' + ((ItemMultiPart) is.getItem()).getTypeByStack(is).name(); + } else if (is.getItemDamage() > 0) { + realName += "." + is.getItemDamage(); + } + + return realName; + } + + String alias(final String in) { + Preconditions.checkNotNull(in); + + final String out = this.data.aliases.get(in); + + if (out != null) { + return out; + } + + return in; + } + + @Override + public void parseRecipes(final IRecipeLoader loader, final String path) { + Preconditions.checkNotNull(loader); + Preconditions.checkNotNull(path); + + try { + BufferedReader reader = null; + try { + reader = loader.getFile(path); + } catch (final Exception err) { + AELog.warn("Error Loading Recipe File:" + path); + if (this.data.exceptions) { + AELog.debug(err); + } + return; + } + + boolean inQuote = false; + boolean inComment = false; + + String token = ""; + int line = 0; + + int val = -1; + while ((val = reader.read()) != -1) { + final char c = (char) val; + + if (c == '\n') { + line++; + } + + if (inComment) { + if (c == '\n' || c == '\r') { + inComment = false; + } + } else if (inQuote) { + switch (c) { + case '"': + inQuote = !inQuote; + break; + default: + token += c; + } + } else { + switch (c) { + case '"': + inQuote = !inQuote; + break; + case ',': + + if (token.length() > 0) { + this.tokens.add(token); + this.tokens.add(","); + } + token = ""; + break; + + case '=': + + this.processTokens(loader, path, line); + + if (token.length() > 0) { + this.tokens.add(token); + } + token = ""; + + break; + + case '#': + inComment = true; + // then add a token if you can... + + case '\n': + case '\t': + case '\r': + case ' ': + + if (token.length() > 0) { + this.tokens.add(token); + } + token = ""; + + break; + default: + token += c; + } + } + } + + if (token.length() > 0) { + this.tokens.add(token); + } + + reader.close(); + this.processTokens(loader, path, line); + } catch (final Throwable e) { + AELog.debug(e); + if (this.data.crash) { + throw new IllegalStateException(e); + } + } + } + + @Override + public void injectRecipes() { + if (cpw.mods.fml.common.Loader.instance().hasReachedState( + LoaderState.POSTINITIALIZATION + )) { + throw new IllegalStateException("Recipes must now be loaded in Init."); + } + + final Map processed = new HashMap(); + try { + for (final ICraftHandler ch : this.data.handlers) { + try { + ch.register(); + + final Class clz = ch.getClass(); + final Integer i = processed.get(clz); + if (i == null) { + processed.put(clz, 1); + } else { + processed.put(clz, i + 1); + } + } catch (final RegistrationError e) { + AELog.warn("Unable to register a recipe: " + e.getMessage()); + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw e; + } + } catch (final MissingIngredientError e) { + if (this.data.errorOnMissing) { + AELog.warn("Unable to register a recipe:" + e.getMessage()); + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw e; + } + } + } + } + } catch (final Throwable e) { + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw new IllegalStateException(e); + } + } + + for (final Entry e : processed.entrySet()) { + AELog.info( + "Recipes Loading: " + e.getKey().getSimpleName() + ": " + e.getValue() + + " loaded." + ); + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.WebsiteRecipes)) { + try { + final ZipOutputStream out + = new ZipOutputStream(new FileOutputStream("recipes.zip")); + + final HashMultimap combined + = HashMultimap.create(); + + for (final String s : this.data.knownItem) { + try { + final IIngredient i = new Ingredient(this, s, 1); + + for (final ItemStack is : i.getItemStackSet()) { + final String realName = this.getName(is); + final List recipes = this.findRecipe(is); + if (!recipes.isEmpty()) { + combined.putAll(realName, recipes); + } + } + } catch (final RecipeError ignored) { + } catch (final MissedIngredientSet ignored) { + } catch (final RegistrationError ignored) { + } catch (final MissingIngredientError ignored) {} + } + + for (final String realName : combined.keySet()) { + int offset = 0; + + for (final IWebsiteSerializer ws : combined.get(realName)) { + final 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 (final FileNotFoundException e1) { + AELog.debug(e1); + } catch (final IOException e1) { + AELog.debug(e1); + } + } + } + + private List findRecipe(final ItemStack output) { + final List out = new LinkedList(); + + for (final ICraftHandler ch : this.data.handlers) { + try { + if (ch instanceof IWebsiteSerializer + && ((IWebsiteSerializer) ch).canCraft(output)) { + out.add((IWebsiteSerializer) ch); + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + + return out; + } + + RecipeData getData() { + return this.data; + } + + private void + processTokens(final IRecipeLoader loader, final String file, final int line) + throws RecipeError { + try { + final IRecipeHandlerRegistry cr = AEApi.instance().registries().recipes(); + + if (this.tokens.isEmpty()) { + return; + } + + final int split = this.tokens.indexOf("->"); + if (split != -1) { + final String operation + = this.tokens.remove(0).toLowerCase(Locale.ENGLISH); + + if (operation.equals("alias")) { + 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")) { + final List pre = this.tokens.subList(0, split - 1); + final List post + = this.tokens.subList(split, this.tokens.size()); + + final List> inputs = this.parseLines(pre); + + 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), 1) + ); + } else { + throw new RecipeError( + "Group must have exactly 1 output, and 1 or more inputs." + ); + } + } else if (operation.equals("ore")) { + final List pre = this.tokens.subList(0, split - 1); + final List post + = this.tokens.subList(split, this.tokens.size()); + + final List> inputs = this.parseLines(pre); + + if (inputs.size() == 1 && inputs.get(0).size() > 0 + && post.size() == 1) { + final ICraftHandler ch + = new OreRegistration(inputs.get(0), post.get(0)); + this.addCrafting(ch); + } else { + throw new RecipeError( + "Group must have exactly 1 output, and 1 or more inputs in a single row." + ); + } + } else { + final List pre = this.tokens.subList(0, split - 1); + final List post + = this.tokens.subList(split, this.tokens.size()); + + final List> inputs = this.parseLines(pre); + final List> outputs = this.parseLines(post); + + final ICraftHandler ch = cr.getCraftHandlerFor(operation); + + if (ch != null) { + ch.setup(inputs, outputs); + this.addCrafting(ch); + } else { + throw new RecipeError("Invalid crafting type: " + operation); + } + } + } else { + final String operation = this.tokens.remove(0).toLowerCase(); + + if (operation.equals("exceptions") + && (this.tokens.get(0).equals("true") + || this.tokens.get(0).equals("false"))) { + 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" ) ) ) { - 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" ) ) - { - 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" ) ) - { - 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( final RecipeError e ) - { - AELog.warn( "Recipe Error '" + e.getMessage() + "' near line:" + line + " in " + file + " with: " + this.tokens.toString() ); - if( this.data.exceptions ) - { - AELog.debug( e ); - } - if( this.data.crash ) - { - throw e; - } - } + 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")) { + 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")) { + 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 (final RecipeError e) { + AELog.warn( + "Recipe Error '" + e.getMessage() + "' near line:" + line + " in " + file + + " with: " + this.tokens.toString() + ); + if (this.data.exceptions) { + AELog.debug(e); + } + if (this.data.crash) { + throw e; + } + } - this.tokens.clear(); - } + this.tokens.clear(); + } - private List> parseLines( final Iterable subList ) throws RecipeError - { - final List> out = new LinkedList>(); - List cList = new LinkedList(); + private List> parseLines(final Iterable subList) + throws RecipeError { + final List> out = new LinkedList>(); + List cList = new LinkedList(); - boolean hasQty = false; - int qty = 1; + boolean hasQty = false; + int qty = 1; - for( final String v : subList ) - { - if( v.equals( "," ) ) - { - if( hasQty ) - { - throw new RecipeError( "Qty found with no item." ); - } - if( !cList.isEmpty() ) - { - out.add( cList ); - } - cList = new LinkedList(); - } - else - { - if( this.isNumber( v ) ) - { - if( hasQty ) - { - throw new RecipeError( "Qty found with no item." ); - } - hasQty = true; - qty = Integer.parseInt( v ); - } - else - { - if( hasQty ) - { - cList.add( this.findIngredient( v, qty ) ); - hasQty = false; - } - else - { - cList.add( this.findIngredient( v, 1 ) ); - } - } - } - } + for (final String v : subList) { + if (v.equals(",")) { + if (hasQty) { + throw new RecipeError("Qty found with no item."); + } + if (!cList.isEmpty()) { + out.add(cList); + } + cList = new LinkedList(); + } else { + if (this.isNumber(v)) { + if (hasQty) { + throw new RecipeError("Qty found with no item."); + } + hasQty = true; + qty = Integer.parseInt(v); + } else { + if (hasQty) { + cList.add(this.findIngredient(v, qty)); + hasQty = false; + } else { + cList.add(this.findIngredient(v, 1)); + } + } + } + } - if( !cList.isEmpty() ) - { - out.add( cList ); - } + if (!cList.isEmpty()) { + out.add(cList); + } - return out; - } + return out; + } - private IIngredient findIngredient( final String v, final int qty ) throws RecipeError - { - final GroupIngredient gi = this.data.groups.get( v ); + private IIngredient findIngredient(final String v, final int qty) throws RecipeError { + final GroupIngredient gi = this.data.groups.get(v); - if( gi != null ) - { - return gi.copy( qty ); - } + if (gi != null) { + return gi.copy(qty); + } - try - { - return new Ingredient( this, v, qty ); - } - catch( final MissedIngredientSet grp ) - { - return new IngredientSet( grp.getResolverResultSet(), qty ); - } - } + try { + return new Ingredient(this, v, qty); + } catch (final MissedIngredientSet grp) { + return new IngredientSet(grp.getResolverResultSet(), qty); + } + } - private boolean isNumber( final CharSequence v ) - { - if( v.length() <= 0 ) - { - return false; - } + private boolean isNumber(final CharSequence v) { + if (v.length() <= 0) { + return false; + } - final int l = v.length(); - for( int x = 0; x < l; x++ ) - { - if( !Character.isDigit( v.charAt( x ) ) ) - { - return false; - } - } + final int l = v.length(); + for (int x = 0; x < l; x++) { + if (!Character.isDigit(v.charAt(x))) { + return false; + } + } - return true; - } + return true; + } } diff --git a/src/main/java/appeng/recipes/game/DisassembleRecipe.java b/src/main/java/appeng/recipes/game/DisassembleRecipe.java index 1f5456f1..8660b71e 100644 --- a/src/main/java/appeng/recipes/game/DisassembleRecipe.java +++ b/src/main/java/appeng/recipes/game/DisassembleRecipe.java @@ -18,6 +18,10 @@ package appeng.recipes.game; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.definitions.*; @@ -32,138 +36,122 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; +public final class DisassembleRecipe implements IRecipe { + private static final ItemStack MISMATCHED_STACK = null; + private final Map cellMappings; + private final Map nonCellMappings; -public final class DisassembleRecipe implements IRecipe -{ - private static final ItemStack MISMATCHED_STACK = null; + public DisassembleRecipe() { + final IDefinitions definitions = AEApi.instance().definitions(); + final IBlocks blocks = definitions.blocks(); + final IItems items = definitions.items(); + final IMaterials mats = definitions.materials(); - private final Map cellMappings; - private final Map nonCellMappings; + this.cellMappings = new HashMap(4); + this.nonCellMappings = new HashMap(5); - public DisassembleRecipe() - { - final IDefinitions definitions = AEApi.instance().definitions(); - final IBlocks blocks = definitions.blocks(); - final IItems items = definitions.items(); - final IMaterials mats = definitions.materials(); + this.cellMappings.put(items.cell1k(), mats.cell1kPart()); + this.cellMappings.put(items.cell4k(), mats.cell4kPart()); + this.cellMappings.put(items.cell16k(), mats.cell16kPart()); + this.cellMappings.put(items.cell64k(), mats.cell64kPart()); - this.cellMappings = new HashMap( 4 ); - this.nonCellMappings = new HashMap( 5 ); + this.nonCellMappings.put(items.encodedPattern(), mats.blankPattern()); + this.nonCellMappings.put(blocks.craftingStorage1k(), mats.cell1kPart()); + this.nonCellMappings.put(blocks.craftingStorage4k(), mats.cell4kPart()); + this.nonCellMappings.put(blocks.craftingStorage16k(), mats.cell16kPart()); + this.nonCellMappings.put(blocks.craftingStorage64k(), mats.cell64kPart()); + } - this.cellMappings.put( items.cell1k(), mats.cell1kPart() ); - this.cellMappings.put( items.cell4k(), mats.cell4kPart() ); - this.cellMappings.put( items.cell16k(), mats.cell16kPart() ); - this.cellMappings.put( items.cell64k(), mats.cell64kPart() ); + @Override + public boolean matches(final InventoryCrafting inv, final World w) { + return this.getOutput(inv) != null; + } - this.nonCellMappings.put( items.encodedPattern(), mats.blankPattern() ); - this.nonCellMappings.put( blocks.craftingStorage1k(), mats.cell1kPart() ); - this.nonCellMappings.put( blocks.craftingStorage4k(), mats.cell4kPart() ); - this.nonCellMappings.put( blocks.craftingStorage16k(), mats.cell16kPart() ); - this.nonCellMappings.put( blocks.craftingStorage64k(), mats.cell64kPart() ); - } + @Nullable + private ItemStack getOutput(final IInventory inventory) { + int itemCount = 0; + ItemStack output = MISMATCHED_STACK; - @Override - public boolean matches( final InventoryCrafting inv, final World w ) - { - return this.getOutput( inv ) != null; - } + for (int slotIndex = 0; slotIndex < inventory.getSizeInventory(); slotIndex++) { + final ItemStack stackInSlot = inventory.getStackInSlot(slotIndex); + if (stackInSlot != null) { + // needs a single input in the recipe + itemCount++; + if (itemCount > 1) { + return MISMATCHED_STACK; + } - @Nullable - private ItemStack getOutput( final IInventory inventory ) - { - int itemCount = 0; - ItemStack output = MISMATCHED_STACK; + // handle storage cells + for (final ItemStack storageCellStack : + this.getCellOutput(stackInSlot).asSet()) { + // make sure the storage cell stackInSlot empty... + final IMEInventory cellInv + = AEApi.instance().registries().cell().getCellInventory( + stackInSlot, null, StorageChannel.ITEMS + ); + if (cellInv != null) { + final IItemList list + = cellInv.getAvailableItems(StorageChannel.ITEMS.createList() + ); + if (!list.isEmpty()) { + return null; + } + } - for( int slotIndex = 0; slotIndex < inventory.getSizeInventory(); slotIndex++ ) - { - final ItemStack stackInSlot = inventory.getStackInSlot( slotIndex ); - if( stackInSlot != null ) - { - // needs a single input in the recipe - itemCount++; - if( itemCount > 1 ) - { - return MISMATCHED_STACK; - } + output = storageCellStack; + } - // handle storage cells - for( final ItemStack storageCellStack : this.getCellOutput( stackInSlot ).asSet() ) - { - // make sure the storage cell stackInSlot empty... - final IMEInventory cellInv = AEApi.instance().registries().cell().getCellInventory( stackInSlot, null, StorageChannel.ITEMS ); - if( cellInv != null ) - { - final IItemList list = cellInv.getAvailableItems( StorageChannel.ITEMS.createList() ); - if( !list.isEmpty() ) - { - return null; - } - } + // handle crafting storage blocks + for (final ItemStack craftingStorageStack : + this.getNonCellOutput(stackInSlot).asSet()) { + output = craftingStorageStack; + } + } + } - output = storageCellStack; - } + return output; + } - // handle crafting storage blocks - for( final ItemStack craftingStorageStack : this.getNonCellOutput( stackInSlot ).asSet() ) - { - output = craftingStorageStack; - } - } - } + @Nonnull + private Optional getCellOutput(final ItemStack compared) { + for (final Map.Entry entry : + this.cellMappings.entrySet()) { + if (entry.getKey().isSameAs(compared)) { + return entry.getValue().maybeStack(1); + } + } - return output; - } + return Optional.absent(); + } - @Nonnull - private Optional getCellOutput( final ItemStack compared ) - { - for( final Map.Entry entry : this.cellMappings.entrySet() ) - { - if( entry.getKey().isSameAs( compared ) ) - { - return entry.getValue().maybeStack( 1 ); - } - } + @Nonnull + private Optional getNonCellOutput(final ItemStack compared) { + for (final Map.Entry entry : + this.nonCellMappings.entrySet()) { + if (entry.getKey().isSameAs(compared)) { + return entry.getValue().maybeStack(1); + } + } - return Optional.absent(); - } + return Optional.absent(); + } - @Nonnull - private Optional getNonCellOutput( final ItemStack compared ) - { - for( final Map.Entry entry : this.nonCellMappings.entrySet() ) - { - if( entry.getKey().isSameAs( compared ) ) - { - return entry.getValue().maybeStack( 1 ); - } - } + @Nullable + @Override + public ItemStack getCraftingResult(final InventoryCrafting inv) { + return this.getOutput(inv); + } - return Optional.absent(); - } + @Override + public int getRecipeSize() { + return 1; + } - @Nullable - @Override - public ItemStack getCraftingResult( final InventoryCrafting inv ) - { - return this.getOutput( inv ); - } - - @Override - public int getRecipeSize() - { - return 1; - } - - @Nullable - @Override - public ItemStack getRecipeOutput() // no default output.. - { - return null; - } + @Nullable + @Override + public ItemStack getRecipeOutput() // no default output.. + { + return null; + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/game/FacadeRecipe.java b/src/main/java/appeng/recipes/game/FacadeRecipe.java index 63698f76..91d3ce3c 100644 --- a/src/main/java/appeng/recipes/game/FacadeRecipe.java +++ b/src/main/java/appeng/recipes/game/FacadeRecipe.java @@ -18,6 +18,7 @@ package appeng.recipes.game; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.definitions.IComparableDefinition; @@ -31,67 +32,60 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; -import javax.annotation.Nullable; +public final class FacadeRecipe implements IRecipe { + private final IComparableDefinition anchor; + private final Optional maybeFacade; + public FacadeRecipe() { + final IDefinitions definitions = AEApi.instance().definitions(); -public final class FacadeRecipe implements IRecipe -{ - private final IComparableDefinition anchor; - private final Optional maybeFacade; + this.maybeFacade = definitions.items().facade().maybeItem(); + this.anchor = definitions.parts().cableAnchor(); + } - public FacadeRecipe() - { - final IDefinitions definitions = AEApi.instance().definitions(); + @Override + public boolean matches(final InventoryCrafting inv, final World w) { + return this.getOutput(inv, false) != null; + } - this.maybeFacade = definitions.items().facade().maybeItem(); - this.anchor = definitions.parts().cableAnchor(); - } + @Nullable + private ItemStack getOutput(final IInventory inv, final boolean createFacade) { + 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))) { + for (final Item facadeItemDefinition : this.maybeFacade.asSet()) { + final ItemFacade facade = (ItemFacade) facadeItemDefinition; - @Override - public boolean matches( final InventoryCrafting inv, final World w ) - { - return this.getOutput( inv, false ) != null; - } + final ItemStack facades = facade.createFacadeForItem( + inv.getStackInSlot(4), !createFacade + ); + if (facades != null && createFacade) { + facades.stackSize = 4; + } + return facades; + } + } + } - @Nullable - private ItemStack getOutput( final IInventory inv, final boolean createFacade ) - { - 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 ) ) ) - { - for( final Item facadeItemDefinition : this.maybeFacade.asSet() ) - { - final ItemFacade facade = (ItemFacade) facadeItemDefinition; + return null; + } - final ItemStack facades = facade.createFacadeForItem( inv.getStackInSlot( 4 ), !createFacade ); - if( facades != null && createFacade ) - { - facades.stackSize = 4; - } - return facades; - } - } - } + @Override + public ItemStack getCraftingResult(final InventoryCrafting inv) { + return this.getOutput(inv, true); + } - return null; - } + @Override + public int getRecipeSize() { + return 9; + } - @Override - public ItemStack getCraftingResult( final InventoryCrafting inv ) - { - return this.getOutput( inv, true ); - } - - @Override - public int getRecipeSize() - { - return 9; - } - - @Override - public ItemStack getRecipeOutput() // no default output.. - { - return null; - } + @Override + public ItemStack getRecipeOutput() // no default output.. + { + return null; + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/game/IRecipeBakeable.java b/src/main/java/appeng/recipes/game/IRecipeBakeable.java index f4d9617e..aabeb8a3 100644 --- a/src/main/java/appeng/recipes/game/IRecipeBakeable.java +++ b/src/main/java/appeng/recipes/game/IRecipeBakeable.java @@ -18,11 +18,8 @@ package appeng.recipes.game; - import appeng.api.exceptions.RegistrationError; - -public interface IRecipeBakeable -{ - void bake() throws RegistrationError; +public interface IRecipeBakeable { + void bake() throws RegistrationError; } diff --git a/src/main/java/appeng/recipes/game/ShapedRecipe.java b/src/main/java/appeng/recipes/game/ShapedRecipe.java index 83e0bd8e..e1aed8b1 100644 --- a/src/main/java/appeng/recipes/game/ShapedRecipe.java +++ b/src/main/java/appeng/recipes/game/ShapedRecipe.java @@ -18,6 +18,9 @@ package appeng.recipes.game; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; @@ -28,299 +31,241 @@ import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; +public class ShapedRecipe implements IRecipe, IRecipeBakeable { + // Added in for future ease of change, but hard coded for now. + private static final int MAX_CRAFT_GRID_WIDTH = 3; + private static final int MAX_CRAFT_GRID_HEIGHT = 3; + private ItemStack output = null; + private Object[] input = null; + private int width = 0; + private int height = 0; + private boolean mirrored = true; + private boolean disable = false; -public class ShapedRecipe implements IRecipe, IRecipeBakeable -{ - // Added in for future ease of change, but hard coded for now. - private static final int MAX_CRAFT_GRID_WIDTH = 3; - private static final int MAX_CRAFT_GRID_HEIGHT = 3; + public ShapedRecipe(final ItemStack result, Object... recipe) { + this.output = result.copy(); - private ItemStack output = null; - private Object[] input = null; - private int width = 0; - private int height = 0; - private boolean mirrored = true; - private boolean disable = false; + final StringBuilder shape = new StringBuilder(); + int idx = 0; - public ShapedRecipe( final ItemStack result, Object... recipe ) - { - this.output = result.copy(); + if (recipe[idx] instanceof Boolean) { + this.mirrored = (Boolean) recipe[idx]; + if (recipe[idx + 1] instanceof Object[]) { + recipe = (Object[]) recipe[idx + 1]; + } else { + idx = 1; + } + } - final StringBuilder shape = new StringBuilder(); - int idx = 0; + if (recipe[idx] instanceof String[]) { + final String[] parts = ((String[]) recipe[idx]); + idx++; - if( recipe[idx] instanceof Boolean ) - { - this.mirrored = (Boolean) recipe[idx]; - if( recipe[idx + 1] instanceof Object[] ) - { - recipe = (Object[]) recipe[idx + 1]; - } - else - { - idx = 1; - } - } + for (final String s : parts) { + this.width = s.length(); + shape.append(s); + } - if( recipe[idx] instanceof String[] ) - { - final String[] parts = ( (String[]) recipe[idx] ); - idx++; + this.height = parts.length; + } else { + while (recipe[idx] instanceof String) { + final String s = (String) recipe[idx]; + idx++; + shape.append(s); + this.width = s.length(); + this.height++; + } + } - for( final String s : parts ) - { - this.width = s.length(); - shape.append( s ); - } + if (this.width * this.height != shape.length()) { + final StringBuilder ret = new StringBuilder("Invalid shaped ore recipe: "); + for (final Object tmp : recipe) { + ret.append(tmp).append(", "); + } + ret.append(this.output); + throw new IllegalStateException(ret.toString()); + } - this.height = parts.length; - } - else - { - while( recipe[idx] instanceof String ) - { - final String s = (String) recipe[idx]; - idx++; - shape.append( s ); - this.width = s.length(); - this.height++; - } - } + final Map itemMap = new HashMap(); - if( this.width * this.height != shape.length() ) - { - final StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); - for( final Object tmp : recipe ) - { - ret.append( tmp ).append( ", " ); - } - ret.append( this.output ); - throw new IllegalStateException( ret.toString() ); - } + for (; idx < recipe.length; idx += 2) { + final Character chr = (Character) recipe[idx]; + final Object in = recipe[idx + 1]; - final Map itemMap = new HashMap(); + if (in instanceof IIngredient) { + itemMap.put(chr, (IIngredient) in); + } else { + final StringBuilder ret + = new StringBuilder("Invalid shaped ore recipe: "); + for (final Object tmp : recipe) { + ret.append(tmp).append(", "); + } + ret.append(this.output); + throw new IllegalStateException(ret.toString()); + } + } - for( ; idx < recipe.length; idx += 2 ) - { - final Character chr = (Character) recipe[idx]; - final Object in = recipe[idx + 1]; + this.input = new Object[this.width * this.height]; + int x = 0; + for (final char chr : shape.toString().toCharArray()) { + this.input[x] = itemMap.get(chr); + x++; + } + } - if( in instanceof IIngredient ) - { - itemMap.put( chr, (IIngredient) in ); - } - else - { - final StringBuilder ret = new StringBuilder( "Invalid shaped ore recipe: " ); - for( final Object tmp : recipe ) - { - ret.append( tmp ).append( ", " ); - } - ret.append( this.output ); - throw new IllegalStateException( ret.toString() ); - } - } + public boolean isEnabled() { + return !this.disable; + } - this.input = new Object[this.width * this.height]; - int x = 0; - for( final char chr : shape.toString().toCharArray() ) - { - this.input[x] = itemMap.get( chr ); - x++; - } - } + @Override + public boolean matches(final InventoryCrafting inv, final World world) { + if (this.disable) { + return false; + } - public boolean isEnabled() - { - return !this.disable; - } + 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; + } - @Override - public boolean matches( final InventoryCrafting inv, final World world ) - { - if( this.disable ) - { - return false; - } + if (this.mirrored && this.checkMatch(inv, x, y, true)) { + return true; + } + } + } - 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; - } + return false; + } - if( this.mirrored && this.checkMatch( inv, x, y, true ) ) - { - return true; - } - } - } + @Override + public ItemStack getCraftingResult(final InventoryCrafting var1) { + return this.output.copy(); + } - return false; - } + @Override + public int getRecipeSize() { + return this.input.length; + } - @Override - public ItemStack getCraftingResult( final InventoryCrafting var1 ) - { - return this.output.copy(); - } + @Override + public ItemStack getRecipeOutput() { + return this.output; + } - @Override - public int getRecipeSize() - { - return this.input.length; - } + @SuppressWarnings("unchecked") + private boolean checkMatch( + final InventoryCrafting inv, + final int startX, + final int startY, + final boolean mirror + ) { + if (this.disable) { + return false; + } - @Override - public ItemStack getRecipeOutput() - { - return this.output; - } + for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) { + for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) { + final int subX = x - startX; + final int subY = y - startY; + Object target = null; - @SuppressWarnings( "unchecked" ) - private boolean checkMatch( final InventoryCrafting inv, final int startX, final int startY, final boolean mirror ) - { - if( this.disable ) - { - return false; - } + if (subX >= 0 && subY >= 0 && subX < this.width && subY < this.height) { + if (mirror) { + target = this.input[this.width - subX - 1 + subY * this.width]; + } else { + target = this.input[subX + subY * this.width]; + } + } - for( int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++ ) - { - for( int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++ ) - { - final int subX = x - startX; - final int subY = y - startY; - Object target = null; + final ItemStack slot = inv.getStackInRowAndColumn(x, y); - if( subX >= 0 && subY >= 0 && subX < this.width && subY < this.height ) - { - if( mirror ) - { - target = this.input[this.width - subX - 1 + subY * this.width]; - } - else - { - target = this.input[subX + subY * this.width]; - } - } + if (target instanceof IIngredient) { + boolean matched = false; - final ItemStack slot = inv.getStackInRowAndColumn( x, y ); + try { + for (final ItemStack item : + ((IIngredient) target).getItemStackSet()) { + matched = matched || this.checkItemEquals(item, slot); + } + } catch (final RegistrationError e) { + // :P + } catch (final MissingIngredientError e) { + // :P + } - if( target instanceof IIngredient ) - { - boolean matched = false; + if (!matched) { + return false; + } + } else if (target instanceof ArrayList) { + boolean matched = false; - try - { - for( final ItemStack item : ( (IIngredient) target ).getItemStackSet() ) - { - matched = matched || this.checkItemEquals( item, slot ); - } - } - catch( final RegistrationError e ) - { - // :P - } - catch( final MissingIngredientError e ) - { - // :P - } + for (final ItemStack item : (Iterable) target) { + matched = matched || this.checkItemEquals(item, slot); + } - if( !matched ) - { - return false; - } - } - else if( target instanceof ArrayList ) - { - boolean matched = false; + if (!matched) { + return false; + } + } else if (target == null && slot != null) { + return false; + } + } + } - for( final ItemStack item : (Iterable) target ) - { - matched = matched || this.checkItemEquals( item, slot ); - } + return true; + } - if( !matched ) - { - return false; - } - } - else if( target == null && slot != null ) - { - return false; - } - } - } + private boolean checkItemEquals(final ItemStack target, final ItemStack input) { + 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 true; - } + public ShapedRecipe setMirrored(final boolean mirror) { + this.mirrored = mirror; + return this; + } - private boolean checkItemEquals( final ItemStack target, final ItemStack input ) - { - 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() ) ); - } + /** + * Returns the input for this recipe, any mod accessing this value should never + * manipulate the values in this array as it will effect the recipe itself. + * + * @return The recipes input vales. + */ + public Object[] getInput() { + return this.input; + } - public ShapedRecipe setMirrored( final boolean mirror ) - { - this.mirrored = mirror; - return this; - } + public int getWidth() { + return this.width; + } - /** - * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array - * as it will effect the recipe itself. - * - * @return The recipes input vales. - */ - public Object[] getInput() - { - return this.input; - } + public int getHeight() { + return this.height; + } - public int getWidth() - { - return this.width; - } + public Object[] getIngredients() { + return this.input; + } - public int getHeight() - { - return this.height; - } - - public Object[] getIngredients() - { - return this.input; - } - - @Override - public void bake() throws RegistrationError - { - try - { - this.disable = false; - for( final Object o : this.input ) - { - if( o instanceof IIngredient ) - { - ( (IIngredient) o ).bake(); - } - } - } - catch( final MissingIngredientError err ) - { - this.disable = true; - } - } + @Override + public void bake() throws RegistrationError { + try { + this.disable = false; + for (final Object o : this.input) { + if (o instanceof IIngredient) { + ((IIngredient) o).bake(); + } + } + } catch (final 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 43b0165d..12d3e16a 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; @@ -28,154 +29,123 @@ import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; +public class ShapelessRecipe implements IRecipe, IRecipeBakeable { + private final ArrayList input = new ArrayList(); + private ItemStack output = null; + private boolean disable = false; + public ShapelessRecipe(final ItemStack result, final Object... recipe) { + this.output = result.copy(); + for (final Object in : recipe) { + if (in instanceof IIngredient) { + this.input.add(in); + } else { + final StringBuilder ret + = new StringBuilder("Invalid shapeless ore recipe: "); + for (final Object tmp : recipe) { + ret.append(tmp).append(", "); + } + ret.append(this.output); + throw new IllegalArgumentException(ret.toString()); + } + } + } -public class ShapelessRecipe implements IRecipe, IRecipeBakeable -{ + public boolean isEnabled() { + return !this.disable; + } - private final ArrayList input = new ArrayList(); - private ItemStack output = null; - private boolean disable = false; + @SuppressWarnings("unchecked") + @Override + public boolean matches(final InventoryCrafting var1, final World world) { + if (this.disable) { + return false; + } - public ShapelessRecipe( final ItemStack result, final Object... recipe ) - { - this.output = result.copy(); - for( final Object in : recipe ) - { - if( in instanceof IIngredient ) - { - this.input.add( in ); - } - else - { - final StringBuilder ret = new StringBuilder( "Invalid shapeless ore recipe: " ); - for( final Object tmp : recipe ) - { - ret.append( tmp ).append( ", " ); - } - ret.append( this.output ); - throw new IllegalArgumentException( ret.toString() ); - } - } - } + final ArrayList required = new ArrayList(this.input); - public boolean isEnabled() - { - return !this.disable; - } + for (int x = 0; x < var1.getSizeInventory(); x++) { + final ItemStack slot = var1.getStackInSlot(x); - @SuppressWarnings( "unchecked" ) - @Override - public boolean matches( final InventoryCrafting var1, final World world ) - { - if( this.disable ) - { - return false; - } + if (slot != null) { + boolean inRecipe = false; - final ArrayList required = new ArrayList( this.input ); + for (final Object next : required) { + boolean match = false; - for( int x = 0; x < var1.getSizeInventory(); x++ ) - { - final ItemStack slot = var1.getStackInSlot( x ); + if (next instanceof IIngredient) { + try { + for (final ItemStack item : + ((IIngredient) next).getItemStackSet()) { + match = match || this.checkItemEquals(item, slot); + } + } catch (final RegistrationError e) { + // :P + } catch (final MissingIngredientError e) { + // :P + } + } - if( slot != null ) - { - boolean inRecipe = false; + if (match) { + inRecipe = true; + required.remove(next); + break; + } + } - for( final Object next : required ) - { - boolean match = false; + if (!inRecipe) { + return false; + } + } + } - if( next instanceof IIngredient ) - { - try - { - for( final ItemStack item : ( (IIngredient) next ).getItemStackSet() ) - { - match = match || this.checkItemEquals( item, slot ); - } - } - catch( final RegistrationError e ) - { - // :P - } - catch( final MissingIngredientError e ) - { - // :P - } - } + return required.isEmpty(); + } - if( match ) - { - inRecipe = true; - required.remove( next ); - break; - } - } + @Override + public ItemStack getCraftingResult(final InventoryCrafting var1) { + return this.output.copy(); + } - if( !inRecipe ) - { - return false; - } - } - } + @Override + public int getRecipeSize() { + return this.input.size(); + } - return required.isEmpty(); - } + @Override + public ItemStack getRecipeOutput() { + return this.output; + } - @Override - public ItemStack getCraftingResult( final InventoryCrafting var1 ) - { - return this.output.copy(); - } + private boolean checkItemEquals(final ItemStack target, final ItemStack input) { + return ( + target.getItem() == input.getItem() + && (target.getItemDamage() == OreDictionary.WILDCARD_VALUE + || target.getItemDamage() == input.getItemDamage()) + ); + } - @Override - public int getRecipeSize() - { - return this.input.size(); - } + /** + * Returns the input for this recipe, any mod accessing this value should never + * manipulate the values in this array as it will effect the recipe itself. + * + * @return The recipes input vales. + */ + public ArrayList getInput() { + return this.input; + } - @Override - public ItemStack getRecipeOutput() - { - return this.output; - } - - private boolean checkItemEquals( final ItemStack target, final ItemStack input ) - { - return ( target.getItem() == input.getItem() && ( target.getItemDamage() == OreDictionary.WILDCARD_VALUE || target.getItemDamage() == input.getItemDamage() ) ); - } - - /** - * Returns the input for this recipe, any mod accessing this value should never manipulate the values in this array - * as it will effect the recipe itself. - * - * @return The recipes input vales. - */ - public ArrayList getInput() - { - return this.input; - } - - @Override - public void bake() throws RegistrationError - { - try - { - this.disable = false; - for( final Object o : this.input ) - { - if( o instanceof IIngredient ) - { - ( (IIngredient) o ).bake(); - } - } - } - catch( final MissingIngredientError e ) - { - this.disable = true; - } - } + @Override + public void bake() throws RegistrationError { + try { + this.disable = false; + for (final Object o : this.input) { + if (o instanceof IIngredient) { + ((IIngredient) o).bake(); + } + } + } catch (final MissingIngredientError e) { + this.disable = true; + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/recipes/handlers/Crusher.java b/src/main/java/appeng/recipes/handlers/Crusher.java index 24f532e2..1dfb030e 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -32,60 +33,48 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import net.minecraft.item.ItemStack; -import java.util.List; +public class Crusher implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } + throw new RecipeError("Crusher must have a single input, and single output."); + } -public class Crusher implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.RC)) { + final IRC rc + = (IRC) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.RC); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + rc.rockCrusher(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("RC not happy - " + err.getMessage()); + } + } + } + } - private IIngredient pro_input; - private IIngredient[] pro_output; + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } - throw new RecipeError( "Crusher must have a single input, and single output." ); - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.RC ) ) - { - final IRC rc = (IRC) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.RC ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - rc.rockCrusher( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "RC not happy - " + err.getMessage() ); - } - } - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 d707310c..fdca2b69 100644 --- a/src/main/java/appeng/recipes/handlers/Grind.java +++ b/src/main/java/appeng/recipes/handlers/Grind.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; +import java.util.List; import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; @@ -29,51 +30,43 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import net.minecraft.item.ItemStack; -import java.util.List; +public class Grind implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } -public class Grind implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + for (final ItemStack is : this.pro_input.getItemStackSet()) { + AEApi.instance().registries().grinder().addRecipe( + is, this.pro_output[0].getItemStack(), 8 + ); + } + } - private IIngredient pro_input; - private IIngredient[] pro_output; + @Override + public String getPattern(final RecipeHandler h) { + return "grind\n" + h.getName(this.pro_input) + '\n' + + h.getName(this.pro_output[0]); + } - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - AEApi.instance().registries().grinder().addRecipe( is, this.pro_output[0].getItemStack(), 8 ); - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return "grind\n" + - h.getName( this.pro_input ) + '\n' + - h.getName( this.pro_output[0] ); - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 571474a1..cffa6bf8 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -32,60 +33,48 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import net.minecraft.item.ItemStack; -import java.util.List; +public class GrindFZ implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } -public class GrindFZ implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.FZ)) { + final IFZ fz + = (IFZ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.FZ); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + fz.grinderRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("FZ not happy - " + err.getMessage()); + } + } + } + } - private IIngredient pro_input; - private IIngredient[] pro_output; + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.FZ ) ) - { - final IFZ fz = (IFZ) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.FZ ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - fz.grinderRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "FZ not happy - " + err.getMessage() ); - } - } - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 c4bc9766..d165890d 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -31,70 +32,60 @@ import cpw.mods.fml.common.event.FMLInterModComms; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; +public class HCCrusher implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } + throw new RecipeError("Crusher must have a single input, and single output."); + } -public class HCCrusher implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + for (final ItemStack beginStack : this.pro_input.getItemStackSet()) { + try { + final NBTTagCompound toRegister = new NBTTagCompound(); - private IIngredient pro_input; - private IIngredient[] pro_output; + final ItemStack endStack = this.pro_output[0].getItemStack(); - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } - throw new RecipeError( "Crusher must have a single input, and single output." ); - } + final NBTTagCompound itemFrom = new NBTTagCompound(); + final NBTTagCompound itemTo = new NBTTagCompound(); - @Override - public void register() throws RegistrationError, MissingIngredientError - { - for( final ItemStack beginStack : this.pro_input.getItemStackSet() ) - { - try - { - final NBTTagCompound toRegister = new NBTTagCompound(); + beginStack.writeToNBT(itemFrom); + endStack.writeToNBT(itemTo); - final ItemStack endStack = this.pro_output[0].getItemStack(); + toRegister.setTag("itemFrom", itemFrom); + toRegister.setTag("itemTo", itemTo); + toRegister.setFloat("pressureRatio", 1.0F); - final NBTTagCompound itemFrom = new NBTTagCompound(); - final NBTTagCompound itemTo = new NBTTagCompound(); + FMLInterModComms.sendMessage( + "HydCraft", "registerCrushingRecipe", toRegister + ); + } catch (final java.lang.RuntimeException err) { + AELog.info("Hydraulicraft not happy - " + err.getMessage()); + } + } + } - beginStack.writeToNBT( itemFrom ); - endStack.writeToNBT( itemTo ); + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - toRegister.setTag( "itemFrom", itemFrom ); - toRegister.setTag( "itemTo", itemTo ); - toRegister.setFloat( "pressureRatio", 1.0F ); - - FMLInterModComms.sendMessage( "HydCraft", "registerCrushingRecipe", toRegister ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "Hydraulicraft not happy - " + err.getMessage() ); - } - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 8006f287..d0055f48 100644 --- a/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java +++ b/src/main/java/appeng/recipes/handlers/IWebsiteSerializer.java @@ -18,17 +18,13 @@ package appeng.recipes.handlers; - import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RegistrationError; import appeng.recipes.RecipeHandler; import net.minecraft.item.ItemStack; +public interface IWebsiteSerializer { + String getPattern(RecipeHandler han); -public interface IWebsiteSerializer -{ - - String getPattern( RecipeHandler han ); - - boolean canCraft( ItemStack output ) throws RegistrationError, MissingIngredientError; + 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 479548a6..d59d1508 100644 --- a/src/main/java/appeng/recipes/handlers/Inscribe.java +++ b/src/main/java/appeng/recipes/handlers/Inscribe.java @@ -18,6 +18,9 @@ package appeng.recipes.handlers; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; @@ -27,11 +30,6 @@ import appeng.api.features.InscriberProcessType; import appeng.core.features.registries.entries.InscriberRecipe; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - /** * recipe translation for inscribe process * @@ -40,30 +38,31 @@ import java.util.List; * @version rv2 * @since rv0 */ -public final class Inscribe extends InscriberProcess -{ - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( this.getImprintable() == null ) - { - return; - } - if( this.getOutput() == null ) - { - return; - } +public final class Inscribe extends InscriberProcess { + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (this.getImprintable() == null) { + return; + } + if (this.getOutput() == null) { + return; + } - final ItemStack[] realInput = this.getImprintable().getItemStackSet(); - final List inputs = new ArrayList( realInput.length ); - Collections.addAll( inputs, realInput ); - final ItemStack top = ( this.getTopOptional() == null ) ? null : this.getTopOptional().getItemStack(); - final ItemStack bot = ( this.getBotOptional() == null ) ? null : this.getBotOptional().getItemStack(); - final ItemStack output = this.getOutput().getItemStack(); - final InscriberProcessType type = InscriberProcessType.Inscribe; + final ItemStack[] realInput = this.getImprintable().getItemStackSet(); + final List inputs = new ArrayList(realInput.length); + Collections.addAll(inputs, realInput); + final ItemStack top = (this.getTopOptional() == null) + ? null + : this.getTopOptional().getItemStack(); + final ItemStack bot = (this.getBotOptional() == null) + ? null + : this.getBotOptional().getItemStack(); + final ItemStack output = this.getOutput().getItemStack(); + final InscriberProcessType type = InscriberProcessType.Inscribe; - final IInscriberRecipe recipe = new InscriberRecipe( inputs, output, top, bot, type ); + final IInscriberRecipe recipe + = new InscriberRecipe(inputs, output, top, bot, type); - AEApi.instance().registries().inscriber().addRecipe( recipe ); - } + AEApi.instance().registries().inscriber().addRecipe(recipe); + } } diff --git a/src/main/java/appeng/recipes/handlers/InscriberProcess.java b/src/main/java/appeng/recipes/handlers/InscriberProcess.java index 5c42bc8f..c2d0176c 100644 --- a/src/main/java/appeng/recipes/handlers/InscriberProcess.java +++ b/src/main/java/appeng/recipes/handlers/InscriberProcess.java @@ -1,5 +1,7 @@ package appeng.recipes.handlers; +import java.util.List; +import javax.annotation.Nullable; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -10,10 +12,6 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import net.minecraft.item.ItemStack; -import javax.annotation.Nullable; -import java.util.List; - - /** * basic inscriber process for recipes * @@ -22,105 +20,92 @@ import java.util.List; * @version rv2 * @since rv0 */ -public abstract class InscriberProcess implements ICraftHandler, IWebsiteSerializer -{ - @Nullable - private IIngredient imprintable; +public abstract class InscriberProcess implements ICraftHandler, IWebsiteSerializer { + @Nullable + private IIngredient imprintable; - @Nullable - private IIngredient topOptional; + @Nullable + private IIngredient topOptional; - @Nullable - private IIngredient botOptional; + @Nullable + private IIngredient botOptional; - @Nullable - private IIngredient output; + @Nullable + private IIngredient output; - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( output.size() == 1 && output.get( 0 ).size() == 1 ) - { - if( input.size() == 1 && input.get( 0 ).size() > 1 ) - { - this.imprintable = input.get( 0 ).get( 0 ); + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (output.size() == 1 && output.get(0).size() == 1) { + if (input.size() == 1 && input.get(0).size() > 1) { + this.imprintable = input.get(0).get(0); - this.topOptional = input.get( 0 ).get( 1 ); + this.topOptional = input.get(0).get(1); - if( input.get( 0 ).size() > 2 ) - { - this.botOptional = input.get( 0 ).get( 2 ); - } + if (input.get(0).size() > 2) { + this.botOptional = input.get(0).get(2); + } - this.output = output.get( 0 ).get( 0 ); - } - else - { - throw new RecipeError( "Inscriber recipes cannot have rows, and must have more then one input." ); - } - } - else - { - throw new RecipeError( "Inscriber recipes must produce a single output." ); - } - } + this.output = output.get(0).get(0); + } else { + throw new RecipeError( + "Inscriber recipes cannot have rows, and must have more then one input." + ); + } + } else { + throw new RecipeError("Inscriber recipes must produce a single output."); + } + } - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - return this.output != null && Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } + @Override + public boolean canCraft(final ItemStack reqOutput) + throws RegistrationError, MissingIngredientError { + return this.output != null + && Platform.isSameItemPrecise(this.output.getItemStack(), reqOutput); + } - @Override - public String getPattern( final RecipeHandler handler ) - { - String pattern = "inscriber "; + @Override + public String getPattern(final RecipeHandler handler) { + String pattern = "inscriber "; - if( this.output != null ) - { - pattern += this.output.getQty() + '\n'; - pattern += handler.getName( this.output ) + '\n'; - } + if (this.output != null) { + pattern += this.output.getQty() + '\n'; + pattern += handler.getName(this.output) + '\n'; + } - if( this.topOptional != null ) - { - pattern += handler.getName( this.topOptional ) + '\n'; - } + if (this.topOptional != null) { + pattern += handler.getName(this.topOptional) + '\n'; + } - if( this.imprintable != null ) - { - pattern += handler.getName( this.imprintable ); - } + if (this.imprintable != null) { + pattern += handler.getName(this.imprintable); + } - if( this.botOptional != null ) - { - pattern += '\n' + handler.getName( this.botOptional ); - } + if (this.botOptional != null) { + pattern += '\n' + handler.getName(this.botOptional); + } - return pattern; - } + return pattern; + } - @Nullable - protected IIngredient getImprintable() - { - return this.imprintable; - } + @Nullable + protected IIngredient getImprintable() { + return this.imprintable; + } - @Nullable - protected IIngredient getTopOptional() - { - return this.topOptional; - } + @Nullable + protected IIngredient getTopOptional() { + return this.topOptional; + } - @Nullable - protected IIngredient getBotOptional() - { - return this.botOptional; - } + @Nullable + protected IIngredient getBotOptional() { + return this.botOptional; + } - @Nullable - protected IIngredient getOutput() - { - return this.output; - } + @Nullable + protected IIngredient getOutput() { + return this.output; + } } diff --git a/src/main/java/appeng/recipes/handlers/Macerator.java b/src/main/java/appeng/recipes/handlers/Macerator.java index 32cc61fc..88b7282e 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -32,60 +33,48 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import net.minecraft.item.ItemStack; -import java.util.List; +public class Macerator implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } -public class Macerator implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.IC2)) { + final IIC2 ic2 + = (IIC2) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.IC2); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + ic2.maceratorRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("IC2 not happy - " + err.getMessage()); + } + } + } + } - private IIngredient pro_input; - private IIngredient[] pro_output; + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - final IIC2 ic2 = (IIC2) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.IC2 ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - ic2.maceratorRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "IC2 not happy - " + err.getMessage() ); - } - } - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 4245defb..a2d84289 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -32,61 +33,49 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import net.minecraft.item.ItemStack; -import java.util.List; +public class MekCrusher implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } -public class MekCrusher implements ICraftHandler, IWebsiteSerializer -{ + throw new RecipeError("MekCrusher must have a single input, and single output."); + } - private IIngredient pro_input; - private IIngredient[] pro_output; + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.Mekanism)) { + final IMekanism rc = (IMekanism + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.Mekanism); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + rc.addCrusherRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("Mekanism not happy - " + err.getMessage()); + } + } + } + } - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - throw new RecipeError( "MekCrusher must have a single input, and single output." ); - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.Mekanism ) ) - { - final IMekanism rc = (IMekanism) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.Mekanism ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - rc.addCrusherRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "Mekanism not happy - " + err.getMessage() ); - } - } - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 a11c78cc..fadac5ae 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -32,60 +33,48 @@ import appeng.recipes.RecipeHandler; import appeng.util.Platform; import net.minecraft.item.ItemStack; -import java.util.List; +public class MekEnrichment implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } + throw new RecipeError("MekCrusher must have a single input, and single output."); + } -public class MekEnrichment implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.Mekanism)) { + final IMekanism rc = (IMekanism + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.Mekanism); + for (final ItemStack is : this.pro_input.getItemStackSet()) { + try { + rc.addEnrichmentChamberRecipe(is, this.pro_output[0].getItemStack()); + } catch (final java.lang.RuntimeException err) { + AELog.info("Mekanism not happy - " + err.getMessage()); + } + } + } + } - private IIngredient pro_input; - private IIngredient[] pro_output; + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } - throw new RecipeError( "MekCrusher must have a single input, and single output." ); - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.Mekanism ) ) - { - final IMekanism rc = (IMekanism) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.Mekanism ); - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - try - { - rc.addEnrichmentChamberRecipe( is, this.pro_output[0].getItemStack() ); - } - catch( final java.lang.RuntimeException err ) - { - AELog.info( "Mekanism not happy - " + err.getMessage() ); - } - } - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 4ff5f0d1..dbadae4e 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -27,36 +28,26 @@ import appeng.api.recipes.IIngredient; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.List; +public class OreRegistration implements ICraftHandler { + private final List inputs; + private final String name; + public OreRegistration(final List in, final String out) { + this.inputs = in; + this.name = out; + } -public class OreRegistration implements ICraftHandler -{ + @Override + public void + setup(final List> input, final List> output) + throws RecipeError {} - private final List inputs; - private final String name; - - public OreRegistration( final List in, final String out ) - { - this.inputs = in; - this.name = out; - } - - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - - } - - @Override - public void register() throws RegistrationError, MissingIngredientError - { - for( final IIngredient i : this.inputs ) - { - for( final ItemStack is : i.getItemStackSet() ) - { - OreDictionary.registerOre( this.name, is ); - } - } - } + @Override + public void register() throws RegistrationError, MissingIngredientError { + for (final IIngredient i : this.inputs) { + for (final ItemStack is : i.getItemStackSet()) { + OreDictionary.registerOre(this.name, is); + } + } + } } diff --git a/src/main/java/appeng/recipes/handlers/Press.java b/src/main/java/appeng/recipes/handlers/Press.java index 5ce4059f..ec68163b 100644 --- a/src/main/java/appeng/recipes/handlers/Press.java +++ b/src/main/java/appeng/recipes/handlers/Press.java @@ -18,6 +18,9 @@ package appeng.recipes.handlers; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import appeng.api.AEApi; import appeng.api.exceptions.MissingIngredientError; @@ -27,11 +30,6 @@ import appeng.api.features.InscriberProcessType; import appeng.core.features.registries.entries.InscriberRecipe; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - /** * recipe translation for pressing in the inscriber * @@ -40,30 +38,31 @@ import java.util.List; * @version rv2 * @since rv0 */ -public final class Press extends InscriberProcess -{ - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( this.getImprintable() == null ) - { - return; - } - if( this.getOutput() == null ) - { - return; - } +public final class Press extends InscriberProcess { + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (this.getImprintable() == null) { + return; + } + if (this.getOutput() == null) { + return; + } - final ItemStack[] realInput = this.getImprintable().getItemStackSet(); - final List inputs = new ArrayList( realInput.length ); - Collections.addAll( inputs, realInput ); - final ItemStack top = ( this.getTopOptional() == null ) ? null : this.getTopOptional().getItemStack(); - final ItemStack bot = ( this.getBotOptional() == null ) ? null : this.getBotOptional().getItemStack(); - final ItemStack output = this.getOutput().getItemStack(); - final InscriberProcessType type = InscriberProcessType.Press; + final ItemStack[] realInput = this.getImprintable().getItemStackSet(); + final List inputs = new ArrayList(realInput.length); + Collections.addAll(inputs, realInput); + final ItemStack top = (this.getTopOptional() == null) + ? null + : this.getTopOptional().getItemStack(); + final ItemStack bot = (this.getBotOptional() == null) + ? null + : this.getBotOptional().getItemStack(); + final ItemStack output = this.getOutput().getItemStack(); + final InscriberProcessType type = InscriberProcessType.Press; - final IInscriberRecipe recipe = new InscriberRecipe( inputs, output, top, bot, type ); + final IInscriberRecipe recipe + = new InscriberRecipe(inputs, output, top, bot, type); - AEApi.instance().registries().inscriber().addRecipe( recipe ); - } + AEApi.instance().registries().inscriber().addRecipe(recipe); + } } diff --git a/src/main/java/appeng/recipes/handlers/Pulverizer.java b/src/main/java/appeng/recipes/handlers/Pulverizer.java index 7a024b19..ea289ec0 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 appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -30,57 +31,49 @@ import cpw.mods.fml.common.event.FMLInterModComms; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.List; +public class Pulverizer implements ICraftHandler, IWebsiteSerializer { + private IIngredient pro_input; + private IIngredient[] pro_output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final int outs = output.get(0).size(); + 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]); + return; + } + } + throw new RecipeError("Grind must have a single input, and single output."); + } -public class Pulverizer implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + final NBTTagCompound toSend = new NBTTagCompound(); + toSend.setInteger("energy", 800); + toSend.setTag("primaryOutput", new NBTTagCompound()); - private IIngredient pro_input; - private IIngredient[] pro_output; + this.pro_output[0].getItemStack().writeToNBT(toSend.getCompoundTag("primaryOutput" + )); - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final int outs = output.get( 0 ).size(); - 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] ); - return; - } - } - throw new RecipeError( "Grind must have a single input, and single output." ); - } + for (final ItemStack is : this.pro_input.getItemStackSet()) { + toSend.setTag("input", new NBTTagCompound()); + is.writeToNBT(toSend.getCompoundTag("input")); + FMLInterModComms.sendMessage("ThermalExpansion", "PulverizerRecipe", toSend); + } + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - final NBTTagCompound toSend = new NBTTagCompound(); - toSend.setInteger( "energy", 800 ); - toSend.setTag( "primaryOutput", new NBTTagCompound() ); + @Override + public String getPattern(final RecipeHandler h) { + return null; + } - this.pro_output[0].getItemStack().writeToNBT( toSend.getCompoundTag( "primaryOutput" ) ); - - for( final ItemStack is : this.pro_input.getItemStackSet() ) - { - toSend.setTag( "input", new NBTTagCompound() ); - is.writeToNBT( toSend.getCompoundTag( "input" ) ); - FMLInterModComms.sendMessage( "ThermalExpansion", "PulverizerRecipe", toSend ); - } - } - - @Override - public String getPattern( final RecipeHandler h ) - { - return null; - } - - @Override - public boolean canCraft( final ItemStack output ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.pro_output[0].getItemStack(), output ); - } + @Override + public boolean canCraft(final 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 fef54c1d..d2593097 100644 --- a/src/main/java/appeng/recipes/handlers/Shaped.java +++ b/src/main/java/appeng/recipes/handlers/Shaped.java @@ -18,6 +18,8 @@ package appeng.recipes.handlers; +import java.util.ArrayList; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -31,145 +33,114 @@ import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.List; +public class Shaped implements ICraftHandler, IWebsiteSerializer { + private List> inputs; + private IIngredient output; + private int rows; + private int cols; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (output.size() == 1 && output.get(0).size() == 1) { + this.rows = input.size(); + if (this.rows > 0 && input.size() <= 3) { + this.cols = input.get(0).size(); + if (this.cols <= 3 && this.cols >= 1) { + for (final List anInput : input) { + if (anInput.size() != this.cols) { + throw new RecipeError( + "all rows in a shaped crafting recipe must contain the same number of ingredients." + ); + } + } -public class Shaped implements ICraftHandler, IWebsiteSerializer -{ + this.inputs = input; + this.output = output.get(0).get(0); + } else { + throw new RecipeError("Crafting recipes must have 1-3 columns."); + } + } else { + throw new RecipeError("shaped crafting recipes must have 1-3 rows."); + } + } else { + throw new RecipeError("Crafting must produce a single output."); + } + } - private List> inputs; - private IIngredient output; - private int rows; - private int cols; + @Override + public void register() throws RegistrationError, MissingIngredientError { + char first = 'A'; + final List args = new ArrayList(); - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( output.size() == 1 && output.get( 0 ).size() == 1 ) - { - this.rows = input.size(); - if( this.rows > 0 && input.size() <= 3 ) - { - this.cols = input.get( 0 ).size(); - if( this.cols <= 3 && this.cols >= 1 ) - { - for( final List anInput : input ) - { - if( anInput.size() != this.cols ) - { - throw new RecipeError( "all rows in a shaped crafting recipe must contain the same number of ingredients." ); - } - } + for (int y = 0; y < this.rows; y++) { + final StringBuilder row = new StringBuilder(); + for (int x = 0; x < this.cols; x++) { + if (this.inputs.get(y).get(x).isAir()) { + row.append(' '); + } else { + row.append(first); + args.add(first); + args.add(this.inputs.get(y).get(x)); - this.inputs = input; - this.output = output.get( 0 ).get( 0 ); - } - else - { - throw new RecipeError( "Crafting recipes must have 1-3 columns." ); - } - } - else - { - throw new RecipeError( "shaped crafting recipes must have 1-3 rows." ); - } - } - else - { - throw new RecipeError( "Crafting must produce a single output." ); - } - } + first++; + } + } + args.add(y, row.toString()); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - char first = 'A'; - final List args = new ArrayList(); + final ItemStack outIS = this.output.getItemStack(); - for( int y = 0; y < this.rows; y++ ) - { - final StringBuilder row = new StringBuilder(); - for( int x = 0; x < this.cols; x++ ) - { - if( this.inputs.get( y ).get( x ).isAir() ) - { - row.append( ' ' ); - } - else - { - row.append( first ); - args.add( first ); - args.add( this.inputs.get( y ).get( x ) ); + try { + GameRegistry.addRecipe( + new ShapedRecipe(outIS, args.toArray(new Object[args.size()])) + ); + } catch (final Throwable e) { + AELog.debug(e); + throw new RegistrationError("Error while adding shaped recipe."); + } + } - first++; - } - } - args.add( y, row.toString() ); - } + @Override + public String getPattern(final RecipeHandler h) { + String o + = "shaped " + this.output.getQty() + ' ' + this.cols + 'x' + this.rows + '\n'; - final ItemStack outIS = this.output.getItemStack(); + o += h.getName(this.output) + '\n'; - try - { - GameRegistry.addRecipe( new ShapedRecipe( outIS, args.toArray( new Object[args.size()] ) ) ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - throw new RegistrationError( "Error while adding shaped recipe." ); - } - } + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.cols; x++) { + final IIngredient i = this.inputs.get(y).get(x); - @Override - public String getPattern( final RecipeHandler h ) - { - String o = "shaped " + this.output.getQty() + ' ' + this.cols + 'x' + this.rows + '\n'; + if (i.isAir()) { + o += "air" + (x + 1 == this.cols ? "\n" : " "); + } else { + o += h.getName(i) + (x + 1 == this.cols ? "\n" : " "); + } + } + } - o += h.getName( this.output ) + '\n'; + return o.trim(); + } - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.cols; x++ ) - { - final IIngredient i = this.inputs.get( y ).get( x ); + @Override + public boolean canCraft(final ItemStack reqOutput) + throws RegistrationError, MissingIngredientError { + for (int y = 0; y < this.rows; y++) { + for (int x = 0; x < this.cols; x++) { + final 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" : " " ); - } - } - } + if (!i.isAir()) { + for (final ItemStack r : i.getItemStackSet()) { + if (Platform.isSameItemPrecise(r, reqOutput)) { + return false; + } + } + } + } + } - return o.trim(); - } - - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - for( int y = 0; y < this.rows; y++ ) - { - for( int x = 0; x < this.cols; x++ ) - { - final IIngredient i = this.inputs.get( y ).get( x ); - - if( !i.isAir() ) - { - for( final ItemStack r : i.getItemStackSet() ) - { - if( Platform.isSameItemPrecise( r, reqOutput ) ) - { - return false; - } - } - } - } - } - - return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } + return Platform.isSameItemPrecise(this.output.getItemStack(), reqOutput); + } } diff --git a/src/main/java/appeng/recipes/handlers/Shapeless.java b/src/main/java/appeng/recipes/handlers/Shapeless.java index 97ca0495..0168b28c 100644 --- a/src/main/java/appeng/recipes/handlers/Shapeless.java +++ b/src/main/java/appeng/recipes/handlers/Shapeless.java @@ -18,6 +18,8 @@ package appeng.recipes.handlers; +import java.util.ArrayList; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -31,110 +33,84 @@ import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.List; +public class Shapeless implements ICraftHandler, IWebsiteSerializer { + private List inputs; + private IIngredient output; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (output.size() == 1 && output.get(0).size() == 1) { + if (input.size() == 1) { + this.inputs = input.get(0); + this.output = output.get(0).get(0); + } else { + throw new RecipeError("Shapeless crafting recipes cannot have rows."); + } + } else { + throw new RecipeError("Crafting must produce a single output."); + } + } -public class Shapeless implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + final List args = new ArrayList(); + for (final IIngredient i : this.inputs) { + args.add(i); + } - private List inputs; - private IIngredient output; + final ItemStack outIS = this.output.getItemStack(); - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( output.size() == 1 && output.get( 0 ).size() == 1 ) - { - if( input.size() == 1 ) - { - this.inputs = input.get( 0 ); - this.output = output.get( 0 ).get( 0 ); - } - else - { - throw new RecipeError( "Shapeless crafting recipes cannot have rows." ); - } - } - else - { - throw new RecipeError( "Crafting must produce a single output." ); - } - } + try { + GameRegistry.addRecipe( + new ShapelessRecipe(outIS, args.toArray(new Object[args.size()])) + ); + } catch (final Throwable e) { + AELog.debug(e); + throw new RegistrationError("Error while adding shapeless recipe."); + } + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - final List args = new ArrayList(); - for( final IIngredient i : this.inputs ) - { - args.add( i ); - } + @Override + public String getPattern(final RecipeHandler h) { + final StringBuilder o + = new StringBuilder("shapeless " + this.output.getQty() + '\n'); - final ItemStack outIS = this.output.getItemStack(); + o.append(h.getName(this.output)).append('\n'); - try - { - GameRegistry.addRecipe( new ShapelessRecipe( outIS, args.toArray( new Object[args.size()] ) ) ); - } - catch( final Throwable e ) - { - AELog.debug( e ); - throw new RegistrationError( "Error while adding shapeless recipe." ); - } - } + for (int y = 0; y < this.inputs.size(); y++) { + final IIngredient i = this.inputs.get(y); - @Override - public String getPattern( final RecipeHandler h ) - { - final StringBuilder o = new StringBuilder( "shapeless " + this.output.getQty() + '\n' ); + if (i.isAir()) { + o.append("air"); + } else { + o.append(h.getName(i)); + } - o.append( h.getName( this.output ) ).append( '\n' ); + if (y + 1 == this.inputs.size()) { + o.append('\n'); + } else { + o.append(' '); + } + } - for( int y = 0; y < this.inputs.size(); y++ ) - { - final IIngredient i = this.inputs.get( y ); + return o.toString().trim(); + } - if( i.isAir() ) - { - o.append( "air" ); - } - else - { - o.append( h.getName( i ) ); - } + @Override + public boolean canCraft(final ItemStack reqOutput) + throws RegistrationError, MissingIngredientError { + for (final IIngredient i : this.inputs) { + if (!i.isAir()) { + for (final ItemStack r : i.getItemStackSet()) { + if (Platform.isSameItemPrecise(r, reqOutput)) { + return false; + } + } + } + } - if( y + 1 == this.inputs.size() ) - { - o.append( '\n' ); - } - else - { - o.append( ' ' ); - } - } - - return o.toString().trim(); - } - - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - - for( final IIngredient i : this.inputs ) - { - if( !i.isAir() ) - { - for( final ItemStack r : i.getItemStackSet() ) - { - if( Platform.isSameItemPrecise( r, reqOutput ) ) - { - return false; - } - } - } - } - - return Platform.isSameItemPrecise( this.output.getItemStack(), reqOutput ); - } + 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 cd72445e..8538a103 100644 --- a/src/main/java/appeng/recipes/handlers/Smelt.java +++ b/src/main/java/appeng/recipes/handlers/Smelt.java @@ -18,6 +18,7 @@ package appeng.recipes.handlers; +import java.util.List; import appeng.api.exceptions.MissingIngredientError; import appeng.api.exceptions.RecipeError; @@ -29,59 +30,52 @@ import appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.item.ItemStack; -import java.util.List; +public class Smelt implements ICraftHandler, IWebsiteSerializer { + private IIngredient in; + private IIngredient out; + @Override + public void + setup(final List> input, final List> output) + throws RecipeError { + if (input.size() == 1 && output.size() == 1) { + final List inputList = input.get(0); + final List outputList = output.get(0); + if (inputList.size() == 1 && outputList.size() == 1) { + this.in = inputList.get(0); + this.out = outputList.get(0); + return; + } + } + throw new RecipeError("Smelting recipe can only have a single input and output."); + } -public class Smelt implements ICraftHandler, IWebsiteSerializer -{ + @Override + public void register() throws RegistrationError, MissingIngredientError { + if (this.in.getItemStack().getItem() == null) { + throw new RegistrationError( + this.in.toString() + ": Smelting Input is not a valid item." + ); + } - private IIngredient in; - private IIngredient out; + if (this.out.getItemStack().getItem() == null) { + throw new RegistrationError( + this.out.toString() + ": Smelting Output is not a valid item." + ); + } - @Override - public void setup( final List> input, final List> output ) throws RecipeError - { - if( input.size() == 1 && output.size() == 1 ) - { - final List inputList = input.get( 0 ); - final List outputList = output.get( 0 ); - if( inputList.size() == 1 && outputList.size() == 1 ) - { - this.in = inputList.get( 0 ); - this.out = outputList.get( 0 ); - return; - } - } - throw new RecipeError( "Smelting recipe can only have a single input and output." ); - } + GameRegistry.addSmelting(this.in.getItemStack(), this.out.getItemStack(), 0); + } - @Override - public void register() throws RegistrationError, MissingIngredientError - { - if( this.in.getItemStack().getItem() == null ) - { - throw new RegistrationError( this.in.toString() + ": Smelting Input is not a valid item." ); - } + @Override + public String getPattern(final RecipeHandler h) { + return "smelt " + this.out.getQty() + '\n' + h.getName(this.out) + '\n' + + h.getName(this.in); + } - 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 String getPattern( final RecipeHandler h ) - { - return "smelt " + this.out.getQty() + '\n' + - h.getName( this.out ) + '\n' + - h.getName( this.in ); - } - - @Override - public boolean canCraft( final ItemStack reqOutput ) throws RegistrationError, MissingIngredientError - { - return Platform.isSameItemPrecise( this.out.getItemStack(), reqOutput ); - } + @Override + public boolean canCraft(final ItemStack reqOutput) + throws RegistrationError, MissingIngredientError { + return Platform.isSameItemPrecise(this.out.getItemStack(), reqOutput); + } } diff --git a/src/main/java/appeng/recipes/loader/ConfigLoader.java b/src/main/java/appeng/recipes/loader/ConfigLoader.java index 58701e08..4310c6b5 100644 --- a/src/main/java/appeng/recipes/loader/ConfigLoader.java +++ b/src/main/java/appeng/recipes/loader/ConfigLoader.java @@ -18,42 +18,44 @@ package appeng.recipes.loader; - -import appeng.api.recipes.IRecipeLoader; -import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; +import javax.annotation.Nonnull; +import appeng.api.recipes.IRecipeLoader; +import com.google.common.base.Preconditions; /** * Loads the recipes from the config folder */ -public final class ConfigLoader implements IRecipeLoader -{ - private final File generatedRecipesDir; - private final File userRecipesDir; +public final class ConfigLoader implements IRecipeLoader { + private final File generatedRecipesDir; + private final File userRecipesDir; - public ConfigLoader( final File generatedRecipesDir, final File userRecipesDir ) - { - this.generatedRecipesDir = generatedRecipesDir; - this.userRecipesDir = userRecipesDir; - } + public ConfigLoader(final File generatedRecipesDir, final File userRecipesDir) { + this.generatedRecipesDir = generatedRecipesDir; + this.userRecipesDir = userRecipesDir; + } - @Override - public BufferedReader getFile( @Nonnull final String relativeFilePath ) throws Exception - { - Preconditions.checkNotNull( relativeFilePath ); - Preconditions.checkArgument( !relativeFilePath.isEmpty(), "Supplying an empty String will result creating a reader of a folder." ); + @Override + public BufferedReader getFile(@Nonnull final String relativeFilePath) + throws Exception { + Preconditions.checkNotNull(relativeFilePath); + Preconditions.checkArgument( + !relativeFilePath.isEmpty(), + "Supplying an empty String will result creating a reader of a folder." + ); - final File generatedFile = new File( this.generatedRecipesDir, relativeFilePath ); - final File userFile = new File( this.userRecipesDir, relativeFilePath ); + final File generatedFile = new File(this.generatedRecipesDir, relativeFilePath); + final File userFile = new File(this.userRecipesDir, relativeFilePath); - final File toBeLoaded = ( userFile.exists() && userFile.isFile() ) ? userFile : generatedFile; + final File toBeLoaded + = (userFile.exists() && userFile.isFile()) ? userFile : generatedFile; - return new BufferedReader( new InputStreamReader( new FileInputStream( toBeLoaded ), "UTF-8" ) ); - } + return new BufferedReader( + new InputStreamReader(new FileInputStream(toBeLoaded), "UTF-8") + ); + } } diff --git a/src/main/java/appeng/recipes/loader/JarLoader.java b/src/main/java/appeng/recipes/loader/JarLoader.java index cb6b6575..7c8389f6 100644 --- a/src/main/java/appeng/recipes/loader/JarLoader.java +++ b/src/main/java/appeng/recipes/loader/JarLoader.java @@ -18,31 +18,27 @@ package appeng.recipes.loader; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import javax.annotation.Nonnull; import appeng.api.recipes.IRecipeLoader; import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import java.io.BufferedReader; -import java.io.InputStreamReader; +public class JarLoader implements IRecipeLoader { + private final String rootPath; + public JarLoader(final String s) { + this.rootPath = s; + } -public class JarLoader implements IRecipeLoader -{ + @Override + public BufferedReader getFile(@Nonnull final String s) throws Exception { + Preconditions.checkNotNull(s); + Preconditions.checkArgument(!s.isEmpty()); - private final String rootPath; - - public JarLoader( final String s ) - { - this.rootPath = s; - } - - @Override - public BufferedReader getFile( @Nonnull final String s ) throws Exception - { - Preconditions.checkNotNull( s ); - Preconditions.checkArgument( !s.isEmpty() ); - - return new BufferedReader( new InputStreamReader( this.getClass().getResourceAsStream( this.rootPath + s ), "UTF-8" ) ); - } + return new BufferedReader(new InputStreamReader( + this.getClass().getResourceAsStream(this.rootPath + s), "UTF-8" + )); + } } diff --git a/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java b/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java index 39ac1574..d567760e 100644 --- a/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java +++ b/src/main/java/appeng/recipes/loader/RecipeResourceCopier.java @@ -18,11 +18,6 @@ package appeng.recipes.loader; - -import com.google.common.base.Preconditions; -import org.apache.commons.io.FileUtils; - -import javax.annotation.Nonnull; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -37,220 +32,226 @@ import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.annotation.Nonnull; +import com.google.common.base.Preconditions; +import org.apache.commons.io.FileUtils; /** - * copies recipes in jars onto file system includes the readme, needs to be modified if other files needs to be handled + * copies recipes in jars onto file system includes the readme, needs to be modified if + * other files needs to be handled * * @author thatsIch * @version rv3 - 11.05.2015 * @since rv3 11.05.2015 */ -public class RecipeResourceCopier -{ - /** - * Most expected size of recipes found - */ - private static final int INITIAL_RESOURCE_CAPACITY = 20; - private static final Pattern DOT_COMPILE_PATTERN = Pattern.compile( ".", Pattern.LITERAL ); - private static final String FILE_PROTOCOL = "file"; - private static final String CLASS_EXTENSION = ".class"; - private static final String JAR_PROTOCOL = "jar"; - private static final String UTF_8_ENCODING = "UTF-8"; +public class RecipeResourceCopier { + /** + * Most expected size of recipes found + */ + private static final int INITIAL_RESOURCE_CAPACITY = 20; + private static final Pattern DOT_COMPILE_PATTERN + = Pattern.compile(".", Pattern.LITERAL); + private static final String FILE_PROTOCOL = "file"; + private static final String CLASS_EXTENSION = ".class"; + private static final String JAR_PROTOCOL = "jar"; + private static final String UTF_8_ENCODING = "UTF-8"; - /** - * copy source in the jar - */ - private final String root; + /** + * copy source in the jar + */ + private final String root; - /** - * @param root source root folder of the recipes inside the jar. - * @throws NullPointerException if root is null - */ - public RecipeResourceCopier( @Nonnull final String root ) - { - Preconditions.checkNotNull( root ); + /** + * @param root source root folder of the recipes inside the jar. + * @throws NullPointerException if root is null + */ + public RecipeResourceCopier(@Nonnull final String root) { + Preconditions.checkNotNull(root); - this.root = root; - } + this.root = root; + } - /** - * copies recipes found in the root to destination. - * - * @param identifier only copy files which end with the identifier - * @param destination destination folder to which the recipes are copied to - * @throws URISyntaxException {@see #getResourceListing} - * @throws IOException {@see #getResourceListing} and if copying the detected resource to file is not possible - * @throws NullPointerException if either parameter is null - * @throws IllegalArgumentException if destination is not a directory - */ - public void copyTo( @Nonnull final String identifier, @Nonnull final File destination ) throws URISyntaxException, IOException - { - Preconditions.checkNotNull( destination ); - Preconditions.checkArgument( destination.isDirectory() ); + /** + * copies recipes found in the root to destination. + * + * @param identifier only copy files which end with the identifier + * @param destination destination folder to which the recipes are copied to + * @throws URISyntaxException {@see #getResourceListing} + * @throws IOException {@see #getResourceListing} and if copying the + * detected resource to file is not possible + * @throws NullPointerException if either parameter is null + * @throws IllegalArgumentException if destination is not a directory + */ + public void copyTo(@Nonnull final String identifier, @Nonnull final File destination) + throws URISyntaxException, IOException { + Preconditions.checkNotNull(destination); + Preconditions.checkArgument(destination.isDirectory()); - this.copyTo( identifier, destination, this.root ); - } + this.copyTo(identifier, destination, this.root); + } - /** - * @param destination destination folder to which the recipes are copied to - * @param directory the folder to copy. - * @throws URISyntaxException {@see #getResourceListing} - * @throws IOException {@see #getResourceListing} and if copying the detected resource to file is not possible - * @see {RecipeResourceCopier#copyTo(File)} - */ - private void copyTo( @Nonnull final String identifier, @Nonnull final File destination, @Nonnull final String directory ) - throws URISyntaxException, IOException - { - assert identifier != null; - assert destination != null; - assert directory != null; + /** + * @param destination destination folder to which the recipes are copied to + * @param directory the folder to copy. + * @throws URISyntaxException {@see #getResourceListing} + * @throws IOException {@see #getResourceListing} and if copying the detected + * resource to file is not possible + * @see {RecipeResourceCopier#copyTo(File)} + */ + private void copyTo( + @Nonnull final String identifier, + @Nonnull final File destination, + @Nonnull final String directory + ) throws URISyntaxException, IOException { + assert identifier != null; + assert destination != null; + assert directory != null; - final Class copierClass = this.getClass(); - final String[] listing = this.getResourceListing( copierClass, directory ); - for( final String list : listing ) - { - if( list.endsWith( identifier ) ) - { - // generate folder before the file is copied so no empty folders will be generated - FileUtils.forceMkdir( destination ); + final Class copierClass = this.getClass(); + final String[] listing = this.getResourceListing(copierClass, directory); + for (final String list : listing) { + if (list.endsWith(identifier)) { + // generate folder before the file is copied so no empty folders will be + // generated + FileUtils.forceMkdir(destination); - this.copyFile( destination, directory, list ); - } - else if( !list.contains( "." ) ) - { - final File subDirectory = new File( destination, list ); + this.copyFile(destination, directory, list); + } else if (!list.contains(".")) { + final File subDirectory = new File(destination, list); - this.copyTo( identifier, subDirectory, directory + list + "/" ); - } - } - } + this.copyTo(identifier, subDirectory, directory + list + "/"); + } + } + } - /** - * Copies a single file inside a folder to the destination. - * - * @param destination folder to which the file is copied to - * @param directory the directory containing the file - * @param fileName the file to copy - * @throws IOException if copying the file is not possible - */ - private void copyFile( @Nonnull final File destination, @Nonnull final String directory, @Nonnull final String fileName ) throws IOException - { - assert destination != null; - assert directory != null; - assert fileName != null; + /** + * Copies a single file inside a folder to the destination. + * + * @param destination folder to which the file is copied to + * @param directory the directory containing the file + * @param fileName the file to copy + * @throws IOException if copying the file is not possible + */ + private void copyFile( + @Nonnull final File destination, + @Nonnull final String directory, + @Nonnull final String fileName + ) throws IOException { + assert destination != null; + assert directory != null; + assert fileName != null; - final Class copierClass = this.getClass(); - final InputStream inStream = copierClass.getResourceAsStream( '/' + directory + fileName ); - final File outFile = new File( destination, fileName ); + final Class copierClass = this.getClass(); + final InputStream inStream + = copierClass.getResourceAsStream('/' + directory + fileName); + final File outFile = new File(destination, fileName); - if( !outFile.exists() && inStream != null ) - { - FileUtils.copyInputStreamToFile( inStream, outFile ); - inStream.close(); - } - } + if (!outFile.exists() && inStream != null) { + FileUtils.copyInputStreamToFile(inStream, outFile); + inStream.close(); + } + } - /** - * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs. - * - * @param clazz Any java class that lives in the same place as the resources you want. - * @param path Should end with "/", but not start with one. - * @return Just the name of each member item, not the full paths. - * @throws URISyntaxException if it is a file path and the URL can not be converted to URI - * @throws IOException if jar path can not be decoded - * @throws UnsupportedOperationException if it is neither in jar nor in file path - */ - @Nonnull - private String[] getResourceListing( @Nonnull final Class clazz, @Nonnull final String path ) throws URISyntaxException, IOException - { - assert clazz != null; - assert path != null; + /** + * List directory contents for a resource folder. Not recursive. This is basically a + * brute-force implementation. Works for regular files and also JARs. + * + * @param clazz Any java class that lives in the same place as the resources you want. + * @param path Should end with "/", but not start with one. + * @return Just the name of each member item, not the full paths. + * @throws URISyntaxException if it is a file path and the URL can not be + * converted to URI + * @throws IOException if jar path can not be decoded + * @throws UnsupportedOperationException if it is neither in jar nor in file path + */ + @Nonnull + private String[] getResourceListing( + @Nonnull final Class clazz, @Nonnull final String path + ) throws URISyntaxException, IOException { + assert clazz != null; + assert path != null; - final ClassLoader classLoader = clazz.getClassLoader(); - if( classLoader == null ) - { - throw new IllegalStateException( "ClassLoader was not found. It was probably loaded at a inappropriate time" ); - } + final ClassLoader classLoader = clazz.getClassLoader(); + if (classLoader == null) { + throw new IllegalStateException( + "ClassLoader was not found. It was probably loaded at a inappropriate time" + ); + } - URL dirURL = classLoader.getResource( path ); - if( dirURL != null ) - { - final String protocol = dirURL.getProtocol(); - if( protocol.equals( FILE_PROTOCOL ) ) - { - // A file path: easy enough + URL dirURL = classLoader.getResource(path); + if (dirURL != null) { + final String protocol = dirURL.getProtocol(); + if (protocol.equals(FILE_PROTOCOL)) { + // A file path: easy enough - final URI uriOfURL = dirURL.toURI(); - final File fileOfURI = new File( uriOfURL ); - final String[] filesAndDirectoriesOfURI = fileOfURI.list(); + final URI uriOfURL = dirURL.toURI(); + final File fileOfURI = new File(uriOfURL); + final String[] filesAndDirectoriesOfURI = fileOfURI.list(); - if( filesAndDirectoriesOfURI == null ) - { - throw new IllegalStateException( "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured." ); - } - else - { - return filesAndDirectoriesOfURI; - } - } - } + if (filesAndDirectoriesOfURI == null) { + throw new IllegalStateException( + "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured." + ); + } else { + return filesAndDirectoriesOfURI; + } + } + } - if( dirURL == null ) - { - /* - * In case of a jar file, we can't actually find a directory. - * Have to assume the same jar as clazz. - */ - final String className = clazz.getName(); - final Matcher matcher = DOT_COMPILE_PATTERN.matcher( className ); - final String me = matcher.replaceAll( "/" ) + CLASS_EXTENSION; - dirURL = classLoader.getResource( me ); - } + if (dirURL == null) { + /* + * In case of a jar file, we can't actually find a directory. + * Have to assume the same jar as clazz. + */ + final String className = clazz.getName(); + final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className); + final String me = matcher.replaceAll("/") + CLASS_EXTENSION; + dirURL = classLoader.getResource(me); + } - if( dirURL != null ) - { - final String protocol = dirURL.getProtocol(); - if( protocol.equals( JAR_PROTOCOL ) ) - { - /* A JAR path */ - final String dirPath = dirURL.getPath(); - final String jarPath = dirPath.substring( 5, dirPath.indexOf( '!' ) ); // strip out only - // the JAR file - final JarFile jar = new JarFile( URLDecoder.decode( jarPath, UTF_8_ENCODING ) ); - try - { - final Enumeration entries = jar.entries(); // gives ALL entries in jar - final Collection result = new HashSet( INITIAL_RESOURCE_CAPACITY ); // avoid duplicates + if (dirURL != null) { + final String protocol = dirURL.getProtocol(); + if (protocol.equals(JAR_PROTOCOL)) { + /* A JAR path */ + final String dirPath = dirURL.getPath(); + final String jarPath + = dirPath.substring(5, dirPath.indexOf('!')); // strip out only + // the JAR file + final JarFile jar + = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING)); + try { + final Enumeration entries + = jar.entries(); // gives ALL entries in jar + final Collection result + = new HashSet(INITIAL_RESOURCE_CAPACITY + ); // avoid duplicates - // in case it is a - // subdirectory - while( entries.hasMoreElements() ) - { - final JarEntry entry = entries.nextElement(); - final String entryFullName = entry.getName(); - if( entryFullName.startsWith( path ) ) - { // filter according to the path - String entryName = entryFullName.substring( path.length() ); - final int checkSubDir = entryName.indexOf( '/' ); - if( checkSubDir >= 0 ) - { - // if it is a subdirectory, we just return the directory name - entryName = entryName.substring( 0, checkSubDir ); - } - result.add( entryName ); - } - } + // in case it is a + // subdirectory + while (entries.hasMoreElements()) { + final JarEntry entry = entries.nextElement(); + final String entryFullName = entry.getName(); + if (entryFullName.startsWith(path + )) { // filter according to the path + String entryName = entryFullName.substring(path.length()); + final int checkSubDir = entryName.indexOf('/'); + if (checkSubDir >= 0) { + // if it is a subdirectory, we just return the directory + // name + entryName = entryName.substring(0, checkSubDir); + } + result.add(entryName); + } + } - return result.toArray( new String[result.size()] ); - } - finally - { - jar.close(); - } - } - } + return result.toArray(new String[result.size()]); + } finally { + jar.close(); + } + } + } - throw new UnsupportedOperationException( "Cannot list files for URL " + dirURL ); - } + throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); + } } diff --git a/src/main/java/appeng/recipes/ores/IOreListener.java b/src/main/java/appeng/recipes/ores/IOreListener.java index 40488371..a6fe0cfb 100644 --- a/src/main/java/appeng/recipes/ores/IOreListener.java +++ b/src/main/java/appeng/recipes/ores/IOreListener.java @@ -18,19 +18,15 @@ package appeng.recipes.ores; - import net.minecraft.item.ItemStack; - -public interface IOreListener -{ - - /** - * Called with various items registered in the dictionary. - * AppEng.oreDictionary.observe(...) to register them. - * - * @param name name of ore - * @param item item with name - */ - void oreRegistered( String name, ItemStack item ); +public interface IOreListener { + /** + * Called with various items registered in the dictionary. + * AppEng.oreDictionary.observe(...) to register them. + * + * @param name name of ore + * @param item item with name + */ + 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 ebfff01a..2fce47b9 100644 --- a/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java +++ b/src/main/java/appeng/recipes/ores/OreDictionaryHandler.java @@ -18,6 +18,8 @@ package appeng.recipes.ores; +import java.util.ArrayList; +import java.util.List; import appeng.core.AELog; import appeng.recipes.game.IRecipeBakeable; @@ -26,95 +28,73 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraftforge.oredict.OreDictionary; -import java.util.ArrayList; -import java.util.List; +public class OreDictionaryHandler { + public static final OreDictionaryHandler INSTANCE = new OreDictionaryHandler(); + private final List oreListeners = new ArrayList(); -public class OreDictionaryHandler -{ + private boolean enableRebaking = false; - public static final OreDictionaryHandler INSTANCE = new OreDictionaryHandler(); + @SubscribeEvent + public void onOreDictionaryRegister(final OreDictionary.OreRegisterEvent event) { + if (event.Name == null || event.Ore == null) { + return; + } - private final List oreListeners = new ArrayList(); + if (this.shouldCare(event.Name)) { + for (final IOreListener v : this.oreListeners) { + v.oreRegistered(event.Name, event.Ore); + } + } - private boolean enableRebaking = false; + if (this.enableRebaking) { + this.bakeRecipes(); + } + } - @SubscribeEvent - public void onOreDictionaryRegister( final OreDictionary.OreRegisterEvent event ) - { - if( event.Name == null || event.Ore == null ) - { - return; - } + /** + * 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(final String name) { + return true; + } - if( this.shouldCare( event.Name ) ) - { - for( final IOreListener v : this.oreListeners ) - { - v.oreRegistered( event.Name, event.Ore ); - } - } + public void bakeRecipes() { + this.enableRebaking = true; - if( this.enableRebaking ) - { - this.bakeRecipes(); - } - } + for (final Object o : CraftingManager.getInstance().getRecipeList()) { + if (o instanceof IRecipeBakeable) { + try { + ((IRecipeBakeable) o).bake(); + } catch (final Throwable e) { + AELog.debug(e); + } + } + } + } - /** - * 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( final String name ) - { - return true; - } + /** + * Adds a new IOreListener and immediately notifies it of any previous ores, any ores + * added latter will be added at that point. + * + * @param n to be added ore listener + */ + public void observe(final IOreListener n) { + this.oreListeners.add(n); - public void bakeRecipes() - { - this.enableRebaking = true; - - for( final Object o : CraftingManager.getInstance().getRecipeList() ) - { - if( o instanceof IRecipeBakeable ) - { - try - { - ( (IRecipeBakeable) o ).bake(); - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - } - } - } - - /** - * Adds a new IOreListener and immediately notifies it of any previous ores, any ores added latter will be added at - * that point. - * - * @param n to be added ore listener - */ - public void observe( final IOreListener n ) - { - this.oreListeners.add( n ); - - // notify the listener of any ore already in existence. - for( final String name : OreDictionary.getOreNames() ) - { - if( name != null && this.shouldCare( name ) ) - { - for( final ItemStack item : OreDictionary.getOres( name ) ) - { - if( item != null ) - { - n.oreRegistered( name, item ); - } - } - } - } - } + // notify the listener of any ore already in existence. + for (final String name : OreDictionary.getOreNames()) { + if (name != null && this.shouldCare(name)) { + for (final ItemStack item : OreDictionary.getOres(name)) { + if (item != null) { + n.oreRegistered(name, item); + } + } + } + } + } } diff --git a/src/main/java/appeng/server/AECommand.java b/src/main/java/appeng/server/AECommand.java index 1070bdcc..432027fe 100644 --- a/src/main/java/appeng/server/AECommand.java +++ b/src/main/java/appeng/server/AECommand.java @@ -18,102 +18,72 @@ 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; +public final class AECommand extends CommandBase { + private final MinecraftServer srv; -public final class AECommand extends CommandBase -{ - private final MinecraftServer srv; + public AECommand(final MinecraftServer server) { + this.srv = server; + } - public AECommand( final MinecraftServer server ) - { - this.srv = server; - } + @Override + public int getRequiredPermissionLevel() { + return 0; + } - @Override - public int getRequiredPermissionLevel() - { - return 0; - } + /** + * wtf? + */ + @Override + public int compareTo(final Object arg0) { + return 1; + } - /** - * wtf? - */ - @Override - public int compareTo( final Object arg0 ) - { - return 1; - } + @Override + public String getCommandName() { + return "ae2"; + } - @Override - public String getCommandName() - { - return "ae2"; - } + @Override + public String getCommandUsage(final ICommandSender icommandsender) { + return "commands.ae2.usage"; + } - @Override - public String getCommandUsage( final ICommandSender icommandsender ) - { - return "commands.ae2.usage"; - } - - @Override - public void processCommand( final ICommandSender sender, final String[] args ) - { - if( args.length == 0 ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - else if( "help".equals( args[0] ) ) - { - try - { - if( args.length > 1 ) - { - final Commands c = Commands.valueOf( args[1] ); - throw new WrongUsageException( c.command.getHelp( this.srv ) ); - } - } - catch( final WrongUsageException wrong ) - { - throw wrong; - } - catch( final Throwable er ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - } - else if( "list".equals( args[0] ) ) - { - throw new WrongUsageException( Joiner.on( ", " ).join( Commands.values() ) ); - } - else - { - try - { - final Commands c = Commands.valueOf( args[0] ); - if( sender.canCommandSenderUseCommand( c.level, this.getCommandName() ) ) - { - c.command.call( this.srv, args, sender ); - } - else - { - throw new WrongUsageException( "commands.ae2.permissions" ); - } - } - catch( final WrongUsageException wrong ) - { - throw wrong; - } - catch( final Throwable er ) - { - throw new WrongUsageException( "commands.ae2.usage" ); - } - } - } + @Override + public void processCommand(final ICommandSender sender, final String[] args) { + if (args.length == 0) { + throw new WrongUsageException("commands.ae2.usage"); + } else if ("help".equals(args[0])) { + try { + if (args.length > 1) { + final Commands c = Commands.valueOf(args[1]); + throw new WrongUsageException(c.command.getHelp(this.srv)); + } + } catch (final WrongUsageException wrong) { + throw wrong; + } catch (final Throwable er) { + throw new WrongUsageException("commands.ae2.usage"); + } + } else if ("list".equals(args[0])) { + throw new WrongUsageException(Joiner.on(", ").join(Commands.values())); + } else { + try { + final Commands c = Commands.valueOf(args[0]); + if (sender.canCommandSenderUseCommand(c.level, this.getCommandName())) { + c.command.call(this.srv, args, sender); + } else { + throw new WrongUsageException("commands.ae2.permissions"); + } + } catch (final WrongUsageException wrong) { + throw wrong; + } catch (final Throwable er) { + throw new WrongUsageException("commands.ae2.usage"); + } + } + } } diff --git a/src/main/java/appeng/server/AccessType.java b/src/main/java/appeng/server/AccessType.java index 0d45762a..b1880e99 100644 --- a/src/main/java/appeng/server/AccessType.java +++ b/src/main/java/appeng/server/AccessType.java @@ -18,36 +18,34 @@ package appeng.server; +public enum AccessType { + /** + * allows basic access to manipulate the block via gui, or other. + */ + BLOCK_ACCESS, -public enum AccessType -{ - /** - * allows basic access to manipulate the block via gui, or other. - */ - BLOCK_ACCESS, + /** + * Can player deposit items into the network. + */ + NETWORK_DEPOSIT, - /** - * Can player deposit items into the network. - */ - NETWORK_DEPOSIT, + /** + * can player withdraw items from the network. + */ + NETWORK_WITHDRAW, - /** - * can player withdraw items from the network. - */ - NETWORK_WITHDRAW, + /** + * can player issue crafting requests? + */ + NETWORK_CRAFT, - /** - * can player issue crafting requests? - */ - NETWORK_CRAFT, + /** + * can player add new blocks to the network. + */ + NETWORK_BUILD, - /** - * can player add new blocks to the network. - */ - NETWORK_BUILD, - - /** - * can player manipulate security settings. - */ - NETWORK_SECURITY + /** + * can player manipulate security settings. + */ + NETWORK_SECURITY } diff --git a/src/main/java/appeng/server/Commands.java b/src/main/java/appeng/server/Commands.java index a07589c7..4a5e65ad 100644 --- a/src/main/java/appeng/server/Commands.java +++ b/src/main/java/appeng/server/Commands.java @@ -18,29 +18,23 @@ package appeng.server; - import appeng.server.subcommands.ChunkLogger; import appeng.server.subcommands.Supporters; +public enum Commands { + Chunklogger(4, new ChunkLogger()), + Supporters(0, new Supporters()); -public enum Commands -{ - Chunklogger( 4, new ChunkLogger() ), - Supporters( 0, new Supporters() ); + public final int level; + public final ISubCommand command; - public final int level; - public final ISubCommand command; - - Commands( final int level, final ISubCommand w ) - { - this.level = level; - this.command = w; - } - - @Override - public String toString() - { - return this.name(); - } + Commands(final int level, final ISubCommand w) { + this.level = level; + this.command = w; + } + @Override + public String toString() { + return this.name(); + } } diff --git a/src/main/java/appeng/server/ISubCommand.java b/src/main/java/appeng/server/ISubCommand.java index 4abd9dde..1d173dfe 100644 --- a/src/main/java/appeng/server/ISubCommand.java +++ b/src/main/java/appeng/server/ISubCommand.java @@ -18,15 +18,11 @@ package appeng.server; - import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; +public interface ISubCommand { + String getHelp(MinecraftServer srv); -public interface ISubCommand -{ - - String getHelp( MinecraftServer srv ); - - void call( MinecraftServer srv, String[] args, ICommandSender sender ); + 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 f29bd3c4..f4b4da62 100644 --- a/src/main/java/appeng/server/ServerHelper.java +++ b/src/main/java/appeng/server/ServerHelper.java @@ -18,6 +18,9 @@ package appeng.server; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; import appeng.api.parts.CableRenderMode; import appeng.block.AEBaseBlock; @@ -37,154 +40,131 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; +public class ServerHelper extends CommonHelper { + private EntityPlayer renderModeBased; + @Override + public void init() {} -public class ServerHelper extends CommonHelper -{ + @Override + public World getWorld() { + throw new UnsupportedOperationException("This is a server..."); + } - private EntityPlayer renderModeBased; + @Override + public void bindTileEntitySpecialRenderer(final Class tile, final AEBaseBlock blk) { + throw new UnsupportedOperationException("This is a server..."); + } - @Override - public void init() - { + @Override + public List getPlayers() { + if (!Platform.isClient()) { + final MinecraftServer server + = FMLCommonHandler.instance().getMinecraftServerInstance(); - } + if (server != null) { + return server.getConfigurationManager().playerEntityList; + } + } - @Override - public World getWorld() - { - throw new UnsupportedOperationException( "This is a server..." ); - } + return new ArrayList(); + } - @Override - public void bindTileEntitySpecialRenderer( final Class tile, final AEBaseBlock blk ) - { - throw new UnsupportedOperationException( "This is a server..." ); - } + @Override + public void sendToAllNearExcept( + final EntityPlayer p, + final double x, + final double y, + final double z, + final double dist, + final World w, + final AppEngPacket packet + ) { + if (Platform.isClient()) { + return; + } - @Override - public List getPlayers() - { - if( !Platform.isClient() ) - { - final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); + for (final EntityPlayer o : this.getPlayers()) { + final EntityPlayerMP entityplayermp = (EntityPlayerMP) o; - if( server != null ) - { - return server.getConfigurationManager().playerEntityList; - } - } + if (entityplayermp != p && entityplayermp.worldObj == w) { + final double dX = x - entityplayermp.posX; + final double dY = y - entityplayermp.posY; + final double dZ = z - entityplayermp.posZ; - return new ArrayList(); - } + if (dX * dX + dY * dY + dZ * dZ < dist * dist) { + NetworkHandler.instance.sendTo(packet, entityplayermp); + } + } + } + } - @Override - public void sendToAllNearExcept( final EntityPlayer p, final double x, final double y, final double z, final double dist, final World w, final AppEngPacket packet ) - { - if( Platform.isClient() ) - { - return; - } + @Override + public void spawnEffect( + final EffectType type, + final World worldObj, + final double posX, + final double posY, + final double posZ, + final Object o + ) { + // :P + } - for( final EntityPlayer o : this.getPlayers() ) - { - final EntityPlayerMP entityplayermp = (EntityPlayerMP) o; + @Override + public boolean shouldAddParticles(final Random r) { + return false; + } - if( entityplayermp != p && entityplayermp.worldObj == w ) - { - final double dX = x - entityplayermp.posX; - final double dY = y - entityplayermp.posY; - final double dZ = z - entityplayermp.posZ; + @Override + public MovingObjectPosition getMOP() { + return null; + } - if( dX * dX + dY * dY + dZ * dZ < dist * dist ) - { - NetworkHandler.instance.sendTo( packet, entityplayermp ); - } - } - } - } + @Override + public void doRenderItem(final ItemStack sis, final World tile) {} - @Override - public void spawnEffect( final EffectType type, final World worldObj, final double posX, final double posY, final double posZ, final Object o ) - { - // :P - } + @Override + public void postInit() {} - @Override - public boolean shouldAddParticles( final Random r ) - { - return false; - } + @Override + public CableRenderMode getRenderMode() { + if (this.renderModeBased == null) { + return CableRenderMode.Standard; + } - @Override - public MovingObjectPosition getMOP() - { - return null; - } + return this.renderModeForPlayer(this.renderModeBased); + } - @Override - public void doRenderItem( final ItemStack sis, final World tile ) - { + protected CableRenderMode renderModeForPlayer(final EntityPlayer player) { + if (player != null) { + for (int x = 0; x < InventoryPlayer.getHotbarSize(); x++) { + final ItemStack is = player.inventory.getStackInSlot(x); - } + if (is != null && is.getItem() instanceof ToolNetworkTool) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null && c.getBoolean("hideFacades")) { + return CableRenderMode.CableView; + } + } + } + } - @Override - public void postInit() - { + return CableRenderMode.Standard; + } - } + @Override + public void triggerUpdates() {} - @Override - public CableRenderMode getRenderMode() - { - if( this.renderModeBased == null ) - { - return CableRenderMode.Standard; - } + @Override + public void updateRenderMode(final EntityPlayer player) { + this.renderModeBased = player; + } - return this.renderModeForPlayer( this.renderModeBased ); - } - - protected CableRenderMode renderModeForPlayer( final EntityPlayer player ) - { - if( player != null ) - { - for( int x = 0; x < InventoryPlayer.getHotbarSize(); x++ ) - { - final ItemStack is = player.inventory.getStackInSlot( x ); - - if( is != null && is.getItem() instanceof ToolNetworkTool ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null && c.getBoolean( "hideFacades" ) ) - { - return CableRenderMode.CableView; - } - } - } - } - - return CableRenderMode.Standard; - } - - @Override - public void triggerUpdates() - { - - } - - @Override - public void updateRenderMode( final EntityPlayer player ) - { - this.renderModeBased = player; - } - - @Override - public void missingCoreMod() - { - throw new IllegalStateException( "Unable to Load Core Mod, please verify that AE2 is properly install in the mods folder, with a .jar extension." ); - } + @Override + public void missingCoreMod() { + throw new IllegalStateException( + "Unable to Load Core Mod, please verify that AE2 is properly install in the mods folder, with a .jar extension." + ); + } } diff --git a/src/main/java/appeng/server/subcommands/ChunkLogger.java b/src/main/java/appeng/server/subcommands/ChunkLogger.java index 1a9d3ed7..6cdb0deb 100644 --- a/src/main/java/appeng/server/subcommands/ChunkLogger.java +++ b/src/main/java/appeng/server/subcommands/ChunkLogger.java @@ -18,7 +18,6 @@ package appeng.server.subcommands; - import appeng.core.AEConfig; import appeng.core.AELog; import appeng.core.features.AEFeature; @@ -30,71 +29,68 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.world.ChunkEvent; +public class ChunkLogger implements ISubCommand { + private boolean enabled = false; -public class ChunkLogger implements ISubCommand -{ + @SubscribeEvent + public void onChunkLoadEvent(final ChunkEvent.Load event) { + if (!event.world.isRemote) { + AELog.info( + "Chunk Loaded: " + event.getChunk().xPosition + ", " + + event.getChunk().zPosition + ); + this.displayStack(); + } + } - private boolean enabled = false; + private void displayStack() { + if (AEConfig.instance.isFeatureEnabled(AEFeature.ChunkLoggerTrace)) { + boolean output = false; + for (final StackTraceElement e : Thread.currentThread().getStackTrace()) { + if (output) { + AELog.info( + " " + e.getClassName() + '.' + e.getMethodName() + " (" + + e.getLineNumber() + ')' + ); + } else { + output = e.getClassName().contains("EventBus") + && e.getMethodName().contains("post"); + } + } + } + } - @SubscribeEvent - public void onChunkLoadEvent( final ChunkEvent.Load event ) - { - if( !event.world.isRemote ) - { - AELog.info( "Chunk Loaded: " + event.getChunk().xPosition + ", " + event.getChunk().zPosition ); - this.displayStack(); - } - } + @SubscribeEvent + public void onChunkUnloadEvent(final ChunkEvent.Unload unload) { + if (!unload.world.isRemote) { + AELog.info( + "Chunk Unloaded: " + unload.getChunk().xPosition + ", " + + unload.getChunk().zPosition + ); + this.displayStack(); + } + } - private void displayStack() - { - if( AEConfig.instance.isFeatureEnabled( AEFeature.ChunkLoggerTrace ) ) - { - boolean output = false; - for( final StackTraceElement e : Thread.currentThread().getStackTrace() ) - { - if( output ) - { - AELog.info( " " + e.getClassName() + '.' + e.getMethodName() + " (" + e.getLineNumber() + ')' ); - } - else - { - output = e.getClassName().contains( "EventBus" ) && e.getMethodName().contains( "post" ); - } - } - } - } + @Override + public String getHelp(final MinecraftServer srv) { + return "commands.ae2.ChunkLogger"; + } - @SubscribeEvent - public void onChunkUnloadEvent( final ChunkEvent.Unload unload ) - { - if( !unload.world.isRemote ) - { - AELog.info( "Chunk Unloaded: " + unload.getChunk().xPosition + ", " + unload.getChunk().zPosition ); - this.displayStack(); - } - } + @Override + public void + call(final MinecraftServer srv, final String[] data, final ICommandSender sender) { + this.enabled = !this.enabled; - @Override - public String getHelp( final MinecraftServer srv ) - { - return "commands.ae2.ChunkLogger"; - } - - @Override - public void call( final MinecraftServer srv, final String[] data, final ICommandSender sender ) - { - this.enabled = !this.enabled; - - if( this.enabled ) - { - MinecraftForge.EVENT_BUS.register( this ); - sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOn" ) ); - } - else - { - MinecraftForge.EVENT_BUS.unregister( this ); - sender.addChatMessage( new ChatComponentTranslation( "commands.ae2.ChunkLoggerOff" ) ); - } - } + if (this.enabled) { + MinecraftForge.EVENT_BUS.register(this); + sender.addChatMessage( + new ChatComponentTranslation("commands.ae2.ChunkLoggerOn") + ); + } else { + MinecraftForge.EVENT_BUS.unregister(this); + sender.addChatMessage( + new ChatComponentTranslation("commands.ae2.ChunkLoggerOff") + ); + } + } } diff --git a/src/main/java/appeng/server/subcommands/Supporters.java b/src/main/java/appeng/server/subcommands/Supporters.java index a0391969..0481e3df 100644 --- a/src/main/java/appeng/server/subcommands/Supporters.java +++ b/src/main/java/appeng/server/subcommands/Supporters.java @@ -18,27 +18,28 @@ package appeng.server.subcommands; - import appeng.server.ISubCommand; import com.google.common.base.Joiner; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; +public class Supporters implements ISubCommand { + @Override + public String getHelp(final MinecraftServer srv) { + return "commands.ae2.Supporters"; + } -public class Supporters implements ISubCommand -{ - - @Override - public String getHelp( final MinecraftServer srv ) - { - return "commands.ae2.Supporters"; - } - - @Override - public void call( final MinecraftServer srv, final String[] data, final ICommandSender sender ) - { - final 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 void + call(final MinecraftServer srv, final String[] data, final ICommandSender sender) { + final 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 da64b7dd..ef7627ca 100644 --- a/src/main/java/appeng/services/CompassService.java +++ b/src/main/java/appeng/services/CompassService.java @@ -18,6 +18,11 @@ package appeng.services; +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.*; +import javax.annotation.Nonnull; import appeng.api.AEApi; import appeng.api.util.DimensionalCoord; @@ -31,327 +36,287 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.event.world.WorldEvent; -import javax.annotation.Nonnull; -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.*; +public final class CompassService { + private static final int CHUNK_SIZE = 16; + private final Map worldSet + = new HashMap(10); + private final ExecutorService executor; -public final class CompassService -{ - private static final int CHUNK_SIZE = 16; + /** + * AE2 Folder for each world + */ + private final File worldCompassFolder; - private final Map worldSet = new HashMap( 10 ); - private final ExecutorService executor; + private int jobSize; - /** - * AE2 Folder for each world - */ - private final File worldCompassFolder; + public CompassService( + @Nonnull final File worldCompassFolder, @Nonnull final ThreadFactory factory + ) { + Preconditions.checkNotNull(worldCompassFolder); - private int jobSize; + this.worldCompassFolder = worldCompassFolder; + this.executor = Executors.newSingleThreadExecutor(factory); + this.jobSize = 0; + } - public CompassService( @Nonnull final File worldCompassFolder, @Nonnull final ThreadFactory factory ) - { - Preconditions.checkNotNull( worldCompassFolder ); + public Future getCompassDirection( + final DimensionalCoord coord, final int maxRange, final ICompassCallback cc + ) { + this.jobSize++; + return this.executor.submit(new CMDirectionRequest(coord, maxRange, cc)); + } - this.worldCompassFolder = worldCompassFolder; - this.executor = Executors.newSingleThreadExecutor( factory ); - this.jobSize = 0; - } + /** + * Ensure the a compass service is removed once a world gets unloaded by forge. + * + * @param event the event containing the unloaded world. + */ + @SubscribeEvent + public void unloadWorld(final WorldEvent.Unload event) { + if (Platform.isServer() && this.worldSet.containsKey(event.world)) { + final CompassReader compassReader = this.worldSet.remove(event.world); - public Future getCompassDirection( final DimensionalCoord coord, final int maxRange, final ICompassCallback cc ) - { - this.jobSize++; - return this.executor.submit( new CMDirectionRequest( coord, maxRange, cc ) ); - } + compassReader.close(); + } + } - /** - * Ensure the a compass service is removed once a world gets unloaded by forge. - * - * @param event the event containing the unloaded world. - */ - @SubscribeEvent - public void unloadWorld( final WorldEvent.Unload event ) - { - if( Platform.isServer() && this.worldSet.containsKey( event.world ) ) - { - final CompassReader compassReader = this.worldSet.remove( event.world ); + private int jobSize() { + return this.jobSize; + } - compassReader.close(); - } - } + private void cleanUp() { + for (final CompassReader cr : this.worldSet.values()) { + cr.close(); + } + } - private int jobSize() - { - return this.jobSize; - } + public void updateArea(final World w, final int chunkX, final int chunkZ) { + final int x = chunkX << 4; + final int z = chunkZ << 4; - private void cleanUp() - { - for( final CompassReader cr : this.worldSet.values() ) - { - cr.close(); - } - } + this.updateArea(w, x, CHUNK_SIZE, z); + this.updateArea(w, x, CHUNK_SIZE + 32, z); + this.updateArea(w, x, CHUNK_SIZE + 64, z); + this.updateArea(w, x, CHUNK_SIZE + 96, z); - public void updateArea( final World w, final int chunkX, final int chunkZ ) - { - final int x = chunkX << 4; - final int z = chunkZ << 4; + this.updateArea(w, x, CHUNK_SIZE + 128, z); + this.updateArea(w, x, CHUNK_SIZE + 160, z); + this.updateArea(w, x, CHUNK_SIZE + 192, z); + this.updateArea(w, x, CHUNK_SIZE + 224, z); + } - this.updateArea( w, x, CHUNK_SIZE, z ); - this.updateArea( w, x, CHUNK_SIZE + 32, z ); - this.updateArea( w, x, CHUNK_SIZE + 64, z ); - this.updateArea( w, x, CHUNK_SIZE + 96, z ); + public Future updateArea(final World w, final int x, final int y, final int z) { + this.jobSize++; - this.updateArea( w, x, CHUNK_SIZE + 128, z ); - this.updateArea( w, x, CHUNK_SIZE + 160, z ); - this.updateArea( w, x, CHUNK_SIZE + 192, z ); - this.updateArea( w, x, CHUNK_SIZE + 224, z ); - } + final int cx = x >> 4; + final int cdy = y >> 5; + final int cz = z >> 4; - public Future updateArea( final World w, final int x, final int y, final int z ) - { - this.jobSize++; + final int low_y = cdy << 5; + final int hi_y = low_y + 32; - final int cx = x >> 4; - final int cdy = y >> 5; - final int cz = z >> 4; + // lower level... + final Chunk c = w.getChunkFromBlockCoords(x, z); - final int low_y = cdy << 5; - final int hi_y = low_y + 32; + for (final Block skyStoneBlock : + AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet()) { + for (int i = 0; i < CHUNK_SIZE; i++) { + for (int j = 0; j < CHUNK_SIZE; j++) { + for (int k = low_y; k < hi_y; k++) { + final Block blk = c.getBlock(i, k, j); + if (blk == skyStoneBlock && c.getBlockMetadata(i, k, j) == 0) { + return this.executor.submit( + new CMUpdatePost(w, cx, cz, cdy, true) + ); + } + } + } + } + } - // lower level... - final Chunk c = w.getChunkFromBlockCoords( x, z ); + return this.executor.submit(new CMUpdatePost(w, cx, cz, cdy, false)); + } - for( final Block skyStoneBlock : AEApi.instance().definitions().blocks().skyStone().maybeBlock().asSet() ) - { - for( int i = 0; i < CHUNK_SIZE; i++ ) - { - for( int j = 0; j < CHUNK_SIZE; j++ ) - { - for( int k = low_y; k < hi_y; k++ ) - { - final Block blk = c.getBlock( i, k, j ); - if( blk == skyStoneBlock && c.getBlockMetadata( i, k, j ) == 0 ) - { - return this.executor.submit( new CMUpdatePost( w, cx, cz, cdy, true ) ); - } - } - } - } - } + public void kill() { + this.executor.shutdown(); - return this.executor.submit( new CMUpdatePost( w, cx, cz, cdy, false ) ); - } + try { + this.executor.awaitTermination(6, TimeUnit.MINUTES); + this.jobSize = 0; - public void kill() - { - this.executor.shutdown(); + for (final CompassReader cr : this.worldSet.values()) { + cr.close(); + } - try - { - this.executor.awaitTermination( 6, TimeUnit.MINUTES ); - this.jobSize = 0; + this.worldSet.clear(); + } catch (final InterruptedException e) { + // wrap this up.. + } + } - for( final CompassReader cr : this.worldSet.values() ) - { - cr.close(); - } + private CompassReader getReader(final World w) { + CompassReader cr = this.worldSet.get(w); - this.worldSet.clear(); - } - catch( final InterruptedException e ) - { - // wrap this up.. - } - } + if (cr == null) { + cr = new CompassReader(w.provider.dimensionId, this.worldCompassFolder); + this.worldSet.put(w, cr); + } - private CompassReader getReader( final World w ) - { - CompassReader cr = this.worldSet.get( w ); + return cr; + } - if( cr == null ) - { - cr = new CompassReader( w.provider.dimensionId, this.worldCompassFolder ); - this.worldSet.put( w, cr ); - } + private int dist(final int ax, final int az, final int bx, final int bz) { + final int up = (bz - az) * CHUNK_SIZE; + final int side = (bx - ax) * CHUNK_SIZE; - return cr; - } + return up * up + side * side; + } - private int dist( final int ax, final int az, final int bx, final int bz ) - { - final int up = ( bz - az ) * CHUNK_SIZE; - final int side = ( bx - ax ) * CHUNK_SIZE; + private double rad(final int ax, final int az, final int bx, final int bz) { + final int up = bz - az; + final int side = bx - ax; - return up * up + side * side; - } + return Math.atan2(-up, side) - Math.PI / 2.0; + } - private double rad( final int ax, final int az, final int bx, final int bz ) - { - final int up = bz - az; - final int side = bx - ax; + private class CMUpdatePost implements Runnable { + public final World world; - return Math.atan2( -up, side ) - Math.PI / 2.0; - } + public final int chunkX; + public final int chunkZ; + public final int doubleChunkY; // 32 blocks instead of 16. + public final boolean value; - private class CMUpdatePost implements Runnable - { + public CMUpdatePost( + final World w, final int cx, final int cz, final int dcy, final boolean val + ) { + this.world = w; + this.chunkX = cx; + this.doubleChunkY = dcy; + this.chunkZ = cz; + this.value = val; + } - public final World world; + @Override + public void run() { + CompassService.this.jobSize--; - public final int chunkX; - public final int chunkZ; - public final int doubleChunkY; // 32 blocks instead of 16. - public final boolean value; + final CompassReader cr = CompassService.this.getReader(this.world); + cr.setHasBeacon(this.chunkX, this.chunkZ, this.doubleChunkY, this.value); - public CMUpdatePost( final World w, final int cx, final int cz, final int dcy, final boolean val ) - { - this.world = w; - this.chunkX = cx; - this.doubleChunkY = dcy; - this.chunkZ = cz; - this.value = val; - } + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } + } + } - @Override - public void run() - { - CompassService.this.jobSize--; + private class CMDirectionRequest implements Runnable { + public final int maxRange; + public final DimensionalCoord coord; + public final ICompassCallback callback; - final CompassReader cr = CompassService.this.getReader( this.world ); - cr.setHasBeacon( this.chunkX, this.chunkZ, this.doubleChunkY, this.value ); + public CMDirectionRequest( + final DimensionalCoord coord, final int getMaxRange, final ICompassCallback cc + ) { + this.coord = coord; + this.maxRange = getMaxRange; + this.callback = cc; + } - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - } - } + @Override + public void run() { + CompassService.this.jobSize--; + final int cx = this.coord.x >> 4; + final int cz = this.coord.z >> 4; - private class CMDirectionRequest implements Runnable - { + final CompassReader cr = CompassService.this.getReader(this.coord.getWorld()); - public final int maxRange; - public final DimensionalCoord coord; - public final ICompassCallback callback; + // Am I standing on it? + if (cr.hasBeacon(cx, cz)) { + this.callback.calculatedDirection(true, true, -999, 0); - public CMDirectionRequest( final DimensionalCoord coord, final int getMaxRange, final ICompassCallback cc ) - { - this.coord = coord; - this.maxRange = getMaxRange; - this.callback = cc; - } + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } - @Override - public void run() - { - CompassService.this.jobSize--; + return; + } - final int cx = this.coord.x >> 4; - final int cz = this.coord.z >> 4; + // spiral outward... + for (int offset = 1; offset < this.maxRange; offset++) { + final int minX = cx - offset; + final int minZ = cz - offset; + final int maxX = cx + offset; + final int maxZ = cz + offset; - final CompassReader cr = CompassService.this.getReader( this.coord.getWorld() ); + int closest = Integer.MAX_VALUE; + int chosen_x = cx; + int chosen_z = cz; - // Am I standing on it? - if( cr.hasBeacon( cx, cz ) ) - { - this.callback.calculatedDirection( true, true, -999, 0 ); + for (int z = minZ; z <= maxZ; z++) { + if (cr.hasBeacon(minX, z)) { + final int closeness = CompassService.this.dist(cx, cz, minX, z); + if (closeness < closest) { + closest = closeness; + chosen_x = minX; + chosen_z = z; + } + } - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } + if (cr.hasBeacon(maxX, z)) { + final int closeness = CompassService.this.dist(cx, cz, maxX, z); + if (closeness < closest) { + closest = closeness; + chosen_x = maxX; + chosen_z = z; + } + } + } - return; - } + for (int x = minX + 1; x < maxX; x++) { + if (cr.hasBeacon(x, minZ)) { + final int closeness = CompassService.this.dist(cx, cz, x, minZ); + if (closeness < closest) { + closest = closeness; + chosen_x = x; + chosen_z = minZ; + } + } - // spiral outward... - for( int offset = 1; offset < this.maxRange; offset++ ) - { - final int minX = cx - offset; - final int minZ = cz - offset; - final int maxX = cx + offset; - final int maxZ = cz + offset; + if (cr.hasBeacon(x, maxZ)) { + final int closeness = CompassService.this.dist(cx, cz, x, maxZ); + if (closeness < closest) { + closest = closeness; + chosen_x = x; + chosen_z = maxZ; + } + } + } - int closest = Integer.MAX_VALUE; - int chosen_x = cx; - int chosen_z = cz; + 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) + ); - for( int z = minZ; z <= maxZ; z++ ) - { - if( cr.hasBeacon( minX, z ) ) - { - final int closeness = CompassService.this.dist( cx, cz, minX, z ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = minX; - chosen_z = z; - } - } + if (CompassService.this.jobSize() < 2) { + CompassService.this.cleanUp(); + } - if( cr.hasBeacon( maxX, z ) ) - { - final int closeness = CompassService.this.dist( cx, cz, maxX, z ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = maxX; - chosen_z = z; - } - } - } + return; + } + } - for( int x = minX + 1; x < maxX; x++ ) - { - if( cr.hasBeacon( x, minZ ) ) - { - final int closeness = CompassService.this.dist( cx, cz, x, minZ ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = x; - chosen_z = minZ; - } - } + // didn't find shit... + this.callback.calculatedDirection(false, true, -999, 999); - if( cr.hasBeacon( x, maxZ ) ) - { - final int closeness = CompassService.this.dist( cx, cz, x, maxZ ); - if( closeness < closest ) - { - closest = closeness; - chosen_x = x; - chosen_z = maxZ; - } - } - } - - 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 ) - { - CompassService.this.cleanUp(); - } - - return; - } - } - - // didn't find shit... - this.callback.calculatedDirection( false, true, -999, 999 ); - - if( CompassService.this.jobSize() < 2 ) - { - CompassService.this.cleanUp(); - } - } - } + 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 a6703e2d..71422e9c 100644 --- a/src/main/java/appeng/services/VersionChecker.java +++ b/src/main/java/appeng/services/VersionChecker.java @@ -18,6 +18,8 @@ package appeng.services; +import java.util.Date; +import javax.annotation.Nonnull; import appeng.core.AEConfig; import appeng.core.AELog; @@ -30,10 +32,6 @@ import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLInterModComms; import net.minecraft.nbt.NBTTagCompound; -import javax.annotation.Nonnull; -import java.util.Date; - - /** * Tries to connect to GitHub to retrieve the most current build. * After comparison with the local version, several path can be chosen. @@ -56,142 +54,145 @@ import java.util.Date; * Only after all that cases, if the external version is higher than the local, * use Version Checker Mod and post several information needed for it to update the mod. */ -public final class VersionChecker implements Runnable -{ - private static final int SEC_TO_HOUR = 3600; - private static final int MS_TO_SEC = 1000; - private final VersionCheckerConfig config; +public final class VersionChecker implements Runnable { + private static final int SEC_TO_HOUR = 3600; + private static final int MS_TO_SEC = 1000; + private final VersionCheckerConfig config; - public VersionChecker( @Nonnull final VersionCheckerConfig config ) - { - Preconditions.checkNotNull( config ); + public VersionChecker(@Nonnull final VersionCheckerConfig config) { + Preconditions.checkNotNull(config); - this.config = config; - } + this.config = config; + } - @Override - public void run() - { - try - { - Thread.yield(); + @Override + public void run() { + try { + Thread.yield(); - // persist the config - this.config.save(); + // persist the config + this.config.save(); - // retrieve data - final String rawLastCheck = this.config.lastCheck(); + // retrieve data + final String rawLastCheck = this.config.lastCheck(); - // process data - final long lastCheck = Long.parseLong( rawLastCheck ); - final Date now = new Date(); - final long nowInMs = now.getTime(); - final long intervalInMs = this.config.interval() * SEC_TO_HOUR * MS_TO_SEC; - final long lastAfterInterval = lastCheck + intervalInMs; + // process data + final long lastCheck = Long.parseLong(rawLastCheck); + final Date now = new Date(); + final long nowInMs = now.getTime(); + final long intervalInMs = this.config.interval() * SEC_TO_HOUR * MS_TO_SEC; + final long lastAfterInterval = lastCheck + intervalInMs; - this.processInterval( nowInMs, lastAfterInterval ); - } - catch( Exception exception ) - { - // Log any unhandled exception to prevent the JVM from reporting them as unhandled. - AELog.debug( exception ); - } + this.processInterval(nowInMs, lastAfterInterval); + } catch (Exception exception) { + // Log any unhandled exception to prevent the JVM from reporting them as + // unhandled. + AELog.debug(exception); + } - AELog.info( "Stopping AE2 VersionChecker" ); - } + AELog.info("Stopping AE2 VersionChecker"); + } - /** - * checks if enough time since last check has expired - * - * @param nowInMs now in milli seconds - * @param lastAfterInterval last version check including the interval defined in the config - */ - private void processInterval( final long nowInMs, final long lastAfterInterval ) - { - if( nowInMs > lastAfterInterval ) - { - final String rawModVersion = AEConfig.VERSION; - final VersionParser parser = new VersionParser(); - final VersionFetcher modFetcher = new ModVersionFetcher( rawModVersion, parser ); - final ReleaseFetcher githubFetcher = new ReleaseFetcher( this.config, parser ); + /** + * checks if enough time since last check has expired + * + * @param nowInMs now in milli seconds + * @param lastAfterInterval last version check including the interval defined in the + * config + */ + private void processInterval(final long nowInMs, final long lastAfterInterval) { + if (nowInMs > lastAfterInterval) { + final String rawModVersion = AEConfig.VERSION; + final VersionParser parser = new VersionParser(); + final VersionFetcher modFetcher + = new ModVersionFetcher(rawModVersion, parser); + final ReleaseFetcher githubFetcher = new ReleaseFetcher(this.config, parser); - final Version modVersion = modFetcher.get(); - final FormattedRelease githubRelease = githubFetcher.get(); + final Version modVersion = modFetcher.get(); + final FormattedRelease githubRelease = githubFetcher.get(); - this.processVersions( modVersion, githubRelease ); - } - else - { - AELog.info( "Last check was just recently." ); - } - } + this.processVersions(modVersion, githubRelease); + } else { + AELog.info("Last check was just recently."); + } + } - /** - * 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 githubRelease release retrieved through github - */ - private void processVersions( @Nonnull final Version modVersion, @Nonnull final FormattedRelease githubRelease ) - { - final Version githubVersion = githubRelease.version(); - final String modFormatted = modVersion.formatted(); - final String ghFormatted = githubVersion.formatted(); + /** + * 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 githubRelease release retrieved through github + */ + private void processVersions( + @Nonnull final Version modVersion, @Nonnull final FormattedRelease githubRelease + ) { + final Version githubVersion = githubRelease.version(); + final String modFormatted = modVersion.formatted(); + final String ghFormatted = githubVersion.formatted(); - if( githubVersion.isNewerAs( modVersion ) ) - { - final String changelog = githubRelease.changelog(); + if (githubVersion.isNewerAs(modVersion)) { + final String changelog = githubRelease.changelog(); - if( this.config.shouldNotifyPlayer() ) - { - AELog.info( "Newer version is available: " + ghFormatted + " (found) > " + modFormatted + " (current)" ); + if (this.config.shouldNotifyPlayer()) { + AELog.info( + "Newer version is available: " + ghFormatted + " (found) > " + + modFormatted + " (current)" + ); - if( this.config.shouldPostChangelog() ) - { - AELog.info( "Changelog: " + changelog ); - } - } + if (this.config.shouldPostChangelog()) { + AELog.info("Changelog: " + changelog); + } + } - this.interactWithVersionCheckerMod( modFormatted, ghFormatted, changelog ); - } - else - { - AELog.info( "No newer version is available: " + ghFormatted + "(found) < " + modFormatted + " (current)" ); - } - } + this.interactWithVersionCheckerMod(modFormatted, ghFormatted, changelog); + } else { + AELog.info( + "No newer version is available: " + ghFormatted + "(found) < " + + modFormatted + " (current)" + ); + } + } - /** - * 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 - */ - private void interactWithVersionCheckerMod( @Nonnull final String modFormatted, @Nonnull final String ghFormatted, @Nonnull final String changelog ) - { - if( Loader.isModLoaded( "VersionChecker" ) ) - { - final NBTTagCompound versionInf = new NBTTagCompound(); - versionInf.setString( "modDisplayName", AppEng.MOD_NAME ); - versionInf.setString( "oldVersion", modFormatted ); - versionInf.setString( "newVersion", ghFormatted ); - versionInf.setString( "updateUrl", "https://github.com/xsun2001/Applied-Energistics-2-Unofficial/releases/download/rv3.beta.13/appliedenergistics2" + ghFormatted + ".jar" ); - versionInf.setBoolean( "isDirectLink", true ); + /** + * 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 + */ + private void interactWithVersionCheckerMod( + @Nonnull final String modFormatted, + @Nonnull final String ghFormatted, + @Nonnull final String changelog + ) { + if (Loader.isModLoaded("VersionChecker")) { + final NBTTagCompound versionInf = new NBTTagCompound(); + versionInf.setString("modDisplayName", AppEng.MOD_NAME); + versionInf.setString("oldVersion", modFormatted); + versionInf.setString("newVersion", ghFormatted); + versionInf.setString( + "updateUrl", + "https://github.com/xsun2001/Applied-Energistics-2-Unofficial/releases/download/rv3.beta.13/appliedenergistics2" + + ghFormatted + ".jar" + ); + versionInf.setBoolean("isDirectLink", true); - if( !changelog.isEmpty() ) - { - versionInf.setString( "changeLog", changelog ); - } + if (!changelog.isEmpty()) { + versionInf.setString("changeLog", changelog); + } - versionInf.setString( "newFileName", "appliedenergistics2-" + ghFormatted + ".jar" ); - FMLInterModComms.sendRuntimeMessage( AppEng.instance(), "VersionChecker", "addUpdate", versionInf ); + versionInf.setString( + "newFileName", "appliedenergistics2-" + ghFormatted + ".jar" + ); + FMLInterModComms.sendRuntimeMessage( + AppEng.instance(), "VersionChecker", "addUpdate", versionInf + ); - AELog.info( "Reported new version to VersionChecker mod." ); - } - else - { - AELog.info( "VersionChecker mod is not installed; Proceeding." ); - } - } + AELog.info("Reported new version to VersionChecker mod."); + } else { + AELog.info("VersionChecker mod is not installed; Proceeding."); + } + } } diff --git a/src/main/java/appeng/services/compass/CompassException.java b/src/main/java/appeng/services/compass/CompassException.java index e61c09c2..39e8ca3b 100644 --- a/src/main/java/appeng/services/compass/CompassException.java +++ b/src/main/java/appeng/services/compass/CompassException.java @@ -18,16 +18,12 @@ package appeng.services.compass; +public class CompassException extends RuntimeException { + private static final long serialVersionUID = 8825268683203860877L; -public class CompassException extends RuntimeException -{ + private final Throwable inner; - private static final long serialVersionUID = 8825268683203860877L; - - private final Throwable inner; - - public CompassException( final Throwable t ) - { - this.inner = t; - } + public CompassException(final 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 3b247328..ec4998f8 100644 --- a/src/main/java/appeng/services/compass/CompassReader.java +++ b/src/main/java/appeng/services/compass/CompassReader.java @@ -18,68 +18,60 @@ package appeng.services.compass; - -import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.File; import java.util.HashMap; import java.util.Map; +import javax.annotation.Nonnull; +import com.google.common.base.Preconditions; -public final class CompassReader -{ - private final Map regions = new HashMap( 100 ); - private final int dimensionId; - private final File worldCompassFolder; +public final class CompassReader { + private final Map regions + = new HashMap(100); + private final int dimensionId; + private final File worldCompassFolder; - public CompassReader( final int dimensionId, @Nonnull final File worldCompassFolder ) - { - Preconditions.checkNotNull( worldCompassFolder ); - Preconditions.checkArgument( worldCompassFolder.isDirectory() ); + public CompassReader(final int dimensionId, @Nonnull final File worldCompassFolder) { + Preconditions.checkNotNull(worldCompassFolder); + Preconditions.checkArgument(worldCompassFolder.isDirectory()); - this.dimensionId = dimensionId; - this.worldCompassFolder = worldCompassFolder; - } + this.dimensionId = dimensionId; + this.worldCompassFolder = worldCompassFolder; + } - public void close() - { - for( final CompassRegion r : this.regions.values() ) - { - r.close(); - } + public void close() { + for (final CompassRegion r : this.regions.values()) { + r.close(); + } - this.regions.clear(); - } + this.regions.clear(); + } - public void setHasBeacon( final int cx, final int cz, final int cdy, final boolean hasBeacon ) - { - final CompassRegion r = this.getRegion( cx, cz ); + public void + setHasBeacon(final int cx, final int cz, final int cdy, final boolean hasBeacon) { + final CompassRegion r = this.getRegion(cx, cz); - r.setHasBeacon( cx, cz, cdy, hasBeacon ); - } + r.setHasBeacon(cx, cz, cdy, hasBeacon); + } - public boolean hasBeacon( final int cx, final int cz ) - { - final CompassRegion r = this.getRegion( cx, cz ); + public boolean hasBeacon(final int cx, final int cz) { + final CompassRegion r = this.getRegion(cx, cz); - return r.hasBeacon( cx, cz ); - } + return r.hasBeacon(cx, cz); + } - private CompassRegion getRegion( final int cx, final int cz ) - { - long pos = cx >> 10; - pos <<= 32; - pos |= ( cz >> 10 ); + private CompassRegion getRegion(final int cx, final int cz) { + long pos = cx >> 10; + pos <<= 32; + pos |= (cz >> 10); - CompassRegion cr = this.regions.get( pos ); + CompassRegion cr = this.regions.get(pos); - if( cr == null ) - { - cr = new CompassRegion( cx, cz, this.dimensionId, this.worldCompassFolder ); - this.regions.put( pos, cr ); - } + if (cr == null) { + cr = new CompassRegion(cx, cz, this.dimensionId, this.worldCompassFolder); + this.regions.put(pos, cr); + } - return cr; - } + return cr; + } } diff --git a/src/main/java/appeng/services/compass/CompassRegion.java b/src/main/java/appeng/services/compass/CompassRegion.java index ad9fb363..08d7b144 100644 --- a/src/main/java/appeng/services/compass/CompassRegion.java +++ b/src/main/java/appeng/services/compass/CompassRegion.java @@ -18,192 +18,157 @@ package appeng.services.compass; - -import appeng.core.worlddata.MeteorDataNameEncoder; -import com.google.common.base.Preconditions; - -import javax.annotation.Nonnull; import java.io.File; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; +import javax.annotation.Nonnull; +import appeng.core.worlddata.MeteorDataNameEncoder; +import com.google.common.base.Preconditions; -public final class CompassRegion -{ - private final int lowX; - private final int lowZ; - private final int world; - private final File worldCompassFolder; - private final MeteorDataNameEncoder encoder; +public final class CompassRegion { + private final int lowX; + private final int lowZ; + private final int world; + private final File worldCompassFolder; + private final MeteorDataNameEncoder encoder; - private boolean hasFile = false; - private RandomAccessFile raf = null; - private ByteBuffer buffer; + private boolean hasFile = false; + private RandomAccessFile raf = null; + private ByteBuffer buffer; - public CompassRegion( final int cx, final int cz, final int worldID, @Nonnull final File worldCompassFolder ) - { - Preconditions.checkNotNull( worldCompassFolder ); - Preconditions.checkArgument( worldCompassFolder.isDirectory() ); + public CompassRegion( + final int cx, + final int cz, + final int worldID, + @Nonnull final File worldCompassFolder + ) { + Preconditions.checkNotNull(worldCompassFolder); + Preconditions.checkArgument(worldCompassFolder.isDirectory()); - this.world = worldID; - this.worldCompassFolder = worldCompassFolder; - this.encoder = new MeteorDataNameEncoder( 0 ); + this.world = worldID; + this.worldCompassFolder = worldCompassFolder; + this.encoder = new MeteorDataNameEncoder(0); - final int region_x = cx >> 10; - final int region_z = cz >> 10; + final int region_x = cx >> 10; + final int region_z = cz >> 10; - this.lowX = region_x << 10; - this.lowZ = region_z << 10; + this.lowX = region_x << 10; + this.lowZ = region_z << 10; - this.openFile( false ); - } + this.openFile(false); + } - void close() - { - try - { - if( this.hasFile ) - { - this.buffer = null; - this.raf.close(); - this.raf = null; - this.hasFile = false; - } - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } + void close() { + try { + if (this.hasFile) { + this.buffer = null; + this.raf.close(); + this.raf = null; + this.hasFile = false; + } + } catch (final Throwable t) { + throw new CompassException(t); + } + } - boolean hasBeacon( int cx, int cz ) - { - if( this.hasFile ) - { - cx &= 0x3FF; - cz &= 0x3FF; + boolean hasBeacon(int cx, int cz) { + if (this.hasFile) { + cx &= 0x3FF; + cz &= 0x3FF; - final int val = this.read( cx, cz ); - if( val != 0 ) - { - return true; - } - } + final int val = this.read(cx, cz); + if (val != 0) { + return true; + } + } - return false; - } + return false; + } - void setHasBeacon( int cx, int cz, final int cdy, final boolean hasBeacon ) - { - cx &= 0x3FF; - cz &= 0x3FF; + void setHasBeacon(int cx, int cz, final int cdy, final boolean hasBeacon) { + cx &= 0x3FF; + cz &= 0x3FF; - this.openFile( hasBeacon ); + this.openFile(hasBeacon); - if( this.hasFile ) - { - int val = this.read( cx, cz ); - final int originalVal = val; + if (this.hasFile) { + int val = this.read(cx, cz); + final int originalVal = val; - if( hasBeacon ) - { - val |= 1 << cdy; - } - else - { - val &= ~( 1 << cdy ); - } + if (hasBeacon) { + val |= 1 << cdy; + } else { + val &= ~(1 << cdy); + } - if( originalVal != val ) - { - this.write( cx, cz, val ); - } - } - } + if (originalVal != val) { + this.write(cx, cz, val); + } + } + } - @Override - protected void finalize() throws Throwable - { - try - { - if( this.raf != null ) - { - this.raf.close(); - } - } - finally - { - super.finalize(); - } + @Override + protected void finalize() throws Throwable { + try { + if (this.raf != null) { + this.raf.close(); + } + } finally { + super.finalize(); + } + } - } + private void openFile(final boolean create) { + if (this.hasFile) { + return; + } - private void openFile( final boolean create ) - { - if( this.hasFile ) - { - return; - } + final File file = this.getFile(); + if (create || this.isFileExistent(file)) { + try { + this.raf = new RandomAccessFile(file, "rw"); + final FileChannel fc = this.raf.getChannel(); + this.buffer = fc.map( + FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400 + ); // fc.size() ); + this.hasFile = true; + } catch (final Throwable t) { + throw new CompassException(t); + } + } + } - final File file = this.getFile(); - if( create || this.isFileExistent( file ) ) - { - try - { - this.raf = new RandomAccessFile( file, "rw" ); - final FileChannel fc = this.raf.getChannel(); - this.buffer = fc.map( FileChannel.MapMode.READ_WRITE, 0, 0x400 * 0x400 );// fc.size() ); - this.hasFile = true; - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } - } + private File getFile() { + final String fileName = this.encoder.encode(this.world, this.lowX, this.lowZ); - private File getFile() - { - final String fileName = this.encoder.encode( this.world, this.lowX, this.lowZ ); + return new File(this.worldCompassFolder, fileName); + } - return new File( this.worldCompassFolder, fileName ); - } + private boolean isFileExistent(final File file) { + return file.exists() && file.isFile(); + } - private boolean isFileExistent( final File file ) - { - return file.exists() && file.isFile(); - } + private int read(final int cx, final int cz) { + try { + return this.buffer.get(cx + cz * 0x400); + // raf.seek( cx + cz * 0x400 ); + // return raf.readByte(); + } catch (final IndexOutOfBoundsException outOfBounds) { + return 0; + } catch (final Throwable t) { + throw new CompassException(t); + } + } - private int read( final int cx, final int cz ) - { - try - { - return this.buffer.get( cx + cz * 0x400 ); - // raf.seek( cx + cz * 0x400 ); - // return raf.readByte(); - } - catch( final IndexOutOfBoundsException outOfBounds ) - { - return 0; - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } - - private void write( final int cx, final int cz, final int val ) - { - try - { - this.buffer.put( cx + cz * 0x400, (byte) val ); - // raf.seek( cx + cz * 0x400 ); - // raf.writeByte( val ); - } - catch( final Throwable t ) - { - throw new CompassException( t ); - } - } + private void write(final int cx, final int cz, final int val) { + try { + this.buffer.put(cx + cz * 0x400, (byte) val); + // raf.seek( cx + cz * 0x400 ); + // raf.writeByte( val ); + } catch (final Throwable t) { + throw new CompassException(t); + } + } } diff --git a/src/main/java/appeng/services/compass/CompassThreadFactory.java b/src/main/java/appeng/services/compass/CompassThreadFactory.java index 08645172..3644cc16 100644 --- a/src/main/java/appeng/services/compass/CompassThreadFactory.java +++ b/src/main/java/appeng/services/compass/CompassThreadFactory.java @@ -18,25 +18,21 @@ package appeng.services.compass; +import java.util.concurrent.ThreadFactory; +import javax.annotation.Nonnull; import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import java.util.concurrent.ThreadFactory; - - /** * @author thatsIch * @version rv3 - 31.05.2015 * @since rv3 31.05.2015 */ -public final class CompassThreadFactory implements ThreadFactory -{ - @Override - public Thread newThread( @Nonnull final Runnable job ) - { - Preconditions.checkNotNull( job ); +public final class CompassThreadFactory implements ThreadFactory { + @Override + public Thread newThread(@Nonnull final Runnable job) { + Preconditions.checkNotNull(job); - return new Thread( job, "AE Compass Service" ); - } + return new Thread(job, "AE Compass Service"); + } } diff --git a/src/main/java/appeng/services/compass/ICompassCallback.java b/src/main/java/appeng/services/compass/ICompassCallback.java index 8eb5d150..29c09552 100644 --- a/src/main/java/appeng/services/compass/ICompassCallback.java +++ b/src/main/java/appeng/services/compass/ICompassCallback.java @@ -18,17 +18,15 @@ package appeng.services.compass; - -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 - */ - void calculatedDirection( boolean hasResult, boolean spin, double radians, double dist ); +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 + */ + void + calculatedDirection(boolean hasResult, boolean spin, double radians, double dist); } diff --git a/src/main/java/appeng/services/export/CheckType.java b/src/main/java/appeng/services/export/CheckType.java index 7b37e04b..31c4388e 100644 --- a/src/main/java/appeng/services/export/CheckType.java +++ b/src/main/java/appeng/services/export/CheckType.java @@ -18,24 +18,23 @@ package appeng.services.export; - /** - * Defines a concrete result type when using the {@link Checker#isEqual(Object)} from the {@link Checker} class. + * Defines a concrete result type when using the {@link Checker#isEqual(Object)} from the + * {@link Checker} class. * * @author thatsIch * @version rv3 - 25.09.2015 * @see Checker * @since rv3 - 25.09.2015 */ -enum CheckType -{ - /** - * If checking resulted in both objects being equal - */ - EQUAL, +enum CheckType { + /** + * If checking resulted in both objects being equal + */ + EQUAL, - /** - * If checking resulted in both objects being unequal - */ - UNEQUAL + /** + * If checking resulted in both objects being unequal + */ + UNEQUAL } diff --git a/src/main/java/appeng/services/export/Checker.java b/src/main/java/appeng/services/export/Checker.java index 8486bf06..21bcc99d 100644 --- a/src/main/java/appeng/services/export/Checker.java +++ b/src/main/java/appeng/services/export/Checker.java @@ -18,10 +18,8 @@ package appeng.services.export; - import javax.annotation.Nonnull; - /** * Checks against a specific type with its own check type for clear outcome. *

@@ -31,13 +29,12 @@ import javax.annotation.Nonnull; * @version rv3 - 01.09.2015 * @since rv3 - 01.09.2015 */ -interface Checker -{ - /** - * @param checkedAgainst the object it is checked against - * @return non null being either equal or unequal - * @since rv3 - 01.09.2015 - */ - @Nonnull - CheckType isEqual( @Nonnull final T checkedAgainst ); +interface Checker { + /** + * @param checkedAgainst the object it is checked against + * @return non null being either equal or unequal + * @since rv3 - 01.09.2015 + */ + @Nonnull + CheckType isEqual(@Nonnull final T checkedAgainst); } diff --git a/src/main/java/appeng/services/export/ExportConfig.java b/src/main/java/appeng/services/export/ExportConfig.java index 8d57e6cc..a837d8e0 100644 --- a/src/main/java/appeng/services/export/ExportConfig.java +++ b/src/main/java/appeng/services/export/ExportConfig.java @@ -18,65 +18,63 @@ package appeng.services.export; - import javax.annotation.Nonnull; - /** * @author thatsIch * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public interface ExportConfig -{ - /** - * config switch to disable the exporting. - * if the recipes system is not used - * there is no reason to export them. - * Still can be useful for debugging purpose, - * thus not tying it to the recipe system directly. - * - * @return true if exporting is enabled - */ - boolean isExportingItemNamesEnabled(); +public interface ExportConfig { + /** + * config switch to disable the exporting. + * if the recipes system is not used + * there is no reason to export them. + * Still can be useful for debugging purpose, + * thus not tying it to the recipe system directly. + * + * @return true if exporting is enabled + */ + boolean isExportingItemNamesEnabled(); - /** - * config switch for using the digest cache. - * - * @return true if cache is enabled - */ - boolean isCacheEnabled(); + /** + * config switch for using the digest cache. + * + * @return true if cache is enabled + */ + boolean isCacheEnabled(); - /** - * config switch to always refresh the CSV. Might be useful to activate on debugging. - * - * @return true if force refresh is enabled - */ - boolean isForceRefreshEnabled(); + /** + * config switch to always refresh the CSV. Might be useful to activate on debugging. + * + * @return true if force refresh is enabled + */ + boolean isForceRefreshEnabled(); - /** - * config switch to export more information mostly used for debugging - * - * @return true if additional information are enabled - */ - boolean isAdditionalInformationEnabled(); + /** + * config switch to export more information mostly used for debugging + * + * @return true if additional information are enabled + */ + boolean isAdditionalInformationEnabled(); - /** - * Will get the cache from last session. Can be used to reduce I/O operations though containing itself calculation. - * - * @return a digest from the last calculation - */ - String getCache(); + /** + * Will get the cache from last session. Can be used to reduce I/O operations though + * containing itself calculation. + * + * @return a digest from the last calculation + */ + String getCache(); - /** - * sets the cache for the next session to reduce calculation overhead - * - * @param digest new digest for the cache - */ - void setCache( @Nonnull String digest ); + /** + * sets the cache for the next session to reduce calculation overhead + * + * @param digest new digest for the cache + */ + void setCache(@Nonnull String digest); - /** - * Will delegate the saving - */ - void save(); + /** + * Will delegate the saving + */ + void save(); } diff --git a/src/main/java/appeng/services/export/ExportMode.java b/src/main/java/appeng/services/export/ExportMode.java index 1c8a559f..d11e7f39 100644 --- a/src/main/java/appeng/services/export/ExportMode.java +++ b/src/main/java/appeng/services/export/ExportMode.java @@ -18,7 +18,6 @@ package appeng.services.export; - /** * Defines the different modes which need to be distinguished upon exporting. *

@@ -28,15 +27,14 @@ package appeng.services.export; * @version rv3 - 23.09.2015 * @since rv3 - 23.09.2015 */ -enum ExportMode -{ - /** - * Will provide general users with information required for recipe making - */ - MINIMAL, +enum ExportMode { + /** + * Will provide general users with information required for recipe making + */ + MINIMAL, - /** - * Will provide advanced users with information with debugging functionality - */ - VERBOSE + /** + * Will provide advanced users with information with debugging functionality + */ + VERBOSE } diff --git a/src/main/java/appeng/services/export/ExportProcess.java b/src/main/java/appeng/services/export/ExportProcess.java index 269fcc74..327993c7 100644 --- a/src/main/java/appeng/services/export/ExportProcess.java +++ b/src/main/java/appeng/services/export/ExportProcess.java @@ -18,6 +18,10 @@ package appeng.services.export; +import java.io.File; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nonnull; import appeng.core.AELog; import com.google.common.base.Preconditions; @@ -28,12 +32,6 @@ import cpw.mods.fml.common.registry.FMLControlledNamespacedRegistry; import cpw.mods.fml.common.registry.GameData; import net.minecraft.item.Item; -import javax.annotation.Nonnull; -import java.io.File; -import java.util.List; -import java.util.concurrent.TimeUnit; - - /** * Main entry point for exporting the CSV file *

@@ -43,85 +41,86 @@ import java.util.concurrent.TimeUnit; * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public class ExportProcess implements Runnable -{ - private static final String FORCE_REFRESH_MESSAGE = "Force Refresh enabled. Will ignore cache and export CSV content."; - private static final String CACHE_ENABLED_MESSAGE = "Cache is enabled. Checking for new mod configurations."; - private static final String EQUAL_CONTENT_MESSAGE = "Same mod configuration was found. Not updating CSV content."; - private static final String UNEQUAL_CONTENT_MESSAGE = "New mod configuration was found. Commencing exporting."; - private static final String CACHE_DISABLED_MESSAGE = "Cache is disabled. Commencing exporting."; - private static final String EXPORT_START_MESSAGE = "Item Exporting ( started )"; - private static final String EXPORT_END_MESSAGE = "Item Exporting ( ended after %s ms)"; +public class ExportProcess implements Runnable { + private static final String FORCE_REFRESH_MESSAGE + = "Force Refresh enabled. Will ignore cache and export CSV content."; + private static final String CACHE_ENABLED_MESSAGE + = "Cache is enabled. Checking for new mod configurations."; + private static final String EQUAL_CONTENT_MESSAGE + = "Same mod configuration was found. Not updating CSV content."; + private static final String UNEQUAL_CONTENT_MESSAGE + = "New mod configuration was found. Commencing exporting."; + private static final String CACHE_DISABLED_MESSAGE + = "Cache is disabled. Commencing exporting."; + private static final String EXPORT_START_MESSAGE = "Item Exporting ( started )"; + private static final String EXPORT_END_MESSAGE + = "Item Exporting ( ended after %s ms)"; - @Nonnull - private final File exportDirectory; - @Nonnull - private final Checker> modChecker; - @Nonnull - private final ExportConfig config; + @Nonnull + private final File exportDirectory; + @Nonnull + private final Checker> modChecker; + @Nonnull + private final ExportConfig config; - /** - * @param exportDirectory directory where the final CSV file will be exported to - * @param config configuration to manipulate the export process - */ - public ExportProcess( @Nonnull final File exportDirectory, @Nonnull final ExportConfig config ) - { - this.exportDirectory = Preconditions.checkNotNull( exportDirectory ); - this.config = Preconditions.checkNotNull( config ); + /** + * @param exportDirectory directory where the final CSV file will be exported to + * @param config configuration to manipulate the export process + */ + public ExportProcess( + @Nonnull final File exportDirectory, @Nonnull final ExportConfig config + ) { + this.exportDirectory = Preconditions.checkNotNull(exportDirectory); + this.config = Preconditions.checkNotNull(config); - this.modChecker = new ModListChecker( config ); - } + this.modChecker = new ModListChecker(config); + } - /** - * Will check and export if various config settings will lead to exporting the CSV file. - */ - @Override - public void run() - { - // no priority to this thread - Thread.yield(); + /** + * Will check and export if various config settings will lead to exporting the CSV + * file. + */ + @Override + public void run() { + // no priority to this thread + Thread.yield(); - // logic when to cancel the export process - if( this.config.isForceRefreshEnabled() ) - { - AELog.info( FORCE_REFRESH_MESSAGE ); - } - else - { - if( this.config.isCacheEnabled() ) - { - AELog.info( CACHE_ENABLED_MESSAGE ); + // logic when to cancel the export process + if (this.config.isForceRefreshEnabled()) { + AELog.info(FORCE_REFRESH_MESSAGE); + } else { + if (this.config.isCacheEnabled()) { + AELog.info(CACHE_ENABLED_MESSAGE); - final Loader loader = Loader.instance(); - final List mods = loader.getActiveModList(); + final Loader loader = Loader.instance(); + final List mods = loader.getActiveModList(); - if( this.modChecker.isEqual( mods ) == CheckType.EQUAL ) - { - AELog.info( EQUAL_CONTENT_MESSAGE ); + if (this.modChecker.isEqual(mods) == CheckType.EQUAL) { + AELog.info(EQUAL_CONTENT_MESSAGE); - return; - } - else - { - AELog.info( UNEQUAL_CONTENT_MESSAGE ); - } - } - else - { - AELog.info( CACHE_DISABLED_MESSAGE ); - } - } + return; + } else { + AELog.info(UNEQUAL_CONTENT_MESSAGE); + } + } else { + AELog.info(CACHE_DISABLED_MESSAGE); + } + } - AELog.info( EXPORT_START_MESSAGE ); - final Stopwatch watch = Stopwatch.createStarted(); + AELog.info(EXPORT_START_MESSAGE); + final Stopwatch watch = Stopwatch.createStarted(); - final FMLControlledNamespacedRegistry itemRegistry = GameData.getItemRegistry(); + final FMLControlledNamespacedRegistry itemRegistry + = GameData.getItemRegistry(); - final ExportMode mode = this.config.isAdditionalInformationEnabled() ? ExportMode.VERBOSE : ExportMode.MINIMAL; - final Exporter exporter = new MinecraftItemCSVExporter( this.exportDirectory, itemRegistry, mode ); + final ExportMode mode = this.config.isAdditionalInformationEnabled() + ? ExportMode.VERBOSE + : ExportMode.MINIMAL; + final Exporter exporter + = new MinecraftItemCSVExporter(this.exportDirectory, itemRegistry, mode); - exporter.export(); + exporter.export(); - AELog.info( EXPORT_END_MESSAGE, watch.elapsed( TimeUnit.MILLISECONDS ) ); - } + AELog.info(EXPORT_END_MESSAGE, watch.elapsed(TimeUnit.MILLISECONDS)); + } } diff --git a/src/main/java/appeng/services/export/Exporter.java b/src/main/java/appeng/services/export/Exporter.java index 4bd5aa64..66407057 100644 --- a/src/main/java/appeng/services/export/Exporter.java +++ b/src/main/java/appeng/services/export/Exporter.java @@ -18,7 +18,6 @@ package appeng.services.export; - /** * General purpose interface to define an export operation with side effects * @@ -26,10 +25,9 @@ package appeng.services.export; * @version rv3 - 19.08.2015 * @since rv3 19.08.2015 */ -interface Exporter -{ - /** - * Will export something defined by the Exporter with side effects - */ - void export(); +interface Exporter { + /** + * Will export something defined by the Exporter with side effects + */ + void export(); } diff --git a/src/main/java/appeng/services/export/ForgeExportConfig.java b/src/main/java/appeng/services/export/ForgeExportConfig.java index 83804087..d6f76838 100644 --- a/src/main/java/appeng/services/export/ForgeExportConfig.java +++ b/src/main/java/appeng/services/export/ForgeExportConfig.java @@ -18,14 +18,12 @@ package appeng.services.export; +import javax.annotation.Nonnull; import com.google.common.base.Preconditions; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; -import javax.annotation.Nonnull; - - /** * Offers configuration switches for the user to change the export process * @@ -33,96 +31,116 @@ import javax.annotation.Nonnull; * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -public final class ForgeExportConfig implements ExportConfig -{ - private static final String GENERAL_CATEGORY = "general"; - private static final String CACHE_CATEGORY = "cache"; +public final class ForgeExportConfig implements ExportConfig { + private static final String GENERAL_CATEGORY = "general"; + private static final String CACHE_CATEGORY = "cache"; - private static final String EXPORT_ITEM_NAMES_KEY = "exportItemNames"; - private static final boolean EXPORT_ITEM_NAMES_DEFAULT = true; - private static final String EXPORT_ITEM_NAMES_DESCRIPTION = "If true, all registered items will be exported containing the internal minecraft name and the localized name to actually find the item you are using. This also contains the item representation of the blocks, but are missing items, which are too much to display e.g. FMP."; + private static final String EXPORT_ITEM_NAMES_KEY = "exportItemNames"; + private static final boolean EXPORT_ITEM_NAMES_DEFAULT = true; + private static final String EXPORT_ITEM_NAMES_DESCRIPTION + = "If true, all registered items will be exported containing the internal minecraft name and the localized name to actually find the item you are using. This also contains the item representation of the blocks, but are missing items, which are too much to display e.g. FMP."; - private static final String ENABLE_FORCE_REFRESH_KEY = "enableForceRefresh"; - private static final boolean ENABLE_FORCE_REFRESH_DEFAULT = false; - private static final String ENABLE_FORCE_REFRESH_DESCRIPTION = "If true, the CSV exporting will always happen. This will not use the cache to reduce the computation."; + private static final String ENABLE_FORCE_REFRESH_KEY = "enableForceRefresh"; + private static final boolean ENABLE_FORCE_REFRESH_DEFAULT = false; + private static final String ENABLE_FORCE_REFRESH_DESCRIPTION + = "If true, the CSV exporting will always happen. This will not use the cache to reduce the computation."; - private static final String ENABLE_CACHE_KEY = "enableCache"; - private static final boolean ENABLE_CACHE_DEFAULT = true; - private static final String ENABLE_CACHE_DESCRIPTION = "Caching can save processing time, if there are a lot of items."; + private static final String ENABLE_CACHE_KEY = "enableCache"; + private static final boolean ENABLE_CACHE_DEFAULT = true; + private static final String ENABLE_CACHE_DESCRIPTION + = "Caching can save processing time, if there are a lot of items."; - private static final String ENABLE_ADDITIONAL_INFO_KEY = "enableAdditionalInfo"; - private static final boolean ENABLE_ADDITIONAL_INFO_DEFAULT = false; - private static final String ENABLE_ADDITIONAL_INFO_DESCRIPTION = "Will output more detailed information into the CSV like corresponding items"; + private static final String ENABLE_ADDITIONAL_INFO_KEY = "enableAdditionalInfo"; + private static final boolean ENABLE_ADDITIONAL_INFO_DEFAULT = false; + private static final String ENABLE_ADDITIONAL_INFO_DESCRIPTION + = "Will output more detailed information into the CSV like corresponding items"; - private static final String DIGEST_KEY = "digest"; - private static final String DIGEST_DEFAULT = ""; - private static final String DIGEST_DESCRIPTION = "Digest of all the mods and versions to check if a re-export of the item names is required."; + private static final String DIGEST_KEY = "digest"; + private static final String DIGEST_DEFAULT = ""; + private static final String DIGEST_DESCRIPTION + = "Digest of all the mods and versions to check if a re-export of the item names is required."; - private final boolean exportItemNamesEnabled; - private final boolean cacheEnabled; - private final boolean forceRefreshEnabled; - private final boolean additionalInformationEnabled; - private final String cache; - private final Configuration config; + private final boolean exportItemNamesEnabled; + private final boolean cacheEnabled; + private final boolean forceRefreshEnabled; + private final boolean additionalInformationEnabled; + private final String cache; + private final Configuration config; - /** - * Constructor using the configuration. Apparently there are some race conditions if constructing configurations on multiple file accesses - * - * @param config to be wrapped configuration. - */ - public ForgeExportConfig( @Nonnull final Configuration config ) - { - this.config = Preconditions.checkNotNull( config ); + /** + * Constructor using the configuration. Apparently there are some race conditions if + * constructing configurations on multiple file accesses + * + * @param config to be wrapped configuration. + */ + public ForgeExportConfig(@Nonnull final Configuration config) { + this.config = Preconditions.checkNotNull(config); - this.exportItemNamesEnabled = this.config.getBoolean( EXPORT_ITEM_NAMES_KEY, GENERAL_CATEGORY, EXPORT_ITEM_NAMES_DEFAULT, EXPORT_ITEM_NAMES_DESCRIPTION ); - this.cacheEnabled = this.config.getBoolean( ENABLE_CACHE_KEY, CACHE_CATEGORY, ENABLE_CACHE_DEFAULT, ENABLE_CACHE_DESCRIPTION ); - this.additionalInformationEnabled = this.config.getBoolean( ENABLE_ADDITIONAL_INFO_KEY, GENERAL_CATEGORY, ENABLE_ADDITIONAL_INFO_DEFAULT, ENABLE_ADDITIONAL_INFO_DESCRIPTION ); - this.cache = this.config.getString( DIGEST_KEY, CACHE_CATEGORY, DIGEST_DEFAULT, DIGEST_DESCRIPTION ); - this.forceRefreshEnabled = this.config.getBoolean( ENABLE_FORCE_REFRESH_KEY, GENERAL_CATEGORY, ENABLE_FORCE_REFRESH_DEFAULT, ENABLE_FORCE_REFRESH_DESCRIPTION ); - } + this.exportItemNamesEnabled = this.config.getBoolean( + EXPORT_ITEM_NAMES_KEY, + GENERAL_CATEGORY, + EXPORT_ITEM_NAMES_DEFAULT, + EXPORT_ITEM_NAMES_DESCRIPTION + ); + this.cacheEnabled = this.config.getBoolean( + ENABLE_CACHE_KEY, + CACHE_CATEGORY, + ENABLE_CACHE_DEFAULT, + ENABLE_CACHE_DESCRIPTION + ); + this.additionalInformationEnabled = this.config.getBoolean( + ENABLE_ADDITIONAL_INFO_KEY, + GENERAL_CATEGORY, + ENABLE_ADDITIONAL_INFO_DEFAULT, + ENABLE_ADDITIONAL_INFO_DESCRIPTION + ); + this.cache = this.config.getString( + DIGEST_KEY, CACHE_CATEGORY, DIGEST_DEFAULT, DIGEST_DESCRIPTION + ); + this.forceRefreshEnabled = this.config.getBoolean( + ENABLE_FORCE_REFRESH_KEY, + GENERAL_CATEGORY, + ENABLE_FORCE_REFRESH_DEFAULT, + ENABLE_FORCE_REFRESH_DESCRIPTION + ); + } - @Override - public boolean isExportingItemNamesEnabled() - { - return this.exportItemNamesEnabled; - } + @Override + public boolean isExportingItemNamesEnabled() { + return this.exportItemNamesEnabled; + } - @Override - public boolean isCacheEnabled() - { - return this.cacheEnabled; - } + @Override + public boolean isCacheEnabled() { + return this.cacheEnabled; + } - @Override - public boolean isForceRefreshEnabled() - { - return this.forceRefreshEnabled; - } + @Override + public boolean isForceRefreshEnabled() { + return this.forceRefreshEnabled; + } - @Override - public boolean isAdditionalInformationEnabled() - { - return this.additionalInformationEnabled; - } + @Override + public boolean isAdditionalInformationEnabled() { + return this.additionalInformationEnabled; + } - @Override - public String getCache() - { - return this.cache; - } + @Override + public String getCache() { + return this.cache; + } - @Override - public void setCache( @Nonnull final String digest ) - { - final Property digestProperty = this.config.get( CACHE_CATEGORY, DIGEST_KEY, DIGEST_DEFAULT ); - digestProperty.set( digest ); + @Override + public void setCache(@Nonnull final String digest) { + final Property digestProperty + = this.config.get(CACHE_CATEGORY, DIGEST_KEY, DIGEST_DEFAULT); + digestProperty.set(digest); - this.config.save(); - } + this.config.save(); + } - @Override - public void save() - { - this.config.save(); - } + @Override + public void save() { + this.config.save(); + } } diff --git a/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java b/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java index c2a72b0f..b641006c 100644 --- a/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java +++ b/src/main/java/appeng/services/export/MinecraftItemCSVExporter.java @@ -18,6 +18,11 @@ package appeng.services.export; +import java.io.*; +import java.nio.charset.Charset; +import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.core.AELog; import com.google.common.base.Function; @@ -33,252 +38,255 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; import org.apache.commons.io.FileUtils; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.*; -import java.nio.charset.Charset; -import java.util.List; - - /** - * handles the exporting including processing, transformation and persisting the information + * handles the exporting including processing, transformation and persisting the + * information * * @author thatsIch * @version rv3 - 14.08.2015 * @since rv3 14.08.2015 */ -final class MinecraftItemCSVExporter implements Exporter -{ - private static final String ITEM_CSV_FILE_NAME = "items.csv"; - private static final String MINIMAL_HEADER = "Mod:Item:MetaData, Localized Name"; - private static final String VERBOSE_HEADER = MINIMAL_HEADER + ", Unlocalized Name, Is Air?, Class Name"; - private static final String EXPORT_SUCCESSFUL_MESSAGE = "Exported successfully %d items into %s"; - private static final String EXPORT_UNSUCCESSFUL_MESSAGE = "Exporting was unsuccessful."; +final class MinecraftItemCSVExporter implements Exporter { + private static final String ITEM_CSV_FILE_NAME = "items.csv"; + private static final String MINIMAL_HEADER = "Mod:Item:MetaData, Localized Name"; + private static final String VERBOSE_HEADER + = MINIMAL_HEADER + ", Unlocalized Name, Is Air?, Class Name"; + private static final String EXPORT_SUCCESSFUL_MESSAGE + = "Exported successfully %d items into %s"; + private static final String EXPORT_UNSUCCESSFUL_MESSAGE + = "Exporting was unsuccessful."; - @Nonnull - private final File exportDirectory; - @Nonnull - private final FMLControlledNamespacedRegistry itemRegistry; - @Nonnull - private final ExportMode mode; + @Nonnull + private final File exportDirectory; + @Nonnull + private final FMLControlledNamespacedRegistry itemRegistry; + @Nonnull + private final ExportMode mode; - /** - * @param exportDirectory directory of the resulting export file. Non-null required. - * @param itemRegistry the registry with minecraft items. Needs to be populated at that time, thus the exporting can - * only happen in init (pre-init is the - * phase when all items are determined) - * @param mode mode in which the export should be operated. Resulting CSV will change depending on this. - */ - MinecraftItemCSVExporter( @Nonnull final File exportDirectory, @Nonnull final FMLControlledNamespacedRegistry itemRegistry, @Nonnull final ExportMode mode ) - { - this.exportDirectory = Preconditions.checkNotNull( exportDirectory ); - Preconditions.checkArgument( !exportDirectory.isFile() ); - this.itemRegistry = Preconditions.checkNotNull( itemRegistry ); - this.mode = Preconditions.checkNotNull( mode ); - } + /** + * @param exportDirectory directory of the resulting export file. Non-null required. + * @param itemRegistry the registry with minecraft items. Needs to be populated at + * that time, thus the exporting can + * only happen in init (pre-init is the + * phase when all items are determined) + * @param mode mode in which the export should be operated. Resulting CSV + * will change depending on this. + */ + MinecraftItemCSVExporter( + @Nonnull final File exportDirectory, + @Nonnull final FMLControlledNamespacedRegistry itemRegistry, + @Nonnull final ExportMode mode + ) { + this.exportDirectory = Preconditions.checkNotNull(exportDirectory); + Preconditions.checkArgument(!exportDirectory.isFile()); + this.itemRegistry = Preconditions.checkNotNull(itemRegistry); + this.mode = Preconditions.checkNotNull(mode); + } - @Override - public void export() - { - final Iterable items = this.itemRegistry.typeSafeIterable(); - final List itemList = Lists.newArrayList( items ); + @Override + public void export() { + final Iterable items = this.itemRegistry.typeSafeIterable(); + final List itemList = Lists.newArrayList(items); - final List lines = Lists.transform( itemList, new ItemRowExtractFunction( this.itemRegistry, this.mode ) ); + final List lines = Lists.transform( + itemList, new ItemRowExtractFunction(this.itemRegistry, this.mode) + ); - final Joiner newLineJoiner = Joiner.on( '\n' ); - final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls(); - final String joined = newLineJoinerIgnoringNull.join( lines ); + final Joiner newLineJoiner = Joiner.on('\n'); + final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls(); + final String joined = newLineJoinerIgnoringNull.join(lines); - final File file = new File( this.exportDirectory, ITEM_CSV_FILE_NAME ); + final File file = new File(this.exportDirectory, ITEM_CSV_FILE_NAME); - try - { - FileUtils.forceMkdir( this.exportDirectory ); + try { + FileUtils.forceMkdir(this.exportDirectory); - final Writer writer = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( file ), Charset.forName( "UTF-8" ) ) ); + final Writer writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(file), Charset.forName("UTF-8") + )); - final String header = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER; - writer.write( header ); - writer.write( "\n" ); - writer.write( joined ); - writer.flush(); - writer.close(); + final String header + = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER; + writer.write(header); + writer.write("\n"); + writer.write(joined); + writer.flush(); + writer.close(); - AELog.info( EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME ); - } - catch( final IOException e ) - { - AELog.warn( EXPORT_UNSUCCESSFUL_MESSAGE ); - AELog.debug( e ); - } - } + AELog.info(EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME); + } catch (final IOException e) { + AELog.warn(EXPORT_UNSUCCESSFUL_MESSAGE); + AELog.debug(e); + } + } - /** - * Extracts item name with meta and the display name - */ - private static final class TypeExtractFunction implements Function - { - private static final String EXTRACTING_NULL_MESSAGE = "extracting type null"; - private static final String EXTRACTING_ITEM_MESSAGE = "extracting type %s:%d"; + /** + * Extracts item name with meta and the display name + */ + private static final class TypeExtractFunction + implements Function { + private static final String EXTRACTING_NULL_MESSAGE = "extracting type null"; + private static final String EXTRACTING_ITEM_MESSAGE = "extracting type %s:%d"; - @Nonnull - private final String itemName; - @Nonnull - private final ExportMode mode; + @Nonnull + private final String itemName; + @Nonnull + private final ExportMode mode; - private TypeExtractFunction( @Nonnull final String itemName, @Nonnull final ExportMode mode ) - { - this.itemName = Preconditions.checkNotNull( itemName ); - Preconditions.checkArgument( !itemName.isEmpty() ); + private TypeExtractFunction( + @Nonnull final String itemName, @Nonnull final ExportMode mode + ) { + this.itemName = Preconditions.checkNotNull(itemName); + Preconditions.checkArgument(!itemName.isEmpty()); - this.mode = Preconditions.checkNotNull( mode ); - } + this.mode = Preconditions.checkNotNull(mode); + } - @Nullable - @Override - public String apply( @Nullable final ItemStack input ) - { - if( input == null ) - { - AELog.debug( EXTRACTING_NULL_MESSAGE ); + @Nullable + @Override + public String apply(@Nullable final ItemStack input) { + if (input == null) { + AELog.debug(EXTRACTING_NULL_MESSAGE); - return null; - } - else - { - AELog.debug( EXTRACTING_ITEM_MESSAGE, input.getDisplayName(), input.getItemDamage() ); - } + return null; + } else { + AELog.debug( + EXTRACTING_ITEM_MESSAGE, input.getDisplayName(), input.getItemDamage() + ); + } - final List joinedBlockAttributes = Lists.newArrayListWithCapacity( 5 ); - final int meta = input.getItemDamage(); - final String metaName = this.itemName + ':' + meta; - final String localization = input.getDisplayName(); + final List joinedBlockAttributes = Lists.newArrayListWithCapacity(5); + final int meta = input.getItemDamage(); + final String metaName = this.itemName + ':' + meta; + final String localization = input.getDisplayName(); - joinedBlockAttributes.add( metaName ); - joinedBlockAttributes.add( localization ); + joinedBlockAttributes.add(metaName); + joinedBlockAttributes.add(localization); - if( this.mode == ExportMode.VERBOSE ) - { - final Item item = input.getItem(); - final String unlocalizedItem = input.getUnlocalizedName(); - final Block block = Block.getBlockFromItem( item ); - final boolean isBlock = !block.equals( Blocks.air ); - final Class stackClass = input.getClass(); - final String stackClassName = stackClass.getName(); + if (this.mode == ExportMode.VERBOSE) { + final Item item = input.getItem(); + final String unlocalizedItem = input.getUnlocalizedName(); + final Block block = Block.getBlockFromItem(item); + final boolean isBlock = !block.equals(Blocks.air); + final Class stackClass = input.getClass(); + final String stackClassName = stackClass.getName(); - joinedBlockAttributes.add( unlocalizedItem ); - joinedBlockAttributes.add( Boolean.toString( isBlock ) ); - joinedBlockAttributes.add( stackClassName ); - } + joinedBlockAttributes.add(unlocalizedItem); + joinedBlockAttributes.add(Boolean.toString(isBlock)); + joinedBlockAttributes.add(stackClassName); + } - final Joiner csvJoiner = Joiner.on( ", " ); - final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); + final Joiner csvJoiner = Joiner.on(", "); + final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); - return csvJoinerIgnoringNulls.join( joinedBlockAttributes ); - } - } + return csvJoinerIgnoringNulls.join(joinedBlockAttributes); + } + } + /** + * transforms an item into a row representation of the CSV file + */ + private static final class ItemRowExtractFunction implements Function { + /** + * this extension is required to apply the {@link StatCollector} + */ + private static final String LOCALIZATION_NAME_EXTENSION = ".name"; + private static final String EXPORTING_NOTHING_MESSAGE = "Exporting nothing"; + private static final String EXPORTING_SUBTYPES_MESSAGE + = "Exporting input %s with subtypes: %b"; + private static final String EXPORTING_SUBTYPES_FAILED_MESSAGE + = "Could not export subtypes of: %s"; - /** - * transforms an item into a row representation of the CSV file - */ - private static final class ItemRowExtractFunction implements Function - { - /** - * this extension is required to apply the {@link StatCollector} - */ - private static final String LOCALIZATION_NAME_EXTENSION = ".name"; - private static final String EXPORTING_NOTHING_MESSAGE = "Exporting nothing"; - private static final String EXPORTING_SUBTYPES_MESSAGE = "Exporting input %s with subtypes: %b"; - private static final String EXPORTING_SUBTYPES_FAILED_MESSAGE = "Could not export subtypes of: %s"; + @Nonnull + private final FMLControlledNamespacedRegistry itemRegistry; + @Nonnull + private final ExportMode mode; - @Nonnull - private final FMLControlledNamespacedRegistry itemRegistry; - @Nonnull - private final ExportMode mode; + /** + * @param itemRegistry used to retrieve the name of the item + * @param mode extracts more or less information from item depending on + * mode + */ + ItemRowExtractFunction( + @Nonnull final FMLControlledNamespacedRegistry itemRegistry, + @Nonnull final ExportMode mode + ) { + this.itemRegistry = Preconditions.checkNotNull(itemRegistry); + this.mode = Preconditions.checkNotNull(mode); + } - /** - * @param itemRegistry used to retrieve the name of the item - * @param mode extracts more or less information from item depending on mode - */ - ItemRowExtractFunction( @Nonnull final FMLControlledNamespacedRegistry itemRegistry, @Nonnull final ExportMode mode ) - { - this.itemRegistry = Preconditions.checkNotNull( itemRegistry ); - this.mode = Preconditions.checkNotNull( mode ); - } + @Nullable + @Override + public String apply(@Nullable final Item input) { + if (input == null) { + AELog.debug(EXPORTING_NOTHING_MESSAGE); - @Nullable - @Override - public String apply( @Nullable final Item input ) - { - if( input == null ) - { - AELog.debug( EXPORTING_NOTHING_MESSAGE ); + return null; + } else { + AELog.debug( + EXPORTING_SUBTYPES_MESSAGE, + input.getUnlocalizedName(), + input.getHasSubtypes() + ); + } - return null; - } - else - { - AELog.debug( EXPORTING_SUBTYPES_MESSAGE, input.getUnlocalizedName(), input.getHasSubtypes() ); - } + final String itemName = this.itemRegistry.getNameForObject(input); + final boolean hasSubtypes = input.getHasSubtypes(); + if (hasSubtypes) { + final CreativeTabs creativeTab = input.getCreativeTab(); + final List stacks = Lists.newArrayList(); - final String itemName = this.itemRegistry.getNameForObject( input ); - final boolean hasSubtypes = input.getHasSubtypes(); - if( hasSubtypes ) - { - final CreativeTabs creativeTab = input.getCreativeTab(); - final List stacks = Lists.newArrayList(); + // modifies the stacks list and adds the different sub types to it + try { + input.getSubItems(input, creativeTab, stacks); + } catch (final Exception ignored) { + AELog.warn( + EXPORTING_SUBTYPES_FAILED_MESSAGE, input.getUnlocalizedName() + ); + AELog.debug(ignored); - // modifies the stacks list and adds the different sub types to it - try - { - input.getSubItems( input, creativeTab, stacks ); - } - catch( final Exception ignored ) - { - AELog.warn( EXPORTING_SUBTYPES_FAILED_MESSAGE, input.getUnlocalizedName() ); - AELog.debug( ignored ); + // ignore if mods do bullshit in their code + return null; + } - // ignore if mods do bullshit in their code - return null; - } + // list can be empty, no clue why + if (stacks.isEmpty()) { + return null; + } - // list can be empty, no clue why - if( stacks.isEmpty() ) - { - return null; - } + final Joiner newLineJoiner = Joiner.on('\n'); + final Joiner typeJoiner = newLineJoiner.skipNulls(); + final List transformedTypes = Lists.transform( + stacks, new TypeExtractFunction(itemName, this.mode) + ); - final Joiner newLineJoiner = Joiner.on( '\n' ); - final Joiner typeJoiner = newLineJoiner.skipNulls(); - final List transformedTypes = Lists.transform( stacks, new TypeExtractFunction( itemName, this.mode ) ); + return typeJoiner.join(transformedTypes); + } - return typeJoiner.join( transformedTypes ); - } + final List joinedBlockAttributes = Lists.newArrayListWithCapacity(5); + final String unlocalizedItem = input.getUnlocalizedName(); + final String localization = StatCollector.translateToLocal( + unlocalizedItem + LOCALIZATION_NAME_EXTENSION + ); - final List joinedBlockAttributes = Lists.newArrayListWithCapacity( 5 ); - final String unlocalizedItem = input.getUnlocalizedName(); - final String localization = StatCollector.translateToLocal( unlocalizedItem + LOCALIZATION_NAME_EXTENSION ); + joinedBlockAttributes.add(itemName); + joinedBlockAttributes.add(localization); - joinedBlockAttributes.add( itemName ); - joinedBlockAttributes.add( localization ); + if (this.mode == ExportMode.VERBOSE) { + final Block block = Block.getBlockFromItem(input); + final boolean isBlock = !block.equals(Blocks.air); + final Class itemClass = input.getClass(); + final String itemClassName = itemClass.getName(); - if( this.mode == ExportMode.VERBOSE ) - { - final Block block = Block.getBlockFromItem( input ); - final boolean isBlock = !block.equals( Blocks.air ); - final Class itemClass = input.getClass(); - final String itemClassName = itemClass.getName(); + joinedBlockAttributes.add(unlocalizedItem); + joinedBlockAttributes.add(Boolean.toString(isBlock)); + joinedBlockAttributes.add(itemClassName); + } - joinedBlockAttributes.add( unlocalizedItem ); - joinedBlockAttributes.add( Boolean.toString( isBlock ) ); - joinedBlockAttributes.add( itemClassName ); - } + final Joiner csvJoiner = Joiner.on(", "); + final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); - final Joiner csvJoiner = Joiner.on( ", " ); - final Joiner csvJoinerIgnoringNulls = csvJoiner.skipNulls(); - - return csvJoinerIgnoringNulls.join( joinedBlockAttributes ); - } - } + return csvJoinerIgnoringNulls.join(joinedBlockAttributes); + } + } } diff --git a/src/main/java/appeng/services/export/ModListChecker.java b/src/main/java/appeng/services/export/ModListChecker.java index 8c5e4443..806e99a3 100644 --- a/src/main/java/appeng/services/export/ModListChecker.java +++ b/src/main/java/appeng/services/export/ModListChecker.java @@ -18,15 +18,13 @@ package appeng.services.export; +import java.util.List; +import javax.annotation.Nonnull; import com.google.common.base.Preconditions; import cpw.mods.fml.common.ModContainer; import org.apache.commons.codec.digest.DigestUtils; -import javax.annotation.Nonnull; -import java.util.List; - - /** * Checks the cached digest against the current mods including their versions. * Use the config to manipulate the process @@ -35,55 +33,50 @@ import java.util.List; * @version rv3 - 01.09.2015 * @since rv3 - 01.09.2015 */ -final class ModListChecker implements Checker> -{ - private final String configHashValue; +final class ModListChecker implements Checker> { + private final String configHashValue; - @Nonnull - private final ExportConfig config; + @Nonnull + private final ExportConfig config; - /** - * @param config uses the config to retrieve the old hash of the mod list - */ - ModListChecker( @Nonnull final ExportConfig config ) - { - this.config = Preconditions.checkNotNull( config ); - this.configHashValue = Preconditions.checkNotNull( config.getCache() ); - } + /** + * @param config uses the config to retrieve the old hash of the mod list + */ + ModListChecker(@Nonnull final ExportConfig config) { + this.config = Preconditions.checkNotNull(config); + this.configHashValue = Preconditions.checkNotNull(config.getCache()); + } - /** - * Compiles a list of all mods and their versions to a digest which is updated, if it differs from the config. This is used to elevate the need to export - * the csv once again, if no change was detected. - * - * @param modContainers all mods and their versions to check if a difference exists between the current instance and the previous instance - * @return CheckType.EQUAL if no change was detected - */ - @Nonnull - @Override - public CheckType isEqual( @Nonnull final List modContainers ) - { - Preconditions.checkNotNull( modContainers ); + /** + * Compiles a list of all mods and their versions to a digest which is updated, if it + * differs from the config. This is used to elevate the need to export the csv once + * again, if no change was detected. + * + * @param modContainers all mods and their versions to check if a difference exists + * between the current instance and the previous instance + * @return CheckType.EQUAL if no change was detected + */ + @Nonnull + @Override + public CheckType isEqual(@Nonnull final List modContainers) { + Preconditions.checkNotNull(modContainers); - final StringBuilder builder = new StringBuilder(); + final StringBuilder builder = new StringBuilder(); - for( final ModContainer container : modContainers ) - { - builder.append( container.getModId() ); - builder.append( container.getVersion() ); - } + for (final ModContainer container : modContainers) { + builder.append(container.getModId()); + builder.append(container.getVersion()); + } - final String allModsAndVersions = builder.toString(); - final String hex = DigestUtils.md5Hex( allModsAndVersions ); + final String allModsAndVersions = builder.toString(); + final String hex = DigestUtils.md5Hex(allModsAndVersions); - if( hex.equals( this.configHashValue ) ) - { - return CheckType.EQUAL; - } - else - { - this.config.setCache( hex ); + if (hex.equals(this.configHashValue)) { + return CheckType.EQUAL; + } else { + this.config.setCache(hex); - return CheckType.UNEQUAL; - } - } + return CheckType.UNEQUAL; + } + } } diff --git a/src/main/java/appeng/services/export/package-info.java b/src/main/java/appeng/services/export/package-info.java index 8d212f17..78a049d4 100644 --- a/src/main/java/appeng/services/export/package-info.java +++ b/src/main/java/appeng/services/export/package-info.java @@ -17,13 +17,11 @@ */ /** - * the export package is to export all the required information for recipes into a convenient CSV file - * often names are difficult to acquire without access to the internal names. - *

- * To save from rescanning every start-up it can save a list of mods and their version - * and if only something changed, it requires to update the CSV. - *

- * There is no explicit check if it was manually tempered + * the export package is to export all the required information for recipes into a + * convenient CSV file often names are difficult to acquire without access to the internal + * names.

To save from rescanning every start-up it can save a list of mods and their + * version and if only something changed, it requires to update the CSV.

There is no + * explicit check if it was manually tempered * * @author thatsIch * @version rv3 - 14.08.2015 diff --git a/src/main/java/appeng/services/version/BaseVersion.java b/src/main/java/appeng/services/version/BaseVersion.java index 8ea58471..b216eac3 100644 --- a/src/main/java/appeng/services/version/BaseVersion.java +++ b/src/main/java/appeng/services/version/BaseVersion.java @@ -18,109 +18,98 @@ package appeng.services.version; - -import com.google.common.base.Preconditions; - import javax.annotation.Nonnegative; import javax.annotation.Nonnull; +import com.google.common.base.Preconditions; /** * Base version of {@link Version}. *

* Provides a unified way to test for equality and print a formatted string */ -public abstract class BaseVersion implements Version -{ - @Nonnegative - private final int revision; - @Nonnull - private final Channel channel; - @Nonnegative - private final int build; +public abstract class BaseVersion implements Version { + @Nonnegative + private final int revision; + @Nonnull + private final Channel channel; + @Nonnegative + private final int build; - /** - * @param revision revision 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 - */ - public BaseVersion( @Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build ) - { - Preconditions.checkArgument( revision >= 0 ); - Preconditions.checkNotNull( channel ); - Preconditions.checkArgument( build >= 0 ); + /** + * @param revision revision 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 + */ + public BaseVersion( + @Nonnegative final int revision, + @Nonnull final Channel channel, + @Nonnegative final int build + ) { + Preconditions.checkArgument(revision >= 0); + Preconditions.checkNotNull(channel); + Preconditions.checkArgument(build >= 0); - this.revision = revision; - this.channel = channel; - this.build = build; - } + this.revision = revision; + this.channel = channel; + this.build = build; + } - @Override - public final int revision() - { - return this.revision; - } + @Override + public final int revision() { + return this.revision; + } - @Override - public final Channel channel() - { - return this.channel; - } + @Override + public final Channel channel() { + return this.channel; + } - @Override - public final int build() - { - return this.build; - } + @Override + public final int build() { + return this.build; + } - @Override - public String formatted() - { - return "rv" + this.revision + '-' + this.channel.name().toLowerCase() + '-' + this.build; - } + @Override + public String formatted() { + return "rv" + this.revision + '-' + this.channel.name().toLowerCase() + '-' + + this.build; + } - @Override - public final int hashCode() - { - int result = this.revision; - result = 31 * result + this.channel.hashCode(); - result = 31 * result + this.build; - return result; - } + @Override + public final int hashCode() { + int result = this.revision; + result = 31 * result + this.channel.hashCode(); + result = 31 * result + this.build; + return result; + } - @Override - public final boolean equals( final Object o ) - { - if( this == o ) - { - return true; - } - if( !( o instanceof Version ) ) - { - return false; - } + @Override + public final boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Version)) { + return false; + } - final Version that = (Version) o; + final Version that = (Version) o; - if( this.revision != that.revision() ) - { - return false; - } - if( this.build != that.build() ) - { - return false; - } - return this.channel == that.channel(); - } + if (this.revision != that.revision()) { + return false; + } + if (this.build != that.build()) { + return false; + } + return this.channel == that.channel(); + } - @Override - public final String toString() - { - return "Version{" + - "revision=" + this.revision + - ", channel=" + this.channel + - ", build=" + this.build + - '}'; - } + @Override + public final String toString() { + return "Version{" + + "revision=" + this.revision + ", channel=" + this.channel + + ", build=" + this.build + '}'; + } } diff --git a/src/main/java/appeng/services/version/Channel.java b/src/main/java/appeng/services/version/Channel.java index 397ed836..1f1c5d7a 100644 --- a/src/main/java/appeng/services/version/Channel.java +++ b/src/main/java/appeng/services/version/Channel.java @@ -18,14 +18,8 @@ package appeng.services.version; - /** - * Represents the release channel of Applied Energistics. The mod is either in Alpha, Beta or Stable channel. - * Any more might be confusing to the end-user + * Represents the release channel of Applied Energistics. The mod is either in Alpha, Beta + * or Stable channel. Any more might be confusing to the end-user */ -public enum Channel -{ - Alpha, - Beta, - Stable -} +public enum Channel { Alpha, Beta, Stable } diff --git a/src/main/java/appeng/services/version/DefaultVersion.java b/src/main/java/appeng/services/version/DefaultVersion.java index bcd4bd6b..eea54547 100644 --- a/src/main/java/appeng/services/version/DefaultVersion.java +++ b/src/main/java/appeng/services/version/DefaultVersion.java @@ -18,39 +18,35 @@ package appeng.services.version; - import javax.annotation.Nonnegative; import javax.annotation.Nonnull; - /** * AE prints version like rv2-beta-8 * GitHub prints version like rv2.beta.8 */ -public final class DefaultVersion extends BaseVersion -{ - /** - * @param revision natural number - * @param channel either alpha, beta or release - * @param build natural number - */ - public DefaultVersion( @Nonnegative final int revision, @Nonnull final Channel channel, @Nonnegative final int build ) - { - super( revision, channel, build ); - } +public final class DefaultVersion extends BaseVersion { + /** + * @param revision natural number + * @param channel either alpha, beta or release + * @param build natural number + */ + public DefaultVersion( + @Nonnegative final int revision, + @Nonnull final Channel channel, + @Nonnegative final int build + ) { + super(revision, channel, build); + } - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - if( this.revision() == maybeOlder.revision() ) - { - if( this.channel().compareTo( maybeOlder.channel() ) == 0 ) - { - return this.build() > maybeOlder.build(); - } - return this.channel().compareTo( maybeOlder.channel() ) > 0; - } - else - return this.revision() > maybeOlder.revision(); - } + @Override + public boolean isNewerAs(final Version maybeOlder) { + if (this.revision() == maybeOlder.revision()) { + if (this.channel().compareTo(maybeOlder.channel()) == 0) { + return this.build() > maybeOlder.build(); + } + return this.channel().compareTo(maybeOlder.channel()) > 0; + } else + return this.revision() > maybeOlder.revision(); + } } diff --git a/src/main/java/appeng/services/version/DoNotCheckVersion.java b/src/main/java/appeng/services/version/DoNotCheckVersion.java index 9edff745..97fa55b9 100644 --- a/src/main/java/appeng/services/version/DoNotCheckVersion.java +++ b/src/main/java/appeng/services/version/DoNotCheckVersion.java @@ -18,26 +18,21 @@ package appeng.services.version; - /** * Exceptional template for {@link Version}, when the mod does not want a check */ -public final class DoNotCheckVersion extends BaseVersion -{ - public DoNotCheckVersion() - { - super( Integer.MAX_VALUE, Channel.Stable, Integer.MAX_VALUE ); - } +public final class DoNotCheckVersion extends BaseVersion { + public DoNotCheckVersion() { + super(Integer.MAX_VALUE, Channel.Stable, Integer.MAX_VALUE); + } - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - return true; - } + @Override + public boolean isNewerAs(final Version maybeOlder) { + return true; + } - @Override - public String formatted() - { - return "dev build"; - } + @Override + public String formatted() { + return "dev build"; + } } diff --git a/src/main/java/appeng/services/version/MissingVersion.java b/src/main/java/appeng/services/version/MissingVersion.java index c7fef3a8..54aff638 100644 --- a/src/main/java/appeng/services/version/MissingVersion.java +++ b/src/main/java/appeng/services/version/MissingVersion.java @@ -18,30 +18,25 @@ package appeng.services.version; - /** * Exceptional template when the {@link Version} could not be retrieved */ -public final class MissingVersion extends BaseVersion -{ - public MissingVersion() - { - super( 0, Channel.Alpha, 0 ); - } +public final class MissingVersion extends BaseVersion { + public MissingVersion() { + super(0, Channel.Alpha, 0); + } - /** - * @param maybeOlder ignored - * @return false - */ - @Override - public boolean isNewerAs( final Version maybeOlder ) - { - return false; - } + /** + * @param maybeOlder ignored + * @return false + */ + @Override + public boolean isNewerAs(final Version maybeOlder) { + return false; + } - @Override - public String formatted() - { - return "missing"; - } + @Override + public String formatted() { + return "missing"; + } } diff --git a/src/main/java/appeng/services/version/ModVersionFetcher.java b/src/main/java/appeng/services/version/ModVersionFetcher.java index 36b4fbea..867500d3 100644 --- a/src/main/java/appeng/services/version/ModVersionFetcher.java +++ b/src/main/java/appeng/services/version/ModVersionFetcher.java @@ -18,58 +18,51 @@ package appeng.services.version; +import javax.annotation.Nonnull; import appeng.core.AELog; import appeng.services.version.exceptions.VersionCheckerException; -import javax.annotation.Nonnull; - - /** - * Wrapper for {@link VersionParser} to check if the check is happening in developer environment or in a pull request. - *

- * In that case ignore the check. + * Wrapper for {@link VersionParser} to check if the check is happening in developer + * environment or in a pull request.

In that case ignore the check. */ -public final class ModVersionFetcher implements VersionFetcher -{ - private static final Version EXCEPTIONAL_VERSION = new MissingVersion(); +public final class ModVersionFetcher implements VersionFetcher { + private static final Version EXCEPTIONAL_VERSION = new MissingVersion(); - @Nonnull - private final String rawModVersion; - @Nonnull - private final VersionParser parser; + @Nonnull + private final String rawModVersion; + @Nonnull + private final VersionParser parser; - public ModVersionFetcher( @Nonnull final String rawModVersion, @Nonnull final VersionParser parser ) - { - this.rawModVersion = rawModVersion; - this.parser = parser; - } + public ModVersionFetcher( + @Nonnull final String rawModVersion, @Nonnull final VersionParser parser + ) { + this.rawModVersion = rawModVersion; + this.parser = parser; + } - /** - * Parses only, if not checked in developer environment or in a pull request - * - * @return {@link DoNotCheckVersion} if in developer environment or pull request, {@link MissingVersion} in case of - * a parser exception or else the parsed {@link Version}. - */ - @Override - public Version get() - { - if( this.rawModVersion.equals( "@version@" ) || this.rawModVersion.contains( "pr" ) ) - { - return new DoNotCheckVersion(); - } + /** + * Parses only, if not checked in developer environment or in a pull request + * + * @return {@link DoNotCheckVersion} if in developer environment or pull request, + * {@link MissingVersion} in case of + * a parser exception or else the parsed {@link Version}. + */ + @Override + public Version get() { + if (this.rawModVersion.equals("@version@") || this.rawModVersion.contains("pr")) { + return new DoNotCheckVersion(); + } - try - { - final Version version = this.parser.parse( this.rawModVersion ); + try { + final Version version = this.parser.parse(this.rawModVersion); - return version; - } - catch( final VersionCheckerException e ) - { - AELog.debug( e ); + return version; + } catch (final VersionCheckerException e) { + AELog.debug(e); - return EXCEPTIONAL_VERSION; - } - } + return EXCEPTIONAL_VERSION; + } + } } diff --git a/src/main/java/appeng/services/version/Version.java b/src/main/java/appeng/services/version/Version.java index 1e3c1925..dd44c0ef 100644 --- a/src/main/java/appeng/services/version/Version.java +++ b/src/main/java/appeng/services/version/Version.java @@ -18,43 +18,42 @@ package appeng.services.version; - /** * Stores version information, which are easily compared */ -public interface Version -{ - /** - * @return revision of this version - */ - int revision(); +public interface Version { + /** + * @return revision of this version + */ + int revision(); - /** - * @return channel of this version - */ - Channel channel(); + /** + * @return channel of this version + */ + Channel channel(); - /** - * @return build of this version - */ - int build(); + /** + * @return build of this version + */ + int build(); - /** - * A version is never if these criteria are met: - * if the current revision is higher than the compared revision OR - * if revision are equal and the current channel is higher than the compared channel (Stable > Beta > Alpha) OR - * if revision, channel are equal and the build is higher than the compared build - * - * @return true if criteria are met - */ - boolean isNewerAs( Version maybeOlder ); + /** + * A version is never if these criteria are met: + * if the current revision is higher than the compared revision OR + * if revision are equal and the current channel is higher than the compared channel + * (Stable > Beta > Alpha) OR if revision, channel are equal and the build is higher + * than the compared build + * + * @return true if criteria are met + */ + boolean isNewerAs(Version maybeOlder); - /** - * Prints the revision, channel and build into a common displayed way - *

- * rv2-beta-8 - * - * @return formatted version - */ - String formatted(); + /** + * Prints the revision, channel and build into a common displayed way + *

+ * rv2-beta-8 + * + * @return formatted version + */ + String formatted(); } diff --git a/src/main/java/appeng/services/version/VersionCheckerConfig.java b/src/main/java/appeng/services/version/VersionCheckerConfig.java index 7c9968c7..31161ec2 100644 --- a/src/main/java/appeng/services/version/VersionCheckerConfig.java +++ b/src/main/java/appeng/services/version/VersionCheckerConfig.java @@ -18,110 +18,130 @@ package appeng.services.version; +import java.io.File; +import java.util.Date; +import javax.annotation.Nonnull; import com.google.common.base.Preconditions; import net.minecraftforge.common.config.Configuration; -import javax.annotation.Nonnull; -import java.io.File; -import java.util.Date; - - /** * Separate config file to handle the version checker */ -public final class VersionCheckerConfig -{ - private static final int DEFAULT_INTERVAL_HOURS = 24; - private static final int MIN_INTERVAL_HOURS = 0; - private static final int MAX_INTERVAL_HOURS = 7 * 24; +public final class VersionCheckerConfig { + private static final int DEFAULT_INTERVAL_HOURS = 24; + private static final int MIN_INTERVAL_HOURS = 0; + private static final int MAX_INTERVAL_HOURS = 7 * 24; - @Nonnull - private final Configuration config; + @Nonnull + private final Configuration config; - private final boolean isEnabled; + private final boolean isEnabled; - @Nonnull - private final String lastCheck; - private final int interval; + @Nonnull + private final String lastCheck; + private final int interval; - @Nonnull - private final String level; + @Nonnull + private final String level; - private final boolean shouldNotifyPlayer; - private final boolean shouldPostChangelog; + private final boolean shouldNotifyPlayer; + private final boolean shouldPostChangelog; - /** - * @param file requires fully qualified file in which the config is saved - */ - public VersionCheckerConfig( @Nonnull final File file ) - { - Preconditions.checkNotNull( file ); - Preconditions.checkState( !file.isDirectory() ); + /** + * @param file requires fully qualified file in which the config is saved + */ + public VersionCheckerConfig(@Nonnull final File file) { + Preconditions.checkNotNull(file); + Preconditions.checkState(!file.isDirectory()); - this.config = new Configuration( file ); + this.config = new Configuration(file); - // initializes default values by caching - this.isEnabled = this.config.getBoolean( "enabled", "general", true, "If true, the version checker is enabled. Acts as a master switch." ); + // initializes default values by caching + this.isEnabled = this.config.getBoolean( + "enabled", + "general", + true, + "If true, the version checker is enabled. Acts as a master switch." + ); - this.lastCheck = this.config.getString( "lastCheck", "cache", "0", "The number of milliseconds since January 1, 1970, 00:00:00 GMT of the last successful check." ); - this.interval = this.config.getInt( "interval", "cache", DEFAULT_INTERVAL_HOURS, MIN_INTERVAL_HOURS, MAX_INTERVAL_HOURS, "Waits as many hours, until it checks again." ); + this.lastCheck = this.config.getString( + "lastCheck", + "cache", + "0", + "The number of milliseconds since January 1, 1970, 00:00:00 GMT of the last successful check." + ); + this.interval = this.config.getInt( + "interval", + "cache", + DEFAULT_INTERVAL_HOURS, + MIN_INTERVAL_HOURS, + MAX_INTERVAL_HOURS, + "Waits as many hours, until it checks again." + ); - this.level = this.config.getString( "level", "channel", "Beta", "Determines the channel level which should be checked for updates. Can be either Stable, Beta or Alpha." ); + this.level = this.config.getString( + "level", + "channel", + "Beta", + "Determines the channel level which should be checked for updates. Can be either Stable, Beta or Alpha." + ); - this.shouldNotifyPlayer = this.config.getBoolean( "notify", "client", true, "If true, the player is getting a notification, that a new version is available." ); - this.shouldPostChangelog = this.config.getBoolean( "changelog", "client", true, "If true, the player is getting a notification including changelog. Only happens if notification are enabled." ); - } + this.shouldNotifyPlayer = this.config.getBoolean( + "notify", + "client", + true, + "If true, the player is getting a notification, that a new version is available." + ); + this.shouldPostChangelog = this.config.getBoolean( + "changelog", + "client", + true, + "If true, the player is getting a notification including changelog. Only happens if notification are enabled." + ); + } - public boolean isVersionCheckingEnabled() - { - return this.isEnabled; - } + public boolean isVersionCheckingEnabled() { + return this.isEnabled; + } - public String lastCheck() - { - return this.lastCheck; - } + public String lastCheck() { + return this.lastCheck; + } - /** - * Stores the current date in milli seconds into the "lastCheck" field of the config and makes it persistent. - */ - public void updateLastCheck() - { - final Date now = new Date(); - final long nowInMs = now.getTime(); - final String nowAsString = Long.toString( nowInMs ); + /** + * Stores the current date in milli seconds into the "lastCheck" field of the config + * and makes it persistent. + */ + public void updateLastCheck() { + final Date now = new Date(); + final long nowInMs = now.getTime(); + final String nowAsString = Long.toString(nowInMs); - this.config.get( "cache", "lastCheck", "0" ).set( nowAsString ); + this.config.get("cache", "lastCheck", "0").set(nowAsString); - this.config.save(); - } + this.config.save(); + } - public int interval() - { - return this.interval; - } + public int interval() { + return this.interval; + } - public String level() - { - return this.level; - } + public String level() { + return this.level; + } - public boolean shouldNotifyPlayer() - { - return this.shouldNotifyPlayer; - } + public boolean shouldNotifyPlayer() { + return this.shouldNotifyPlayer; + } - public boolean shouldPostChangelog() - { - return this.shouldPostChangelog; - } + public boolean shouldPostChangelog() { + return this.shouldPostChangelog; + } - public void save() - { - if( this.config.hasChanged() ) - { - this.config.save(); - } - } + public void save() { + if (this.config.hasChanged()) { + this.config.save(); + } + } } diff --git a/src/main/java/appeng/services/version/VersionFetcher.java b/src/main/java/appeng/services/version/VersionFetcher.java index c30faddf..b343ac0f 100644 --- a/src/main/java/appeng/services/version/VersionFetcher.java +++ b/src/main/java/appeng/services/version/VersionFetcher.java @@ -18,11 +18,9 @@ package appeng.services.version; - /** * Processes base information to retrieve a {@link Version} */ -public interface VersionFetcher -{ - Version get(); +public interface VersionFetcher { + Version get(); } diff --git a/src/main/java/appeng/services/version/VersionParser.java b/src/main/java/appeng/services/version/VersionParser.java index d5d73cf8..8df320a3 100644 --- a/src/main/java/appeng/services/version/VersionParser.java +++ b/src/main/java/appeng/services/version/VersionParser.java @@ -18,163 +18,154 @@ package appeng.services.version; +import java.util.Scanner; +import java.util.regex.Pattern; +import javax.annotation.Nonnull; import appeng.services.version.exceptions.*; import com.google.common.base.Preconditions; -import javax.annotation.Nonnull; -import java.util.Scanner; -import java.util.regex.Pattern; - - /** * can parse a version in form of rv2-beta-8 or rv2.beta.8 */ -public final class VersionParser -{ - private static final Pattern PATTERN_DOT = Pattern.compile( "\\." ); - private static final Pattern PATTERN_DASH = Pattern.compile( "-" ); - private static final Pattern PATTERN_REVISION = Pattern.compile( "[^0-9]+" ); - private static final Pattern PATTERN_BUILD = Pattern.compile( "[^0-9]+" ); - private static final Pattern PATTERN_NATURAL = Pattern.compile( "[0-9]+" ); - private static final Pattern PATTERN_VALID_REVISION = Pattern.compile( "^rv\\d+$" ); +public final class VersionParser { + private static final Pattern PATTERN_DOT = Pattern.compile("\\."); + private static final Pattern PATTERN_DASH = Pattern.compile("-"); + private static final Pattern PATTERN_REVISION = Pattern.compile("[^0-9]+"); + private static final Pattern PATTERN_BUILD = Pattern.compile("[^0-9]+"); + private static final Pattern PATTERN_NATURAL = Pattern.compile("[0-9]+"); + private static final Pattern PATTERN_VALID_REVISION = Pattern.compile("^rv\\d+$"); - /** - * Parses the {@link Version} out of a String - * - * @param raw String in form of rv2-beta-8 or rv2.beta.8 - * @return {@link Version} encoded in the raw String - * @throws VersionCheckerException if parsing the raw string was not successful. - */ - public Version parse( @Nonnull final String raw ) throws VersionCheckerException - { - Preconditions.checkNotNull( raw ); + /** + * Parses the {@link Version} out of a String + * + * @param raw String in form of rv2-beta-8 or rv2.beta.8 + * @return {@link Version} encoded in the raw String + * @throws VersionCheckerException if parsing the raw string was not successful. + */ + public Version parse(@Nonnull final String raw) throws VersionCheckerException { + Preconditions.checkNotNull(raw); - final String transformed = this.transformDelimiter( raw ); - final String[] split = transformed.split( "_" ); + final String transformed = this.transformDelimiter(raw); + final String[] split = transformed.split("_"); - return this.parseVersion( split ); - } + return this.parseVersion(split); + } - /** - * Replaces all "." and "-" into "_" to make them uniform - * - * @param raw raw version string containing "." or "-" - * @return transformed raw, where "." and "-" are replaced by "_" - * @throws MissingSeparatorException if not containing valid separators - */ - private String transformDelimiter( @Nonnull final String raw ) throws MissingSeparatorException - { - if( !( raw.contains( "." ) || raw.contains( "-" ) ) ) - { - throw new MissingSeparatorException(); - } + /** + * Replaces all "." and "-" into "_" to make them uniform + * + * @param raw raw version string containing "." or "-" + * @return transformed raw, where "." and "-" are replaced by "_" + * @throws MissingSeparatorException if not containing valid separators + */ + private String transformDelimiter(@Nonnull final String raw) + throws MissingSeparatorException { + if (!(raw.contains(".") || raw.contains("-"))) { + throw new MissingSeparatorException(); + } - final String withoutDot = PATTERN_DOT.matcher( raw ).replaceAll( "_" ); - final String withoutDash = PATTERN_DASH.matcher( withoutDot ).replaceAll( "_" ); + final String withoutDot = PATTERN_DOT.matcher(raw).replaceAll("_"); + final String withoutDash = PATTERN_DASH.matcher(withoutDot).replaceAll("_"); - return withoutDash; - } + return withoutDash; + } - /** - * parses the {@link Version} out of the split. - * The split must have a length of 3, - * representing revision, channel and build. - * - * @param splitRaw raw version split with length of 3 - * @return {@link Version} represented by the splitRaw - * @throws InvalidVersionException when length not 3 - * @throws InvalidRevisionException {@link VersionParser#parseRevision(String)} - * @throws InvalidChannelException {@link VersionParser#parseChannel(String)} - * @throws InvalidBuildException {@link VersionParser#parseBuild(String)} - */ - private Version parseVersion( @Nonnull final String[] splitRaw ) - throws InvalidVersionException, InvalidRevisionException, InvalidChannelException, InvalidBuildException - { - if( splitRaw.length != 3 ) - { - throw new InvalidVersionException(); - } + /** + * parses the {@link Version} out of the split. + * The split must have a length of 3, + * representing revision, channel and build. + * + * @param splitRaw raw version split with length of 3 + * @return {@link Version} represented by the splitRaw + * @throws InvalidVersionException when length not 3 + * @throws InvalidRevisionException {@link VersionParser#parseRevision(String)} + * @throws InvalidChannelException {@link VersionParser#parseChannel(String)} + * @throws InvalidBuildException {@link VersionParser#parseBuild(String)} + */ + private Version parseVersion(@Nonnull final String[] splitRaw) + throws InvalidVersionException, InvalidRevisionException, InvalidChannelException, + InvalidBuildException { + if (splitRaw.length != 3) { + throw new InvalidVersionException(); + } - final String rawRevision = splitRaw[0]; - final String rawChannel = splitRaw[1]; - final String rawBuild = splitRaw[2]; + final String rawRevision = splitRaw[0]; + final String rawChannel = splitRaw[1]; + final String rawBuild = splitRaw[2]; - final int revision = this.parseRevision( rawRevision ); - final Channel channel = this.parseChannel( rawChannel ); - final int build = this.parseBuild( rawBuild ); + final int revision = this.parseRevision(rawRevision); + final Channel channel = this.parseChannel(rawChannel); + final int build = this.parseBuild(rawBuild); - return new DefaultVersion( revision, channel, build ); - } + return new DefaultVersion(revision, channel, build); + } - /** - * A revision starts with the keyword "rv", followed by a natural number - * - * @param rawRevision String containing the revision number - * @return revision number - * @throws InvalidRevisionException if not matching "rv" followed by a natural number. - */ - private int parseRevision( @Nonnull final String rawRevision ) throws InvalidRevisionException - { - if( !PATTERN_VALID_REVISION.matcher( rawRevision ).matches() ) - { - throw new InvalidRevisionException(); - } + /** + * A revision starts with the keyword "rv", followed by a natural number + * + * @param rawRevision String containing the revision number + * @return revision number + * @throws InvalidRevisionException if not matching "rv" followed by a natural number. + */ + private int parseRevision(@Nonnull final String rawRevision) + throws InvalidRevisionException { + if (!PATTERN_VALID_REVISION.matcher(rawRevision).matches()) { + throw new InvalidRevisionException(); + } - final Scanner scanner = new Scanner( rawRevision ); + final Scanner scanner = new Scanner(rawRevision); - final int revision = scanner.useDelimiter( PATTERN_REVISION ).nextInt(); + final int revision = scanner.useDelimiter(PATTERN_REVISION).nextInt(); - scanner.close(); + scanner.close(); - return revision; - } + return revision; + } - /** - * A channel is atm either one of {@link Channel#Alpha}, {@link Channel#Beta} or {@link Channel#Stable} - * - * @param rawChannel String containing the channel - * @return matching {@link Channel} to the String - * @throws InvalidChannelException if not one of {@link Channel} values. - */ - private Channel parseChannel( @Nonnull final String rawChannel ) throws InvalidChannelException - { - if( !( rawChannel.equalsIgnoreCase( Channel.Alpha.name() ) || rawChannel.equalsIgnoreCase( Channel.Beta.name() ) || rawChannel.equalsIgnoreCase( Channel.Stable.name() ) ) ) - { - throw new InvalidChannelException(); - } + /** + * A channel is atm either one of {@link Channel#Alpha}, {@link Channel#Beta} or + * {@link Channel#Stable} + * + * @param rawChannel String containing the channel + * @return matching {@link Channel} to the String + * @throws InvalidChannelException if not one of {@link Channel} values. + */ + private Channel parseChannel(@Nonnull final String rawChannel) + throws InvalidChannelException { + if (!(rawChannel.equalsIgnoreCase(Channel.Alpha.name()) + || rawChannel.equalsIgnoreCase(Channel.Beta.name()) + || rawChannel.equalsIgnoreCase(Channel.Stable.name()))) { + throw new InvalidChannelException(); + } - for( final Channel channel : Channel.values() ) - { - if( channel.name().equalsIgnoreCase( rawChannel ) ) - { - return channel; - } - } + for (final Channel channel : Channel.values()) { + if (channel.name().equalsIgnoreCase(rawChannel)) { + return channel; + } + } - throw new InvalidChannelException(); - } + throw new InvalidChannelException(); + } - /** - * A build is just a natural number - * - * @param rawBuild String containing the build number - * @return build number - * @throws InvalidBuildException if not a natural number. - */ - private int parseBuild( @Nonnull final String rawBuild ) throws InvalidBuildException - { - if( !PATTERN_NATURAL.matcher( rawBuild ).matches() ) - { - throw new InvalidBuildException(); - } + /** + * A build is just a natural number + * + * @param rawBuild String containing the build number + * @return build number + * @throws InvalidBuildException if not a natural number. + */ + private int parseBuild(@Nonnull final String rawBuild) throws InvalidBuildException { + if (!PATTERN_NATURAL.matcher(rawBuild).matches()) { + throw new InvalidBuildException(); + } - final Scanner scanner = new Scanner( rawBuild ); + final Scanner scanner = new Scanner(rawBuild); - final int build = scanner.useDelimiter( PATTERN_BUILD ).nextInt(); + final int build = scanner.useDelimiter(PATTERN_BUILD).nextInt(); - scanner.close(); + scanner.close(); - return build; - } + return build; + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java b/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java index b7049016..6d3d9bbf 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidBuildException.java @@ -18,16 +18,13 @@ package appeng.services.version.exceptions; - /** * Indicates a invalid build number, which is any string except a natural number. */ -public class InvalidBuildException extends VersionCheckerException -{ - private static final long serialVersionUID = 3015432444672364991L; +public class InvalidBuildException extends VersionCheckerException { + private static final long serialVersionUID = 3015432444672364991L; - public InvalidBuildException() - { - super( "Invalid Build: Needs to be a natural number." ); - } + public InvalidBuildException() { + super("Invalid Build: Needs to be a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java b/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java index 824d1f87..f8ab4210 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidChannelException.java @@ -18,19 +18,17 @@ package appeng.services.version.exceptions; - import appeng.services.version.Channel; - /** * Indicates an invalid {@link Channel} value. */ -public class InvalidChannelException extends VersionCheckerException -{ - private static final long serialVersionUID = -1306378515002341620L; +public class InvalidChannelException extends VersionCheckerException { + private static final long serialVersionUID = -1306378515002341620L; - public InvalidChannelException() - { - super( "Invalid Channel: Needs to be one of the following values; alpha, beta, or stable." ); - } + public InvalidChannelException() { + super( + "Invalid Channel: Needs to be one of the following values; alpha, beta, or stable." + ); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java b/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java index 02a155ce..e2c2dfa8 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidRevisionException.java @@ -18,17 +18,14 @@ package appeng.services.version.exceptions; - /** - * Indicates a invalid revision, which does not match the pattern "rv" followed by a natural number. + * Indicates a invalid revision, which does not match the pattern "rv" followed by a + * natural number. */ -public class InvalidRevisionException extends VersionCheckerException -{ +public class InvalidRevisionException extends VersionCheckerException { + private static final long serialVersionUID = 4828906902143875942L; - private static final long serialVersionUID = 4828906902143875942L; - - public InvalidRevisionException() - { - super( "Invalid Revision: Needs to be 'rv' followd by a natural number." ); - } + public InvalidRevisionException() { + super("Invalid Revision: Needs to be 'rv' followd by a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java b/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java index 1985bc76..e76f1cda 100644 --- a/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java +++ b/src/main/java/appeng/services/version/exceptions/InvalidVersionException.java @@ -18,17 +18,16 @@ package appeng.services.version.exceptions; - /** - * Indicates an invalid version, which does not consists of 3 parts matching /(rv\d+)-(alpha|beta|stable)-(b\d+)/. + * Indicates an invalid version, which does not consists of 3 parts matching + * /(rv\d+)-(alpha|beta|stable)-(b\d+)/. */ -public class InvalidVersionException extends VersionCheckerException -{ +public class InvalidVersionException extends VersionCheckerException { + private static final long serialVersionUID = 4828906902143875942L; - private static final long serialVersionUID = 4828906902143875942L; - - public InvalidVersionException() - { - super( "Invalid Version Format: Need to consist of exactly 3 parts separated by a dash." ); - } + public InvalidVersionException() { + super( + "Invalid Version Format: Need to consist of exactly 3 parts separated by a dash." + ); + } } diff --git a/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java b/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java index 7c1af0f0..3360c430 100644 --- a/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java +++ b/src/main/java/appeng/services/version/exceptions/MissingSeparatorException.java @@ -18,18 +18,15 @@ package appeng.services.version.exceptions; - /** * Indicates a version without a valid separator. *

* Valid separators are a dash ("-") or dot (".") */ -public class MissingSeparatorException extends VersionCheckerException -{ - private static final long serialVersionUID = 8366370192017020750L; +public class MissingSeparatorException extends VersionCheckerException { + private static final long serialVersionUID = 8366370192017020750L; - public MissingSeparatorException() - { - super( "Invalid Revision: Needs to match 'rv' followed by a natural number." ); - } + public MissingSeparatorException() { + super("Invalid Revision: Needs to match 'rv' followed by a natural number."); + } } diff --git a/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java b/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java index caf373b7..7358dd7e 100644 --- a/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java +++ b/src/main/java/appeng/services/version/exceptions/VersionCheckerException.java @@ -18,19 +18,15 @@ package appeng.services.version.exceptions; - import javax.annotation.Nonnull; - /** * A super class for any exception thrown by the version checker for easier handling. */ -public class VersionCheckerException extends Exception -{ - private static final long serialVersionUID = 4582501864800542884L; +public class VersionCheckerException extends Exception { + private static final long serialVersionUID = 4582501864800542884L; - public VersionCheckerException( @Nonnull String string ) - { - super( string ); - } + public VersionCheckerException(@Nonnull String string) { + super(string); + } } diff --git a/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java b/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java index b2269d19..1510bf12 100644 --- a/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java +++ b/src/main/java/appeng/services/version/github/DefaultFormattedRelease.java @@ -18,37 +18,33 @@ package appeng.services.version.github; - -import appeng.services.version.Version; - import javax.annotation.Nonnull; +import appeng.services.version.Version; /** * Default template when a {@link FormattedRelease} is needed. */ -public final class DefaultFormattedRelease implements FormattedRelease -{ - @Nonnull - private final Version version; - @Nonnull - private final String changelog; +public final class DefaultFormattedRelease implements FormattedRelease { + @Nonnull + private final Version version; + @Nonnull + private final String changelog; - public DefaultFormattedRelease( @Nonnull final Version version, @Nonnull final String changelog ) - { - this.version = version; - this.changelog = changelog; - } + public DefaultFormattedRelease( + @Nonnull final Version version, @Nonnull final String changelog + ) { + this.version = version; + this.changelog = changelog; + } - @Override - public String changelog() - { - return this.changelog; - } + @Override + public String changelog() { + return this.changelog; + } - @Override - public Version version() - { - return this.version; - } + @Override + public Version version() { + return this.version; + } } diff --git a/src/main/java/appeng/services/version/github/FormattedRelease.java b/src/main/java/appeng/services/version/github/FormattedRelease.java index fef5ae2f..7973cd8d 100644 --- a/src/main/java/appeng/services/version/github/FormattedRelease.java +++ b/src/main/java/appeng/services/version/github/FormattedRelease.java @@ -18,22 +18,20 @@ package appeng.services.version.github; - import appeng.services.version.Version; - /** - * Represents the acquired, processed information through github about a release of Applied Energistics 2 + * Represents the acquired, processed information through github about a release of + * Applied Energistics 2 */ -public interface FormattedRelease -{ - /** - * @return changelog - */ - String changelog(); +public interface FormattedRelease { + /** + * @return changelog + */ + String changelog(); - /** - * @return processed version - */ - Version version(); + /** + * @return processed version + */ + Version version(); } diff --git a/src/main/java/appeng/services/version/github/MissingFormattedRelease.java b/src/main/java/appeng/services/version/github/MissingFormattedRelease.java index b7ebd93c..04ac10ae 100644 --- a/src/main/java/appeng/services/version/github/MissingFormattedRelease.java +++ b/src/main/java/appeng/services/version/github/MissingFormattedRelease.java @@ -18,41 +18,35 @@ package appeng.services.version.github; +import javax.annotation.Nonnull; import appeng.services.version.MissingVersion; import appeng.services.version.Version; -import javax.annotation.Nonnull; - - /** * Exceptional template, when no meaningful {@link FormattedRelease} could be obtained */ -public final class MissingFormattedRelease implements FormattedRelease -{ - @Nonnull - private final Version version; +public final class MissingFormattedRelease implements FormattedRelease { + @Nonnull + private final Version version; - public MissingFormattedRelease() - { - this.version = new MissingVersion(); - } + public MissingFormattedRelease() { + this.version = new MissingVersion(); + } - /** - * @return empty string - */ - @Override - public String changelog() - { - return ""; - } + /** + * @return empty string + */ + @Override + public String changelog() { + return ""; + } - /** - * @return {@link MissingVersion} - */ - @Override - public Version version() - { - return this.version; - } + /** + * @return {@link MissingVersion} + */ + @Override + public Version version() { + return this.version; + } } diff --git a/src/main/java/appeng/services/version/github/Release.java b/src/main/java/appeng/services/version/github/Release.java index 9dc0f651..bbf6c957 100644 --- a/src/main/java/appeng/services/version/github/Release.java +++ b/src/main/java/appeng/services/version/github/Release.java @@ -18,20 +18,18 @@ package appeng.services.version.github; - /** * Template class for Gson to write values from the Json Object into an actual class */ -@SuppressWarnings( "all" ) -public class Release -{ - /** - * name of the tag it is saved - */ - public String tag_name; +@SuppressWarnings("all") +public class Release { + /** + * name of the tag it is saved + */ + public String tag_name; - /** - * Contains the changelog - */ - public String body; + /** + * Contains the changelog + */ + public String body; } diff --git a/src/main/java/appeng/services/version/github/ReleaseFetcher.java b/src/main/java/appeng/services/version/github/ReleaseFetcher.java index a072cc4e..0572dd45 100644 --- a/src/main/java/appeng/services/version/github/ReleaseFetcher.java +++ b/src/main/java/appeng/services/version/github/ReleaseFetcher.java @@ -18,6 +18,12 @@ package appeng.services.version.github; +import java.io.IOException; +import java.lang.reflect.Type; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; +import javax.annotation.Nonnull; import appeng.core.AELog; import appeng.services.version.Channel; @@ -29,91 +35,72 @@ import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.apache.commons.io.IOUtils; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.lang.reflect.Type; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; +public final class ReleaseFetcher { + private static final String GITHUB_RELEASES_URL + = "https://api.github.com/repos/xsun2001/Applied-Energistics-2-Unofficial/releases"; + private static final FormattedRelease EXCEPTIONAL_RELEASE + = new MissingFormattedRelease(); + @Nonnull + private final VersionCheckerConfig config; + @Nonnull + private final VersionParser parser; -public final class ReleaseFetcher -{ - private static final String GITHUB_RELEASES_URL = "https://api.github.com/repos/xsun2001/Applied-Energistics-2-Unofficial/releases"; - private static final FormattedRelease EXCEPTIONAL_RELEASE = new MissingFormattedRelease(); + public ReleaseFetcher( + @Nonnull final VersionCheckerConfig config, @Nonnull final VersionParser parser + ) { + this.config = config; + this.parser = parser; + } - @Nonnull - private final VersionCheckerConfig config; - @Nonnull - private final VersionParser parser; + public FormattedRelease get() { + final Gson gson = new Gson(); + final Type type = new ReleasesTypeToken().getType(); - public ReleaseFetcher( @Nonnull final VersionCheckerConfig config, @Nonnull final VersionParser parser ) - { - this.config = config; - this.parser = parser; - } + try { + final URL releasesURL = new URL(GITHUB_RELEASES_URL); + final String rawReleases = this.getRawReleases(releasesURL); - public FormattedRelease get() - { - final Gson gson = new Gson(); - final Type type = new ReleasesTypeToken().getType(); + this.config.updateLastCheck(); - try - { - final URL releasesURL = new URL( GITHUB_RELEASES_URL ); - final String rawReleases = this.getRawReleases( releasesURL ); + final List releases = gson.fromJson(rawReleases, type); + final FormattedRelease latestFitRelease = this.getLatestFitRelease(releases); - this.config.updateLastCheck(); + return latestFitRelease; + } catch (final VersionCheckerException e) { + AELog.debug(e); + } catch (MalformedURLException e) { + AELog.debug(e); + } catch (IOException e) { + AELog.debug(e); + } - final List releases = gson.fromJson( rawReleases, type ); - final FormattedRelease latestFitRelease = this.getLatestFitRelease( releases ); + return EXCEPTIONAL_RELEASE; + } - return latestFitRelease; - } - catch( final VersionCheckerException e ) - { - AELog.debug( e ); - } - catch( MalformedURLException e ) - { - AELog.debug( e ); - } - catch( IOException e ) - { - AELog.debug( e ); - } + private String getRawReleases(final URL url) throws IOException { + return IOUtils.toString(url); + } - return EXCEPTIONAL_RELEASE; - } + private FormattedRelease getLatestFitRelease(final Iterable releases) + throws VersionCheckerException { + final String levelInConfig = this.config.level(); + final Channel level = Channel.valueOf(levelInConfig); + final int levelOrdinal = level.ordinal(); - private String getRawReleases( final URL url ) throws IOException - { - return IOUtils.toString( url ); - } + for (final Release release : releases) { + final String rawVersion = release.tag_name; + final String changelog = release.body; - private FormattedRelease getLatestFitRelease( final Iterable releases ) throws VersionCheckerException - { - final String levelInConfig = this.config.level(); - final Channel level = Channel.valueOf( levelInConfig ); - final int levelOrdinal = level.ordinal(); + final Version version = this.parser.parse(rawVersion); - for( final Release release : releases ) - { - final String rawVersion = release.tag_name; - final String changelog = release.body; + if (version.channel().ordinal() >= levelOrdinal) { + return new DefaultFormattedRelease(version, changelog); + } + } - final Version version = this.parser.parse( rawVersion ); + return EXCEPTIONAL_RELEASE; + } - if( version.channel().ordinal() >= levelOrdinal ) - { - return new DefaultFormattedRelease( version, changelog ); - } - } - - return EXCEPTIONAL_RELEASE; - } - - private static final class ReleasesTypeToken extends TypeToken> - { - } + private static final class ReleasesTypeToken extends TypeToken> {} } diff --git a/src/main/java/appeng/spatial/BiomeGenStorage.java b/src/main/java/appeng/spatial/BiomeGenStorage.java index 79e9e077..d65a8bbd 100644 --- a/src/main/java/appeng/spatial/BiomeGenStorage.java +++ b/src/main/java/appeng/spatial/BiomeGenStorage.java @@ -18,28 +18,23 @@ package appeng.spatial; - import net.minecraft.world.biome.BiomeGenBase; +public class BiomeGenStorage extends BiomeGenBase { + public BiomeGenStorage(final int id) { + super(id); + this.setBiomeName("Storage Cell"); -public class BiomeGenStorage extends BiomeGenBase -{ + this.setDisableRain(); + this.temperature = -100; - public BiomeGenStorage( final int id ) - { - super( id ); - this.setBiomeName( "Storage Cell" ); + this.theBiomeDecorator.treesPerChunk = 0; + this.theBiomeDecorator.flowersPerChunk = 0; + this.theBiomeDecorator.grassPerChunk = 0; - this.setDisableRain(); - this.temperature = -100; - - this.theBiomeDecorator.treesPerChunk = 0; - this.theBiomeDecorator.flowersPerChunk = 0; - this.theBiomeDecorator.grassPerChunk = 0; - - this.spawnableMonsterList.clear(); - this.spawnableCreatureList.clear(); - this.spawnableWaterCreatureList.clear(); - this.spawnableCaveCreatureList.clear(); - } + this.spawnableMonsterList.clear(); + this.spawnableCreatureList.clear(); + 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 becb198a..510917b3 100644 --- a/src/main/java/appeng/spatial/CachedPlane.java +++ b/src/main/java/appeng/spatial/CachedPlane.java @@ -18,6 +18,10 @@ package appeng.spatial; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -36,408 +40,437 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; import net.minecraftforge.common.util.ForgeDirection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map.Entry; +public class CachedPlane { + private final int x_size; + private final int z_size; + private final int cx_size; + private final int cz_size; + private final int x_offset; + private final int y_offset; + private final int z_offset; + private final int y_size; + private final Chunk[][] myChunks; + private final Column[][] myColumns; + private final LinkedList tiles = new LinkedList(); + private final LinkedList ticks + = new LinkedList(); + private final World world; + private final IMovableRegistry reg = AEApi.instance().registries().movable(); + private final LinkedList updates = new LinkedList(); + private final IBlockDefinition matrixFrame + = AEApi.instance().definitions().blocks().matrixFrame(); + private int verticalBits; + public CachedPlane( + final World w, + final int minX, + final int minY, + final int minZ, + final int maxX, + final int maxY, + final int maxZ + ) { + this.world = w; -public class CachedPlane -{ - private final int x_size; - private final int z_size; - private final int cx_size; - private final int cz_size; - private final int x_offset; - private final int y_offset; - private final int z_offset; - private final int y_size; - private final Chunk[][] myChunks; - private final Column[][] myColumns; - private final LinkedList tiles = new LinkedList(); - private final LinkedList ticks = new LinkedList(); - private final World world; - private final IMovableRegistry reg = AEApi.instance().registries().movable(); - private final LinkedList updates = new LinkedList(); - private final IBlockDefinition matrixFrame = AEApi.instance().definitions().blocks().matrixFrame(); - private int verticalBits; + this.x_size = maxX - minX + 1; + this.y_size = maxY - minY + 1; + this.z_size = maxZ - minZ + 1; - public CachedPlane( final World w, final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ ) - { + this.x_offset = minX; + this.y_offset = minY; + this.z_offset = minZ; - this.world = w; + final int minCX = minX >> 4; + final int minCY = minY >> 4; + final int minCZ = minZ >> 4; + final int maxCX = maxX >> 4; + final int maxCY = maxY >> 4; + final int maxCZ = maxZ >> 4; - this.x_size = maxX - minX + 1; - this.y_size = maxY - minY + 1; - this.z_size = maxZ - minZ + 1; + this.cx_size = maxCX - minCX + 1; + final int cy_size = maxCY - minCY + 1; + this.cz_size = maxCZ - minCZ + 1; - this.x_offset = minX; - this.y_offset = minY; - this.z_offset = minZ; + this.myChunks = new Chunk[this.cx_size][this.cz_size]; + this.myColumns = new Column[this.x_size][this.z_size]; - final int minCX = minX >> 4; - final int minCY = minY >> 4; - final int minCZ = minZ >> 4; - final int maxCX = maxX >> 4; - final int maxCY = maxY >> 4; - final int maxCZ = maxZ >> 4; + this.verticalBits = 0; + for (int cy = 0; cy < cy_size; cy++) { + this.verticalBits |= 1 << (minCY + cy); + } - this.cx_size = maxCX - minCX + 1; - final int cy_size = maxCY - minCY + 1; - this.cz_size = maxCZ - minCZ + 1; + 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 + ); + } + } - this.myChunks = new Chunk[this.cx_size][this.cz_size]; - this.myColumns = new Column[this.x_size][this.z_size]; + final IMovableRegistry mr = AEApi.instance().registries().movable(); - this.verticalBits = 0; - for( int cy = 0; cy < cy_size; cy++ ) - { - this.verticalBits |= 1 << ( minCY + cy ); - } + for (int cx = 0; cx < this.cx_size; cx++) { + for (int cz = 0; cz < this.cz_size; cz++) { + final LinkedList> rawTiles + = new LinkedList>(); + final LinkedList deadTiles + = new LinkedList(); - 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 ); - } - } + final Chunk c = w.getChunkFromChunkCoords(minCX + cx, minCZ + cz); + this.myChunks[cx][cz] = c; - final IMovableRegistry mr = AEApi.instance().registries().movable(); + rawTiles.addAll( + ((HashMap) c.chunkTileEntityMap).entrySet() + ); + for (final Entry tx : rawTiles) { + final ChunkPosition cp = tx.getKey(); + final TileEntity te = tx.getValue(); + if (te.xCoord >= minX && te.xCoord <= maxX && te.yCoord >= minY + && te.yCoord <= maxY && te.zCoord >= minZ && te.zCoord <= maxZ) { + if (mr.askToMove(te)) { + this.tiles.add(te); + deadTiles.add(cp); + } else { + final Object[] details + = this.myColumns[te.xCoord - minX][te.zCoord - minZ] + .getDetails(te.yCoord); + final Block blk = (Block) details[0]; - for( int cx = 0; cx < this.cx_size; cx++ ) - { - for( int cz = 0; cz < this.cz_size; cz++ ) - { - final LinkedList> rawTiles = new LinkedList>(); - final LinkedList deadTiles = new LinkedList(); + // 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 + )) { + c.worldObj.setBlock( + te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK + ); + c.worldObj.notifyBlocksOfNeighborChange( + te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK + ); + } else { + this.myColumns[te.xCoord - minX][te.zCoord - minZ] + .setSkip(te.yCoord); + } + } + } + } - final Chunk c = w.getChunkFromChunkCoords( minCX + cx, minCZ + cz ); - this.myChunks[cx][cz] = c; + for (final ChunkPosition cp : deadTiles) { + c.chunkTileEntityMap.remove(cp); + } - rawTiles.addAll( ( (HashMap) c.chunkTileEntityMap ).entrySet() ); - for( final Entry tx : rawTiles ) - { - final ChunkPosition cp = tx.getKey(); - final TileEntity te = tx.getValue(); - if( te.xCoord >= minX && te.xCoord <= maxX && te.yCoord >= minY && te.yCoord <= maxY && te.zCoord >= minZ && te.zCoord <= maxZ ) - { - if( mr.askToMove( te ) ) - { - this.tiles.add( te ); - deadTiles.add( cp ); - } - else - { - final Object[] details = this.myColumns[te.xCoord - minX][te.zCoord - minZ].getDetails( te.yCoord ); - final Block blk = (Block) details[0]; + final long k = this.getWorld().getTotalWorldTime(); + final List list = this.getWorld().getPendingBlockUpdates(c, false); + if (list != null) { + for (final Object o : list) { + final NextTickListEntry entry = (NextTickListEntry) o; + if (entry.xCoord >= minX && entry.xCoord <= maxX + && entry.yCoord >= minY && entry.yCoord <= maxY + && entry.zCoord >= minZ && entry.zCoord <= maxZ) { + final NextTickListEntry newEntry = new NextTickListEntry( + entry.xCoord, + entry.yCoord, + entry.zCoord, + entry.func_151351_a() + ); + newEntry.scheduledTime = entry.scheduledTime - k; + this.ticks.add(newEntry); + } + } + } + } + } - // 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 ) ) - { - c.worldObj.setBlock( te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK ); - c.worldObj.notifyBlocksOfNeighborChange( te.xCoord, te.yCoord, te.zCoord, Platform.AIR_BLOCK ); - } - else - { - this.myColumns[te.xCoord - minX][te.zCoord - minZ].setSkip( te.yCoord ); - } - } - } - } + for (final TileEntity te : this.tiles) { + try { + this.getWorld().loadedTileEntityList.remove(te); + } catch (final Exception e) { + AELog.debug(e); + } + } + } - for( final ChunkPosition cp : deadTiles ) - { - c.chunkTileEntityMap.remove( cp ); - } + private IMovableHandler getHandler(final TileEntity te) { + final IMovableRegistry mr = AEApi.instance().registries().movable(); + return mr.getHandler(te); + } - final long k = this.getWorld().getTotalWorldTime(); - final List list = this.getWorld().getPendingBlockUpdates( c, false ); - if( list != null ) - { - for( final Object o : list ) - { - final NextTickListEntry entry = (NextTickListEntry) o; - if( entry.xCoord >= minX && entry.xCoord <= maxX && entry.yCoord >= minY && entry.yCoord <= maxY && entry.zCoord >= minZ && entry.zCoord <= maxZ ) - { - final NextTickListEntry newEntry = new NextTickListEntry( entry.xCoord, entry.yCoord, entry.zCoord, entry.func_151351_a() ); - newEntry.scheduledTime = entry.scheduledTime - k; - this.ticks.add( newEntry ); - } - } - } - } - } + void swap(final CachedPlane dst) { + final IMovableRegistry mr = AEApi.instance().registries().movable(); - for( final TileEntity te : this.tiles ) - { - try - { - this.getWorld().loadedTileEntityList.remove( te ); - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } + 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 + ); - private IMovableHandler getHandler( final TileEntity te ) - { - final IMovableRegistry mr = AEApi.instance().registries().movable(); - return mr.getHandler( te ); - } + long startTime = System.nanoTime(); - void swap( final CachedPlane dst ) - { - final IMovableRegistry mr = AEApi.instance().registries().movable(); + for (int x = 0; x < this.x_size; x++) { + for (int z = 0; z < this.z_size; z++) { + final Column a = this.myColumns[x][z]; + final Column b = dst.myColumns[x][z]; - 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 ); + for (int y = 0; y < this.y_size; y++) { + final int src_y = y + this.y_offset; + final int dst_y = y + dst.y_offset; - long startTime = System.nanoTime(); + if (a.doNotSkip(src_y) && b.doNotSkip(dst_y)) { + final Object[] aD = a.getDetails(src_y); + final Object[] bD = b.getDetails(dst_y); - for( int x = 0; x < this.x_size; x++ ) - { - for( int z = 0; z < this.z_size; z++ ) - { - final Column a = this.myColumns[x][z]; - final Column b = dst.myColumns[x][z]; + a.setBlockIDWithMetadata(src_y, bD); + b.setBlockIDWithMetadata(dst_y, aD); + } else { + this.markForUpdate( + x + this.x_offset, src_y, z + this.z_offset + ); + dst.markForUpdate(x + dst.x_offset, dst_y, z + dst.z_offset); + } + } + } + } - for( int y = 0; y < this.y_size; y++ ) - { - final int src_y = y + this.y_offset; - final int dst_y = y + dst.y_offset; + long endTime = System.nanoTime(); + long duration = endTime - startTime; + AELog.info("Block Copy Time: " + duration); - if( a.doNotSkip( src_y ) && b.doNotSkip( dst_y ) ) - { - final Object[] aD = a.getDetails( src_y ); - final Object[] bD = b.getDetails( dst_y ); + for (final TileEntity te : this.tiles) { + dst.addTile( + te.xCoord - this.x_offset, + te.yCoord - this.y_offset, + te.zCoord - this.z_offset, + te, + this, + mr + ); + } - a.setBlockIDWithMetadata( src_y, bD ); - b.setBlockIDWithMetadata( dst_y, aD ); - } - else - { - this.markForUpdate( x + this.x_offset, src_y, z + this.z_offset ); - dst.markForUpdate( x + dst.x_offset, dst_y, z + dst.z_offset ); - } - } - } - } + for (final TileEntity te : dst.tiles) { + this.addTile( + te.xCoord - dst.x_offset, + te.yCoord - dst.y_offset, + te.zCoord - dst.z_offset, + te, + dst, + mr + ); + } - long endTime = System.nanoTime(); - long duration = endTime - startTime; - AELog.info( "Block Copy Time: " + duration ); + for (final NextTickListEntry entry : this.ticks) { + dst.addTick( + entry.xCoord - this.x_offset, + entry.yCoord - this.y_offset, + entry.zCoord - this.z_offset, + entry + ); + } - for( final 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 (final NextTickListEntry entry : dst.ticks) { + this.addTick( + entry.xCoord - dst.x_offset, + entry.yCoord - dst.y_offset, + entry.zCoord - dst.z_offset, + entry + ); + } - for( final TileEntity te : dst.tiles ) - { - this.addTile( te.xCoord - dst.x_offset, te.yCoord - dst.y_offset, te.zCoord - dst.z_offset, te, dst, mr ); - } + startTime = System.nanoTime(); + this.updateChunks(); + dst.updateChunks(); + endTime = System.nanoTime(); - for( final NextTickListEntry entry : this.ticks ) - { - dst.addTick( entry.xCoord - this.x_offset, entry.yCoord - this.y_offset, entry.zCoord - this.z_offset, entry ); - } + duration = endTime - startTime; + AELog.info("Update Time: " + duration); + } + } - for( final NextTickListEntry entry : dst.ticks ) - { - this.addTick( entry.xCoord - dst.x_offset, entry.yCoord - dst.y_offset, entry.zCoord - dst.z_offset, entry ); - } + private void markForUpdate(final int x, final int y, final int z) { + this.getUpdates().add(new WorldCoord(x, y, z)); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + this.getUpdates().add( + new WorldCoord(x + d.offsetX, y + d.offsetY, z + d.offsetZ) + ); + } + } - startTime = System.nanoTime(); - this.updateChunks(); - dst.updateChunks(); - endTime = System.nanoTime(); + private void + addTick(final int x, final int y, final int z, final NextTickListEntry entry) { + this.getWorld().scheduleBlockUpdate( + x + this.x_offset, + y + this.y_offset, + z + this.z_offset, + entry.func_151351_a(), + (int) entry.scheduledTime + ); + } - duration = endTime - startTime; - AELog.info( "Update Time: " + duration ); - } - } + private void addTile( + final int x, + final int y, + final int z, + final TileEntity te, + final CachedPlane alternateDestination, + final IMovableRegistry mr + ) { + try { + final Column c = this.myColumns[x][z]; - private void markForUpdate( final int x, final int y, final int z ) - { - this.getUpdates().add( new WorldCoord( x, y, z ) ); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - this.getUpdates().add( new WorldCoord( x + d.offsetX, y + d.offsetY, z + d.offsetZ ) ); - } - } + if (c.doNotSkip(y + this.y_offset) || alternateDestination == null) { + final IMovableHandler handler = this.getHandler(te); - private void addTick( final int x, final int y, final int z, final NextTickListEntry entry ) - { - this.getWorld().scheduleBlockUpdate( x + this.x_offset, y + this.y_offset, z + this.z_offset, entry.func_151351_a(), (int) entry.scheduledTime ); - } + try { + handler.moveTile( + te, + this.getWorld(), + x + this.x_offset, + y + this.y_offset, + z + this.z_offset + ); + } catch (final Throwable e) { + AELog.debug(e); - private void addTile( final int x, final int y, final int z, final TileEntity te, final CachedPlane alternateDestination, final IMovableRegistry mr ) - { - try - { - final Column c = this.myColumns[x][z]; + // attempt recovery... + te.setWorldObj(this.getWorld()); + te.xCoord = x; + te.yCoord = y; + te.zCoord = z; - if( c.doNotSkip( y + this.y_offset ) || alternateDestination == null ) - { - final IMovableHandler handler = this.getHandler( te ); + c.c.func_150812_a(c.x, y + y, c.z, te); + // c.c.setChunkTileEntity( c.x, y + y, c.z, te ); - try - { - handler.moveTile( te, this.getWorld(), x + this.x_offset, y + this.y_offset, z + this.z_offset ); - } - catch( final Throwable e ) - { - AELog.debug( e ); + if (c.c.isChunkLoaded) { + this.getWorld().addTileEntity(te); + this.getWorld().markBlockForUpdate(x, y, z); + } + } - // attempt recovery... - te.setWorldObj( this.getWorld() ); - te.xCoord = x; - te.yCoord = y; - te.zCoord = z; + mr.doneMoving(te); + } else { + alternateDestination.addTile(x, y, z, te, null, mr); + } + } catch (final Throwable e) { + AELog.debug(e); + } + } - c.c.func_150812_a( c.x, y + y, c.z, te ); - // c.c.setChunkTileEntity( c.x, y + y, c.z, te ); + private void updateChunks() { + // update shit.. + for (int x = 0; x < this.cx_size; x++) { + for (int z = 0; z < this.cz_size; z++) { + final Chunk c = this.myChunks[x][z]; + c.resetRelightChecks(); + c.generateSkylightMap(); + c.isModified = true; + } + } - if( c.c.isChunkLoaded ) - { - this.getWorld().addTileEntity( te ); - this.getWorld().markBlockForUpdate( x, y, z ); - } - } + // send shit... + for (int x = 0; x < this.cx_size; x++) { + for (int z = 0; z < this.cz_size; z++) { + final Chunk c = this.myChunks[x][z]; - mr.doneMoving( te ); - } - else - { - alternateDestination.addTile( x, y, z, te, null, mr ); - } - } - catch( final Throwable e ) - { - AELog.debug( e ); - } - } + for (int y = 1; y < 255; y += 32) { + WorldData.instance().compassData().service().updateArea( + this.getWorld(), c.xPosition << 4, y, c.zPosition << 4 + ); + } - private void updateChunks() - { + Platform.sendChunk(c, this.verticalBits); + } + } + } - // update shit.. - for( int x = 0; x < this.cx_size; x++ ) - { - for( int z = 0; z < this.cz_size; z++ ) - { - final Chunk c = this.myChunks[x][z]; - c.resetRelightChecks(); - c.generateSkylightMap(); - c.isModified = true; - } - } + LinkedList getUpdates() { + return this.updates; + } - // send shit... - for( int x = 0; x < this.cx_size; x++ ) - { - for( int z = 0; z < this.cz_size; z++ ) - { + World getWorld() { + return this.world; + } - final Chunk c = this.myChunks[x][z]; + private class Column { + private final int x; + private final int z; + private final Chunk c; + private final Object[] ch = { 0, 0, 0 }; + private final ExtendedBlockStorage[] storage; + private List skipThese = null; - for( int y = 1; y < 255; y += 32 ) - { - WorldData.instance().compassData().service().updateArea( this.getWorld(), c.xPosition << 4, y, c.zPosition << 4 ); - } + public Column( + final Chunk chunk, + final int x, + final int z, + final int chunkY, + final int chunkHeight + ) { + this.x = x; + this.z = z; + this.c = chunk; + this.storage = this.c.getBlockStorageArray(); - Platform.sendChunk( c, this.verticalBits ); - } - } - } + // make sure storage exists before hand... + for (int ay = 0; ay < chunkHeight; ay++) { + final int by = (ay + chunkY); + ExtendedBlockStorage extendedblockstorage = this.storage[by]; + if (extendedblockstorage == null) { + extendedblockstorage = this.storage[by] = new ExtendedBlockStorage( + by << 4, !this.c.worldObj.provider.hasNoSky + ); + } + } + } - LinkedList getUpdates() - { - return this.updates; - } + private void setBlockIDWithMetadata(final int y, final Object[] blk) { + for (final Block matrixFrameBlock : + CachedPlane.this.matrixFrame.maybeBlock().asSet()) { + if (blk[0] == matrixFrameBlock) { + blk[0] = Platform.AIR_BLOCK; + } + } - World getWorld() - { - return this.world; - } + final ExtendedBlockStorage extendedBlockStorage = this.storage[y >> 4]; + extendedBlockStorage.func_150818_a(this.x, y & 15, this.z, (Block) blk[0]); + // extendedBlockStorage.setExtBlockID( x, y & 15, z, blk[0] ); + extendedBlockStorage.setExtBlockMetadata( + this.x, y & 15, this.z, (Integer) blk[1] + ); + extendedBlockStorage.setExtBlocklightValue( + this.x, y & 15, this.z, (Integer) blk[2] + ); + } - private class Column - { + private Object[] getDetails(final int y) { + final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; + this.ch[0] = extendedblockstorage.getBlockByExtId(this.x, y & 15, this.z); + this.ch[1] = extendedblockstorage.getExtBlockMetadata(this.x, y & 15, this.z); + this.ch[2] + = extendedblockstorage.getExtBlocklightValue(this.x, y & 15, this.z); + return this.ch; + } - private final int x; - private final int z; - private final Chunk c; - private final Object[] ch = { 0, 0, 0 }; - private final ExtendedBlockStorage[] storage; - private List skipThese = null; + private boolean doNotSkip(final int y) { + final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; + if (CachedPlane.this.reg.isBlacklisted( + extendedblockstorage.getBlockByExtId(this.x, y & 15, this.z) + )) { + return false; + } - public Column( final Chunk chunk, final int x, final int z, final int chunkY, final int chunkHeight ) - { - this.x = x; - this.z = z; - this.c = chunk; - this.storage = this.c.getBlockStorageArray(); + return this.skipThese == null || !this.skipThese.contains(y); + } - // make sure storage exists before hand... - for( int ay = 0; ay < chunkHeight; ay++ ) - { - final int by = ( ay + chunkY ); - ExtendedBlockStorage extendedblockstorage = this.storage[by]; - if( extendedblockstorage == null ) - { - extendedblockstorage = this.storage[by] = new ExtendedBlockStorage( by << 4, !this.c.worldObj.provider.hasNoSky ); - } - } - } - - private void setBlockIDWithMetadata( final int y, final Object[] blk ) - { - for( final Block matrixFrameBlock : CachedPlane.this.matrixFrame.maybeBlock().asSet() ) - { - if( blk[0] == matrixFrameBlock ) - { - blk[0] = Platform.AIR_BLOCK; - } - } - - final ExtendedBlockStorage extendedBlockStorage = this.storage[y >> 4]; - extendedBlockStorage.func_150818_a( this.x, y & 15, this.z, (Block) blk[0] ); - // extendedBlockStorage.setExtBlockID( x, y & 15, z, blk[0] ); - extendedBlockStorage.setExtBlockMetadata( this.x, y & 15, this.z, (Integer) blk[1] ); - extendedBlockStorage.setExtBlocklightValue( this.x, y & 15, this.z, (Integer) blk[2] ); - } - - private Object[] getDetails( final int y ) - { - final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; - this.ch[0] = extendedblockstorage.getBlockByExtId( this.x, y & 15, this.z ); - this.ch[1] = extendedblockstorage.getExtBlockMetadata( this.x, y & 15, this.z ); - this.ch[2] = extendedblockstorage.getExtBlocklightValue( this.x, y & 15, this.z ); - return this.ch; - } - - private boolean doNotSkip( final int y ) - { - final ExtendedBlockStorage extendedblockstorage = this.storage[y >> 4]; - if( CachedPlane.this.reg.isBlacklisted( extendedblockstorage.getBlockByExtId( this.x, y & 15, this.z ) ) ) - { - return false; - } - - return this.skipThese == null || !this.skipThese.contains( y ); - } - - private void setSkip( final int yCoord ) - { - if( this.skipThese == null ) - { - this.skipThese = new LinkedList(); - } - this.skipThese.add( yCoord ); - } - } + private void setSkip(final int yCoord) { + 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 3234dbae..941a076d 100644 --- a/src/main/java/appeng/spatial/DefaultSpatialHandler.java +++ b/src/main/java/appeng/spatial/DefaultSpatialHandler.java @@ -18,45 +18,39 @@ package appeng.spatial; - import appeng.api.movable.IMovableHandler; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; +public class DefaultSpatialHandler implements IMovableHandler { + /** + * never called for the default. + * + * @param tile tile entity + * @return true + */ + @Override + public boolean + canHandle(final Class myClass, final TileEntity tile) { + return true; + } -public class DefaultSpatialHandler implements IMovableHandler -{ + @Override + public void + moveTile(final TileEntity te, final World w, final int x, final int y, final int z) { + te.setWorldObj(w); + te.xCoord = x; + te.yCoord = y; + te.zCoord = z; - /** - * never called for the default. - * - * @param tile tile entity - * @return true - */ - @Override - public boolean canHandle( final Class myClass, final TileEntity tile ) - { - return true; - } + final Chunk c = w.getChunkFromBlockCoords(x, z); + c.func_150812_a(x & 0xF, y, z & 0xF, te); + // c.setChunkBlockTileEntity( x & 0xF, y, z & 0xF, te ); - @Override - public void moveTile( final TileEntity te, final World w, final int x, final int y, final int z ) - { - - te.setWorldObj( w ); - te.xCoord = x; - te.yCoord = y; - te.zCoord = z; - - final Chunk c = w.getChunkFromBlockCoords( x, z ); - c.func_150812_a( x & 0xF, y, z & 0xF, te ); - // c.setChunkBlockTileEntity( x & 0xF, y, z & 0xF, te ); - - if( c.isChunkLoaded ) - { - w.addTileEntity( te ); - w.markBlockForUpdate( x, y, z ); - } - } + if (c.isChunkLoaded) { + w.addTileEntity(te); + w.markBlockForUpdate(x, y, z); + } + } } diff --git a/src/main/java/appeng/spatial/ISpatialVisitor.java b/src/main/java/appeng/spatial/ISpatialVisitor.java index 204bde08..1921c004 100644 --- a/src/main/java/appeng/spatial/ISpatialVisitor.java +++ b/src/main/java/appeng/spatial/ISpatialVisitor.java @@ -18,9 +18,6 @@ package appeng.spatial; - -public interface ISpatialVisitor -{ - - void visit( int x, int y, int z ); +public interface ISpatialVisitor { + 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 3d1da438..b7201029 100644 --- a/src/main/java/appeng/spatial/StorageChunkProvider.java +++ b/src/main/java/appeng/spatial/StorageChunkProvider.java @@ -18,6 +18,8 @@ package appeng.spatial; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.core.AEConfig; @@ -28,73 +30,60 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkProviderGenerate; -import java.util.ArrayList; -import java.util.List; +public class StorageChunkProvider extends ChunkProviderGenerate { + private static final int SQUARE_CHUNK_SIZE = 256; + private static final Block[] BLOCKS; + static { + BLOCKS = new Block[255 * SQUARE_CHUNK_SIZE]; -public class StorageChunkProvider extends ChunkProviderGenerate -{ - private static final int SQUARE_CHUNK_SIZE = 256; - private static final Block[] BLOCKS; + for (final Block matrixFrameBlock : + AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet()) { + for (int x = 0; x < BLOCKS.length; x++) { + BLOCKS[x] = matrixFrameBlock; + } + } + } - static - { - BLOCKS = new Block[255 * SQUARE_CHUNK_SIZE]; + private final World world; - for( final Block matrixFrameBlock : AEApi.instance().definitions().blocks().matrixFrame().maybeBlock().asSet() ) - { - for( int x = 0; x < BLOCKS.length; x++ ) - { - BLOCKS[x] = matrixFrameBlock; - } - } - } + public StorageChunkProvider(final World world, final long i) { + super(world, i, false); + this.world = world; + } - private final World world; + @Override + public Chunk provideChunk(final int x, final int z) { + final Chunk chunk = new Chunk(this.world, BLOCKS, x, z); - public StorageChunkProvider( final World world, final long i ) - { - super( world, i, false ); - this.world = world; - } + final byte[] biomes = chunk.getBiomeArray(); + final AEConfig config = AEConfig.instance; - @Override - public Chunk provideChunk( final int x, final int z ) - { - final Chunk chunk = new Chunk( this.world, BLOCKS, x, z ); + for (int k = 0; k < biomes.length; ++k) { + biomes[k] = (byte) config.storageBiomeID; + } - final byte[] biomes = chunk.getBiomeArray(); - final AEConfig config = AEConfig.instance; + if (!chunk.isTerrainPopulated) { + chunk.isTerrainPopulated = true; + chunk.resetRelightChecks(); + } - for( int k = 0; k < biomes.length; ++k ) - { - biomes[k] = (byte) config.storageBiomeID; - } + return chunk; + } - if( !chunk.isTerrainPopulated ) - { - chunk.isTerrainPopulated = true; - chunk.resetRelightChecks(); - } + @Override + public void + populate(final IChunkProvider par1iChunkProvider, final int par2, final int par3) {} - return chunk; - } + @Override + public boolean unloadQueuedChunks() { + return true; + } - @Override - public void populate( final IChunkProvider par1iChunkProvider, final int par2, final int par3 ) - { - - } - - @Override - public boolean unloadQueuedChunks() - { - return true; - } - - @Override - public List getPossibleCreatures( final EnumCreatureType a, final int b, final int c, final int d ) - { - return new ArrayList(); - } + @Override + public List getPossibleCreatures( + final EnumCreatureType a, final int b, final int c, final int d + ) { + return new ArrayList(); + } } diff --git a/src/main/java/appeng/spatial/StorageHelper.java b/src/main/java/appeng/spatial/StorageHelper.java index 3befb3af..7c6e307b 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.util.List; import appeng.api.AEApi; import appeng.api.util.WorldCoord; @@ -34,331 +35,373 @@ import net.minecraft.world.Teleporter; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -import java.util.List; +public class StorageHelper { + private static StorageHelper instance; + public static StorageHelper getInstance() { + if (instance == null) { + instance = new StorageHelper(); + } + return instance; + } -public class StorageHelper -{ + /** + * Mostly from dimensional doors.. which mostly got it form X-Comp. + * + * @param entity to be teleported entity + * @param link destination + * @return teleported entity + */ + private Entity teleportEntity(Entity entity, final TelDestination link) { + final WorldServer oldWorld; + final WorldServer newWorld; + final EntityPlayerMP player; - private static StorageHelper instance; + try { + oldWorld = (WorldServer) entity.worldObj; + newWorld = (WorldServer) link.dim; + player = (entity instanceof EntityPlayerMP) ? (EntityPlayerMP) entity : null; + } catch (final Throwable e) { + return entity; + } - public static StorageHelper getInstance() - { - if( instance == null ) - { - instance = new StorageHelper(); - } - return instance; - } + if (oldWorld == null) { + return entity; + } + if (newWorld == null) { + return entity; + } - /** - * Mostly from dimensional doors.. which mostly got it form X-Comp. - * - * @param entity to be teleported entity - * @param link destination - * @return teleported entity - */ - private Entity teleportEntity( Entity entity, final TelDestination link ) - { - final WorldServer oldWorld; - final WorldServer newWorld; - final EntityPlayerMP player; + // Is something riding? Handle it first. + 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) { + entity.mountEntity(null); + cart = this.teleportEntity(cart, link); + // We keep track of both so we can remount them on the other side. + } - try - { - oldWorld = (WorldServer) entity.worldObj; - newWorld = (WorldServer) link.dim; - player = ( entity instanceof EntityPlayerMP ) ? (EntityPlayerMP) entity : null; - } - catch( final Throwable e ) - { - return entity; - } + // load the chunk! + WorldServer.class.cast(newWorld).getChunkProvider().loadChunk( + MathHelper.floor_double(link.x) >> 4, MathHelper.floor_double(link.z) >> 4 + ); - if( oldWorld == null ) - { - return entity; - } - if( newWorld == null ) - { - return entity; - } + final boolean diffDestination = newWorld != oldWorld; + if (diffDestination) { + if (player != null) { + if (link.dim.provider instanceof StorageWorldProvider) { + Achievements.SpatialIOExplorer.addToPlayer(player); + } - // Is something riding? Handle it first. - 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 ) - { - entity.mountEntity( null ); - cart = this.teleportEntity( cart, link ); - // We keep track of both so we can remount them on the other side. - } + player.mcServer.getConfigurationManager().transferPlayerToDimension( + player, + link.dim.provider.dimensionId, + new METeleporter(newWorld, link) + ); + } else { + final int entX = entity.chunkCoordX; + final int entZ = entity.chunkCoordZ; - // load the chunk! - WorldServer.class.cast( newWorld ).getChunkProvider().loadChunk( MathHelper.floor_double( link.x ) >> 4, MathHelper.floor_double( link.z ) >> 4 ); + if ((entity.addedToChunk) + && (oldWorld.getChunkProvider().chunkExists(entX, entZ))) { + oldWorld.getChunkFromChunkCoords(entX, entZ).removeEntity(entity); + oldWorld.getChunkFromChunkCoords(entX, entZ).isModified = true; + } - final boolean diffDestination = newWorld != oldWorld; - if( diffDestination ) - { - if( player != null ) - { - if( link.dim.provider instanceof StorageWorldProvider ) - { - Achievements.SpatialIOExplorer.addToPlayer( player ); - } + final Entity newEntity = EntityList.createEntityByName( + EntityList.getEntityString(entity), newWorld + ); + 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; - player.mcServer.getConfigurationManager().transferPlayerToDimension( player, link.dim.provider.dimensionId, new METeleporter( newWorld, link ) ); - } - else - { - final int entX = entity.chunkCoordX; - final int entZ = entity.chunkCoordZ; + if (entity instanceof EntityHanging) { + final EntityHanging h = (EntityHanging) entity; + h.field_146063_b += link.xOff; + h.field_146064_c += link.yOff; + h.field_146062_d += link.zOff; + } - if( ( entity.addedToChunk ) && ( oldWorld.getChunkProvider().chunkExists( entX, entZ ) ) ) - { - oldWorld.getChunkFromChunkCoords( entX, entZ ).removeEntity( entity ); - oldWorld.getChunkFromChunkCoords( entX, entZ ).isModified = true; - } + newEntity.copyDataFrom(entity, true); + newEntity.dimension = newWorld.provider.dimensionId; + newEntity.forceSpawn = true; - final Entity newEntity = EntityList.createEntityByName( EntityList.getEntityString( entity ), newWorld ); - 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; + entity.isDead = true; + entity = newEntity; + } else { + return null; + } - if( entity instanceof EntityHanging ) - { - final EntityHanging h = (EntityHanging) entity; - h.field_146063_b += link.xOff; - h.field_146064_c += link.yOff; - h.field_146062_d += link.zOff; - } + // myChunk.addEntity( entity ); + // newWorld.loadedEntityList.add( entity ); + // newWorld.onEntityAdded( entity ); + newWorld.spawnEntityInWorld(entity); + } + } - newEntity.copyDataFrom( entity, true ); - newEntity.dimension = newWorld.provider.dimensionId; - newEntity.forceSpawn = true; + entity.worldObj.updateEntityWithOptionalForce(entity, false); - entity.isDead = true; - entity = newEntity; - } - else - { - return null; - } + if (cart != null) { + if (player != null) { + entity.worldObj.updateEntityWithOptionalForce(entity, true); + } - // myChunk.addEntity( entity ); - // newWorld.loadedEntityList.add( entity ); - // newWorld.onEntityAdded( entity ); - newWorld.spawnEntityInWorld( entity ); - } - } + entity.mountEntity(cart); + } - entity.worldObj.updateEntityWithOptionalForce( entity, false ); + return entity; + } - if( cart != null ) - { - if( player != null ) - { - entity.worldObj.updateEntityWithOptionalForce( entity, true ); - } + private void transverseEdges( + final int minX, + final int minY, + final int minZ, + final int maxX, + final int maxY, + final int maxZ, + final ISpatialVisitor visitor + ) { + for (int y = minY; y < maxY; y++) { + for (int z = minZ; z < maxZ; z++) { + visitor.visit(minX, y, z); + visitor.visit(maxX, y, z); + } + } - entity.mountEntity( cart ); - } + for (int x = minX; x < maxX; x++) { + for (int z = minZ; z < maxZ; z++) { + visitor.visit(x, minY, z); + visitor.visit(x, maxY, z); + } + } - return entity; - } + for (int x = minX; x < maxX; x++) { + for (int y = minY; y < maxY; y++) { + visitor.visit(x, y, minZ); + visitor.visit(x, y, maxZ); + } + } + } - private void transverseEdges( final int minX, final int minY, final int minZ, final int maxX, final int maxY, final int maxZ, final ISpatialVisitor visitor ) - { - for( int y = minY; y < maxY; y++ ) - { - for( int z = minZ; z < maxZ; z++ ) - { - visitor.visit( minX, y, z ); - visitor.visit( maxX, y, z ); - } - } + public void swapRegions( + final World src /** over world **/ + , + final World dst /** storage cell **/ + , + final int x, + final int y, + final int z, + final int i, + final int j, + final int k, + final int scaleX, + final int scaleY, + final int scaleZ + ) { + for (final 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) + ); + } - for( int x = minX; x < maxX; x++ ) - { - for( int z = minZ; z < maxZ; z++ ) - { - visitor.visit( x, minY, z ); - visitor.visit( x, maxY, z ); - } - } + final AxisAlignedBB srcBox = AxisAlignedBB.getBoundingBox( + x, y, z, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1 + ); - for( int x = minX; x < maxX; x++ ) - { - for( int y = minY; y < maxY; y++ ) - { - visitor.visit( x, y, minZ ); - visitor.visit( x, y, maxZ ); - } - } - } + final AxisAlignedBB dstBox = AxisAlignedBB.getBoundingBox( + i, j, k, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1 + ); - public void swapRegions( final World src /** over world **/ - , final World dst /** storage cell **/ - , final int x, final int y, final int z, final int i, final int j, final int k, final int scaleX, final int scaleY, final int scaleZ ) - { - for( final 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 ) ); - } + final CachedPlane cDst + = new CachedPlane(dst, i, j, k, i + scaleX, j + scaleY, k + scaleZ); + final CachedPlane cSrc + = new CachedPlane(src, x, y, z, x + scaleX, y + scaleY, z + scaleZ); - final AxisAlignedBB srcBox = AxisAlignedBB.getBoundingBox( x, y, z, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1 ); + // do nearly all the work... swaps blocks, tiles, and block ticks + cSrc.swap(cDst); - final AxisAlignedBB dstBox = AxisAlignedBB.getBoundingBox( i, j, k, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1 ); + final List srcE = src.getEntitiesWithinAABB(Entity.class, srcBox); + final List dstE = dst.getEntitiesWithinAABB(Entity.class, dstBox); - final CachedPlane cDst = new CachedPlane( dst, i, j, k, i + scaleX, j + scaleY, k + scaleZ ); - final CachedPlane cSrc = new CachedPlane( src, x, y, z, x + scaleX, y + scaleY, z + scaleZ ); + for (final Entity e : dstE) { + this.teleportEntity( + e, + new TelDestination( + src, srcBox, e.posX, e.posY, e.posZ, -i + x, -j + y, -k + z + ) + ); + } - // do nearly all the work... swaps blocks, tiles, and block ticks - cSrc.swap( cDst ); + for (final Entity e : srcE) { + this.teleportEntity( + e, + new TelDestination( + dst, dstBox, e.posX, e.posY, e.posZ, -x + i, -y + j, -z + k + ) + ); + } - final List srcE = src.getEntitiesWithinAABB( Entity.class, srcBox ); - final List dstE = dst.getEntitiesWithinAABB( Entity.class, dstBox ); + for (final WorldCoord wc : cDst.getUpdates()) { + cDst.getWorld().notifyBlockOfNeighborChange( + wc.x, wc.y, wc.z, Platform.AIR_BLOCK + ); + } - for( final Entity e : dstE ) - { - this.teleportEntity( e, new TelDestination( src, srcBox, e.posX, e.posY, e.posZ, -i + x, -j + y, -k + z ) ); - } + for (final WorldCoord wc : cSrc.getUpdates()) { + cSrc.getWorld().notifyBlockOfNeighborChange( + wc.x, wc.y, wc.z, Platform.AIR_BLOCK + ); + } - for( final Entity e : srcE ) - { - this.teleportEntity( e, new TelDestination( dst, dstBox, e.posX, e.posY, e.posZ, -x + i, -y + j, -z + k ) ); - } + this.transverseEdges( + x - 1, + y - 1, + z - 1, + x + scaleX + 1, + y + scaleY + 1, + z + scaleZ + 1, + new TriggerUpdates(src) + ); + this.transverseEdges( + i - 1, + j - 1, + k - 1, + i + scaleX + 1, + j + scaleY + 1, + k + scaleZ + 1, + new TriggerUpdates(dst) + ); - for( final WorldCoord wc : cDst.getUpdates() ) - { - cDst.getWorld().notifyBlockOfNeighborChange( wc.x, wc.y, wc.z, Platform.AIR_BLOCK ); - } + this.transverseEdges( + x, y, z, x + scaleX, y + scaleY, z + scaleZ, new TriggerUpdates(src) + ); + this.transverseEdges( + i, j, k, i + scaleX, j + scaleY, k + scaleZ, new TriggerUpdates(dst) + ); - for( final WorldCoord wc : cSrc.getUpdates() ) - { - cSrc.getWorld().notifyBlockOfNeighborChange( wc.x, wc.y, wc.z, Platform.AIR_BLOCK ); - } + /* + * IChunkProvider cp = destination.getChunkProvider(); if ( cp instanceof + * ChunkProviderServer ) { ChunkProviderServer srv = (ChunkProviderServer) cp; + * srv.unloadAllChunks(); } cp.unloadQueuedChunks(); + */ + } - this.transverseEdges( x - 1, y - 1, z - 1, x + scaleX + 1, y + scaleY + 1, z + scaleZ + 1, new TriggerUpdates( src ) ); - this.transverseEdges( i - 1, j - 1, k - 1, i + scaleX + 1, j + scaleY + 1, k + scaleZ + 1, new TriggerUpdates( dst ) ); + private static class TriggerUpdates implements ISpatialVisitor { + private final World dst; - this.transverseEdges( x, y, z, x + scaleX, y + scaleY, z + scaleZ, new TriggerUpdates( src ) ); - this.transverseEdges( i, j, k, i + scaleX, j + scaleY, k + scaleZ, new TriggerUpdates( dst ) ); + public TriggerUpdates(final World dst2) { + this.dst = dst2; + } - /* - * IChunkProvider cp = destination.getChunkProvider(); if ( cp instanceof ChunkProviderServer ) { - * ChunkProviderServer - * srv = (ChunkProviderServer) cp; srv.unloadAllChunks(); } - * cp.unloadQueuedChunks(); - */ + @Override + public void visit(final int x, final int y, final int z) { + final Block blk = this.dst.getBlock(x, y, z); + blk.onNeighborBlockChange(this.dst, x, y, z, Platform.AIR_BLOCK); + } + } - } + private static class WrapInMatrixFrame implements ISpatialVisitor { + private final World dst; + private final Block blkID; + private final int Meta; - private static class TriggerUpdates implements ISpatialVisitor - { + public WrapInMatrixFrame( + final Block blockID, final int metaData, final World dst2 + ) { + this.dst = dst2; + this.blkID = blockID; + this.Meta = metaData; + } - private final World dst; + @Override + public void visit(final int x, final int y, final int z) { + this.dst.setBlock(x, y, z, this.blkID, this.Meta, 3); + } + } - public TriggerUpdates( final World dst2 ) - { - this.dst = dst2; - } + private static class TelDestination { + private final World dim; + private final double x; + private final double y; + private final double z; + private final int xOff; + private final int yOff; + private final int zOff; - @Override - public void visit( final int x, final int y, final int z ) - { - final Block blk = this.dst.getBlock( x, y, z ); - blk.onNeighborBlockChange( this.dst, x, y, z, Platform.AIR_BLOCK ); - } - } + TelDestination( + final World dimension, + final AxisAlignedBB srcBox, + final double x, + final double y, + final double z, + final int tileX, + final int tileY, + final int tileZ + ) { + this.dim = dimension; + 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; + } + } + private static class METeleporter extends Teleporter { + private final TelDestination destination; - private static class WrapInMatrixFrame implements ISpatialVisitor - { + public METeleporter(final WorldServer par1WorldServer, final TelDestination d) { + super(par1WorldServer); + this.destination = d; + } - private final World dst; - private final Block blkID; - private final int Meta; + @Override + public void placeInPortal( + final Entity par1Entity, + final double par2, + final double par4, + final double par6, + final 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; + } - public WrapInMatrixFrame( final Block blockID, final int metaData, final World dst2 ) - { - this.dst = dst2; - this.blkID = blockID; - this.Meta = metaData; - } + @Override + public boolean placeInExistingPortal( + final Entity par1Entity, + final double par2, + final double par4, + final double par6, + final float par8 + ) { + return false; + } - @Override - public void visit( final int x, final int y, final int z ) - { - this.dst.setBlock( x, y, z, this.blkID, this.Meta, 3 ); - } - } + @Override + public boolean makePortal(final Entity par1Entity) { + return false; + } - - private static class TelDestination - { - - private final World dim; - private final double x; - private final double y; - private final double z; - private final int xOff; - private final int yOff; - private final int zOff; - - TelDestination( final World dimension, final AxisAlignedBB srcBox, final double x, final double y, final double z, final int tileX, final int tileY, final int tileZ ) - { - this.dim = dimension; - 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; - } - } - - - private static class METeleporter extends Teleporter - { - - private final TelDestination destination; - - public METeleporter( final WorldServer par1WorldServer, final TelDestination d ) - { - super( par1WorldServer ); - this.destination = d; - } - - @Override - public void placeInPortal( final Entity par1Entity, final double par2, final double par4, final double par6, final 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( final Entity par1Entity, final double par2, final double par4, final double par6, final float par8 ) - { - return false; - } - - @Override - public boolean makePortal( final Entity par1Entity ) - { - return false; - } - - @Override - public void removeStalePortalLocations( final long par1 ) - { - - } - } + @Override + public void removeStalePortalLocations(final long par1) {} + } } diff --git a/src/main/java/appeng/spatial/StorageWorldProvider.java b/src/main/java/appeng/spatial/StorageWorldProvider.java index 3eee9324..029b7aec 100644 --- a/src/main/java/appeng/spatial/StorageWorldProvider.java +++ b/src/main/java/appeng/spatial/StorageWorldProvider.java @@ -18,7 +18,6 @@ package appeng.spatial; - import appeng.client.render.SpatialSkyRender; import appeng.core.AppEng; import appeng.core.Registration; @@ -34,126 +33,107 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraftforge.client.IRenderHandler; +public class StorageWorldProvider extends WorldProvider { + public StorageWorldProvider() { + this.hasNoSky = true; + } -public class StorageWorldProvider extends WorldProvider -{ + @Override + protected void registerWorldChunkManager() { + final AppEng ae2internal = AppEng.instance(); + final Registration ae2registration = ae2internal.getRegistration(); + final BiomeGenBase storageBiome = ae2registration.getStorageBiome(); - public StorageWorldProvider() - { - this.hasNoSky = true; - } + super.worldChunkMgr = new WorldChunkManagerHell(storageBiome, 0.0F); + } - @Override - protected void registerWorldChunkManager() - { - final AppEng ae2internal = AppEng.instance(); - final Registration ae2registration = ae2internal.getRegistration(); - final BiomeGenBase storageBiome = ae2registration.getStorageBiome(); + @Override + public IChunkProvider createChunkGenerator() { + return new StorageChunkProvider(this.worldObj, 0); + } - super.worldChunkMgr = new WorldChunkManagerHell( storageBiome, 0.0F ); - } + @Override + public float calculateCelestialAngle(final long par1, final float par3) { + return 0; + } - @Override - public IChunkProvider createChunkGenerator() - { - return new StorageChunkProvider( this.worldObj, 0 ); - } + @Override + public boolean isSurfaceWorld() { + return false; + } - @Override - public float calculateCelestialAngle( final long par1, final float par3 ) - { - return 0; - } + @Override + @SideOnly(Side.CLIENT) + public float[] calcSunriseSunsetColors( + final float celestialAngle, final float partialTicks + ) { + return null; + } - @Override - public boolean isSurfaceWorld() - { - return false; - } + @Override + public Vec3 getFogColor(final float par1, final float par2) { + return Vec3.createVectorHelper(0.07, 0.07, 0.07); + } - @Override - @SideOnly( Side.CLIENT ) - public float[] calcSunriseSunsetColors( final float celestialAngle, final float partialTicks ) - { - return null; - } + @Override + public boolean canRespawnHere() { + return false; + } - @Override - public Vec3 getFogColor( final float par1, final float par2 ) - { - return Vec3.createVectorHelper( 0.07, 0.07, 0.07 ); - } + @Override + @SideOnly(Side.CLIENT) + public boolean isSkyColored() { + return true; + } - @Override - public boolean canRespawnHere() - { - return false; - } + @Override + public boolean doesXZShowFog(final int par1, final int par2) { + return false; + } - @Override - @SideOnly( Side.CLIENT ) - public boolean isSkyColored() - { - return true; - } + @Override + public String getDimensionName() { + return "Storage Cell"; + } - @Override - public boolean doesXZShowFog( final int par1, final int par2 ) - { - return false; - } + @Override + public IRenderHandler getSkyRenderer() { + return SpatialSkyRender.getInstance(); + } - @Override - public String getDimensionName() - { - return "Storage Cell"; - } + @Override + public boolean isDaytime() { + return false; + } - @Override - public IRenderHandler getSkyRenderer() - { - return SpatialSkyRender.getInstance(); - } + @Override + public Vec3 getSkyColor(final Entity cameraEntity, final float partialTicks) { + return Vec3.createVectorHelper(0.07, 0.07, 0.07); + } - @Override - public boolean isDaytime() - { - return false; - } + @Override + public float getStarBrightness(final float par1) { + return 0; + } - @Override - public Vec3 getSkyColor( final Entity cameraEntity, final float partialTicks ) - { - return Vec3.createVectorHelper( 0.07, 0.07, 0.07 ); - } + @Override + public boolean + canSnowAt(final int x, final int y, final int z, final boolean checkLight) { + return false; + } - @Override - public float getStarBrightness( final float par1 ) - { - return 0; - } + @Override + public ChunkCoordinates getSpawnPoint() { + return new ChunkCoordinates(0, 0, 0); + } - @Override - public boolean canSnowAt( final int x, final int y, final int z, final boolean checkLight ) - { - return false; - } + @Override + public boolean isBlockHighHumidity(final int x, final int y, final int z) { + return false; + } - @Override - public ChunkCoordinates getSpawnPoint() - { - return new ChunkCoordinates( 0, 0, 0 ); - } - - @Override - public boolean isBlockHighHumidity( final int x, final int y, final int z ) - { - return false; - } - - @Override - public boolean canDoLightning( final Chunk chunk ) - { - return false; - } + @Override + public boolean canDoLightning(final Chunk chunk) { + return false; + } } diff --git a/src/main/java/appeng/tile/AEBaseInvTile.java b/src/main/java/appeng/tile/AEBaseInvTile.java index f0b2da24..250a1228 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 javax.annotation.Nullable; import appeng.block.AEBaseBlock; import appeng.tile.events.TileEventType; @@ -31,148 +32,130 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; +public abstract class AEBaseInvTile + extends AEBaseTile implements ISidedInventory, IAEAppEngInventory { + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AEBaseInvTile(final net.minecraft.nbt.NBTTagCompound data) { + final IInventory inv = this.getInternalInventory(); + final NBTTagCompound opt = data.getCompoundTag("inv"); + for (int x = 0; x < inv.getSizeInventory(); x++) { + final NBTTagCompound item = opt.getCompoundTag("item" + x); + inv.setInventorySlotContents(x, ItemStack.loadItemStackFromNBT(item)); + } + } + public abstract IInventory getInternalInventory(); -public abstract class AEBaseInvTile extends AEBaseTile implements ISidedInventory, IAEAppEngInventory -{ + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AEBaseInvTile(final net.minecraft.nbt.NBTTagCompound data) { + final IInventory inv = this.getInternalInventory(); + final NBTTagCompound opt = new NBTTagCompound(); + for (int x = 0; x < inv.getSizeInventory(); x++) { + final NBTTagCompound item = new NBTTagCompound(); + final ItemStack is = this.getStackInSlot(x); + if (is != null) { + is.writeToNBT(item); + } + opt.setTag("item" + x, item); + } + data.setTag("inv", opt); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AEBaseInvTile( final net.minecraft.nbt.NBTTagCompound data ) - { - final IInventory inv = this.getInternalInventory(); - final NBTTagCompound opt = data.getCompoundTag( "inv" ); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - final NBTTagCompound item = opt.getCompoundTag( "item" + x ); - inv.setInventorySlotContents( x, ItemStack.loadItemStackFromNBT( item ) ); - } - } + @Override + public int getSizeInventory() { + return this.getInternalInventory().getSizeInventory(); + } - public abstract IInventory getInternalInventory(); + @Override + public ItemStack getStackInSlot(final int i) { + return this.getInternalInventory().getStackInSlot(i); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AEBaseInvTile( final net.minecraft.nbt.NBTTagCompound data ) - { - final IInventory inv = this.getInternalInventory(); - final NBTTagCompound opt = new NBTTagCompound(); - for( int x = 0; x < inv.getSizeInventory(); x++ ) - { - final NBTTagCompound item = new NBTTagCompound(); - final ItemStack is = this.getStackInSlot( x ); - if( is != null ) - { - is.writeToNBT( item ); - } - opt.setTag( "item" + x, item ); - } - data.setTag( "inv", opt ); - } + @Override + public ItemStack decrStackSize(final int i, final int j) { + return this.getInternalInventory().decrStackSize(i, j); + } - @Override - public int getSizeInventory() - { - return this.getInternalInventory().getSizeInventory(); - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.getInternalInventory().getStackInSlot( i ); - } + @Override + public void + setInventorySlotContents(final int i, @Nullable final ItemStack itemstack) { + this.getInternalInventory().setInventorySlotContents(i, itemstack); + } - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return this.getInternalInventory().decrStackSize( i, j ); - } + /** + * Returns the name of the inventory + */ + @Override + public String getInventoryName() { + return this.getCustomName(); + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } + /** + * Returns if the inventory is named + */ + @Override + public boolean hasCustomInventoryName() { + return this.hasCustomName(); + } - @Override - public void setInventorySlotContents( final int i, @Nullable final ItemStack itemstack ) - { - this.getInternalInventory().setInventorySlotContents( i, itemstack ); - } + @Override + public int getInventoryStackLimit() { + return 64; + } - /** - * Returns the name of the inventory - */ - @Override - public String getInventoryName() - { - return this.getCustomName(); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer p) { + final double squaredMCReach = 64.0D; - /** - * Returns if the inventory is named - */ - @Override - public boolean hasCustomInventoryName() - { - return this.hasCustomName(); - } + 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 int getInventoryStackLimit() - { - return 64; - } + @Override + public void openInventory() {} - @Override - public boolean isUseableByPlayer( final EntityPlayer p ) - { - final double squaredMCReach = 64.0D; + @Override + public void closeInventory() {} - 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(final int i, final ItemStack itemstack) { + return true; + } - @Override - public void openInventory() - { - } + @Override + public abstract void onChangeInventory( + IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added + ); - @Override - public void closeInventory() - { - } + @Override + public final int[] getAccessibleSlotsFromSide(final int side) { + final Block blk = this.worldObj.getBlock(this.xCoord, this.yCoord, this.zCoord); + if (blk instanceof AEBaseBlock) { + final ForgeDirection mySide = ForgeDirection.getOrientation(side); + return this.getAccessibleSlotsBySide( + ((AEBaseBlock) blk).mapRotation(this, mySide) + ); + } + return this.getAccessibleSlotsBySide(ForgeDirection.getOrientation(side)); + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return true; - } + @Override + public boolean + canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + return this.isItemValidForSlot(slotIndex, insertingItem); + } - @Override - public abstract void onChangeInventory( IInventory inv, int slot, InvOperation mc, ItemStack removed, ItemStack added ); + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return true; + } - @Override - public final int[] getAccessibleSlotsFromSide( final int side ) - { - final Block blk = this.worldObj.getBlock( this.xCoord, this.yCoord, this.zCoord ); - if( blk instanceof AEBaseBlock ) - { - final ForgeDirection mySide = ForgeDirection.getOrientation( side ); - return this.getAccessibleSlotsBySide( ( (AEBaseBlock) blk ).mapRotation( this, mySide ) ); - } - return this.getAccessibleSlotsBySide( ForgeDirection.getOrientation( side ) ); - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - return this.isItemValidForSlot( slotIndex, insertingItem ); - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return true; - } - - public abstract int[] getAccessibleSlotsBySide( ForgeDirection whichSide ); + 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 ad9e6e13..ee3e7412 100644 --- a/src/main/java/appeng/tile/AEBaseTile.java +++ b/src/main/java/appeng/tile/AEBaseTile.java @@ -18,6 +18,11 @@ package appeng.tile; +import java.lang.ref.WeakReference; +import java.lang.reflect.Method; +import java.util.*; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.implementations.tiles.ISegmentedInventory; import appeng.api.util.ICommonTile; @@ -46,539 +51,468 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.lang.ref.WeakReference; -import java.lang.reflect.Method; -import java.util.*; - - -public class AEBaseTile extends TileEntity implements IOrientable, ICommonTile, ICustomNameObject -{ - - private static final ThreadLocal> DROP_NO_ITEMS = new ThreadLocal>(); - private static final Map, Map>> HANDLERS = new HashMap, Map>>(); - private static final Map, IStackSrc> ITEM_STACKS = new HashMap, IStackSrc>(); - private int renderFragment = 0; - @Nullable - private String customName; - private ForgeDirection forward = ForgeDirection.UNKNOWN; - private ForgeDirection up = ForgeDirection.UNKNOWN; - - public static void registerTileItem( final Class c, final IStackSrc wat ) - { - ITEM_STACKS.put( c, wat ); - } - - public boolean dropItems() - { - final WeakReference what = DROP_NO_ITEMS.get(); - return what == null || what.get() != this; - } - - public boolean notLoaded() - { - return !this.worldObj.blockExists( this.xCoord, this.yCoord, this.zCoord ); - } - - @Nonnull - public TileEntity getTile() - { - return this; - } - - @Nullable - protected ItemStack getItemFromTile( final Object obj ) - { - final IStackSrc src = ITEM_STACKS.get( obj.getClass() ); - if( src == null ) - { - return null; - } - return src.stack( 1 ); - } - - /** - * for dormant chunk cache. - */ - public void onChunkLoad() - { - if( this.isInvalid() ) - { - this.validate(); - } - } - - @Override - // NOTE: WAS FINAL, changed for Immibis - public void readFromNBT(final 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( final IllegalArgumentException ignored ) - { - } - - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_READ ) ) - { - h.readFromNBT( this, data ); - } - } - - @Override - // NOTE: WAS FINAL, changed for Immibis - public void writeToNBT(final 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( final AETileEventHandler h : this.getHandlerListFor( TileEventType.WORLD_NBT_WRITE ) ) - { - h.writeToNBT( this, data ); - } - } - - @Override - public final void updateEntity() - { - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.TICK ) ) - { - h.tick( this ); - } - } - - @Override - public Packet getDescriptionPacket() - { - final NBTTagCompound data = new NBTTagCompound(); - - final ByteBuf stream = Unpooled.buffer(); - - try - { - this.writeToStream( stream ); - if( stream.readableBytes() == 0 ) - { - return null; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - stream.capacity( stream.readableBytes() ); - data.setByteArray( "X", stream.array() ); - return new S35PacketUpdateTileEntity( this.xCoord, this.yCoord, this.zCoord, 64, data ); - } - - @Override - public final boolean canUpdate() - { - return this.hasHandlerFor( TileEventType.TICK ); - } - - private boolean hasHandlerFor( final TileEventType type ) - { - final List list = this.getHandlerListFor( type ); - - return !list.isEmpty(); - } - - @Override - public void onDataPacket( final NetworkManager net, final S35PacketUpdateTileEntity pkt ) - { - // / pkt.actionType - if( pkt.func_148853_f() == 64 ) - { - final ByteBuf stream = Unpooled.copiedBuffer( pkt.func_148857_g().getByteArray( "X" ) ); - if( this.readFromStream( stream ) ) - { - this.markForUpdate(); - } - } - } - - @Override - public void onChunkUnload() - { - if( !this.isInvalid() ) - { - this.invalidate(); - } - } - - private final boolean readFromStream( final ByteBuf data ) - { - boolean output = false; - - try - { - - if( this.canBeRotated() ) - { - final ForgeDirection old_Forward = this.forward; - final ForgeDirection old_Up = this.up; - - final byte orientation = data.readByte(); - this.forward = ForgeDirection.getOrientation( orientation & 0x7 ); - this.up = ForgeDirection.getOrientation( orientation >> 3 ); - - output = this.forward != old_Forward || this.up != old_Up; - } - - this.renderFragment = 100; - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_READ ) ) - { - if( h.readFromStream( this, data ) ) - { - output = true; - } - } - - if( ( this.renderFragment & 1 ) == 1 ) - { - output = true; - } - this.renderFragment = 0; - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - 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 ); - } - } - } - - private final void writeToStream( final ByteBuf data ) - { - try - { - if( this.canBeRotated() ) - { - final byte orientation = (byte) ( ( this.up.ordinal() << 3 ) | this.forward.ordinal() ); - data.writeByte( orientation ); - } - - for( final AETileEventHandler h : this.getHandlerListFor( TileEventType.NETWORK_WRITE ) ) - { - h.writeToStream( this, data ); - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - /** - * By default all blocks can have orientation, this handles saving, and loading, as well as synchronization. - * - * @return true if tile can be rotated - */ - @Override - public boolean canBeRotated() - { - return true; - } - - @Nonnull - private List getHandlerListFor( final TileEventType type ) - { - final Map> eventToHandlers = this.getEventToHandlers(); - final List handlers = this.getHandlers( eventToHandlers, type ); - - return handlers; - } - - @Nonnull - private Map> getEventToHandlers() - { - final Class clazz = this.getClass(); - final Map> storedHandlers = HANDLERS.get( clazz ); - - if( storedHandlers == null ) - { - final Map> newStoredHandlers = new EnumMap>( TileEventType.class ); - - HANDLERS.put( clazz, newStoredHandlers ); - - for( final Method method : clazz.getMethods() ) - { - final TileEvent event = method.getAnnotation( TileEvent.class ); - if( event != null ) - { - this.addHandler( newStoredHandlers, event.value(), method ); - } - } - - return newStoredHandlers; - } - else - { - return storedHandlers; - } - } - - @Nonnull - private List getHandlers( final Map> eventToHandlers, final TileEventType event ) - { - final List oldHandlers = eventToHandlers.get( event ); - - if( oldHandlers == null ) - { - final List newHandlers = new LinkedList(); - eventToHandlers.put( event, newHandlers ); - - return newHandlers; - } - else - { - return oldHandlers; - } - } - - private void addHandler( final Map> handlerSet, final TileEventType value, final Method m ) - { - List list = handlerSet.get( value ); - - if( list == null ) - { - list = new ArrayList(); - handlerSet.put( value, list ); - } - - list.add( new AETileEventHandler( m ) ); - } - - @Override - public ForgeDirection getForward() - { - return this.forward; - } - - @Override - public ForgeDirection getUp() - { - return this.up; - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - this.forward = inForward; - this.up = inUp; - this.markForUpdate(); - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - - public void onPlacement( final ItemStack stack, final EntityPlayer player, final int side ) - { - if( stack.hasTagCompound() ) - { - this.uploadSettings( SettingsFrom.DISMANTLE_ITEM, stack.getTagCompound() ); - } - } - - /** - * 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( final SettingsFrom from, final NBTTagCompound compound ) - { - if( compound != null && this instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); - if( cm != null ) - { - cm.readFromNBT( compound ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - pHost.setPriority( compound.getInteger( "priority" ) ); - } - - if( this instanceof ISegmentedInventory ) - { - final IInventory inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; - final 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 ) ); - } - } - } - } - - /** - * 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 drops drops of tile entity - */ - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - if( this instanceof IInventory ) - { - final IInventory inv = (IInventory) this; - - for( int l = 0; l < inv.getSizeInventory(); l++ ) - { - final ItemStack is = inv.getStackInSlot( l ); - if( is != null ) - { - drops.add( is ); - } - } - } - } - - public void getNoDrops( final World w, final int x, final int y, final int z, final List drops ) - { - - } - - public void onReady() - { - - } - - /** - * null means nothing to store... - * - * @param from source of settings - * @return compound of source - */ - public NBTTagCompound downloadSettings( final SettingsFrom from ) - { - final NBTTagCompound output = new NBTTagCompound(); - - if( this.hasCustomName() ) - { - final NBTTagCompound dsp = new NBTTagCompound(); - dsp.setString( "Name", this.getCustomName() ); - output.setTag( "display", dsp ); - } - - if( this instanceof IConfigurableObject ) - { - final IConfigManager cm = ( (IConfigurableObject) this ).getConfigManager(); - if( cm != null ) - { - cm.writeToNBT( output ); - } - } - - if( this instanceof IPriorityHost ) - { - final IPriorityHost pHost = (IPriorityHost) this; - output.setInteger( "priority", pHost.getPriority() ); - } - - if( this instanceof ISegmentedInventory ) - { - final IInventory inv = ( (ISegmentedInventory) this ).getInventoryByName( "config" ); - if( inv instanceof AppEngInternalAEInventory ) - { - ( (AppEngInternalAEInventory) inv ).writeToNBT( output, "config" ); - } - } - - return output.hasNoTags() ? null : output; - } - - @Override - public String getCustomName() - { - return this.hasCustomName() ? this.customName : this.getClass().getSimpleName(); - } - - @Override - public boolean hasCustomName() - { - 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( final String name ) - { - this.customName = name; - } +public class AEBaseTile + extends TileEntity implements IOrientable, ICommonTile, ICustomNameObject { + private static final ThreadLocal> DROP_NO_ITEMS + = new ThreadLocal>(); + private static final + Map, Map>> + HANDLERS = new HashMap< + Class, + Map>>(); + private static final Map, IStackSrc> ITEM_STACKS + = new HashMap, IStackSrc>(); + private int renderFragment = 0; + @Nullable + private String customName; + private ForgeDirection forward = ForgeDirection.UNKNOWN; + private ForgeDirection up = ForgeDirection.UNKNOWN; + + public static void + registerTileItem(final Class c, final IStackSrc wat) { + ITEM_STACKS.put(c, wat); + } + + public boolean dropItems() { + final WeakReference what = DROP_NO_ITEMS.get(); + return what == null || what.get() != this; + } + + public boolean notLoaded() { + return !this.worldObj.blockExists(this.xCoord, this.yCoord, this.zCoord); + } + + @Nonnull + public TileEntity getTile() { + return this; + } + + @Nullable + protected ItemStack getItemFromTile(final Object obj) { + final IStackSrc src = ITEM_STACKS.get(obj.getClass()); + if (src == null) { + return null; + } + return src.stack(1); + } + + /** + * for dormant chunk cache. + */ + public void onChunkLoad() { + if (this.isInvalid()) { + this.validate(); + } + } + + @Override + // NOTE: WAS FINAL, changed for Immibis + public void readFromNBT(final 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 (final IllegalArgumentException ignored) {} + + for (final AETileEventHandler h : + this.getHandlerListFor(TileEventType.WORLD_NBT_READ)) { + h.readFromNBT(this, data); + } + } + + @Override + // NOTE: WAS FINAL, changed for Immibis + public void writeToNBT(final 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 (final AETileEventHandler h : + this.getHandlerListFor(TileEventType.WORLD_NBT_WRITE)) { + h.writeToNBT(this, data); + } + } + + @Override + public final void updateEntity() { + for (final AETileEventHandler h : this.getHandlerListFor(TileEventType.TICK)) { + h.tick(this); + } + } + + @Override + public Packet getDescriptionPacket() { + final NBTTagCompound data = new NBTTagCompound(); + + final ByteBuf stream = Unpooled.buffer(); + + try { + this.writeToStream(stream); + if (stream.readableBytes() == 0) { + return null; + } + } catch (final Throwable t) { + AELog.debug(t); + } + + stream.capacity(stream.readableBytes()); + data.setByteArray("X", stream.array()); + return new S35PacketUpdateTileEntity( + this.xCoord, this.yCoord, this.zCoord, 64, data + ); + } + + @Override + public final boolean canUpdate() { + return this.hasHandlerFor(TileEventType.TICK); + } + + private boolean hasHandlerFor(final TileEventType type) { + final List list = this.getHandlerListFor(type); + + return !list.isEmpty(); + } + + @Override + public void + onDataPacket(final NetworkManager net, final S35PacketUpdateTileEntity pkt) { + // / pkt.actionType + if (pkt.func_148853_f() == 64) { + final ByteBuf stream + = Unpooled.copiedBuffer(pkt.func_148857_g().getByteArray("X")); + if (this.readFromStream(stream)) { + this.markForUpdate(); + } + } + } + + @Override + public void onChunkUnload() { + if (!this.isInvalid()) { + this.invalidate(); + } + } + + private final boolean readFromStream(final ByteBuf data) { + boolean output = false; + + try { + if (this.canBeRotated()) { + final ForgeDirection old_Forward = this.forward; + final ForgeDirection old_Up = this.up; + + final byte orientation = data.readByte(); + this.forward = ForgeDirection.getOrientation(orientation & 0x7); + this.up = ForgeDirection.getOrientation(orientation >> 3); + + output = this.forward != old_Forward || this.up != old_Up; + } + + this.renderFragment = 100; + for (final AETileEventHandler h : + this.getHandlerListFor(TileEventType.NETWORK_READ)) { + if (h.readFromStream(this, data)) { + output = true; + } + } + + if ((this.renderFragment & 1) == 1) { + output = true; + } + this.renderFragment = 0; + } catch (final Throwable t) { + AELog.debug(t); + } + + 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); + } + } + } + + private final void writeToStream(final ByteBuf data) { + try { + if (this.canBeRotated()) { + final byte orientation + = (byte) ((this.up.ordinal() << 3) | this.forward.ordinal()); + data.writeByte(orientation); + } + + for (final AETileEventHandler h : + this.getHandlerListFor(TileEventType.NETWORK_WRITE)) { + h.writeToStream(this, data); + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + + /** + * By default all blocks can have orientation, this handles saving, and loading, as + * well as synchronization. + * + * @return true if tile can be rotated + */ + @Override + public boolean canBeRotated() { + return true; + } + + @Nonnull + private List getHandlerListFor(final TileEventType type) { + final Map> eventToHandlers + = this.getEventToHandlers(); + final List handlers = this.getHandlers(eventToHandlers, type); + + return handlers; + } + + @Nonnull + private Map> getEventToHandlers() { + final Class clazz = this.getClass(); + final Map> storedHandlers + = HANDLERS.get(clazz); + + if (storedHandlers == null) { + final Map> newStoredHandlers + = new EnumMap>(TileEventType + .class); + + HANDLERS.put(clazz, newStoredHandlers); + + for (final Method method : clazz.getMethods()) { + final TileEvent event = method.getAnnotation(TileEvent.class); + if (event != null) { + this.addHandler(newStoredHandlers, event.value(), method); + } + } + + return newStoredHandlers; + } else { + return storedHandlers; + } + } + + @Nonnull + private List getHandlers( + final Map> eventToHandlers, + final TileEventType event + ) { + final List oldHandlers = eventToHandlers.get(event); + + if (oldHandlers == null) { + final List newHandlers + = new LinkedList(); + eventToHandlers.put(event, newHandlers); + + return newHandlers; + } else { + return oldHandlers; + } + } + + private void addHandler( + final Map> handlerSet, + final TileEventType value, + final Method m + ) { + List list = handlerSet.get(value); + + if (list == null) { + list = new ArrayList(); + handlerSet.put(value, list); + } + + list.add(new AETileEventHandler(m)); + } + + @Override + public ForgeDirection getForward() { + return this.forward; + } + + @Override + public ForgeDirection getUp() { + return this.up; + } + + @Override + public void + setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + this.forward = inForward; + this.up = inUp; + this.markForUpdate(); + Platform.notifyBlocksOfNeighbors( + this.worldObj, this.xCoord, this.yCoord, this.zCoord + ); + } + + public void + onPlacement(final ItemStack stack, final EntityPlayer player, final int side) { + if (stack.hasTagCompound()) { + this.uploadSettings(SettingsFrom.DISMANTLE_ITEM, stack.getTagCompound()); + } + } + + /** + * 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(final SettingsFrom from, final NBTTagCompound compound) { + if (compound != null && this instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); + if (cm != null) { + cm.readFromNBT(compound); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + pHost.setPriority(compound.getInteger("priority")); + } + + if (this instanceof ISegmentedInventory) { + final IInventory inv + = ((ISegmentedInventory) this).getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + final AppEngInternalAEInventory target = (AppEngInternalAEInventory) inv; + final 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)); + } + } + } + } + + /** + * 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 drops drops of tile entity + */ + @Override + public void getDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + if (this instanceof IInventory) { + final IInventory inv = (IInventory) this; + + for (int l = 0; l < inv.getSizeInventory(); l++) { + final ItemStack is = inv.getStackInSlot(l); + if (is != null) { + drops.add(is); + } + } + } + } + + public void getNoDrops( + final World w, final int x, final int y, final int z, final List drops + ) {} + + public void onReady() {} + + /** + * null means nothing to store... + * + * @param from source of settings + * @return compound of source + */ + public NBTTagCompound downloadSettings(final SettingsFrom from) { + final NBTTagCompound output = new NBTTagCompound(); + + if (this.hasCustomName()) { + final NBTTagCompound dsp = new NBTTagCompound(); + dsp.setString("Name", this.getCustomName()); + output.setTag("display", dsp); + } + + if (this instanceof IConfigurableObject) { + final IConfigManager cm = ((IConfigurableObject) this).getConfigManager(); + if (cm != null) { + cm.writeToNBT(output); + } + } + + if (this instanceof IPriorityHost) { + final IPriorityHost pHost = (IPriorityHost) this; + output.setInteger("priority", pHost.getPriority()); + } + + if (this instanceof ISegmentedInventory) { + final IInventory inv + = ((ISegmentedInventory) this).getInventoryByName("config"); + if (inv instanceof AppEngInternalAEInventory) { + ((AppEngInternalAEInventory) inv).writeToNBT(output, "config"); + } + } + + return output.hasNoTags() ? null : output; + } + + @Override + public String getCustomName() { + return this.hasCustomName() ? this.customName : this.getClass().getSimpleName(); + } + + @Override + public boolean hasCustomName() { + 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(final String name) { + this.customName = name; + } } diff --git a/src/main/java/appeng/tile/TileEvent.java b/src/main/java/appeng/tile/TileEvent.java index 8a0024f1..26f2588f 100644 --- a/src/main/java/appeng/tile/TileEvent.java +++ b/src/main/java/appeng/tile/TileEvent.java @@ -18,16 +18,12 @@ package appeng.tile; - -import appeng.tile.events.TileEventType; - import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import appeng.tile.events.TileEventType; -@Retention( RetentionPolicy.RUNTIME ) -public @interface TileEvent -{ - - TileEventType value(); +@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 4657730c..ac8b1423 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 appeng.api.implementations.tiles.IColorableTile; import appeng.api.storage.data.IAEItemStack; @@ -32,150 +33,122 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; +public class TileCraftingMonitorTile extends TileCraftingTile implements IColorableTile { + @SideOnly(Side.CLIENT) + private Integer dspList; + @SideOnly(Side.CLIENT) + private boolean updateList; -public class TileCraftingMonitorTile extends TileCraftingTile implements IColorableTile -{ + private IAEItemStack dspPlay; + private AEColor paintedColor = AEColor.Transparent; - @SideOnly( Side.CLIENT ) - private Integer dspList; + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCraftingMonitorTile(final ByteBuf data) + throws IOException { + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; - @SideOnly( Side.CLIENT ) - private boolean updateList; + final boolean hasItem = data.readBoolean(); - private IAEItemStack dspPlay; - private AEColor paintedColor = AEColor.Transparent; + if (hasItem) { + this.dspPlay = AEItemStack.loadItemStackFromPacket(data); + } else { + this.dspPlay = null; + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCraftingMonitorTile( final ByteBuf data ) throws IOException - { - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; + this.setUpdateList(true); + return oldPaintedColor != this.paintedColor; // tesr! + } - final boolean hasItem = data.readBoolean(); + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCraftingMonitorTile(final ByteBuf data) + throws IOException { + data.writeByte(this.paintedColor.ordinal()); - if( hasItem ) - { - this.dspPlay = AEItemStack.loadItemStackFromPacket( data ); - } - else - { - this.dspPlay = null; - } + if (this.dspPlay == null) { + data.writeBoolean(false); + } else { + data.writeBoolean(true); + this.dspPlay.writeToPacket(data); + } + } - this.setUpdateList( true ); - return oldPaintedColor != this.paintedColor; // tesr! - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCraftingMonitorTile(final NBTTagCompound data) { + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCraftingMonitorTile( final ByteBuf data ) throws IOException - { - data.writeByte( this.paintedColor.ordinal() ); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCraftingMonitorTile(final NBTTagCompound data) { + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); + } - if( this.dspPlay == null ) - { - data.writeBoolean( false ); - } - else - { - data.writeBoolean( true ); - this.dspPlay.writeToPacket( data ); - } - } + @Override + public boolean isAccelerator() { + return false; + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCraftingMonitorTile( final NBTTagCompound data ) - { - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } - } + @Override + public boolean isStatus() { + return true; + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCraftingMonitorTile( final NBTTagCompound data ) - { - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - } + public void setJob(final IAEItemStack is) { + if ((is == null) != (this.dspPlay == null)) { + this.dspPlay = is == null ? null : is.copy(); + this.markForUpdate(); + } else if (is != null && this.dspPlay != null) { + if (is.getStackSize() != this.dspPlay.getStackSize()) { + this.dspPlay = is.copy(); + this.markForUpdate(); + } + } + } - @Override - public boolean isAccelerator() - { - return false; - } + public IAEItemStack getJobProgress() { + return this.dspPlay; // AEItemStack.create( new ItemStack( Items.diamond, 64 ) ); + } - @Override - public boolean isStatus() - { - return true; - } + @Override + public boolean requiresTESR() { + return this.dspPlay != null; + } - public void setJob( final IAEItemStack is ) - { - if( ( is == null ) != ( this.dspPlay == null ) ) - { - this.dspPlay = is == null ? null : is.copy(); - this.markForUpdate(); - } - else if( is != null && this.dspPlay != null ) - { - if( is.getStackSize() != this.dspPlay.getStackSize() ) - { - this.dspPlay = is.copy(); - this.markForUpdate(); - } - } - } + @Override + public AEColor getColor() { + return this.paintedColor; + } - public IAEItemStack getJobProgress() - { - return this.dspPlay;// AEItemStack.create( new ItemStack( Items.diamond, 64 ) ); - } + @Override + public boolean recolourBlock( + final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who + ) { + if (this.paintedColor == newPaintedColor) { + return false; + } - @Override - public boolean requiresTESR() - { - return this.dspPlay != null; - } + this.paintedColor = newPaintedColor; + this.markDirty(); + this.markForUpdate(); + return true; + } - @Override - public AEColor getColor() - { - return this.paintedColor; - } + public Integer getDisplayList() { + return this.dspList; + } - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } + public void setDisplayList(final Integer dspList) { + this.dspList = dspList; + } - this.paintedColor = newPaintedColor; - this.markDirty(); - this.markForUpdate(); - return true; - } + public boolean isUpdateList() { + return this.updateList; + } - public Integer getDisplayList() - { - return this.dspList; - } - - public void setDisplayList( final Integer dspList ) - { - this.dspList = dspList; - } - - public boolean isUpdateList() - { - return this.updateList; - } - - public void setUpdateList( final boolean updateList ) - { - this.updateList = updateList; - } + public void setUpdateList(final boolean updateList) { + this.updateList = updateList; + } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java index b015d136..c0647bcd 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingStorageTile.java @@ -18,78 +18,69 @@ package appeng.tile.crafting; - import appeng.api.AEApi; import appeng.api.definitions.IBlocks; import net.minecraft.item.ItemStack; +public class TileCraftingStorageTile extends TileCraftingTile { + private static final int KILO_SCALAR = 1024; -public class TileCraftingStorageTile extends TileCraftingTile -{ - private static final int KILO_SCALAR = 1024; + @Override + protected ItemStack getItemFromTile(final Object obj) { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final int storage = ((TileCraftingTile) obj).getStorageBytes() / KILO_SCALAR; - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final int storage = ( (TileCraftingTile) obj ).getStorageBytes() / KILO_SCALAR; + switch (storage) { + case 4: + for (final ItemStack stack : + blocks.craftingStorage4k().maybeStack(1).asSet()) { + return stack; + } + break; + case 16: + for (final ItemStack stack : + blocks.craftingStorage16k().maybeStack(1).asSet()) { + return stack; + } + break; + case 64: + for (final ItemStack stack : + blocks.craftingStorage64k().maybeStack(1).asSet()) { + return stack; + } + break; + } - switch( storage ) - { - case 4: - for( final ItemStack stack : blocks.craftingStorage4k().maybeStack( 1 ).asSet() ) - { - return stack; - } - break; - case 16: - for( final ItemStack stack : blocks.craftingStorage16k().maybeStack( 1 ).asSet() ) - { - return stack; - } - break; - case 64: - for( final ItemStack stack : blocks.craftingStorage64k().maybeStack( 1 ).asSet() ) - { - return stack; - } - break; - } + return super.getItemFromTile(obj); + } - return super.getItemFromTile( obj ); - } + @Override + public boolean isAccelerator() { + return false; + } - @Override - public boolean isAccelerator() - { - return false; - } + @Override + public boolean isStorage() { + return true; + } - @Override - public boolean isStorage() - { - return true; - } + @Override + public int getStorageBytes() { + if (this.worldObj == null || this.notLoaded()) { + return 0; + } - @Override - public int getStorageBytes() - { - if( this.worldObj == null || this.notLoaded() ) - { - return 0; - } - - 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; - } - } + 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; + } + } } diff --git a/src/main/java/appeng/tile/crafting/TileCraftingTile.java b/src/main/java/appeng/tile/crafting/TileCraftingTile.java index 60a6ac58..d5f57d73 100644 --- a/src/main/java/appeng/tile/crafting/TileCraftingTile.java +++ b/src/main/java/appeng/tile/crafting/TileCraftingTile.java @@ -18,6 +18,10 @@ package appeng.tile.crafting; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.LinkedList; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -46,332 +50,291 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedList; +public class TileCraftingTile + extends AENetworkTile implements IAEMultiBlock, IPowerChannelState { + private final CraftingCPUCalculator calc = new CraftingCPUCalculator(this); + private ISimplifiedBundle lightCache; -public class TileCraftingTile extends AENetworkTile implements IAEMultiBlock, IPowerChannelState -{ - private final CraftingCPUCalculator calc = new CraftingCPUCalculator( this ); + private NBTTagCompound previousState = null; + private boolean isCoreBlock = false; + private CraftingCPUCluster cluster; - private ISimplifiedBundle lightCache; + public TileCraftingTile() { + this.getProxy().setFlags(GridFlags.MULTIBLOCK, GridFlags.REQUIRE_CHANNEL); + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } - private NBTTagCompound previousState = null; - private boolean isCoreBlock = false; - private CraftingCPUCluster cluster; + @Override + protected AENetworkProxy createProxy() { + return new AENetworkProxyMultiblock( + this, "proxy", this.getItemFromTile(this), true + ); + } - public TileCraftingTile() - { - this.getProxy().setFlags( GridFlags.MULTIBLOCK, GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } + @Override + protected ItemStack getItemFromTile(final Object obj) { + if (((TileCraftingTile) obj).isAccelerator()) { + for (final ItemStack accelerator : AEApi.instance() + .definitions() + .blocks() + .craftingAccelerator() + .maybeStack(1) + .asSet()) { + return accelerator; + } + } - @Override - protected AENetworkProxy createProxy() - { - return new AENetworkProxyMultiblock( this, "proxy", this.getItemFromTile( this ), true ); - } + return super.getItemFromTile(obj); + } - @Override - protected ItemStack getItemFromTile( final Object obj ) - { - if( ( (TileCraftingTile) obj ).isAccelerator() ) - { - for( final ItemStack accelerator : AEApi.instance().definitions().blocks().craftingAccelerator().maybeStack( 1 ).asSet() ) - { - return accelerator; - } - } + @Override + public boolean canBeRotated() { + return true; // return BlockCraftingUnit.checkType( worldObj.getBlockMetadata( + // xCoord, yCoord, zCoord ), + // BlockCraftingUnit.BASE_MONITOR ); + } - return super.getItemFromTile( obj ); - } + @Override + public void setName(final String name) { + super.setName(name); + if (this.cluster != null) { + this.cluster.updateName(); + } + } - @Override - public boolean canBeRotated() - { - return true;// return BlockCraftingUnit.checkType( worldObj.getBlockMetadata( xCoord, yCoord, zCoord ), - // BlockCraftingUnit.BASE_MONITOR ); - } + public boolean isAccelerator() { + if (this.worldObj == null) { + return false; + } + return (this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) & 3) + == 1; + } - @Override - public void setName( final String name ) - { - super.setName( name ); - if( this.cluster != null ) - { - this.cluster.updateName(); - } - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().setVisualRepresentation(this.getItemFromTile(this)); + this.updateMultiBlock(); + } - public boolean isAccelerator() - { - if( this.worldObj == null ) - { - return false; - } - return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 3 ) == 1; - } + public void updateMultiBlock() { + this.calc.calculateMultiblock(this.worldObj, this.getLocation()); + } - @Override - public void onReady() - { - super.onReady(); - this.getProxy().setVisualRepresentation( this.getItemFromTile( this ) ); - this.updateMultiBlock(); - } + public void updateStatus(final CraftingCPUCluster c) { + if (this.cluster != null && this.cluster != c) { + this.cluster.breakCluster(); + } - public void updateMultiBlock() - { - this.calc.calculateMultiblock( this.worldObj, this.getLocation() ); - } + this.cluster = c; + this.updateMeta(true); + } - public void updateStatus( final CraftingCPUCluster c ) - { - if( this.cluster != null && this.cluster != c ) - { - this.cluster.breakCluster(); - } + public void updateMeta(final boolean updateFormed) { + if (this.worldObj == null || this.notLoaded()) { + return; + } - this.cluster = c; - this.updateMeta( true ); - } + final boolean formed = this.isFormed(); + boolean power = false; - public void updateMeta( final boolean updateFormed ) - { - if( this.worldObj == null || this.notLoaded() ) - { - return; - } + if (this.getProxy().isReady()) { + power = this.getProxy().isActive(); + } - final boolean formed = this.isFormed(); - boolean power = false; + final int current + = this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord); + final int newMeta = (current & 3) | (formed ? 8 : 0) | (power ? 4 : 0); - if( this.getProxy().isReady() ) - { - power = this.getProxy().isActive(); - } + if (current != newMeta) { + this.worldObj.setBlockMetadataWithNotify( + this.xCoord, this.yCoord, this.zCoord, newMeta, 2 + ); + } - final int current = this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ); - final int newMeta = ( current & 3 ) | ( formed ? 8 : 0 ) | ( power ? 4 : 0 ); + if (updateFormed) { + if (formed) { + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); + } else { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + } + } - if( current != newMeta ) - { - this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, newMeta, 2 ); - } + public boolean isFormed() { + if (Platform.isClient()) { + return (this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) + & 8) + == 8; + } + return this.cluster != null; + } - if( updateFormed ) - { - if( formed ) - { - this.getProxy().setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - else - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - } - } + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCraftingTile(final NBTTagCompound data) { + data.setBoolean("core", this.isCoreBlock()); + if (this.isCoreBlock() && this.cluster != null) { + this.cluster.writeToNBT(data); + } + } - public boolean isFormed() - { - if( Platform.isClient() ) - { - return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 8 ) == 8; - } - return this.cluster != null; - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCraftingTile(final NBTTagCompound data) { + this.setCoreBlock(data.getBoolean("core")); + if (this.isCoreBlock()) { + if (this.cluster != null) { + this.cluster.readFromNBT(data); + } else { + this.setPreviousState((NBTTagCompound) data.copy()); + } + } + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCraftingTile( final NBTTagCompound data ) - { - data.setBoolean( "core", this.isCoreBlock() ); - if( this.isCoreBlock() && this.cluster != null ) - { - this.cluster.writeToNBT( data ); - } - } + @Override + public void disconnect(final boolean update) { + if (this.cluster != null) { + this.cluster.destroy(); + if (update) { + this.updateMeta(true); + } + } + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCraftingTile( final NBTTagCompound data ) - { - this.setCoreBlock( data.getBoolean( "core" ) ); - if( this.isCoreBlock() ) - { - if( this.cluster != null ) - { - this.cluster.readFromNBT( data ); - } - else - { - this.setPreviousState( (NBTTagCompound) data.copy() ); - } - } - } + @Override + public IAECluster getCluster() { + return this.cluster; + } - @Override - public void disconnect( final boolean update ) - { - if( this.cluster != null ) - { - this.cluster.destroy(); - if( update ) - { - this.updateMeta( true ); - } - } - } + @Override + public boolean isValid() { + return true; + } - @Override - public IAECluster getCluster() - { - return this.cluster; - } + @MENetworkEventSubscribe + public void onPowerStateChange(final MENetworkChannelsChanged ev) { + this.updateMeta(false); + } - @Override - public boolean isValid() - { - return true; - } + @MENetworkEventSubscribe + public void onPowerStateChange(final MENetworkPowerStatusChange ev) { + this.updateMeta(false); + } - @MENetworkEventSubscribe - public void onPowerStateChange( final MENetworkChannelsChanged ev ) - { - this.updateMeta( false ); - } + public boolean isStatus() { + return false; + } - @MENetworkEventSubscribe - public void onPowerStateChange( final MENetworkPowerStatusChange ev ) - { - this.updateMeta( false ); - } + public boolean isStorage() { + return false; + } - public boolean isStatus() - { - return false; - } + public int getStorageBytes() { + return 0; + } - public boolean isStorage() - { - return false; - } + public void breakCluster() { + if (this.cluster != null) { + this.cluster.cancel(); + final IMEInventory inv = this.cluster.getInventory(); - public int getStorageBytes() - { - return 0; - } + final LinkedList places = new LinkedList(); - public void breakCluster() - { - if( this.cluster != null ) - { - this.cluster.cancel(); - final IMEInventory inv = this.cluster.getInventory(); + final Iterator i = this.cluster.getTiles(); + while (i.hasNext()) { + final IGridHost h = i.next(); + if (h == this) { + places.add(new WorldCoord(this)); + } else { + final TileEntity te = (TileEntity) h; - final LinkedList places = new LinkedList(); + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + final WorldCoord wc = new WorldCoord(te); + wc.add(d, 1); + if (this.worldObj.isAirBlock(wc.x, wc.y, wc.z)) { + places.add(wc); + } + } + } + } - final Iterator i = this.cluster.getTiles(); - while( i.hasNext() ) - { - final IGridHost h = i.next(); - if( h == this ) - { - places.add( new WorldCoord( this ) ); - } - else - { - final TileEntity te = (TileEntity) h; + Collections.shuffle(places); - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - final WorldCoord wc = new WorldCoord( te ); - wc.add( d, 1 ); - if( this.worldObj.isAirBlock( wc.x, wc.y, wc.z ) ) - { - places.add( wc ); - } - } - } - } + if (places.isEmpty()) { + throw new IllegalStateException( + this.cluster + + " does not contain any kind of blocks, which were destroyed." + ); + } - Collections.shuffle( places ); + for (IAEItemStack ais : + inv.getAvailableItems(AEApi.instance().storage().createItemList())) { + ais = ais.copy(); + ais.setStackSize(ais.getItemStack().getMaxStackSize()); + while (true) { + final IAEItemStack g = inv.extractItems( + ais.copy(), Actionable.MODULATE, this.cluster.getActionSource() + ); + if (g == null) { + break; + } - if( places.isEmpty() ) - { - throw new IllegalStateException( this.cluster + " does not contain any kind of blocks, which were destroyed." ); - } + final WorldCoord wc = places.poll(); + places.add(wc); - for( IAEItemStack ais : inv.getAvailableItems( AEApi.instance().storage().createItemList() ) ) - { - ais = ais.copy(); - ais.setStackSize( ais.getItemStack().getMaxStackSize() ); - while( true ) - { - final IAEItemStack g = inv.extractItems( ais.copy(), Actionable.MODULATE, this.cluster.getActionSource() ); - if( g == null ) - { - break; - } + Platform.spawnDrops( + this.worldObj, + wc.x, + wc.y, + wc.z, + Collections.singletonList(g.getItemStack()) + ); + } + } - final WorldCoord wc = places.poll(); - places.add( wc ); + this.cluster.destroy(); + } + } - Platform.spawnDrops( this.worldObj, wc.x, wc.y, wc.z, Collections.singletonList( g.getItemStack() ) ); - } - } + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return (this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) + & 4) + == 4; + } + return this.getProxy().isActive(); + } - this.cluster.destroy(); - } - } + @Override + public boolean isActive() { + if (Platform.isServer()) { + return this.getProxy().isActive(); + } + return this.isPowered() && this.isFormed(); + } - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) & 4 ) == 4; - } - return this.getProxy().isActive(); - } + public boolean isCoreBlock() { + return this.isCoreBlock; + } - @Override - public boolean isActive() - { - if( Platform.isServer() ) - { - return this.getProxy().isActive(); - } - return this.isPowered() && this.isFormed(); - } + public void setCoreBlock(final boolean isCoreBlock) { + this.isCoreBlock = isCoreBlock; + } - public boolean isCoreBlock() - { - return this.isCoreBlock; - } + public ISimplifiedBundle getLightCache() { + return this.lightCache; + } - public void setCoreBlock( final boolean isCoreBlock ) - { - this.isCoreBlock = isCoreBlock; - } + public void setLightCache(final ISimplifiedBundle lightCache) { + this.lightCache = lightCache; + } - public ISimplifiedBundle getLightCache() - { - return this.lightCache; - } + public NBTTagCompound getPreviousState() { + return this.previousState; + } - public void setLightCache( final ISimplifiedBundle lightCache ) - { - this.lightCache = lightCache; - } - - public NBTTagCompound getPreviousState() - { - return this.previousState; - } - - public void setPreviousState( final NBTTagCompound previousState ) - { - this.previousState = previousState; - } + public void setPreviousState(final NBTTagCompound previousState) { + this.previousState = previousState; + } } diff --git a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java index 48e93e5f..61761c63 100644 --- a/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java +++ b/src/main/java/appeng/tile/crafting/TileMolecularAssembler.java @@ -18,6 +18,8 @@ package appeng.tile.crafting; +import java.io.IOException; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.*; @@ -66,596 +68,535 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; - - public class TileMolecularAssembler extends AENetworkInvTile - implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, IPowerChannelState -{ - private static final int[] SIDES = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - - private final InventoryCrafting craftingInv; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 9 + 2 ); - private final IConfigManager settings; - private final UpgradeInventory upgrades; - private ISimplifiedBundle lightCache; - private boolean isPowered = false; - private ForgeDirection pushDirection = ForgeDirection.UNKNOWN; - private ItemStack myPattern = null; - private ICraftingPatternDetails myPlan = null; - private double progress = 0; - private boolean isAwake = false; - private boolean forcePlan = false; - private boolean reboot = true; - - public TileMolecularAssembler() - { - final ITileDefinition assembler = AEApi.instance().definitions().blocks().molecularAssembler(); - - this.settings = new ConfigManager( this ); - this.settings.registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.inv.setMaxStackSize( 1 ); - this.getProxy().setIdlePowerUsage( 0.0 ); - this.upgrades = new DefinitionUpgradeInventory( assembler, this, this.getUpgradeSlots() ); - this.craftingInv = new InventoryCrafting( new ContainerNull(), 3, 3 ); - } - - private int getUpgradeSlots() - { - return 5; - } - - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table, final ForgeDirection where ) - { - if( this.myPattern == null ) - { - boolean isEmpty = true; - for( int x = 0; x < this.inv.getSizeInventory(); x++ ) - { - isEmpty = this.inv.getStackInSlot( x ) == null && isEmpty; - } - - if( isEmpty && patternDetails.isCraftable() ) - { - this.forcePlan = true; - this.myPlan = patternDetails; - this.pushDirection = where; - - for( int x = 0; x < table.getSizeInventory(); x++ ) - { - this.inv.setInventorySlotContents( x, table.getStackInSlot( x ) ); - } - - this.updateSleepiness(); - this.markDirty(); - return true; - } - } - return false; - } - - private void updateSleepiness() - { - final boolean wasEnabled = this.isAwake; - this.isAwake = this.myPlan != null && this.hasMats() || this.canPush(); - if( wasEnabled != this.isAwake ) - { - try - { - if( this.isAwake ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - } - - private boolean canPush() - { - return this.inv.getStackInSlot( 9 ) != null; - } - - private boolean hasMats() - { - if( this.myPlan == null ) - { - return false; - } - - 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; - } - - @Override - public boolean acceptsPlans() - { - return this.inv.getStackInSlot( 10 ) == null; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileMolecularAssembler( final ByteBuf data ) - { - final boolean oldPower = this.isPowered; - this.isPowered = data.readBoolean(); - return this.isPowered != oldPower; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileMolecularAssembler( final ByteBuf data ) - { - data.writeBoolean( this.isPowered ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileMolecularAssembler( final NBTTagCompound data ) - { - if( this.forcePlan && this.myPlan != null ) - { - final ItemStack pattern = this.myPlan.getPattern(); - if( pattern != null ) - { - final NBTTagCompound compound = new NBTTagCompound(); - pattern.writeToNBT( compound ); - data.setTag( "myPlan", compound ); - data.setInteger( "pushDirection", this.pushDirection.ordinal() ); - } - } - - this.upgrades.writeToNBT( data, "upgrades" ); - this.inv.writeToNBT( data, "inv" ); - this.settings.writeToNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileMolecularAssembler( final NBTTagCompound data ) - { - if( data.hasKey( "myPlan" ) ) - { - final ItemStack myPat = ItemStack.loadItemStackFromNBT( data.getCompoundTag( "myPlan" ) ); - - if( myPat != null && myPat.getItem() instanceof ItemEncodedPattern ) - { - final World w = this.getWorldObj(); - final ItemEncodedPattern iep = (ItemEncodedPattern) myPat.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( myPat, w ); - if( ph != null && ph.isCraftable() ) - { - this.forcePlan = true; - this.myPlan = ph; - this.pushDirection = ForgeDirection.getOrientation( data.getInteger( "pushDirection" ) ); - } - } - } - - this.upgrades.readFromNBT( data, "upgrades" ); - this.inv.readFromNBT( data, "inv" ); - this.settings.readFromNBT( data ); - this.recalculatePlan(); - } - - private void recalculatePlan() - { - this.reboot = true; - - if( this.forcePlan ) - { - return; - } - - final ItemStack is = this.inv.getStackInSlot( 10 ); - - if( is != null && is.getItem() instanceof ItemEncodedPattern ) - { - if( !Platform.isSameItem( is, this.myPattern ) ) - { - final World w = this.getWorldObj(); - final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); - final ICraftingPatternDetails ph = iep.getPatternForItem( is, w ); - - if( ph != null && ph.isCraftable() ) - { - this.progress = 0; - this.myPattern = is; - this.myPlan = ph; - } - } - } - else - { - this.progress = 0; - this.forcePlan = false; - this.myPlan = null; - this.myPattern = null; - this.pushDirection = ForgeDirection.UNKNOWN; - } - - this.updateSleepiness(); - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - if( name.equals( "mac" ) ) - { - return this.inv; - } - - return null; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( i >= 9 ) - { - return false; - } - - if( this.hasPattern() ) - { - return this.myPlan.isValidItemForSlot( i, itemstack, this.getWorldObj() ); - } - - return false; - } - - private boolean hasPattern() - { - return this.myPlan != null && this.inv.getStackInSlot( 10 ) != null; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( inv == this.inv ) - { - this.recalculatePlan(); - } - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex == 9; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection whichSide ) - { - return SIDES; - } - - public int getCraftingProgress() - { - return (int) this.progress; - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - for( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) - { - final ItemStack is = this.upgrades.getStackInSlot( h ); - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - this.recalculatePlan(); - this.updateSleepiness(); - return new TickingRequest( 1, 1, !this.isAwake, false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, int ticksSinceLastCall ) - { - if( this.inv.getStackInSlot( 9 ) != null ) - { - this.pushOut( this.inv.getStackInSlot( 9 ) ); - - // did it eject? - if( this.inv.getStackInSlot( 9 ) == null ) - { - this.markDirty(); - } - - this.ejectHeldItems(); - this.updateSleepiness(); - this.progress = 0; - return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; - } - - if( this.myPlan == null ) - { - this.updateSleepiness(); - return TickRateModulation.SLEEP; - } - - if( this.reboot ) - { - ticksSinceLastCall = 1; - } - - if( !this.isAwake ) - { - return TickRateModulation.SLEEP; - } - - this.reboot = false; - int speed = 10; - switch( this.upgrades.getInstalledUpgrades( Upgrades.SPEED ) ) - { - case 0: - this.progress += this.userPower( ticksSinceLastCall, speed = 10, 1.0 ); - break; - case 1: - this.progress += this.userPower( ticksSinceLastCall, speed = 13, 1.3 ); - break; - case 2: - this.progress += this.userPower( ticksSinceLastCall, speed = 17, 1.7 ); - break; - case 3: - this.progress += this.userPower( ticksSinceLastCall, speed = 20, 2.0 ); - break; - case 4: - this.progress += this.userPower( ticksSinceLastCall, speed = 25, 2.5 ); - break; - case 5: - this.progress += this.userPower( ticksSinceLastCall, speed = 50, 5.0 ); - break; - } - - if( this.progress >= 100 ) - { - for( int x = 0; x < this.craftingInv.getSizeInventory(); x++ ) - { - this.craftingInv.setInventorySlotContents( x, this.inv.getStackInSlot( x ) ); - } - - this.progress = 0; - final ItemStack output = this.myPlan.getOutput( this.craftingInv, this.getWorldObj() ); - 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++ ) - { - this.inv.setInventorySlotContents( x, Platform.getContainerItem( this.craftingInv.getStackInSlot( x ) ) ); - } - - if( this.inv.getStackInSlot( 10 ) == null ) - { - this.forcePlan = false; - this.myPlan = null; - this.pushDirection = ForgeDirection.UNKNOWN; - } - - this.ejectHeldItems(); - - try - { - final TargetPoint where = new TargetPoint( this.worldObj.provider.dimensionId, this.xCoord, this.yCoord, this.zCoord, 32 ); - final IAEItemStack item = AEItemStack.create( output ); - NetworkHandler.instance.sendToAllAround( new PacketAssemblerAnimation( this.xCoord, this.yCoord, this.zCoord, (byte) speed, item ), where ); - } - catch( final IOException e ) - { - // ;P - } - - this.markDirty(); - this.updateSleepiness(); - return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; - } - } - - return TickRateModulation.FASTER; - } - - private void ejectHeldItems() - { - if( this.inv.getStackInSlot( 9 ) == null ) - { - for( int x = 0; x < 9; x++ ) - { - final ItemStack is = this.inv.getStackInSlot( x ); - if( is != null ) - { - if( this.myPlan == null || !this.myPlan.isValidItemForSlot( x, is, this.worldObj ) ) - { - this.inv.setInventorySlotContents( 9, is ); - this.inv.setInventorySlotContents( x, null ); - this.markDirty(); - return; - } - } - } - } - } - - private int userPower( final int ticksPassed, final int bonusValue, final double acceleratorTax ) - { - try - { - return (int) ( this.getProxy().getEnergy().extractAEPower( ticksPassed * bonusValue * acceleratorTax, Actionable.MODULATE, PowerMultiplier.CONFIG ) / acceleratorTax ); - } - catch( final GridAccessException e ) - { - return 0; - } - } - - private void pushOut( ItemStack output ) - { - if( this.pushDirection == ForgeDirection.UNKNOWN ) - { - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - output = this.pushTo( output, d ); - } - } - else - { - output = this.pushTo( output, this.pushDirection ); - } - - if( output == null && this.forcePlan ) - { - this.forcePlan = false; - this.recalculatePlan(); - } - - this.inv.setInventorySlotContents( 9, output ); - } - - private ItemStack pushTo( ItemStack output, final ForgeDirection d ) - { - if( output == null ) - { - return output; - } - - final TileEntity te = this.getWorldObj().getTileEntity( this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ ); - - if( te == null ) - { - return output; - } - - final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor( te, d.getOpposite() ); - - if( adaptor == null ) - { - return output; - } - - final int size = output.stackSize; - output = adaptor.addItems( output ); - final int newSize = output == null ? 0 : output.stackSize; - - if( size != newSize ) - { - this.markDirty(); - } - - return output; - } - - @MENetworkEventSubscribe - public void onPowerEvent( final MENetworkPowerStatusChange p ) - { - this.updatePowerState(); - } - - private void updatePowerState() - { - boolean newState = false; - - try - { - newState = this.getProxy().isActive() && this.getProxy().getEnergy().extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.0001; - } - catch( final GridAccessException ignored ) - { - - } - - if( newState != this.isPowered ) - { - this.isPowered = newState; - this.markForUpdate(); - } - } - - @Override - public boolean isPowered() - { - return this.isPowered; - } - - @Override - public boolean isActive() - { - return this.isPowered; - } - - public ISimplifiedBundle getLightCache() - { - return this.lightCache; - } - - public void setLightCache( final ISimplifiedBundle lightCache ) - { - this.lightCache = lightCache; - } + implements IUpgradeableHost, IConfigManagerHost, IGridTickable, ICraftingMachine, + IPowerChannelState { + private static final int[] SIDES = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + + private final InventoryCrafting craftingInv; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 9 + 2); + private final IConfigManager settings; + private final UpgradeInventory upgrades; + private ISimplifiedBundle lightCache; + private boolean isPowered = false; + private ForgeDirection pushDirection = ForgeDirection.UNKNOWN; + private ItemStack myPattern = null; + private ICraftingPatternDetails myPlan = null; + private double progress = 0; + private boolean isAwake = false; + private boolean forcePlan = false; + private boolean reboot = true; + + public TileMolecularAssembler() { + final ITileDefinition assembler + = AEApi.instance().definitions().blocks().molecularAssembler(); + + this.settings = new ConfigManager(this); + this.settings.registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.inv.setMaxStackSize(1); + this.getProxy().setIdlePowerUsage(0.0); + this.upgrades + = new DefinitionUpgradeInventory(assembler, this, this.getUpgradeSlots()); + this.craftingInv = new InventoryCrafting(new ContainerNull(), 3, 3); + } + + private int getUpgradeSlots() { + return 5; + } + + @Override + public boolean pushPattern( + final ICraftingPatternDetails patternDetails, + final InventoryCrafting table, + final ForgeDirection where + ) { + if (this.myPattern == null) { + boolean isEmpty = true; + for (int x = 0; x < this.inv.getSizeInventory(); x++) { + isEmpty = this.inv.getStackInSlot(x) == null && isEmpty; + } + + if (isEmpty && patternDetails.isCraftable()) { + this.forcePlan = true; + this.myPlan = patternDetails; + this.pushDirection = where; + + for (int x = 0; x < table.getSizeInventory(); x++) { + this.inv.setInventorySlotContents(x, table.getStackInSlot(x)); + } + + this.updateSleepiness(); + this.markDirty(); + return true; + } + } + return false; + } + + private void updateSleepiness() { + final boolean wasEnabled = this.isAwake; + this.isAwake = this.myPlan != null && this.hasMats() || this.canPush(); + if (wasEnabled != this.isAwake) { + try { + if (this.isAwake) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + } + + private boolean canPush() { + return this.inv.getStackInSlot(9) != null; + } + + private boolean hasMats() { + if (this.myPlan == null) { + return false; + } + + 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; + } + + @Override + public boolean acceptsPlans() { + return this.inv.getStackInSlot(10) == null; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileMolecularAssembler(final ByteBuf data) { + final boolean oldPower = this.isPowered; + this.isPowered = data.readBoolean(); + return this.isPowered != oldPower; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileMolecularAssembler(final ByteBuf data) { + data.writeBoolean(this.isPowered); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileMolecularAssembler(final NBTTagCompound data) { + if (this.forcePlan && this.myPlan != null) { + final ItemStack pattern = this.myPlan.getPattern(); + if (pattern != null) { + final NBTTagCompound compound = new NBTTagCompound(); + pattern.writeToNBT(compound); + data.setTag("myPlan", compound); + data.setInteger("pushDirection", this.pushDirection.ordinal()); + } + } + + this.upgrades.writeToNBT(data, "upgrades"); + this.inv.writeToNBT(data, "inv"); + this.settings.writeToNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileMolecularAssembler(final NBTTagCompound data) { + if (data.hasKey("myPlan")) { + final ItemStack myPat + = ItemStack.loadItemStackFromNBT(data.getCompoundTag("myPlan")); + + if (myPat != null && myPat.getItem() instanceof ItemEncodedPattern) { + final World w = this.getWorldObj(); + final ItemEncodedPattern iep = (ItemEncodedPattern) myPat.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(myPat, w); + if (ph != null && ph.isCraftable()) { + this.forcePlan = true; + this.myPlan = ph; + this.pushDirection + = ForgeDirection.getOrientation(data.getInteger("pushDirection")); + } + } + } + + this.upgrades.readFromNBT(data, "upgrades"); + this.inv.readFromNBT(data, "inv"); + this.settings.readFromNBT(data); + this.recalculatePlan(); + } + + private void recalculatePlan() { + this.reboot = true; + + if (this.forcePlan) { + return; + } + + final ItemStack is = this.inv.getStackInSlot(10); + + if (is != null && is.getItem() instanceof ItemEncodedPattern) { + if (!Platform.isSameItem(is, this.myPattern)) { + final World w = this.getWorldObj(); + final ItemEncodedPattern iep = (ItemEncodedPattern) is.getItem(); + final ICraftingPatternDetails ph = iep.getPatternForItem(is, w); + + if (ph != null && ph.isCraftable()) { + this.progress = 0; + this.myPattern = is; + this.myPlan = ph; + } + } + } else { + this.progress = 0; + this.forcePlan = false; + this.myPlan = null; + this.myPattern = null; + this.pushDirection = ForgeDirection.UNKNOWN; + } + + this.updateSleepiness(); + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } + + if (name.equals("mac")) { + return this.inv; + } + + return null; + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) {} + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (i >= 9) { + return false; + } + + if (this.hasPattern()) { + return this.myPlan.isValidItemForSlot(i, itemstack, this.getWorldObj()); + } + + return false; + } + + private boolean hasPattern() { + return this.myPlan != null && this.inv.getStackInSlot(10) != null; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + if (inv == this.inv) { + this.recalculatePlan(); + } + } + + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex == 9; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection whichSide) { + return SIDES; + } + + public int getCraftingProgress() { + return (int) this.progress; + } + + @Override + public void getDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + super.getDrops(w, x, y, z, drops); + + for (int h = 0; h < this.upgrades.getSizeInventory(); h++) { + final ItemStack is = this.upgrades.getStackInSlot(h); + if (is != null) { + drops.add(is); + } + } + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + this.recalculatePlan(); + this.updateSleepiness(); + return new TickingRequest(1, 1, !this.isAwake, false); + } + + @Override + public TickRateModulation + tickingRequest(final IGridNode node, int ticksSinceLastCall) { + if (this.inv.getStackInSlot(9) != null) { + this.pushOut(this.inv.getStackInSlot(9)); + + // did it eject? + if (this.inv.getStackInSlot(9) == null) { + this.markDirty(); + } + + this.ejectHeldItems(); + this.updateSleepiness(); + this.progress = 0; + return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; + } + + if (this.myPlan == null) { + this.updateSleepiness(); + return TickRateModulation.SLEEP; + } + + if (this.reboot) { + ticksSinceLastCall = 1; + } + + if (!this.isAwake) { + return TickRateModulation.SLEEP; + } + + this.reboot = false; + int speed = 10; + switch (this.upgrades.getInstalledUpgrades(Upgrades.SPEED)) { + case 0: + this.progress += this.userPower(ticksSinceLastCall, speed = 10, 1.0); + break; + case 1: + this.progress += this.userPower(ticksSinceLastCall, speed = 13, 1.3); + break; + case 2: + this.progress += this.userPower(ticksSinceLastCall, speed = 17, 1.7); + break; + case 3: + this.progress += this.userPower(ticksSinceLastCall, speed = 20, 2.0); + break; + case 4: + this.progress += this.userPower(ticksSinceLastCall, speed = 25, 2.5); + break; + case 5: + this.progress += this.userPower(ticksSinceLastCall, speed = 50, 5.0); + break; + } + + if (this.progress >= 100) { + for (int x = 0; x < this.craftingInv.getSizeInventory(); x++) { + this.craftingInv.setInventorySlotContents(x, this.inv.getStackInSlot(x)); + } + + this.progress = 0; + final ItemStack output + = this.myPlan.getOutput(this.craftingInv, this.getWorldObj()); + 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++) { + this.inv.setInventorySlotContents( + x, Platform.getContainerItem(this.craftingInv.getStackInSlot(x)) + ); + } + + if (this.inv.getStackInSlot(10) == null) { + this.forcePlan = false; + this.myPlan = null; + this.pushDirection = ForgeDirection.UNKNOWN; + } + + this.ejectHeldItems(); + + try { + final TargetPoint where = new TargetPoint( + this.worldObj.provider.dimensionId, + this.xCoord, + this.yCoord, + this.zCoord, + 32 + ); + final IAEItemStack item = AEItemStack.create(output); + NetworkHandler.instance.sendToAllAround( + new PacketAssemblerAnimation( + this.xCoord, this.yCoord, this.zCoord, (byte) speed, item + ), + where + ); + } catch (final IOException e) { + // ;P + } + + this.markDirty(); + this.updateSleepiness(); + return this.isAwake ? TickRateModulation.IDLE : TickRateModulation.SLEEP; + } + } + + return TickRateModulation.FASTER; + } + + private void ejectHeldItems() { + if (this.inv.getStackInSlot(9) == null) { + for (int x = 0; x < 9; x++) { + final ItemStack is = this.inv.getStackInSlot(x); + if (is != null) { + if (this.myPlan == null + || !this.myPlan.isValidItemForSlot(x, is, this.worldObj)) { + this.inv.setInventorySlotContents(9, is); + this.inv.setInventorySlotContents(x, null); + this.markDirty(); + return; + } + } + } + } + } + + private int + userPower(final int ticksPassed, final int bonusValue, final double acceleratorTax) { + try { + return (int + ) (this.getProxy().getEnergy().extractAEPower( + ticksPassed * bonusValue * acceleratorTax, + Actionable.MODULATE, + PowerMultiplier.CONFIG + ) + / acceleratorTax); + } catch (final GridAccessException e) { + return 0; + } + } + + private void pushOut(ItemStack output) { + if (this.pushDirection == ForgeDirection.UNKNOWN) { + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + output = this.pushTo(output, d); + } + } else { + output = this.pushTo(output, this.pushDirection); + } + + if (output == null && this.forcePlan) { + this.forcePlan = false; + this.recalculatePlan(); + } + + this.inv.setInventorySlotContents(9, output); + } + + private ItemStack pushTo(ItemStack output, final ForgeDirection d) { + if (output == null) { + return output; + } + + final TileEntity te = this.getWorldObj().getTileEntity( + this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ + ); + + if (te == null) { + return output; + } + + final InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(te, d.getOpposite()); + + if (adaptor == null) { + return output; + } + + final int size = output.stackSize; + output = adaptor.addItems(output); + final int newSize = output == null ? 0 : output.stackSize; + + if (size != newSize) { + this.markDirty(); + } + + return output; + } + + @MENetworkEventSubscribe + public void onPowerEvent(final MENetworkPowerStatusChange p) { + this.updatePowerState(); + } + + private void updatePowerState() { + boolean newState = false; + + try { + newState = this.getProxy().isActive() + && this.getProxy().getEnergy().extractAEPower( + 1, Actionable.SIMULATE, PowerMultiplier.CONFIG + ) > 0.0001; + } catch (final GridAccessException ignored) {} + + if (newState != this.isPowered) { + this.isPowered = newState; + this.markForUpdate(); + } + } + + @Override + public boolean isPowered() { + return this.isPowered; + } + + @Override + public boolean isActive() { + return this.isPowered; + } + + public ISimplifiedBundle getLightCache() { + return this.lightCache; + } + + public void setLightCache(final ISimplifiedBundle lightCache) { + this.lightCache = lightCache; + } } diff --git a/src/main/java/appeng/tile/events/AETileEventHandler.java b/src/main/java/appeng/tile/events/AETileEventHandler.java index f4dccab1..35dba032 100644 --- a/src/main/java/appeng/tile/events/AETileEventHandler.java +++ b/src/main/java/appeng/tile/events/AETileEventHandler.java @@ -18,6 +18,8 @@ package appeng.tile.events; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import appeng.tile.AEBaseTile; import cpw.mods.fml.relauncher.Side; @@ -25,130 +27,83 @@ import cpw.mods.fml.relauncher.SideOnly; import io.netty.buffer.ByteBuf; import net.minecraft.nbt.NBTTagCompound; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; +public final class AETileEventHandler { + private final Method method; + public AETileEventHandler(final Method method) { + this.method = method; + } -public final class AETileEventHandler -{ + // TICK + public void tick(final AEBaseTile tile) { + try { + this.method.invoke(tile); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - private final Method method; + // WORLD_NBT + public void writeToNBT(final AEBaseTile tile, final NBTTagCompound data) { + try { + this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - public AETileEventHandler( final Method method ) - { - this.method = method; - } + // WORLD NBT + public void readFromNBT(final AEBaseTile tile, final NBTTagCompound data) { + try { + this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - // TICK - public void tick( final AEBaseTile tile ) - { - try - { - this.method.invoke( tile ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + // NETWORK + public void writeToStream(final AEBaseTile tile, final ByteBuf data) { + try { + this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } - // WORLD_NBT - public void writeToNBT( final AEBaseTile tile, final NBTTagCompound data ) - { - try - { - this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + // NETWORK - // WORLD NBT - public void readFromNBT( final AEBaseTile tile, final NBTTagCompound data ) - { - try - { - this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } - - // NETWORK - public void writeToStream( final AEBaseTile tile, final ByteBuf data ) - { - try - { - this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( 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 ) - public boolean readFromStream( final AEBaseTile tile, final ByteBuf data ) - { - try - { - return (Boolean) this.method.invoke( tile, data ); - } - catch( final IllegalAccessException e ) - { - throw new IllegalStateException( e ); - } - catch( final IllegalArgumentException e ) - { - throw new IllegalStateException( e ); - } - catch( final InvocationTargetException e ) - { - throw new IllegalStateException( e ); - } - } + /** + * 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) + public boolean readFromStream(final AEBaseTile tile, final ByteBuf data) { + try { + return (Boolean) this.method.invoke(tile, data); + } catch (final IllegalAccessException e) { + throw new IllegalStateException(e); + } catch (final IllegalArgumentException e) { + throw new IllegalStateException(e); + } catch (final InvocationTargetException e) { + throw new IllegalStateException(e); + } + } } diff --git a/src/main/java/appeng/tile/events/TileEventType.java b/src/main/java/appeng/tile/events/TileEventType.java index 26cadd3d..a7ee4b8f 100644 --- a/src/main/java/appeng/tile/events/TileEventType.java +++ b/src/main/java/appeng/tile/events/TileEventType.java @@ -18,17 +18,16 @@ package appeng.tile.events; +public enum TileEventType { + TICK, -public enum TileEventType -{ - TICK, + WORLD_NBT_READ, + WORLD_NBT_WRITE, - WORLD_NBT_READ, WORLD_NBT_WRITE, + /** + * Methods annotated with this need to return a boolean + */ + NETWORK_READ, - /** - * Methods annotated with this need to return a boolean - */ - NETWORK_READ, - - NETWORK_WRITE + NETWORK_WRITE } diff --git a/src/main/java/appeng/tile/grid/AENetworkInvTile.java b/src/main/java/appeng/tile/grid/AENetworkInvTile.java index c24ffaa9..d5d98fc4 100644 --- a/src/main/java/appeng/tile/grid/AENetworkInvTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkInvTile.java @@ -18,7 +18,6 @@ package appeng.tile.grid; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.me.helpers.AENetworkProxy; @@ -29,74 +28,60 @@ import appeng.tile.events.TileEventType; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +public abstract class AENetworkInvTile + extends AEBaseInvTile implements IActionHost, IGridProxyable { + private final AENetworkProxy gridProxy + = new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); -public abstract class AENetworkInvTile extends AEBaseInvTile implements IActionHost, IGridProxyable -{ + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().readFromNBT(data); + } - private final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().writeToNBT(data); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().readFromNBT( data ); - } + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().writeToNBT( data ); - } + @Override + public void gridChanged() {} - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getProxy().getNode(); + } - @Override - public void gridChanged() - { + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getProxy().getNode(); - } + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } - - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } - - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } - - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } - - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java index f042362f..102a3b66 100644 --- a/src/main/java/appeng/tile/grid/AENetworkPowerTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkPowerTile.java @@ -18,7 +18,6 @@ package appeng.tile.grid; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.api.util.AECableType; @@ -31,86 +30,70 @@ import appeng.tile.powersink.AEBasePoweredTile; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +public abstract class AENetworkPowerTile + extends AEBasePoweredTile implements IActionHost, IGridProxyable { + private final AENetworkProxy gridProxy + = new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); -public abstract class AENetworkPowerTile extends AEBasePoweredTile implements IActionHost, IGridProxyable -{ + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().readFromNBT(data); + } - private final AENetworkProxy gridProxy = new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().writeToNBT(data); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().readFromNBT( data ); - } + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().writeToNBT( data ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } + @Override + public void gridChanged() {} - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getProxy().getNode(); + } - @Override - public void gridChanged() - { + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } - } + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getProxy().getNode(); - } + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } - - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } - - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } - - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } - - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grid/AENetworkTile.java b/src/main/java/appeng/tile/grid/AENetworkTile.java index 3f574300..fd234d3d 100644 --- a/src/main/java/appeng/tile/grid/AENetworkTile.java +++ b/src/main/java/appeng/tile/grid/AENetworkTile.java @@ -18,7 +18,6 @@ package appeng.tile.grid; - import appeng.api.networking.IGridNode; import appeng.api.networking.security.IActionHost; import appeng.api.util.AECableType; @@ -31,90 +30,72 @@ import appeng.tile.events.TileEventType; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxyable { + private final AENetworkProxy gridProxy = this.createProxy(); -public class AENetworkTile extends AEBaseTile implements IActionHost, IGridProxyable -{ + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().readFromNBT(data); + } - private final AENetworkProxy gridProxy = this.createProxy(); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AENetwork(final NBTTagCompound data) { + this.getProxy().writeToNBT(data); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().readFromNBT( data ); - } + protected AENetworkProxy createProxy() { + return new AENetworkProxy(this, "proxy", this.getItemFromTile(this), true); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - this.getProxy().writeToNBT( data ); - } + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getProxy().getNode(); + } - protected AENetworkProxy createProxy() - { - return new AENetworkProxy( this, "proxy", this.getItemFromTile( this ), true ); - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getProxy().getNode(); - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getProxy().onChunkUnload(); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } + @Override + public void onReady() { + super.onReady(); + this.getProxy().onReady(); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getProxy().onChunkUnload(); - } + @Override + public void invalidate() { + super.invalidate(); + this.getProxy().invalidate(); + } - @Override - public void onReady() - { - super.onReady(); - this.getProxy().onReady(); - } + @Override + public void validate() { + super.validate(); + this.getProxy().validate(); + } - @Override - public void invalidate() - { - super.invalidate(); - this.getProxy().invalidate(); - } + @Override + public AENetworkProxy getProxy() { + return this.gridProxy; + } - @Override - public void validate() - { - super.validate(); - this.getProxy().validate(); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public AENetworkProxy getProxy() - { - return this.gridProxy; - } + @Override + public void gridChanged() {} - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - @Override - public void gridChanged() - { - - } - - @Override - public IGridNode getActionableNode() - { - return this.getProxy().getNode(); - } + @Override + public IGridNode getActionableNode() { + return this.getProxy().getNode(); + } } diff --git a/src/main/java/appeng/tile/grindstone/TileCrank.java b/src/main/java/appeng/tile/grindstone/TileCrank.java index ab5bb22e..c3c7af9d 100644 --- a/src/main/java/appeng/tile/grindstone/TileCrank.java +++ b/src/main/java/appeng/tile/grindstone/TileCrank.java @@ -18,6 +18,8 @@ package appeng.tile.grindstone; +import java.util.Collections; +import java.util.List; import appeng.api.implementations.tiles.ICrankable; import appeng.helpers.ICustomCollision; @@ -32,148 +34,153 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Collections; -import java.util.List; +public class TileCrank extends AEBaseTile implements ICustomCollision { + private final int ticksPerRotation = 18; + // sided values.. + private float visibleRotation = 0; + private int charge = 0; -public class TileCrank extends AEBaseTile implements ICustomCollision -{ + private int hits = 0; + private int rotation = 0; - private final int ticksPerRotation = 18; + @TileEvent(TileEventType.TICK) + public void Tick_TileCrank() { + if (this.rotation > 0) { + this.setVisibleRotation( + this.getVisibleRotation() - 360 / (this.ticksPerRotation) + ); + this.charge++; + if (this.charge >= this.ticksPerRotation) { + this.charge -= this.ticksPerRotation; + final ICrankable g = this.getGrinder(); + if (g != null) { + g.applyTurn(); + } + } - // sided values.. - private float visibleRotation = 0; - private int charge = 0; + this.rotation--; + } + } - private int hits = 0; - private int rotation = 0; + private ICrankable getGrinder() { + if (Platform.isClient()) { + return null; + } - @TileEvent( TileEventType.TICK ) - public void Tick_TileCrank() - { - if( this.rotation > 0 ) - { - this.setVisibleRotation( this.getVisibleRotation() - 360 / ( this.ticksPerRotation ) ); - this.charge++; - if( this.charge >= this.ticksPerRotation ) - { - this.charge -= this.ticksPerRotation; - final ICrankable g = this.getGrinder(); - if( g != null ) - { - g.applyTurn(); - } - } + final ForgeDirection grinder = this.getUp().getOpposite(); + final 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; + } - this.rotation--; - } - } + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCrank(final ByteBuf data) { + this.rotation = data.readInt(); + return false; + } - private ICrankable getGrinder() - { - if( Platform.isClient() ) - { - return null; - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCrank(final ByteBuf data) { + data.writeInt(this.rotation); + } - final ForgeDirection grinder = this.getUp().getOpposite(); - final 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(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getBlockType().onNeighborBlockChange( + this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK + ); + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCrank( final ByteBuf data ) - { - this.rotation = data.readInt(); - return false; - } + @Override + public boolean requiresTESR() { + return true; + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCrank( final ByteBuf data ) - { - data.writeInt( this.rotation ); - } + /** + * return true if this should count towards stats. + */ + public boolean power() { + if (Platform.isClient()) { + return false; + } - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getBlockType().onNeighborBlockChange( this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK ); - } + if (this.rotation < 3) { + final ICrankable g = this.getGrinder(); + if (g != null) { + if (g.canTurn()) { + this.hits = 0; + this.rotation += this.ticksPerRotation; + this.markForUpdate(); + return true; + } else { + this.hits++; + if (this.hits > 10) { + this.worldObj.func_147480_a( + this.xCoord, this.yCoord, this.zCoord, false + ); + // worldObj.destroyBlock( xCoord, yCoord, zCoord, false ); + } + } + } + } - @Override - public boolean requiresTESR() - { - return true; - } + return false; + } - /** - * return true if this should count towards stats. - */ - public boolean power() - { - if( Platform.isClient() ) - { - return false; - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean isVisual + ) { + final double xOff = -0.15 * this.getUp().offsetX; + final double yOff = -0.15 * this.getUp().offsetY; + final double zOff = -0.15 * this.getUp().offsetZ; + return Collections.singletonList(AxisAlignedBB.getBoundingBox( + xOff + 0.15, yOff + 0.15, zOff + 0.15, xOff + 0.85, yOff + 0.85, zOff + 0.85 + )); + } - if( this.rotation < 3 ) - { - final ICrankable g = this.getGrinder(); - if( g != null ) - { - if( g.canTurn() ) - { - this.hits = 0; - this.rotation += this.ticksPerRotation; - this.markForUpdate(); - return true; - } - else - { - this.hits++; - if( this.hits > 10 ) - { - this.worldObj.func_147480_a( this.xCoord, this.yCoord, this.zCoord, false ); - // worldObj.destroyBlock( xCoord, yCoord, zCoord, false ); - } - } - } - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + final double xOff = -0.15 * this.getUp().offsetX; + final double yOff = -0.15 * this.getUp().offsetY; + final double zOff = -0.15 * this.getUp().offsetZ; + out.add(AxisAlignedBB.getBoundingBox( + xOff + 0.15, + yOff + 0.15, + zOff + 0.15, // ahh + xOff + 0.85, + yOff + 0.85, + zOff + 0.85 + )); + } - return false; - } + public float getVisibleRotation() { + return this.visibleRotation; + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean isVisual ) - { - final double xOff = -0.15 * this.getUp().offsetX; - final double yOff = -0.15 * this.getUp().offsetY; - final double zOff = -0.15 * this.getUp().offsetZ; - return Collections.singletonList( AxisAlignedBB.getBoundingBox( xOff + 0.15, yOff + 0.15, zOff + 0.15, xOff + 0.85, yOff + 0.85, zOff + 0.85 ) ); - } - - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - final double xOff = -0.15 * this.getUp().offsetX; - final double yOff = -0.15 * this.getUp().offsetY; - final double zOff = -0.15 * this.getUp().offsetZ; - out.add( AxisAlignedBB.getBoundingBox( xOff + 0.15, yOff + 0.15, zOff + 0.15,// ahh - xOff + 0.85, yOff + 0.85, zOff + 0.85 ) ); - } - - public float getVisibleRotation() - { - return this.visibleRotation; - } - - private void setVisibleRotation( final float visibleRotation ) - { - this.visibleRotation = visibleRotation; - } + private void setVisibleRotation(final float visibleRotation) { + this.visibleRotation = visibleRotation; + } } diff --git a/src/main/java/appeng/tile/grindstone/TileGrinder.java b/src/main/java/appeng/tile/grindstone/TileGrinder.java index 33f25753..2a8aa8e3 100644 --- a/src/main/java/appeng/tile/grindstone/TileGrinder.java +++ b/src/main/java/appeng/tile/grindstone/TileGrinder.java @@ -18,6 +18,8 @@ package appeng.tile.grindstone; +import java.util.ArrayList; +import java.util.List; import appeng.api.AEApi; import appeng.api.features.IGrinderEntry; @@ -33,168 +35,152 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.List; +public class TileGrinder extends AEBaseInvTile implements ICrankable { + private final int[] inputs = { 0, 1, 2 }; + private final int[] sides = { 0, 1, 2, 3, 4, 5 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 7); + private int points; + @Override + public void + setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getBlockType().onNeighborBlockChange( + this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK + ); + } -public class TileGrinder extends AEBaseInvTile implements ICrankable -{ + @Override + public IInventory getInternalInventory() { + return this.inv; + } - private final int[] inputs = { 0, 1, 2 }; - private final int[] sides = { 0, 1, 2, 3, 4, 5 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 7 ); - private int points; + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) {} - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getBlockType().onNeighborBlockChange( this.worldObj, this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK ); - } + @Override + public boolean + canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + if (AEApi.instance().registries().grinder().getRecipeForInput(insertingItem) + == null) { + return false; + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + return slotIndex >= 0 && slotIndex <= 2; + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex >= 3 && slotIndex <= 5; + } - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - if( AEApi.instance().registries().grinder().getRecipeForInput( insertingItem ) == null ) - { - return false; - } + @Override + public boolean canTurn() { + if (Platform.isClient()) { + return false; + } - return slotIndex >= 0 && slotIndex <= 2; - } + if (null == this.getStackInSlot(6)) // Add if there isn't one... + { + final IInventory src = new WrapperInventoryRange(this, this.inputs, true); + for (int x = 0; x < src.getSizeInventory(); x++) { + ItemStack item = src.getStackInSlot(x); + if (item == null) { + continue; + } - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex >= 3 && slotIndex <= 5; - } + final IGrinderEntry r + = AEApi.instance().registries().grinder().getRecipeForInput(item); + if (r != null) { + if (item.stackSize >= r.getInput().stackSize) { + item.stackSize -= r.getInput().stackSize; + final ItemStack ais = item.copy(); + ais.stackSize = r.getInput().stackSize; - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } + if (item.stackSize <= 0) { + item = null; + } - @Override - public boolean canTurn() - { - if( Platform.isClient() ) - { - return false; - } + src.setInventorySlotContents(x, item); + this.setInventorySlotContents(6, ais); + return true; + } + } + } + return false; + } + return true; + } - if( null == this.getStackInSlot( 6 ) ) // Add if there isn't one... - { - final IInventory src = new WrapperInventoryRange( this, this.inputs, true ); - for( int x = 0; x < src.getSizeInventory(); x++ ) - { - ItemStack item = src.getStackInSlot( x ); - if( item == null ) - { - continue; - } + @Override + public void applyTurn() { + if (Platform.isClient()) { + return; + } - final IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput( item ); - if( r != null ) - { - if( item.stackSize >= r.getInput().stackSize ) - { - item.stackSize -= r.getInput().stackSize; - final ItemStack ais = item.copy(); - ais.stackSize = r.getInput().stackSize; + this.points++; - if( item.stackSize <= 0 ) - { - item = null; - } + final ItemStack processing = this.getStackInSlot(6); + final IGrinderEntry r + = AEApi.instance().registries().grinder().getRecipeForInput(processing); + if (r != null) { + if (r.getEnergyCost() > this.points) { + return; + } - src.setInventorySlotContents( x, item ); - this.setInventorySlotContents( 6, ais ); - return true; - } - } - } - return false; - } - return true; - } + this.points = 0; + final InventoryAdaptor sia = InventoryAdaptor.getAdaptor( + new WrapperInventoryRange(this, 3, 3, true), ForgeDirection.EAST + ); - @Override - public void applyTurn() - { - if( Platform.isClient() ) - { - return; - } + this.addItem(sia, r.getOutput()); - this.points++; + float chance = (Platform.getRandomInt() % 2000) / 2000.0f; + if (chance <= r.getOptionalChance()) { + this.addItem(sia, r.getOptionalOutput()); + } - final ItemStack processing = this.getStackInSlot( 6 ); - final IGrinderEntry r = AEApi.instance().registries().grinder().getRecipeForInput( processing ); - if( r != null ) - { - if( r.getEnergyCost() > this.points ) - { - return; - } + chance = (Platform.getRandomInt() % 2000) / 2000.0f; + if (chance <= r.getSecondOptionalChance()) { + this.addItem(sia, r.getSecondOptionalOutput()); + } - this.points = 0; - final InventoryAdaptor sia = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this, 3, 3, true ), ForgeDirection.EAST ); + this.setInventorySlotContents(6, null); + } + } - this.addItem( sia, r.getOutput() ); + private void addItem(final InventoryAdaptor sia, final ItemStack output) { + if (output == null) { + return; + } - float chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; - if( chance <= r.getOptionalChance() ) - { - this.addItem( sia, r.getOptionalOutput() ); - } + final ItemStack notAdded = sia.addItems(output); + if (notAdded != null) { + final WorldCoord wc = new WorldCoord(this.xCoord, this.yCoord, this.zCoord); - chance = ( Platform.getRandomInt() % 2000 ) / 2000.0f; - if( chance <= r.getSecondOptionalChance() ) - { - this.addItem( sia, r.getSecondOptionalOutput() ); - } + wc.add(this.getForward(), 1); - this.setInventorySlotContents( 6, null ); - } - } + final List out = new ArrayList(); + out.add(notAdded); - private void addItem( final InventoryAdaptor sia, final ItemStack output ) - { - if( output == null ) - { - return; - } + Platform.spawnDrops(this.worldObj, wc.x, wc.y, wc.z, out); + } + } - final ItemStack notAdded = sia.addItems( output ); - if( notAdded != null ) - { - final WorldCoord wc = new WorldCoord( this.xCoord, this.yCoord, this.zCoord ); - - wc.add( this.getForward(), 1 ); - - final List out = new ArrayList(); - out.add( notAdded ); - - Platform.spawnDrops( this.worldObj, wc.x, wc.y, wc.z, out ); - } - } - - @Override - public boolean canCrankAttach( final ForgeDirection directionToCrank ) - { - return this.getUp() == directionToCrank; - } + @Override + public boolean canCrankAttach(final 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 10e504f1..692115af 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 appeng.api.AEApi; import appeng.api.storage.data.IAEItemStack; @@ -31,251 +32,198 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.Iterator; +public class AppEngInternalAEInventory implements IInventory, Iterable { + private final IAEAppEngInventory te; + private final IAEItemStack[] inv; + private final int size; + private int maxStack; + public AppEngInternalAEInventory(final IAEAppEngInventory te, final int s) { + this.te = te; + this.size = s; + this.maxStack = 64; + this.inv = new IAEItemStack[s]; + } -public class AppEngInternalAEInventory implements IInventory, Iterable -{ + public boolean isEmpty() { + for (int x = 0; x < this.size; x++) { + if (this.getStackInSlot(x) != null) { + return false; + } + } + return true; + } - private final IAEAppEngInventory te; - private final IAEItemStack[] inv; - private final int size; - private int maxStack; + public void setMaxStackSize(final int s) { + this.maxStack = s; + } - public AppEngInternalAEInventory( final IAEAppEngInventory te, final int s ) - { - this.te = te; - this.size = s; - this.maxStack = 64; - this.inv = new IAEItemStack[s]; - } + public IAEItemStack getAEStackInSlot(final int var1) { + return this.inv[var1]; + } - public boolean isEmpty() - { - for( int x = 0; x < this.size; x++ ) - { - if( this.getStackInSlot( x ) != null ) - { - return false; - } - } - return true; - } + public void writeToNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = new NBTTagCompound(); + this.writeToNBT(c); + data.setTag(name, c); + } - public void setMaxStackSize( final int s ) - { - this.maxStack = s; - } + private void writeToNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = new NBTTagCompound(); - public IAEItemStack getAEStackInSlot( final int var1 ) - { - return this.inv[var1]; - } + if (this.inv[x] != null) { + this.inv[x].writeToNBT(c); + } - public void writeToNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = new NBTTagCompound(); - this.writeToNBT( c ); - data.setTag( name, c ); - } + target.setTag("#" + x, c); + } catch (final Exception ignored) {} + } + } - private void writeToNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = new NBTTagCompound(); + public void readFromNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = data.getCompoundTag(name); + if (c != null) { + this.readFromNBT(c); + } + } - if( this.inv[x] != null ) - { - this.inv[x].writeToNBT( c ); - } + private void readFromNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = target.getCompoundTag("#" + x); - target.setTag( "#" + x, c ); - } - catch( final Exception ignored ) - { - } - } - } + if (c != null) { + this.inv[x] = AEItemStack.loadItemStackFromNBT(c); + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } - public void readFromNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = data.getCompoundTag( name ); - if( c != null ) - { - this.readFromNBT( c ); - } - } + @Override + public int getSizeInventory() { + return this.size; + } - private void readFromNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = target.getCompoundTag( "#" + x ); + @Override + public ItemStack getStackInSlot(final int var1) { + if (this.inv[var1] == null) { + return null; + } - if( c != null ) - { - this.inv[x] = AEItemStack.loadItemStackFromNBT( c ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } + return this.inv[var1].getItemStack(); + } - @Override - public int getSizeInventory() - { - return this.size; - } + @Override + public ItemStack decrStackSize(final int slot, final int qty) { + if (this.inv[slot] != null) { + final ItemStack split = this.getStackInSlot(slot); + ItemStack ns = null; - @Override - public ItemStack getStackInSlot( final int var1 ) - { - if( this.inv[var1] == null ) - { - return null; - } + if (qty >= split.stackSize) { + ns = this.getStackInSlot(slot); + this.inv[slot] = null; + } else { + ns = split.splitStack(qty); + } - return this.inv[var1].getItemStack(); - } + if (this.te != null && Platform.isServer()) { + this.te.onChangeInventory( + this, slot, InvOperation.decreaseStackSize, ns, null + ); + this.te.saveChanges(); + } - @Override - public ItemStack decrStackSize( final int slot, final int qty ) - { - if( this.inv[slot] != null ) - { - final ItemStack split = this.getStackInSlot( slot ); - ItemStack ns = null; + return ns; + } - if( qty >= split.stackSize ) - { - ns = this.getStackInSlot( slot ); - this.inv[slot] = null; - } - else - { - ns = split.splitStack( qty ); - } + return null; + } - if( this.te != null && Platform.isServer() ) - { - this.te.onChangeInventory( this, slot, InvOperation.decreaseStackSize, ns, null ); - this.te.saveChanges(); - } + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } - return ns; - } + @Override + public void setInventorySlotContents(final int slot, final ItemStack newItemStack) { + final ItemStack oldStack = this.getStackInSlot(slot); + this.inv[slot] = AEApi.instance().storage().createItemStack(newItemStack); - return null; - } + if (this.te != null && Platform.isServer()) { + ItemStack removed = oldStack; + ItemStack added = newItemStack; - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } + if (oldStack != null && newItemStack != null + && Platform.isSameItem(oldStack, newItemStack)) { + if (oldStack.stackSize > newItemStack.stackSize) { + removed = removed.copy(); + removed.stackSize -= newItemStack.stackSize; + added = null; + } else if (oldStack.stackSize < newItemStack.stackSize) { + added = added.copy(); + added.stackSize -= oldStack.stackSize; + removed = null; + } else { + removed = added = null; + } + } - @Override - public void setInventorySlotContents( final int slot, final ItemStack newItemStack ) - { - final ItemStack oldStack = this.getStackInSlot( slot ); - this.inv[slot] = AEApi.instance().storage().createItemStack( newItemStack ); + this.te.onChangeInventory( + this, slot, InvOperation.setInventorySlotContents, removed, added + ); + this.te.saveChanges(); + } + } - if( this.te != null && Platform.isServer() ) - { - ItemStack removed = oldStack; - ItemStack added = newItemStack; + @Override + public String getInventoryName() { + return "appeng-internal"; + } - if( oldStack != null && newItemStack != null && Platform.isSameItem( oldStack, newItemStack ) ) - { - if( oldStack.stackSize > newItemStack.stackSize ) - { - removed = removed.copy(); - removed.stackSize -= newItemStack.stackSize; - added = null; - } - else if( oldStack.stackSize < newItemStack.stackSize ) - { - added = added.copy(); - added.stackSize -= oldStack.stackSize; - removed = null; - } - else - { - removed = added = null; - } - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - this.te.onChangeInventory( this, slot, InvOperation.setInventorySlotContents, removed, added ); - this.te.saveChanges(); - } - } + @Override + public int getInventoryStackLimit() { + return this.maxStack > 64 ? 64 : this.maxStack; + } - @Override - public String getInventoryName() - { - return "appeng-internal"; - } + @Override + public void markDirty() { + if (this.te != null && Platform.isServer()) { + this.te.onChangeInventory(this, -1, InvOperation.markDirty, null, null); + this.te.saveChanges(); + } + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return true; + } - @Override - public int getInventoryStackLimit() - { - return this.maxStack > 64 ? 64 : this.maxStack; - } + @Override + public void openInventory() {} - @Override - public void markDirty() - { - if( this.te != null && Platform.isServer() ) - { - this.te.onChangeInventory( this, -1, InvOperation.markDirty, null, null ); - this.te.saveChanges(); - } - } + @Override + public void closeInventory() {} - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return true; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return true; + } - @Override - public void openInventory() - { - } + @Override + public Iterator iterator() { + return new InvIterator(this); + } - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return true; - } - - @Override - public Iterator iterator() - { - return new InvIterator( this ); - } - - public Iterator getNewAEIterator() - { - return new AEInvIterator( this ); - } + public Iterator getNewAEIterator() { + return new AEInvIterator(this); + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java b/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java index fb28cb5b..9c22fb56 100644 --- a/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngInternalInventory.java @@ -18,6 +18,7 @@ package appeng.tile.inventory; +import java.util.Iterator; import appeng.api.storage.IMEInventory; import appeng.core.AELog; @@ -29,278 +30,224 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.util.Iterator; +public class AppEngInternalInventory implements IInventory, Iterable { + private final int size; + private final ItemStack[] inv; + private boolean enableClientEvents = false; + private IAEAppEngInventory te; + private int maxStack; + public AppEngInternalInventory(final IAEAppEngInventory inventory, final int size) { + this.setTileEntity(inventory); + this.size = size; + this.maxStack = 64; + this.inv = new ItemStack[size]; + } -public class AppEngInternalInventory implements IInventory, Iterable -{ + public IMEInventory getMEInventory() { + return new MEIInventoryWrapper(this, null); + } - private final int size; - private final ItemStack[] inv; - private boolean enableClientEvents = false; - private IAEAppEngInventory te; - private int maxStack; + public boolean isEmpty() { + for (int x = 0; x < this.size; x++) { + if (this.getStackInSlot(x) != null) { + return false; + } + } + return true; + } - public AppEngInternalInventory( final IAEAppEngInventory inventory, final int size ) - { - this.setTileEntity( inventory ); - this.size = size; - this.maxStack = 64; - this.inv = new ItemStack[size]; - } + @Override + public int getSizeInventory() { + return this.size; + } - public IMEInventory getMEInventory() - { - return new MEIInventoryWrapper( this, null ); - } + @Override + public ItemStack getStackInSlot(final int var1) { + return this.inv[var1]; + } - public boolean isEmpty() - { - for( int x = 0; x < this.size; x++ ) - { - if( this.getStackInSlot( x ) != null ) - { - return false; - } - } - return true; - } + @Override + public ItemStack decrStackSize(final int slot, final int qty) { + if (this.inv[slot] != null) { + final ItemStack split = this.getStackInSlot(slot); + ItemStack ns = null; - @Override - public int getSizeInventory() - { - return this.size; - } + if (qty >= split.stackSize) { + ns = this.inv[slot]; + this.inv[slot] = null; + } else { + ns = split.splitStack(qty); + } - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return this.inv[var1]; - } + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory( + this, slot, InvOperation.decreaseStackSize, ns, null + ); + } - @Override - public ItemStack decrStackSize( final int slot, final int qty ) - { - if( this.inv[slot] != null ) - { - final ItemStack split = this.getStackInSlot( slot ); - ItemStack ns = null; + this.markDirty(); + return ns; + } - if( qty >= split.stackSize ) - { - ns = this.inv[slot]; - this.inv[slot] = null; - } - else - { - ns = split.splitStack( qty ); - } + return null; + } - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - this.getTileEntity().onChangeInventory( this, slot, InvOperation.decreaseStackSize, ns, null ); - } + protected boolean eventsEnabled() { + return Platform.isServer() || this.isEnableClientEvents(); + } - this.markDirty(); - return ns; - } + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } - return null; - } + @Override + public void setInventorySlotContents(final int slot, final ItemStack newItemStack) { + final ItemStack oldStack = this.inv[slot]; + this.inv[slot] = newItemStack; - protected boolean eventsEnabled() - { - return Platform.isServer() || this.isEnableClientEvents(); - } + if (this.getTileEntity() != null && this.eventsEnabled()) { + ItemStack removed = oldStack; + ItemStack added = newItemStack; - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } + if (oldStack != null && newItemStack != null + && Platform.isSameItem(oldStack, newItemStack)) { + if (oldStack.stackSize > newItemStack.stackSize) { + removed = removed.copy(); + removed.stackSize -= newItemStack.stackSize; + added = null; + } else if (oldStack.stackSize < newItemStack.stackSize) { + added = added.copy(); + added.stackSize -= oldStack.stackSize; + removed = null; + } else { + removed = added = null; + } + } - @Override - public void setInventorySlotContents( final int slot, final ItemStack newItemStack ) - { - final ItemStack oldStack = this.inv[slot]; - this.inv[slot] = newItemStack; + this.getTileEntity().onChangeInventory( + this, slot, InvOperation.setInventorySlotContents, removed, added + ); - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - ItemStack removed = oldStack; - ItemStack added = newItemStack; + this.markDirty(); + } + } - if( oldStack != null && newItemStack != null && Platform.isSameItem( oldStack, newItemStack ) ) - { - if( oldStack.stackSize > newItemStack.stackSize ) - { - removed = removed.copy(); - removed.stackSize -= newItemStack.stackSize; - added = null; - } - else if( oldStack.stackSize < newItemStack.stackSize ) - { - added = added.copy(); - added.stackSize -= oldStack.stackSize; - removed = null; - } - else - { - removed = added = null; - } - } + @Override + public String getInventoryName() { + return "appeng-internal"; + } - this.getTileEntity().onChangeInventory( this, slot, InvOperation.setInventorySlotContents, removed, added ); + @Override + public boolean hasCustomInventoryName() { + return false; + } - this.markDirty(); - } - } + @Override + public int getInventoryStackLimit() { + return this.maxStack > 64 ? 64 : this.maxStack; + } - @Override - public String getInventoryName() - { - return "appeng-internal"; - } + @Override + public void markDirty() { + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory( + this, -1, InvOperation.markDirty, null, null + ); + this.getTileEntity().saveChanges(); + } + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return true; + } - @Override - public int getInventoryStackLimit() - { - return this.maxStack > 64 ? 64 : this.maxStack; - } + @Override + public void openInventory() {} - @Override - public void markDirty() - { - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - this.getTileEntity().onChangeInventory( this, -1, InvOperation.markDirty, null, null ); - this.getTileEntity().saveChanges(); - } - } + @Override + public void closeInventory() {} - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return true; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return true; + } - @Override - public void openInventory() - { - } + public void setMaxStackSize(final int s) { + this.maxStack = s; + } - @Override - public void closeInventory() - { - } + // for guis... + public void markDirty(final int slotIndex) { + if (this.getTileEntity() != null && this.eventsEnabled()) { + this.getTileEntity().onChangeInventory( + this, slotIndex, InvOperation.markDirty, null, null + ); + this.getTileEntity().saveChanges(); + } + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return true; - } + public void writeToNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = new NBTTagCompound(); + this.writeToNBT(c); + data.setTag(name, c); + } - public void setMaxStackSize( final int s ) - { - this.maxStack = s; - } + private void writeToNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = new NBTTagCompound(); - // for guis... - public void markDirty( final int slotIndex ) - { - if( this.getTileEntity() != null && this.eventsEnabled() ) - { - this.getTileEntity().onChangeInventory( this, slotIndex, InvOperation.markDirty, null, null ); - this.getTileEntity().saveChanges(); - } - } + if (this.inv[x] != null) { + this.inv[x].writeToNBT(c); + } - public void writeToNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = new NBTTagCompound(); - this.writeToNBT( c ); - data.setTag( name, c ); - } + target.setTag("#" + x, c); + } catch (final Exception ignored) {} + } + } - private void writeToNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = new NBTTagCompound(); + public void readFromNBT(final NBTTagCompound data, final String name) { + final NBTTagCompound c = data.getCompoundTag(name); + if (c != null) { + this.readFromNBT(c); + } + } - if( this.inv[x] != null ) - { - this.inv[x].writeToNBT( c ); - } + public void readFromNBT(final NBTTagCompound target) { + for (int x = 0; x < this.size; x++) { + try { + final NBTTagCompound c = target.getCompoundTag("#" + x); - target.setTag( "#" + x, c ); - } - catch( final Exception ignored ) - { - } - } - } + if (c != null) { + this.inv[x] = ItemStack.loadItemStackFromNBT(c); + } + } catch (final Exception e) { + AELog.debug(e); + } + } + } - public void readFromNBT( final NBTTagCompound data, final String name ) - { - final NBTTagCompound c = data.getCompoundTag( name ); - if( c != null ) - { - this.readFromNBT( c ); - } - } + @Override + public Iterator iterator() { + return new InvIterator(this); + } - public void readFromNBT( final NBTTagCompound target ) - { - for( int x = 0; x < this.size; x++ ) - { - try - { - final NBTTagCompound c = target.getCompoundTag( "#" + x ); + private boolean isEnableClientEvents() { + return this.enableClientEvents; + } - if( c != null ) - { - this.inv[x] = ItemStack.loadItemStackFromNBT( c ); - } - } - catch( final Exception e ) - { - AELog.debug( e ); - } - } - } + public void setEnableClientEvents(final boolean enableClientEvents) { + this.enableClientEvents = enableClientEvents; + } - @Override - public Iterator iterator() - { - return new InvIterator( this ); - } + private IAEAppEngInventory getTileEntity() { + return this.te; + } - private boolean isEnableClientEvents() - { - return this.enableClientEvents; - } - - public void setEnableClientEvents( final boolean enableClientEvents ) - { - this.enableClientEvents = enableClientEvents; - } - - private IAEAppEngInventory getTileEntity() - { - return this.te; - } - - public void setTileEntity( final IAEAppEngInventory te ) - { - this.te = te; - } + public void setTileEntity(final IAEAppEngInventory te) { + this.te = te; + } } diff --git a/src/main/java/appeng/tile/inventory/AppEngNullInventory.java b/src/main/java/appeng/tile/inventory/AppEngNullInventory.java index 1cb62853..cc743d9f 100644 --- a/src/main/java/appeng/tile/inventory/AppEngNullInventory.java +++ b/src/main/java/appeng/tile/inventory/AppEngNullInventory.java @@ -18,97 +18,70 @@ 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() {} -public class AppEngNullInventory implements IInventory -{ + public void writeToNBT(final NBTTagCompound target) {} - public AppEngNullInventory() - { - } + @Override + public int getSizeInventory() { + return 0; + } - public void writeToNBT( final NBTTagCompound target ) - { - } + @Override + public ItemStack getStackInSlot(final int var1) { + return null; + } - @Override - public int getSizeInventory() - { - return 0; - } + @Override + public ItemStack decrStackSize(final int slot, final int qty) { + return null; + } - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return null; - } + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return null; + } - @Override - public ItemStack decrStackSize( final int slot, final int qty ) - { - return null; - } + @Override + public void setInventorySlotContents(final int slot, final ItemStack newItemStack) {} - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return null; - } + @Override + public String getInventoryName() { + return "appeng-internal"; + } - @Override - public void setInventorySlotContents( final int slot, final ItemStack newItemStack ) - { + @Override + public boolean hasCustomInventoryName() { + return false; + } - } + @Override + public int getInventoryStackLimit() { + return 0; + } - @Override - public String getInventoryName() - { - return "appeng-internal"; - } + @Override + public void markDirty() {} - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return false; + } - @Override - public int getInventoryStackLimit() - { - return 0; - } + @Override + public void openInventory() {} - @Override - public void markDirty() - { + @Override + public void closeInventory() {} - } - - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return false; - } - - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return false; - } + @Override + public boolean isItemValidForSlot(final int i, final 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 2ca28a38..ebc8d2fa 100644 --- a/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java +++ b/src/main/java/appeng/tile/inventory/IAEAppEngInventory.java @@ -18,15 +18,17 @@ package appeng.tile.inventory; - import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; +public interface IAEAppEngInventory { + void saveChanges(); -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 aaa9a016..05e1450b 100644 --- a/src/main/java/appeng/tile/inventory/InvOperation.java +++ b/src/main/java/appeng/tile/inventory/InvOperation.java @@ -18,9 +18,9 @@ package appeng.tile.inventory; - -public enum InvOperation -{ - decreaseStackSize, setInventorySlotContents, markDirty +public enum InvOperation { + decreaseStackSize, + setInventorySlotContents, + markDirty } diff --git a/src/main/java/appeng/tile/legacy/TileCraftTerminal.java b/src/main/java/appeng/tile/legacy/TileCraftTerminal.java index 07407f77..93d534c1 100644 --- a/src/main/java/appeng/tile/legacy/TileCraftTerminal.java +++ b/src/main/java/appeng/tile/legacy/TileCraftTerminal.java @@ -8,36 +8,39 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -public class TileCraftTerminal extends TileTerminal implements ICraftingTerminal, IAEAppEngInventory { - - private final AppEngInternalInventory craftingGrid = new AppEngInternalInventory( this, 9 ); +public class TileCraftTerminal + extends TileTerminal implements ICraftingTerminal, IAEAppEngInventory { + private final AppEngInternalInventory craftingGrid + = new AppEngInternalInventory(this, 9); @Override public IInventory getInventoryByName(String name) { - if( name.equals( "crafting" ) ) - { + if (name.equals("crafting")) { return this.craftingGrid; } return null; } @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 + ) { this.markDirty(); } @Override - public void readFromNBT( final NBTTagCompound data ) - { - super.readFromNBT( data ); - this.craftingGrid.readFromNBT( data, "craftingGrid" ); + public void readFromNBT(final NBTTagCompound data) { + super.readFromNBT(data); + this.craftingGrid.readFromNBT(data, "craftingGrid"); } @Override - public void writeToNBT( final NBTTagCompound data ) - { - super.writeToNBT( data ); - this.craftingGrid.writeToNBT( data, "craftingGrid" ); + public void writeToNBT(final NBTTagCompound data) { + super.writeToNBT(data); + this.craftingGrid.writeToNBT(data, "craftingGrid"); } - } diff --git a/src/main/java/appeng/tile/legacy/TileCraftingMonitor.java b/src/main/java/appeng/tile/legacy/TileCraftingMonitor.java index 262b26ef..33f06e0a 100644 --- a/src/main/java/appeng/tile/legacy/TileCraftingMonitor.java +++ b/src/main/java/appeng/tile/legacy/TileCraftingMonitor.java @@ -2,5 +2,4 @@ package appeng.tile.legacy; import appeng.api.storage.ITerminalHost; -public class TileCraftingMonitor extends TileTerminal { -} +public class TileCraftingMonitor extends TileTerminal {} diff --git a/src/main/java/appeng/tile/legacy/TileLegacyController.java b/src/main/java/appeng/tile/legacy/TileLegacyController.java index b74b1e0b..21bad806 100644 --- a/src/main/java/appeng/tile/legacy/TileLegacyController.java +++ b/src/main/java/appeng/tile/legacy/TileLegacyController.java @@ -10,13 +10,12 @@ import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; public class TileLegacyController extends AENetworkPowerTile { - - private static final IInventory NULL_INVENTORY = new AppEngInternalInventory( null, 0 ); + private static final IInventory NULL_INVENTORY = new AppEngInternalInventory(null, 0); private static final int[] ACCESSIBLE_SLOTS_BY_SIDE = {}; public TileLegacyController() { //TODO Fix power storage - this.setInternalMaxPower( 10000 ); - this.setInternalPublicPowerStorage( true ); + this.setInternalMaxPower(10000); + this.setInternalPublicPowerStorage(true); this.getProxy().setIdlePowerUsage(6.0); } @@ -26,9 +25,9 @@ public class TileLegacyController 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 whichSide) { @@ -36,42 +35,34 @@ public class TileLegacyController extends AENetworkPowerTile { } @Override - protected double getFunnelPowerDemand( final double maxReceived ) - { + protected double getFunnelPowerDemand(final double maxReceived) { updateMeta(); - try - { - return this.getProxy().getEnergy().getEnergyDemand( 10000 ); - } - catch( final GridAccessException e ) - { + try { + return this.getProxy().getEnergy().getEnergyDemand(10000); + } catch (final GridAccessException e) { // no grid? use local... - return super.getFunnelPowerDemand( maxReceived ); + return super.getFunnelPowerDemand(maxReceived); } } @Override - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { updateMeta(); - try - { - final double ret = this.getProxy().getEnergy().injectPower( power, mode ); - if( mode == Actionable.SIMULATE ) - { + try { + final double ret = this.getProxy().getEnergy().injectPower(power, mode); + if (mode == Actionable.SIMULATE) { return ret; } return 0; - } - catch( final GridAccessException e ) - { + } catch (final GridAccessException e) { // no grid? use local... - return super.funnelPowerIntoStorage( power, mode ); + return super.funnelPowerIntoStorage(power, mode); } } public void updateMeta() { - int meta = (int) Math.ceil((5.0 * this.getInternalCurrentPower() / this.getInternalMaxPower())); + int meta = (int + ) Math.ceil((5.0 * this.getInternalCurrentPower() / this.getInternalMaxPower())); if (meta < 0) { meta = 0; } else if (meta > 5) { @@ -80,9 +71,8 @@ public class TileLegacyController extends AENetworkPowerTile { if (getProxy().isActive() && getInternalCurrentPower() == 0.0) { meta = 6; } - this.worldObj.setBlockMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, meta, 2); + this.worldObj.setBlockMetadataWithNotify( + this.xCoord, this.yCoord, this.zCoord, meta, 2 + ); } - - - } diff --git a/src/main/java/appeng/tile/legacy/TileTerminal.java b/src/main/java/appeng/tile/legacy/TileTerminal.java index 0aeabdb5..8949694d 100644 --- a/src/main/java/appeng/tile/legacy/TileTerminal.java +++ b/src/main/java/appeng/tile/legacy/TileTerminal.java @@ -1,5 +1,7 @@ package appeng.tile.legacy; +import java.util.EnumSet; + import appeng.api.config.Settings; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; @@ -15,31 +17,25 @@ import appeng.util.ConfigManager; import appeng.util.IConfigManagerHost; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class TileTerminal + extends AENetworkTile implements ITerminalHost, IConfigManagerHost { + private final IConfigManager cm = new ConfigManager(this); -public class TileTerminal extends AENetworkTile implements ITerminalHost, IConfigManagerHost { + public TileTerminal() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(0.5); + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); - private final IConfigManager cm = new ConfigManager( this ); - - public TileTerminal() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setIdlePowerUsage( 0.5 ); - this.getProxy().setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - - this.cm.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.cm.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.cm.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); + 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 IMEMonitor getItemInventory() { - try - { + try { return this.getProxy().getStorage().getItemInventory(); - } - catch( final GridAccessException e ) - { + } catch (final GridAccessException e) { // err nope? } return null; @@ -47,12 +43,9 @@ public class TileTerminal extends AENetworkTile implements ITerminalHost, IConfi @Override public IMEMonitor getFluidInventory() { - try - { + try { return this.getProxy().getStorage().getFluidInventory(); - } - catch( final GridAccessException e ) - { + } catch (final GridAccessException e) { // err nope? } return null; @@ -64,8 +57,5 @@ public class TileTerminal extends AENetworkTile implements ITerminalHost, IConfi } @Override - public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) { - - } - + public void updateSetting(IConfigManager manager, Enum settingName, Enum newValue) {} } diff --git a/src/main/java/appeng/tile/misc/TileCellWorkbench.java b/src/main/java/appeng/tile/misc/TileCellWorkbench.java index 025740a2..a774d749 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.List; import appeng.api.config.CopyMode; import appeng.api.config.Settings; @@ -39,220 +40,190 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -import java.util.List; +public class TileCellWorkbench extends AEBaseTile + implements IUpgradeableHost, IAEAppEngInventory, IConfigManagerHost { + private final AppEngInternalInventory cell = new AppEngInternalInventory(this, 1); + private final AppEngInternalAEInventory config + = new AppEngInternalAEInventory(this, 63); + private final ConfigManager manager = new ConfigManager(this); + private IInventory cacheUpgrades = null; + private IInventory cacheConfig = null; + private boolean locked = false; -public class TileCellWorkbench extends AEBaseTile implements IUpgradeableHost, IAEAppEngInventory, IConfigManagerHost -{ + public TileCellWorkbench() { + this.manager.registerSetting(Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE); + this.cell.setEnableClientEvents(true); + } - private final AppEngInternalInventory cell = new AppEngInternalInventory( this, 1 ); - private final AppEngInternalAEInventory config = new AppEngInternalAEInventory( this, 63 ); - private final ConfigManager manager = new ConfigManager( this ); + public IInventory getCellUpgradeInventory() { + if (this.cacheUpgrades == null) { + final ICellWorkbenchItem cell = this.getCell(); + if (cell == null) { + return null; + } - private IInventory cacheUpgrades = null; - private IInventory cacheConfig = null; - private boolean locked = false; + final ItemStack is = this.cell.getStackInSlot(0); + if (is == null) { + return null; + } - public TileCellWorkbench() - { - this.manager.registerSetting( Settings.COPY_MODE, CopyMode.CLEAR_ON_REMOVE ); - this.cell.setEnableClientEvents( true ); - } + final IInventory inv = cell.getUpgradesInventory(is); + if (inv == null) { + return null; + } - public IInventory getCellUpgradeInventory() - { - if( this.cacheUpgrades == null ) - { - final ICellWorkbenchItem cell = this.getCell(); - if( cell == null ) - { - return null; - } + return this.cacheUpgrades = inv; + } + return this.cacheUpgrades; + } - final ItemStack is = this.cell.getStackInSlot( 0 ); - if( is == null ) - { - return null; - } + public ICellWorkbenchItem getCell() { + if (this.cell.getStackInSlot(0) == null) { + return null; + } - final IInventory inv = cell.getUpgradesInventory( is ); - if( inv == null ) - { - return null; - } + if (this.cell.getStackInSlot(0).getItem() instanceof ICellWorkbenchItem) { + return ((ICellWorkbenchItem) this.cell.getStackInSlot(0).getItem()); + } - return this.cacheUpgrades = inv; - } - return this.cacheUpgrades; - } + return null; + } - public ICellWorkbenchItem getCell() - { - if( this.cell.getStackInSlot( 0 ) == null ) - { - return null; - } + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCellWorkbench(final NBTTagCompound data) { + this.cell.writeToNBT(data, "cell"); + this.config.writeToNBT(data, "config"); + this.manager.writeToNBT(data); + } - if( this.cell.getStackInSlot( 0 ).getItem() instanceof ICellWorkbenchItem ) - { - return ( (ICellWorkbenchItem) this.cell.getStackInSlot( 0 ).getItem() ); - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCellWorkbench(final NBTTagCompound data) { + this.cell.readFromNBT(data, "cell"); + this.config.readFromNBT(data, "config"); + this.manager.readFromNBT(data); + } - return null; - } + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("config")) { + return this.config; + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCellWorkbench( final NBTTagCompound data ) - { - this.cell.writeToNBT( data, "cell" ); - this.config.writeToNBT( data, "config" ); - this.manager.writeToNBT( data ); - } + if (name.equals("cell")) { + return this.cell; + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCellWorkbench( final NBTTagCompound data ) - { - this.cell.readFromNBT( data, "cell" ); - this.config.readFromNBT( data, "config" ); - this.manager.readFromNBT( data ); - } + return null; + } - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "config" ) ) - { - return this.config; - } + @Override + public int getInstalledUpgrades(final Upgrades u) { + return 0; + } - if( name.equals( "cell" ) ) - { - return this.cell; - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) { + if (inv == this.cell && !this.locked) { + this.locked = true; - return null; - } + this.cacheUpgrades = null; + this.cacheConfig = null; - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return 0; - } + final IInventory configInventory = this.getCellConfigInventory(); + if (configInventory != null) { + boolean cellHasConfig = false; + for (int x = 0; x < configInventory.getSizeInventory(); x++) { + if (configInventory.getStackInSlot(x) != null) { + cellHasConfig = true; + break; + } + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { - if( inv == this.cell && !this.locked ) - { - this.locked = true; + if (cellHasConfig) { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + this.config.setInventorySlotContents( + x, configInventory.getStackInSlot(x) + ); + } + } else { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + configInventory.setInventorySlotContents( + x, this.config.getStackInSlot(x) + ); + } - this.cacheUpgrades = null; - this.cacheConfig = null; + configInventory.markDirty(); + } + } else if (this.manager.getSetting(Settings.COPY_MODE) == CopyMode.CLEAR_ON_REMOVE) { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + this.config.setInventorySlotContents(x, null); + } - final IInventory configInventory = this.getCellConfigInventory(); - if( configInventory != null ) - { - boolean cellHasConfig = false; - for( int x = 0; x < configInventory.getSizeInventory(); x++ ) - { - if( configInventory.getStackInSlot( x ) != null ) - { - cellHasConfig = true; - break; - } - } + this.markDirty(); + } - if( cellHasConfig ) - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - this.config.setInventorySlotContents( x, configInventory.getStackInSlot( x ) ); - } - } - else - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - configInventory.setInventorySlotContents( x, this.config.getStackInSlot( x ) ); - } + this.locked = false; + } else if (inv == this.config && !this.locked) { + final IInventory c = this.getCellConfigInventory(); + if (c != null) { + for (int x = 0; x < this.config.getSizeInventory(); x++) { + c.setInventorySlotContents(x, this.config.getStackInSlot(x)); + } - configInventory.markDirty(); - } - } - else if( this.manager.getSetting( Settings.COPY_MODE ) == CopyMode.CLEAR_ON_REMOVE ) - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - this.config.setInventorySlotContents( x, null ); - } + c.markDirty(); + } + } + } - this.markDirty(); - } + private IInventory getCellConfigInventory() { + if (this.cacheConfig == null) { + final ICellWorkbenchItem cell = this.getCell(); + if (cell == null) { + return null; + } - this.locked = false; - } - else if( inv == this.config && !this.locked ) - { - final IInventory c = this.getCellConfigInventory(); - if( c != null ) - { - for( int x = 0; x < this.config.getSizeInventory(); x++ ) - { - c.setInventorySlotContents( x, this.config.getStackInSlot( x ) ); - } + final ItemStack is = this.cell.getStackInSlot(0); + if (is == null) { + return null; + } - c.markDirty(); - } - } - } + final IInventory inv = cell.getConfigInventory(is); + if (inv == null) { + return null; + } - private IInventory getCellConfigInventory() - { - if( this.cacheConfig == null ) - { - final ICellWorkbenchItem cell = this.getCell(); - if( cell == null ) - { - return null; - } + this.cacheConfig = inv; + } + return this.cacheConfig; + } - final ItemStack is = this.cell.getStackInSlot( 0 ); - if( is == null ) - { - return null; - } + @Override + public void getDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + super.getDrops(w, x, y, z, drops); - final IInventory inv = cell.getConfigInventory( is ); - if( inv == null ) - { - return null; - } + if (this.cell.getStackInSlot(0) != null) { + drops.add(this.cell.getStackInSlot(0)); + } + } - this.cacheConfig = inv; - } - return this.cacheConfig; - } + @Override + public IConfigManager getConfigManager() { + return this.manager; + } - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - if( this.cell.getStackInSlot( 0 ) != null ) - { - drops.add( this.cell.getStackInSlot( 0 ) ); - } - } - - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - // nothing here.. - } + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final 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 4cfe2ff6..07ed0639 100644 --- a/src/main/java/appeng/tile/misc/TileCharger.java +++ b/src/main/java/appeng/tile/misc/TileCharger.java @@ -18,6 +18,10 @@ package appeng.tile.misc; +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -44,252 +48,251 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; +public class TileCharger extends AENetworkPowerTile implements ICrankable { + private final int[] sides = { 0 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 1); + private int tickTickTimer = 0; + private int lastUpdate = 0; + private boolean requiresUpdate = false; -public class TileCharger extends AENetworkPowerTile implements ICrankable -{ + public TileCharger() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + this.getProxy().setFlags(); + this.setInternalMaxPower(1500); + this.getProxy().setIdlePowerUsage(0); + } - private final int[] sides = { 0 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 1 ); - private int tickTickTimer = 0; + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - private int lastUpdate = 0; - private boolean requiresUpdate = false; + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCharger(final ByteBuf data) { + try { + final IAEItemStack item = AEItemStack.loadItemStackFromPacket(data); + final ItemStack is = item.getItemStack(); + this.inv.setInventorySlotContents(0, is); + } catch (final Throwable t) { + this.inv.setInventorySlotContents(0, null); + } + return false; // TESR doesn't need updates! + } - public TileCharger() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.getProxy().setFlags(); - this.setInternalMaxPower( 1500 ); - this.getProxy().setIdlePowerUsage( 0 ); - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCharger(final ByteBuf data) throws IOException { + final AEItemStack is = AEItemStack.create(this.getStackInSlot(0)); + if (is != null) { + is.writeToPacket(data); + } + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + @TileEvent(TileEventType.TICK) + public void Tick_TileCharger() { + if (this.lastUpdate > 60 && this.requiresUpdate) { + this.requiresUpdate = false; + this.markForUpdate(); + this.lastUpdate = 0; + } + this.lastUpdate++; - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCharger( final ByteBuf data ) - { - try - { - final IAEItemStack item = AEItemStack.loadItemStackFromPacket( data ); - final ItemStack is = item.getItemStack(); - this.inv.setInventorySlotContents( 0, is ); - } - catch( final Throwable t ) - { - this.inv.setInventorySlotContents( 0, null ); - } - return false; // TESR doesn't need updates! - } + this.tickTickTimer++; + if (this.tickTickTimer < 20) { + return; + } + this.tickTickTimer = 0; - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCharger( final ByteBuf data ) throws IOException - { - final AEItemStack is = AEItemStack.create( this.getStackInSlot( 0 ) ); - if( is != null ) - { - is.writeToPacket( data ); - } - } + final ItemStack myItem = this.getStackInSlot(0); - @TileEvent( TileEventType.TICK ) - public void Tick_TileCharger() - { - if( this.lastUpdate > 60 && this.requiresUpdate ) - { - this.requiresUpdate = false; - this.markForUpdate(); - this.lastUpdate = 0; - } - this.lastUpdate++; + // charge from the network! + if (this.getInternalCurrentPower() < 1499) { + try { + this.injectExternalPower( + PowerUnits.AE, + this.getProxy().getEnergy().extractAEPower( + Math.min(150.0, 1500.0 - this.getInternalCurrentPower()), + Actionable.MODULATE, + PowerMultiplier.ONE + ) + ); + this.tickTickTimer = 20; // keep ticking... + } catch (final GridAccessException e) { + // continue! + } + } - this.tickTickTimer++; - if( this.tickTickTimer < 20 ) - { - return; - } - this.tickTickTimer = 0; + if (myItem == null) { + return; + } - final ItemStack myItem = this.getStackInSlot( 0 ); + final IMaterials materials = AEApi.instance().definitions().materials(); - // charge from the network! - if( this.getInternalCurrentPower() < 1499 ) - { - try - { - this.injectExternalPower( PowerUnits.AE, this.getProxy().getEnergy().extractAEPower( Math.min( 150.0, 1500.0 - this.getInternalCurrentPower() ), Actionable.MODULATE, PowerMultiplier.ONE ) ); - this.tickTickTimer = 20; // keep ticking... - } - catch( final GridAccessException e ) - { - // continue! - } - } + if (this.getInternalCurrentPower() > 149 && Platform.isChargeable(myItem)) { + final IAEItemPowerStorage ps = (IAEItemPowerStorage) myItem.getItem(); + if (ps.getAEMaxPower(myItem) > ps.getAECurrentPower(myItem)) { + final double oldPower = this.getInternalCurrentPower(); - if( myItem == null ) - { - return; - } - - final IMaterials materials = AEApi.instance().definitions().materials(); - - if( this.getInternalCurrentPower() > 149 && Platform.isChargeable( myItem ) ) - { - final IAEItemPowerStorage ps = (IAEItemPowerStorage) myItem.getItem(); - if( ps.getAEMaxPower( myItem ) > ps.getAECurrentPower( myItem ) ) - { - final double oldPower = this.getInternalCurrentPower(); - - final double adjustment = ps.injectAEPower( myItem, this.extractAEPower( 150.0, Actionable.MODULATE, PowerMultiplier.CONFIG ) ); - this.setInternalCurrentPower( this.getInternalCurrentPower() + adjustment ); - if( oldPower > this.getInternalCurrentPower() ) - { - this.requiresUpdate = true; - } - this.tickTickTimer = 20; // keep ticking... - } - } + final double adjustment = ps.injectAEPower( + myItem, + this.extractAEPower( + 150.0, Actionable.MODULATE, PowerMultiplier.CONFIG + ) + ); + this.setInternalCurrentPower(this.getInternalCurrentPower() + adjustment); + if (oldPower > this.getInternalCurrentPower()) { + this.requiresUpdate = true; + } + this.tickTickTimer = 20; // keep ticking... + } + } else if( this.getInternalCurrentPower() > 1499 && materials.certusQuartzCrystal().isSameAs( myItem ) ) { - if( Platform.getRandomFloat() > 0.8f ) // simulate wait - { - this.extractAEPower( this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG );// 1500 + if (Platform.getRandomFloat() > 0.8f) // simulate wait + { + this.extractAEPower( + this.getInternalMaxPower(), + Actionable.MODULATE, + PowerMultiplier.CONFIG + ); // 1500 - for( final ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) - { - this.setInventorySlotContents( 0, charged ); - } - } - } - } + for (final ItemStack charged : materials.certusQuartzCrystalCharged() + .maybeStack(myItem.stackSize) + .asSet()) { + this.setInventorySlotContents(0, charged); + } + } + } + } - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - this.setPowerSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - } + @Override + public void + setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().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 requiresTESR() { + return true; + } - @Override - public boolean canTurn() - { - return this.getInternalCurrentPower() < this.getInternalMaxPower(); - } + @Override + public boolean canTurn() { + return this.getInternalCurrentPower() < this.getInternalMaxPower(); + } - @Override - public void applyTurn() - { - this.injectExternalPower( PowerUnits.AE, 150 ); + @Override + public void applyTurn() { + this.injectExternalPower(PowerUnits.AE, 150); - final ItemStack myItem = this.getStackInSlot( 0 ); - if( this.getInternalCurrentPower() > 1499 ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); + final ItemStack myItem = this.getStackInSlot(0); + if (this.getInternalCurrentPower() > 1499) { + final IMaterials materials = AEApi.instance().definitions().materials(); - if( materials.certusQuartzCrystal().isSameAs( myItem ) ) - { - this.extractAEPower( this.getInternalMaxPower(), Actionable.MODULATE, PowerMultiplier.CONFIG );// 1500 + if (materials.certusQuartzCrystal().isSameAs(myItem)) { + this.extractAEPower( + this.getInternalMaxPower(), + Actionable.MODULATE, + PowerMultiplier.CONFIG + ); // 1500 - for( final ItemStack charged : materials.certusQuartzCrystalCharged().maybeStack( myItem.stackSize ).asSet() ) - { - this.setInventorySlotContents( 0, charged ); - } - } - } - } + for (final ItemStack charged : materials.certusQuartzCrystalCharged() + .maybeStack(myItem.stackSize) + .asSet()) { + this.setInventorySlotContents(0, charged); + } + } + } + } - @Override - public boolean canCrankAttach( final ForgeDirection directionToCrank ) - { - return this.getUp() == directionToCrank || this.getUp().getOpposite() == directionToCrank; - } + @Override + public boolean canCrankAttach(final ForgeDirection directionToCrank) { + return this.getUp() == directionToCrank + || this.getUp().getOpposite() == directionToCrank; + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + @Override + public IInventory getInternalInventory() { + return this.inv; + } - @Override - public int getInventoryStackLimit() - { - return 1; - } + @Override + public int getInventoryStackLimit() { + return 1; + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - final IItemDefinition cert = AEApi.instance().definitions().materials().certusQuartzCrystal(); + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + final IItemDefinition cert + = AEApi.instance().definitions().materials().certusQuartzCrystal(); - return Platform.isChargeable( itemstack ) || cert.isSameAs( itemstack ); - } + return Platform.isChargeable(itemstack) || cert.isSameAs(itemstack); + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - this.markForUpdate(); - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + this.markForUpdate(); + } - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - if( Platform.isChargeable( extractedItem ) ) - { - final IAEItemPowerStorage ips = (IAEItemPowerStorage) extractedItem.getItem(); - if( ips.getAECurrentPower( extractedItem ) >= ips.getAEMaxPower( extractedItem ) ) - { - return true; - } - } + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + if (Platform.isChargeable(extractedItem)) { + final IAEItemPowerStorage ips = (IAEItemPowerStorage) extractedItem.getItem(); + if (ips.getAECurrentPower(extractedItem) + >= ips.getAEMaxPower(extractedItem)) { + return true; + } + } - return AEApi.instance().definitions().materials().certusQuartzCrystalCharged().isSameAs( extractedItem ); - } + return AEApi.instance() + .definitions() + .materials() + .certusQuartzCrystalCharged() + .isSameAs(extractedItem); + } - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection whichSide ) - { - return this.sides; - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection whichSide) { + return this.sides; + } - public void activate( final EntityPlayer player ) - { - if( !Platform.hasPermissions( new DimensionalCoord( this ), player ) ) - { - return; - } + public void activate(final EntityPlayer player) { + if (!Platform.hasPermissions(new DimensionalCoord(this), player)) { + return; + } - final ItemStack myItem = this.getStackInSlot( 0 ); - if( myItem == null ) - { - ItemStack held = player.inventory.getCurrentItem(); + final ItemStack myItem = this.getStackInSlot(0); + if (myItem == null) { + ItemStack held = player.inventory.getCurrentItem(); - if( AEApi.instance().definitions().materials().certusQuartzCrystal().isSameAs( held ) || Platform.isChargeable( held ) ) - { - held = player.inventory.decrStackSize( player.inventory.currentItem, 1 ); - this.setInventorySlotContents( 0, held ); - } - } - else - { - final List drops = new ArrayList(); - drops.add( myItem ); - this.setInventorySlotContents( 0, null ); - Platform.spawnDrops( this.worldObj, this.xCoord + this.getForward().offsetX, this.yCoord + this.getForward().offsetY, this.zCoord + this.getForward().offsetZ, drops ); - } - } + if (AEApi.instance().definitions().materials().certusQuartzCrystal().isSameAs( + held + ) + || Platform.isChargeable(held)) { + held = player.inventory.decrStackSize(player.inventory.currentItem, 1); + this.setInventorySlotContents(0, held); + } + } else { + final List drops = new ArrayList(); + drops.add(myItem); + this.setInventorySlotContents(0, null); + Platform.spawnDrops( + this.worldObj, + this.xCoord + this.getForward().offsetX, + this.yCoord + this.getForward().offsetY, + this.zCoord + this.getForward().offsetZ, + drops + ); + } + } } diff --git a/src/main/java/appeng/tile/misc/TileCondenser.java b/src/main/java/appeng/tile/misc/TileCondenser.java index 5754e6c3..ec379ec2 100644 --- a/src/main/java/appeng/tile/misc/TileCondenser.java +++ b/src/main/java/appeng/tile/misc/TileCondenser.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.AEApi; import appeng.api.config.CondenserOutput; import appeng.api.config.Settings; @@ -43,248 +42,221 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; +public class TileCondenser extends AEBaseInvTile + implements IFluidHandler, IConfigManagerHost, IConfigurableObject { + private static final FluidTankInfo[] EMPTY = { new FluidTankInfo(null, 10) }; + private final int[] sides = { 0, 1 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 3); + private final ConfigManager cm = new ConfigManager(this); -public class TileCondenser extends AEBaseInvTile implements IFluidHandler, IConfigManagerHost, IConfigurableObject -{ + private double storedPower = 0; - private static final FluidTankInfo[] EMPTY = { new FluidTankInfo( null, 10 ) }; - private final int[] sides = { 0, 1 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 3 ); - private final ConfigManager cm = new ConfigManager( this ); + public TileCondenser() { + this.cm.registerSetting(Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH); + } - private double storedPower = 0; + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCondenser(final NBTTagCompound data) { + this.cm.writeToNBT(data); + data.setDouble("storedPower", this.getStoredPower()); + } - public TileCondenser() - { - this.cm.registerSetting( Settings.CONDENSER_OUTPUT, CondenserOutput.TRASH ); - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCondenser(final NBTTagCompound data) { + this.cm.readFromNBT(data); + this.setStoredPower(data.getDouble("storedPower")); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCondenser( final NBTTagCompound data ) - { - this.cm.writeToNBT( data ); - data.setDouble( "storedPower", this.getStoredPower() ); - } + public double getStorage() { + final ItemStack is = this.inv.getStackInSlot(2); + if (is != null) { + if (is.getItem() instanceof IStorageComponent) { + final IStorageComponent sc = (IStorageComponent) is.getItem(); + if (sc.isStorageComponent(is)) { + return sc.getBytes(is) * 8; + } + } + } + return 0; + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCondenser( final NBTTagCompound data ) - { - this.cm.readFromNBT( data ); - this.setStoredPower( data.getDouble( "storedPower" ) ); - } + public void addPower(final double rawPower) { + this.setStoredPower(this.getStoredPower() + rawPower); + this.setStoredPower( + Math.max(0.0, Math.min(this.getStorage(), this.getStoredPower())) + ); - public double getStorage() - { - final ItemStack is = this.inv.getStackInSlot( 2 ); - if( is != null ) - { - if( is.getItem() instanceof IStorageComponent ) - { - final IStorageComponent sc = (IStorageComponent) is.getItem(); - if( sc.isStorageComponent( is ) ) - { - return sc.getBytes( is ) * 8; - } - } - } - return 0; - } + final double requiredPower = this.getRequiredPower(); + final ItemStack output = this.getOutput(); + while (requiredPower <= this.getStoredPower() && output != null + && requiredPower > 0) { + if (this.canAddOutput(output)) { + this.setStoredPower(this.getStoredPower() - requiredPower); + this.addOutput(output); + } else { + break; + } + } + } - public void addPower( final double rawPower ) - { - this.setStoredPower( this.getStoredPower() + rawPower ); - this.setStoredPower( Math.max( 0.0, Math.min( this.getStorage(), this.getStoredPower() ) ) ); + private boolean canAddOutput(final ItemStack output) { + final ItemStack outputStack = this.getStackInSlot(1); + return outputStack == null + || (Platform.isSameItem(outputStack, output) + && outputStack.stackSize < outputStack.getMaxStackSize()); + } - final double requiredPower = this.getRequiredPower(); - final ItemStack output = this.getOutput(); - while( requiredPower <= this.getStoredPower() && output != null && requiredPower > 0 ) - { - if( this.canAddOutput( output ) ) - { - this.setStoredPower( this.getStoredPower() - requiredPower ); - this.addOutput( output ); - } - else - { - break; - } - } - } + /** + * make sure you validate with canAddOutput prior to this. + * + * @param output to be added output + */ + private void addOutput(final ItemStack output) { + final ItemStack outputStack = this.getStackInSlot(1); + if (outputStack == null) { + this.setInventorySlotContents(1, output.copy()); + } else { + outputStack.stackSize++; + this.setInventorySlotContents(1, outputStack); + } + } - private boolean canAddOutput( final ItemStack output ) - { - final ItemStack outputStack = this.getStackInSlot( 1 ); - return outputStack == null || ( Platform.isSameItem( outputStack, output ) && outputStack.stackSize < outputStack.getMaxStackSize() ); - } + private ItemStack getOutput() { + final IMaterials materials = AEApi.instance().definitions().materials(); - /** - * make sure you validate with canAddOutput prior to this. - * - * @param output to be added output - */ - private void addOutput( final ItemStack output ) - { - final ItemStack outputStack = this.getStackInSlot( 1 ); - if( outputStack == null ) - { - this.setInventorySlotContents( 1, output.copy() ); - } - else - { - outputStack.stackSize++; - this.setInventorySlotContents( 1, outputStack ); - } - } + switch ((CondenserOutput) this.cm.getSetting(Settings.CONDENSER_OUTPUT)) { + case MATTER_BALLS: + for (final ItemStack matterBallStack : + materials.matterBall().maybeStack(1).asSet()) { + return matterBallStack; + } - private ItemStack getOutput() - { - final IMaterials materials = AEApi.instance().definitions().materials(); + case SINGULARITY: + for (final ItemStack singularityStack : + materials.singularity().maybeStack(1).asSet()) { + return singularityStack; + } - switch( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ) - { - case MATTER_BALLS: - for( final ItemStack matterBallStack : materials.matterBall().maybeStack( 1 ).asSet() ) - { - return matterBallStack; - } + case TRASH: + default: + } + return null; + } - case SINGULARITY: - for( final ItemStack singularityStack : materials.singularity().maybeStack( 1 ).asSet() ) - { - return singularityStack; - } + public double getRequiredPower() { + return ((CondenserOutput) this.cm.getSetting(Settings.CONDENSER_OUTPUT)) + .requiredPower; + } - case TRASH: - default: - } - return null; - } + @Override + public IInventory getInternalInventory() { + return this.inv; + } - public double getRequiredPower() - { - return ( (CondenserOutput) this.cm.getSetting( Settings.CONDENSER_OUTPUT ) ).requiredPower; - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + if (i == 0) { + if (itemstack != null) { + this.addPower(itemstack.stackSize); + } + } else { + this.inv.setInventorySlotContents(1, itemstack); + } + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return i == 0; + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - if( i == 0 ) - { - if( itemstack != null ) - { - this.addPower( itemstack.stackSize ); - } - } - else - { - this.inv.setInventorySlotContents( 1, itemstack ); - } - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + if (slot == 0) { + final ItemStack is = inv.getStackInSlot(0); + if (is != null) { + this.addPower(is.stackSize); + inv.setInventorySlotContents(0, null); + } + } + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return i == 0; - } + @Override + public boolean + canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + return slotIndex == 0; + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( slot == 0 ) - { - final ItemStack is = inv.getStackInSlot( 0 ); - if( is != null ) - { - this.addPower( is.stackSize ); - inv.setInventorySlotContents( 0, null ); - } - } - } + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex != 0; + } - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - return slotIndex == 0; - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex != 0; - } + @Override + public int + fill(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + if (doFill) { + this.addPower((resource == null ? 0.0 : (double) resource.amount) / 500.0); + } - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } + return resource == null ? 0 : resource.amount; + } - @Override - public int fill( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - if( doFill ) - { - this.addPower( ( resource == null ? 0.0 : (double) resource.amount ) / 500.0 ); - } + @Override + public FluidStack + drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + return null; + } - return resource == null ? 0 : resource.amount; - } + @Override + public FluidStack + drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + return null; + } - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - return null; - } + @Override + public boolean canFill(final ForgeDirection from, final Fluid fluid) { + return true; + } - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - return null; - } + @Override + public boolean canDrain(final ForgeDirection from, final Fluid fluid) { + return false; + } - @Override - public boolean canFill( final ForgeDirection from, final Fluid fluid ) - { - return true; - } + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + return EMPTY; + } - @Override - public boolean canDrain( final ForgeDirection from, final Fluid fluid ) - { - return false; - } + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + this.addPower(0); + } - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - return EMPTY; - } + @Override + public IConfigManager getConfigManager() { + return this.cm; + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.addPower( 0 ); - } + public double getStoredPower() { + return this.storedPower; + } - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } - - public double getStoredPower() - { - return this.storedPower; - } - - private void setStoredPower( final double storedPower ) - { - this.storedPower = storedPower; - } + private void setStoredPower(final double storedPower) { + this.storedPower = storedPower; + } } diff --git a/src/main/java/appeng/tile/misc/TileInscriber.java b/src/main/java/appeng/tile/misc/TileInscriber.java index 554ed8a5..a5a49ff1 100644 --- a/src/main/java/appeng/tile/misc/TileInscriber.java +++ b/src/main/java/appeng/tile/misc/TileInscriber.java @@ -18,6 +18,10 @@ package appeng.tile.misc; +import java.io.IOException; +import java.util.EnumSet; +import java.util.List; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -61,517 +65,471 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import javax.annotation.Nullable; -import java.io.IOException; -import java.util.EnumSet; -import java.util.List; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class TileInscriber extends AENetworkPowerTile implements IGridTickable, IUpgradeableHost, IConfigManagerHost -{ - - private final int maxProcessingTime = 100; - private final int[] top = { 0 }; - private final int[] bottom = { 1 }; - private final int[] sides = { 2, 3 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 4 ); - private final IConfigManager settings; - private final UpgradeInventory upgrades; - private int processingTime = 0; - // cycles from 0 - 16, at 8 it preforms the action, at 16 it re-enables the normal routine. - private boolean smash; - private int finalStep; - private long clientStart; - - @Reflected - public TileInscriber() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.setInternalMaxPower( 1500 ); - this.getProxy().setIdlePowerUsage( 0 ); - this.settings = new ConfigManager( this ); - - final ITileDefinition inscriberDefinition = AEApi.instance().definitions().blocks().inscriber(); - this.upgrades = new DefinitionUpgradeInventory( inscriberDefinition, this, this.getUpgradeSlots() ); - } - - private int getUpgradeSlots() - { - return 3; - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileInscriber( final NBTTagCompound data ) - { - this.inv.writeToNBT( data, "inscriberInv" ); - this.upgrades.writeToNBT( data, "upgrades" ); - this.settings.writeToNBT( data ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileInscriber( final NBTTagCompound data ) - { - this.inv.readFromNBT( data, "inscriberInv" ); - this.upgrades.readFromNBT( data, "upgrades" ); - this.settings.readFromNBT( data ); - } - - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileInscriber( final ByteBuf data ) throws IOException - { - final int slot = data.readByte(); - - final boolean oldSmash = this.isSmash(); - final boolean newSmash = ( slot & 64 ) == 64; - - if( oldSmash != newSmash && newSmash ) - { - this.setSmash( true ); - this.setClientStart( System.currentTimeMillis() ); - } - - for( int num = 0; num < this.inv.getSizeInventory(); num++ ) - { - if( ( slot & ( 1 << num ) ) > 0 ) - { - this.inv.setInventorySlotContents( num, AEItemStack.loadItemStackFromPacket( data ).getItemStack() ); - } - else - { - this.inv.setInventorySlotContents( num, null ); - } - } - - return false; - } - - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileInscriber( final ByteBuf data ) throws IOException - { - int slot = this.isSmash() ? 64 : 0; - - for( int num = 0; num < this.inv.getSizeInventory(); num++ ) - { - if( this.inv.getStackInSlot( num ) != null ) - { - slot |= ( 1 << num ); - } - } - - data.writeByte( slot ); - for( int num = 0; num < this.inv.getSizeInventory(); num++ ) - { - if( ( slot & ( 1 << num ) ) > 0 ) - { - final AEItemStack st = AEItemStack.create( this.inv.getStackInSlot( num ) ); - st.writeToPacket( data ); - } - } - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.getForward() ) ) ); - this.setPowerSides( EnumSet.complementOf( EnumSet.of( this.getForward() ) ) ); - } - - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - for( int h = 0; h < this.upgrades.getSizeInventory(); h++ ) - { - final ItemStack is = this.upgrades.getStackInSlot( h ); - if( is != null ) - { - drops.add( is ); - } - } - } - - @Override - public boolean requiresTESR() - { - return true; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public int getInventoryStackLimit() - { - return 1; - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( this.isSmash() ) - { - return false; - } - - if( i == 0 || i == 1 ) - { - if( AEApi.instance().definitions().materials().namePress().isSameAs( itemstack ) ) - { - return true; - } - - for( final ItemStack optionals : AEApi.instance().registries().inscriber().getOptionals() ) - { - if( Platform.isSameItemPrecise( optionals, itemstack ) ) - { - return true; - } - } - } - - return i == 2; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - try - { - if( mc != InvOperation.markDirty ) - { - if( slot != 3 ) - { - this.setProcessingTime( 0 ); - } - - if( !this.isSmash() ) - { - this.markForUpdate(); - } - - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - if( this.isSmash() ) - { - return false; - } - - return slotIndex == 0 || slotIndex == 1 || slotIndex == 3; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection d ) - { - if( d == ForgeDirection.UP ) - { - return this.top; - } - - if( d == ForgeDirection.DOWN ) - { - return this.bottom; - } - - return this.sides; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.Inscriber.getMin(), TickRates.Inscriber.getMax(), !this.hasWork(), false ); - } - - private boolean hasWork() - { - if( this.getTask() != null ) - { - return true; - } - - this.setProcessingTime( 0 ); - return this.isSmash(); - } - - @Nullable - public IInscriberRecipe getTask() - { - final ItemStack plateA = this.getStackInSlot( 0 ); - final ItemStack plateB = this.getStackInSlot( 1 ); - ItemStack renamedItem = this.getStackInSlot( 2 ); - - if( plateA != null && plateA.stackSize > 1 ) - { - return null; - } - - if( plateB != null && plateB.stackSize > 1 ) - { - return null; - } - - if( renamedItem != null && renamedItem.stackSize > 1 ) - { - return null; - } - - final IComparableDefinition namePress = AEApi.instance().definitions().materials().namePress(); - final boolean isNameA = namePress.isSameAs( plateA ); - final boolean isNameB = namePress.isSameAs( plateB ); - - if( ( isNameA || isNameB ) && ( isNameA || plateA == null ) && ( isNameB || plateB == null ) ) - { - if( renamedItem != null ) - { - String name = ""; - - if( plateA != null ) - { - final NBTTagCompound tag = Platform.openNbtData( plateA ); - name += tag.getString( "InscribeName" ); - } - - if( plateB != null ) - { - final NBTTagCompound tag = Platform.openNbtData( plateB ); - if( name.length() > 0 ) - { - name += " "; - } - name += tag.getString( "InscribeName" ); - } - - final ItemStack startingItem = renamedItem.copy(); - renamedItem = renamedItem.copy(); - final NBTTagCompound tag = Platform.openNbtData( renamedItem ); - - final NBTTagCompound display = tag.getCompoundTag( "display" ); - tag.setTag( "display", display ); - - if( name.length() > 0 ) - { - display.setString( "Name", name ); - } - else - { - display.removeTag( "Name" ); - } - - final List inputs = Lists.newArrayList( startingItem ); - final InscriberProcessType type = InscriberProcessType.Inscribe; - - return new InscriberRecipe( inputs, renamedItem, plateA, plateB, type ); - } - } - - for( final IInscriberRecipe recipe : AEApi.instance().registries().inscriber().getRecipes() ) - { - - final boolean matchA = ( plateA == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( plateA, recipe.getTopOptional().orNull() ) ) && // and... - ( plateB == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( plateB, recipe.getBottomOptional().orNull() ) ); - - final boolean matchB = ( plateB == null && !recipe.getTopOptional().isPresent() ) || ( Platform.isSameItemPrecise( plateB, recipe.getTopOptional().orNull() ) ) && // and... - ( plateA == null && !recipe.getBottomOptional().isPresent() ) | ( Platform.isSameItemPrecise( plateA, recipe.getBottomOptional().orNull() ) ); - - if( matchA || matchB ) - { - for( final ItemStack option : recipe.getInputs() ) - { - if( Platform.isSameItemPrecise( option, this.getStackInSlot( 2 ) ) ) - { - return recipe; - } - } - } - } - return null; - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.isSmash() ) - { - this.finalStep++; - if( this.finalStep == 8 ) - { - final IInscriberRecipe out = this.getTask(); - if( out != null ) - { - final ItemStack outputCopy = out.getOutput().copy(); - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this.inv, 3, 1, true ), ForgeDirection.UNKNOWN ); - - if( ad.addItems( outputCopy ) == null ) - { - this.setProcessingTime( 0 ); - if( out.getProcessType() == InscriberProcessType.Press ) - { - this.setInventorySlotContents( 0, null ); - this.setInventorySlotContents( 1, null ); - } - this.setInventorySlotContents( 2, null ); - } - } - - this.markDirty(); - } - else if( this.finalStep == 16 ) - { - this.finalStep = 0; - this.setSmash( false ); - this.markForUpdate(); - } - } - else - { - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - IEnergySource src = this; - - // Base 1, increase by 1 for each card - final int speedFactor = 1 + this.upgrades.getInstalledUpgrades( Upgrades.SPEED ); - final int powerConsumption = 10 * speedFactor; - final double powerThreshold = powerConsumption - 0.01; - double powerReq = this.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - if( powerReq <= powerThreshold ) - { - src = eg; - powerReq = eg.extractAEPower( powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - } - - if( powerReq > powerThreshold ) - { - src.extractAEPower( powerConsumption, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - if( this.getProcessingTime() == 0 ) - { - this.setProcessingTime( this.getProcessingTime() + speedFactor ); - } - else - { - this.setProcessingTime( this.getProcessingTime() + ticksSinceLastCall * speedFactor ); - } - } - } - catch( final GridAccessException e ) - { - // :P - } - - if( this.getProcessingTime() > this.getMaxProcessingTime() ) - { - this.setProcessingTime( this.getMaxProcessingTime() ); - final IInscriberRecipe out = this.getTask(); - if( out != null ) - { - final ItemStack outputCopy = out.getOutput().copy(); - final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( new WrapperInventoryRange( this.inv, 3, 1, true ), ForgeDirection.UNKNOWN ); - if( ad.simulateAdd( outputCopy ) == null ) - { - this.setSmash( true ); - this.finalStep = 0; - this.markForUpdate(); - } - } - } - } - - return this.hasWork() ? TickRateModulation.URGENT : TickRateModulation.SLEEP; - } - - @Override - public IConfigManager getConfigManager() - { - return this.settings; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "inv" ) ) - { - return this.inv; - } - - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - return null; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - } - - public long getClientStart() - { - return this.clientStart; - } - - private void setClientStart( final long clientStart ) - { - this.clientStart = clientStart; - } - - public boolean isSmash() - { - return this.smash; - } - - public void setSmash( final boolean smash ) - { - this.smash = smash; - } - - public int getMaxProcessingTime() - { - return this.maxProcessingTime; - } - - public int getProcessingTime() - { - return this.processingTime; - } - - private void setProcessingTime( final int processingTime ) - { - this.processingTime = processingTime; - } +public class TileInscriber extends AENetworkPowerTile + implements IGridTickable, IUpgradeableHost, IConfigManagerHost { + private final int maxProcessingTime = 100; + private final int[] top = { 0 }; + private final int[] bottom = { 1 }; + private final int[] sides = { 2, 3 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 4); + private final IConfigManager settings; + private final UpgradeInventory upgrades; + private int processingTime = 0; + // cycles from 0 - 16, at 8 it preforms the action, at 16 it re-enables the normal + // routine. + private boolean smash; + private int finalStep; + private long clientStart; + + @Reflected + public TileInscriber() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + this.setInternalMaxPower(1500); + this.getProxy().setIdlePowerUsage(0); + this.settings = new ConfigManager(this); + + final ITileDefinition inscriberDefinition + = AEApi.instance().definitions().blocks().inscriber(); + this.upgrades = new DefinitionUpgradeInventory( + inscriberDefinition, this, this.getUpgradeSlots() + ); + } + + private int getUpgradeSlots() { + return 3; + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileInscriber(final NBTTagCompound data) { + this.inv.writeToNBT(data, "inscriberInv"); + this.upgrades.writeToNBT(data, "upgrades"); + this.settings.writeToNBT(data); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileInscriber(final NBTTagCompound data) { + this.inv.readFromNBT(data, "inscriberInv"); + this.upgrades.readFromNBT(data, "upgrades"); + this.settings.readFromNBT(data); + } + + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileInscriber(final ByteBuf data) throws IOException { + final int slot = data.readByte(); + + final boolean oldSmash = this.isSmash(); + final boolean newSmash = (slot & 64) == 64; + + if (oldSmash != newSmash && newSmash) { + this.setSmash(true); + this.setClientStart(System.currentTimeMillis()); + } + + for (int num = 0; num < this.inv.getSizeInventory(); num++) { + if ((slot & (1 << num)) > 0) { + this.inv.setInventorySlotContents( + num, AEItemStack.loadItemStackFromPacket(data).getItemStack() + ); + } else { + this.inv.setInventorySlotContents(num, null); + } + } + + return false; + } + + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileInscriber(final ByteBuf data) throws IOException { + int slot = this.isSmash() ? 64 : 0; + + for (int num = 0; num < this.inv.getSizeInventory(); num++) { + if (this.inv.getStackInSlot(num) != null) { + slot |= (1 << num); + } + } + + data.writeByte(slot); + for (int num = 0; num < this.inv.getSizeInventory(); num++) { + if ((slot & (1 << num)) > 0) { + final AEItemStack st = AEItemStack.create(this.inv.getStackInSlot(num)); + st.writeToPacket(data); + } + } + } + + @Override + public void + setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.getForward())) + ); + this.setPowerSides(EnumSet.complementOf(EnumSet.of(this.getForward()))); + } + + @Override + public void getDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + super.getDrops(w, x, y, z, drops); + + for (int h = 0; h < this.upgrades.getSizeInventory(); h++) { + final ItemStack is = this.upgrades.getStackInSlot(h); + if (is != null) { + drops.add(is); + } + } + } + + @Override + public boolean requiresTESR() { + return true; + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (this.isSmash()) { + return false; + } + + if (i == 0 || i == 1) { + if (AEApi.instance().definitions().materials().namePress().isSameAs(itemstack + )) { + return true; + } + + for (final ItemStack optionals : + AEApi.instance().registries().inscriber().getOptionals()) { + if (Platform.isSameItemPrecise(optionals, itemstack)) { + return true; + } + } + } + + return i == 2; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + try { + if (mc != InvOperation.markDirty) { + if (slot != 3) { + this.setProcessingTime(0); + } + + if (!this.isSmash()) { + this.markForUpdate(); + } + + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + if (this.isSmash()) { + return false; + } + + return slotIndex == 0 || slotIndex == 1 || slotIndex == 3; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection d) { + if (d == ForgeDirection.UP) { + return this.top; + } + + if (d == ForgeDirection.DOWN) { + return this.bottom; + } + + return this.sides; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.Inscriber.getMin(), + TickRates.Inscriber.getMax(), + !this.hasWork(), + false + ); + } + + private boolean hasWork() { + if (this.getTask() != null) { + return true; + } + + this.setProcessingTime(0); + return this.isSmash(); + } + + @Nullable + public IInscriberRecipe getTask() { + final ItemStack plateA = this.getStackInSlot(0); + final ItemStack plateB = this.getStackInSlot(1); + ItemStack renamedItem = this.getStackInSlot(2); + + if (plateA != null && plateA.stackSize > 1) { + return null; + } + + if (plateB != null && plateB.stackSize > 1) { + return null; + } + + if (renamedItem != null && renamedItem.stackSize > 1) { + return null; + } + + final IComparableDefinition namePress + = AEApi.instance().definitions().materials().namePress(); + final boolean isNameA = namePress.isSameAs(plateA); + final boolean isNameB = namePress.isSameAs(plateB); + + if ((isNameA || isNameB) && (isNameA || plateA == null) + && (isNameB || plateB == null)) { + if (renamedItem != null) { + String name = ""; + + if (plateA != null) { + final NBTTagCompound tag = Platform.openNbtData(plateA); + name += tag.getString("InscribeName"); + } + + if (plateB != null) { + final NBTTagCompound tag = Platform.openNbtData(plateB); + if (name.length() > 0) { + name += " "; + } + name += tag.getString("InscribeName"); + } + + final ItemStack startingItem = renamedItem.copy(); + renamedItem = renamedItem.copy(); + final NBTTagCompound tag = Platform.openNbtData(renamedItem); + + final NBTTagCompound display = tag.getCompoundTag("display"); + tag.setTag("display", display); + + if (name.length() > 0) { + display.setString("Name", name); + } else { + display.removeTag("Name"); + } + + final List inputs = Lists.newArrayList(startingItem); + final InscriberProcessType type = InscriberProcessType.Inscribe; + + return new InscriberRecipe(inputs, renamedItem, plateA, plateB, type); + } + } + + for (final IInscriberRecipe recipe : + AEApi.instance().registries().inscriber().getRecipes()) { + final boolean matchA + = (plateA == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise(plateA, recipe.getTopOptional().orNull())) + && // and... + (plateB == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + plateB, recipe.getBottomOptional().orNull() + )); + + final boolean matchB + = (plateB == null && !recipe.getTopOptional().isPresent()) + || (Platform.isSameItemPrecise(plateB, recipe.getTopOptional().orNull())) + && // and... + (plateA == null && !recipe.getBottomOptional().isPresent()) + | (Platform.isSameItemPrecise( + plateA, recipe.getBottomOptional().orNull() + )); + + if (matchA || matchB) { + for (final ItemStack option : recipe.getInputs()) { + if (Platform.isSameItemPrecise(option, this.getStackInSlot(2))) { + return recipe; + } + } + } + } + return null; + } + + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.isSmash()) { + this.finalStep++; + if (this.finalStep == 8) { + final IInscriberRecipe out = this.getTask(); + if (out != null) { + final ItemStack outputCopy = out.getOutput().copy(); + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( + new WrapperInventoryRange(this.inv, 3, 1, true), + ForgeDirection.UNKNOWN + ); + + if (ad.addItems(outputCopy) == null) { + this.setProcessingTime(0); + if (out.getProcessType() == InscriberProcessType.Press) { + this.setInventorySlotContents(0, null); + this.setInventorySlotContents(1, null); + } + this.setInventorySlotContents(2, null); + } + } + + this.markDirty(); + } else if (this.finalStep == 16) { + this.finalStep = 0; + this.setSmash(false); + this.markForUpdate(); + } + } else { + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + IEnergySource src = this; + + // Base 1, increase by 1 for each card + final int speedFactor + = 1 + this.upgrades.getInstalledUpgrades(Upgrades.SPEED); + final int powerConsumption = 10 * speedFactor; + final double powerThreshold = powerConsumption - 0.01; + double powerReq = this.extractAEPower( + powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG + ); + + if (powerReq <= powerThreshold) { + src = eg; + powerReq = eg.extractAEPower( + powerConsumption, Actionable.SIMULATE, PowerMultiplier.CONFIG + ); + } + + if (powerReq > powerThreshold) { + src.extractAEPower( + powerConsumption, Actionable.MODULATE, PowerMultiplier.CONFIG + ); + + if (this.getProcessingTime() == 0) { + this.setProcessingTime(this.getProcessingTime() + speedFactor); + } else { + this.setProcessingTime( + this.getProcessingTime() + ticksSinceLastCall * speedFactor + ); + } + } + } catch (final GridAccessException e) { + // :P + } + + if (this.getProcessingTime() > this.getMaxProcessingTime()) { + this.setProcessingTime(this.getMaxProcessingTime()); + final IInscriberRecipe out = this.getTask(); + if (out != null) { + final ItemStack outputCopy = out.getOutput().copy(); + final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( + new WrapperInventoryRange(this.inv, 3, 1, true), + ForgeDirection.UNKNOWN + ); + if (ad.simulateAdd(outputCopy) == null) { + this.setSmash(true); + this.finalStep = 0; + this.markForUpdate(); + } + } + } + } + + return this.hasWork() ? TickRateModulation.URGENT : TickRateModulation.SLEEP; + } + + @Override + public IConfigManager getConfigManager() { + return this.settings; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("inv")) { + return this.inv; + } + + if (name.equals("upgrades")) { + return this.upgrades; + } + + return null; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) {} + + public long getClientStart() { + return this.clientStart; + } + + private void setClientStart(final long clientStart) { + this.clientStart = clientStart; + } + + public boolean isSmash() { + return this.smash; + } + + public void setSmash(final boolean smash) { + this.smash = smash; + } + + public int getMaxProcessingTime() { + return this.maxProcessingTime; + } + + public int getProcessingTime() { + return this.processingTime; + } + + private void setProcessingTime(final int processingTime) { + this.processingTime = processingTime; + } } diff --git a/src/main/java/appeng/tile/misc/TileInterface.java b/src/main/java/appeng/tile/misc/TileInterface.java index 60beff19..7d6cb1d3 100644 --- a/src/main/java/appeng/tile/misc/TileInterface.java +++ b/src/main/java/appeng/tile/misc/TileInterface.java @@ -18,6 +18,8 @@ package appeng.tile.misc; +import java.util.EnumSet; +import java.util.List; import appeng.api.config.Actionable; import appeng.api.config.Upgrades; @@ -58,268 +60,231 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.List; - - public class TileInterface extends AENetworkInvTile - implements IGridTickable, ITileStorageMonitorable, IStorageMonitorable, IInventoryDestination, IInterfaceHost, IPriorityHost -{ + implements IGridTickable, ITileStorageMonitorable, IStorageMonitorable, + IInventoryDestination, IInterfaceHost, IPriorityHost { + private final DualityInterface duality = new DualityInterface(this.getProxy(), this); + private ForgeDirection pointAt = ForgeDirection.UNKNOWN; - private final DualityInterface duality = new DualityInterface( this.getProxy(), this ); - private ForgeDirection pointAt = ForgeDirection.UNKNOWN; + @MENetworkEventSubscribe + public void stateChange(final MENetworkChannelsChanged c) { + this.duality.notifyNeighbors(); + } - @MENetworkEventSubscribe - public void stateChange( final MENetworkChannelsChanged c ) - { - this.duality.notifyNeighbors(); - } + @MENetworkEventSubscribe + public void stateChange(final MENetworkPowerStatusChange c) { + this.duality.notifyNeighbors(); + } - @MENetworkEventSubscribe - public void stateChange( final MENetworkPowerStatusChange c ) - { - this.duality.notifyNeighbors(); - } + public void setSide(final ForgeDirection axis) { + if (Platform.isClient()) { + return; + } - public void setSide( final ForgeDirection axis ) - { - if( Platform.isClient() ) - { - return; - } + if (this.pointAt == axis.getOpposite()) { + this.pointAt = axis; + } else if (this.pointAt == axis || this.pointAt == axis.getOpposite()) { + this.pointAt = ForgeDirection.UNKNOWN; + } else if (this.pointAt == ForgeDirection.UNKNOWN) { + this.pointAt = axis.getOpposite(); + } else { + this.pointAt = Platform.rotateAround(this.pointAt, axis); + } - if( this.pointAt == axis.getOpposite() ) - { - this.pointAt = axis; - } - else if( this.pointAt == axis || this.pointAt == axis.getOpposite() ) - { - 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) { + this.setOrientation(this.pointAt, this.pointAt); + } else { + this.setOrientation( + this.pointAt.offsetY != 0 ? ForgeDirection.SOUTH : ForgeDirection.UP, + this.pointAt.getOpposite() + ); + } - 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() ); - } + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.pointAt))); + this.markForUpdate(); + this.markDirty(); + } - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.pointAt ) ) ); - this.markForUpdate(); - this.markDirty(); - } + @Override + public void markDirty() { + this.duality.markDirty(); + } - @Override - public void markDirty() - { - this.duality.markDirty(); - } + @Override + public void getDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + this.duality.addDrops(drops); + } - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - this.duality.addDrops( drops ); - } + @Override + public void gridChanged() { + this.duality.gridChanged(); + } - @Override - public void gridChanged() - { - this.duality.gridChanged(); - } + @Override + public void onReady() { + this.getProxy().setValidSides(EnumSet.complementOf(EnumSet.of(this.pointAt))); + super.onReady(); + this.duality.initialize(); + } - @Override - public void onReady() - { - this.getProxy().setValidSides( EnumSet.complementOf( EnumSet.of( this.pointAt ) ) ); - super.onReady(); - this.duality.initialize(); - } + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileInterface(final NBTTagCompound data) { + data.setInteger("pointAt", this.pointAt.ordinal()); + this.duality.writeToNBT(data); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileInterface( final NBTTagCompound data ) - { - data.setInteger( "pointAt", this.pointAt.ordinal() ); - this.duality.writeToNBT( data ); - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileInterface(final NBTTagCompound data) { + final int val = data.getInteger("pointAt"); - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileInterface( final NBTTagCompound data ) - { - final int val = data.getInteger( "pointAt" ); + if (val >= 0 && val < ForgeDirection.values().length) { + this.pointAt = ForgeDirection.values()[val]; + } else { + this.pointAt = ForgeDirection.UNKNOWN; + } - if( val >= 0 && val < ForgeDirection.values().length ) - { - this.pointAt = ForgeDirection.values()[val]; - } - else - { - this.pointAt = ForgeDirection.UNKNOWN; - } + this.duality.readFromNBT(data); + } - this.duality.readFromNBT( data ); - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return this.duality.getCableConnectionType(dir); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return this.duality.getCableConnectionType( dir ); - } + @Override + public DimensionalCoord getLocation() { + return this.duality.getLocation(); + } - @Override - public DimensionalCoord getLocation() - { - return this.duality.getLocation(); - } + @Override + public boolean canInsert(final ItemStack stack) { + return this.duality.canInsert(stack); + } - @Override - public boolean canInsert( final ItemStack stack ) - { - return this.duality.canInsert( stack ); - } + @Override + public IMEMonitor getItemInventory() { + return this.duality.getItemInventory(); + } - @Override - public IMEMonitor getItemInventory() - { - return this.duality.getItemInventory(); - } + @Override + public IMEMonitor getFluidInventory() { + return this.duality.getFluidInventory(); + } - @Override - public IMEMonitor getFluidInventory() - { - return this.duality.getFluidInventory(); - } + @Override + public IInventory getInventoryByName(final String name) { + return this.duality.getInventoryByName(name); + } - @Override - public IInventory getInventoryByName( final String name ) - { - return this.duality.getInventoryByName( name ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return this.duality.getTickingRequest(node); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return this.duality.getTickingRequest( node ); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + return this.duality.tickingRequest(node, ticksSinceLastCall); + } - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - return this.duality.tickingRequest( node, ticksSinceLastCall ); - } + @Override + public IInventory getInternalInventory() { + return this.duality.getInternalInventory(); + } - @Override - public IInventory getInternalInventory() - { - return this.duality.getInternalInventory(); - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + this.duality.onChangeInventory(inv, slot, mc, removed, added); + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - this.duality.onChangeInventory( inv, slot, mc, removed, added ); - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.duality.getAccessibleSlotsFromSide(side.ordinal()); + } - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.duality.getAccessibleSlotsFromSide( side.ordinal() ); - } + @Override + public DualityInterface getInterfaceDuality() { + return this.duality; + } - @Override - public DualityInterface getInterfaceDuality() - { - return this.duality; - } + @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 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 TileEntity getTileEntity() - { - return this; - } + @Override + public IStorageMonitorable + getMonitorable(final ForgeDirection side, final BaseActionSource src) { + return this.duality.getMonitorable(side, src, this); + } - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - return this.duality.getMonitorable( side, src, this ); - } + @Override + public IConfigManager getConfigManager() { + return this.duality.getConfigManager(); + } - @Override - public IConfigManager getConfigManager() - { - return this.duality.getConfigManager(); - } + @Override + public boolean pushPattern( + final ICraftingPatternDetails patternDetails, final InventoryCrafting table + ) { + return this.duality.pushPattern(patternDetails, table); + } - @Override - public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) - { - return this.duality.pushPattern( patternDetails, table ); - } + @Override + public boolean isBusy() { + return this.duality.isBusy(); + } - @Override - public boolean isBusy() - { - return this.duality.isBusy(); - } + @Override + public void provideCrafting(final ICraftingProviderHelper craftingTracker) { + this.duality.provideCrafting(craftingTracker); + } - @Override - public void provideCrafting( final ICraftingProviderHelper craftingTracker ) - { - this.duality.provideCrafting( craftingTracker ); - } + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.duality.getInstalledUpgrades(u); + } - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.duality.getInstalledUpgrades( u ); - } + @Override + public ImmutableSet getRequestedJobs() { + return this.duality.getRequestedJobs(); + } - @Override - public ImmutableSet getRequestedJobs() - { - return this.duality.getRequestedJobs(); - } + @Override + public IAEItemStack injectCraftedItems( + final ICraftingLink link, final IAEItemStack items, final Actionable mode + ) { + return this.duality.injectCraftedItems(link, items, mode); + } - @Override - public IAEItemStack injectCraftedItems( final ICraftingLink link, final IAEItemStack items, final Actionable mode ) - { - return this.duality.injectCraftedItems( link, items, mode ); - } + @Override + public void jobStateChange(final ICraftingLink link) { + this.duality.jobStateChange(link); + } - @Override - public void jobStateChange( final ICraftingLink link ) - { - this.duality.jobStateChange( link ); - } + @Override + public int getPriority() { + return this.duality.getPriority(); + } - @Override - public int getPriority() - { - return this.duality.getPriority(); - } - - @Override - public void setPriority( final int newValue ) - { - this.duality.setPriority( newValue ); - } + @Override + public void setPriority(final 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 1f6764ff..10afeea8 100644 --- a/src/main/java/appeng/tile/misc/TileLightDetector.java +++ b/src/main/java/appeng/tile/misc/TileLightDetector.java @@ -18,49 +18,42 @@ 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 { + private int lastCheck = 30; + private int lastLight = 0; -public class TileLightDetector extends AEBaseTile -{ + public boolean isReady() { + return this.lastLight > 0; + } - private int lastCheck = 30; - private int lastLight = 0; + @TileEvent(TileEventType.TICK) + public void Tick_TileLightDetector() { + this.lastCheck++; + if (this.lastCheck > 30) { + this.lastCheck = 0; + this.updateLight(); + } + } - public boolean isReady() - { - return this.lastLight > 0; - } + public void updateLight() { + final int val + = this.worldObj.getBlockLightValue(this.xCoord, this.yCoord, this.zCoord); - @TileEvent( TileEventType.TICK ) - public void Tick_TileLightDetector() - { - this.lastCheck++; - if( this.lastCheck > 30 ) - { - this.lastCheck = 0; - this.updateLight(); - } - } + if (this.lastLight != val) { + this.lastLight = val; + Platform.notifyBlocksOfNeighbors( + this.worldObj, this.xCoord, this.yCoord, this.zCoord + ); + } + } - public void updateLight() - { - final int val = this.worldObj.getBlockLightValue( this.xCoord, this.yCoord, this.zCoord ); - - if( this.lastLight != val ) - { - this.lastLight = val; - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - } - - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public boolean canBeRotated() { + return false; + } } diff --git a/src/main/java/appeng/tile/misc/TilePaint.java b/src/main/java/appeng/tile/misc/TilePaint.java index e6fe87e8..046e24a2 100644 --- a/src/main/java/appeng/tile/misc/TilePaint.java +++ b/src/main/java/appeng/tile/misc/TilePaint.java @@ -18,6 +18,10 @@ package appeng.tile.misc; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; import appeng.api.util.AEColor; import appeng.helpers.Splotch; @@ -36,231 +40,206 @@ import net.minecraft.util.Vec3; import net.minecraft.world.EnumSkyBlock; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; +public class TilePaint extends AEBaseTile { + private static final int LIGHT_PER_DOT = 12; + private int isLit = 0; + private List dots = null; -public class TilePaint extends AEBaseTile -{ + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TilePaint(final NBTTagCompound data) { + final ByteBuf myDat = Unpooled.buffer(); + this.writeBuffer(myDat); + if (myDat.hasArray()) { + data.setByteArray("dots", myDat.array()); + } + } - private static final int LIGHT_PER_DOT = 12; + private void writeBuffer(final ByteBuf out) { + if (this.dots == null) { + out.writeByte(0); + return; + } - private int isLit = 0; - private List dots = null; + out.writeByte(this.dots.size()); - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TilePaint( final NBTTagCompound data ) - { - final ByteBuf myDat = Unpooled.buffer(); - this.writeBuffer( myDat ); - if( myDat.hasArray() ) - { - data.setByteArray( "dots", myDat.array() ); - } - } + for (final Splotch s : this.dots) { + s.writeToStream(out); + } + } - private void writeBuffer( final ByteBuf out ) - { - if( this.dots == null ) - { - out.writeByte( 0 ); - return; - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TilePaint(final NBTTagCompound data) { + if (data.hasKey("dots")) { + this.readBuffer(Unpooled.copiedBuffer(data.getByteArray("dots"))); + } + } - out.writeByte( this.dots.size() ); + private void readBuffer(final ByteBuf in) { + final byte howMany = in.readByte(); - for( final Splotch s : this.dots ) - { - s.writeToStream( out ); - } - } + if (howMany == 0) { + this.isLit = 0; + this.dots = null; + return; + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TilePaint( final NBTTagCompound data ) - { - if( data.hasKey( "dots" ) ) - { - this.readBuffer( Unpooled.copiedBuffer( data.getByteArray( "dots" ) ) ); - } - } + this.dots = new ArrayList(howMany); + for (int x = 0; x < howMany; x++) { + this.dots.add(new Splotch(in)); + } - private void readBuffer( final ByteBuf in ) - { - final byte howMany = in.readByte(); + this.isLit = 0; + for (final Splotch s : this.dots) { + if (s.isLumen()) { + this.isLit += LIGHT_PER_DOT; + } + } - if( howMany == 0 ) - { - this.isLit = 0; - this.dots = null; - return; - } + this.maxLit(); + } - this.dots = new ArrayList( howMany ); - for( int x = 0; x < howMany; x++ ) - { - this.dots.add( new Splotch( in ) ); - } + private void maxLit() { + if (this.isLit > 14) { + this.isLit = 14; + } - this.isLit = 0; - for( final Splotch s : this.dots ) - { - if( s.isLumen() ) - { - this.isLit += LIGHT_PER_DOT; - } - } + if (this.worldObj != null) { + this.worldObj.updateLightByType( + EnumSkyBlock.Block, this.xCoord, this.yCoord, this.zCoord + ); + } + } - this.maxLit(); - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TilePaint(final ByteBuf data) { + this.writeBuffer(data); + } - private void maxLit() - { - if( this.isLit > 14 ) - { - this.isLit = 14; - } + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TilePaint(final ByteBuf data) { + this.readBuffer(data); + return true; + } - if( this.worldObj != null ) - { - this.worldObj.updateLightByType( EnumSkyBlock.Block, this.xCoord, this.yCoord, this.zCoord ); - } - } + public void onNeighborBlockChange() { + if (this.dots == null) { + return; + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TilePaint( final ByteBuf data ) - { - this.writeBuffer( data ); - } + for (final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + if (!this.isSideValid(side)) { + this.removeSide(side); + } + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TilePaint( final ByteBuf data ) - { - this.readBuffer( data ); - return true; - } + this.updateData(); + } - public void onNeighborBlockChange() - { - if( this.dots == null ) - { - return; - } + public boolean isSideValid(final ForgeDirection side) { + final 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() + ); + } - for( final ForgeDirection side : ForgeDirection.VALID_DIRECTIONS ) - { - if( !this.isSideValid( side ) ) - { - this.removeSide( side ); - } - } + private void removeSide(final ForgeDirection side) { + final Iterator i = this.dots.iterator(); + while (i.hasNext()) { + final Splotch s = i.next(); + if (s.getSide() == side) { + i.remove(); + } + } - this.updateData(); - } + this.markForUpdate(); + this.markDirty(); + } - public boolean isSideValid( final ForgeDirection side ) - { - final 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 updateData() { + this.isLit = 0; + for (final Splotch s : this.dots) { + if (s.isLumen()) { + this.isLit += LIGHT_PER_DOT; + } + } - private void removeSide( final ForgeDirection side ) - { - final Iterator i = this.dots.iterator(); - while( i.hasNext() ) - { - final Splotch s = i.next(); - if( s.getSide() == side ) - { - i.remove(); - } - } + this.maxLit(); - this.markForUpdate(); - this.markDirty(); - } + if (this.dots.isEmpty()) { + this.dots = null; + } - private void updateData() - { - this.isLit = 0; - for( final Splotch s : this.dots ) - { - if( s.isLumen() ) - { - this.isLit += LIGHT_PER_DOT; - } - } + if (this.dots == null) { + this.worldObj.setBlock(this.xCoord, this.yCoord, this.zCoord, Blocks.air); + } + } - this.maxLit(); + public void cleanSide(final ForgeDirection side) { + if (this.dots == null) { + return; + } - if( this.dots.isEmpty() ) - { - this.dots = null; - } + this.removeSide(side); - if( this.dots == null ) - { - this.worldObj.setBlock( this.xCoord, this.yCoord, this.zCoord, Blocks.air ); - } - } + this.updateData(); + } - public void cleanSide( final ForgeDirection side ) - { - if( this.dots == null ) - { - return; - } + public int getLightLevel() { + return this.isLit; + } - this.removeSide( side ); + public void + addBlot(final ItemStack type, final ForgeDirection side, final Vec3 hitVec) { + final 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() + )) { + final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); - this.updateData(); - } + final AEColor col = ipb.getColor(type); + final boolean lit = ipb.isLumen(type); - public int getLightLevel() - { - return this.isLit; - } + if (this.dots == null) { + this.dots = new ArrayList(); + } - public void addBlot( final ItemStack type, final ForgeDirection side, final Vec3 hitVec ) - { - final 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() ) ) - { - final ItemPaintBall ipb = (ItemPaintBall) type.getItem(); + if (this.dots.size() > 20) { + this.dots.remove(0); + } - final AEColor col = ipb.getColor( type ); - final boolean lit = ipb.isLumen( type ); + this.dots.add(new Splotch(col, lit, side, hitVec)); + if (lit) { + this.isLit += LIGHT_PER_DOT; + } - if( this.dots == null ) - { - this.dots = new ArrayList(); - } + this.maxLit(); + this.markForUpdate(); + this.markDirty(); + } + } - if( this.dots.size() > 20 ) - { - this.dots.remove( 0 ); - } + public Collection getDots() { + if (this.dots == null) { + return ImmutableList.of(); + } - this.dots.add( new Splotch( col, lit, side, hitVec ) ); - if( lit ) - { - this.isLit += LIGHT_PER_DOT; - } - - this.maxLit(); - this.markForUpdate(); - this.markDirty(); - } - } - - public Collection getDots() - { - if( this.dots == null ) - { - return ImmutableList.of(); - } - - return this.dots; - } + return this.dots; + } } diff --git a/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java b/src/main/java/appeng/tile/misc/TileQuartzGrowthAccelerator.java index 9ba0726f..59ace5e4 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 appeng.api.implementations.IPowerChannelState; import appeng.api.implementations.tiles.ICrystalGrowthAccelerator; @@ -32,87 +33,69 @@ import appeng.util.Platform; import io.netty.buffer.ByteBuf; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class TileQuartzGrowthAccelerator + extends AENetworkTile implements IPowerChannelState, ICrystalGrowthAccelerator { + private boolean hasPower = false; + public TileQuartzGrowthAccelerator() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + this.getProxy().setFlags(); + this.getProxy().setIdlePowerUsage(8); + } -public class TileQuartzGrowthAccelerator extends AENetworkTile implements IPowerChannelState, ICrystalGrowthAccelerator -{ + @MENetworkEventSubscribe + public void onPower(final MENetworkPowerStatusChange ch) { + this.markForUpdate(); + } - private boolean hasPower = false; + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - public TileQuartzGrowthAccelerator() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.getProxy().setFlags(); - this.getProxy().setIdlePowerUsage( 8 ); - } + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileQuartzGrowthAccelerator(final ByteBuf data) { + final boolean hadPower = this.isPowered(); + this.setPowered(data.readBoolean()); + return this.isPowered() != hadPower; + } - @MENetworkEventSubscribe - public void onPower( final MENetworkPowerStatusChange ch ) - { - this.markForUpdate(); - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileQuartzGrowthAccelerator(final ByteBuf data) { + try { + data.writeBoolean(this.getProxy().getEnergy().isNetworkPowered()); + } catch (final GridAccessException e) { + data.writeBoolean(false); + } + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + @Override + public void + setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + this.getProxy().setValidSides(EnumSet.of(this.getUp(), this.getUp().getOpposite()) + ); + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileQuartzGrowthAccelerator( final ByteBuf data ) - { - final boolean hadPower = this.isPowered(); - this.setPowered( data.readBoolean() ); - return this.isPowered() != hadPower; - } + @Override + public boolean isPowered() { + if (Platform.isServer()) { + try { + return this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + return false; + } + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileQuartzGrowthAccelerator( final ByteBuf data ) - { - try - { - data.writeBoolean( this.getProxy().getEnergy().isNetworkPowered() ); - } - catch( final GridAccessException e ) - { - data.writeBoolean( false ); - } - } + return this.hasPower; + } - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - this.getProxy().setValidSides( EnumSet.of( this.getUp(), this.getUp().getOpposite() ) ); - } + @Override + public boolean isActive() { + return this.isPowered(); + } - @Override - public boolean isPowered() - { - if( Platform.isServer() ) - { - try - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - return false; - } - } - - return this.hasPower; - } - - @Override - public boolean isActive() - { - return this.isPowered(); - } - - private void setPowered( final boolean hasPower ) - { - this.hasPower = hasPower; - } + private void setPowered(final boolean hasPower) { + this.hasPower = hasPower; + } } diff --git a/src/main/java/appeng/tile/misc/TileSecurity.java b/src/main/java/appeng/tile/misc/TileSecurity.java index 7c38f210..1c70712d 100644 --- a/src/main/java/appeng/tile/misc/TileSecurity.java +++ b/src/main/java/appeng/tile/misc/TileSecurity.java @@ -18,6 +18,9 @@ package appeng.tile.misc; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.*; @@ -67,295 +70,268 @@ import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.List; +public class TileSecurity extends AENetworkTile + implements ITerminalHost, IAEAppEngInventory, ILocatable, IConfigManagerHost, + ISecurityProvider, IColorableTile { + private static int difference = 0; + private 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); + private long securityKey; + private AEColor paintedColor = AEColor.Transparent; + private boolean isActive = false; + public TileSecurity() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(2.0); + difference++; -public class TileSecurity extends AENetworkTile implements ITerminalHost, IAEAppEngInventory, ILocatable, IConfigManagerHost, ISecurityProvider, IColorableTile -{ + this.securityKey = System.currentTimeMillis() * 10 + difference; + if (difference > 10) { + difference = 0; + } - private static int difference = 0; - private 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 ); - private long securityKey; - private AEColor paintedColor = AEColor.Transparent; - private boolean isActive = false; + this.cm.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.cm.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.cm.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + } - public TileSecurity() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setIdlePowerUsage( 2.0 ); - difference++; + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removedStack, + final ItemStack newStack + ) {} - this.securityKey = System.currentTimeMillis() * 10 + difference; - if( difference > 10 ) - { - difference = 0; - } + @Override + public void getDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + if (!this.getConfigSlot().isEmpty()) { + drops.add(this.getConfigSlot().getStackInSlot(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 ); - } + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + drops.add(ais.getItemStack()); + } + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removedStack, final ItemStack newStack ) - { + IMEInventoryHandler getSecurityInventory() { + return this.inventory; + } - } + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileSecurity(final ByteBuf data) { + final boolean wasActive = this.isActive; + this.isActive = data.readBoolean(); - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - if( !this.getConfigSlot().isEmpty() ) - { - drops.add( this.getConfigSlot().getStackInSlot( 0 ) ); - } + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - drops.add( ais.getItemStack() ); - } - } + return oldPaintedColor != this.paintedColor || wasActive != this.isActive; + } - IMEInventoryHandler getSecurityInventory() - { - return this.inventory; - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileSecurity(final ByteBuf data) { + data.writeBoolean(this.getProxy().isActive()); + data.writeByte(this.paintedColor.ordinal()); + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileSecurity( final ByteBuf data ) - { - final boolean wasActive = this.isActive; - this.isActive = data.readBoolean(); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileSecurity(final NBTTagCompound data) { + this.cm.writeToNBT(data); + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; + data.setLong("securityKey", this.securityKey); + this.getConfigSlot().writeToNBT(data, "config"); - return oldPaintedColor != this.paintedColor || wasActive != this.isActive; - } + final NBTTagCompound storedItems = new NBTTagCompound(); - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileSecurity( final ByteBuf data ) - { - data.writeBoolean( this.getProxy().isActive() ); - data.writeByte( this.paintedColor.ordinal() ); - } + int offset = 0; + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + final NBTTagCompound it = new NBTTagCompound(); + ais.getItemStack().writeToNBT(it); + storedItems.setTag(String.valueOf(offset), it); + offset++; + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileSecurity( final NBTTagCompound data ) - { - this.cm.writeToNBT( data ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); + data.setTag("storedItems", storedItems); + } - data.setLong( "securityKey", this.securityKey ); - this.getConfigSlot().writeToNBT( data, "config" ); + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileSecurity(final NBTTagCompound data) { + this.cm.readFromNBT(data); + if (data.hasKey("paintedColor")) { + this.paintedColor = AEColor.values()[data.getByte("paintedColor")]; + } - final NBTTagCompound storedItems = new NBTTagCompound(); + this.securityKey = data.getLong("securityKey"); + this.getConfigSlot().readFromNBT(data, "config"); - int offset = 0; - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - final NBTTagCompound it = new NBTTagCompound(); - ais.getItemStack().writeToNBT( it ); - storedItems.setTag( String.valueOf( offset ), it ); - offset++; - } + final NBTTagCompound storedItems = data.getCompoundTag("storedItems"); + for (final Object key : storedItems.func_150296_c()) { + final NBTBase obj = storedItems.getTag((String) key); + if (obj instanceof NBTTagCompound) { + this.inventory.getStoredItems().add(AEItemStack.create( + ItemStack.loadItemStackFromNBT((NBTTagCompound) obj) + )); + } + } + } - data.setTag( "storedItems", storedItems ); - } + public void inventoryChanged() { + try { + this.saveChanges(); + this.getProxy().getGrid().postEvent(new MENetworkSecurityChange()); + } catch (final GridAccessException e) { + // :P + } + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileSecurity( final NBTTagCompound data ) - { - this.cm.readFromNBT( data ); - if( data.hasKey( "paintedColor" ) ) - { - this.paintedColor = AEColor.values()[data.getByte( "paintedColor" )]; - } + @MENetworkEventSubscribe + public void bootUpdate(final MENetworkChannelsChanged changed) { + this.markForUpdate(); + } - this.securityKey = data.getLong( "securityKey" ); - this.getConfigSlot().readFromNBT( data, "config" ); + @MENetworkEventSubscribe + public void powerUpdate(final MENetworkPowerStatusChange changed) { + this.markForUpdate(); + } - final NBTTagCompound storedItems = data.getCompoundTag( "storedItems" ); - for( final Object key : storedItems.func_150296_c() ) - { - final NBTBase obj = storedItems.getTag( (String) key ); - if( obj instanceof NBTTagCompound ) - { - this.inventory.getStoredItems().add( AEItemStack.create( ItemStack.loadItemStackFromNBT( (NBTTagCompound) obj ) ) ); - } - } - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } - public void inventoryChanged() - { - try - { - this.saveChanges(); - this.getProxy().getGrid().postEvent( new MENetworkSecurityChange() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + MinecraftForge.EVENT_BUS.post( + new LocatableEventAnnounce(this, LocatableEvent.Unregister) + ); + this.isActive = false; + } - @MENetworkEventSubscribe - public void bootUpdate( final MENetworkChannelsChanged changed ) - { - this.markForUpdate(); - } + @Override + public void onReady() { + super.onReady(); + if (Platform.isServer()) { + this.isActive = true; + MinecraftForge.EVENT_BUS.post( + new LocatableEventAnnounce(this, LocatableEvent.Register) + ); + } + } - @MENetworkEventSubscribe - public void powerUpdate( final MENetworkPowerStatusChange changed ) - { - this.markForUpdate(); - } + @Override + public void invalidate() { + super.invalidate(); + MinecraftForge.EVENT_BUS.post( + new LocatableEventAnnounce(this, LocatableEvent.Unregister) + ); + this.isActive = false; + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - this.isActive = false; - } + public boolean isActive() { + return this.isActive; + } - @Override - public void onReady() - { - super.onReady(); - if( Platform.isServer() ) - { - this.isActive = true; - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Register ) ); - } - } + @Override + public IMEMonitor getItemInventory() { + return this.securityMonitor; + } - @Override - public void invalidate() - { - super.invalidate(); - MinecraftForge.EVENT_BUS.post( new LocatableEventAnnounce( this, LocatableEvent.Unregister ) ); - this.isActive = false; - } + @Override + public IMEMonitor getFluidInventory() { + return null; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public long getLocatableSerial() { + return this.securityKey; + } - public boolean isActive() - { - return this.isActive; - } + public boolean isPowered() { + return this.getProxy().isActive(); + } - @Override - public IMEMonitor getItemInventory() - { - return this.securityMonitor; - } + @Override + public IConfigManager getConfigManager() { + return this.cm; + } - @Override - public IMEMonitor getFluidInventory() - { - return null; - } + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) {} - @Override - public long getLocatableSerial() - { - return this.securityKey; - } + @Override + public long getSecurityKey() { + return this.securityKey; + } - public boolean isPowered() - { - return this.getProxy().isActive(); - } + @Override + public void + readPermissions(final HashMap> playerPerms) { + final IPlayerRegistry pr = AEApi.instance().registries().players(); - @Override - public IConfigManager getConfigManager() - { - return this.cm; - } + // read permissions + for (final IAEItemStack ais : this.inventory.getStoredItems()) { + final ItemStack is = ais.getItemStack(); + final Item i = is.getItem(); + if (i instanceof IBiometricCard) { + final IBiometricCard bc = (IBiometricCard) i; + bc.registerPermissions(new PlayerSecurityWrapper(playerPerms), pr, is); + } + } - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { + // make sure thea admin is Boss. + playerPerms.put( + this.getProxy().getNode().getPlayerID(), + EnumSet.allOf(SecurityPermissions.class) + ); + } - } + @Override + public boolean isSecurityEnabled() { + return this.isActive && this.getProxy().isActive(); + } - @Override - public long getSecurityKey() - { - return this.securityKey; - } + @Override + public int getOwner() { + return this.getProxy().getNode().getPlayerID(); + } - @Override - public void readPermissions( final HashMap> playerPerms ) - { - final IPlayerRegistry pr = AEApi.instance().registries().players(); + @Override + public AEColor getColor() { + return this.paintedColor; + } - // read permissions - for( final IAEItemStack ais : this.inventory.getStoredItems() ) - { - final ItemStack is = ais.getItemStack(); - final Item i = is.getItem(); - if( i instanceof IBiometricCard ) - { - final IBiometricCard bc = (IBiometricCard) i; - bc.registerPermissions( new PlayerSecurityWrapper( playerPerms ), pr, is ); - } - } + @Override + public boolean recolourBlock( + final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who + ) { + if (this.paintedColor == newPaintedColor) { + return false; + } - // make sure thea admin is Boss. - playerPerms.put( this.getProxy().getNode().getPlayerID(), EnumSet.allOf( SecurityPermissions.class ) ); - } + this.paintedColor = newPaintedColor; + this.markDirty(); + this.markForUpdate(); + return true; + } - @Override - public boolean isSecurityEnabled() - { - return this.isActive && this.getProxy().isActive(); - } - - @Override - public int getOwner() - { - return this.getProxy().getNode().getPlayerID(); - } - - @Override - public AEColor getColor() - { - return this.paintedColor; - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } - - this.paintedColor = newPaintedColor; - this.markDirty(); - this.markForUpdate(); - return true; - } - - public AppEngInternalInventory getConfigSlot() - { - return this.configSlot; - } + public AppEngInternalInventory getConfigSlot() { + return this.configSlot; + } } diff --git a/src/main/java/appeng/tile/misc/TileSkyCompass.java b/src/main/java/appeng/tile/misc/TileSkyCompass.java index 7937029b..61cd7fd0 100644 --- a/src/main/java/appeng/tile/misc/TileSkyCompass.java +++ b/src/main/java/appeng/tile/misc/TileSkyCompass.java @@ -18,16 +18,11 @@ package appeng.tile.misc; - import appeng.tile.AEBaseTile; - -public class TileSkyCompass extends AEBaseTile -{ - - @Override - public boolean requiresTESR() - { - return true; - } +public class TileSkyCompass extends AEBaseTile { + @Override + public boolean requiresTESR() { + return true; + } } diff --git a/src/main/java/appeng/tile/misc/TileVibrationChamber.java b/src/main/java/appeng/tile/misc/TileVibrationChamber.java index 60ff2e3b..d94ba715 100644 --- a/src/main/java/appeng/tile/misc/TileVibrationChamber.java +++ b/src/main/java/appeng/tile/misc/TileVibrationChamber.java @@ -18,7 +18,6 @@ package appeng.tile.misc; - import appeng.api.config.Actionable; import appeng.api.networking.IGridNode; import appeng.api.networking.energy.IEnergyGrid; @@ -44,283 +43,252 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraftforge.common.util.ForgeDirection; +public class TileVibrationChamber extends AENetworkInvTile implements IGridTickable { + private static final int FUEL_SLOT_INDEX = 0; + private static final double POWER_PER_TICK = 5; + private static final int[] ACCESSIBLE_SLOTS = { FUEL_SLOT_INDEX }; + private static final int MAX_BURN_SPEED = 200; + private static final double DILATION_SCALING = 100.0; + private static final int MIN_BURN_SPEED = 20; + private final IInventory inv = new AppEngInternalInventory(this, 1); -public class TileVibrationChamber extends AENetworkInvTile implements IGridTickable -{ - private static final int FUEL_SLOT_INDEX = 0; - private static final double POWER_PER_TICK = 5; - private static final int[] ACCESSIBLE_SLOTS = { FUEL_SLOT_INDEX }; - private static final int MAX_BURN_SPEED = 200; - private static final double DILATION_SCALING = 100.0; - private static final int MIN_BURN_SPEED = 20; - private final IInventory inv = new AppEngInternalInventory( this, 1 ); + private int burnSpeed = 100; + private double burnTime = 0; + private double maxBurnTime = 0; - private int burnSpeed = 100; - private double burnTime = 0; - private double maxBurnTime = 0; + // client side.. + public boolean isOn; - // client side.. - public boolean isOn; + public TileVibrationChamber() { + this.getProxy().setIdlePowerUsage(0); + this.getProxy().setFlags(); + } - public TileVibrationChamber() - { - this.getProxy().setIdlePowerUsage( 0 ); - this.getProxy().setFlags(); - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + @Reflected + @TileEvent(TileEventType.NETWORK_READ) + public boolean hasUpdate(final ByteBuf data) { + final boolean wasOn = this.isOn; - @Reflected - @TileEvent( TileEventType.NETWORK_READ ) - public boolean hasUpdate( final ByteBuf data ) - { - final boolean wasOn = this.isOn; + this.isOn = data.readBoolean(); - this.isOn = data.readBoolean(); + return wasOn != this.isOn; // TESR doesn't need updates! + } - return wasOn != this.isOn; // TESR doesn't need updates! - } + @Reflected + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToNetwork(final ByteBuf data) { + data.writeBoolean(this.getBurnTime() > 0); + } - @Reflected - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToNetwork( final ByteBuf data ) - { - data.writeBoolean( this.getBurnTime() > 0 ); - } + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileVibrationChamber(final NBTTagCompound data) { + data.setDouble("burnTime", this.getBurnTime()); + data.setDouble("maxBurnTime", this.getMaxBurnTime()); + data.setInteger("burnSpeed", this.getBurnSpeed()); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileVibrationChamber( final NBTTagCompound data ) - { - data.setDouble( "burnTime", this.getBurnTime() ); - data.setDouble( "maxBurnTime", this.getMaxBurnTime() ); - data.setInteger( "burnSpeed", this.getBurnSpeed() ); - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileVibrationChamber(final NBTTagCompound data) { + this.setBurnTime(data.getDouble("burnTime")); + this.setMaxBurnTime(data.getDouble("maxBurnTime")); + this.setBurnSpeed(data.getInteger("burnSpeed")); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileVibrationChamber( final NBTTagCompound data ) - { - this.setBurnTime( data.getDouble( "burnTime" ) ); - this.setMaxBurnTime( data.getDouble( "maxBurnTime" ) ); - this.setBurnSpeed( data.getInteger( "burnSpeed" ) ); - } + @Override + public IInventory getInternalInventory() { + return this.inv; + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return TileEntityFurnace.getItemBurnTime(itemstack) > 0; + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return TileEntityFurnace.getItemBurnTime( itemstack ) > 0; - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + if (this.getBurnTime() <= 0) { + if (this.canEatFuel()) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // wake up! + } + } + } + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.getBurnTime() <= 0 ) - { - if( this.canEatFuel() ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // wake up! - } - } - } - } + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return extractedItem.getItem() == Items.bucket; + } - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return extractedItem.getItem() == Items.bucket; - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return ACCESSIBLE_SLOTS; + } - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return ACCESSIBLE_SLOTS; - } + private boolean canEatFuel() { + final ItemStack is = this.getStackInSlot(FUEL_SLOT_INDEX); + if (is != null) { + final int newBurnTime = TileEntityFurnace.getItemBurnTime(is); + if (newBurnTime > 0 && is.stackSize > 0) { + return true; + } + } + return false; + } - private boolean canEatFuel() - { - final ItemStack is = this.getStackInSlot( FUEL_SLOT_INDEX ); - if( is != null ) - { - final int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if( newBurnTime > 0 && is.stackSize > 0 ) - { - return true; - } - } - return false; - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + if (this.getBurnTime() <= 0) { + this.eatFuel(); + } - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - if( this.getBurnTime() <= 0 ) - { - this.eatFuel(); - } + return new TickingRequest( + TickRates.VibrationChamber.getMin(), + TickRates.VibrationChamber.getMax(), + this.getBurnTime() <= 0, + false + ); + } - return new TickingRequest( TickRates.VibrationChamber.getMin(), TickRates.VibrationChamber.getMax(), this.getBurnTime() <= 0, false ); - } + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (this.getBurnTime() <= 0) { + this.eatFuel(); - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( this.getBurnTime() <= 0 ) - { - this.eatFuel(); + if (this.getBurnTime() > 0) { + return TickRateModulation.URGENT; + } - if( this.getBurnTime() > 0 ) - { - return TickRateModulation.URGENT; - } + this.setBurnSpeed(100); + return TickRateModulation.SLEEP; + } - this.setBurnSpeed( 100 ); - return TickRateModulation.SLEEP; - } + this.setBurnSpeed( + Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED)) + ); + final double dilation = this.getBurnSpeed() / DILATION_SCALING; - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - final double dilation = this.getBurnSpeed() / DILATION_SCALING; + double timePassed = ticksSinceLastCall * dilation; + this.setBurnTime(this.getBurnTime() - timePassed); + if (this.getBurnTime() < 0) { + timePassed += this.getBurnTime(); + this.setBurnTime(0); + } - double timePassed = ticksSinceLastCall * dilation; - this.setBurnTime( this.getBurnTime() - timePassed ); - if( this.getBurnTime() < 0 ) - { - timePassed += this.getBurnTime(); - this.setBurnTime( 0 ); - } + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + final double newPower = timePassed * POWER_PER_TICK; + final double overFlow = grid.injectPower(newPower, Actionable.SIMULATE); - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - final double newPower = timePassed * POWER_PER_TICK; - final double overFlow = grid.injectPower( newPower, Actionable.SIMULATE ); + // burn the over flow. + grid.injectPower(Math.max(0.0, newPower - overFlow), Actionable.MODULATE); - // burn the over flow. - grid.injectPower( Math.max( 0.0, newPower - overFlow ), Actionable.MODULATE ); + if (overFlow > 0) { + this.setBurnSpeed(this.getBurnSpeed() - ticksSinceLastCall); + } else { + this.setBurnSpeed(this.getBurnSpeed() + ticksSinceLastCall); + } - if( overFlow > 0 ) - { - this.setBurnSpeed( this.getBurnSpeed() - ticksSinceLastCall ); - } - else - { - this.setBurnSpeed( this.getBurnSpeed() + ticksSinceLastCall ); - } + this.setBurnSpeed( + Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED)) + ); + return overFlow > 0 ? TickRateModulation.SLOWER : TickRateModulation.FASTER; + } catch (final GridAccessException e) { + this.setBurnSpeed(this.getBurnSpeed() - ticksSinceLastCall); + this.setBurnSpeed( + Math.max(MIN_BURN_SPEED, Math.min(this.getBurnSpeed(), MAX_BURN_SPEED)) + ); + return TickRateModulation.SLOWER; + } + } - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - return overFlow > 0 ? TickRateModulation.SLOWER : TickRateModulation.FASTER; - } - catch( final GridAccessException e ) - { - this.setBurnSpeed( this.getBurnSpeed() - ticksSinceLastCall ); - this.setBurnSpeed( Math.max( MIN_BURN_SPEED, Math.min( this.getBurnSpeed(), MAX_BURN_SPEED ) ) ); - return TickRateModulation.SLOWER; - } - } + private void eatFuel() { + final ItemStack is = this.getStackInSlot(FUEL_SLOT_INDEX); + if (is != null) { + final int newBurnTime = TileEntityFurnace.getItemBurnTime(is); + if (newBurnTime > 0 && is.stackSize > 0) { + this.setBurnTime(this.getBurnTime() + newBurnTime); + this.setMaxBurnTime(this.getBurnTime()); + is.stackSize--; + if (is.stackSize <= 0) { + ItemStack container = null; - private void eatFuel() - { - final ItemStack is = this.getStackInSlot( FUEL_SLOT_INDEX ); - if( is != null ) - { - final int newBurnTime = TileEntityFurnace.getItemBurnTime( is ); - if( newBurnTime > 0 && is.stackSize > 0 ) - { - this.setBurnTime( this.getBurnTime() + newBurnTime ); - this.setMaxBurnTime( this.getBurnTime() ); - is.stackSize--; - if( is.stackSize <= 0 ) - { - ItemStack container = null; + if (is.getItem() != null && is.getItem().hasContainerItem(is)) { + container = is.getItem().getContainerItem(is); + } - if( is.getItem() != null && is.getItem().hasContainerItem( is ) ) - { - container = is.getItem().getContainerItem( is ); - } + this.setInventorySlotContents(0, container); + } else { + this.setInventorySlotContents(0, is); + } - this.setInventorySlotContents( 0, container ); - } - else - { - this.setInventorySlotContents( 0, is ); - } + this.markDirty(); + } + } - this.markDirty(); - } - } + if (this.getBurnTime() > 0) { + try { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } catch (final GridAccessException e) { + // gah! + } + } - if( this.getBurnTime() > 0 ) - { - try - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - catch( final GridAccessException e ) - { - // gah! - } - } + // state change + if ((!this.isOn && this.getBurnTime() > 0) + || (this.isOn && this.getBurnTime() <= 0)) { + this.isOn = this.getBurnTime() > 0; + this.markForUpdate(); - // state change - if( ( !this.isOn && this.getBurnTime() > 0 ) || ( this.isOn && this.getBurnTime() <= 0 ) ) - { - this.isOn = this.getBurnTime() > 0; - this.markForUpdate(); + if (this.hasWorldObj()) { + Platform.notifyBlocksOfNeighbors( + this.worldObj, this.xCoord, this.yCoord, this.zCoord + ); + } + } + } - if( this.hasWorldObj() ) - { - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - } - } - } + public int getBurnSpeed() { + return this.burnSpeed; + } - public int getBurnSpeed() - { - return this.burnSpeed; - } + private void setBurnSpeed(final int burnSpeed) { + this.burnSpeed = burnSpeed; + } - private void setBurnSpeed( final int burnSpeed ) - { - this.burnSpeed = burnSpeed; - } + public double getMaxBurnTime() { + return this.maxBurnTime; + } - public double getMaxBurnTime() - { - return this.maxBurnTime; - } + private void setMaxBurnTime(final double maxBurnTime) { + this.maxBurnTime = maxBurnTime; + } - private void setMaxBurnTime( final double maxBurnTime ) - { - this.maxBurnTime = maxBurnTime; - } + public double getBurnTime() { + return this.burnTime; + } - public double getBurnTime() - { - return this.burnTime; - } - - private void setBurnTime( final double burnTime ) - { - this.burnTime = burnTime; - } + private void setBurnTime(final double burnTime) { + this.burnTime = burnTime; + } } diff --git a/src/main/java/appeng/tile/networking/TileCableBus.java b/src/main/java/appeng/tile/networking/TileCableBus.java index 26a99051..593b8b68 100644 --- a/src/main/java/appeng/tile/networking/TileCableBus.java +++ b/src/main/java/appeng/tile/networking/TileCableBus.java @@ -18,6 +18,9 @@ package appeng.tile.networking; +import java.io.IOException; +import java.util.List; +import java.util.Set; import appeng.api.networking.IGridNode; import appeng.api.parts.IFacadeContainer; @@ -49,340 +52,310 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.io.IOException; -import java.util.List; -import java.util.Set; +public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomCollision { + private CableBusContainer cb = new CableBusContainer(this); + /** + * Immibis MB Support + */ + private boolean ImmibisMicroblocks_TransformableTileEntityMarker = true; + private int oldLV = -1; // on re-calculate light when it changes -public class TileCableBus extends AEBaseTile implements AEMultiTile, ICustomCollision -{ + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileCableBus(final NBTTagCompound data) { + this.getCableBus().readFromNBT(data); + } - private CableBusContainer cb = new CableBusContainer( this ); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileCableBus(final NBTTagCompound data) { + this.getCableBus().writeToNBT(data); + } - /** - * Immibis MB Support - */ - private boolean ImmibisMicroblocks_TransformableTileEntityMarker = true; - private int oldLV = -1; // on re-calculate light when it changes + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileCableBus(final ByteBuf data) throws IOException { + final boolean ret = this.getCableBus().readFromStream(data); - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileCableBus( final NBTTagCompound data ) - { - this.getCableBus().readFromNBT( data ); - } + final int newLV = this.getCableBus().getLightValue(); + if (newLV != this.oldLV) { + this.oldLV = newLV; + this.worldObj.func_147451_t(this.xCoord, this.yCoord, this.zCoord); + // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileCableBus( final NBTTagCompound data ) - { - this.getCableBus().writeToNBT( data ); - } + this.updateTileSetting(); + return ret; + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileCableBus( final ByteBuf data ) throws IOException - { - final boolean ret = this.getCableBus().readFromStream( data ); + protected void updateTileSetting() { + if (this.getCableBus().isRequiresDynamicRender()) { + try { + final TileCableBus tcb + = (TileCableBus) BlockCableBus.getTesrTile().newInstance(); + tcb.copyFrom(this); + this.getWorldObj().setTileEntity( + this.xCoord, this.yCoord, this.zCoord, tcb + ); + } catch (final Throwable ignored) {} + } + } - final int newLV = this.getCableBus().getLightValue(); - if( newLV != this.oldLV ) - { - this.oldLV = newLV; - this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); - // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); - } + protected void copyFrom(final TileCableBus oldTile) { + final CableBusContainer tmpCB = this.getCableBus(); + this.setCableBus(oldTile.getCableBus()); + this.oldLV = oldTile.oldLV; + oldTile.setCableBus(tmpCB); + } - this.updateTileSetting(); - return ret; - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileCableBus(final ByteBuf data) throws IOException { + this.getCableBus().writeToStream(data); + } - protected void updateTileSetting() - { - if( this.getCableBus().isRequiresDynamicRender() ) - { - try - { - final TileCableBus tcb = (TileCableBus) BlockCableBus.getTesrTile().newInstance(); - tcb.copyFrom( this ); - this.getWorldObj().setTileEntity( this.xCoord, this.yCoord, this.zCoord, tcb ); - } - catch( final Throwable ignored ) - { + @Override + public double getMaxRenderDistanceSquared() { + return 900.0; + } - } - } - } + @Override + public void invalidate() { + super.invalidate(); + this.getCableBus().removeFromWorld(); + } - protected void copyFrom( final TileCableBus oldTile ) - { - final CableBusContainer tmpCB = this.getCableBus(); - this.setCableBus( oldTile.getCableBus() ); - this.oldLV = oldTile.oldLV; - oldTile.setCableBus( tmpCB ); - } + @Override + public void validate() { + super.validate(); + TickHandler.INSTANCE.addInit(this); + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileCableBus( final ByteBuf data ) throws IOException - { - this.getCableBus().writeToStream( data ); - } + @Override + public IGridNode getGridNode(final ForgeDirection dir) { + return this.getCableBus().getGridNode(dir); + } - @Override - public double getMaxRenderDistanceSquared() - { - return 900.0; - } + @Override + public AECableType getCableConnectionType(final ForgeDirection side) { + return this.getCableBus().getCableConnectionType(side); + } - @Override - public void invalidate() - { - super.invalidate(); - this.getCableBus().removeFromWorld(); - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.getCableBus().removeFromWorld(); + } - @Override - public void validate() - { - super.validate(); - TickHandler.INSTANCE.addInit( this ); - } + @Override + public void markForUpdate() { + if (this.worldObj == null) { + return; + } - @Override - public IGridNode getGridNode( final ForgeDirection dir ) - { - return this.getCableBus().getGridNode( dir ); - } + final int newLV = this.getCableBus().getLightValue(); + if (newLV != this.oldLV) { + this.oldLV = newLV; + this.worldObj.func_147451_t(this.xCoord, this.yCoord, this.zCoord); + // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection side ) - { - return this.getCableBus().getCableConnectionType( side ); - } + super.markForUpdate(); + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.getCableBus().removeFromWorld(); - } + @Override + public boolean canBeRotated() { + return false; + } - @Override - public void markForUpdate() - { - if( this.worldObj == null ) - { - return; - } + @Override + public void + getDrops(final World w, final int x, final int y, final int z, final List drops) { + this.getCableBus().getDrops(drops); + } - final int newLV = this.getCableBus().getLightValue(); - if( newLV != this.oldLV ) - { - this.oldLV = newLV; - this.worldObj.func_147451_t( this.xCoord, this.yCoord, this.zCoord ); - // worldObj.updateAllLightTypes( xCoord, yCoord, zCoord ); - } + @Override + public void getNoDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + this.getCableBus().getNoDrops(drops); + } - super.markForUpdate(); - } + @Override + public void onReady() { + super.onReady(); + if (this.getCableBus().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.getCableBus().addToWorld(); + } + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public boolean requiresTESR() { + return this.getCableBus().isRequiresDynamicRender(); + } - @Override - public void getDrops( final World w, final int x, final int y, final int z, final List drops ) - { - this.getCableBus().getDrops( drops ); - } + @Override + public IFacadeContainer getFacadeContainer() { + return this.getCableBus().getFacadeContainer(); + } - @Override - public void getNoDrops( final World w, final int x, final int y, final int z, final List drops ) - { - this.getCableBus().getNoDrops( drops ); - } + @Override + public boolean canAddPart(final ItemStack is, final ForgeDirection side) { + return this.getCableBus().canAddPart(is, side); + } - @Override - public void onReady() - { - super.onReady(); - if( this.getCableBus().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.getCableBus().addToWorld(); - } - } + @Override + public ForgeDirection + addPart(final ItemStack is, final ForgeDirection side, final EntityPlayer player) { + return this.getCableBus().addPart(is, side, player); + } - @Override - public boolean requiresTESR() - { - return this.getCableBus().isRequiresDynamicRender(); - } + @Override + public IPart getPart(final ForgeDirection side) { + return this.getCableBus().getPart(side); + } - @Override - public IFacadeContainer getFacadeContainer() - { - return this.getCableBus().getFacadeContainer(); - } + @Override + public void removePart(final ForgeDirection side, final boolean suppressUpdate) { + this.getCableBus().removePart(side, suppressUpdate); + } - @Override - public boolean canAddPart( final ItemStack is, final ForgeDirection side ) - { - return this.getCableBus().canAddPart( is, side ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public ForgeDirection addPart( final ItemStack is, final ForgeDirection side, final EntityPlayer player ) - { - return this.getCableBus().addPart( is, side, player ); - } + @Override + public AEColor getColor() { + return this.getCableBus().getColor(); + } - @Override - public IPart getPart( final ForgeDirection side ) - { - return this.getCableBus().getPart( side ); - } + @Override + public void clearContainer() { + this.setCableBus(new CableBusContainer(this)); + } - @Override - public void removePart( final ForgeDirection side, final boolean suppressUpdate ) - { - this.getCableBus().removePart( side, suppressUpdate ); - } + @Override + public boolean isBlocked(final ForgeDirection side) { + return !this.ImmibisMicroblocks_isSideOpen(side.ordinal()); + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public Iterable getSelectedBoundingBoxesFromPool( + final World w, + final int x, + final int y, + final int z, + final Entity e, + final boolean visual + ) { + return this.getCableBus().getSelectedBoundingBoxesFromPool( + false, true, e, visual + ); + } - @Override - public AEColor getColor() - { - return this.getCableBus().getColor(); - } + @Override + public SelectedPart selectPart(final Vec3 pos) { + return this.getCableBus().selectPart(pos); + } - @Override - public void clearContainer() - { - this.setCableBus( new CableBusContainer( this ) ); - } + @Override + public void markForSave() { + super.markDirty(); + } - @Override - public boolean isBlocked( final ForgeDirection side ) - { - return !this.ImmibisMicroblocks_isSideOpen( side.ordinal() ); - } + @Override + public void partChanged() { + this.notifyNeighbors(); + } - @Override - public Iterable getSelectedBoundingBoxesFromPool( final World w, final int x, final int y, final int z, final Entity e, final boolean visual ) - { - return this.getCableBus().getSelectedBoundingBoxesFromPool( false, true, e, visual ); - } + @Override + public boolean hasRedstone(final ForgeDirection side) { + return this.getCableBus().hasRedstone(side); + } - @Override - public SelectedPart selectPart( final Vec3 pos ) - { - return this.getCableBus().selectPart( pos ); - } + @Override + public boolean isEmpty() { + return this.getCableBus().isEmpty(); + } - @Override - public void markForSave() - { - super.markDirty(); - } + @Override + public Set getLayerFlags() { + return this.getCableBus().getLayerFlags(); + } - @Override - public void partChanged() - { - this.notifyNeighbors(); - } + @Override + public void cleanup() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.ImmibisMicroblocks)) { + final IImmibisMicroblocks imb = (IImmibisMicroblocks + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.ImmibisMicroblocks + ); + if (imb != null && imb.leaveParts(this)) { + return; + } + } - @Override - public boolean hasRedstone( final ForgeDirection side ) - { - return this.getCableBus().hasRedstone( side ); - } + this.getWorldObj().setBlock( + this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK + ); + } - @Override - public boolean isEmpty() - { - return this.getCableBus().isEmpty(); - } + @Override + public void addCollidingBlockToList( + final World w, + final int x, + final int y, + final int z, + final AxisAlignedBB bb, + final List out, + final Entity e + ) { + for (final 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 Set getLayerFlags() - { - return this.getCableBus().getLayerFlags(); - } + @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 cleanup() - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.ImmibisMicroblocks ) ) - { - final IImmibisMicroblocks imb = (IImmibisMicroblocks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.ImmibisMicroblocks ); - if( imb != null && imb.leaveParts( this ) ) - { - return; - } - } + @Override + public boolean isInWorld() { + return this.getCableBus().isInWorld(); + } - this.getWorldObj().setBlock( this.xCoord, this.yCoord, this.zCoord, Platform.AIR_BLOCK ); - } + private boolean ImmibisMicroblocks_isSideOpen(final int side) { + return true; + } - @Override - public void addCollidingBlockToList( final World w, final int x, final int y, final int z, final AxisAlignedBB bb, final List out, final Entity e ) - { - for( final 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 ) ); - } - } + public void ImmibisMicroblocks_onMicroblocksChanged() { + this.getCableBus().updateConnections(); + } - @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 boolean recolourBlock( + final ForgeDirection side, final AEColor colour, final EntityPlayer who + ) { + return this.getCableBus().recolourBlock(side, colour, who); + } - @Override - public boolean isInWorld() - { - return this.getCableBus().isInWorld(); - } - - private boolean ImmibisMicroblocks_isSideOpen( final int side ) - { - return true; - } - - public void ImmibisMicroblocks_onMicroblocksChanged() - { - this.getCableBus().updateConnections(); - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor colour, final EntityPlayer who ) - { - return this.getCableBus().recolourBlock( side, colour, who ); - } - - public CableBusContainer getCableBus() - { - return this.cb; - } - - private void setCableBus( final CableBusContainer cb ) - { - this.cb = cb; - } + public CableBusContainer getCableBus() { + return this.cb; + } + private void setCableBus(final CableBusContainer cb) { + this.cb = cb; + } } diff --git a/src/main/java/appeng/tile/networking/TileCableBusTESR.java b/src/main/java/appeng/tile/networking/TileCableBusTESR.java index 4e3711f8..678f68f7 100644 --- a/src/main/java/appeng/tile/networking/TileCableBusTESR.java +++ b/src/main/java/appeng/tile/networking/TileCableBusTESR.java @@ -18,28 +18,20 @@ package appeng.tile.networking; - import appeng.block.networking.BlockCableBus; - -public class TileCableBusTESR extends TileCableBus -{ - - @Override - protected void updateTileSetting() - { - if( !this.getCableBus().isRequiresDynamicRender() ) - { - try - { - final TileCableBus tcb = (TileCableBus) BlockCableBus.getNoTesrTile().newInstance(); - tcb.copyFrom( this ); - this.getWorldObj().setTileEntity( this.xCoord, this.yCoord, this.zCoord, tcb ); - } - catch( final Throwable ignored ) - { - - } - } - } +public class TileCableBusTESR extends TileCableBus { + @Override + protected void updateTileSetting() { + if (!this.getCableBus().isRequiresDynamicRender()) { + try { + final TileCableBus tcb + = (TileCableBus) BlockCableBus.getNoTesrTile().newInstance(); + tcb.copyFrom(this); + this.getWorldObj().setTileEntity( + this.xCoord, this.yCoord, this.zCoord, tcb + ); + } catch (final Throwable ignored) {} + } + } } diff --git a/src/main/java/appeng/tile/networking/TileController.java b/src/main/java/appeng/tile/networking/TileController.java index fc3ef3bc..51b9efe5 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 appeng.api.config.Actionable; import appeng.api.networking.GridFlags; @@ -36,186 +37,160 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class TileController extends AENetworkPowerTile { + private static final IInventory NULL_INVENTORY = new AppEngInternalInventory(null, 0); + private static final int[] ACCESSIBLE_SLOTS_BY_SIDE = {}; + private boolean isValid = false; -public class TileController extends AENetworkPowerTile -{ - private static final IInventory NULL_INVENTORY = new AppEngInternalInventory( null, 0 ); - private static final int[] ACCESSIBLE_SLOTS_BY_SIDE = {}; + public TileController() { + this.setInternalMaxPower(8000); + this.setInternalPublicPowerStorage(true); + this.getProxy().setIdlePowerUsage(3); + this.getProxy().setFlags(GridFlags.CANNOT_CARRY, GridFlags.DENSE_CAPACITY); + } - private boolean isValid = false; + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.DENSE; + } - public TileController() - { - this.setInternalMaxPower( 8000 ); - this.setInternalPublicPowerStorage( true ); - this.getProxy().setIdlePowerUsage( 3 ); - this.getProxy().setFlags( GridFlags.CANNOT_CARRY, GridFlags.DENSE_CAPACITY ); - } + @Override + public void onReady() { + this.onNeighborChange(true); + super.onReady(); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.DENSE; - } + public void onNeighborChange(final boolean force) { + final boolean xx = this.checkController(this.xCoord - 1, this.yCoord, this.zCoord) + && this.checkController(this.xCoord + 1, this.yCoord, this.zCoord); + final boolean yy = this.checkController(this.xCoord, this.yCoord - 1, this.zCoord) + && this.checkController(this.xCoord, this.yCoord + 1, this.zCoord); + final boolean zz = this.checkController(this.xCoord, this.yCoord, this.zCoord - 1) + && this.checkController(this.xCoord, this.yCoord, this.zCoord + 1); - @Override - public void onReady() - { - this.onNeighborChange( true ); - super.onReady(); - } + // int meta = world.getBlockMetadata( xCoord, yCoord, zCoord ); + // boolean hasPower = meta > 0; + // boolean isConflict = meta == 2; - public void onNeighborChange( final boolean force ) - { - final boolean xx = this.checkController( this.xCoord - 1, this.yCoord, this.zCoord ) && this.checkController( this.xCoord + 1, this.yCoord, this.zCoord ); - final boolean yy = this.checkController( this.xCoord, this.yCoord - 1, this.zCoord ) && this.checkController( this.xCoord, this.yCoord + 1, this.zCoord ); - final boolean zz = this.checkController( this.xCoord, this.yCoord, this.zCoord - 1 ) && this.checkController( this.xCoord, this.yCoord, this.zCoord + 1 ); + final boolean oldValid = this.isValid; - // int meta = world.getBlockMetadata( xCoord, yCoord, zCoord ); - // boolean hasPower = meta > 0; - // boolean isConflict = meta == 2; + this.isValid = (xx && !yy && !zz) || (!xx && yy && !zz) || (!xx && !yy && zz) + || ((xx ? 1 : 0) + (yy ? 1 : 0) + (zz ? 1 : 0) <= 1); - final boolean oldValid = this.isValid; + if (oldValid != this.isValid || force) { + if (this.isValid) { + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); + } else { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } - this.isValid = ( xx && !yy && !zz ) || ( !xx && yy && !zz ) || ( !xx && !yy && zz ) || ( ( xx ? 1 : 0 ) + ( yy ? 1 : 0 ) + ( zz ? 1 : 0 ) <= 1 ); + this.updateMeta(); + } + } - if( oldValid != this.isValid || force ) - { - if( this.isValid ) - { - this.getProxy().setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - else - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } + private void updateMeta() { + if (!this.getProxy().isReady()) { + return; + } - this.updateMeta(); - } + int meta = 0; - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + meta = 1; - private void updateMeta() - { - if( !this.getProxy().isReady() ) - { - return; - } + if (this.getProxy().getPath().getControllerState() + == ControllerState.CONTROLLER_CONFLICT) { + meta = 2; + } + } + } catch (final GridAccessException e) { + meta = 0; + } - int meta = 0; + if (this.checkController(this.xCoord, this.yCoord, this.zCoord) + && this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) + != meta) { + this.worldObj.setBlockMetadataWithNotify( + this.xCoord, this.yCoord, this.zCoord, meta, 2 + ); + } + } - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - meta = 1; + @Override + protected double getFunnelPowerDemand(final double maxReceived) { + try { + return this.getProxy().getEnergy().getEnergyDemand(8000); + } catch (final GridAccessException e) { + // no grid? use local... + return super.getFunnelPowerDemand(maxReceived); + } + } - if( this.getProxy().getPath().getControllerState() == ControllerState.CONTROLLER_CONFLICT ) - { - meta = 2; - } - } - } - catch( final GridAccessException e ) - { - meta = 0; - } + @Override + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + try { + final double ret = this.getProxy().getEnergy().injectPower(power, mode); + if (mode == Actionable.SIMULATE) { + return ret; + } + return 0; + } catch (final GridAccessException e) { + // no grid? use local... + return super.funnelPowerIntoStorage(power, mode); + } + } - if( this.checkController( this.xCoord, this.yCoord, this.zCoord ) && this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ) != meta ) - { - this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, meta, 2 ); - } - } + @Override + protected void PowerEvent(final PowerEventType x) { + try { + this.getProxy().getGrid().postEvent(new MENetworkPowerStorage(this, x)); + } catch (final GridAccessException e) { + // not ready! + } + } - @Override - protected double getFunnelPowerDemand( final double maxReceived ) - { - try - { - return this.getProxy().getEnergy().getEnergyDemand( 8000 ); - } - catch( final GridAccessException e ) - { - // no grid? use local... - return super.getFunnelPowerDemand( maxReceived ); - } - } + @MENetworkEventSubscribe + public void onControllerChange(final MENetworkControllerChange status) { + this.updateMeta(); + } - @Override - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - try - { - final double ret = this.getProxy().getEnergy().injectPower( power, mode ); - if( mode == Actionable.SIMULATE ) - { - return ret; - } - return 0; - } - catch( final GridAccessException e ) - { - // no grid? use local... - return super.funnelPowerIntoStorage( power, mode ); - } - } + @MENetworkEventSubscribe + public void onPowerChange(final MENetworkPowerStatusChange status) { + this.updateMeta(); + } - @Override - protected void PowerEvent( final PowerEventType x ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, x ) ); - } - catch( final GridAccessException e ) - { - // not ready! - } - } + @Override + public IInventory getInternalInventory() { + return NULL_INVENTORY; + } - @MENetworkEventSubscribe - public void onControllerChange( final MENetworkControllerChange status ) - { - this.updateMeta(); - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) {} - @MENetworkEventSubscribe - public void onPowerChange( final MENetworkPowerStatusChange status ) - { - this.updateMeta(); - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return ACCESSIBLE_SLOTS_BY_SIDE; + } - @Override - public IInventory getInternalInventory() - { - return NULL_INVENTORY; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return ACCESSIBLE_SLOTS_BY_SIDE; - } - - /** - * Check for a controller at this coordinates as well as is it loaded. - * - * @return true if there is a loaded controller - */ - private boolean checkController( final int x, final int y, final int z ) - { - if( this.worldObj.getChunkProvider().chunkExists( this.xCoord >> 4, this.zCoord >> 4 ) ) - { - return this.worldObj.getTileEntity( x, y, z ) instanceof TileController; - } - return false; - } + /** + * Check for a controller at this coordinates as well as is it loaded. + * + * @return true if there is a loaded controller + */ + private boolean checkController(final int x, final int y, final int z) { + if (this.worldObj.getChunkProvider().chunkExists( + this.xCoord >> 4, this.zCoord >> 4 + )) { + return this.worldObj.getTileEntity(x, y, z) instanceof TileController; + } + return false; + } } diff --git a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java index b11f9c06..45d4a3cb 100644 --- a/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileCreativeEnergyCell.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -27,54 +26,44 @@ import appeng.api.util.AECableType; import appeng.tile.grid.AENetworkTile; import net.minecraftforge.common.util.ForgeDirection; +public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerStorage { + public TileCreativeEnergyCell() { + this.getProxy().setIdlePowerUsage(0); + } -public class TileCreativeEnergyCell extends AENetworkTile implements IAEPowerStorage -{ + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - public TileCreativeEnergyCell() - { - this.getProxy().setIdlePowerUsage( 0 ); - } + @Override + public double injectAEPower(final double amt, final Actionable mode) { + return 0; + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + @Override + public double getAEMaxPower() { + return Long.MAX_VALUE / 10000; + } - @Override - public double injectAEPower( final double amt, final Actionable mode ) - { - return 0; - } + @Override + public double getAECurrentPower() { + return Long.MAX_VALUE / 10000; + } - @Override - public double getAEMaxPower() - { - return Long.MAX_VALUE / 10000; - } + @Override + public boolean isAEPublicPowerStorage() { + return true; + } - @Override - public double getAECurrentPower() - { - return Long.MAX_VALUE / 10000; - } + @Override + public AccessRestriction getPowerFlow() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isAEPublicPowerStorage() - { - return true; - } - - @Override - public AccessRestriction getPowerFlow() - { - return AccessRestriction.READ_WRITE; - } - - @Override - public double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - return amt; - } + @Override + public double + extractAEPower(final double amt, final Actionable mode, final 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 7c2a8dee..d14ef355 100644 --- a/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileDenseEnergyCell.java @@ -18,12 +18,8 @@ package appeng.tile.networking; - -public class TileDenseEnergyCell extends TileEnergyCell -{ - - public TileDenseEnergyCell() - { - this.setInternalMaxPower( 200000 * 8 ); - } +public class TileDenseEnergyCell extends TileEnergyCell { + public TileDenseEnergyCell() { + this.setInternalMaxPower(200000 * 8); + } } diff --git a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java index 3ceaaa3f..8254ce43 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java +++ b/src/main/java/appeng/tile/networking/TileEnergyAcceptor.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.config.Actionable; import appeng.api.networking.energy.IEnergyGrid; import appeng.api.util.AECableType; @@ -31,89 +30,75 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +public class TileEnergyAcceptor extends AENetworkPowerTile { + private static final AppEngInternalInventory INTERNAL_INVENTORY + = new AppEngInternalInventory(null, 0); + private final int[] sides = {}; -public class TileEnergyAcceptor extends AENetworkPowerTile -{ + public TileEnergyAcceptor() { + this.getProxy().setIdlePowerUsage(0.0); + this.setInternalMaxPower(0); + } - private static final AppEngInternalInventory INTERNAL_INVENTORY = new AppEngInternalInventory( null, 0 ); - private final int[] sides = {}; + @Override + public void readFromNBT_AENetwork(final NBTTagCompound data) { + /** + * Does nothing here since the NBT tag in the parent is not needed anymore + */ + } - public TileEnergyAcceptor() - { - this.getProxy().setIdlePowerUsage( 0.0 ); - this.setInternalMaxPower( 0 ); - } + @Override + public void writeToNBT_AENetwork(final NBTTagCompound data) { + /** + * Does nothing here since the NBT tag in the parent is not needed anymore + */ + } - @Override - public void readFromNBT_AENetwork( final NBTTagCompound data ) - { - /** - * Does nothing here since the NBT tag in the parent is not needed anymore - */ - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - @Override - public void writeToNBT_AENetwork( final NBTTagCompound data ) - { - /** - * Does nothing here since the NBT tag in the parent is not needed anymore - */ - } + @Override + protected double getFunnelPowerDemand(final double maxRequired) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + return grid.getEnergyDemand(maxRequired); + } catch (final GridAccessException e) { + return this.getInternalMaxPower(); + } + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + @Override + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + try { + final IEnergyGrid grid = this.getProxy().getEnergy(); + final double leftOver = grid.injectPower(power, mode); + if (mode == Actionable.SIMULATE) { + return leftOver; + } + return 0.0; + } catch (final GridAccessException e) { + return super.funnelPowerIntoStorage(power, mode); + } + } - @Override - protected double getFunnelPowerDemand( final double maxRequired ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - return grid.getEnergyDemand( maxRequired ); - } - catch( final GridAccessException e ) - { - return this.getInternalMaxPower(); - } - } + @Override + public IInventory getInternalInventory() { + return INTERNAL_INVENTORY; + } - @Override - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - try - { - final IEnergyGrid grid = this.getProxy().getEnergy(); - final double leftOver = grid.injectPower( power, mode ); - if( mode == Actionable.SIMULATE ) - { - return leftOver; - } - return 0.0; - } - catch( final GridAccessException e ) - { - return super.funnelPowerIntoStorage( power, mode ); - } - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) {} - @Override - public IInventory getInternalInventory() - { - return INTERNAL_INVENTORY; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } } diff --git a/src/main/java/appeng/tile/networking/TileEnergyCell.java b/src/main/java/appeng/tile/networking/TileEnergyCell.java index cb47ca0e..5168c699 100644 --- a/src/main/java/appeng/tile/networking/TileEnergyCell.java +++ b/src/main/java/appeng/tile/networking/TileEnergyCell.java @@ -18,7 +18,6 @@ package appeng.tile.networking; - import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -34,212 +33,183 @@ import appeng.util.SettingsFrom; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; +public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage { + private double internalCurrentPower = 0.0; + private double internalMaxPower = 200000.0; -public class TileEnergyCell extends AENetworkTile implements IAEPowerStorage -{ + private byte currentMeta = -1; - private double internalCurrentPower = 0.0; - private double internalMaxPower = 200000.0; + public TileEnergyCell() { + this.getProxy().setIdlePowerUsage(0); + } - private byte currentMeta = -1; + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.COVERED; + } - public TileEnergyCell() - { - this.getProxy().setIdlePowerUsage( 0 ); - } + @Override + public void onReady() { + super.onReady(); + this.currentMeta = (byte + ) this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord); + this.changePowerLevel(); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.COVERED; - } + private void changePowerLevel() { + if (this.notLoaded()) { + return; + } - @Override - public void onReady() - { - super.onReady(); - this.currentMeta = (byte) this.worldObj.getBlockMetadata( this.xCoord, this.yCoord, this.zCoord ); - this.changePowerLevel(); - } + byte boundMetadata + = (byte) (8.0 * (this.internalCurrentPower / this.getInternalMaxPower())); - private void changePowerLevel() - { - if( this.notLoaded() ) - { - return; - } + if (boundMetadata > 7) { + boundMetadata = 7; + } + if (boundMetadata < 0) { + boundMetadata = 0; + } - byte boundMetadata = (byte) ( 8.0 * ( this.internalCurrentPower / this.getInternalMaxPower() ) ); + if (this.currentMeta != boundMetadata) { + this.currentMeta = boundMetadata; + this.worldObj.setBlockMetadataWithNotify( + this.xCoord, this.yCoord, this.zCoord, this.currentMeta, 2 + ); + } + } - if( boundMetadata > 7 ) - { - boundMetadata = 7; - } - if( boundMetadata < 0 ) - { - boundMetadata = 0; - } + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileEnergyCell(final NBTTagCompound data) { + if (!this.worldObj.isRemote) { + data.setDouble("internalCurrentPower", this.internalCurrentPower); + } + } - if( this.currentMeta != boundMetadata ) - { - this.currentMeta = boundMetadata; - this.worldObj.setBlockMetadataWithNotify( this.xCoord, this.yCoord, this.zCoord, this.currentMeta, 2 ); - } - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileEnergyCell(final NBTTagCompound data) { + this.internalCurrentPower = data.getDouble("internalCurrentPower"); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileEnergyCell( final NBTTagCompound data ) - { - if( !this.worldObj.isRemote ) - { - data.setDouble( "internalCurrentPower", this.internalCurrentPower ); - } - } + @Override + public boolean canBeRotated() { + return false; + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileEnergyCell( final NBTTagCompound data ) - { - this.internalCurrentPower = data.getDouble( "internalCurrentPower" ); - } + @Override + public void uploadSettings(final SettingsFrom from, final NBTTagCompound compound) { + if (from == SettingsFrom.DISMANTLE_ITEM) { + this.internalCurrentPower = compound.getDouble("internalCurrentPower"); + } + } - @Override - public boolean canBeRotated() - { - return false; - } + @Override + public NBTTagCompound downloadSettings(final SettingsFrom from) { + if (from == SettingsFrom.DISMANTLE_ITEM) { + final NBTTagCompound tag = new NBTTagCompound(); + tag.setDouble("internalCurrentPower", this.internalCurrentPower); + tag.setDouble( + "internalMaxPower", this.getInternalMaxPower() + ); // used for tool tip. + return tag; + } + return null; + } - @Override - public void uploadSettings( final SettingsFrom from, final NBTTagCompound compound ) - { - if( from == SettingsFrom.DISMANTLE_ITEM ) - { - this.internalCurrentPower = compound.getDouble( "internalCurrentPower" ); - } - } + @Override + public final double injectAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + final double fakeBattery = this.internalCurrentPower + amt; + if (fakeBattery > this.getInternalMaxPower()) { + return fakeBattery - this.getInternalMaxPower(); + } - @Override - public NBTTagCompound downloadSettings( final SettingsFrom from ) - { - if( from == SettingsFrom.DISMANTLE_ITEM ) - { - final NBTTagCompound tag = new NBTTagCompound(); - tag.setDouble( "internalCurrentPower", this.internalCurrentPower ); - tag.setDouble( "internalMaxPower", this.getInternalMaxPower() ); // used for tool tip. - return tag; - } - return null; - } + return 0; + } - @Override - public final double injectAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - final double fakeBattery = this.internalCurrentPower + amt; - if( fakeBattery > this.getInternalMaxPower() ) - { - return fakeBattery - this.getInternalMaxPower(); - } + if (this.internalCurrentPower < 0.01 && amt > 0.01) { + this.getProxy().getNode().getGrid().postEvent( + new MENetworkPowerStorage(this, PowerEventType.PROVIDE_POWER) + ); + } - return 0; - } + this.internalCurrentPower += amt; + if (this.internalCurrentPower > this.getInternalMaxPower()) { + amt = this.internalCurrentPower - this.getInternalMaxPower(); + this.internalCurrentPower = this.getInternalMaxPower(); - if( this.internalCurrentPower < 0.01 && amt > 0.01 ) - { - this.getProxy().getNode().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.PROVIDE_POWER ) ); - } + this.changePowerLevel(); + return amt; + } - this.internalCurrentPower += amt; - if( this.internalCurrentPower > this.getInternalMaxPower() ) - { - amt = this.internalCurrentPower - this.getInternalMaxPower(); - this.internalCurrentPower = this.getInternalMaxPower(); + this.changePowerLevel(); + return 0; + } - this.changePowerLevel(); - return amt; - } + @Override + public double getAEMaxPower() { + return this.getInternalMaxPower(); + } - this.changePowerLevel(); - return 0; - } + @Override + public double getAECurrentPower() { + return this.internalCurrentPower; + } - @Override - public double getAEMaxPower() - { - return this.getInternalMaxPower(); - } + @Override + public boolean isAEPublicPowerStorage() { + return true; + } - @Override - public double getAECurrentPower() - { - return this.internalCurrentPower; - } + @Override + public AccessRestriction getPowerFlow() { + return AccessRestriction.READ_WRITE; + } - @Override - public boolean isAEPublicPowerStorage() - { - return true; - } + @Override + public final double + extractAEPower(final double amt, final Actionable mode, final PowerMultiplier pm) { + return pm.divide(this.extractAEPower(pm.multiply(amt), mode)); + } - @Override - public AccessRestriction getPowerFlow() - { - return AccessRestriction.READ_WRITE; - } + private double extractAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + if (this.internalCurrentPower > amt) { + return amt; + } + return this.internalCurrentPower; + } - @Override - public final double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier pm ) - { - return pm.divide( this.extractAEPower( pm.multiply( amt ), mode ) ); - } + final boolean wasFull + = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001; - private double extractAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - if( this.internalCurrentPower > amt ) - { - return amt; - } - return this.internalCurrentPower; - } + if (wasFull && amt > 0.001) { + try { + this.getProxy().getGrid().postEvent( + new MENetworkPowerStorage(this, PowerEventType.REQUEST_POWER) + ); + } catch (final GridAccessException ignored) {} + } - final boolean wasFull = this.internalCurrentPower >= this.getInternalMaxPower() - 0.001; + if (this.internalCurrentPower > amt) { + this.internalCurrentPower -= amt; - if( wasFull && amt > 0.001 ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch( final GridAccessException ignored ) - { + this.changePowerLevel(); + return amt; + } - } - } + amt = this.internalCurrentPower; + this.internalCurrentPower = 0; - if( this.internalCurrentPower > amt ) - { - this.internalCurrentPower -= amt; + this.changePowerLevel(); + return amt; + } - this.changePowerLevel(); - return amt; - } + private double getInternalMaxPower() { + return this.internalMaxPower; + } - amt = this.internalCurrentPower; - this.internalCurrentPower = 0; - - this.changePowerLevel(); - return amt; - } - - private double getInternalMaxPower() - { - return this.internalMaxPower; - } - - void setInternalMaxPower( final double internalMaxPower ) - { - this.internalMaxPower = internalMaxPower; - } + void setInternalMaxPower(final double internalMaxPower) { + this.internalMaxPower = internalMaxPower; + } } diff --git a/src/main/java/appeng/tile/networking/TileWireless.java b/src/main/java/appeng/tile/networking/TileWireless.java index 83302e85..e71923ee 100644 --- a/src/main/java/appeng/tile/networking/TileWireless.java +++ b/src/main/java/appeng/tile/networking/TileWireless.java @@ -18,6 +18,7 @@ package appeng.tile.networking; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.implementations.IPowerChannelState; @@ -43,186 +44,164 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class TileWireless + extends AENetworkInvTile implements IWirelessAccessPoint, IPowerChannelState { + public static final int POWERED_FLAG = 1; + public static final int CHANNEL_FLAG = 2; + private final int[] sides = { 0 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 1); -public class TileWireless extends AENetworkInvTile implements IWirelessAccessPoint, IPowerChannelState -{ + private int clientFlags = 0; - public static final int POWERED_FLAG = 1; - public static final int CHANNEL_FLAG = 2; + public TileWireless() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } - private final int[] sides = { 0 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 1 ); - - private int clientFlags = 0; - - public TileWireless() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - - @Override - public void setOrientation( final ForgeDirection inForward, final ForgeDirection inUp ) - { - super.setOrientation( inForward, inUp ); - if (this.worldObj.getBlock(this.xCoord, this.yCoord, this.zCoord) instanceof BlockWirelessAccessPoint) { - this.getProxy().setValidSides( EnumSet.allOf(ForgeDirection.class) ); + @Override + public void + setOrientation(final ForgeDirection inForward, final ForgeDirection inUp) { + super.setOrientation(inForward, inUp); + if (this.worldObj.getBlock(this.xCoord, this.yCoord, this.zCoord) + instanceof BlockWirelessAccessPoint) { + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); } else { - this.getProxy().setValidSides( EnumSet.of( this.getForward().getOpposite() ) ); + this.getProxy().setValidSides(EnumSet.of(this.getForward().getOpposite())); } - } + } - @MENetworkEventSubscribe - public void chanRender( final MENetworkChannelsChanged c ) - { - this.markForUpdate(); - } + @MENetworkEventSubscribe + public void chanRender(final MENetworkChannelsChanged c) { + this.markForUpdate(); + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.markForUpdate(); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.markForUpdate(); + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileWireless( final ByteBuf data ) - { - final int old = this.getClientFlags(); - this.setClientFlags( data.readByte() ); + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileWireless(final ByteBuf data) { + final int old = this.getClientFlags(); + this.setClientFlags(data.readByte()); - return old != this.getClientFlags(); - } + return old != this.getClientFlags(); + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileWireless( final ByteBuf data ) - { - this.setClientFlags( 0 ); + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileWireless(final ByteBuf data) { + this.setClientFlags(0); - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.setClientFlags( this.getClientFlags() | POWERED_FLAG ); - } + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.setClientFlags(this.getClientFlags() | POWERED_FLAG); + } - if( this.getProxy().getNode().meetsChannelRequirements() ) - { - this.setClientFlags( this.getClientFlags() | CHANNEL_FLAG ); - } - } - catch( final GridAccessException e ) - { - // meh - } + if (this.getProxy().getNode().meetsChannelRequirements()) { + this.setClientFlags(this.getClientFlags() | CHANNEL_FLAG); + } + } catch (final GridAccessException e) { + // meh + } - data.writeByte( (byte) this.getClientFlags() ); - } + data.writeByte((byte) this.getClientFlags()); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + @Override + public IInventory getInternalInventory() { + return this.inv; + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return AEApi.instance().definitions().materials().wirelessBooster().isSameAs( itemstack ); - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return AEApi.instance().definitions().materials().wirelessBooster().isSameAs( + itemstack + ); + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - // :P - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + // :P + } - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } - @Override - public void onReady() - { - this.updatePower(); - super.onReady(); - } + @Override + public void onReady() { + this.updatePower(); + super.onReady(); + } - private void updatePower() - { - this.getProxy().setIdlePowerUsage( AEConfig.instance.wireless_getPowerDrain( this.getBoosters() ) ); - } + private void updatePower() { + this.getProxy().setIdlePowerUsage( + AEConfig.instance.wireless_getPowerDrain(this.getBoosters()) + ); + } - private int getBoosters() - { - final ItemStack boosters = this.inv.getStackInSlot( 0 ); - return boosters == null ? 0 : boosters.stackSize; - } + private int getBoosters() { + final ItemStack boosters = this.inv.getStackInSlot(0); + return boosters == null ? 0 : boosters.stackSize; + } - @Override - public void markDirty() - { - this.updatePower(); - } + @Override + public void markDirty() { + this.updatePower(); + } - @Override - public double getRange() - { - return AEConfig.instance.wireless_getMaxRange( this.getBoosters() ); - } + @Override + public double getRange() { + return AEConfig.instance.wireless_getMaxRange(this.getBoosters()); + } - @Override - public boolean isActive() - { - if( Platform.isClient() ) - { - return this.isPowered() && ( CHANNEL_FLAG == ( this.getClientFlags() & CHANNEL_FLAG ) ); - } + @Override + public boolean isActive() { + if (Platform.isClient()) { + return this.isPowered() + && (CHANNEL_FLAG == (this.getClientFlags() & CHANNEL_FLAG)); + } - return this.getProxy().isActive(); - } + return this.getProxy().isActive(); + } - @Override - public IGrid getGrid() - { - try - { - return this.getProxy().getGrid(); - } - catch( final GridAccessException e ) - { - return null; - } - } + @Override + public IGrid getGrid() { + try { + return this.getProxy().getGrid(); + } catch (final GridAccessException e) { + return null; + } + } - @Override - public boolean isPowered() - { - return POWERED_FLAG == ( this.getClientFlags() & POWERED_FLAG ); - } + @Override + public boolean isPowered() { + return POWERED_FLAG == (this.getClientFlags() & POWERED_FLAG); + } - public int getClientFlags() - { - return this.clientFlags; - } + public int getClientFlags() { + return this.clientFlags; + } - private void setClientFlags( final int clientFlags ) - { - this.clientFlags = clientFlags; - } + private void setClientFlags(final int clientFlags) { + this.clientFlags = clientFlags; + } } diff --git a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java index 592a7241..80410305 100644 --- a/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java +++ b/src/main/java/appeng/tile/powersink/AEBasePoweredTile.java @@ -18,8 +18,4 @@ package appeng.tile.powersink; - -public abstract class AEBasePoweredTile extends MekJoules -{ - -} +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 58fe2dd5..b0cdb72f 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 appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -31,202 +32,180 @@ import appeng.tile.events.TileEventType; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public abstract class AERootPoweredTile extends AEBaseInvTile implements IAEPowerStorage { + // values that determine general function, are set by inheriting classes if + // needed. These should generally remain static. + private double internalMaxPower = 10000; + private boolean internalPublicPowerStorage = false; + private AccessRestriction internalPowerFlow = AccessRestriction.READ_WRITE; + // the current power buffer. + private double internalCurrentPower = 0; + private EnumSet internalPowerSides + = EnumSet.allOf(ForgeDirection.class); + protected EnumSet getPowerSides() { + return this.internalPowerSides.clone(); + } -public abstract class AERootPoweredTile extends AEBaseInvTile implements IAEPowerStorage -{ + protected void setPowerSides(final EnumSet sides) { + this.internalPowerSides = sides; + // trigger re-calc! + } - // values that determine general function, are set by inheriting classes if - // needed. These should generally remain static. - private double internalMaxPower = 10000; - private boolean internalPublicPowerStorage = false; - private AccessRestriction internalPowerFlow = AccessRestriction.READ_WRITE; - // the current power buffer. - private double internalCurrentPower = 0; - private EnumSet internalPowerSides = EnumSet.allOf( ForgeDirection.class ); + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_AERootPoweredTile(final NBTTagCompound data) { + data.setDouble("internalCurrentPower", this.getInternalCurrentPower()); + } - protected EnumSet getPowerSides() - { - return this.internalPowerSides.clone(); - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_AERootPoweredTile(final NBTTagCompound data) { + this.setInternalCurrentPower(data.getDouble("internalCurrentPower")); + } - protected void setPowerSides( final EnumSet sides ) - { - this.internalPowerSides = sides; - // trigger re-calc! - } + protected final double + getExternalPowerDemand(final PowerUnits externalUnit, final double maxPowerRequired) { + return PowerUnits.AE.convertTo( + externalUnit, + Math.max( + 0.0, + this.getFunnelPowerDemand( + externalUnit.convertTo(PowerUnits.AE, maxPowerRequired) + ) + ) + ); + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_AERootPoweredTile( final NBTTagCompound data ) - { - data.setDouble( "internalCurrentPower", this.getInternalCurrentPower() ); - } + protected double getFunnelPowerDemand(final double maxRequired) { + return this.getInternalMaxPower() - this.getInternalCurrentPower(); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_AERootPoweredTile( final NBTTagCompound data ) - { - this.setInternalCurrentPower( data.getDouble( "internalCurrentPower" ) ); - } + public final double injectExternalPower(final PowerUnits input, final double amt) { + return PowerUnits.AE.convertTo( + input, + this.funnelPowerIntoStorage( + input.convertTo(PowerUnits.AE, amt), Actionable.MODULATE + ) + ); + } - protected final double getExternalPowerDemand( final PowerUnits externalUnit, final double maxPowerRequired ) - { - return PowerUnits.AE.convertTo( externalUnit, Math.max( 0.0, this.getFunnelPowerDemand( externalUnit.convertTo( PowerUnits.AE, maxPowerRequired ) ) ) ); - } + protected double funnelPowerIntoStorage(final double power, final Actionable mode) { + return this.injectAEPower(power, mode); + } - protected double getFunnelPowerDemand( final double maxRequired ) - { - return this.getInternalMaxPower() - this.getInternalCurrentPower(); - } + @Override + public final double injectAEPower(double amt, final Actionable mode) { + if (amt < 0.000001) { + return 0; + } - public final double injectExternalPower( final PowerUnits input, final double amt ) - { - return PowerUnits.AE.convertTo( input, this.funnelPowerIntoStorage( input.convertTo( PowerUnits.AE, amt ), Actionable.MODULATE ) ); - } + if (mode == Actionable.SIMULATE) { + final double fakeBattery = this.getInternalCurrentPower() + amt; - protected double funnelPowerIntoStorage( final double power, final Actionable mode ) - { - return this.injectAEPower( power, mode ); - } + if (fakeBattery > this.getInternalMaxPower()) { + return fakeBattery - this.getInternalMaxPower(); + } - @Override - public final double injectAEPower( double amt, final Actionable mode ) - { - if( amt < 0.000001 ) - { - return 0; - } + return 0; + } else { + if (this.getInternalCurrentPower() < 0.01 && amt > 0.01) { + this.PowerEvent(PowerEventType.PROVIDE_POWER); + } - if( mode == Actionable.SIMULATE ) - { - final double fakeBattery = this.getInternalCurrentPower() + amt; + this.setInternalCurrentPower(this.getInternalCurrentPower() + amt); + if (this.getInternalCurrentPower() > this.getInternalMaxPower()) { + amt = this.getInternalCurrentPower() - this.getInternalMaxPower(); + this.setInternalCurrentPower(this.getInternalMaxPower()); + return amt; + } - if( fakeBattery > this.getInternalMaxPower() ) - { - return fakeBattery - this.getInternalMaxPower(); - } + return 0; + } + } - return 0; - } - else - { - if( this.getInternalCurrentPower() < 0.01 && amt > 0.01 ) - { - this.PowerEvent( PowerEventType.PROVIDE_POWER ); - } + protected void PowerEvent(final PowerEventType x) { + // nothing. + } - this.setInternalCurrentPower( this.getInternalCurrentPower() + amt ); - if( this.getInternalCurrentPower() > this.getInternalMaxPower() ) - { - amt = this.getInternalCurrentPower() - this.getInternalMaxPower(); - this.setInternalCurrentPower( this.getInternalMaxPower() ); - return amt; - } + @Override + public final double getAEMaxPower() { + return this.getInternalMaxPower(); + } - return 0; - } - } + @Override + public final double getAECurrentPower() { + return this.getInternalCurrentPower(); + } - protected void PowerEvent( final PowerEventType x ) - { - // nothing. - } + @Override + public final boolean isAEPublicPowerStorage() { + return this.isInternalPublicPowerStorage(); + } - @Override - public final double getAEMaxPower() - { - return this.getInternalMaxPower(); - } + @Override + public final AccessRestriction getPowerFlow() { + return this.getInternalPowerFlow(); + } - @Override - public final double getAECurrentPower() - { - return this.getInternalCurrentPower(); - } + @Override + public final double extractAEPower( + final double amt, final Actionable mode, final PowerMultiplier multiplier + ) { + return multiplier.divide(this.extractAEPower(multiplier.multiply(amt), mode)); + } - @Override - public final boolean isAEPublicPowerStorage() - { - return this.isInternalPublicPowerStorage(); - } + protected double extractAEPower(double amt, final Actionable mode) { + if (mode == Actionable.SIMULATE) { + if (this.getInternalCurrentPower() > amt) { + return amt; + } + return this.getInternalCurrentPower(); + } - @Override - public final AccessRestriction getPowerFlow() - { - return this.getInternalPowerFlow(); - } + final boolean wasFull + = this.getInternalCurrentPower() >= this.getInternalMaxPower() - 0.001; + if (wasFull && amt > 0.001) { + this.PowerEvent(PowerEventType.REQUEST_POWER); + } - @Override - public final double extractAEPower( final double amt, final Actionable mode, final PowerMultiplier multiplier ) - { - return multiplier.divide( this.extractAEPower( multiplier.multiply( amt ), mode ) ); - } + if (this.getInternalCurrentPower() > amt) { + this.setInternalCurrentPower(this.getInternalCurrentPower() - amt); + return amt; + } - protected double extractAEPower( double amt, final Actionable mode ) - { - if( mode == Actionable.SIMULATE ) - { - if( this.getInternalCurrentPower() > amt ) - { - return amt; - } - return this.getInternalCurrentPower(); - } + amt = this.getInternalCurrentPower(); + this.setInternalCurrentPower(0); + return amt; + } - final boolean wasFull = this.getInternalCurrentPower() >= this.getInternalMaxPower() - 0.001; - if( wasFull && amt > 0.001 ) - { - this.PowerEvent( PowerEventType.REQUEST_POWER ); - } + public double getInternalCurrentPower() { + return this.internalCurrentPower; + } - if( this.getInternalCurrentPower() > amt ) - { - this.setInternalCurrentPower( this.getInternalCurrentPower() - amt ); - return amt; - } + public void setInternalCurrentPower(final double internalCurrentPower) { + this.internalCurrentPower = internalCurrentPower; + } - amt = this.getInternalCurrentPower(); - this.setInternalCurrentPower( 0 ); - return amt; - } + public double getInternalMaxPower() { + return this.internalMaxPower; + } - public double getInternalCurrentPower() - { - return this.internalCurrentPower; - } + public void setInternalMaxPower(final double internalMaxPower) { + this.internalMaxPower = internalMaxPower; + } - public void setInternalCurrentPower( final double internalCurrentPower ) - { - this.internalCurrentPower = internalCurrentPower; - } + private boolean isInternalPublicPowerStorage() { + return this.internalPublicPowerStorage; + } - public double getInternalMaxPower() - { - return this.internalMaxPower; - } + public void setInternalPublicPowerStorage(final boolean internalPublicPowerStorage) { + this.internalPublicPowerStorage = internalPublicPowerStorage; + } - public void setInternalMaxPower( final double internalMaxPower ) - { - this.internalMaxPower = internalMaxPower; - } + private AccessRestriction getInternalPowerFlow() { + return this.internalPowerFlow; + } - private boolean isInternalPublicPowerStorage() - { - return this.internalPublicPowerStorage; - } - - public void setInternalPublicPowerStorage( final boolean internalPublicPowerStorage ) - { - this.internalPublicPowerStorage = internalPublicPowerStorage; - } - - private AccessRestriction getInternalPowerFlow() - { - return this.internalPowerFlow; - } - - public void setInternalPowerFlow( final AccessRestriction internalPowerFlow ) - { - this.internalPowerFlow = internalPowerFlow; - } + public void setInternalPowerFlow(final AccessRestriction internalPowerFlow) { + this.internalPowerFlow = internalPowerFlow; + } } diff --git a/src/main/java/appeng/tile/powersink/IC2.java b/src/main/java/appeng/tile/powersink/IC2.java index b7539337..ecb40d6c 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 appeng.api.config.PowerUnits; import appeng.integration.IntegrationRegistry; @@ -29,95 +30,83 @@ import ic2.api.energy.tile.IEnergySink; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +@Interface(iname = IntegrationType.IC2, iface = "ic2.api.energy.tile.IEnergySink") +public abstract class IC2 extends AERootPoweredTile implements IEnergySink { + private boolean isInIC2 = false; + @Override + public final boolean + acceptsEnergyFrom(final TileEntity emitter, final ForgeDirection direction) { + return this.getPowerSides().contains(direction); + } -@Interface( iname = IntegrationType.IC2, iface = "ic2.api.energy.tile.IEnergySink" ) -public abstract class IC2 extends AERootPoweredTile implements IEnergySink -{ + @Override + public final double getDemandedEnergy() { + return this.getExternalPowerDemand(PowerUnits.EU, Double.MAX_VALUE); + } - private boolean isInIC2 = false; + @Override + public final int getSinkTier() { + return Integer.MAX_VALUE; + } - @Override - public final boolean acceptsEnergyFrom( final TileEntity emitter, final ForgeDirection direction ) - { - return this.getPowerSides().contains( direction ); - } + @Override + public final double injectEnergy( + final ForgeDirection directionFrom, final double amount, final double voltage + ) { + // just store the excess in the current block, if I return the waste, + // IC2 will just disintegrate it - Oct 20th 2013 + final double overflow = PowerUnits.EU.convertTo( + PowerUnits.AE, this.injectExternalPower(PowerUnits.EU, amount) + ); + this.setInternalCurrentPower(this.getInternalCurrentPower() + overflow); + return 0; // see above comment. + } - @Override - public final double getDemandedEnergy() - { - return this.getExternalPowerDemand( PowerUnits.EU, Double.MAX_VALUE ); - } + @Override + public void invalidate() { + super.invalidate(); + this.removeFromENet(); + } - @Override - public final int getSinkTier() - { - return Integer.MAX_VALUE; - } + private void removeFromENet() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.IC2)) { + final IIC2 ic2Integration + = (IIC2) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.IC2); + if (this.isInIC2 && Platform.isServer() && ic2Integration != null) { + ic2Integration.removeFromEnergyNet(this); + this.isInIC2 = false; + } + } + } - @Override - public final double injectEnergy( final ForgeDirection directionFrom, final double amount, final double voltage ) - { - // just store the excess in the current block, if I return the waste, - // IC2 will just disintegrate it - Oct 20th 2013 - final double overflow = PowerUnits.EU.convertTo( PowerUnits.AE, this.injectExternalPower( PowerUnits.EU, amount ) ); - this.setInternalCurrentPower( this.getInternalCurrentPower() + overflow ); - return 0; // see above comment. - } + @Override + public void onChunkUnload() { + super.onChunkUnload(); + this.removeFromENet(); + } - @Override - public void invalidate() - { - super.invalidate(); - this.removeFromENet(); - } + @Override + public void onReady() { + super.onReady(); + this.addToENet(); + } - private void removeFromENet() - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - final IIC2 ic2Integration = (IIC2) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.IC2 ); - if( this.isInIC2 && Platform.isServer() && ic2Integration != null ) - { - ic2Integration.removeFromEnergyNet( this ); - this.isInIC2 = false; - } - } - } + private void addToENet() { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.IC2)) { + final IIC2 ic2Integration + = (IIC2) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.IC2); + if (!this.isInIC2 && Platform.isServer() && ic2Integration != null) { + ic2Integration.addToEnergyNet(this); + this.isInIC2 = true; + } + } + } - @Override - public void onChunkUnload() - { - super.onChunkUnload(); - this.removeFromENet(); - } - - @Override - public void onReady() - { - super.onReady(); - this.addToENet(); - } - - private void addToENet() - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.IC2 ) ) - { - final IIC2 ic2Integration = (IIC2) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.IC2 ); - if( !this.isInIC2 && Platform.isServer() && ic2Integration != null ) - { - ic2Integration.addToEnergyNet( this ); - this.isInIC2 = true; - } - } - } - - @Override - protected void setPowerSides( final EnumSet sides ) - { - super.setPowerSides( sides ); - this.removeFromENet(); - this.addToENet(); - } + @Override + protected void setPowerSides(final EnumSet sides) { + 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 60ca31c8..7e5c19ac 100644 --- a/src/main/java/appeng/tile/powersink/MekJoules.java +++ b/src/main/java/appeng/tile/powersink/MekJoules.java @@ -18,53 +18,48 @@ package appeng.tile.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; import mekanism.api.energy.IStrictEnergyAcceptor; import net.minecraftforge.common.util.ForgeDirection; +@Interface( + iname = IntegrationType.Mekanism, iface = "mekanism.api.energy.IStrictEnergyAcceptor" +) +public abstract class MekJoules extends RedstoneFlux implements IStrictEnergyAcceptor { + @Override + public double getEnergy() { + return 0; + } -@Interface( iname = IntegrationType.Mekanism, iface = "mekanism.api.energy.IStrictEnergyAcceptor" ) -public abstract class MekJoules extends RedstoneFlux implements IStrictEnergyAcceptor -{ + @Override + public void setEnergy(final double energy) { + final double extra = this.injectExternalPower(PowerUnits.MK, energy); + this.setInternalCurrentPower( + this.getInternalCurrentPower() + PowerUnits.MK.convertTo(PowerUnits.AE, extra) + ); + } - @Override - public double getEnergy() - { - return 0; - } + @Override + public double getMaxEnergy() { + return this.getExternalPowerDemand(PowerUnits.MK, 100000); + } - @Override - public void setEnergy( final double energy ) - { - final double extra = this.injectExternalPower( PowerUnits.MK, energy ); - this.setInternalCurrentPower( this.getInternalCurrentPower() + PowerUnits.MK.convertTo( PowerUnits.AE, extra ) ); - } + @Override + public double transferEnergyToAcceptor(final ForgeDirection side, double amount) { + final double demand + = this.getExternalPowerDemand(PowerUnits.MK, Double.MAX_VALUE); + if (amount > demand) { + amount = demand; + } - @Override - public double getMaxEnergy() - { - return this.getExternalPowerDemand( PowerUnits.MK, 100000 ); - } + final double overflow = this.injectExternalPower(PowerUnits.MK, amount); + return amount - overflow; + } - @Override - public double transferEnergyToAcceptor( final ForgeDirection side, double amount ) - { - final double demand = this.getExternalPowerDemand( PowerUnits.MK, Double.MAX_VALUE ); - if( amount > demand ) - { - amount = demand; - } - - final double overflow = this.injectExternalPower( PowerUnits.MK, amount ); - return amount - overflow; - } - - @Override - public boolean canReceiveEnergy( final ForgeDirection side ) - { - return this.getPowerSides().contains( side ); - } + @Override + public boolean canReceiveEnergy(final 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 8d89af7e..1329e3ed 100644 --- a/src/main/java/appeng/tile/powersink/RedstoneFlux.java +++ b/src/main/java/appeng/tile/powersink/RedstoneFlux.java @@ -18,46 +18,43 @@ package appeng.tile.powersink; - import appeng.api.config.PowerUnits; import appeng.integration.IntegrationType; import appeng.transformer.annotations.Integration.Interface; import cofh.api.energy.IEnergyReceiver; import net.minecraftforge.common.util.ForgeDirection; +@Interface(iname = IntegrationType.RF, iface = "cofh.api.energy.IEnergyReceiver") +public abstract class RedstoneFlux extends RotaryCraft implements IEnergyReceiver { + @Override + public final int receiveEnergy( + final ForgeDirection from, final int maxReceive, final boolean simulate + ) { + final int networkRFDemand + = (int) Math.floor(this.getExternalPowerDemand(PowerUnits.RF, maxReceive)); + final int usedRF = Math.min(maxReceive, networkRFDemand); -@Interface( iname = IntegrationType.RF, iface = "cofh.api.energy.IEnergyReceiver" ) -public abstract class RedstoneFlux extends RotaryCraft implements IEnergyReceiver -{ - @Override - public final int receiveEnergy( final ForgeDirection from, final int maxReceive, final boolean simulate ) - { - final int networkRFDemand = (int) Math.floor( this.getExternalPowerDemand( PowerUnits.RF, maxReceive ) ); - final int usedRF = Math.min( maxReceive, networkRFDemand ); + if (!simulate) { + this.injectExternalPower(PowerUnits.RF, usedRF); + } - if( !simulate ) - { - this.injectExternalPower( PowerUnits.RF, usedRF ); - } + return usedRF; + } - return usedRF; - } + @Override + public final int getEnergyStored(final ForgeDirection from) { + return (int + ) Math.floor(PowerUnits.AE.convertTo(PowerUnits.RF, this.getAECurrentPower())); + } - @Override - public final int getEnergyStored( final ForgeDirection from ) - { - return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAECurrentPower() ) ); - } + @Override + public final int getMaxEnergyStored(final ForgeDirection from) { + return (int + ) Math.floor(PowerUnits.AE.convertTo(PowerUnits.RF, this.getAEMaxPower())); + } - @Override - public final int getMaxEnergyStored( final ForgeDirection from ) - { - return (int) Math.floor( PowerUnits.AE.convertTo( PowerUnits.RF, this.getAEMaxPower() ) ); - } - - @Override - public final boolean canConnectEnergy( final ForgeDirection from ) - { - return this.getPowerSides().contains( from ); - } + @Override + public final boolean canConnectEnergy(final ForgeDirection from) { + return this.getPowerSides().contains(from); + } } diff --git a/src/main/java/appeng/tile/powersink/RotaryCraft.java b/src/main/java/appeng/tile/powersink/RotaryCraft.java index b588e011..85b8e8a6 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 java.util.ArrayList; import Reika.RotaryCraft.API.Interfaces.Transducerable; import Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver; @@ -31,153 +32,126 @@ import appeng.transformer.annotations.Integration.Method; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; - - @InterfaceList( value = { @Interface( iname = IntegrationType.RotaryCraft, iface = "Reika.RotaryCraft.API.Power.AdvancedShaftPowerReceiver" ), @Interface( iname = IntegrationType.RotaryCraft, iface = "Reika.RotaryCraft.API.Interfaces.Transducerable" ) } ) public abstract class RotaryCraft extends IC2 implements AdvancedShaftPowerReceiver, Transducerable { + private int omega = 0; + private int torque = 0; + private long power = 0; + private int alpha = 0; - private int omega = 0; - private int torque = 0; - private long power = 0; - private int alpha = 0; + private long currentPower = 0; - private long currentPower = 0; + @TileEvent(TileEventType.TICK) + @Method(iname = IntegrationType.RotaryCraft) + public void Tick_RotaryCraft() { + if (this.worldObj != null && !this.worldObj.isRemote && this.currentPower > 0) { + this.injectExternalPower(PowerUnits.WA, this.currentPower); + this.currentPower = 0; + } + } - @TileEvent( TileEventType.TICK ) - @Method( iname = IntegrationType.RotaryCraft ) - public void Tick_RotaryCraft() - { - if( this.worldObj != null && !this.worldObj.isRemote && this.currentPower > 0 ) - { - this.injectExternalPower( PowerUnits.WA, this.currentPower ); - this.currentPower = 0; - } - } + @Override + public final boolean addPower( + final int torque, final int omega, final long power, final ForgeDirection side + ) { + this.omega = omega; + this.torque = torque; + this.power = power; - @Override - public final boolean addPower( final int torque, final int omega, final long power, final ForgeDirection side ) - { - this.omega = omega; - this.torque = torque; - this.power = power; + this.currentPower += power; - this.currentPower += power; + return true; + } - return true; + @Override + public final int getOmega() { + return this.omega; + } - } + @Override + public final int getTorque() { + return this.torque; + } - @Override - public final int getOmega() - { - return this.omega; - } + @Override + public final long getPower() { + return this.power; + } - @Override - public final int getTorque() - { - return this.torque; - } + @Override + public final String getName() { + return "AE"; + } - @Override - public final long getPower() - { - return this.power; - } + @Override + public final int getIORenderAlpha() { + return this.alpha; + } - @Override - public final String getName() - { - return "AE"; - } + @Override + public final void setIORenderAlpha(final int io) { + this.alpha = io; + } - @Override - public final int getIORenderAlpha() - { - return this.alpha; - } + public final boolean canReadFromBlock(final int x, final int y, final int z) { + ForgeDirection side = ForgeDirection.UNKNOWN; - @Override - public final void setIORenderAlpha( final int io ) - { - this.alpha = io; - } + 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; + } - public final boolean canReadFromBlock( final int x, final int y, final int z ) - { - ForgeDirection side = ForgeDirection.UNKNOWN; + return this.getPowerSides().contains(side); + } - 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; - } + @Override + public final boolean canReadFrom(final ForgeDirection side) { + return this.getPowerSides().contains(side); + } - return this.getPowerSides().contains( side ); - } + @Override + public final boolean isReceiving() { + return true; + } - @Override - public final boolean canReadFrom( final ForgeDirection side ) - { - return this.getPowerSides().contains( side ); - } + @Override + public final int getMinTorque(final int available) { + return 1; + } - @Override - public final boolean isReceiving() - { - return true; - } + @Override + public final ArrayList getMessages( + final World world, final int x, final int y, final int z, final int side + ) { + final String out; + if (this.power >= 1000000000) { + out = String.format( + "Receiving %.3f GW @ %d rad/s.", this.power / 1000000000.0D, this.omega + ); + } else if (this.power >= 1000000) { + out = String.format( + "Receiving %.3f MW @ %d rad/s.", this.power / 1000000.0D, this.omega + ); + } else if (this.power >= 1000) { + out = String.format( + "Receiving %.3f kW @ %d rad/s.", this.power / 1000.0D, this.omega + ); + } else { + out = String.format("Receiving %d W @ %d rad/s.", this.power, this.omega); + } - @Override - public final int getMinTorque( final int available ) - { - return 1; - } - - @Override - public final ArrayList getMessages( final World world, final int x, final int y, final int z, final int side ) - { - final String out; - if( this.power >= 1000000000 ) - { - out = String.format( "Receiving %.3f GW @ %d rad/s.", this.power / 1000000000.0D, this.omega ); - } - else if( this.power >= 1000000 ) - { - out = String.format( "Receiving %.3f MW @ %d rad/s.", this.power / 1000000.0D, this.omega ); - } - else if( this.power >= 1000 ) - { - out = String.format( "Receiving %.3f kW @ %d rad/s.", this.power / 1000.0D, this.omega ); - } - else - { - out = String.format( "Receiving %d W @ %d rad/s.", this.power, this.omega ); - } - - final ArrayList messages = new ArrayList( 1 ); - messages.add( out ); - return messages; - } + final ArrayList messages = new ArrayList(1); + messages.add(out); + return messages; + } } diff --git a/src/main/java/appeng/tile/powersink/UniversalElectricity.java b/src/main/java/appeng/tile/powersink/UniversalElectricity.java index 86f02773..3a8334fc 100644 --- a/src/main/java/appeng/tile/powersink/UniversalElectricity.java +++ b/src/main/java/appeng/tile/powersink/UniversalElectricity.java @@ -18,13 +18,13 @@ package appeng.tile.powersink; - /* * import net.minecraftforge.common.util.ForgeDirection; * import universalelectricity.core.block.IElectrical; * import universalelectricity.core.electricity.ElectricityPack; * import appeng.api.config.PowerUnits; - * public abstract class UniversalElectricity extends ThermalExpansion implements IElectrical + * public abstract class UniversalElectricity extends ThermalExpansion implements + * IElectrical * { * @Override * public final boolean canConnect(ForgeDirection direction) @@ -32,13 +32,15 @@ package appeng.tile.powersink; * return internalCanAcceptPower && getPowerSides().contains( direction ); * } * @Override - * public final float receiveElectricity(ForgeDirection from, ElectricityPack receive, boolean doReceive) + * public final float receiveElectricity(ForgeDirection from, ElectricityPack receive, + * boolean doReceive) * { * float accepted = 0; * double receivedPower = receive.getWatts(); * if ( doReceive ) * { - * accepted = (float) (receivedPower - injectExternalPower( PowerUnits.KJ, receivedPower )); + * accepted = (float) (receivedPower - injectExternalPower( PowerUnits.KJ, receivedPower + * )); * } * else * { @@ -61,7 +63,8 @@ package appeng.tile.powersink; * return 120; * } * @Override - * public final ElectricityPack provideElectricity(ForgeDirection from, ElectricityPack request, boolean doProvide) + * public final ElectricityPack provideElectricity(ForgeDirection from, ElectricityPack + * request, boolean doProvide) * { * return null; // cannot be dis-charged * } diff --git a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java index bfe76bc4..93c7ff17 100644 --- a/src/main/java/appeng/tile/qnb/TileQuantumBridge.java +++ b/src/main/java/appeng/tile/qnb/TileQuantumBridge.java @@ -18,6 +18,7 @@ package appeng.tile.qnb; +import java.util.EnumSet; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -46,296 +47,254 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock { + private final byte corner = 16; + private final int[] sidesRing = {}; + private final int[] sidesLink = { 0 }; + private final AppEngInternalInventory internalInventory + = new AppEngInternalInventory(this, 1); + private final byte hasSingularity = 32; + private final byte powered = 64; + private final QuantumCalculator calc = new QuantumCalculator(this); + private byte constructed = -1; + private QuantumCluster cluster; + private boolean updateStatus = false; -public class TileQuantumBridge extends AENetworkInvTile implements IAEMultiBlock -{ - private final byte corner = 16; - private final int[] sidesRing = {}; - private final int[] sidesLink = { 0 }; - private final AppEngInternalInventory internalInventory = new AppEngInternalInventory( this, 1 ); - private final byte hasSingularity = 32; - private final byte powered = 64; + public TileQuantumBridge() { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + this.getProxy().setFlags(GridFlags.DENSE_CAPACITY); + this.getProxy().setIdlePowerUsage(22); + this.internalInventory.setMaxStackSize(1); + } - private final QuantumCalculator calc = new QuantumCalculator( this ); - private byte constructed = -1; - private QuantumCluster cluster; - private boolean updateStatus = false; + @TileEvent(TileEventType.TICK) + public void onTickEvent() { + if (this.updateStatus) { + this.updateStatus = false; + if (this.cluster != null) { + this.cluster.updateStatus(true); + } + this.markForUpdate(); + } + } - public TileQuantumBridge() - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - this.getProxy().setFlags( GridFlags.DENSE_CAPACITY ); - this.getProxy().setIdlePowerUsage( 22 ); - this.internalInventory.setMaxStackSize( 1 ); - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void onNetworkWriteEvent(final ByteBuf data) { + int out = this.constructed; - @TileEvent( TileEventType.TICK ) - public void onTickEvent() - { - if( this.updateStatus ) - { - this.updateStatus = false; - if( this.cluster != null ) - { - this.cluster.updateStatus( true ); - } - this.markForUpdate(); - } - } + if (this.getStackInSlot(0) != null && this.constructed != -1) { + out |= this.hasSingularity; + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void onNetworkWriteEvent( final ByteBuf data ) - { - int out = this.constructed; + if (this.getProxy().isActive() && this.constructed != -1) { + out |= this.powered; + } - if( this.getStackInSlot( 0 ) != null && this.constructed != -1 ) - { - out |= this.hasSingularity; - } + data.writeByte((byte) out); + } - if( this.getProxy().isActive() && this.constructed != -1 ) - { - out |= this.powered; - } + @TileEvent(TileEventType.NETWORK_READ) + public boolean onNetworkReadEvent(final ByteBuf data) { + final int oldValue = this.constructed; + this.constructed = data.readByte(); + return this.constructed != oldValue; + } - data.writeByte( (byte) out ); - } + @Override + public IInventory getInternalInventory() { + return this.internalInventory; + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean onNetworkReadEvent( final ByteBuf data ) - { - final int oldValue = this.constructed; - this.constructed = data.readByte(); - return this.constructed != oldValue; - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + if (this.cluster != null) { + this.cluster.updateStatus(true); + } + } - @Override - public IInventory getInternalInventory() - { - return this.internalInventory; - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + if (this.isCenter()) { + return this.sidesLink; + } + return this.sidesRing; + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.cluster != null ) - { - this.cluster.updateStatus( true ); - } - } + private boolean isCenter() { + for (final Block link : + AEApi.instance().definitions().blocks().quantumLink().maybeBlock().asSet()) { + return this.getBlockType() == link; + } - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - if( this.isCenter() ) - { - return this.sidesLink; - } - return this.sidesRing; - } + return false; + } - private boolean isCenter() - { - for( final Block link : AEApi.instance().definitions().blocks().quantumLink().maybeBlock().asSet() ) - { - return this.getBlockType() == link; - } + @MENetworkEventSubscribe + public void onPowerStatusChange(final MENetworkPowerStatusChange c) { + this.updateStatus = true; + } - return false; - } + @Override + public void onChunkUnload() { + this.disconnect(false); + super.onChunkUnload(); + } - @MENetworkEventSubscribe - public void onPowerStatusChange( final MENetworkPowerStatusChange c ) - { - this.updateStatus = true; - } + @Override + public void onReady() { + super.onReady(); - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } + final IBlockDefinition quantumRing + = AEApi.instance().definitions().blocks().quantumRing(); + final Optional maybeLinkBlock = quantumRing.maybeBlock(); + final Optional maybeLinkStack = quantumRing.maybeStack(1); - @Override - public void onReady() - { - super.onReady(); + final boolean isPresent + = maybeLinkBlock.isPresent() && maybeLinkStack.isPresent(); - final IBlockDefinition quantumRing = AEApi.instance().definitions().blocks().quantumRing(); - final Optional maybeLinkBlock = quantumRing.maybeBlock(); - final Optional maybeLinkStack = quantumRing.maybeStack( 1 ); + if (isPresent && this.getBlockType() == maybeLinkBlock.get()) { + final ItemStack linkStack = maybeLinkStack.get(); - final boolean isPresent = maybeLinkBlock.isPresent() && maybeLinkStack.isPresent(); + this.getProxy().setVisualRepresentation(linkStack); + } + } - if( isPresent && this.getBlockType() == maybeLinkBlock.get() ) - { - final ItemStack linkStack = maybeLinkStack.get(); + @Override + public void invalidate() { + this.disconnect(false); + super.invalidate(); + } - this.getProxy().setVisualRepresentation( linkStack ); - } - } + @Override + public void disconnect(final boolean affectWorld) { + if (this.cluster != null) { + if (!affectWorld) { + this.cluster.setUpdateStatus(false); + } - @Override - public void invalidate() - { - this.disconnect( false ); - super.invalidate(); - } + this.cluster.destroy(); + } - @Override - public void disconnect( final boolean affectWorld ) - { - if( this.cluster != null ) - { - if( !affectWorld ) - { - this.cluster.setUpdateStatus( false ); - } + this.cluster = null; - this.cluster.destroy(); - } + if (affectWorld) { + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } + } - this.cluster = null; + @Override + public IAECluster getCluster() { + return this.cluster; + } - if( affectWorld ) - { - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } - } + @Override + public boolean isValid() { + return !this.isInvalid(); + } - @Override - public IAECluster getCluster() - { - return this.cluster; - } + public void + updateStatus(final QuantumCluster c, final byte flags, final boolean affectWorld) { + this.cluster = c; - @Override - public boolean isValid() - { - return !this.isInvalid(); - } + if (affectWorld) { + if (this.constructed != flags) { + this.constructed = flags; + this.markForUpdate(); + } - public void updateStatus( final QuantumCluster c, final byte flags, final boolean affectWorld ) - { - this.cluster = c; + if (this.isCorner() || this.isCenter()) { + this.getProxy().setValidSides(this.getConnections()); + } else { + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); + } + } + } - if( affectWorld ) - { - if( this.constructed != flags ) - { - this.constructed = flags; - this.markForUpdate(); - } + public boolean isCorner() { + return (this.constructed & this.getCorner()) == this.getCorner() + && this.constructed != -1; + } - if( this.isCorner() || this.isCenter() ) - { - this.getProxy().setValidSides( this.getConnections() ); - } - else - { - this.getProxy().setValidSides( EnumSet.allOf( ForgeDirection.class ) ); - } - } - } + public EnumSet getConnections() { + final EnumSet set = EnumSet.noneOf(ForgeDirection.class); - public boolean isCorner() - { - return ( this.constructed & this.getCorner() ) == this.getCorner() && this.constructed != -1; - } + for (final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS) { + final TileEntity te = this.worldObj.getTileEntity( + this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ + ); + if (te instanceof TileQuantumBridge) { + set.add(d); + } + } - public EnumSet getConnections() - { - final EnumSet set = EnumSet.noneOf( ForgeDirection.class ); + return set; + } - for( final ForgeDirection d : ForgeDirection.VALID_DIRECTIONS ) - { - final TileEntity te = this.worldObj.getTileEntity( this.xCoord + d.offsetX, this.yCoord + d.offsetY, this.zCoord + d.offsetZ ); - if( te instanceof TileQuantumBridge ) - { - set.add( d ); - } - } + public long getQEFrequency() { + final ItemStack is = this.internalInventory.getStackInSlot(0); + if (is != null) { + final NBTTagCompound c = is.getTagCompound(); + if (c != null) { + return c.getLong("freq"); + } + } + return 0; + } - return set; - } + public boolean isPowered() { + if (Platform.isClient()) { + return (this.constructed & this.powered) == this.powered + && this.constructed != -1; + } - public long getQEFrequency() - { - final ItemStack is = this.internalInventory.getStackInSlot( 0 ); - if( is != null ) - { - final NBTTagCompound c = is.getTagCompound(); - if( c != null ) - { - return c.getLong( "freq" ); - } - } - return 0; - } + try { + return this.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException e) { + // :P + } - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.constructed & this.powered ) == this.powered && this.constructed != -1; - } + return false; + } - try - { - return this.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException e ) - { - // :P - } + public boolean isFormed() { + return this.constructed != -1; + } - return false; - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.DENSE; + } - public boolean isFormed() - { - return this.constructed != -1; - } + public void neighborUpdate() { + this.calc.calculateMultiblock(this.worldObj, this.getLocation()); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.DENSE; - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - public void neighborUpdate() - { - this.calc.calculateMultiblock( this.worldObj, this.getLocation() ); - } + public boolean hasQES() { + if (this.constructed == -1) { + return false; + } + return (this.constructed & this.hasSingularity) == this.hasSingularity; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + public void breakCluster() { + if (this.cluster != null) { + this.cluster.destroy(); + } + } - public boolean hasQES() - { - if( this.constructed == -1 ) - { - return false; - } - return ( this.constructed & this.hasSingularity ) == this.hasSingularity; - } - - public void breakCluster() - { - if( this.cluster != null ) - { - this.cluster.destroy(); - } - } - - public byte getCorner() - { - return this.corner; - } + public byte getCorner() { + return this.corner; + } } diff --git a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java index 2881cb62..045e548e 100644 --- a/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java +++ b/src/main/java/appeng/tile/spatial/TileSpatialIOPort.java @@ -18,7 +18,6 @@ package appeng.tile.spatial; - import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; import appeng.api.config.YesNo; @@ -47,160 +46,148 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +public class TileSpatialIOPort extends AENetworkInvTile implements IWorldCallable { + private final int[] sides = { 0, 1 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 2); + private YesNo lastRedstoneState = YesNo.UNDECIDED; -public class TileSpatialIOPort extends AENetworkInvTile implements IWorldCallable -{ + public TileSpatialIOPort() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } - private final int[] sides = { 0, 1 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 2 ); - private YesNo lastRedstoneState = YesNo.UNDECIDED; + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileSpatialIOPort(final NBTTagCompound data) { + data.setInteger("lastRedstoneState", this.lastRedstoneState.ordinal()); + } - public TileSpatialIOPort() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileSpatialIOPort(final NBTTagCompound data) { + if (data.hasKey("lastRedstoneState")) { + this.lastRedstoneState = YesNo.values()[data.getInteger("lastRedstoneState")]; + } + } - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileSpatialIOPort( final NBTTagCompound data ) - { - data.setInteger( "lastRedstoneState", this.lastRedstoneState.ordinal() ); - } + public boolean getRedstoneState() { + if (this.lastRedstoneState == YesNo.UNDECIDED) { + this.updateRedstoneState(); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileSpatialIOPort( final NBTTagCompound data ) - { - if( data.hasKey( "lastRedstoneState" ) ) - { - this.lastRedstoneState = YesNo.values()[data.getInteger( "lastRedstoneState" )]; - } - } + return this.lastRedstoneState == YesNo.YES; + } - public boolean getRedstoneState() - { - if( this.lastRedstoneState == YesNo.UNDECIDED ) - { - this.updateRedstoneState(); - } + public void updateRedstoneState() { + final 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(); + } + } + } - return this.lastRedstoneState == YesNo.YES; - } + private void triggerTransition() { + if (Platform.isServer()) { + final ItemStack cell = this.getStackInSlot(0); + if (this.isSpatialCell(cell)) { + TickHandler.INSTANCE.addCallable( + null, this + ); // this needs to be cross world synced. + } + } + } - public void updateRedstoneState() - { - final 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 boolean isSpatialCell(final ItemStack cell) { + if (cell != null && cell.getItem() instanceof ISpatialStorageCell) { + final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); + return sc != null && sc.isSpatialStorage(cell); + } + return false; + } - private void triggerTransition() - { - if( Platform.isServer() ) - { - final ItemStack cell = this.getStackInSlot( 0 ); - if( this.isSpatialCell( cell ) ) - { - TickHandler.INSTANCE.addCallable( null, this );// this needs to be cross world synced. - } - } - } + @Override + public Void call(final World world) throws Exception { + final ItemStack cell = this.getStackInSlot(0); + if (this.isSpatialCell(cell) && this.getStackInSlot(1) == null) { + final IGrid gi = this.getProxy().getGrid(); + final IEnergyGrid energy = this.getProxy().getEnergy(); - private boolean isSpatialCell( final ItemStack cell ) - { - if( cell != null && cell.getItem() instanceof ISpatialStorageCell ) - { - final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); - return sc != null && sc.isSpatialStorage( cell ); - } - return false; - } + final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); - @Override - public Void call( final World world ) throws Exception - { - final ItemStack cell = this.getStackInSlot( 0 ); - if( this.isSpatialCell( cell ) && this.getStackInSlot( 1 ) == null ) - { - final IGrid gi = this.getProxy().getGrid(); - final IEnergyGrid energy = this.getProxy().getEnergy(); + final SpatialPylonCache spc = gi.getCache(ISpatialCache.class); + if (spc.hasRegion() && spc.isValidRegion()) { + final double req = spc.requiredPower(); + final double pr = energy.extractAEPower( + req, Actionable.SIMULATE, PowerMultiplier.CONFIG + ); + if (Math.abs(pr - req) < req * 0.001) { + final MENetworkEvent res + = gi.postEvent(new MENetworkSpatialEvent(this, req)); + if (!res.isCanceled()) { + final TransitionResult tr = sc.doSpatialTransition( + cell, this.worldObj, spc.getMin(), spc.getMax(), true + ); + if (tr.success) { + energy.extractAEPower( + req, Actionable.MODULATE, PowerMultiplier.CONFIG + ); + this.setInventorySlotContents(0, null); + this.setInventorySlotContents(1, cell); + } + } + } + } + } - final ISpatialStorageCell sc = (ISpatialStorageCell) cell.getItem(); + return null; + } - final SpatialPylonCache spc = gi.getCache( ISpatialCache.class ); - if( spc.hasRegion() && spc.isValidRegion() ) - { - final double req = spc.requiredPower(); - final double pr = energy.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if( Math.abs( pr - req ) < req * 0.001 ) - { - final MENetworkEvent res = gi.postEvent( new MENetworkSpatialEvent( this, req ) ); - if( !res.isCanceled() ) - { - final TransitionResult tr = sc.doSpatialTransition( cell, this.worldObj, spc.getMin(), spc.getMax(), true ); - if( tr.success ) - { - energy.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); - this.setInventorySlotContents( 0, null ); - this.setInventorySlotContents( 1, cell ); - } - } - } - } - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } - return null; - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } + @Override + public IInventory getInternalInventory() { + return this.inv; + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return (i == 0 && this.isSpatialCell(itemstack)); + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) {} - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return ( i == 0 && this.isSpatialCell( itemstack ) ); - } + @Override + public boolean + canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + return this.isItemValidForSlot(slotIndex, insertingItem); + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex == 1; + } - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - return this.isItemValidForSlot( slotIndex, insertingItem ); - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex == 1; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } + @Override + public int[] getAccessibleSlotsBySide(final 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 452dd58c..c9a47c61 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 appeng.api.networking.GridFlags; import appeng.api.networking.events.MENetworkChannelsChanged; @@ -35,214 +36,179 @@ import appeng.tile.grid.AENetworkTile; import io.netty.buffer.ByteBuf; import net.minecraftforge.common.util.ForgeDirection; -import java.util.EnumSet; +public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock { + public static final int DISPLAY_END_MIN = 0x01; + public static final int DISPLAY_END_MAX = 0x02; + public static final int DISPLAY_MIDDLE = 0x01 + 0x02; + public static final int DISPLAY_X = 0x04; + public static final int DISPLAY_Y = 0x08; + public static final int DISPLAY_Z = 0x04 + 0x08; + public static final int MB_STATUS = 0x01 + 0x02 + 0x04 + 0x08; + public static final int DISPLAY_ENABLED = 0x10; + public static final int DISPLAY_POWERED_ENABLED = 0x20; + public static final int NET_STATUS = 0x10 + 0x20; -public class TileSpatialPylon extends AENetworkTile implements IAEMultiBlock -{ + private final SpatialPylonCalculator calc = new SpatialPylonCalculator(this); + private int displayBits = 0; + private SpatialPylonCluster cluster; + private boolean didHaveLight = false; - public static final int DISPLAY_END_MIN = 0x01; - public static final int DISPLAY_END_MAX = 0x02; - public static final int DISPLAY_MIDDLE = 0x01 + 0x02; - public static final int DISPLAY_X = 0x04; - public static final int DISPLAY_Y = 0x08; - public static final int DISPLAY_Z = 0x04 + 0x08; - public static final int MB_STATUS = 0x01 + 0x02 + 0x04 + 0x08; + public TileSpatialPylon() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK); + this.getProxy().setIdlePowerUsage(0.5); + this.getProxy().setValidSides(EnumSet.noneOf(ForgeDirection.class)); + } - public static final int DISPLAY_ENABLED = 0x10; - public static final int DISPLAY_POWERED_ENABLED = 0x20; - public static final int NET_STATUS = 0x10 + 0x20; + @Override + protected AENetworkProxy createProxy() { + return new AENetworkProxyMultiblock( + this, "proxy", this.getItemFromTile(this), true + ); + } - private final SpatialPylonCalculator calc = new SpatialPylonCalculator( this ); - private int displayBits = 0; - private SpatialPylonCluster cluster; - private boolean didHaveLight = false; + @Override + public void onChunkUnload() { + this.disconnect(false); + super.onChunkUnload(); + } - public TileSpatialPylon() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL, GridFlags.MULTIBLOCK ); - this.getProxy().setIdlePowerUsage( 0.5 ); - this.getProxy().setValidSides( EnumSet.noneOf( ForgeDirection.class ) ); - } + @Override + public void onReady() { + super.onReady(); + this.onNeighborBlockChange(); + } - @Override - protected AENetworkProxy createProxy() - { - return new AENetworkProxyMultiblock( this, "proxy", this.getItemFromTile( this ), true ); - } + @Override + public void invalidate() { + this.disconnect(false); + super.invalidate(); + } - @Override - public void onChunkUnload() - { - this.disconnect( false ); - super.onChunkUnload(); - } + public void onNeighborBlockChange() { + this.calc.calculateMultiblock(this.worldObj, this.getLocation()); + } - @Override - public void onReady() - { - super.onReady(); - this.onNeighborBlockChange(); - } + @Override + public void disconnect(final boolean b) { + if (this.cluster != null) { + this.cluster.destroy(); + this.updateStatus(null); + } + } - @Override - public void invalidate() - { - this.disconnect( false ); - super.invalidate(); - } + @Override + public SpatialPylonCluster getCluster() { + return this.cluster; + } - public void onNeighborBlockChange() - { - this.calc.calculateMultiblock( this.worldObj, this.getLocation() ); - } + @Override + public boolean isValid() { + return true; + } - @Override - public void disconnect( final boolean b ) - { - if( this.cluster != null ) - { - this.cluster.destroy(); - this.updateStatus( null ); - } - } + public void updateStatus(final SpatialPylonCluster c) { + this.cluster = c; + this.getProxy().setValidSides( + c == null ? EnumSet.noneOf(ForgeDirection.class) + : EnumSet.allOf(ForgeDirection.class) + ); + this.recalculateDisplay(); + } - @Override - public SpatialPylonCluster getCluster() - { - return this.cluster; - } + public void recalculateDisplay() { + final int oldBits = this.displayBits; - @Override - public boolean isValid() - { - return true; - } + this.displayBits = 0; - public void updateStatus( final SpatialPylonCluster c ) - { - this.cluster = c; - this.getProxy().setValidSides( c == null ? EnumSet.noneOf( ForgeDirection.class ) : EnumSet.allOf( ForgeDirection.class ) ); - this.recalculateDisplay(); - } + if (this.cluster != null) { + if (this.cluster.getMin().equals(this.getLocation())) { + this.displayBits = DISPLAY_END_MIN; + } else if (this.cluster.getMax().equals(this.getLocation())) { + this.displayBits = DISPLAY_END_MAX; + } else { + this.displayBits = DISPLAY_MIDDLE; + } - public void recalculateDisplay() - { - final int oldBits = this.displayBits; + switch (this.cluster.getCurrentAxis()) { + case X: + this.displayBits |= DISPLAY_X; + break; + case Y: + this.displayBits |= DISPLAY_Y; + break; + case Z: + this.displayBits |= DISPLAY_Z; + break; + default: + this.displayBits = 0; + break; + } - this.displayBits = 0; + try { + if (this.getProxy().getEnergy().isNetworkPowered()) { + this.displayBits |= DISPLAY_POWERED_ENABLED; + } - if( this.cluster != null ) - { - if( this.cluster.getMin().equals( this.getLocation() ) ) - { - this.displayBits = DISPLAY_END_MIN; - } - else if( this.cluster.getMax().equals( this.getLocation() ) ) - { - this.displayBits = DISPLAY_END_MAX; - } - else - { - this.displayBits = DISPLAY_MIDDLE; - } + if (this.cluster.isValid() && this.getProxy().isActive()) { + this.displayBits |= DISPLAY_ENABLED; + } + } catch (final GridAccessException e) { + // nothing? + } + } - switch( this.cluster.getCurrentAxis() ) - { - case X: - this.displayBits |= DISPLAY_X; - break; - case Y: - this.displayBits |= DISPLAY_Y; - break; - case Z: - this.displayBits |= DISPLAY_Z; - break; - default: - this.displayBits = 0; - break; - } + if (oldBits != this.displayBits) { + this.markForUpdate(); + } + } - try - { - if( this.getProxy().getEnergy().isNetworkPowered() ) - { - this.displayBits |= DISPLAY_POWERED_ENABLED; - } + @Override + public void markForUpdate() { + super.markForUpdate(); + final 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 ); + } + } - if( this.cluster.isValid() && this.getProxy().isActive() ) - { - this.displayBits |= DISPLAY_ENABLED; - } - } - catch( final GridAccessException e ) - { - // nothing? - } - } + @Override + public boolean canBeRotated() { + return false; + } - if( oldBits != this.displayBits ) - { - this.markForUpdate(); - } - } + public int getLightValue() { + if ((this.displayBits & DISPLAY_POWERED_ENABLED) == DISPLAY_POWERED_ENABLED) { + return 8; + } + return 0; + } - @Override - public void markForUpdate() - { - super.markForUpdate(); - final 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 ); - } - } + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileSpatialPylon(final ByteBuf data) { + final int old = this.displayBits; + this.displayBits = data.readByte(); + return old != this.displayBits; + } - @Override - public boolean canBeRotated() - { - return false; - } + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileSpatialPylon(final ByteBuf data) { + data.writeByte(this.displayBits); + } - public int getLightValue() - { - if( ( this.displayBits & DISPLAY_POWERED_ENABLED ) == DISPLAY_POWERED_ENABLED ) - { - return 8; - } - return 0; - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileSpatialPylon( final ByteBuf data ) - { - final int old = this.displayBits; - this.displayBits = data.readByte(); - return old != this.displayBits; - } + @MENetworkEventSubscribe + public void activeRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileSpatialPylon( final ByteBuf data ) - { - data.writeByte( this.displayBits ); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } - - @MENetworkEventSubscribe - public void activeRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } - - public int getDisplayBits() - { - return this.displayBits; - } + 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 f27a20c6..4fc8bbb1 100644 --- a/src/main/java/appeng/tile/storage/TileChest.java +++ b/src/main/java/appeng/tile/storage/TileChest.java @@ -18,6 +18,9 @@ package appeng.tile.storage; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.*; @@ -62,907 +65,788 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidHandler; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - - -public class TileChest extends AENetworkPowerTile implements IMEChest, IFluidHandler, ITerminalHost, IPriorityHost, IConfigManagerHost, IColorableTile -{ - - private static final ChestNoHandler NO_HANDLER = new ChestNoHandler(); - private static final int[] SIDES = { 0 }; - private static final int[] FRONT = { 1 }; - private static final int[] NO_SLOTS = {}; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 2 ); - private final BaseActionSource mySrc = new MachineSource( this ); - private final IConfigManager config = new ConfigManager( this ); - private ItemStack storageType; - private long lastStateChange = 0; - private int priority = 0; - private int state = 0; - private boolean wasActive = false; - private AEColor paintedColor = AEColor.Transparent; - private boolean isCached = false; - private ICellHandler cellHandler; - private MEMonitorHandler itemCell; - private MEMonitorHandler fluidCell; - - public TileChest() - { - this.setInternalMaxPower( PowerMultiplier.CONFIG.multiply( 40 ) ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.config.registerSetting( Settings.SORT_BY, SortOrder.NAME ); - this.config.registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - this.config.registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); - - this.setInternalPublicPowerStorage( true ); - this.setInternalPowerFlow( AccessRestriction.WRITE ); - } - - @Override - protected void PowerEvent( final PowerEventType x ) - { - if( x == PowerEventType.REQUEST_POWER ) - { - try - { - this.getProxy().getGrid().postEvent( new MENetworkPowerStorage( this, PowerEventType.REQUEST_POWER ) ); - } - catch( final GridAccessException e ) - { - // :( - } - } - else - { - this.recalculateDisplay(); - } - } - - private void recalculateDisplay() - { - final 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; - } - - final boolean currentActive = this.getProxy().isActive(); - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - if( oldState != this.state ) - { - this.markForUpdate(); - } - } - - @Override - public int getCellCount() - { - return 1; - } - - private IMEInventoryHandler getHandler( final StorageChannel channel ) throws ChestNoHandler - { - if( !this.isCached ) - { - this.itemCell = null; - this.fluidCell = null; - - final 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; - - final IMEInventoryHandler itemCell = this.cellHandler.getCellInventory( is, this, StorageChannel.ITEMS ); - final 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.getProxy().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( final IMEInventoryHandler h ) - { - if( h == null ) - { - return null; - } - - final MEInventoryHandler ih = new MEInventoryHandler( h, h.getChannel() ); - ih.setPriority( this.priority ); - - final MEMonitorHandler g = new ChestMonitorHandler( ih ); - g.addListener( new ChestNetNotifier( h.getChannel() ), g ); - - return g; - } - - @Override - public int getCellStatus( final int slot ) - { - if( Platform.isClient() ) - { - return ( this.state >> ( slot * 3 ) ) & 3; - } - - final ItemStack cell = this.inv.getStackInSlot( 1 ); - final ICellHandler ch = AEApi.instance().registries().cell().getHandler( cell ); - - if( ch != null ) - { - try - { - final IMEInventoryHandler handler = this.getHandler( StorageChannel.ITEMS ); - if( handler instanceof ChestMonitorHandler ) - { - return ch.getStatusForCell( cell, ( (ChestMonitorHandler) handler ).getInternalHandler() ); - } - } - catch( final ChestNoHandler ignored ) - { - } - - try - { - final IMEInventoryHandler handler = this.getHandler( StorageChannel.FLUIDS ); - if( handler instanceof ChestMonitorHandler ) - { - return ch.getStatusForCell( cell, ( (ChestMonitorHandler) handler ).getInternalHandler() ); - } - } - catch( final 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.getProxy().getEnergy().isNetworkPowered(); - } - catch( final GridAccessException ignored ) - { - } - } - - return super.getAECurrentPower() > 1 || gridPowered; - } - - @Override - public boolean isCellBlinking( final int slot ) - { - final long now = this.worldObj.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - return false; - } - - return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; - } - - @Override - protected double extractAEPower( final double amt, final Actionable mode ) - { - double stash = 0.0; - - try - { - final IEnergyGrid eg = this.getProxy().getEnergy(); - stash = eg.extractAEPower( amt, mode, PowerMultiplier.ONE ); - if( stash >= amt ) - { - return stash; - } - } - catch( final 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; - } - - final double idleUsage = this.getProxy().getIdlePowerUsage(); - - try - { - if( !this.getProxy().getEnergy().isNetworkPowered() ) - { - final double powerUsed = this.extractAEPower( idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG ); // drain - if( powerUsed + 0.1 >= idleUsage != ( this.state & 0x40 ) > 0 ) - { - this.recalculateDisplay(); - } - } - } - catch( final GridAccessException e ) - { - final double powerUsed = this.extractAEPower( this.getProxy().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( final 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() ); - - final 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( final ByteBuf data ) - { - final int oldState = this.state; - final ItemStack oldType = this.storageType; - - this.state = data.readByte(); - final AEColor oldPaintedColor = this.paintedColor; - this.paintedColor = AEColor.values()[data.readByte()]; - - final 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( final 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( final NBTTagCompound data ) - { - this.config.writeToNBT( data ); - data.setInteger( "priority", this.priority ); - data.setByte( "paintedColor", (byte) this.paintedColor.ordinal() ); - } - - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } - - @MENetworkEventSubscribe - public void channelRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } - - @Override - public IMEMonitor getItemInventory() - { - return this.itemCell; - } - - @Override - public IMEMonitor getFluidInventory() - { - return this.fluidCell; - } - - @Override - public IInventory getInternalInventory() - { - return this.inv; - } - - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.inv.setInventorySlotContents( i, itemstack ); - this.tryToStoreContents(); - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( slot == 1 ) - { - this.itemCell = null; - this.fluidCell = null; - this.isCached = false; // recalculate the storage cell. - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - - final IStorageGrid gs = this.getProxy().getStorage(); - Platform.postChanges( gs, removed, added, this.mySrc ); - } - catch( final GridAccessException ignored ) - { - - } - - // update the neighbors - if( this.worldObj != null ) - { - Platform.notifyBlocksOfNeighbors( this.worldObj, this.xCoord, this.yCoord, this.zCoord ); - this.markForUpdate(); - } - } - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - if( slotIndex == 1 ) - { - if( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.ITEMS ) != null ) - { - return true; - } - if( AEApi.instance().registries().cell().getCellInventory( insertingItem, this, StorageChannel.FLUIDS ) != null ) - { - return true; - } - } - else - { - try - { - final IMEInventory cell = this.getHandler( StorageChannel.ITEMS ); - final IAEItemStack returns = cell.injectItems( AEApi.instance().storage().createItemStack( this.inv.getStackInSlot( 0 ) ), Actionable.SIMULATE, this.mySrc ); - return returns == null || returns.getStackSize() != insertingItem.stackSize; - } - catch( final ChestNoHandler ignored ) - { - } - } - return false; - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - return slotIndex == 1; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - if( ForgeDirection.SOUTH == side ) - { - return FRONT; - } - - if( this.isPowered() ) - { - try - { - if( this.getHandler( StorageChannel.ITEMS ) != null ) - { - return SIDES; - } - } - catch( final ChestNoHandler e ) - { - // nope! - } - } - return NO_SLOTS; - } - - private void tryToStoreContents() - { - try - { - if( this.getStackInSlot( 0 ) != null ) - { - final IMEInventory cell = this.getHandler( StorageChannel.ITEMS ); - - final 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( final ChestNoHandler ignored ) - { - } - } - - @Override - public List getCellArray( final StorageChannel channel ) - { - if( this.getProxy().isActive() ) - { - try - { - return Collections.singletonList( this.getHandler( channel ) ); - } - catch( final ChestNoHandler e ) - { - // :P - } - } - return new ArrayList(); - } - - @Override - public int getPriority() - { - return this.priority; - } - - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - - this.itemCell = null; - this.fluidCell = null; - this.isCached = false; // recalculate the storage cell. - - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } - - @Override - public void blinkCell( final int slot ) - { - final 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( final ForgeDirection from, final FluidStack resource, final boolean doFill ) - { - final double req = resource.amount / 500.0; - final double available = this.extractAEPower( req, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - if( available >= req - 0.01 ) - { - try - { - final IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - - this.extractAEPower( req, Actionable.MODULATE, PowerMultiplier.CONFIG ); - final 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( final ChestNoHandler ignored ) - { - } - } - return 0; - } - - @Override - public FluidStack drain( final ForgeDirection from, final FluidStack resource, final boolean doDrain ) - { - return null; - } - - @Override - public FluidStack drain( final ForgeDirection from, final int maxDrain, final boolean doDrain ) - { - return null; - } - - @Override - public boolean canFill( final ForgeDirection from, final Fluid fluid ) - { - try - { - final IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - return h.canAccept( AEFluidStack.create( new FluidStack( fluid, 1 ) ) ); - } - catch( final ChestNoHandler ignored ) - { - } - return false; - } - - @Override - public boolean canDrain( final ForgeDirection from, final Fluid fluid ) - { - return false; - } - - @Override - public FluidTankInfo[] getTankInfo( final ForgeDirection from ) - { - try - { - final IMEInventoryHandler h = this.getHandler( StorageChannel.FLUIDS ); - if( h.getChannel() == StorageChannel.FLUIDS ) - { - return new FluidTankInfo[] { new FluidTankInfo( null, 1 ) }; // eh? - } - } - catch( final ChestNoHandler ignored ) - { - } - - return null; - } - - @Override - public IStorageMonitorable getMonitorable( final ForgeDirection side, final BaseActionSource src ) - { - if( Platform.canAccess( this.getProxy(), src ) && side != this.getForward() ) - { - return this; - } - return null; - } - - public ItemStack getStorageType() - { - if( this.isPowered() ) - { - return this.storageType; - } - return null; - } - - @Override - public IConfigManager getConfigManager() - { - return this.config; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - - } - - public boolean openGui( final EntityPlayer p, final ICellHandler ch, final ItemStack cell, final int side ) - { - try - { - final IMEInventoryHandler invHandler = this.getHandler( StorageChannel.ITEMS ); - if( ch != null && invHandler != null ) - { - ch.openChestGui( p, this, ch, invHandler, cell, StorageChannel.ITEMS ); - return true; - } - } - catch( final ChestNoHandler e ) - { - // :P - } - - try - { - final IMEInventoryHandler invHandler = this.getHandler( StorageChannel.FLUIDS ); - if( ch != null && invHandler != null ) - { - ch.openChestGui( p, this, ch, invHandler, cell, StorageChannel.FLUIDS ); - return true; - } - } - catch( final ChestNoHandler e ) - { - // :P - } - - return false; - } - - @Override - public AEColor getColor() - { - return this.paintedColor; - } - - @Override - public boolean recolourBlock( final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who ) - { - if( this.paintedColor == newPaintedColor ) - { - return false; - } - - this.paintedColor = newPaintedColor; - this.markDirty(); - this.markForUpdate(); - return true; - } - - @Override - public void saveChanges( final IMEInventory cellInventory ) - { - this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); - } - - private static class ChestNoHandler extends Exception - { - private static final long serialVersionUID = 7995805326136526631L; - } - - - private class ChestNetNotifier> implements IMEMonitorHandlerReceiver - { - - private final StorageChannel chan; - - public ChestNetNotifier( final StorageChannel chan ) - { - this.chan = chan; - } - - @Override - public boolean isValid( final 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( final IBaseMonitor monitor, final Iterable change, final BaseActionSource source ) - { - if( source == TileChest.this.mySrc || ( source instanceof PlayerSource && ( (PlayerSource) source ).via == TileChest.this ) ) - { - try - { - if( TileChest.this.getProxy().isActive() ) - { - TileChest.this.getProxy().getStorage().postAlterationOfStoredItems( this.chan, change, TileChest.this.mySrc ); - } - } - catch( final GridAccessException e ) - { - // :( - } - } - - TileChest.this.blinkCell( 0 ); - } - - @Override - public void onListUpdate() - { - // not used here - } - } - - - private class ChestMonitorHandler extends MEMonitorHandler - { - - public ChestMonitorHandler( final IMEInventoryHandler t ) - { - super( t ); - } - - private IMEInventoryHandler getInternalHandler() - { - final IMEInventoryHandler h = this.getHandler(); - if( h instanceof MEInventoryHandler ) - { - return (IMEInventoryHandler) ( (MEInventoryHandler) h ).getInternal(); - } - return this.getHandler(); - } - - @Override - public T injectItems( final T input, final Actionable mode, final BaseActionSource src ) - { - if( src.isPlayer() && !this.securityCheck( ( (PlayerSource) src ).player, SecurityPermissions.INJECT ) ) - { - return input; - } - return super.injectItems( input, mode, src ); - } - - private boolean securityCheck( final EntityPlayer player, final SecurityPermissions requiredPermission ) - { - if( TileChest.this.getTile() instanceof IActionHost && requiredPermission != null ) - { - final IGridNode gn = ( (IActionHost) TileChest.this.getTile() ).getActionableNode(); - if( gn != null ) - { - final IGrid g = gn.getGrid(); - if( g != null ) - { - final boolean requirePower = false; - if( requirePower ) - { - final IEnergyGrid eg = g.getCache( IEnergyGrid.class ); - if( !eg.isNetworkPowered() ) - { - return false; - } - } - - final ISecurityGrid sg = g.getCache( ISecurityGrid.class ); - if( sg.hasPermission( player, requiredPermission ) ) - { - return true; - } - } - } - - return false; - } - return true; - } - - @Override - public T extractItems( final T request, final Actionable mode, final BaseActionSource src ) - { - if( src.isPlayer() && !this.securityCheck( ( (PlayerSource) src ).player, SecurityPermissions.EXTRACT ) ) - { - return null; - } - return super.extractItems( request, mode, src ); - } - } +public class TileChest extends AENetworkPowerTile + implements IMEChest, IFluidHandler, ITerminalHost, IPriorityHost, IConfigManagerHost, + IColorableTile { + private static final ChestNoHandler NO_HANDLER = new ChestNoHandler(); + private static final int[] SIDES = { 0 }; + private static final int[] FRONT = { 1 }; + private static final int[] NO_SLOTS = {}; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 2); + private final BaseActionSource mySrc = new MachineSource(this); + private final IConfigManager config = new ConfigManager(this); + private ItemStack storageType; + private long lastStateChange = 0; + private int priority = 0; + private int state = 0; + private boolean wasActive = false; + private AEColor paintedColor = AEColor.Transparent; + private boolean isCached = false; + private ICellHandler cellHandler; + private MEMonitorHandler itemCell; + private MEMonitorHandler fluidCell; + + public TileChest() { + this.setInternalMaxPower(PowerMultiplier.CONFIG.multiply(40)); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.config.registerSetting(Settings.SORT_BY, SortOrder.NAME); + this.config.registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + this.config.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); + + this.setInternalPublicPowerStorage(true); + this.setInternalPowerFlow(AccessRestriction.WRITE); + } + + @Override + protected void PowerEvent(final PowerEventType x) { + if (x == PowerEventType.REQUEST_POWER) { + try { + this.getProxy().getGrid().postEvent( + new MENetworkPowerStorage(this, PowerEventType.REQUEST_POWER) + ); + } catch (final GridAccessException e) { + // :( + } + } else { + this.recalculateDisplay(); + } + } + + private void recalculateDisplay() { + final 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; + } + + final boolean currentActive = this.getProxy().isActive(); + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + if (oldState != this.state) { + this.markForUpdate(); + } + } + + @Override + public int getCellCount() { + return 1; + } + + private IMEInventoryHandler getHandler(final StorageChannel channel) + throws ChestNoHandler { + if (!this.isCached) { + this.itemCell = null; + this.fluidCell = null; + + final 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; + + final IMEInventoryHandler itemCell + = this.cellHandler.getCellInventory( + is, this, StorageChannel.ITEMS + ); + final 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.getProxy().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(final IMEInventoryHandler h) { + if (h == null) { + return null; + } + + final MEInventoryHandler ih = new MEInventoryHandler(h, h.getChannel()); + ih.setPriority(this.priority); + + final MEMonitorHandler g = new ChestMonitorHandler(ih); + g.addListener(new ChestNetNotifier(h.getChannel()), g); + + return g; + } + + @Override + public int getCellStatus(final int slot) { + if (Platform.isClient()) { + return (this.state >> (slot * 3)) & 3; + } + + final ItemStack cell = this.inv.getStackInSlot(1); + final ICellHandler ch = AEApi.instance().registries().cell().getHandler(cell); + + if (ch != null) { + try { + final IMEInventoryHandler handler = this.getHandler(StorageChannel.ITEMS); + if (handler instanceof ChestMonitorHandler) { + return ch.getStatusForCell( + cell, ((ChestMonitorHandler) handler).getInternalHandler() + ); + } + } catch (final ChestNoHandler ignored) {} + + try { + final IMEInventoryHandler handler + = this.getHandler(StorageChannel.FLUIDS); + if (handler instanceof ChestMonitorHandler) { + return ch.getStatusForCell( + cell, ((ChestMonitorHandler) handler).getInternalHandler() + ); + } + } catch (final 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.getProxy().getEnergy().isNetworkPowered(); + } catch (final GridAccessException ignored) {} + } + + return super.getAECurrentPower() > 1 || gridPowered; + } + + @Override + public boolean isCellBlinking(final int slot) { + final long now = this.worldObj.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + return false; + } + + return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; + } + + @Override + protected double extractAEPower(final double amt, final Actionable mode) { + double stash = 0.0; + + try { + final IEnergyGrid eg = this.getProxy().getEnergy(); + stash = eg.extractAEPower(amt, mode, PowerMultiplier.ONE); + if (stash >= amt) { + return stash; + } + } catch (final 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; + } + + final double idleUsage = this.getProxy().getIdlePowerUsage(); + + try { + if (!this.getProxy().getEnergy().isNetworkPowered()) { + final double powerUsed = this.extractAEPower( + idleUsage, Actionable.MODULATE, PowerMultiplier.CONFIG + ); // drain + if (powerUsed + 0.1 >= idleUsage != (this.state & 0x40) > 0) { + this.recalculateDisplay(); + } + } + } catch (final GridAccessException e) { + final double powerUsed = this.extractAEPower( + this.getProxy().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(final 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()); + + final 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(final ByteBuf data) { + final int oldState = this.state; + final ItemStack oldType = this.storageType; + + this.state = data.readByte(); + final AEColor oldPaintedColor = this.paintedColor; + this.paintedColor = AEColor.values()[data.readByte()]; + + final 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(final 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(final NBTTagCompound data) { + this.config.writeToNBT(data); + data.setInteger("priority", this.priority); + data.setByte("paintedColor", (byte) this.paintedColor.ordinal()); + } + + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } + + @MENetworkEventSubscribe + public void channelRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } + + @Override + public IMEMonitor getItemInventory() { + return this.itemCell; + } + + @Override + public IMEMonitor getFluidInventory() { + return this.fluidCell; + } + + @Override + public IInventory getInternalInventory() { + return this.inv; + } + + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.inv.setInventorySlotContents(i, itemstack); + this.tryToStoreContents(); + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + if (slot == 1) { + this.itemCell = null; + this.fluidCell = null; + this.isCached = false; // recalculate the storage cell. + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + + final IStorageGrid gs = this.getProxy().getStorage(); + Platform.postChanges(gs, removed, added, this.mySrc); + } catch (final GridAccessException ignored) {} + + // update the neighbors + if (this.worldObj != null) { + Platform.notifyBlocksOfNeighbors( + this.worldObj, this.xCoord, this.yCoord, this.zCoord + ); + this.markForUpdate(); + } + } + } + + @Override + public boolean + canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + if (slotIndex == 1) { + if (AEApi.instance().registries().cell().getCellInventory( + insertingItem, this, StorageChannel.ITEMS + ) + != null) { + return true; + } + if (AEApi.instance().registries().cell().getCellInventory( + insertingItem, this, StorageChannel.FLUIDS + ) + != null) { + return true; + } + } else { + try { + final IMEInventory cell + = this.getHandler(StorageChannel.ITEMS); + final IAEItemStack returns = cell.injectItems( + AEApi.instance().storage().createItemStack(this.inv.getStackInSlot(0) + ), + Actionable.SIMULATE, + this.mySrc + ); + return returns == null + || returns.getStackSize() != insertingItem.stackSize; + } catch (final ChestNoHandler ignored) {} + } + return false; + } + + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + return slotIndex == 1; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + if (ForgeDirection.SOUTH == side) { + return FRONT; + } + + if (this.isPowered()) { + try { + if (this.getHandler(StorageChannel.ITEMS) != null) { + return SIDES; + } + } catch (final ChestNoHandler e) { + // nope! + } + } + return NO_SLOTS; + } + + private void tryToStoreContents() { + try { + if (this.getStackInSlot(0) != null) { + final IMEInventory cell + = this.getHandler(StorageChannel.ITEMS); + + final 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 (final ChestNoHandler ignored) {} + } + + @Override + public List getCellArray(final StorageChannel channel) { + if (this.getProxy().isActive()) { + try { + return Collections.singletonList(this.getHandler(channel)); + } catch (final ChestNoHandler e) { + // :P + } + } + return new ArrayList(); + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + + this.itemCell = null; + this.fluidCell = null; + this.isCached = false; // recalculate the storage cell. + + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } + + @Override + public void blinkCell(final int slot) { + final 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(final ForgeDirection from, final FluidStack resource, final boolean doFill) { + final double req = resource.amount / 500.0; + final double available + = this.extractAEPower(req, Actionable.SIMULATE, PowerMultiplier.CONFIG); + if (available >= req - 0.01) { + try { + final IMEInventoryHandler h = this.getHandler(StorageChannel.FLUIDS); + + this.extractAEPower(req, Actionable.MODULATE, PowerMultiplier.CONFIG); + final 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 (final ChestNoHandler ignored) {} + } + return 0; + } + + @Override + public FluidStack + drain(final ForgeDirection from, final FluidStack resource, final boolean doDrain) { + return null; + } + + @Override + public FluidStack + drain(final ForgeDirection from, final int maxDrain, final boolean doDrain) { + return null; + } + + @Override + public boolean canFill(final ForgeDirection from, final Fluid fluid) { + try { + final IMEInventoryHandler h = this.getHandler(StorageChannel.FLUIDS); + return h.canAccept(AEFluidStack.create(new FluidStack(fluid, 1))); + } catch (final ChestNoHandler ignored) {} + return false; + } + + @Override + public boolean canDrain(final ForgeDirection from, final Fluid fluid) { + return false; + } + + @Override + public FluidTankInfo[] getTankInfo(final ForgeDirection from) { + try { + final IMEInventoryHandler h = this.getHandler(StorageChannel.FLUIDS); + if (h.getChannel() == StorageChannel.FLUIDS) { + return new FluidTankInfo[] { new FluidTankInfo(null, 1) }; // eh? + } + } catch (final ChestNoHandler ignored) {} + + return null; + } + + @Override + public IStorageMonitorable + getMonitorable(final ForgeDirection side, final BaseActionSource src) { + if (Platform.canAccess(this.getProxy(), src) && side != this.getForward()) { + return this; + } + return null; + } + + public ItemStack getStorageType() { + if (this.isPowered()) { + return this.storageType; + } + return null; + } + + @Override + public IConfigManager getConfigManager() { + return this.config; + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) {} + + public boolean openGui( + final EntityPlayer p, final ICellHandler ch, final ItemStack cell, final int side + ) { + try { + final IMEInventoryHandler invHandler = this.getHandler(StorageChannel.ITEMS); + if (ch != null && invHandler != null) { + ch.openChestGui(p, this, ch, invHandler, cell, StorageChannel.ITEMS); + return true; + } + } catch (final ChestNoHandler e) { + // :P + } + + try { + final IMEInventoryHandler invHandler = this.getHandler(StorageChannel.FLUIDS); + if (ch != null && invHandler != null) { + ch.openChestGui(p, this, ch, invHandler, cell, StorageChannel.FLUIDS); + return true; + } + } catch (final ChestNoHandler e) { + // :P + } + + return false; + } + + @Override + public AEColor getColor() { + return this.paintedColor; + } + + @Override + public boolean recolourBlock( + final ForgeDirection side, final AEColor newPaintedColor, final EntityPlayer who + ) { + if (this.paintedColor == newPaintedColor) { + return false; + } + + this.paintedColor = newPaintedColor; + this.markDirty(); + this.markForUpdate(); + return true; + } + + @Override + public void saveChanges(final IMEInventory cellInventory) { + this.worldObj.markTileEntityChunkModified( + this.xCoord, this.yCoord, this.zCoord, this + ); + } + + private static class ChestNoHandler extends Exception { + private static final long serialVersionUID = 7995805326136526631L; + } + + private class ChestNetNotifier> + implements IMEMonitorHandlerReceiver { + private final StorageChannel chan; + + public ChestNetNotifier(final StorageChannel chan) { + this.chan = chan; + } + + @Override + public boolean isValid(final 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( + final IBaseMonitor monitor, + final Iterable change, + final BaseActionSource source + ) { + if (source == TileChest.this.mySrc + || (source instanceof PlayerSource + && ((PlayerSource) source).via == TileChest.this)) { + try { + if (TileChest.this.getProxy().isActive()) { + TileChest.this.getProxy() + .getStorage() + .postAlterationOfStoredItems( + this.chan, change, TileChest.this.mySrc + ); + } + } catch (final GridAccessException e) { + // :( + } + } + + TileChest.this.blinkCell(0); + } + + @Override + public void onListUpdate() { + // not used here + } + } + + private class ChestMonitorHandler extends MEMonitorHandler { + public ChestMonitorHandler(final IMEInventoryHandler t) { + super(t); + } + + private IMEInventoryHandler getInternalHandler() { + final IMEInventoryHandler h = this.getHandler(); + if (h instanceof MEInventoryHandler) { + return (IMEInventoryHandler) ((MEInventoryHandler) h).getInternal(); + } + return this.getHandler(); + } + + @Override + public T + injectItems(final T input, final Actionable mode, final BaseActionSource src) { + if (src.isPlayer() + && !this.securityCheck( + ((PlayerSource) src).player, SecurityPermissions.INJECT + )) { + return input; + } + return super.injectItems(input, mode, src); + } + + private boolean securityCheck( + final EntityPlayer player, final SecurityPermissions requiredPermission + ) { + if (TileChest.this.getTile() instanceof IActionHost + && requiredPermission != null) { + final IGridNode gn + = ((IActionHost) TileChest.this.getTile()).getActionableNode(); + if (gn != null) { + final IGrid g = gn.getGrid(); + if (g != null) { + final boolean requirePower = false; + if (requirePower) { + final IEnergyGrid eg = g.getCache(IEnergyGrid.class); + if (!eg.isNetworkPowered()) { + return false; + } + } + + final ISecurityGrid sg = g.getCache(ISecurityGrid.class); + if (sg.hasPermission(player, requiredPermission)) { + return true; + } + } + } + + return false; + } + return true; + } + + @Override + public T + extractItems(final T request, final Actionable mode, final 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 ad3a5775..f169f467 100644 --- a/src/main/java/appeng/tile/storage/TileDrive.java +++ b/src/main/java/appeng/tile/storage/TileDrive.java @@ -18,6 +18,9 @@ package appeng.tile.storage; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; import appeng.api.AEApi; import appeng.api.implementations.tiles.IChestOrDrive; @@ -52,370 +55,315 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; +public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPriorityHost { + private final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 10); + private final ICellHandler[] handlersBySlot = new ICellHandler[10]; + private final DriveWatcher[] invBySlot = new DriveWatcher[10]; + private final BaseActionSource mySrc; + private boolean isCached = false; + private List items = new LinkedList(); + private List fluids = new LinkedList(); + private long lastStateChange = 0; + private int state = 0; + private int priority = 0; + private boolean wasActive = false; + public TileDrive() { + this.mySrc = new MachineSource(this); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + } -public class TileDrive extends AENetworkInvTile implements IChestOrDrive, IPriorityHost -{ + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileDrive(final ByteBuf data) { + if (this.worldObj.getTotalWorldTime() - this.lastStateChange > 8) { + this.state = 0; + } else { + this.state &= 0x24924924; // just keep the blinks... + } - private final int[] sides = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 10 ); - private final ICellHandler[] handlersBySlot = new ICellHandler[10]; - private final DriveWatcher[] invBySlot = new DriveWatcher[10]; - private final BaseActionSource mySrc; - private boolean isCached = false; - private List items = new LinkedList(); - private List fluids = new LinkedList(); - private long lastStateChange = 0; - private int state = 0; - private int priority = 0; - private boolean wasActive = false; + if (this.getProxy().isActive()) { + this.state |= 0x80000000; + } else { + this.state &= ~0x80000000; + } - public TileDrive() - { - this.mySrc = new MachineSource( this ); - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - } + for (int x = 0; x < this.getCellCount(); x++) { + this.state |= (this.getCellStatus(x) << (3 * x)); + } - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileDrive( final ByteBuf data ) - { - if( this.worldObj.getTotalWorldTime() - this.lastStateChange > 8 ) - { - this.state = 0; - } - else - { - this.state &= 0x24924924; // just keep the blinks... - } + data.writeInt(this.state); + } - if( this.getProxy().isActive() ) - { - this.state |= 0x80000000; - } - else - { - this.state &= ~0x80000000; - } + @Override + public int getCellCount() { + return 10; + } - for( int x = 0; x < this.getCellCount(); x++ ) - { - this.state |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } + @Override + public int getCellStatus(final int slot) { + if (Platform.isClient()) { + return (this.state >> (slot * 3)) & 3; + } - data.writeInt( this.state ); - } + final ItemStack cell = this.inv.getStackInSlot(2); + final ICellHandler ch = this.handlersBySlot[slot]; - @Override - public int getCellCount() - { - return 10; - } + final MEInventoryHandler handler = this.invBySlot[slot]; + if (handler == null) { + return 0; + } - @Override - public int getCellStatus( final int slot ) - { - if( Platform.isClient() ) - { - return ( this.state >> ( slot * 3 ) ) & 3; - } + if (handler.getChannel() == StorageChannel.ITEMS) { + if (ch != null) { + return ch.getStatusForCell(cell, handler.getInternal()); + } + } - final ItemStack cell = this.inv.getStackInSlot( 2 ); - final ICellHandler ch = this.handlersBySlot[slot]; + if (handler.getChannel() == StorageChannel.FLUIDS) { + if (ch != null) { + return ch.getStatusForCell(cell, handler.getInternal()); + } + } - final MEInventoryHandler handler = this.invBySlot[slot]; - if( handler == null ) - { - return 0; - } + return 0; + } - if( handler.getChannel() == StorageChannel.ITEMS ) - { - if( ch != null ) - { - return ch.getStatusForCell( cell, handler.getInternal() ); - } - } + @Override + public boolean isPowered() { + if (Platform.isClient()) { + return (this.state & 0x80000000) == 0x80000000; + } - if( handler.getChannel() == StorageChannel.FLUIDS ) - { - if( ch != null ) - { - return ch.getStatusForCell( cell, handler.getInternal() ); - } - } + return this.getProxy().isActive(); + } - return 0; - } + @Override + public boolean isCellBlinking(final int slot) { + final long now = this.worldObj.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + return false; + } - @Override - public boolean isPowered() - { - if( Platform.isClient() ) - { - return ( this.state & 0x80000000 ) == 0x80000000; - } + return ((this.state >> (slot * 3 + 2)) & 0x01) == 0x01; + } - return this.getProxy().isActive(); - } + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileDrive(final ByteBuf data) { + final int oldState = this.state; + this.state = data.readInt(); + this.lastStateChange = this.worldObj.getTotalWorldTime(); + return (this.state & 0xDB6DB6DB) != (oldState & 0xDB6DB6DB); + } - @Override - public boolean isCellBlinking( final int slot ) - { - final long now = this.worldObj.getTotalWorldTime(); - if( now - this.lastStateChange > 8 ) - { - return false; - } + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileDrive(final NBTTagCompound data) { + this.isCached = false; + this.priority = data.getInteger("priority"); + } - return ( ( this.state >> ( slot * 3 + 2 ) ) & 0x01 ) == 0x01; - } + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileDrive(final NBTTagCompound data) { + data.setInteger("priority", this.priority); + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileDrive( final ByteBuf data ) - { - final int oldState = this.state; - this.state = data.readInt(); - this.lastStateChange = this.worldObj.getTotalWorldTime(); - return ( this.state & 0xDB6DB6DB ) != ( oldState & 0xDB6DB6DB ); - } + @MENetworkEventSubscribe + public void powerRender(final MENetworkPowerStatusChange c) { + this.recalculateDisplay(); + } - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileDrive( final NBTTagCompound data ) - { - this.isCached = false; - this.priority = data.getInteger( "priority" ); - } + private void recalculateDisplay() { + final boolean currentActive = this.getProxy().isActive(); + int newState = this.state; - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileDrive( final NBTTagCompound data ) - { - data.setInteger( "priority", this.priority ); - } + if (currentActive) { + newState |= 0x80000000; + } else { + newState &= ~0x80000000; + } - @MENetworkEventSubscribe - public void powerRender( final MENetworkPowerStatusChange c ) - { - this.recalculateDisplay(); - } + if (this.wasActive != currentActive) { + this.wasActive = currentActive; + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } - private void recalculateDisplay() - { - final boolean currentActive = this.getProxy().isActive(); - int newState = this.state; + for (int x = 0; x < this.getCellCount(); x++) { + newState |= (this.getCellStatus(x) << (3 * x)); + } - if( currentActive ) - { - newState |= 0x80000000; - } - else - { - newState &= ~0x80000000; - } + if (newState != this.state) { + this.state = newState; + this.markForUpdate(); + } + } - if( this.wasActive != currentActive ) - { - this.wasActive = currentActive; - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + @MENetworkEventSubscribe + public void channelRender(final MENetworkChannelsChanged c) { + this.recalculateDisplay(); + } - for( int x = 0; x < this.getCellCount(); x++ ) - { - newState |= ( this.getCellStatus( x ) << ( 3 * x ) ); - } + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } - if( newState != this.state ) - { - this.state = newState; - this.markForUpdate(); - } - } + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } - @MENetworkEventSubscribe - public void channelRender( final MENetworkChannelsChanged c ) - { - this.recalculateDisplay(); - } + @Override + public IInventory getInternalInventory() { + return this.inv; + } - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return itemstack != null + && AEApi.instance().registries().cell().isCellHandled(itemstack); + } - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + if (this.isCached) { + this.isCached = false; // recalculate the storage cell. + this.updateState(); + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return itemstack != null && AEApi.instance().registries().cell().isCellHandled( itemstack ); - } + final IStorageGrid gs = this.getProxy().getStorage(); + Platform.postChanges(gs, removed, added, this.mySrc); + } catch (final GridAccessException ignored) {} - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.isCached ) - { - this.isCached = false; // recalculate the storage cell. - this.updateState(); - } + this.markForUpdate(); + } - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } - final IStorageGrid gs = this.getProxy().getStorage(); - Platform.postChanges( gs, removed, added, this.mySrc ); - } - catch( final GridAccessException ignored ) - { - } + private void updateState() { + if (!this.isCached) { + this.items = new LinkedList(); + this.fluids = new LinkedList(); - this.markForUpdate(); - } + double power = 2.0; - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } + for (int x = 0; x < this.inv.getSizeInventory(); x++) { + final ItemStack is = this.inv.getStackInSlot(x); + this.invBySlot[x] = null; + this.handlersBySlot[x] = null; - private void updateState() - { - if( !this.isCached ) - { - this.items = new LinkedList(); - this.fluids = new LinkedList(); + if (is != null) { + this.handlersBySlot[x] + = AEApi.instance().registries().cell().getHandler(is); - double power = 2.0; + if (this.handlersBySlot[x] != null) { + IMEInventoryHandler cell + = this.handlersBySlot[x].getCellInventory( + is, this, StorageChannel.ITEMS + ); - for( int x = 0; x < this.inv.getSizeInventory(); x++ ) - { - final ItemStack is = this.inv.getStackInSlot( x ); - this.invBySlot[x] = null; - this.handlersBySlot[x] = null; + if (cell != null) { + power += this.handlersBySlot[x].cellIdleDrain(is, cell); - if( is != null ) - { - this.handlersBySlot[x] = AEApi.instance().registries().cell().getHandler( is ); + final DriveWatcher ih = new DriveWatcher( + cell, is, this.handlersBySlot[x], this + ); + ih.setPriority(this.priority); + this.invBySlot[x] = ih; + this.items.add(ih); + } else { + cell = this.handlersBySlot[x].getCellInventory( + is, this, StorageChannel.FLUIDS + ); - if( this.handlersBySlot[x] != null ) - { - IMEInventoryHandler cell = this.handlersBySlot[x].getCellInventory( is, this, StorageChannel.ITEMS ); + if (cell != null) { + power += this.handlersBySlot[x].cellIdleDrain(is, cell); - if( cell != null ) - { - power += this.handlersBySlot[x].cellIdleDrain( is, cell ); + final DriveWatcher ih = new DriveWatcher( + cell, is, this.handlersBySlot[x], this + ); + ih.setPriority(this.priority); + this.invBySlot[x] = ih; + this.fluids.add(ih); + } + } + } + } + } - final DriveWatcher ih = new DriveWatcher( cell, is, this.handlersBySlot[x], this ); - ih.setPriority( this.priority ); - this.invBySlot[x] = ih; - this.items.add( ih ); - } - else - { - cell = this.handlersBySlot[x].getCellInventory( is, this, StorageChannel.FLUIDS ); + this.getProxy().setIdlePowerUsage(power); - if( cell != null ) - { - power += this.handlersBySlot[x].cellIdleDrain( is, cell ); + this.isCached = true; + } + } - final DriveWatcher ih = new DriveWatcher( cell, is, this.handlersBySlot[x], this ); - ih.setPriority( this.priority ); - this.invBySlot[x] = ih; - this.fluids.add( ih ); - } - } - } - } - } + @Override + public void onReady() { + super.onReady(); + this.updateState(); + } - this.getProxy().setIdlePowerUsage( power ); + @Override + public List getCellArray(final StorageChannel channel) { + if (this.getProxy().isActive()) { + this.updateState(); + return (List) (channel == StorageChannel.ITEMS ? this.items : this.fluids); + } + return new ArrayList(); + } - this.isCached = true; - } - } + @Override + public int getPriority() { + return this.priority; + } - @Override - public void onReady() - { - super.onReady(); - this.updateState(); - } + @Override + public void setPriority(final int newValue) { + this.priority = newValue; + this.markDirty(); - @Override - public List getCellArray( final StorageChannel channel ) - { - if( this.getProxy().isActive() ) - { - this.updateState(); - return (List) ( channel == StorageChannel.ITEMS ? this.items : this.fluids ); - } - return new ArrayList(); - } + this.isCached = false; // recalculate the storage cell. + this.updateState(); - @Override - public int getPriority() - { - return this.priority; - } + try { + this.getProxy().getGrid().postEvent(new MENetworkCellArrayUpdate()); + } catch (final GridAccessException e) { + // :P + } + } - @Override - public void setPriority( final int newValue ) - { - this.priority = newValue; - this.markDirty(); + @Override + public void blinkCell(final int slot) { + final long now = this.worldObj.getTotalWorldTime(); + if (now - this.lastStateChange > 8) { + this.state = 0; + } + this.lastStateChange = now; - this.isCached = false; // recalculate the storage cell. - this.updateState(); + this.state |= 1 << (slot * 3 + 2); - try - { - this.getProxy().getGrid().postEvent( new MENetworkCellArrayUpdate() ); - } - catch( final GridAccessException e ) - { - // :P - } - } + this.recalculateDisplay(); + } - @Override - public void blinkCell( final int slot ) - { - final 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( final IMEInventory cellInventory ) - { - this.worldObj.markTileEntityChunkModified( this.xCoord, this.yCoord, this.zCoord, this ); - } + @Override + public void saveChanges(final 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 06a844a4..bab0693d 100644 --- a/src/main/java/appeng/tile/storage/TileIOPort.java +++ b/src/main/java/appeng/tile/storage/TileIOPort.java @@ -18,6 +18,7 @@ package appeng.tile.storage; +import java.util.List; import appeng.api.AEApi; import appeng.api.config.*; @@ -62,511 +63,489 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; - - -public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IConfigManagerHost, IGridTickable -{ - private static final int INPUT_SLOT_INDEX_TOP_LEFT = 0; - private static final int INPUT_SLOT_INDEX_TOP_RIGHT = 1; - private static final int INPUT_SLOT_INDEX_CENTER_LEFT = 2; - private static final int INPUT_SLOT_INDEX_CENTER_RIGHT = 3; - private static final int INPUT_SLOT_INDEX_BOTTOM_LEFT = 4; - private static final int INPUT_SLOT_INDEX_BOTTOM_RIGHT = 5; - - private static final int OUTPUT_SLOT_INDEX_TOP_LEFT = 6; - private static final int OUTPUT_SLOT_INDEX_TOP_RIGHT = 7; - private static final int OUTPUT_SLOT_INDEX_CENTER_LEFT = 8; - private static final int OUTPUT_SLOT_INDEX_CENTER_RIGHT = 9; - private static final int OUTPUT_SLOT_INDEX_BOTTOM_LEFT = 10; - private static final int OUTPUT_SLOT_INDEX_BOTTOM_RIGHT = 11; - - private final ConfigManager manager; - - private final int[] input = { INPUT_SLOT_INDEX_TOP_LEFT, INPUT_SLOT_INDEX_TOP_RIGHT, INPUT_SLOT_INDEX_CENTER_LEFT, INPUT_SLOT_INDEX_CENTER_RIGHT, INPUT_SLOT_INDEX_BOTTOM_LEFT, INPUT_SLOT_INDEX_BOTTOM_RIGHT }; - private final int[] output = { OUTPUT_SLOT_INDEX_TOP_LEFT, OUTPUT_SLOT_INDEX_TOP_RIGHT, OUTPUT_SLOT_INDEX_CENTER_LEFT, OUTPUT_SLOT_INDEX_CENTER_RIGHT, OUTPUT_SLOT_INDEX_BOTTOM_LEFT, OUTPUT_SLOT_INDEX_BOTTOM_RIGHT }; - - private final AppEngInternalInventory cells; - private final UpgradeInventory upgrades; - - private final BaseActionSource mySrc; - - private YesNo lastRedstoneState; - private ItemStack currentCell; - private IMEInventory cachedFluid; - private IMEInventory cachedItem; - - @Reflected - public TileIOPort() - { - this.getProxy().setFlags( GridFlags.REQUIRE_CHANNEL ); - this.manager = new ConfigManager( this ); - this.manager.registerSetting( Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE ); - this.manager.registerSetting( Settings.FULLNESS_MODE, FullnessMode.EMPTY ); - this.manager.registerSetting( Settings.OPERATION_MODE, OperationMode.EMPTY ); - this.cells = new AppEngInternalInventory( this, 12 ); - this.mySrc = new MachineSource( this ); - this.lastRedstoneState = YesNo.UNDECIDED; - - final Block ioPortBlock = AEApi.instance().definitions().blocks().iOPort().maybeBlock().get(); - this.upgrades = new BlockUpgradeInventory( ioPortBlock, this, 3 ); - } - - @TileEvent( TileEventType.WORLD_NBT_WRITE ) - public void writeToNBT_TileIOPort( final NBTTagCompound data ) - { - this.manager.writeToNBT( data ); - this.cells.writeToNBT( data, "cells" ); - this.upgrades.writeToNBT( data, "upgrades" ); - data.setInteger( "lastRedstoneState", this.lastRedstoneState.ordinal() ); - } - - @TileEvent( TileEventType.WORLD_NBT_READ ) - public void readFromNBT_TileIOPort( final NBTTagCompound data ) - { - this.manager.readFromNBT( data ); - this.cells.readFromNBT( data, "cells" ); - this.upgrades.readFromNBT( data, "upgrades" ); - if( data.hasKey( "lastRedstoneState" ) ) - { - this.lastRedstoneState = YesNo.values()[data.getInteger( "lastRedstoneState" )]; - } - } - - @Override - public AECableType getCableConnectionType( final ForgeDirection dir ) - { - return AECableType.SMART; - } - - @Override - public DimensionalCoord getLocation() - { - return new DimensionalCoord( this ); - } - - private void updateTask() - { - try - { - if( this.hasWork() ) - { - this.getProxy().getTick().wakeDevice( this.getProxy().getNode() ); - } - else - { - this.getProxy().getTick().sleepDevice( this.getProxy().getNode() ); - } - } - catch( final GridAccessException e ) - { - // :P - } - } - - public void updateRedstoneState() - { - final YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered( this.xCoord, this.yCoord, this.zCoord ) ? YesNo.YES : YesNo.NO; - if( this.lastRedstoneState != currentState ) - { - this.lastRedstoneState = currentState; - this.updateTask(); - } - } - - private boolean getRedstoneState() - { - if( this.lastRedstoneState == YesNo.UNDECIDED ) - { - this.updateRedstoneState(); - } - - return this.lastRedstoneState == YesNo.YES; - } - - private boolean isEnabled() - { - if( this.getInstalledUpgrades( Upgrades.REDSTONE ) == 0 ) - { - return true; - } - - final RedstoneMode rs = (RedstoneMode) this.manager.getSetting( Settings.REDSTONE_CONTROLLED ); - if( rs == RedstoneMode.HIGH_SIGNAL ) - { - return this.getRedstoneState(); - } - return !this.getRedstoneState(); - } - - @Override - public IConfigManager getConfigManager() - { - return this.manager; - } - - @Override - public IInventory getInventoryByName( final String name ) - { - if( name.equals( "upgrades" ) ) - { - return this.upgrades; - } - - if( name.equals( "cells" ) ) - { - return this.cells; - } - - return null; - } - - @Override - public void updateSetting( final IConfigManager manager, final Enum settingName, final Enum newValue ) - { - this.updateTask(); - } - - private boolean hasWork() - { - if( this.isEnabled() ) - { - for( int x = 0; x < 6; x++ ) - { - if( this.cells.getStackInSlot( x ) != null ) - { - return true; - } - } - } - - return false; - } - - @Override - public IInventory getInternalInventory() - { - return this.cells; - } - - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { - if( this.cells == inv ) - { - this.updateTask(); - } - } - - @Override - public boolean canInsertItem( final int slotIndex, final ItemStack insertingItem, final int side ) - { - for( final int inputSlotIndex : this.input ) - { - if( inputSlotIndex == slotIndex ) - { - return true; - } - } - - return false; - } - - @Override - public boolean canExtractItem( final int slotIndex, final ItemStack extractedItem, final int side ) - { - for( final int outputSlotIndex : this.output ) - { - if( outputSlotIndex == slotIndex ) - { - return true; - } - } - - return false; - } - - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection d ) - { - if( d == ForgeDirection.UP || d == ForgeDirection.DOWN ) - { - return this.input; - } - - return this.output; - } - - @Override - public TickingRequest getTickingRequest( final IGridNode node ) - { - return new TickingRequest( TickRates.IOPort.getMin(), TickRates.IOPort.getMax(), this.hasWork(), false ); - } - - @Override - public TickRateModulation tickingRequest( final IGridNode node, final int ticksSinceLastCall ) - { - if( !this.getProxy().isActive() ) - { - return TickRateModulation.IDLE; - } - - long ItemsToMove = 256; - - switch( this.getInstalledUpgrades( Upgrades.SPEED ) ) - { - case 1: - ItemsToMove *= 2; - break; - case 2: - ItemsToMove *= 4; - break; - case 3: - ItemsToMove *= 8; - break; - } - - try - { - final IMEInventory itemNet = this.getProxy().getStorage().getItemInventory(); - final IMEInventory fluidNet = this.getProxy().getStorage().getFluidInventory(); - final IEnergySource energy = this.getProxy().getEnergy(); - for( int x = 0; x < 6; x++ ) - { - final ItemStack is = this.cells.getStackInSlot( x ); - if( is != null ) - { - if( ItemsToMove > 0 ) - { - final IMEInventory itemInv = this.getInv( is, StorageChannel.ITEMS ); - final IMEInventory fluidInv = this.getInv( is, StorageChannel.FLUIDS ); - - if( this.manager.getSetting( Settings.OPERATION_MODE ) == OperationMode.EMPTY ) - { - if( itemInv != null ) - { - ItemsToMove = this.transferContents( energy, itemInv, itemNet, ItemsToMove, StorageChannel.ITEMS ); - } - if( fluidInv != null ) - { - ItemsToMove = this.transferContents( energy, fluidInv, fluidNet, ItemsToMove, StorageChannel.FLUIDS ); - } - } - else - { - if( itemInv != null ) - { - ItemsToMove = this.transferContents( energy, itemNet, itemInv, ItemsToMove, StorageChannel.ITEMS ); - } - if( fluidInv != null ) - { - ItemsToMove = this.transferContents( energy, fluidNet, fluidInv, ItemsToMove, StorageChannel.FLUIDS ); - } - } - - if( ItemsToMove > 0 && this.shouldMove( itemInv, fluidInv ) && !this.moveSlot( x ) ) - { - return TickRateModulation.IDLE; - } - - return TickRateModulation.URGENT; - } - else - { - return TickRateModulation.URGENT; - } - } - } - } - catch( final GridAccessException e ) - { - return TickRateModulation.IDLE; - } - - // nothing left to do... - return TickRateModulation.SLEEP; - } - - @Override - public int getInstalledUpgrades( final Upgrades u ) - { - return this.upgrades.getInstalledUpgrades( u ); - } - - private IMEInventory getInv( final ItemStack is, final StorageChannel chan ) - { - if( this.currentCell != is ) - { - this.currentCell = is; - this.cachedFluid = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.FLUIDS ); - this.cachedItem = AEApi.instance().registries().cell().getCellInventory( is, null, StorageChannel.ITEMS ); - } - - if( StorageChannel.ITEMS == chan ) - { - return this.cachedItem; - } - - return this.cachedFluid; - } - - private long transferContents( final IEnergySource energy, final IMEInventory src, final IMEInventory destination, long itemsToMove, final StorageChannel chan ) - { - final IItemList myList; - if( src instanceof IMEMonitor ) - { - myList = ( (IMEMonitor) src ).getStorageList(); - } - else - { - myList = src.getAvailableItems( src.getChannel().createList() ); - } - - boolean didStuff; - - do - { - didStuff = false; - - for( final IAEStack s : myList ) - { - final long totalStackSize = s.getStackSize(); - if( totalStackSize > 0 ) - { - final IAEStack stack = destination.injectItems( s, Actionable.SIMULATE, this.mySrc ); - - long possible = 0; - if( stack == null ) - { - possible = totalStackSize; - } - else - { - possible = totalStackSize - stack.getStackSize(); - } - - if( possible > 0 ) - { - possible = Math.min( possible, itemsToMove ); - s.setStackSize( possible ); - - final IAEStack extracted = src.extractItems( s, Actionable.MODULATE, this.mySrc ); - if( extracted != null ) - { - possible = extracted.getStackSize(); - final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc ); - - if( failed != null ) - { - possible -= failed.getStackSize(); - src.injectItems( failed, Actionable.MODULATE, this.mySrc ); - } - - if( possible > 0 ) - { - itemsToMove -= possible; - didStuff = true; - } - - break; - } - } - } - } - } - while( itemsToMove > 0 && didStuff ); - - return itemsToMove; - } - - private boolean shouldMove( final IMEInventory itemInv, final IMEInventory fluidInv ) - { - final FullnessMode fm = (FullnessMode) this.manager.getSetting( Settings.FULLNESS_MODE ); - - if( itemInv != null && fluidInv != null ) - { - return this.matches( fm, itemInv ) && this.matches( fm, fluidInv ); - } - else if( itemInv != null ) - { - return this.matches( fm, itemInv ); - } - else if( fluidInv != null ) - { - return this.matches( fm, fluidInv ); - } - - return true; - } - - private boolean moveSlot( final int x ) - { - final WrapperInventoryRange wir = new WrapperInventoryRange( this, this.output, true ); - final ItemStack result = InventoryAdaptor.getAdaptor( wir, ForgeDirection.UNKNOWN ).addItems( this.getStackInSlot( x ) ); - - if( result == null ) - { - this.setInventorySlotContents( x, null ); - return true; - } - - return false; - } - - private boolean matches( final FullnessMode fm, final IMEInventory src ) - { - if( fm == FullnessMode.HALF ) - { - return true; - } - - final IItemList myList; - - if( src instanceof IMEMonitor ) - { - myList = ( (IMEMonitor) src ).getStorageList(); - } - else - { - myList = src.getAvailableItems( src.getChannel().createList() ); - } - - if( fm == FullnessMode.EMPTY ) - { - return myList.isEmpty(); - } - - final IAEStack test = myList.getFirstItem(); - if( test != null ) - { - test.setStackSize( 1 ); - return src.injectItems( test, Actionable.SIMULATE, this.mySrc ) != null; - } - return false; - } - - /** - * Adds the items in the upgrade slots to the drop list. - * - * @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( final World w, final int x, final int y, final int z, final List drops ) - { - super.getDrops( w, x, y, z, drops ); - - for( int upgradeIndex = 0; upgradeIndex < this.upgrades.getSizeInventory(); upgradeIndex++ ) - { - final ItemStack stackInSlot = this.upgrades.getStackInSlot( upgradeIndex ); - - if( stackInSlot != null ) - { - drops.add( stackInSlot ); - } - } - } +public class TileIOPort extends AENetworkInvTile + implements IUpgradeableHost, IConfigManagerHost, IGridTickable { + private static final int INPUT_SLOT_INDEX_TOP_LEFT = 0; + private static final int INPUT_SLOT_INDEX_TOP_RIGHT = 1; + private static final int INPUT_SLOT_INDEX_CENTER_LEFT = 2; + private static final int INPUT_SLOT_INDEX_CENTER_RIGHT = 3; + private static final int INPUT_SLOT_INDEX_BOTTOM_LEFT = 4; + private static final int INPUT_SLOT_INDEX_BOTTOM_RIGHT = 5; + + private static final int OUTPUT_SLOT_INDEX_TOP_LEFT = 6; + private static final int OUTPUT_SLOT_INDEX_TOP_RIGHT = 7; + private static final int OUTPUT_SLOT_INDEX_CENTER_LEFT = 8; + private static final int OUTPUT_SLOT_INDEX_CENTER_RIGHT = 9; + private static final int OUTPUT_SLOT_INDEX_BOTTOM_LEFT = 10; + private static final int OUTPUT_SLOT_INDEX_BOTTOM_RIGHT = 11; + + private final ConfigManager manager; + + private final int[] input + = { INPUT_SLOT_INDEX_TOP_LEFT, INPUT_SLOT_INDEX_TOP_RIGHT, + INPUT_SLOT_INDEX_CENTER_LEFT, INPUT_SLOT_INDEX_CENTER_RIGHT, + INPUT_SLOT_INDEX_BOTTOM_LEFT, INPUT_SLOT_INDEX_BOTTOM_RIGHT }; + private final int[] output + = { OUTPUT_SLOT_INDEX_TOP_LEFT, OUTPUT_SLOT_INDEX_TOP_RIGHT, + OUTPUT_SLOT_INDEX_CENTER_LEFT, OUTPUT_SLOT_INDEX_CENTER_RIGHT, + OUTPUT_SLOT_INDEX_BOTTOM_LEFT, OUTPUT_SLOT_INDEX_BOTTOM_RIGHT }; + + private final AppEngInternalInventory cells; + private final UpgradeInventory upgrades; + + private final BaseActionSource mySrc; + + private YesNo lastRedstoneState; + private ItemStack currentCell; + private IMEInventory cachedFluid; + private IMEInventory cachedItem; + + @Reflected + public TileIOPort() { + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.manager = new ConfigManager(this); + this.manager.registerSetting(Settings.REDSTONE_CONTROLLED, RedstoneMode.IGNORE); + this.manager.registerSetting(Settings.FULLNESS_MODE, FullnessMode.EMPTY); + this.manager.registerSetting(Settings.OPERATION_MODE, OperationMode.EMPTY); + this.cells = new AppEngInternalInventory(this, 12); + this.mySrc = new MachineSource(this); + this.lastRedstoneState = YesNo.UNDECIDED; + + final Block ioPortBlock + = AEApi.instance().definitions().blocks().iOPort().maybeBlock().get(); + this.upgrades = new BlockUpgradeInventory(ioPortBlock, this, 3); + } + + @TileEvent(TileEventType.WORLD_NBT_WRITE) + public void writeToNBT_TileIOPort(final NBTTagCompound data) { + this.manager.writeToNBT(data); + this.cells.writeToNBT(data, "cells"); + this.upgrades.writeToNBT(data, "upgrades"); + data.setInteger("lastRedstoneState", this.lastRedstoneState.ordinal()); + } + + @TileEvent(TileEventType.WORLD_NBT_READ) + public void readFromNBT_TileIOPort(final NBTTagCompound data) { + this.manager.readFromNBT(data); + this.cells.readFromNBT(data, "cells"); + this.upgrades.readFromNBT(data, "upgrades"); + if (data.hasKey("lastRedstoneState")) { + this.lastRedstoneState = YesNo.values()[data.getInteger("lastRedstoneState")]; + } + } + + @Override + public AECableType getCableConnectionType(final ForgeDirection dir) { + return AECableType.SMART; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + private void updateTask() { + try { + if (this.hasWork()) { + this.getProxy().getTick().wakeDevice(this.getProxy().getNode()); + } else { + this.getProxy().getTick().sleepDevice(this.getProxy().getNode()); + } + } catch (final GridAccessException e) { + // :P + } + } + + public void updateRedstoneState() { + final YesNo currentState = this.worldObj.isBlockIndirectlyGettingPowered( + this.xCoord, this.yCoord, this.zCoord + ) + ? YesNo.YES + : YesNo.NO; + if (this.lastRedstoneState != currentState) { + this.lastRedstoneState = currentState; + this.updateTask(); + } + } + + private boolean getRedstoneState() { + if (this.lastRedstoneState == YesNo.UNDECIDED) { + this.updateRedstoneState(); + } + + return this.lastRedstoneState == YesNo.YES; + } + + private boolean isEnabled() { + if (this.getInstalledUpgrades(Upgrades.REDSTONE) == 0) { + return true; + } + + final RedstoneMode rs + = (RedstoneMode) this.manager.getSetting(Settings.REDSTONE_CONTROLLED); + if (rs == RedstoneMode.HIGH_SIGNAL) { + return this.getRedstoneState(); + } + return !this.getRedstoneState(); + } + + @Override + public IConfigManager getConfigManager() { + return this.manager; + } + + @Override + public IInventory getInventoryByName(final String name) { + if (name.equals("upgrades")) { + return this.upgrades; + } + + if (name.equals("cells")) { + return this.cells; + } + + return null; + } + + @Override + public void updateSetting( + final IConfigManager manager, final Enum settingName, final Enum newValue + ) { + this.updateTask(); + } + + private boolean hasWork() { + if (this.isEnabled()) { + for (int x = 0; x < 6; x++) { + if (this.cells.getStackInSlot(x) != null) { + return true; + } + } + } + + return false; + } + + @Override + public IInventory getInternalInventory() { + return this.cells; + } + + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) { + if (this.cells == inv) { + this.updateTask(); + } + } + + @Override + public boolean + canInsertItem(final int slotIndex, final ItemStack insertingItem, final int side) { + for (final int inputSlotIndex : this.input) { + if (inputSlotIndex == slotIndex) { + return true; + } + } + + return false; + } + + @Override + public boolean + canExtractItem(final int slotIndex, final ItemStack extractedItem, final int side) { + for (final int outputSlotIndex : this.output) { + if (outputSlotIndex == slotIndex) { + return true; + } + } + + return false; + } + + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection d) { + if (d == ForgeDirection.UP || d == ForgeDirection.DOWN) { + return this.input; + } + + return this.output; + } + + @Override + public TickingRequest getTickingRequest(final IGridNode node) { + return new TickingRequest( + TickRates.IOPort.getMin(), TickRates.IOPort.getMax(), this.hasWork(), false + ); + } + + @Override + public TickRateModulation + tickingRequest(final IGridNode node, final int ticksSinceLastCall) { + if (!this.getProxy().isActive()) { + return TickRateModulation.IDLE; + } + + long ItemsToMove = 256; + + switch (this.getInstalledUpgrades(Upgrades.SPEED)) { + case 1: + ItemsToMove *= 2; + break; + case 2: + ItemsToMove *= 4; + break; + case 3: + ItemsToMove *= 8; + break; + } + + try { + final IMEInventory itemNet + = this.getProxy().getStorage().getItemInventory(); + final IMEInventory fluidNet + = this.getProxy().getStorage().getFluidInventory(); + final IEnergySource energy = this.getProxy().getEnergy(); + for (int x = 0; x < 6; x++) { + final ItemStack is = this.cells.getStackInSlot(x); + if (is != null) { + if (ItemsToMove > 0) { + final IMEInventory itemInv + = this.getInv(is, StorageChannel.ITEMS); + final IMEInventory fluidInv + = this.getInv(is, StorageChannel.FLUIDS); + + if (this.manager.getSetting(Settings.OPERATION_MODE) + == OperationMode.EMPTY) { + if (itemInv != null) { + ItemsToMove = this.transferContents( + energy, + itemInv, + itemNet, + ItemsToMove, + StorageChannel.ITEMS + ); + } + if (fluidInv != null) { + ItemsToMove = this.transferContents( + energy, + fluidInv, + fluidNet, + ItemsToMove, + StorageChannel.FLUIDS + ); + } + } else { + if (itemInv != null) { + ItemsToMove = this.transferContents( + energy, + itemNet, + itemInv, + ItemsToMove, + StorageChannel.ITEMS + ); + } + if (fluidInv != null) { + ItemsToMove = this.transferContents( + energy, + fluidNet, + fluidInv, + ItemsToMove, + StorageChannel.FLUIDS + ); + } + } + + if (ItemsToMove > 0 && this.shouldMove(itemInv, fluidInv) + && !this.moveSlot(x)) { + return TickRateModulation.IDLE; + } + + return TickRateModulation.URGENT; + } else { + return TickRateModulation.URGENT; + } + } + } + } catch (final GridAccessException e) { + return TickRateModulation.IDLE; + } + + // nothing left to do... + return TickRateModulation.SLEEP; + } + + @Override + public int getInstalledUpgrades(final Upgrades u) { + return this.upgrades.getInstalledUpgrades(u); + } + + private IMEInventory getInv(final ItemStack is, final StorageChannel chan) { + if (this.currentCell != is) { + this.currentCell = is; + this.cachedFluid = AEApi.instance().registries().cell().getCellInventory( + is, null, StorageChannel.FLUIDS + ); + this.cachedItem = AEApi.instance().registries().cell().getCellInventory( + is, null, StorageChannel.ITEMS + ); + } + + if (StorageChannel.ITEMS == chan) { + return this.cachedItem; + } + + return this.cachedFluid; + } + + private long transferContents( + final IEnergySource energy, + final IMEInventory src, + final IMEInventory destination, + long itemsToMove, + final StorageChannel chan + ) { + final IItemList myList; + if (src instanceof IMEMonitor) { + myList = ((IMEMonitor) src).getStorageList(); + } else { + myList = src.getAvailableItems(src.getChannel().createList()); + } + + boolean didStuff; + + do { + didStuff = false; + + for (final IAEStack s : myList) { + final long totalStackSize = s.getStackSize(); + if (totalStackSize > 0) { + final IAEStack stack + = destination.injectItems(s, Actionable.SIMULATE, this.mySrc); + + long possible = 0; + if (stack == null) { + possible = totalStackSize; + } else { + possible = totalStackSize - stack.getStackSize(); + } + + if (possible > 0) { + possible = Math.min(possible, itemsToMove); + s.setStackSize(possible); + + final IAEStack extracted + = src.extractItems(s, Actionable.MODULATE, this.mySrc); + if (extracted != null) { + possible = extracted.getStackSize(); + final IAEStack failed = Platform.poweredInsert( + energy, destination, extracted, this.mySrc + ); + + if (failed != null) { + possible -= failed.getStackSize(); + src.injectItems(failed, Actionable.MODULATE, this.mySrc); + } + + if (possible > 0) { + itemsToMove -= possible; + didStuff = true; + } + + break; + } + } + } + } + } while (itemsToMove > 0 && didStuff); + + return itemsToMove; + } + + private boolean shouldMove( + final IMEInventory itemInv, + final IMEInventory fluidInv + ) { + final FullnessMode fm + = (FullnessMode) this.manager.getSetting(Settings.FULLNESS_MODE); + + if (itemInv != null && fluidInv != null) { + return this.matches(fm, itemInv) && this.matches(fm, fluidInv); + } else if (itemInv != null) { + return this.matches(fm, itemInv); + } else if (fluidInv != null) { + return this.matches(fm, fluidInv); + } + + return true; + } + + private boolean moveSlot(final int x) { + final WrapperInventoryRange wir + = new WrapperInventoryRange(this, this.output, true); + final ItemStack result = InventoryAdaptor.getAdaptor(wir, ForgeDirection.UNKNOWN) + .addItems(this.getStackInSlot(x)); + + if (result == null) { + this.setInventorySlotContents(x, null); + return true; + } + + return false; + } + + private boolean matches(final FullnessMode fm, final IMEInventory src) { + if (fm == FullnessMode.HALF) { + return true; + } + + final IItemList myList; + + if (src instanceof IMEMonitor) { + myList = ((IMEMonitor) src).getStorageList(); + } else { + myList = src.getAvailableItems(src.getChannel().createList()); + } + + if (fm == FullnessMode.EMPTY) { + return myList.isEmpty(); + } + + final IAEStack test = myList.getFirstItem(); + if (test != null) { + test.setStackSize(1); + return src.injectItems(test, Actionable.SIMULATE, this.mySrc) != null; + } + return false; + } + + /** + * Adds the items in the upgrade slots to the drop list. + * + * @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( + final World w, final int x, final int y, final int z, final List drops + ) { + super.getDrops(w, x, y, z, drops); + + for (int upgradeIndex = 0; upgradeIndex < this.upgrades.getSizeInventory(); + upgradeIndex++) { + final ItemStack stackInSlot = this.upgrades.getStackInSlot(upgradeIndex); + + if (stackInSlot != null) { + drops.add(stackInSlot); + } + } + } } diff --git a/src/main/java/appeng/tile/storage/TileSkyChest.java b/src/main/java/appeng/tile/storage/TileSkyChest.java index cdf74f65..fce5ca4c 100644 --- a/src/main/java/appeng/tile/storage/TileSkyChest.java +++ b/src/main/java/appeng/tile/storage/TileSkyChest.java @@ -18,7 +18,6 @@ package appeng.tile.storage; - import appeng.tile.AEBaseInvTile; import appeng.tile.TileEvent; import appeng.tile.events.TileEventType; @@ -30,128 +29,125 @@ import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; +public class TileSkyChest extends AEBaseInvTile { + private 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 }; + private final AppEngInternalInventory inv = new AppEngInternalInventory(this, 9 * 4); + // server + private int playerOpen; + // client.. + private long lastEvent; + private float lidAngle; -public class TileSkyChest extends AEBaseInvTile -{ + @TileEvent(TileEventType.NETWORK_WRITE) + public void writeToStream_TileSkyChest(final ByteBuf data) { + data.writeBoolean(this.getPlayerOpen() > 0); + } - private 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 }; - private final AppEngInternalInventory inv = new AppEngInternalInventory( this, 9 * 4 ); - // server - private int playerOpen; - // client.. - private long lastEvent; - private float lidAngle; + @TileEvent(TileEventType.NETWORK_READ) + public boolean readFromStream_TileSkyChest(final ByteBuf data) { + final int wasOpen = this.getPlayerOpen(); + this.setPlayerOpen(data.readBoolean() ? 1 : 0); - @TileEvent( TileEventType.NETWORK_WRITE ) - public void writeToStream_TileSkyChest( final ByteBuf data ) - { - data.writeBoolean( this.getPlayerOpen() > 0 ); - } + if (wasOpen != this.getPlayerOpen()) { + this.setLastEvent(System.currentTimeMillis()); + } - @TileEvent( TileEventType.NETWORK_READ ) - public boolean readFromStream_TileSkyChest( final ByteBuf data ) - { - final int wasOpen = this.getPlayerOpen(); - this.setPlayerOpen( data.readBoolean() ? 1 : 0 ); + return false; // TESR yo! + } - if( wasOpen != this.getPlayerOpen() ) - { - this.setLastEvent( System.currentTimeMillis() ); - } + @Override + public boolean requiresTESR() { + return true; + } - return false; // TESR yo! - } + @Override + public IInventory getInternalInventory() { + return this.inv; + } - @Override - public boolean requiresTESR() - { - return true; - } + @Override + public void openInventory() { + if (Platform.isClient()) { + return; + } - @Override - public IInventory getInternalInventory() - { - return this.inv; - } + this.setPlayerOpen(this.getPlayerOpen() + 1); - @Override - public void openInventory() - { - if( Platform.isClient() ) - { - return; - } + if (this.getPlayerOpen() == 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(); + } + } - this.setPlayerOpen( this.getPlayerOpen() + 1 ); + @Override + public void closeInventory() { + if (Platform.isClient()) { + return; + } - if( this.getPlayerOpen() == 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(); - } - } + this.setPlayerOpen(this.getPlayerOpen() - 1); - @Override - public void closeInventory() - { - if( Platform.isClient() ) - { - return; - } + if (this.getPlayerOpen() < 0) { + this.setPlayerOpen(0); + } - this.setPlayerOpen( this.getPlayerOpen() - 1 ); + if (this.getPlayerOpen() == 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.markForUpdate(); + } + } - if( this.getPlayerOpen() < 0 ) - { - this.setPlayerOpen( 0 ); - } + @Override + public void onChangeInventory( + final IInventory inv, + final int slot, + final InvOperation mc, + final ItemStack removed, + final ItemStack added + ) {} - if( this.getPlayerOpen() == 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.markForUpdate(); - } - } + @Override + public int[] getAccessibleSlotsBySide(final ForgeDirection side) { + return this.sides; + } - @Override - public void onChangeInventory( final IInventory inv, final int slot, final InvOperation mc, final ItemStack removed, final ItemStack added ) - { + public float getLidAngle() { + return this.lidAngle; + } - } + public void setLidAngle(final float lidAngle) { + this.lidAngle = lidAngle; + } - @Override - public int[] getAccessibleSlotsBySide( final ForgeDirection side ) - { - return this.sides; - } + public int getPlayerOpen() { + return this.playerOpen; + } - public float getLidAngle() - { - return this.lidAngle; - } + private void setPlayerOpen(final int playerOpen) { + this.playerOpen = playerOpen; + } - public void setLidAngle( final float lidAngle ) - { - this.lidAngle = lidAngle; - } + public long getLastEvent() { + return this.lastEvent; + } - public int getPlayerOpen() - { - return this.playerOpen; - } - - private void setPlayerOpen( final int playerOpen ) - { - this.playerOpen = playerOpen; - } - - public long getLastEvent() - { - return this.lastEvent; - } - - private void setLastEvent( final long lastEvent ) - { - this.lastEvent = lastEvent; - } + private void setLastEvent(final long lastEvent) { + this.lastEvent = lastEvent; + } } diff --git a/src/main/java/appeng/transformer/AppEngCore.java b/src/main/java/appeng/transformer/AppEngCore.java index 1f76c6d0..0707301b 100644 --- a/src/main/java/appeng/transformer/AppEngCore.java +++ b/src/main/java/appeng/transformer/AppEngCore.java @@ -18,6 +18,8 @@ package appeng.transformer; +import java.util.Map; +import javax.annotation.Nullable; import appeng.core.AEConfig; import com.google.common.eventbus.EventBus; @@ -30,98 +32,78 @@ import cpw.mods.fml.relauncher.FMLRelaunchLog; import cpw.mods.fml.relauncher.IFMLLoadingPlugin; import cpw.mods.fml.relauncher.IFMLLoadingPlugin.MCVersion; -import javax.annotation.Nullable; -import java.util.Map; +@MCVersion("1.7.10") +public final class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin { + private final ModMetadata metadata = new ModMetadata(); + public AppEngCore() { + FMLRelaunchLog.info("[AppEng] Core Init"); + this.metadata.autogenerated = false; + this.metadata.authorList.add("AlgorithmX2"); + this.metadata.credits = "AlgorithmX2"; + this.metadata.modId = this.getModId(); + this.metadata.version = this.getVersion(); + this.metadata.name = this.getName(); + this.metadata.url = "http://ae2.ae-mod.info"; + this.metadata.logoFile = "assets/appliedenergistics2/meta/logo.png"; + this.metadata.description = "Embedded Coremod for Applied Energistics 2"; + } -@MCVersion( "1.7.10" ) -public final class AppEngCore extends DummyModContainer implements IFMLLoadingPlugin -{ - private final ModMetadata metadata = new ModMetadata(); + @EventHandler + public void load(final FMLInitializationEvent event) {} - public AppEngCore() - { - FMLRelaunchLog.info( "[AppEng] Core Init" ); - this.metadata.autogenerated = false; - this.metadata.authorList.add( "AlgorithmX2" ); - this.metadata.credits = "AlgorithmX2"; - this.metadata.modId = this.getModId(); - this.metadata.version = this.getVersion(); - this.metadata.name = this.getName(); - this.metadata.url = "http://ae2.ae-mod.info"; - this.metadata.logoFile = "assets/appliedenergistics2/meta/logo.png"; - this.metadata.description = "Embedded Coremod for Applied Energistics 2"; - } + @Override + public String[] getASMTransformerClass() { + return new String[] { "appeng.transformer.asm.ASMIntegration", + "appeng.transformer.asm.ApiRepairer" }; + } - @EventHandler - public void load( final FMLInitializationEvent event ) - { - } + @Override + public String getModContainerClass() { + return "appeng.transformer.AppEngCore"; + } - @Override - public String[] getASMTransformerClass() - { - return new String[] { "appeng.transformer.asm.ASMIntegration", "appeng.transformer.asm.ApiRepairer" }; - } + @Nullable + @Override + public String getSetupClass() { + return null; + } - @Override - public String getModContainerClass() - { - return "appeng.transformer.AppEngCore"; - } + @Override + public void injectData(final Map data) {} - @Nullable - @Override - public String getSetupClass() - { - return null; - } + @Override + public String getAccessTransformerClass() { + return "appeng.transformer.asm.ASMTweaker"; + } - @Override - public void injectData( final Map data ) - { + @Override + public ModMetadata getMetadata() { + return this.metadata; + } - } + @Override + public String getModId() { + return "appliedenergistics2-core"; + } - @Override - public String getAccessTransformerClass() - { - return "appeng.transformer.asm.ASMTweaker"; - } + @Override + public String getName() { + return "Applied Energistics 2 Core"; + } - @Override - public ModMetadata getMetadata() - { - return this.metadata; - } + @Override + public String getVersion() { + return AEConfig.VERSION; + } - @Override - public String getModId() - { - return "appliedenergistics2-core"; - } + @Override + public boolean registerBus(final EventBus bus, final LoadController controller) { + return true; + } - @Override - public String getName() - { - return "Applied Energistics 2 Core"; - } - - @Override - public String getVersion() - { - return AEConfig.VERSION; - } - - @Override - public boolean registerBus( final EventBus bus, final LoadController controller ) - { - return true; - } - - @Override - public String getDisplayVersion() - { - return this.getVersion(); - } + @Override + public String getDisplayVersion() { + return this.getVersion(); + } } diff --git a/src/main/java/appeng/transformer/MissingCoreMod.java b/src/main/java/appeng/transformer/MissingCoreMod.java index c981cb99..948445dc 100644 --- a/src/main/java/appeng/transformer/MissingCoreMod.java +++ b/src/main/java/appeng/transformer/MissingCoreMod.java @@ -18,83 +18,136 @@ package appeng.transformer; - import cpw.mods.fml.client.CustomModLoadingErrorDisplayException; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiErrorScreen; +@SideOnly(Side.CLIENT) +public final class MissingCoreMod extends CustomModLoadingErrorDisplayException { + private static final int SHADOW_WHITE = 0xeeeeee; + private static final int COLOR_WHITE = 0xffffff; + private static final long serialVersionUID = -966774766922821652L; + private static final int SCREEN_OFFSET = 15; -@SideOnly( Side.CLIENT ) -public final class MissingCoreMod extends CustomModLoadingErrorDisplayException -{ - private static final int SHADOW_WHITE = 0xeeeeee; - private static final int COLOR_WHITE = 0xffffff; - private static final long serialVersionUID = -966774766922821652L; - private static final int SCREEN_OFFSET = 15; + private boolean deobf = false; - private boolean deobf = false; + @Override + public void + initGui(final GuiErrorScreen errorScreen, final FontRenderer fontRenderer) { + final Class clz = errorScreen.getClass(); + try { + clz.getField("mc"); + this.deobf = true; + } catch (final Throwable ignored) {} + } - @Override - public void initGui( final GuiErrorScreen errorScreen, final FontRenderer fontRenderer ) - { - final Class clz = errorScreen.getClass(); - try - { - clz.getField( "mc" ); - this.deobf = true; - } - catch( final Throwable ignored ) - { + @Override + public void drawScreen( + final GuiErrorScreen errorScreen, + final FontRenderer fontRenderer, + final int mouseRelX, + final int mouseRelY, + final float tickTime + ) { + int offset = 10; + this.drawCenteredString( + fontRenderer, + "Sorry, couldn't load AE2 properly.", + errorScreen.width / 2, + offset, + COLOR_WHITE + ); - } - } + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Please make sure that AE2 is installed into your mods folder.", + errorScreen.width / 2, + offset, + SHADOW_WHITE + ); - @Override - public void drawScreen( final GuiErrorScreen errorScreen, final FontRenderer fontRenderer, final int mouseRelX, final int mouseRelY, final float tickTime ) - { - int offset = 10; - this.drawCenteredString( fontRenderer, "Sorry, couldn't load AE2 properly.", errorScreen.width / 2, offset, COLOR_WHITE ); + offset += 2 * SCREEN_OFFSET; - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Please make sure that AE2 is installed into your mods folder.", errorScreen.width / 2, offset, SHADOW_WHITE ); + if (this.deobf) { + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "In a developer environment add the following too your args,", + errorScreen.width / 2, + offset, + COLOR_WHITE + ); - offset += 2 * SCREEN_OFFSET; + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "-Dfml.coreMods.load=appeng.transformer.AppEngCore", + errorScreen.width / 2, + offset, + SHADOW_WHITE + ); + } else { + this.drawCenteredString( + fontRenderer, + "You're launcher may refer to this by different names,", + errorScreen.width / 2, + offset, + COLOR_WHITE + ); - if( this.deobf ) - { - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "In a developer environment add the following too your args,", errorScreen.width / 2, offset, COLOR_WHITE ); + offset += SCREEN_OFFSET + 5; - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "-Dfml.coreMods.load=appeng.transformer.AppEngCore", errorScreen.width / 2, offset, SHADOW_WHITE ); - } - else - { - this.drawCenteredString( fontRenderer, "You're launcher may refer to this by different names,", errorScreen.width / 2, offset, COLOR_WHITE ); + this.drawCenteredString( + fontRenderer, + "MultiMC calls this tab \"Loader Mods\"", + errorScreen.width / 2, + offset, + SHADOW_WHITE + ); - offset += SCREEN_OFFSET + 5; + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Magic Launcher calls this tab \"External Mods\"", + errorScreen.width / 2, + offset, + SHADOW_WHITE + ); - this.drawCenteredString( fontRenderer, "MultiMC calls this tab \"Loader Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); + offset += SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Most other launchers refer to this tab as just \"Mods\"", + errorScreen.width / 2, + offset, + SHADOW_WHITE + ); - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Magic Launcher calls this tab \"External Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); + offset += 2 * SCREEN_OFFSET; + this.drawCenteredString( + fontRenderer, + "Also make sure that the AE2 file is a .jar, and not a .zip", + errorScreen.width / 2, + offset, + COLOR_WHITE + ); + } + } - offset += SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Most other launchers refer to this tab as just \"Mods\"", errorScreen.width / 2, offset, SHADOW_WHITE ); + private void drawCenteredString( + final FontRenderer fontRenderer, + final String string, + final int x, + final int y, + final int colour + ) { + final String reEncoded = string.replaceAll("\\P{InBasic_Latin}", ""); + final int reEncodedWidth = fontRenderer.getStringWidth(reEncoded); + final int centeredX = x - reEncodedWidth / 2; - offset += 2 * SCREEN_OFFSET; - this.drawCenteredString( fontRenderer, "Also make sure that the AE2 file is a .jar, and not a .zip", errorScreen.width / 2, offset, COLOR_WHITE ); - } - } - - private void drawCenteredString( final FontRenderer fontRenderer, final String string, final int x, final int y, final int colour ) - { - final String reEncoded = string.replaceAll( "\\P{InBasic_Latin}", "" ); - final int reEncodedWidth = fontRenderer.getStringWidth( reEncoded ); - final int centeredX = x - reEncodedWidth / 2; - - fontRenderer.drawStringWithShadow( string, centeredX, y, colour ); - } + fontRenderer.drawStringWithShadow(string, centeredX, y, colour); + } } \ No newline at end of file diff --git a/src/main/java/appeng/transformer/annotations/Integration.java b/src/main/java/appeng/transformer/annotations/Integration.java index b84bd274..47dea8cc 100644 --- a/src/main/java/appeng/transformer/annotations/Integration.java +++ b/src/main/java/appeng/transformer/annotations/Integration.java @@ -18,36 +18,31 @@ package appeng.transformer.annotations; - -import appeng.integration.IntegrationType; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import appeng.integration.IntegrationType; -public @interface Integration -{ - @Retention( RetentionPolicy.RUNTIME ) - @Target( ElementType.TYPE ) @interface InterfaceList - { - Interface[] value(); - } +public @interface Integration { + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + @interface InterfaceList { + Interface[] value(); + } + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.TYPE) + @interface Interface { + String iface(); - @Retention( RetentionPolicy.RUNTIME ) - @Target( ElementType.TYPE ) @interface Interface - { - String iface(); + IntegrationType iname(); + } - IntegrationType iname(); - } - - - @Retention( RetentionPolicy.RUNTIME ) - @Target( ElementType.METHOD ) @interface Method - { - IntegrationType iname(); - } + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + @interface Method { + IntegrationType iname(); + } } \ No newline at end of file diff --git a/src/main/java/appeng/transformer/asm/ASMIntegration.java b/src/main/java/appeng/transformer/asm/ASMIntegration.java index f9db8ec4..ee77653f 100644 --- a/src/main/java/appeng/transformer/asm/ASMIntegration.java +++ b/src/main/java/appeng/transformer/asm/ASMIntegration.java @@ -18,6 +18,8 @@ package appeng.transformer.asm; +import java.util.Iterator; +import javax.annotation.Nullable; import appeng.helpers.Reflected; import appeng.integration.IntegrationRegistry; @@ -33,220 +35,204 @@ import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; -import javax.annotation.Nullable; -import java.util.Iterator; - - @Reflected -public final class ASMIntegration implements IClassTransformer -{ - @Reflected - public ASMIntegration() - { +public final class ASMIntegration implements IClassTransformer { + @Reflected + public ASMIntegration() { + /** + * Side, Display Name, ModID ClassPostFix + */ - /** - * Side, Display Name, ModID ClassPostFix - */ + for (final IntegrationType type : IntegrationType.values()) { + IntegrationRegistry.INSTANCE.add(type); + } - for( final IntegrationType type : IntegrationType.values() ) - { - IntegrationRegistry.INSTANCE.add( type ); - } + // integrationModules.add( IntegrationSide.BOTH, "Thermal Expansion", + // "ThermalExpansion", IntegrationType.TE ); integrationModules.add( + // IntegrationSide.BOTH, "Mystcraft", "Mystcraft", IntegrationType.Mystcraft ); + // integrationModules.add( IntegrationSide.BOTH, "Greg Tech", "gregtech_addon", + // IntegrationType.GT ); integrationModules.add( IntegrationSide.BOTH, "Universal + // Electricity", null, IntegrationType.UE ); integrationModules.add( + // IntegrationSide.BOTH, "Logistics Pipes", "LogisticsPipes|Main", + // IntegrationType.LP ); integrationModules.add( IntegrationSide.BOTH, "Better + // Storage", IntegrationType.betterstorage ); integrationModules.add( + // IntegrationSide.BOTH, "Forestry", "Forestry", IntegrationType.Forestry ); + // integrationModules.add( IntegrationSide.BOTH, "Mekanism", "Mekanism", + // IntegrationType.Mekanism ); + } - // integrationModules.add( IntegrationSide.BOTH, "Thermal Expansion", "ThermalExpansion", IntegrationType.TE ); - // integrationModules.add( IntegrationSide.BOTH, "Mystcraft", "Mystcraft", IntegrationType.Mystcraft ); - // integrationModules.add( IntegrationSide.BOTH, "Greg Tech", "gregtech_addon", IntegrationType.GT ); - // integrationModules.add( IntegrationSide.BOTH, "Universal Electricity", null, IntegrationType.UE ); - // integrationModules.add( IntegrationSide.BOTH, "Logistics Pipes", "LogisticsPipes|Main", IntegrationType.LP ); - // integrationModules.add( IntegrationSide.BOTH, "Better Storage", IntegrationType.betterstorage ); - // integrationModules.add( IntegrationSide.BOTH, "Forestry", "Forestry", IntegrationType.Forestry ); - // integrationModules.add( IntegrationSide.BOTH, "Mekanism", "Mekanism", IntegrationType.Mekanism ); + @Nullable + @Override + public byte[] transform( + final String name, final String transformedName, final byte[] basicClass + ) { + if (basicClass == null || transformedName.startsWith("appeng.transformer")) { + return basicClass; + } - } + if (transformedName.startsWith("appeng.")) { + final ClassNode classNode = new ClassNode(); + final ClassReader classReader = new ClassReader(basicClass); + classReader.accept(classNode, 0); - @Nullable - @Override - public byte[] transform( final String name, final String transformedName, final byte[] basicClass ) - { - if( basicClass == null || transformedName.startsWith( "appeng.transformer" ) ) - { - return basicClass; - } + try { + final boolean reWrite = this.removeOptionals(classNode); - if( transformedName.startsWith( "appeng." ) ) - { - final ClassNode classNode = new ClassNode(); - final ClassReader classReader = new ClassReader( basicClass ); - classReader.accept( classNode, 0 ); + if (reWrite) { + final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + return writer.toByteArray(); + } + } catch (final Throwable t) { + t.printStackTrace(); + } + } + return basicClass; + } - try - { - final boolean reWrite = this.removeOptionals( classNode ); + private boolean removeOptionals(final ClassNode classNode) { + boolean changed = false; - if( reWrite ) - { - final ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - classNode.accept( writer ); - return writer.toByteArray(); - } - } - catch( final Throwable t ) - { - t.printStackTrace(); - } - } - return basicClass; - } + if (classNode.visibleAnnotations != null) { + for (final AnnotationNode an : classNode.visibleAnnotations) { + if (this.hasAnnotation(an, Integration.Interface.class)) { + if (this.stripInterface(classNode, Integration.Interface.class, an)) { + changed = true; + } + } else if (this.hasAnnotation(an, Integration.InterfaceList.class)) { + for (final Object o : ((Iterable) an.values.get(1))) { + if (this.stripInterface( + classNode, + Integration.InterfaceList.class, + (AnnotationNode) o + )) { + changed = true; + } + } + } + } + } - private boolean removeOptionals( final ClassNode classNode ) - { - boolean changed = false; + final Iterator i = classNode.methods.iterator(); + while (i.hasNext()) { + final MethodNode mn = i.next(); - if( classNode.visibleAnnotations != null ) - { - for( final AnnotationNode an : classNode.visibleAnnotations ) - { - if( this.hasAnnotation( an, Integration.Interface.class ) ) - { - if( this.stripInterface( classNode, Integration.Interface.class, an ) ) - { - changed = true; - } - } - else if( this.hasAnnotation( an, Integration.InterfaceList.class ) ) - { - for( final Object o : ( (Iterable) an.values.get( 1 ) ) ) - { - if( this.stripInterface( classNode, Integration.InterfaceList.class, (AnnotationNode) o ) ) - { - changed = true; - } - } - } - } - } + if (mn.visibleAnnotations != null) { + for (final AnnotationNode an : mn.visibleAnnotations) { + if (this.hasAnnotation(an, Integration.Method.class)) { + if (this.stripMethod( + classNode, mn, i, Integration.Method.class, an + )) { + changed = true; + } + } + } + } + } - final Iterator i = classNode.methods.iterator(); - while( i.hasNext() ) - { - final MethodNode mn = i.next(); + if (changed) { + this.log("Updated " + classNode.name); + } - if( mn.visibleAnnotations != null ) - { - for( final AnnotationNode an : mn.visibleAnnotations ) - { - if( this.hasAnnotation( an, Integration.Method.class ) ) - { - if( this.stripMethod( classNode, mn, i, Integration.Method.class, an ) ) - { - changed = true; - } - } - } - } - } + return changed; + } - if( changed ) - { - this.log( "Updated " + classNode.name ); - } + private boolean hasAnnotation(final AnnotationNode ann, final Class annotation) { + return ann.desc.equals(Type.getDescriptor(annotation)); + } - return changed; - } + private boolean stripInterface( + final ClassNode classNode, final Class class1, final AnnotationNode an + ) { + if (an.values.size() != 4) { + throw new IllegalArgumentException( + "Unable to handle Interface annotation on " + classNode.name + ); + } - private boolean hasAnnotation( final AnnotationNode ann, final Class annotation ) - { - return ann.desc.equals( Type.getDescriptor( annotation ) ); - } + String iFace = null; - private boolean stripInterface( final ClassNode classNode, final Class class1, final AnnotationNode an ) - { - if( an.values.size() != 4 ) - { - throw new IllegalArgumentException( "Unable to handle Interface annotation on " + classNode.name ); - } + 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); + } - String iFace = null; + String iName = null; + if (an.values.get(0).equals("iname")) { + iName = ((String[]) an.values.get(1))[1]; + } else if (an.values.get(2).equals("iname")) { + iName = ((String[]) an.values.get(3))[1]; + } - 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 (iName != null && iFace != null) { + final IntegrationType type = IntegrationType.valueOf(iName); + if (!IntegrationRegistry.INSTANCE.isEnabled(type)) { + this.log( + "Removing Interface " + iFace + " from " + classNode.name + + " because " + iName + " integration is disabled." + ); + classNode.interfaces.remove(iFace.replace('.', '/')); + return true; + } else { + this.log( + "Allowing Interface " + iFace + " from " + classNode.name + + " because " + iName + " integration is enabled." + ); + } + } else { + throw new IllegalStateException( + "Unable to handle Method annotation on " + classNode.name + ); + } - String iName = null; - if( an.values.get( 0 ).equals( "iname" ) ) - { - iName = ( (String[]) an.values.get( 1 ) )[1]; - } - else if( an.values.get( 2 ).equals( "iname" ) ) - { - iName = ( (String[]) an.values.get( 3 ) )[1]; - } + return false; + } - if( iName != null && iFace != null ) - { - final IntegrationType type = IntegrationType.valueOf( iName ); - if( !IntegrationRegistry.INSTANCE.isEnabled( type ) ) - { - this.log( "Removing Interface " + iFace + " from " + classNode.name + " because " + iName + " integration is disabled." ); - classNode.interfaces.remove( iFace.replace( '.', '/' ) ); - return true; - } - else - { - this.log( "Allowing Interface " + iFace + " from " + classNode.name + " because " + iName + " integration is enabled." ); - } - } - else - { - throw new IllegalStateException( "Unable to handle Method annotation on " + classNode.name ); - } + private boolean stripMethod( + final ClassNode classNode, + final MethodNode mn, + final Iterator i, + final Class class1, + final AnnotationNode an + ) { + if (an.values.size() != 2) { + throw new IllegalArgumentException( + "Unable to handle Method annotation on " + classNode.name + ); + } - return false; - } + String iName = null; - private boolean stripMethod( final ClassNode classNode, final MethodNode mn, final Iterator i, final Class class1, final AnnotationNode an ) - { - if( an.values.size() != 2 ) - { - throw new IllegalArgumentException( "Unable to handle Method annotation on " + classNode.name ); - } + if (an.values.get(0).equals("iname")) { + iName = ((String[]) an.values.get(1))[1]; + } - String iName = null; + if (iName != null) { + final 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 IllegalStateException( + "Unable to handle Method annotation on " + classNode.name + ); + } - if( an.values.get( 0 ).equals( "iname" ) ) - { - iName = ( (String[]) an.values.get( 1 ) )[1]; - } + return false; + } - if( iName != null ) - { - final 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 IllegalStateException( "Unable to handle Method annotation on " + classNode.name ); - } - - return false; - } - - private void log( final String string ) - { - FMLRelaunchLog.log( "AE2-CORE", Level.INFO, string ); - } + private void log(final 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 d997bee8..2429b14e 100644 --- a/src/main/java/appeng/transformer/asm/ASMTweaker.java +++ b/src/main/java/appeng/transformer/asm/ASMTweaker.java @@ -18,6 +18,8 @@ package appeng.transformer.asm; +import java.util.Iterator; +import javax.annotation.Nullable; import appeng.helpers.Reflected; import com.google.common.collect.HashMultimap; @@ -30,133 +32,165 @@ import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.*; -import javax.annotation.Nullable; -import java.util.Iterator; - - @Reflected -public final class ASMTweaker implements IClassTransformer -{ - private static final String[] EXCEPTIONS = new String[0]; - private final Multimap privateToPublicMethods = HashMultimap.create(); +public final class ASMTweaker implements IClassTransformer { + private static final String[] EXCEPTIONS = new String[0]; + private final Multimap privateToPublicMethods + = HashMultimap.create(); - @Reflected - 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" ) ); + @Reflected + 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") + ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "writeToNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "func_145841_b", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "b", "(Ldh;)V" ) ); + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", + new PublicLine("writeToNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V") + ); + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", + new PublicLine("func_145841_b", "(Lnet/minecraft/nbt/NBTTagCompound;)V") + ); + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", new PublicLine("b", "(Ldh;)V") + ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "readFromNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "func_145839_a", "(Lnet/minecraft/nbt/NBTTagCompound;)V" ) ); - this.privateToPublicMethods.put( "appeng.tile.AEBaseTile", new PublicLine( "a", "(Ldh;)V" ) ); - } + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", + new PublicLine("readFromNBT", "(Lnet/minecraft/nbt/NBTTagCompound;)V") + ); + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", + new PublicLine("func_145839_a", "(Lnet/minecraft/nbt/NBTTagCompound;)V") + ); + this.privateToPublicMethods.put( + "appeng.tile.AEBaseTile", new PublicLine("a", "(Ldh;)V") + ); + } - @Nullable - @Override - public byte[] transform( final String name, final String transformedName, final byte[] basicClass ) - { - if( basicClass == null ) - { - return null; - } + @Nullable + @Override + public byte[] transform( + final String name, final String transformedName, final byte[] basicClass + ) { + if (basicClass == null) { + return null; + } - try - { - if( transformedName != null && this.privateToPublicMethods.containsKey( transformedName ) ) - { - final ClassNode classNode = new ClassNode(); - final ClassReader classReader = new ClassReader( basicClass ); - classReader.accept( classNode, 0 ); + try { + if (transformedName != null + && this.privateToPublicMethods.containsKey(transformedName)) { + final ClassNode classNode = new ClassNode(); + final ClassReader classReader = new ClassReader(basicClass); + classReader.accept(classNode, 0); - for( final PublicLine set : this.privateToPublicMethods.get( transformedName ) ) - { - this.makePublic( classNode, set ); - } + for (final PublicLine set : + this.privateToPublicMethods.get(transformedName)) { + this.makePublic(classNode, set); + } - // CALL VIRTUAL! - if( transformedName.equals( "net.minecraft.client.gui.inventory.GuiContainer" ) ) - { - for( final MethodNode mn : classNode.methods ) - { - if( mn.name.equals( "func_146977_a" ) || ( mn.name.equals( "a" ) && mn.desc.equals( "(Lzk;)V" ) ) ) - { - final MethodNode newNode = new MethodNode( Opcodes.ACC_PUBLIC, "func_146977_a_original", mn.desc, mn.signature, EXCEPTIONS ); - newNode.instructions.add( new VarInsnNode( Opcodes.ALOAD, 0 ) ); - newNode.instructions.add( new VarInsnNode( Opcodes.ALOAD, 1 ) ); - newNode.instructions.add( new MethodInsnNode( Opcodes.INVOKESPECIAL, classNode.name, mn.name, mn.desc, false ) ); - newNode.instructions.add( new InsnNode( Opcodes.RETURN ) ); - this.log( newNode.name + newNode.desc + " - New Method" ); - classNode.methods.add( newNode ); - break; - } - } + // CALL VIRTUAL! + if (transformedName.equals( + "net.minecraft.client.gui.inventory.GuiContainer" + )) { + for (final MethodNode mn : classNode.methods) { + if (mn.name.equals("func_146977_a") + || (mn.name.equals("a") && mn.desc.equals("(Lzk;)V"))) { + final MethodNode newNode = new MethodNode( + Opcodes.ACC_PUBLIC, + "func_146977_a_original", + mn.desc, + mn.signature, + EXCEPTIONS + ); + newNode.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); + newNode.instructions.add(new VarInsnNode(Opcodes.ALOAD, 1)); + newNode.instructions.add(new MethodInsnNode( + Opcodes.INVOKESPECIAL, + classNode.name, + mn.name, + mn.desc, + false + )); + newNode.instructions.add(new InsnNode(Opcodes.RETURN)); + this.log(newNode.name + newNode.desc + " - New Method"); + classNode.methods.add(newNode); + break; + } + } - for( final MethodNode mn : classNode.methods ) - { - if( mn.name.equals( "func_73863_a" ) || mn.name.equals( "drawScreen" ) || ( mn.name.equals( "a" ) && mn.desc.equals( "(IIF)V" ) ) ) - { - final Iterator i = mn.instructions.iterator(); - while( i.hasNext() ) - { - final AbstractInsnNode in = i.next(); - if( in.getOpcode() == Opcodes.INVOKESPECIAL ) - { - final MethodInsnNode n = (MethodInsnNode) in; - 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 ) ); - mn.instructions.remove( in ); - break; - } - } - } - } - } - } + for (final MethodNode mn : classNode.methods) { + if (mn.name.equals("func_73863_a") || mn.name.equals("drawScreen") + || (mn.name.equals("a") && mn.desc.equals("(IIF)V"))) { + final Iterator i + = mn.instructions.iterator(); + while (i.hasNext()) { + final AbstractInsnNode in = i.next(); + if (in.getOpcode() == Opcodes.INVOKESPECIAL) { + final MethodInsnNode n = (MethodInsnNode) in; + 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 + ) + ); + mn.instructions.remove(in); + break; + } + } + } + } + } + } - final ClassWriter writer = new ClassWriter( ClassWriter.COMPUTE_MAXS ); - classNode.accept( writer ); - return writer.toByteArray(); - } - } - catch( final Throwable ignored ) - { - } + final ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); + classNode.accept(writer); + return writer.toByteArray(); + } + } catch (final Throwable ignored) {} - return basicClass; - } + return basicClass; + } - private void makePublic( final ClassNode classNode, final PublicLine set ) - { - for( final MethodNode mn : classNode.methods ) - { - 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; - this.log( mn.name + mn.desc + " - Transformed" ); - } - } - } + private void makePublic(final ClassNode classNode, final PublicLine set) { + for (final MethodNode mn : classNode.methods) { + 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; + this.log(mn.name + mn.desc + " - Transformed"); + } + } + } - private void log( final String string ) - { - FMLRelaunchLog.log( "AE2-CORE", Level.INFO, string ); - } + private void log(final String string) { + FMLRelaunchLog.log("AE2-CORE", Level.INFO, string); + } - private static final class PublicLine - { - private final String name; - private final String desc; + private static final class PublicLine { + private final String name; + private final String desc; - public PublicLine( final String name, final String desc ) - { - this.name = name; - this.desc = desc; - } - } + public PublicLine(final String name, final String desc) { + this.name = name; + this.desc = desc; + } + } } diff --git a/src/main/java/appeng/transformer/asm/ApiRepairer.java b/src/main/java/appeng/transformer/asm/ApiRepairer.java index c02d5612..89c30ff6 100644 --- a/src/main/java/appeng/transformer/asm/ApiRepairer.java +++ b/src/main/java/appeng/transformer/asm/ApiRepairer.java @@ -18,6 +18,8 @@ package appeng.transformer.asm; +import java.net.URL; +import java.net.URLConnection; import appeng.helpers.Reflected; import cpw.mods.fml.relauncher.FMLRelaunchLog; @@ -25,58 +27,57 @@ import net.minecraft.launchwrapper.IClassTransformer; import net.minecraft.launchwrapper.LaunchClassLoader; import org.apache.logging.log4j.Level; -import java.net.URL; -import java.net.URLConnection; - - /* - * It is a ClassTransformer which can transformer the older AE2 api class that some addons including, - * which can occur the crash due to java.lang.NoSuchMethodError. - * See also : https://github.com/xsun2001/Applied-Energistics-2-Unofficial/issues/1 + * It is a ClassTransformer which can transformer the older AE2 api class that some addons + * including, which can occur the crash due to java.lang.NoSuchMethodError. See also : + * https://github.com/xsun2001/Applied-Energistics-2-Unofficial/issues/1 */ @Reflected -public class ApiRepairer implements IClassTransformer -{ +public class ApiRepairer implements IClassTransformer { + private LaunchClassLoader launchClassLoader; - private LaunchClassLoader launchClassLoader; + public ApiRepairer() { + launchClassLoader = (LaunchClassLoader) this.getClass().getClassLoader(); + FMLRelaunchLog.log("AE2-ApiRepairer", Level.INFO, "AE2 ApiFixer Installed"); + } - public ApiRepairer() - { - launchClassLoader = (LaunchClassLoader) this.getClass().getClassLoader(); - FMLRelaunchLog.log( "AE2-ApiRepairer", Level.INFO, "AE2 ApiFixer Installed" ); - } - - @Override public byte[] transform( String name, String transformedName, byte[] basicClass ) - { - if( transformedName.startsWith( "appeng.api" ) ) - { - try - { - String clazzurl = getClass().getResource( "" ).toString(); - clazzurl = clazzurl.substring( 0, clazzurl.length() - 23 ) + transformedName.replace( '.', '/' ) + ".class"; - //23 is "appeng/transformer/asm"'s length + 1 - URL url = new URL( clazzurl ); - URLConnection connection = url.openConnection(); - byte[] bytes = new byte[connection.getContentLength()]; - if( connection.getInputStream().read( bytes ) == -1 ) - { - FMLRelaunchLog.log( "AE2-ApiRepairer", Level.ERROR, "Failed to fix api class [%s] because the new class couldn't be read", transformedName ); - return basicClass; - } - for( IClassTransformer ct : launchClassLoader.getTransformers() ) - { - if( ct == this ) - continue; - bytes = ct.transform( name, transformedName, bytes ); - } - return bytes; - } - catch( Exception e ) - { - FMLRelaunchLog.log( "AE2-ApiRepairer", Level.ERROR, "Failed to fix api class [%s] because of [%s]", transformedName, e.getClass().getName() ); - return basicClass; - } - } - return basicClass; - } + @Override + public byte[] transform(String name, String transformedName, byte[] basicClass) { + if (transformedName.startsWith("appeng.api")) { + try { + String clazzurl = getClass().getResource("").toString(); + clazzurl = clazzurl.substring(0, clazzurl.length() - 23) + + transformedName.replace('.', '/') + ".class"; + //23 is "appeng/transformer/asm"'s length + 1 + URL url = new URL(clazzurl); + URLConnection connection = url.openConnection(); + byte[] bytes = new byte[connection.getContentLength()]; + if (connection.getInputStream().read(bytes) == -1) { + FMLRelaunchLog.log( + "AE2-ApiRepairer", + Level.ERROR, + "Failed to fix api class [%s] because the new class couldn't be read", + transformedName + ); + return basicClass; + } + for (IClassTransformer ct : launchClassLoader.getTransformers()) { + if (ct == this) + continue; + bytes = ct.transform(name, transformedName, bytes); + } + return bytes; + } catch (Exception e) { + FMLRelaunchLog.log( + "AE2-ApiRepairer", + Level.ERROR, + "Failed to fix api class [%s] because of [%s]", + transformedName, + e.getClass().getName() + ); + return basicClass; + } + } + return basicClass; + } } diff --git a/src/main/java/appeng/util/BlockUpdate.java b/src/main/java/appeng/util/BlockUpdate.java index 16fa9851..26348371 100644 --- a/src/main/java/appeng/util/BlockUpdate.java +++ b/src/main/java/appeng/util/BlockUpdate.java @@ -18,32 +18,27 @@ package appeng.util; - import net.minecraft.world.World; +public class BlockUpdate implements IWorldCallable { + private final int x; + private final int y; + private final int z; -public class BlockUpdate implements IWorldCallable -{ + public BlockUpdate(final int x, final int y, final int z) { + this.x = x; + this.y = y; + this.z = z; + } - private final int x; - private final int y; - private final int z; + @Override + public Boolean call(final World world) throws Exception { + if (world.blockExists(this.x, this.y, this.z)) { + world.notifyBlocksOfNeighborChange( + this.x, this.y, this.z, Platform.AIR_BLOCK + ); + } - public BlockUpdate( final int x, final int y, final int z ) - { - this.x = x; - this.y = y; - this.z = z; - } - - @Override - public Boolean call( final World world ) throws Exception - { - if( world.blockExists( this.x, this.y, this.z ) ) - { - world.notifyBlocksOfNeighborChange( this.x, this.y, this.z, Platform.AIR_BLOCK ); - } - - return true; - } + return true; + } } diff --git a/src/main/java/appeng/util/ClassInstantiation.java b/src/main/java/appeng/util/ClassInstantiation.java index fdb2dcbb..e63b5e8c 100644 --- a/src/main/java/appeng/util/ClassInstantiation.java +++ b/src/main/java/appeng/util/ClassInstantiation.java @@ -18,103 +18,99 @@ package appeng.util; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import appeng.core.AELog; import com.google.common.base.Optional; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; +public class ClassInstantiation { + private final Class template; + private final Object[] args; + public ClassInstantiation(final Class template, final Object... args) { + this.template = template; + this.args = args; + } -public class ClassInstantiation -{ - private final Class template; - private final Object[] args; + public Optional get() { + @SuppressWarnings("unchecked") + final Constructor[] constructors + = (Constructor[]) this.template.getConstructors(); - public ClassInstantiation( final Class template, final Object... args ) - { - this.template = template; - this.args = args; - } + for (final Constructor constructor : constructors) { + final Class[] paramTypes = constructor.getParameterTypes(); + if (paramTypes.length == this.args.length) { + boolean valid = true; - public Optional get() - { - @SuppressWarnings( "unchecked" ) final Constructor[] constructors = (Constructor[]) this.template.getConstructors(); + for (int idx = 0; idx < paramTypes.length; idx++) { + final Class cz = this.args[idx].getClass(); + if (!this.isClassMatch(paramTypes[idx], cz, this.args[idx])) { + valid = false; + } + } - for( final Constructor constructor : constructors ) - { - final Class[] paramTypes = constructor.getParameterTypes(); - if( paramTypes.length == this.args.length ) - { - boolean valid = true; + if (valid) { + try { + return Optional.of(constructor.newInstance(this.args)); + } catch (final InstantiationException e) { + e.printStackTrace(); + } catch (final IllegalAccessException e) { + e.printStackTrace(); + } catch (final InvocationTargetException e) { + e.printStackTrace(); + } + break; + } + } + } - for( int idx = 0; idx < paramTypes.length; idx++ ) - { - final Class cz = this.args[idx].getClass(); - if( !this.isClassMatch( paramTypes[idx], cz, this.args[idx] ) ) - { - valid = false; - } - } + return Optional.absent(); + } - if( valid ) - { - try - { - return Optional.of( constructor.newInstance( this.args ) ); - } - catch( final InstantiationException e ) - { - e.printStackTrace(); - } - catch( final IllegalAccessException e ) - { - e.printStackTrace(); - } - catch( final InvocationTargetException e ) - { - e.printStackTrace(); - } - break; - } - } - } + private boolean isClassMatch(Class expected, Class got, final Object value) { + if (value == null && !expected.isPrimitive()) { + return true; + } - return Optional.absent(); - } + expected = this.condense( + expected, + Boolean.class, + Character.class, + Byte.class, + Short.class, + Integer.class, + Long.class, + Float.class, + Double.class + ); + got = this.condense( + got, + Boolean.class, + Character.class, + Byte.class, + Short.class, + Integer.class, + Long.class, + Float.class, + Double.class + ); - private boolean isClassMatch( Class expected, Class got, final Object value ) - { - if( value == null && !expected.isPrimitive() ) - { - return true; - } + return expected == got || expected.isAssignableFrom(got); + } - expected = this.condense( expected, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ); - got = this.condense( got, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class ); - - return expected == got || expected.isAssignableFrom( got ); - } - - private Class condense( final Class expected, final Class... wrappers ) - { - if( expected.isPrimitive() ) - { - for( final Class clz : wrappers ) - { - try - { - if( expected == clz.getField( "TYPE" ).get( null ) ) - { - return clz; - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - } - return expected; - } + private Class condense(final Class expected, final Class... wrappers) { + if (expected.isPrimitive()) { + for (final Class clz : wrappers) { + try { + if (expected == clz.getField("TYPE").get(null)) { + return clz; + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + } + return expected; + } } diff --git a/src/main/java/appeng/util/ConfigManager.java b/src/main/java/appeng/util/ConfigManager.java index c76ea887..ce12572c 100644 --- a/src/main/java/appeng/util/ConfigManager.java +++ b/src/main/java/appeng/util/ConfigManager.java @@ -18,6 +18,9 @@ package appeng.util; +import java.util.EnumMap; +import java.util.Map; +import java.util.Set; import appeng.api.config.LevelEmitterMode; import appeng.api.config.Settings; @@ -26,106 +29,89 @@ import appeng.api.util.IConfigManager; import appeng.core.AELog; import net.minecraft.nbt.NBTTagCompound; -import java.util.EnumMap; -import java.util.Map; -import java.util.Set; +public final class ConfigManager implements IConfigManager { + private final Map> settings + = new EnumMap>(Settings.class); + private final IConfigManagerHost target; + public ConfigManager(final IConfigManagerHost tile) { + this.target = tile; + } -public final class ConfigManager implements IConfigManager -{ - private final Map> settings = new EnumMap>( Settings.class ); - private final IConfigManagerHost target; + @Override + public Set getSettings() { + return this.settings.keySet(); + } - public ConfigManager( final IConfigManagerHost tile ) - { - this.target = tile; - } + @Override + public void registerSetting(final Settings settingName, final Enum defaultValue) { + this.settings.put(settingName, defaultValue); + } - @Override - public Set getSettings() - { - return this.settings.keySet(); - } + @Override + public Enum getSetting(final Settings settingName) { + final Enum oldValue = this.settings.get(settingName); - @Override - public void registerSetting( final Settings settingName, final Enum defaultValue ) - { - this.settings.put( settingName, defaultValue ); - } + if (oldValue != null) { + return oldValue; + } - @Override - public Enum getSetting( final Settings settingName ) - { - final Enum oldValue = this.settings.get( settingName ); + throw new IllegalStateException( + "Invalid Config setting. Expected a non-null value for " + settingName + ); + } - if( oldValue != null ) - { - return oldValue; - } + @Override + public Enum putSetting(final Settings settingName, final Enum newValue) { + final Enum oldValue = this.getSetting(settingName); + this.settings.put(settingName, newValue); + this.target.updateSetting(this, settingName, newValue); + return oldValue; + } - throw new IllegalStateException( "Invalid Config setting. Expected a non-null value for " + settingName ); - } + /** + * save all settings using config manager. + * + * @param tagCompound to be written to compound + */ + @Override + public void writeToNBT(final NBTTagCompound tagCompound) { + for (final Map.Entry> entry : this.settings.entrySet()) { + tagCompound.setString( + entry.getKey().name(), this.settings.get(entry.getKey()).toString() + ); + } + } - @Override - public Enum putSetting( final Settings settingName, final Enum newValue ) - { - final Enum oldValue = this.getSetting( settingName ); - this.settings.put( settingName, newValue ); - this.target.updateSetting( this, settingName, newValue ); - return oldValue; - } + /** + * read all settings using config manager. + * + * @param tagCompound to be read from compound + */ + @Override + public void readFromNBT(final NBTTagCompound tagCompound) { + for (final Map.Entry> entry : this.settings.entrySet()) { + try { + if (tagCompound.hasKey(entry.getKey().name())) { + String value = tagCompound.getString(entry.getKey().name()); - /** - * save all settings using config manager. - * - * @param tagCompound to be written to compound - */ - @Override - public void writeToNBT( final NBTTagCompound tagCompound ) - { - for( final Map.Entry> entry : this.settings.entrySet() ) - { - tagCompound.setString( entry.getKey().name(), this.settings.get( entry.getKey() ).toString() ); - } - } + // Provides an upgrade path for the rename of this value in the API + // between rv1 and rv2 + if (value.equals("EXTACTABLE_ONLY")) { + value = StorageFilter.EXTRACTABLE_ONLY.toString(); + } else if (value.equals("STOREABLE_AMOUNT")) { + value = LevelEmitterMode.STORABLE_AMOUNT.toString(); + } - /** - * read all settings using config manager. - * - * @param tagCompound to be read from compound - */ - @Override - public void readFromNBT( final NBTTagCompound tagCompound ) - { - for( final Map.Entry> entry : this.settings.entrySet() ) - { - try - { - if( tagCompound.hasKey( entry.getKey().name() ) ) - { - String value = tagCompound.getString( entry.getKey().name() ); + final Enum oldValue = this.settings.get(entry.getKey()); - // Provides an upgrade path for the rename of this value in the API between rv1 and rv2 - if( value.equals( "EXTACTABLE_ONLY" ) ) - { - value = StorageFilter.EXTRACTABLE_ONLY.toString(); - } - else if( value.equals( "STOREABLE_AMOUNT" ) ) - { - value = LevelEmitterMode.STORABLE_AMOUNT.toString(); - } + final Enum newValue = Enum.valueOf(oldValue.getClass(), value); - final Enum oldValue = this.settings.get( entry.getKey() ); - - final Enum newValue = Enum.valueOf( oldValue.getClass(), value ); - - this.putSetting( entry.getKey(), newValue ); - } - } - catch( final IllegalArgumentException e ) - { - AELog.debug( e ); - } - } - } + this.putSetting(entry.getKey(), newValue); + } + } catch (final IllegalArgumentException e) { + AELog.debug(e); + } + } + } } diff --git a/src/main/java/appeng/util/IConfigManagerHost.java b/src/main/java/appeng/util/IConfigManagerHost.java index 1323a7df..f0fafc76 100644 --- a/src/main/java/appeng/util/IConfigManagerHost.java +++ b/src/main/java/appeng/util/IConfigManagerHost.java @@ -18,12 +18,8 @@ package appeng.util; - import appeng.api.util.IConfigManager; - -public interface IConfigManagerHost -{ - - void updateSetting( IConfigManager manager, Enum settingName, Enum newValue ); +public interface IConfigManagerHost { + void updateSetting(IConfigManager manager, Enum settingName, Enum newValue); } diff --git a/src/main/java/appeng/util/ISlimReadableNumberConverter.java b/src/main/java/appeng/util/ISlimReadableNumberConverter.java index ed8cdb35..5a2228c8 100644 --- a/src/main/java/appeng/util/ISlimReadableNumberConverter.java +++ b/src/main/java/appeng/util/ISlimReadableNumberConverter.java @@ -1,9 +1,7 @@ package appeng.util; - import javax.annotation.Nonnegative; - /** * Limits a number converter to a char width of at max 3 characters. * This is generally used for players, who activated the large font extension. @@ -12,19 +10,15 @@ import javax.annotation.Nonnegative; * @version rv2 * @since rv2 */ -public interface ISlimReadableNumberConverter -{ - /** - * Converts a number into a human readable form. It will not round the number, but down it. - * Will try to cut the number down 1 decimal later, but rarely because of the 3 width limitation. - * Can only handle non negative numbers - *

- * Example: - * 10000L -> 10K - * 9999L -> 9K, not 9.9K cause 4 width - * - * @param number to be converted number - * @return String in SI format cut down as far as possible - */ - String toSlimReadableForm( @Nonnegative long number ); +public interface ISlimReadableNumberConverter { + /** + * Converts a number into a human readable form. It will not round the number, but + * down it. Will try to cut the number down 1 decimal later, but rarely because of the + * 3 width limitation. Can only handle non negative numbers

Example: 10000L -> 10K + * 9999L -> 9K, not 9.9K cause 4 width + * + * @param number to be converted number + * @return String in SI format cut down as far as possible + */ + String toSlimReadableForm(@Nonnegative long number); } diff --git a/src/main/java/appeng/util/IWideReadableNumberConverter.java b/src/main/java/appeng/util/IWideReadableNumberConverter.java index 56602c2f..990679c1 100644 --- a/src/main/java/appeng/util/IWideReadableNumberConverter.java +++ b/src/main/java/appeng/util/IWideReadableNumberConverter.java @@ -1,9 +1,7 @@ package appeng.util; - import javax.annotation.Nonnegative; - /** * Limits a number converter to a char width of at max 4 characters * @@ -11,19 +9,18 @@ import javax.annotation.Nonnegative; * @version rv2 * @since rv2 */ -public interface IWideReadableNumberConverter -{ - /** - * Converts a number into a human readable form. It will not round the number, but down it. - * Will try to cut the number down 1 decimal later if width can be below 4. - * Can only handle non negative numbers - *

- * Example: - * 10000L -> 10K - * 9999L -> 9999 - * - * @param number to be converted number - * @return String in SI format cut down as far as possible - */ - String toWideReadableForm( @Nonnegative long number ); +public interface IWideReadableNumberConverter { + /** + * Converts a number into a human readable form. It will not round the number, but + * down it. Will try to cut the number down 1 decimal later if width can be below 4. + * Can only handle non negative numbers + *

+ * Example: + * 10000L -> 10K + * 9999L -> 9999 + * + * @param number to be converted number + * @return String in SI format cut down as far as possible + */ + String toWideReadableForm(@Nonnegative long number); } diff --git a/src/main/java/appeng/util/IWorldCallable.java b/src/main/java/appeng/util/IWorldCallable.java index f81e4e45..a31b23de 100644 --- a/src/main/java/appeng/util/IWorldCallable.java +++ b/src/main/java/appeng/util/IWorldCallable.java @@ -18,32 +18,31 @@ package appeng.util; +import java.util.concurrent.Callable; +import javax.annotation.Nullable; import net.minecraft.world.World; -import javax.annotation.Nullable; -import java.util.concurrent.Callable; - - /** - * An interface similar to {@link Callable}, but allowing to pass the {@link World} when calling. + * An interface similar to {@link Callable}, but allowing to pass the {@link World} when + * calling. * * @author yueh * @version rv3 * @see Callable * @since rv3 */ -public interface IWorldCallable -{ - /** - * Similar to {@link Callable#call()} - * - * @param world this param is given to not hold a reference to the world but let the caller handle it. Do not expect a world here thus can be - * null. - * @return result of call on the world. Can be null. - * @throws Exception if the call fails - * @see Callable#call() - */ - @Nullable - T call( @Nullable World world ) throws Exception; +public interface IWorldCallable { + /** + * Similar to {@link Callable#call()} + * + * @param world this param is given to not hold a reference to the world but let the + * caller handle it. Do not expect a world here thus can be + * null. + * @return result of call on the world. Can be null. + * @throws Exception if the call fails + * @see Callable#call() + */ + @Nullable + T call(@Nullable World world) throws Exception; } diff --git a/src/main/java/appeng/util/InWorldToolOperationResult.java b/src/main/java/appeng/util/InWorldToolOperationResult.java index 304047bf..b092cbcf 100644 --- a/src/main/java/appeng/util/InWorldToolOperationResult.java +++ b/src/main/java/appeng/util/InWorldToolOperationResult.java @@ -18,70 +18,60 @@ package appeng.util; +import java.util.ArrayList; +import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockAir; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.List; +public class InWorldToolOperationResult { + private final ItemStack BlockItem; + private final List Drops; + public InWorldToolOperationResult() { + this.BlockItem = null; + this.Drops = null; + } -public class InWorldToolOperationResult -{ + public InWorldToolOperationResult( + final ItemStack block, final List drops + ) { + this.BlockItem = block; + this.Drops = drops; + } - private final ItemStack BlockItem; - private final List Drops; + public InWorldToolOperationResult(final ItemStack block) { + this.BlockItem = block; + this.Drops = null; + } - public InWorldToolOperationResult() - { - this.BlockItem = null; - this.Drops = null; - } + public static InWorldToolOperationResult + getBlockOperationResult(final ItemStack[] items) { + final List temp = new ArrayList(); + ItemStack b = null; - public InWorldToolOperationResult( final ItemStack block, final List drops ) - { - this.BlockItem = block; - this.Drops = drops; - } + for (final ItemStack l : items) { + if (b == null) { + final Block bl = Block.getBlockFromItem(l.getItem()); - public InWorldToolOperationResult( final ItemStack block ) - { - this.BlockItem = block; - this.Drops = null; - } + if (bl != null && !(bl instanceof BlockAir)) { + b = l; + continue; + } + } - public static InWorldToolOperationResult getBlockOperationResult( final ItemStack[] items ) - { - final List temp = new ArrayList(); - ItemStack b = null; + temp.add(l); + } - for( final ItemStack l : items ) - { - if( b == null ) - { - final Block bl = Block.getBlockFromItem( l.getItem() ); + return new InWorldToolOperationResult(b, temp); + } - if( bl != null && !( bl instanceof BlockAir ) ) - { - b = l; - continue; - } - } + public ItemStack getBlockItem() { + return this.BlockItem; + } - temp.add( l ); - } - - return new InWorldToolOperationResult( b, temp ); - } - - public ItemStack getBlockItem() - { - return this.BlockItem; - } - - public List getDrops() - { - return this.Drops; - } + public List getDrops() { + return this.Drops; + } } diff --git a/src/main/java/appeng/util/InventoryAdaptor.java b/src/main/java/appeng/util/InventoryAdaptor.java index 913275c5..1ee22e9c 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 appeng.api.config.FuzzyMode; import appeng.integration.IntegrationRegistry; @@ -31,75 +32,73 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityChest; import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; +public abstract class InventoryAdaptor implements Iterable { + // returns an appropriate adaptor, or null + public static InventoryAdaptor getAdaptor(final Object te, final ForgeDirection d) { + if (te == null) { + return null; + } + final IBetterStorage bs = (IBetterStorage + ) (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BetterStorage) + ? IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BetterStorage) + : null); -public abstract class InventoryAdaptor implements Iterable -{ + if (te instanceof EntityPlayer) { + return new AdaptorIInventory( + new AdaptorPlayerInventory(((EntityPlayer) te).inventory, false) + ); + } else if (te instanceof ArrayList) { + @SuppressWarnings("unchecked") + final ArrayList list = (ArrayList) te; - // returns an appropriate adaptor, or null - public static InventoryAdaptor getAdaptor( final Object te, final ForgeDirection d ) - { - if( te == null ) - { - return null; - } + return new AdaptorList(list); + } else if (bs != null && bs.isStorageCrate(te)) { + return bs.getAdaptor(te, d); + } else if (te instanceof TileEntityChest) { + return new AdaptorIInventory(Platform.GetChestInv(te)); + } else if (te instanceof ISidedInventory) { + final ISidedInventory si = (ISidedInventory) te; + final int[] slots = si.getAccessibleSlotsFromSide(d.ordinal()); + if (si.getSizeInventory() > 0 && slots != null && slots.length > 0) { + return new AdaptorIInventory(new WrapperMCISidedInventory(si, d)); + } + } else if (te instanceof IInventory) { + final IInventory i = (IInventory) te; + if (i.getSizeInventory() > 0) { + return new AdaptorIInventory(i); + } + } - final IBetterStorage bs = (IBetterStorage) ( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BetterStorage ) ? IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BetterStorage ) : null ); + return null; + } - if( te instanceof EntityPlayer ) - { - return new AdaptorIInventory( new AdaptorPlayerInventory( ( (EntityPlayer) te ).inventory, false ) ); - } - else if( te instanceof ArrayList ) - { - @SuppressWarnings( "unchecked" ) final ArrayList list = (ArrayList) te; + // return what was extracted. + public abstract ItemStack + removeItems(int amount, ItemStack filter, IInventoryDestination destination); - return new AdaptorList( list ); - } - else if( bs != null && bs.isStorageCrate( te ) ) - { - return bs.getAdaptor( te, d ); - } - else if( te instanceof TileEntityChest ) - { - return new AdaptorIInventory( Platform.GetChestInv( te ) ); - } - else if( te instanceof ISidedInventory ) - { - final ISidedInventory si = (ISidedInventory) te; - final int[] slots = si.getAccessibleSlotsFromSide( d.ordinal() ); - if( si.getSizeInventory() > 0 && slots != null && slots.length > 0 ) - { - return new AdaptorIInventory( new WrapperMCISidedInventory( si, d ) ); - } - } - else if( te instanceof IInventory ) - { - final IInventory i = (IInventory) te; - if( i.getSizeInventory() > 0 ) - { - return new AdaptorIInventory( i ); - } - } + public abstract ItemStack + simulateRemove(int amount, ItemStack filter, IInventoryDestination destination); - return null; - } + // return what was extracted. + public abstract ItemStack removeSimilarItems( + int amount, + ItemStack filter, + FuzzyMode fuzzyMode, + IInventoryDestination destination + ); - // return what was extracted. - public abstract ItemStack removeItems( int amount, ItemStack filter, IInventoryDestination destination ); + public abstract ItemStack simulateSimilarRemove( + int amount, + ItemStack filter, + FuzzyMode fuzzyMode, + IInventoryDestination destination + ); - public abstract ItemStack simulateRemove( int amount, ItemStack filter, IInventoryDestination destination ); + // return what isn't used... + public abstract ItemStack addItems(ItemStack toBeAdded); - // return what was extracted. - public abstract ItemStack removeSimilarItems( int amount, ItemStack filter, FuzzyMode fuzzyMode, IInventoryDestination destination ); + public abstract ItemStack simulateAdd(ItemStack toBeSimulated); - 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(); + public abstract boolean containsItems(); } diff --git a/src/main/java/appeng/util/ItemSorters.java b/src/main/java/appeng/util/ItemSorters.java index 9da43efd..9d2a119b 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; import appeng.api.storage.data.IAEItemStack; @@ -26,151 +27,130 @@ import appeng.integration.IntegrationType; import appeng.integration.abstraction.IInvTweaks; import appeng.util.item.AEItemStack; -import java.util.Comparator; +public class ItemSorters { + private static SortDir Direction = SortDir.ASCENDING; + public static final Comparator CONFIG_BASED_SORT_BY_NAME + = new Comparator() { + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + if (getDirection() == 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() { + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + final AEItemStack op1 = (AEItemStack) o1; + final AEItemStack op2 = (AEItemStack) o2; -public class ItemSorters -{ + if (getDirection() == SortDir.ASCENDING) { + return this.secondarySort( + op2.getModID().compareToIgnoreCase(op1.getModID()), o1, o2 + ); + } + return this.secondarySort( + op1.getModID().compareToIgnoreCase(op2.getModID()), o2, o1 + ); + } - private static SortDir Direction = SortDir.ASCENDING; + private int secondarySort( + final int compareToIgnoreCase, + final IAEItemStack o1, + final IAEItemStack o2 + ) { + if (compareToIgnoreCase == 0) { + return Platform.getItemDisplayName(o2).compareToIgnoreCase( + Platform.getItemDisplayName(o1) + ); + } - public static final Comparator CONFIG_BASED_SORT_BY_NAME = new Comparator() - { + return compareToIgnoreCase; + } + }; + public static final Comparator CONFIG_BASED_SORT_BY_SIZE + = new Comparator() { + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + if (getDirection() == SortDir.ASCENDING) { + return compareLong(o2.getStackSize(), o1.getStackSize()); + } + return compareLong(o1.getStackSize(), o2.getStackSize()); + } + }; + private static IInvTweaks api; + public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS + = new Comparator() { + @Override + public int compare(final IAEItemStack o1, final IAEItemStack o2) { + if (api == null) { + return CONFIG_BASED_SORT_BY_NAME.compare(o1, o2); + } - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - if( getDirection() == 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() - { + final int cmp = api.compareItems(o1.getItemStack(), o2.getItemStack()); - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - final AEItemStack op1 = (AEItemStack) o1; - final AEItemStack op2 = (AEItemStack) o2; + if (getDirection() == SortDir.ASCENDING) { + return cmp; + } + return -cmp; + } + }; - if( getDirection() == SortDir.ASCENDING ) - { - return this.secondarySort( op2.getModID().compareToIgnoreCase( op1.getModID() ), o1, o2 ); - } - return this.secondarySort( op1.getModID().compareToIgnoreCase( op2.getModID() ), o2, o1 ); - } + public static void init() { + if (api != null) { + return; + } - private int secondarySort( final int compareToIgnoreCase, final IAEItemStack o1, final IAEItemStack o2 ) - { - if( compareToIgnoreCase == 0 ) - { - return Platform.getItemDisplayName( o2 ).compareToIgnoreCase( Platform.getItemDisplayName( o1 ) ); - } + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.InvTweaks)) { + api = (IInvTweaks + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.InvTweaks); + } else { + api = null; + } + } - return compareToIgnoreCase; - } - }; - public static final Comparator CONFIG_BASED_SORT_BY_SIZE = new Comparator() - { + public static int compareInt(final int a, final int b) { + if (a == b) { + return 0; + } + if (a < b) { + return -1; + } + return 1; + } - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - if( getDirection() == SortDir.ASCENDING ) - { - return compareLong( o2.getStackSize(), o1.getStackSize() ); - } - return compareLong( o1.getStackSize(), o2.getStackSize() ); - } - }; - private static IInvTweaks api; - public static final Comparator CONFIG_BASED_SORT_BY_INV_TWEAKS = new Comparator() - { + public static int compareLong(final long a, final long b) { + if (a == b) { + return 0; + } + if (a < b) { + return -1; + } + return 1; + } - @Override - public int compare( final IAEItemStack o1, final IAEItemStack o2 ) - { - if( api == null ) - { - return CONFIG_BASED_SORT_BY_NAME.compare( o1, o2 ); - } + public static int compareDouble(final double a, final double b) { + if (a == b) { + return 0; + } + if (a < b) { + return -1; + } + return 1; + } - final int cmp = api.compareItems( o1.getItemStack(), o2.getItemStack() ); + private static SortDir getDirection() { + return Direction; + } - if( getDirection() == SortDir.ASCENDING ) - { - return cmp; - } - return -cmp; - } - }; - - public static void init() - { - if( api != null ) - { - return; - } - - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.InvTweaks ) ) - { - api = (IInvTweaks) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.InvTweaks ); - } - else - { - api = null; - } - } - - public static int compareInt( final int a, final int b ) - { - if( a == b ) - { - return 0; - } - if( a < b ) - { - return -1; - } - return 1; - } - - public static int compareLong( final long a, final long b ) - { - if( a == b ) - { - return 0; - } - if( a < b ) - { - return -1; - } - return 1; - } - - public static int compareDouble( final double a, final double b ) - { - if( a == b ) - { - return 0; - } - if( a < b ) - { - return -1; - } - return 1; - } - - private static SortDir getDirection() - { - return Direction; - } - - public static void setDirection( final SortDir direction ) - { - Direction = direction; - } + public static void setDirection(final SortDir direction) { + Direction = direction; + } } diff --git a/src/main/java/appeng/util/LookDirection.java b/src/main/java/appeng/util/LookDirection.java index a05cce61..ff61752f 100644 --- a/src/main/java/appeng/util/LookDirection.java +++ b/src/main/java/appeng/util/LookDirection.java @@ -18,29 +18,22 @@ package appeng.util; - import net.minecraft.util.Vec3; +public class LookDirection { + private final Vec3 a; + private final Vec3 b; -public class LookDirection -{ + public LookDirection(final Vec3 a, final Vec3 b) { + this.a = a; + this.b = b; + } - private final Vec3 a; - private final Vec3 b; + public Vec3 getA() { + return this.a; + } - public LookDirection( final Vec3 a, final Vec3 b ) - { - this.a = a; - this.b = b; - } - - public Vec3 getA() - { - return this.a; - } - - public Vec3 getB() - { - return this.b; - } + public Vec3 getB() { + return this.b; + } } diff --git a/src/main/java/appeng/util/Platform.java b/src/main/java/appeng/util/Platform.java index c844c36e..bf5afe85 100644 --- a/src/main/java/appeng/util/Platform.java +++ b/src/main/java/appeng/util/Platform.java @@ -18,6 +18,13 @@ package appeng.util; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.security.InvalidParameterException; +import java.text.DecimalFormat; +import java.util.*; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import appeng.api.AEApi; import appeng.api.config.*; @@ -100,1927 +107,1795 @@ import net.minecraftforge.common.util.FakePlayerFactory; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.security.InvalidParameterException; -import java.text.DecimalFormat; -import java.util.*; - - /** * @author AlgorithmX2 * @author thatsIch * @version rv2 * @since rv0 */ -public class Platform -{ - - public static final Block AIR_BLOCK = Blocks.air; - - public static final int DEF_OFFSET = 16; - - /* - * random source, use it for item drop locations... - */ - private static 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; - private static GameProfile fakeProfile = new GameProfile( UUID.fromString( "839eb18c-50bc-400c-8291-9383f09763e7" ), "[AE2Player]" ); - - public static Random getRandom() - { - return RANDOM_GENERATOR; - } - - public static float getRandomFloat() - { - return RANDOM_GENERATOR.nextFloat(); - } - - /** - * This displays the value for encoded longs ( double *100 ) - * - * @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( final long n, final boolean isRate ) - { - double p = ( (double) n ) / 100; - - final PowerUnits displayUnits = AEConfig.instance.selectedPowerUnit(); - p = PowerUnits.AE.convertTo( displayUnits, p ); - - String unitName = displayUnits.name(); - - if( displayUnits == PowerUnits.WA ) - { - unitName = "J"; - } - - if( displayUnits == PowerUnits.MK ) - { - unitName = "J"; - } - - final String[] preFixes = { - "k", - "M", - "G", - "T", - "P", - "T", - "P", - "E", - "Z", - "Y" - }; - String level = ""; - int offset = 0; - while( p > 1000 && offset < preFixes.length ) - { - p /= 1000; - level = preFixes[offset]; - offset++; - } - - final DecimalFormat df = new DecimalFormat( "#.##" ); - return df.format( p ) + ' ' + level + unitName + ( isRate ? "/t" : "" ); - } - - public static ForgeDirection crossProduct( final ForgeDirection forward, final ForgeDirection up ) - { - final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; - final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; - final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; - - switch( west_x + west_y * 2 + west_z * 3 ) - { - case 1: - return ForgeDirection.EAST; - case -1: - return ForgeDirection.WEST; - - case 2: - return ForgeDirection.UP; - case -2: - return ForgeDirection.DOWN; - - case 3: - return ForgeDirection.SOUTH; - case -3: - return ForgeDirection.NORTH; - } - - return ForgeDirection.UNKNOWN; - } - - public static T rotateEnum( T ce, final boolean backwards, final 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... - */ - private static T prevEnum( final T ce ) - { - final EnumSet valList = EnumSet.allOf( ce.getClass() ); - - int pLoc = ce.ordinal() - 1; - if( pLoc < 0 ) - { - pLoc = valList.size() - 1; - } - - if( pLoc < 0 || pLoc >= valList.size() ) - { - pLoc = 0; - } - - int pos = 0; - for( final Object g : valList ) - { - if( pos == pLoc ) - { - return (T) g; - } - pos++; - } - - return null; - } - - /* - * Simple way to cycle an enum... - */ - public static T nextEnum( final T ce ) - { - final EnumSet valList = EnumSet.allOf( ce.getClass() ); - - int pLoc = ce.ordinal() + 1; - if( pLoc >= valList.size() ) - { - pLoc = 0; - } - - if( pLoc < 0 || pLoc >= valList.size() ) - { - pLoc = 0; - } - - int pos = 0; - for( final Object g : valList ) - { - if( pos == pLoc ) - { - return (T) g; - } - pos++; - } - - return null; - } - - private static boolean isNotValidSetting( final Enum e ) - { - if( e == SortOrder.INVTWEAKS && !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.InvTweaks ) ) - { - return true; - } - - if( e == SearchBoxMode.NEI_AUTOSEARCH && !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ) ) - { - return true; - } - - return e == SearchBoxMode.NEI_MANUAL_SEARCH && !IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.NEI ); - - } - - public static void openGUI( @Nonnull final EntityPlayer p, @Nullable final TileEntity tile, @Nullable final ForgeDirection side, @Nonnull final 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, p.getEntityWorld(), p.inventory.currentItem, 0, 0 ); - } - else 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 ); - } - } - } - - /* - * returns true if the code is on the client. - */ - public static boolean isClient() - { - return FMLCommonHandler.instance().getEffectiveSide().isClient(); - } - - public static boolean hasPermissions( final DimensionalCoord dc, final EntityPlayer player ) - { - return dc.getWorld().canMineBlock( player, dc.x, dc.y, dc.z ); - } - - /* - * Checks to see if a block is air? - */ - public static boolean isBlockAir( final World w, final int x, final int y, final int z ) - { - try - { - return w.getBlock( x, y, z ).isAir( w, x, y, z ); - } - catch( final Throwable e ) - { - return false; - } - } - - /* - * 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. - */ - private static boolean sameStackStags( final ItemStack a, final ItemStack b ) - { - if( a == null && b == null ) - { - return true; - } - if( a == null || b == null ) - { - return false; - } - if( a == b ) - { - return true; - } - - final NBTTagCompound ta = a.getTagCompound(); - final NBTTagCompound tb = b.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 both tags are shared this is easy... - if( AESharedNBT.isShared( ta ) && AESharedNBT.isShared( tb ) ) - { - return ta == tb; - } - - return NBTEqualityTest( ta, tb ); - } - - /* - * recursive test for NBT Equality, this was faster then trying to compare / generate hashes, its also more reliable - * 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( final NBTBase left, final NBTBase right ) - { - // same type? - final byte id = left.getId(); - if( id == right.getId() ) - { - switch( id ) - { - case 10: - { - final NBTTagCompound ctA = (NBTTagCompound) left; - final NBTTagCompound ctB = (NBTTagCompound) right; - - final Set cA = ctA.func_150296_c(); - final Set cB = ctB.func_150296_c(); - - if( cA.size() != cB.size() ) - { - return false; - } - - for( final String name : cA ) - { - final NBTBase tag = ctA.getTag( name ); - final NBTBase aTag = ctB.getTag( name ); - if( aTag == null ) - { - return false; - } - - if( !NBTEqualityTest( tag, aTag ) ) - { - return false; - } - } - - return true; - } - - case 9: // ) // A instanceof NBTTagList ) - { - final NBTTagList lA = (NBTTagList) left; - final NBTTagList lB = (NBTTagList) right; - if( lA.tagCount() != lB.tagCount() ) - { - return false; - } - - final List tag = tagList( lA ); - final 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; - } - - case 1: // ( A instanceof NBTTagByte ) - return ( (NBTBase.NBTPrimitive) left ).func_150287_d() == ( (NBTBase.NBTPrimitive) right ).func_150287_d(); - - case 4: // else if ( A instanceof NBTTagLong ) - return ( (NBTBase.NBTPrimitive) left ).func_150291_c() == ( (NBTBase.NBTPrimitive) right ).func_150291_c(); - - case 8: // else if ( A instanceof NBTTagString ) - return ( (NBTTagString) left ).func_150285_a_().equals( ( (NBTTagString) right ).func_150285_a_() ) || ( (NBTTagString) left ).func_150285_a_().equals( ( (NBTTagString) right ).func_150285_a_() ); - - case 6: // else if ( A instanceof NBTTagDouble ) - return ( (NBTBase.NBTPrimitive) left ).func_150286_g() == ( (NBTBase.NBTPrimitive) right ).func_150286_g(); - - case 5: // else if ( A instanceof NBTTagFloat ) - return ( (NBTBase.NBTPrimitive) left ).func_150288_h() == ( (NBTBase.NBTPrimitive) right ).func_150288_h(); - - case 3: // else if ( A instanceof NBTTagInt ) - return ( (NBTBase.NBTPrimitive) left ).func_150287_d() == ( (NBTBase.NBTPrimitive) right ).func_150287_d(); - - default: - return left.equals( right ); - } - } - - return false; - } - - private static List tagList( final NBTTagList lB ) - { - if( tagList == null ) - { - try - { - tagList = lB.getClass().getDeclaredField( "tagList" ); - } - catch( final Throwable t ) - { - try - { - tagList = lB.getClass().getDeclaredField( "field_74747_a" ); - } - catch( final Throwable z ) - { - AELog.debug( t ); - AELog.debug( z ); - } - } - } - - try - { - tagList.setAccessible( true ); - return (List) tagList.get( lB ); - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - - return new ArrayList(); - } - - /* - * 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( final NBTBase nbt ) - { - // same type? - int hash = 0; - final byte id = nbt.getId(); - hash += id; - switch( id ) - { - case 10: - { - final NBTTagCompound ctA = (NBTTagCompound) nbt; - - final Set cA = ctA.func_150296_c(); - - for( final String name : cA ) - { - hash += name.hashCode() ^ NBTOrderlessHash( ctA.getTag( name ) ); - } - - return hash; - } - - case 9: // ) // A instanceof NBTTagList ) - { - final NBTTagList lA = (NBTTagList) nbt; - hash += 9 * lA.tagCount(); - - final List l = tagList( lA ); - for( int x = 0; x < l.size(); x++ ) - { - hash += ( (Integer) x ).hashCode() ^ NBTOrderlessHash( l.get( x ) ); - } - - return hash; - } - - case 1: // ( A instanceof NBTTagByte ) - return hash + ( (NBTBase.NBTPrimitive) nbt ).func_150290_f(); - - case 4: // else if ( A instanceof NBTTagLong ) - return hash + (int) ( (NBTBase.NBTPrimitive) nbt ).func_150291_c(); - - case 8: // else if ( A instanceof NBTTagString ) - return hash + ( (NBTTagString) nbt ).func_150285_a_().hashCode(); - - case 6: // else if ( A instanceof NBTTagDouble ) - return hash + (int) ( (NBTBase.NBTPrimitive) nbt ).func_150286_g(); - - case 5: // else if ( A instanceof NBTTagFloat ) - return hash + (int) ( (NBTBase.NBTPrimitive) nbt ).func_150288_h(); - - case 3: // else if ( A instanceof NBTTagInt ) - return hash + ( (NBTBase.NBTPrimitive) nbt ).func_150287_d(); - - default: - return hash; - } - } - - /* - * The usual version of this returns an ItemStack, this version returns the recipe. - */ - public static IRecipe findMatchingRecipe( final InventoryCrafting inventoryCrafting, final World par2World ) - { - final CraftingManager cm = CraftingManager.getInstance(); - final List rl = cm.getRecipeList(); - - for( final IRecipe r : rl ) - { - if( r.matches( inventoryCrafting, par2World ) ) - { - return r; - } - } - - return null; - } - - public static ItemStack[] getBlockDrops( final World w, final int x, final int y, final int z ) - { - List out = new ArrayList(); - final Block which = w.getBlock( x, y, z ); - - if( which != null ) - { - out = which.getDrops( w, x, y, z, w.getBlockMetadata( x, y, z ), 0 ); - } - - if( out == null ) - { - return new ItemStack[0]; - } - return out.toArray( new ItemStack[out.size()] ); - } - - public static ForgeDirection cycleOrientations( final ForgeDirection dir, final boolean upAndDown ) - { - if( upAndDown ) - { - 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; - } - } - else - { - 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; - } - } - - return ForgeDirection.UNKNOWN; - } - - /* - * Creates / or loads previous NBT Data on items, used for editing items owned by AE. - */ - public static NBTTagCompound openNbtData( final ItemStack i ) - { - NBTTagCompound compound = i.getTagCompound(); - - if( compound == null ) - { - i.setTagCompound( compound = new NBTTagCompound() ); - } - - return compound; - } - - /* - * Generates Item entities in the world similar to how items are generally dropped. - */ - public static void spawnDrops( final World w, final int x, final int y, final int z, final List drops ) - { - if( isServer() ) - { - for( final ItemStack i : drops ) - { - if( i != null ) - { - if( i.stackSize > 0 ) - { - final double offset_x = ( getRandomInt() % 32 - 16 ) / 82; - final double offset_y = ( getRandomInt() % 32 - 16 ) / 82; - final double offset_z = ( getRandomInt() % 32 - 16 ) / 82; - final 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 ); - } - } - } - } - } - - /* - * 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( final Object te ) - { - TileEntityChest teA = (TileEntityChest) te; - TileEntity teB = null; - final Block myBlockID = teA.getWorldObj().getBlock( teA.xCoord, teA.yCoord, teA.zCoord ); - - 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 ) ) - { - teB = null; - } - } - - if( teB == null ) - { - 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 ) ) - { - teB = null; - } - else - { - final TileEntityChest x = teA; - teA = (TileEntityChest) teB; - teB = x; - } - } - } - - if( teB == null ) - { - 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 ) ) - { - teB = null; - } - } - } - - if( teB == null ) - { - 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 ) ) - { - teB = null; - } - else - { - final TileEntityChest x = teA; - teA = (TileEntityChest) teB; - teB = x; - } - } - } - - if( teB == null ) - { - return teA; - } - - return new InventoryLargeChest( "", teA, (IInventory) teB ); - } - - public static boolean isModLoaded( final String modid ) - { - try - { - // if this fails for some reason, try the other method. - return Loader.isModLoaded( modid ); - } - catch( final Throwable ignored ) - { - } - - for( final ModContainer f : Loader.instance().getActiveModList() ) - { - if( f.getModId().equals( modid ) ) - { - return true; - } - } - return false; - } - - public static ItemStack findMatchingRecipeOutput( final InventoryCrafting ic, final World worldObj ) - { - return CraftingManager.getInstance().findMatchingRecipe( ic, worldObj ); - } - - @SideOnly( Side.CLIENT ) - public static List getTooltip( final Object o ) - { - if( o == null ) - { - return new ArrayList(); - } - - ItemStack itemStack = null; - if( o instanceof AEItemStack ) - { - final AEItemStack ais = (AEItemStack) o; - return ais.getToolTip(); - } - else if( o instanceof ItemStack ) - { - itemStack = (ItemStack) o; - } - else - { - return new ArrayList(); - } - - try - { - return itemStack.getTooltip( Minecraft.getMinecraft().thePlayer, false ); - } - catch( final Exception errB ) - { - return new ArrayList(); - } - } - - public static String getModId( final IAEItemStack is ) - { - if( is == null ) - { - return "** Null"; - } - - final String n = ( (AEItemStack) is ).getModID(); - return n == null ? "** Null" : n; - } - - public static String getItemDisplayName( final Object o ) - { - if( o == null ) - { - return "** Null"; - } - - ItemStack itemStack = null; - if( o instanceof AEItemStack ) - { - final String n = ( (AEItemStack) o ).getDisplayName(); - return n == null ? "** Null" : n; - } - else if( o instanceof ItemStack ) - { - itemStack = (ItemStack) o; - } - else - { - return "**Invalid Object"; - } - - try - { - String name = itemStack.getDisplayName(); - if( name == null || name.isEmpty() ) - { - name = itemStack.getItem().getUnlocalizedName( itemStack ); - } - return name == null ? "** Null" : name; - } - catch( final Exception errA ) - { - try - { - final String n = itemStack.getUnlocalizedName(); - return n == null ? "** Null" : n; - } - catch( final Exception errB ) - { - return "** Exception"; - } - } - } - - public static boolean hasSpecialComparison( final IAEItemStack willAdd ) - { - if( willAdd == null ) - { - return false; - } - final IAETagCompound tag = willAdd.getTagCompound(); - return tag != null && tag.getSpecialComparison() != null; - } - - public static boolean hasSpecialComparison( final ItemStack willAdd ) - { - if( AESharedNBT.isShared( willAdd.getTagCompound() ) ) - { - if( ( (IAETagCompound) willAdd.getTagCompound() ).getSpecialComparison() != null ) - { - return true; - } - } - return false; - } - - public static boolean isWrench( final EntityPlayer player, final ItemStack eq, final int x, final int y, final int z ) - { - if( eq != null ) - { - try - { - if( eq.getItem() instanceof IToolWrench ) - { - final IToolWrench wrench = (IToolWrench) eq.getItem(); - return wrench.canWrench( player, x, y, z ); - } - } - catch( final Throwable ignore ) - { // explodes without BC - - } - - if( eq.getItem() instanceof IAEWrench ) - { - final IAEWrench wrench = (IAEWrench) eq.getItem(); - return wrench.canWrench( eq, player, x, y, z ); - } - } - return false; - } - - public static boolean isChargeable( final ItemStack i ) - { - if( i == null ) - { - return false; - } - final Item it = i.getItem(); - if( it instanceof IAEItemPowerStorage ) - { - return ( (IAEItemPowerStorage) it ).getPowerFlow( i ) != AccessRestriction.READ; - } - return false; - } - - public static EntityPlayer getPlayer( final WorldServer w ) - { - if( w == null ) - { - throw new InvalidParameterException( "World is null." ); - } - - final EntityPlayer wrp = FAKE_PLAYERS.get( w ); - if( wrp != null ) - { - return wrp; - } - - final EntityPlayer p = FakePlayerFactory.get( w, fakeProfile ); - FAKE_PLAYERS.put( w, p ); - return p; - } - - public static int MC2MEColor( final int 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" - } - return -1; - } - - public static int findEmpty( final Object[] l ) - { - for( int x = 0; x < l.length; x++ ) - { - if( l[x] == null ) - { - return x; - } - } - return -1; - } - - public static T pickRandom( final Collection outs ) - { - int index = RANDOM_GENERATOR.nextInt( outs.size() ); - final Iterator i = outs.iterator(); - while( i.hasNext() && index > 0 ) - { - index--; - i.next(); - } - index--; - if( i.hasNext() ) - { - return i.next(); - } - return null; // wtf? - } - - public static ForgeDirection rotateAround( final ForgeDirection forward, final ForgeDirection axis ) - { - if( axis == ForgeDirection.UNKNOWN || forward == ForgeDirection.UNKNOWN ) - { - return forward; - } - - switch( forward ) - { - case DOWN: - 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: - 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( final String string ) - { - return StatCollector.translateToLocal( string ); - } - - public static boolean isSameItemPrecise( @Nullable final ItemStack is, @Nullable final ItemStack filter ) - { - return isSameItem( is, filter ) && sameStackStags( is, filter ); - } - - public static boolean isSameItemFuzzy( final ItemStack a, final ItemStack b, final FuzzyMode mode ) - { - if( a == null && b == null ) - { - return true; - } - - if( a == null ) - { - return false; - } - - if( b == null ) - { - return false; - } - - /* - * if ( a.itemID != 0 && b.itemID != 0 && a.isItemStackDamageable() && ! a.getHasSubtypes() && a.itemID == - * b.itemID ) { return (a.getItemDamage() > 0) == (b.getItemDamage() > 0); } - */ - - // test damageable items.. - if( a.getItem() != null && b.getItem() != null && a.getItem().isDamageable() && a.getItem() == b.getItem() ) - { - try - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamageForDisplay() > 1 ) == ( b.getItemDamageForDisplay() > 1 ); - } - else - { - final float percentDamagedOfA = 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); - final float percentDamagedOfB = 1.0f - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); - - return ( percentDamagedOfA > mode.breakPoint ) == ( percentDamagedOfB > mode.breakPoint ); - } - } - catch( final Throwable e ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 ); - } - else - { - final float percentDamagedOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); - final float percentDamagedOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); - - return ( percentDamagedOfA > mode.breakPoint ) == ( percentDamagedOfB > mode.breakPoint ); - } - } - } - - final OreReference aOR = OreHelper.INSTANCE.isOre( a ); - final OreReference bOR = OreHelper.INSTANCE.isOre( b ); - - if( OreHelper.INSTANCE.sameOre( aOR, bOR ) ) - { - return true; - } - - /* - * // test ore dictionary.. int OreID = getOreID( a ); if ( OreID != -1 ) return OreID == getOreID( b ); - * if ( Mode != FuzzyMode.IGNORE_ALL ) { if ( a.hasTagCompound() && !isShared( a.getTagCompound() ) ) { a = - * Platform.getSharedItemStack( AEItemStack.create( a ) ); } - * if ( b.hasTagCompound() && !isShared( b.getTagCompound() ) ) { b = Platform.getSharedItemStack( - * AEItemStack.create( b ) ); } - * // test regular items with damage values and what not... if ( isShared( a.getTagCompound() ) && isShared( - * b.getTagCompound() ) && a.itemID == b.itemID ) { return ((AppEngSharedNBTTagCompound) - * a.getTagCompound()).compareFuzzyWithRegistry( (AppEngSharedNBTTagCompound) b.getTagCompound() ); } } - */ - - return a.isItemEqual( b ); - } - - public static LookDirection getPlayerRay( final EntityPlayer player, final float eyeOffset ) - { - final float f = 1.0F; - final float f1 = player.prevRotationPitch + ( player.rotationPitch - player.prevRotationPitch ) * f; - final float f2 = player.prevRotationYaw + ( player.rotationYaw - player.prevRotationYaw ) * f; - final double d0 = player.prevPosX + ( player.posX - player.prevPosX ) * f; - final double d1 = eyeOffset; - final double d2 = player.prevPosZ + ( player.posZ - player.prevPosZ ) * f; - - final Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); - final float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); - final float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); - final float f5 = -MathHelper.cos( -f1 * 0.017453292F ); - final float f6 = MathHelper.sin( -f1 * 0.017453292F ); - final float f7 = f4 * f5; - final float f8 = f3 * f5; - double d3 = 5.0D; - - if( player instanceof EntityPlayerMP ) - { - d3 = ( (EntityPlayerMP) player ).theItemInWorldManager.getBlockReachDistance(); - } - final Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - return new LookDirection( vec3, vec31 ); - } - - public static MovingObjectPosition rayTrace( final EntityPlayer p, final boolean hitBlocks, final boolean hitEntities ) - { - final World w = p.getEntityWorld(); - - final float f = 1.0F; - float f1 = p.prevRotationPitch + ( p.rotationPitch - p.prevRotationPitch ) * f; - final float f2 = p.prevRotationYaw + ( p.rotationYaw - p.prevRotationYaw ) * f; - final double d0 = p.prevPosX + ( p.posX - p.prevPosX ) * f; - final double d1 = p.prevPosY + ( p.posY - p.prevPosY ) * f + 1.62D - p.yOffset; - final double d2 = p.prevPosZ + ( p.posZ - p.prevPosZ ) * f; - final Vec3 vec3 = Vec3.createVectorHelper( d0, d1, d2 ); - final float f3 = MathHelper.cos( -f2 * 0.017453292F - (float) Math.PI ); - final float f4 = MathHelper.sin( -f2 * 0.017453292F - (float) Math.PI ); - final float f5 = -MathHelper.cos( -f1 * 0.017453292F ); - final float f6 = MathHelper.sin( -f1 * 0.017453292F ); - final float f7 = f4 * f5; - final float f8 = f3 * f5; - final double d3 = 32.0D; - - final Vec3 vec31 = vec3.addVector( f7 * d3, f6 * d3, f8 * d3 ); - - final 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 ) - { - final List list = w.getEntitiesWithinAABBExcludingEntity( p, bb ); - - for( int l = 0; l < list.size(); ++l ) - { - final Entity entity1 = (Entity) list.get( l ); - - if( !entity1.isDead && entity1 != p && !( entity1 instanceof EntityItem ) ) - { - if( entity1.isEntityAlive() ) - { - // prevent killing / flying of mounts. - if( entity1.riddenByEntity == p ) - { - continue; - } - - f1 = 0.3F; - final AxisAlignedBB boundingBox = entity1.boundingBox.expand( f1, f1, f1 ); - final MovingObjectPosition movingObjectPosition = boundingBox.calculateIntercept( vec3, vec31 ); - - if( movingObjectPosition != null ) - { - final double nd = vec3.squareDistanceTo( movingObjectPosition.hitVec ); - - if( nd < closest ) - { - entity = entity1; - closest = nd; - } - } - } - } - } - } - - MovingObjectPosition pos = null; - Vec3 vec = null; - - if( hitBlocks ) - { - vec = Vec3.createVectorHelper( d0, d1, d2 ); - pos = w.rayTraceBlocks( vec3, vec31, true ); - } - - if( entity != null && pos != null && pos.hitVec.squareDistanceTo( vec ) > closest ) - { - pos = new MovingObjectPosition( entity ); - } - else if( entity != null && pos == null ) - { - pos = new MovingObjectPosition( entity ); - } - - return pos; - } - - public static long nanoTime() - { - // if ( Configuration.INSTANCE.enableNetworkProfiler ) - // return System.nanoTime(); - return 0; - } - - public static StackType poweredExtraction( final IEnergySource energy, final IMEInventory cell, final StackType request, final BaseActionSource src ) - { - final StackType possible = cell.extractItems( (StackType) request.copy(), Actionable.SIMULATE, src ); - - long retrieved = 0; - if( possible != null ) - { - retrieved = possible.getStackSize(); - } - - final double availablePower = energy.extractAEPower( retrieved, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - final long itemToExtract = Math.min( (long) ( availablePower + 0.9 ), retrieved ); - - if( itemToExtract > 0 ) - { - energy.extractAEPower( retrieved, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - possible.setStackSize( itemToExtract ); - final StackType ret = cell.extractItems( possible, Actionable.MODULATE, src ); - - if( ret != null && src.isPlayer() ) - { - Stats.ItemsExtracted.addToPlayer( ( (PlayerSource) src ).player, (int) ret.getStackSize() ); - } - - return ret; - } - - return null; - } - - public static StackType poweredInsert( final IEnergySource energy, final IMEInventory cell, final StackType input, final BaseActionSource src ) - { - final StackType possible = cell.injectItems( (StackType) input.copy(), Actionable.SIMULATE, src ); - - long stored = input.getStackSize(); - if( possible != null ) - { - stored -= possible.getStackSize(); - } - - final double availablePower = energy.extractAEPower( stored, Actionable.SIMULATE, PowerMultiplier.CONFIG ); - - final long itemToAdd = Math.min( (long) ( availablePower + 0.9 ), stored ); - - if( itemToAdd > 0 ) - { - energy.extractAEPower( stored, Actionable.MODULATE, PowerMultiplier.CONFIG ); - - if( itemToAdd < input.getStackSize() ) - { - final long original = input.getStackSize(); - final StackType split = (StackType) input.copy(); - split.decStackSize( itemToAdd ); - input.setStackSize( itemToAdd ); - split.add( cell.injectItems( input, Actionable.MODULATE, src ) ); - - if( src.isPlayer() ) - { - final long diff = original - split.getStackSize(); - Stats.ItemsInserted.addToPlayer( ( (PlayerSource) src ).player, (int) diff ); - } - - return split; - } - - final StackType ret = cell.injectItems( input, Actionable.MODULATE, src ); - - if( src.isPlayer() ) - { - final long diff = ret == null ? input.getStackSize() : input.getStackSize() - ret.getStackSize(); - Stats.ItemsInserted.addToPlayer( ( (PlayerSource) src ).player, (int) diff ); - } - - return ret; - } - - return input; - } - - public static void postChanges( final IStorageGrid gs, final ItemStack removed, final ItemStack added, final BaseActionSource src ) - { - final IItemList itemChanges = AEApi.instance().storage().createItemList(); - final IItemList fluidChanges = AEApi.instance().storage().createFluidList(); - - if( removed != null ) - { - final IMEInventory myItems = AEApi.instance().registries().cell().getCellInventory( removed, null, StorageChannel.ITEMS ); - - if( myItems != null ) - { - for( final IAEItemStack is : myItems.getAvailableItems( itemChanges ) ) - { - is.setStackSize( -is.getStackSize() ); - } - } - - final IMEInventory myFluids = AEApi.instance().registries().cell().getCellInventory( removed, null, StorageChannel.FLUIDS ); - - if( myFluids != null ) - { - for( final IAEFluidStack is : myFluids.getAvailableItems( fluidChanges ) ) - { - is.setStackSize( -is.getStackSize() ); - } - } - } - - if( added != null ) - { - final IMEInventory myItems = AEApi.instance().registries().cell().getCellInventory( added, null, StorageChannel.ITEMS ); - - if( myItems != null ) - { - myItems.getAvailableItems( itemChanges ); - } - - final IMEInventory myFluids = AEApi.instance().registries().cell().getCellInventory( added, null, StorageChannel.FLUIDS ); - - if( myFluids != null ) - { - myFluids.getAvailableItems( fluidChanges ); - } - } - - gs.postAlterationOfStoredItems( StorageChannel.ITEMS, itemChanges, src ); - } - - public static > void postListChanges( final IItemList before, final IItemList after, final IMEMonitorHandlerReceiver meMonitorPassthrough, final BaseActionSource source ) - { - final LinkedList changes = new LinkedList(); - - for( final T is : before ) - { - is.setStackSize( -is.getStackSize() ); - } - - for( final T is : after ) - { - before.add( is ); - } - - for( final T is : before ) - { - if( is.getStackSize() != 0 ) - { - changes.add( is ); - } - } - - if( !changes.isEmpty() ) - { - meMonitorPassthrough.postChange( null, changes, source ); - } - } - - public static int generateTileHash( final TileEntity target ) - { - if( target == null ) - { - return 0; - } - - int hash = target.hashCode(); - - if( target instanceof ITileStorageMonitorable ) - { - return 0; - } - else if( target instanceof TileEntityChest ) - { - final TileEntityChest chest = (TileEntityChest) target; - chest.checkForAdjacentChests(); - if( chest.adjacentChestZNeg != null ) - { - hash ^= chest.adjacentChestZNeg.hashCode(); - } - else if( chest.adjacentChestZPos != null ) - { - hash ^= chest.adjacentChestZPos.hashCode(); - } - else if( chest.adjacentChestXPos != null ) - { - hash ^= chest.adjacentChestXPos.hashCode(); - } - else if( chest.adjacentChestXNeg != null ) - { - hash ^= chest.adjacentChestXNeg.hashCode(); - } - } - else if( target instanceof IInventory ) - { - hash ^= ( (IInventory) target ).getSizeInventory(); - - if( target instanceof ISidedInventory ) - { - for( final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS ) - { - - final int[] sides = ( (ISidedInventory) target ).getAccessibleSlotsFromSide( dir.ordinal() ); - - if( sides == null ) - { - return 0; - } - - int offset = 0; - for( final int side : sides ) - { - final int c = ( side << ( offset % 8 ) ) ^ ( 1 << dir.ordinal() ); - offset++; - hash = c + ( hash << 6 ) + ( hash << 16 ) - hash; - } - } - } - } - - return hash; - } - - public static boolean securityCheck( final GridNode a, final GridNode b ) - { - if( a.getLastSecurityKey() == -1 && b.getLastSecurityKey() == -1 ) - { - return false; - } - else if( a.getLastSecurityKey() == b.getLastSecurityKey() ) - { - return false; - } - - final boolean a_isSecure = isPowered( a.getGrid() ) && a.getLastSecurityKey() != -1; - final boolean b_isSecure = isPowered( b.getGrid() ) && b.getLastSecurityKey() != -1; - - if( AEConfig.instance.isFeatureEnabled( AEFeature.LogSecurityAudits ) ) - { - AELog.info( "Audit: " + a_isSecure + " : " + b_isSecure + " @ " + a.getLastSecurityKey() + " vs " + b.getLastSecurityKey() + " & " + a.getPlayerID() + " vs " + b.getPlayerID() ); - } - - // can't do that son... - if( a_isSecure && b_isSecure ) - { - return true; - } - - if( !a_isSecure && b_isSecure ) - { - return checkPlayerPermissions( b.getGrid(), a.getPlayerID() ); - } - - if( a_isSecure && !b_isSecure ) - { - return checkPlayerPermissions( a.getGrid(), b.getPlayerID() ); - } - - return false; - } - - private static boolean isPowered( final IGrid grid ) - { - if( grid == null ) - { - return false; - } - - final IEnergyGrid eg = grid.getCache( IEnergyGrid.class ); - return eg.isNetworkPowered(); - } - - private static boolean checkPlayerPermissions( final IGrid grid, final int playerID ) - { - if( grid == null ) - { - return false; - } - - final ISecurityGrid gs = grid.getCache( ISecurityGrid.class ); - - if( gs == null ) - { - return false; - } - - if( !gs.isAvailable() ) - { - return false; - } - - return !gs.hasPermission( playerID, SecurityPermissions.BUILD ); - } - - public static void configurePlayer( final EntityPlayer player, final ForgeDirection side, final TileEntity tile ) - { - player.yOffset = 1.8f; - - float yaw = 0.0f; - float pitch = 0.0f; - 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; - } - - player.posX = tile.xCoord + 0.5; - player.posY = tile.yCoord + 0.5; - player.posZ = tile.zCoord + 0.5; - - player.rotationPitch = player.prevCameraPitch = player.cameraPitch = pitch; - player.rotationYaw = player.prevCameraYaw = player.cameraYaw = yaw; - } - - public static boolean canAccess( final AENetworkProxy gridProxy, final BaseActionSource src ) - { - try - { - if( src.isPlayer() ) - { - return gridProxy.getSecurity().hasPermission( ( (PlayerSource) src ).player, SecurityPermissions.BUILD ); - } - else if( src.isMachine() ) - { - final IActionHost te = ( (MachineSource) src ).via; - final IGridNode n = te.getActionableNode(); - if( n == null ) - { - return false; - } - - final int playerID = n.getPlayerID(); - return gridProxy.getSecurity().hasPermission( playerID, SecurityPermissions.BUILD ); - } - else - { - return false; - } - } - catch( final GridAccessException gae ) - { - return false; - } - } - - public static ItemStack extractItemsByRecipe( final IEnergySource energySrc, final BaseActionSource mySrc, final IMEMonitor src, final World w, final IRecipe r, final ItemStack output, final InventoryCrafting ci, final ItemStack providedTemplate, final int slot, final IItemList items, final Actionable realForFake, final IPartitionList filter ) - { - if( energySrc.extractAEPower( 1, Actionable.SIMULATE, PowerMultiplier.CONFIG ) > 0.9 ) - { - if( providedTemplate == null ) - { - return null; - } - - final AEItemStack ae_req = AEItemStack.create( providedTemplate ); - ae_req.setStackSize( 1 ); - - if( filter == null || filter.isListed( ae_req ) ) - { - final IAEItemStack ae_ext = src.extractItems( ae_req, realForFake, mySrc ); - if( ae_ext != null ) - { - final ItemStack extracted = ae_ext.getItemStack(); - if( extracted != null ) - { - energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); - return extracted; - } - } - } - - final boolean checkFuzzy = ae_req.isOre() || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE || providedTemplate.hasTagCompound() || providedTemplate.isItemStackDamageable(); - - if( items != null && checkFuzzy ) - { - for( final IAEItemStack x : items ) - { - final ItemStack sh = x.getItemStack(); - if( ( Platform.isSameItemType( providedTemplate, sh ) || ae_req.sameOre( x ) ) && !Platform.isSameItem( sh, output ) ) - { // Platform.isSameItemType( sh, providedTemplate ) - final ItemStack cp = Platform.cloneItemStack( sh ); - cp.stackSize = 1; - ci.setInventorySlotContents( slot, cp ); - if( r.matches( ci, w ) && Platform.isSameItem( r.getCraftingResult( ci ), output ) ) - { - final IAEItemStack ax = x.copy(); - ax.setStackSize( 1 ); - if( filter == null || filter.isListed( ax ) ) - { - final IAEItemStack ex = src.extractItems( ax, realForFake, mySrc ); - if( ex != null ) - { - energySrc.extractAEPower( 1, realForFake, PowerMultiplier.CONFIG ); - return ex.getItemStack(); - } - } - } - ci.setInventorySlotContents( slot, providedTemplate ); - } - } - } - } - return null; - } - - public static boolean isSameItemType( final ItemStack that, final ItemStack other ) - { - if( that != null && other != null && that.getItem() == other.getItem() ) - { - if( that.isItemStackDamageable() ) - { - return true; - } - return that.getItemDamage() == other.getItemDamage(); - } - return false; - } - - public static boolean isSameItem( @Nullable final ItemStack left, @Nullable final ItemStack right ) - { - return left != null && right != null && left.isItemEqual( right ); - } - - public static ItemStack cloneItemStack( final ItemStack a ) - { - return a.copy(); - } - - public static ItemStack getContainerItem( final ItemStack stackInSlot ) - { - if( stackInSlot == null ) - { - return null; - } - - final Item i = stackInSlot.getItem(); - if( i == null || !i.hasContainerItem( stackInSlot ) ) - { - if( stackInSlot.stackSize > 1 ) - { - stackInSlot.stackSize--; - return stackInSlot; - } - return null; - } - - ItemStack ci = i.getContainerItem( stackInSlot.copy() ); - if( ci != null && ci.isItemStackDamageable() && ci.getItemDamage() == ci.getMaxDamage() ) - { - ci = null; - } - - return ci; - } - - public static void notifyBlocksOfNeighbors( final World worldObj, final int xCoord, final int yCoord, final int zCoord ) - { - if( !worldObj.isRemote ) - { - TickHandler.INSTANCE.addCallable( worldObj, new BlockUpdate( xCoord, yCoord, zCoord ) ); - } - } - - public static boolean canRepair( final AEFeature type, final ItemStack a, final ItemStack b ) - { - if( b == null || a == null ) - { - return false; - } - - if( type == AEFeature.CertusQuartzTools ) - { - final IItemDefinition certusQuartzCrystal = AEApi.instance().definitions().materials().certusQuartzCrystal(); - - return certusQuartzCrystal.isSameAs( b ); - } - - if( type == AEFeature.NetherQuartzTools ) - { - return Items.quartz == b.getItem(); - } - - return false; - } - - public static Object findPreferred( final ItemStack[] is ) - { - final IParts parts = AEApi.instance().definitions().parts(); - - for( final ItemStack stack : is ) - { - if( parts.cableGlass().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableCovered().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableSmart().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - - if( parts.cableDense().sameAs( AEColor.Transparent, stack ) ) - { - return stack; - } - } - - return is; - } - - public static void sendChunk( final Chunk c, final int verticalBits ) - { - try - { - final WorldServer ws = (WorldServer) c.worldObj; - final PlayerManager pm = ws.getPlayerManager(); - - if( getOrCreateChunkWatcher == null ) - { - getOrCreateChunkWatcher = ReflectionHelper.findMethod( PlayerManager.class, pm, new String[] { "getOrCreateChunkWatcher", "func_72690_a" }, int.class, int.class, boolean.class ); - } - - if( getOrCreateChunkWatcher != null ) - { - final Object playerInstance = getOrCreateChunkWatcher.invoke( pm, c.xPosition, c.zPosition, false ); - if( playerInstance != null ) - { - Platform.playerInstance = playerInstance.getClass(); - - if( sendToAllPlayersWatchingChunk == null ) - { - sendToAllPlayersWatchingChunk = ReflectionHelper.findMethod( Platform.playerInstance, playerInstance, new String[] { "sendToAllPlayersWatchingChunk", "func_151251_a" }, Packet.class ); - } - - if( sendToAllPlayersWatchingChunk != null ) - { - sendToAllPlayersWatchingChunk.invoke( playerInstance, new S21PacketChunkData( c, false, verticalBits ) ); - } - } - } - } - catch( final Throwable t ) - { - AELog.debug( t ); - } - } - - public static AxisAlignedBB getPrimaryBox( final ForgeDirection side, final int facadeThickness ) - { - 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; - } - return AxisAlignedBB.getBoundingBox( 0, 0, 0, 1, 1, 1 ); - } - - public static float getEyeOffset( final EntityPlayer player ) - { - assert player.worldObj.isRemote : "Valid only on client"; - return (float) ( player.posY + player.getEyeHeight() - player.getDefaultEyeHeight() ); - } - - public static void addStat( final int playerID, final Achievement achievement ) - { - final EntityPlayer p = AEApi.instance().registries().players().findPlayer( playerID ); - if( p != null ) - { - p.addStat( achievement, 1 ); - } - } - - public static boolean isRecipePrioritized( final ItemStack what ) - { - final IMaterials materials = AEApi.instance().definitions().materials(); - - boolean isPurified = materials.purifiedCertusQuartzCrystal().isSameAs( what ); - isPurified |= materials.purifiedFluixCrystal().isSameAs( what ); - isPurified |= materials.purifiedNetherQuartzCrystal().isSameAs( what ); - - return isPurified; - } +public class Platform { + public static final Block AIR_BLOCK = Blocks.air; + + public static final int DEF_OFFSET = 16; + + /* + * random source, use it for item drop locations... + */ + private static 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; + private static GameProfile fakeProfile = new GameProfile( + UUID.fromString("839eb18c-50bc-400c-8291-9383f09763e7"), "[AE2Player]" + ); + + public static Random getRandom() { + return RANDOM_GENERATOR; + } + + public static float getRandomFloat() { + return RANDOM_GENERATOR.nextFloat(); + } + + /** + * This displays the value for encoded longs ( double *100 ) + * + * @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(final long n, final boolean isRate) { + double p = ((double) n) / 100; + + final PowerUnits displayUnits = AEConfig.instance.selectedPowerUnit(); + p = PowerUnits.AE.convertTo(displayUnits, p); + + String unitName = displayUnits.name(); + + if (displayUnits == PowerUnits.WA) { + unitName = "J"; + } + + if (displayUnits == PowerUnits.MK) { + unitName = "J"; + } + + final String[] preFixes = { "k", "M", "G", "T", "P", "T", "P", "E", "Z", "Y" }; + String level = ""; + int offset = 0; + while (p > 1000 && offset < preFixes.length) { + p /= 1000; + level = preFixes[offset]; + offset++; + } + + final DecimalFormat df = new DecimalFormat("#.##"); + return df.format(p) + ' ' + level + unitName + (isRate ? "/t" : ""); + } + + public static ForgeDirection + crossProduct(final ForgeDirection forward, final ForgeDirection up) { + final int west_x = forward.offsetY * up.offsetZ - forward.offsetZ * up.offsetY; + final int west_y = forward.offsetZ * up.offsetX - forward.offsetX * up.offsetZ; + final int west_z = forward.offsetX * up.offsetY - forward.offsetY * up.offsetX; + + switch (west_x + west_y * 2 + west_z * 3) { + case 1: + return ForgeDirection.EAST; + case -1: + return ForgeDirection.WEST; + + case 2: + return ForgeDirection.UP; + case -2: + return ForgeDirection.DOWN; + + case 3: + return ForgeDirection.SOUTH; + case -3: + return ForgeDirection.NORTH; + } + + return ForgeDirection.UNKNOWN; + } + + public static + T rotateEnum(T ce, final boolean backwards, final 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... + */ + private static T prevEnum(final T ce) { + final EnumSet valList = EnumSet.allOf(ce.getClass()); + + int pLoc = ce.ordinal() - 1; + if (pLoc < 0) { + pLoc = valList.size() - 1; + } + + if (pLoc < 0 || pLoc >= valList.size()) { + pLoc = 0; + } + + int pos = 0; + for (final Object g : valList) { + if (pos == pLoc) { + return (T) g; + } + pos++; + } + + return null; + } + + /* + * Simple way to cycle an enum... + */ + public static T nextEnum(final T ce) { + final EnumSet valList = EnumSet.allOf(ce.getClass()); + + int pLoc = ce.ordinal() + 1; + if (pLoc >= valList.size()) { + pLoc = 0; + } + + if (pLoc < 0 || pLoc >= valList.size()) { + pLoc = 0; + } + + int pos = 0; + for (final Object g : valList) { + if (pos == pLoc) { + return (T) g; + } + pos++; + } + + return null; + } + + private static boolean isNotValidSetting(final Enum e) { + if (e == SortOrder.INVTWEAKS + && !IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.InvTweaks)) { + return true; + } + + if (e == SearchBoxMode.NEI_AUTOSEARCH + && !IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI)) { + return true; + } + + return e == SearchBoxMode.NEI_MANUAL_SEARCH + && !IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.NEI); + } + + public static void openGUI( + @Nonnull final EntityPlayer p, + @Nullable final TileEntity tile, + @Nullable final ForgeDirection side, + @Nonnull final 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, + p.getEntityWorld(), + p.inventory.currentItem, + 0, + 0 + ); + } else 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 + ); + } + } + } + + /* + * returns true if the code is on the client. + */ + public static boolean isClient() { + return FMLCommonHandler.instance().getEffectiveSide().isClient(); + } + + public static boolean + hasPermissions(final DimensionalCoord dc, final EntityPlayer player) { + return dc.getWorld().canMineBlock(player, dc.x, dc.y, dc.z); + } + + /* + * Checks to see if a block is air? + */ + public static boolean + isBlockAir(final World w, final int x, final int y, final int z) { + try { + return w.getBlock(x, y, z).isAir(w, x, y, z); + } catch (final Throwable e) { + return false; + } + } + + /* + * 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. + */ + private static boolean sameStackStags(final ItemStack a, final ItemStack b) { + if (a == null && b == null) { + return true; + } + if (a == null || b == null) { + return false; + } + if (a == b) { + return true; + } + + final NBTTagCompound ta = a.getTagCompound(); + final NBTTagCompound tb = b.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 both tags are shared this is easy... + if (AESharedNBT.isShared(ta) && AESharedNBT.isShared(tb)) { + return ta == tb; + } + + return NBTEqualityTest(ta, tb); + } + + /* + * recursive test for NBT Equality, this was faster then trying to compare / generate + * hashes, its also more reliable 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(final NBTBase left, final NBTBase right) { + // same type? + final byte id = left.getId(); + if (id == right.getId()) { + switch (id) { + case 10: { + final NBTTagCompound ctA = (NBTTagCompound) left; + final NBTTagCompound ctB = (NBTTagCompound) right; + + final Set cA = ctA.func_150296_c(); + final Set cB = ctB.func_150296_c(); + + if (cA.size() != cB.size()) { + return false; + } + + for (final String name : cA) { + final NBTBase tag = ctA.getTag(name); + final NBTBase aTag = ctB.getTag(name); + if (aTag == null) { + return false; + } + + if (!NBTEqualityTest(tag, aTag)) { + return false; + } + } + + return true; + } + + case 9: // ) // A instanceof NBTTagList ) + { + final NBTTagList lA = (NBTTagList) left; + final NBTTagList lB = (NBTTagList) right; + if (lA.tagCount() != lB.tagCount()) { + return false; + } + + final List tag = tagList(lA); + final 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; + } + + case 1: // ( A instanceof NBTTagByte ) + return ((NBTBase.NBTPrimitive) left).func_150287_d() + == ((NBTBase.NBTPrimitive) right).func_150287_d(); + + case 4: // else if ( A instanceof NBTTagLong ) + return ((NBTBase.NBTPrimitive) left).func_150291_c() + == ((NBTBase.NBTPrimitive) right).func_150291_c(); + + case 8: // else if ( A instanceof NBTTagString ) + return ((NBTTagString) left) + .func_150285_a_() + .equals(((NBTTagString) right).func_150285_a_()) + || ((NBTTagString) left) + .func_150285_a_() + .equals(((NBTTagString) right).func_150285_a_()); + + case 6: // else if ( A instanceof NBTTagDouble ) + return ((NBTBase.NBTPrimitive) left).func_150286_g() + == ((NBTBase.NBTPrimitive) right).func_150286_g(); + + case 5: // else if ( A instanceof NBTTagFloat ) + return ((NBTBase.NBTPrimitive) left).func_150288_h() + == ((NBTBase.NBTPrimitive) right).func_150288_h(); + + case 3: // else if ( A instanceof NBTTagInt ) + return ((NBTBase.NBTPrimitive) left).func_150287_d() + == ((NBTBase.NBTPrimitive) right).func_150287_d(); + + default: + return left.equals(right); + } + } + + return false; + } + + private static List tagList(final NBTTagList lB) { + if (tagList == null) { + try { + tagList = lB.getClass().getDeclaredField("tagList"); + } catch (final Throwable t) { + try { + tagList = lB.getClass().getDeclaredField("field_74747_a"); + } catch (final Throwable z) { + AELog.debug(t); + AELog.debug(z); + } + } + } + + try { + tagList.setAccessible(true); + return (List) tagList.get(lB); + } catch (final Throwable t) { + AELog.debug(t); + } + + return new ArrayList(); + } + + /* + * 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(final NBTBase nbt) { + // same type? + int hash = 0; + final byte id = nbt.getId(); + hash += id; + switch (id) { + case 10: { + final NBTTagCompound ctA = (NBTTagCompound) nbt; + + final Set cA = ctA.func_150296_c(); + + for (final String name : cA) { + hash += name.hashCode() ^ NBTOrderlessHash(ctA.getTag(name)); + } + + return hash; + } + + case 9: // ) // A instanceof NBTTagList ) + { + final NBTTagList lA = (NBTTagList) nbt; + hash += 9 * lA.tagCount(); + + final List l = tagList(lA); + for (int x = 0; x < l.size(); x++) { + hash += ((Integer) x).hashCode() ^ NBTOrderlessHash(l.get(x)); + } + + return hash; + } + + case 1: // ( A instanceof NBTTagByte ) + return hash + ((NBTBase.NBTPrimitive) nbt).func_150290_f(); + + case 4: // else if ( A instanceof NBTTagLong ) + return hash + (int) ((NBTBase.NBTPrimitive) nbt).func_150291_c(); + + case 8: // else if ( A instanceof NBTTagString ) + return hash + ((NBTTagString) nbt).func_150285_a_().hashCode(); + + case 6: // else if ( A instanceof NBTTagDouble ) + return hash + (int) ((NBTBase.NBTPrimitive) nbt).func_150286_g(); + + case 5: // else if ( A instanceof NBTTagFloat ) + return hash + (int) ((NBTBase.NBTPrimitive) nbt).func_150288_h(); + + case 3: // else if ( A instanceof NBTTagInt ) + return hash + ((NBTBase.NBTPrimitive) nbt).func_150287_d(); + + default: + return hash; + } + } + + /* + * The usual version of this returns an ItemStack, this version returns the recipe. + */ + public static IRecipe + findMatchingRecipe(final InventoryCrafting inventoryCrafting, final World par2World) { + final CraftingManager cm = CraftingManager.getInstance(); + final List rl = cm.getRecipeList(); + + for (final IRecipe r : rl) { + if (r.matches(inventoryCrafting, par2World)) { + return r; + } + } + + return null; + } + + public static ItemStack[] getBlockDrops( + final World w, final int x, final int y, final int z + ) { + List out = new ArrayList(); + final Block which = w.getBlock(x, y, z); + + if (which != null) { + out = which.getDrops(w, x, y, z, w.getBlockMetadata(x, y, z), 0); + } + + if (out == null) { + return new ItemStack[0]; + } + return out.toArray(new ItemStack[out.size()]); + } + + public static ForgeDirection + cycleOrientations(final ForgeDirection dir, final boolean upAndDown) { + if (upAndDown) { + 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; + } + } else { + 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; + } + } + + return ForgeDirection.UNKNOWN; + } + + /* + * Creates / or loads previous NBT Data on items, used for editing items owned by AE. + */ + public static NBTTagCompound openNbtData(final ItemStack i) { + NBTTagCompound compound = i.getTagCompound(); + + if (compound == null) { + i.setTagCompound(compound = new NBTTagCompound()); + } + + return compound; + } + + /* + * Generates Item entities in the world similar to how items are generally dropped. + */ + public static void spawnDrops( + final World w, final int x, final int y, final int z, final List drops + ) { + if (isServer()) { + for (final ItemStack i : drops) { + if (i != null) { + if (i.stackSize > 0) { + final double offset_x = (getRandomInt() % 32 - 16) / 82; + final double offset_y = (getRandomInt() % 32 - 16) / 82; + final double offset_z = (getRandomInt() % 32 - 16) / 82; + final 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); + } + } + } + } + } + + /* + * 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(final Object te) { + TileEntityChest teA = (TileEntityChest) te; + TileEntity teB = null; + final Block myBlockID + = teA.getWorldObj().getBlock(teA.xCoord, teA.yCoord, teA.zCoord); + + 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)) { + teB = null; + } + } + + if (teB == null) { + 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)) { + teB = null; + } else { + final TileEntityChest x = teA; + teA = (TileEntityChest) teB; + teB = x; + } + } + } + + if (teB == null) { + 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)) { + teB = null; + } + } + } + + if (teB == null) { + 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)) { + teB = null; + } else { + final TileEntityChest x = teA; + teA = (TileEntityChest) teB; + teB = x; + } + } + } + + if (teB == null) { + return teA; + } + + return new InventoryLargeChest("", teA, (IInventory) teB); + } + + public static boolean isModLoaded(final String modid) { + try { + // if this fails for some reason, try the other method. + return Loader.isModLoaded(modid); + } catch (final Throwable ignored) {} + + for (final ModContainer f : Loader.instance().getActiveModList()) { + if (f.getModId().equals(modid)) { + return true; + } + } + return false; + } + + public static ItemStack + findMatchingRecipeOutput(final InventoryCrafting ic, final World worldObj) { + return CraftingManager.getInstance().findMatchingRecipe(ic, worldObj); + } + + @SideOnly(Side.CLIENT) + public static List getTooltip(final Object o) { + if (o == null) { + return new ArrayList(); + } + + ItemStack itemStack = null; + if (o instanceof AEItemStack) { + final AEItemStack ais = (AEItemStack) o; + return ais.getToolTip(); + } else if (o instanceof ItemStack) { + itemStack = (ItemStack) o; + } else { + return new ArrayList(); + } + + try { + return itemStack.getTooltip(Minecraft.getMinecraft().thePlayer, false); + } catch (final Exception errB) { + return new ArrayList(); + } + } + + public static String getModId(final IAEItemStack is) { + if (is == null) { + return "** Null"; + } + + final String n = ((AEItemStack) is).getModID(); + return n == null ? "** Null" : n; + } + + public static String getItemDisplayName(final Object o) { + if (o == null) { + return "** Null"; + } + + ItemStack itemStack = null; + if (o instanceof AEItemStack) { + final String n = ((AEItemStack) o).getDisplayName(); + return n == null ? "** Null" : n; + } else if (o instanceof ItemStack) { + itemStack = (ItemStack) o; + } else { + return "**Invalid Object"; + } + + try { + String name = itemStack.getDisplayName(); + if (name == null || name.isEmpty()) { + name = itemStack.getItem().getUnlocalizedName(itemStack); + } + return name == null ? "** Null" : name; + } catch (final Exception errA) { + try { + final String n = itemStack.getUnlocalizedName(); + return n == null ? "** Null" : n; + } catch (final Exception errB) { + return "** Exception"; + } + } + } + + public static boolean hasSpecialComparison(final IAEItemStack willAdd) { + if (willAdd == null) { + return false; + } + final IAETagCompound tag = willAdd.getTagCompound(); + return tag != null && tag.getSpecialComparison() != null; + } + + public static boolean hasSpecialComparison(final ItemStack willAdd) { + if (AESharedNBT.isShared(willAdd.getTagCompound())) { + if (((IAETagCompound) willAdd.getTagCompound()).getSpecialComparison() + != null) { + return true; + } + } + return false; + } + + public static boolean isWrench( + final EntityPlayer player, + final ItemStack eq, + final int x, + final int y, + final int z + ) { + if (eq != null) { + try { + if (eq.getItem() instanceof IToolWrench) { + final IToolWrench wrench = (IToolWrench) eq.getItem(); + return wrench.canWrench(player, x, y, z); + } + } catch (final Throwable ignore) { // explodes without BC + } + + if (eq.getItem() instanceof IAEWrench) { + final IAEWrench wrench = (IAEWrench) eq.getItem(); + return wrench.canWrench(eq, player, x, y, z); + } + } + return false; + } + + public static boolean isChargeable(final ItemStack i) { + if (i == null) { + return false; + } + final Item it = i.getItem(); + if (it instanceof IAEItemPowerStorage) { + return ((IAEItemPowerStorage) it).getPowerFlow(i) != AccessRestriction.READ; + } + return false; + } + + public static EntityPlayer getPlayer(final WorldServer w) { + if (w == null) { + throw new InvalidParameterException("World is null."); + } + + final EntityPlayer wrp = FAKE_PLAYERS.get(w); + if (wrp != null) { + return wrp; + } + + final EntityPlayer p = FakePlayerFactory.get(w, fakeProfile); + FAKE_PLAYERS.put(w, p); + return p; + } + + public static int MC2MEColor(final int 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" + } + return -1; + } + + public static int findEmpty(final Object[] l) { + for (int x = 0; x < l.length; x++) { + if (l[x] == null) { + return x; + } + } + return -1; + } + + public static T pickRandom(final Collection outs) { + int index = RANDOM_GENERATOR.nextInt(outs.size()); + final Iterator i = outs.iterator(); + while (i.hasNext() && index > 0) { + index--; + i.next(); + } + index--; + if (i.hasNext()) { + return i.next(); + } + return null; // wtf? + } + + public static ForgeDirection + rotateAround(final ForgeDirection forward, final ForgeDirection axis) { + if (axis == ForgeDirection.UNKNOWN || forward == ForgeDirection.UNKNOWN) { + return forward; + } + + switch (forward) { + case DOWN: + 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: + 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(final String string) { + return StatCollector.translateToLocal(string); + } + + public static boolean + isSameItemPrecise(@Nullable final ItemStack is, @Nullable final ItemStack filter) { + return isSameItem(is, filter) && sameStackStags(is, filter); + } + + public static boolean + isSameItemFuzzy(final ItemStack a, final ItemStack b, final FuzzyMode mode) { + if (a == null && b == null) { + return true; + } + + if (a == null) { + return false; + } + + if (b == null) { + return false; + } + + /* + * if ( a.itemID != 0 && b.itemID != 0 && a.isItemStackDamageable() && ! + * a.getHasSubtypes() && a.itemID == b.itemID ) { return (a.getItemDamage() > 0) + * == (b.getItemDamage() > 0); } + */ + + // test damageable items.. + if (a.getItem() != null && b.getItem() != null && a.getItem().isDamageable() + && a.getItem() == b.getItem()) { + try { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamageForDisplay() > 1) + == (b.getItemDamageForDisplay() > 1); + } else { + final float percentDamagedOfA = 1.0f + - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); + final float percentDamagedOfB = 1.0f + - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); + + return (percentDamagedOfA > mode.breakPoint) + == (percentDamagedOfB > mode.breakPoint); + } + } catch (final Throwable e) { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamage() > 1) == (b.getItemDamage() > 1); + } else { + final float percentDamagedOfA + = (float) a.getItemDamage() / (float) a.getMaxDamage(); + final float percentDamagedOfB + = (float) b.getItemDamage() / (float) b.getMaxDamage(); + + return (percentDamagedOfA > mode.breakPoint) + == (percentDamagedOfB > mode.breakPoint); + } + } + } + + final OreReference aOR = OreHelper.INSTANCE.isOre(a); + final OreReference bOR = OreHelper.INSTANCE.isOre(b); + + if (OreHelper.INSTANCE.sameOre(aOR, bOR)) { + return true; + } + + /* + * // test ore dictionary.. int OreID = getOreID( a ); if ( OreID != -1 ) return + * OreID == getOreID( b ); if ( Mode != FuzzyMode.IGNORE_ALL ) { if ( + * a.hasTagCompound() && !isShared( a.getTagCompound() ) ) { a = + * Platform.getSharedItemStack( AEItemStack.create( a ) ); } + * if ( b.hasTagCompound() && !isShared( b.getTagCompound() ) ) { b = + * Platform.getSharedItemStack( AEItemStack.create( b ) ); } + * // test regular items with damage values and what not... if ( isShared( + * a.getTagCompound() ) && isShared( b.getTagCompound() ) && a.itemID == b.itemID + * ) { return ((AppEngSharedNBTTagCompound) + * a.getTagCompound()).compareFuzzyWithRegistry( (AppEngSharedNBTTagCompound) + * b.getTagCompound() ); } } + */ + + return a.isItemEqual(b); + } + + public static LookDirection + getPlayerRay(final EntityPlayer player, final float eyeOffset) { + final float f = 1.0F; + final float f1 = player.prevRotationPitch + + (player.rotationPitch - player.prevRotationPitch) * f; + final float f2 + = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * f; + final double d0 = player.prevPosX + (player.posX - player.prevPosX) * f; + final double d1 = eyeOffset; + final double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * f; + + final Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); + final float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); + final float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); + final float f5 = -MathHelper.cos(-f1 * 0.017453292F); + final float f6 = MathHelper.sin(-f1 * 0.017453292F); + final float f7 = f4 * f5; + final float f8 = f3 * f5; + double d3 = 5.0D; + + if (player instanceof EntityPlayerMP) { + d3 = ((EntityPlayerMP) player).theItemInWorldManager.getBlockReachDistance(); + } + final Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); + return new LookDirection(vec3, vec31); + } + + public static MovingObjectPosition + rayTrace(final EntityPlayer p, final boolean hitBlocks, final boolean hitEntities) { + final World w = p.getEntityWorld(); + + final float f = 1.0F; + float f1 = p.prevRotationPitch + (p.rotationPitch - p.prevRotationPitch) * f; + final float f2 = p.prevRotationYaw + (p.rotationYaw - p.prevRotationYaw) * f; + final double d0 = p.prevPosX + (p.posX - p.prevPosX) * f; + final double d1 = p.prevPosY + (p.posY - p.prevPosY) * f + 1.62D - p.yOffset; + final double d2 = p.prevPosZ + (p.posZ - p.prevPosZ) * f; + final Vec3 vec3 = Vec3.createVectorHelper(d0, d1, d2); + final float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI); + final float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI); + final float f5 = -MathHelper.cos(-f1 * 0.017453292F); + final float f6 = MathHelper.sin(-f1 * 0.017453292F); + final float f7 = f4 * f5; + final float f8 = f3 * f5; + final double d3 = 32.0D; + + final Vec3 vec31 = vec3.addVector(f7 * d3, f6 * d3, f8 * d3); + + final 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) { + final List list = w.getEntitiesWithinAABBExcludingEntity(p, bb); + + for (int l = 0; l < list.size(); ++l) { + final Entity entity1 = (Entity) list.get(l); + + if (!entity1.isDead && entity1 != p && !(entity1 instanceof EntityItem)) { + if (entity1.isEntityAlive()) { + // prevent killing / flying of mounts. + if (entity1.riddenByEntity == p) { + continue; + } + + f1 = 0.3F; + final AxisAlignedBB boundingBox + = entity1.boundingBox.expand(f1, f1, f1); + final MovingObjectPosition movingObjectPosition + = boundingBox.calculateIntercept(vec3, vec31); + + if (movingObjectPosition != null) { + final double nd + = vec3.squareDistanceTo(movingObjectPosition.hitVec); + + if (nd < closest) { + entity = entity1; + closest = nd; + } + } + } + } + } + } + + MovingObjectPosition pos = null; + Vec3 vec = null; + + if (hitBlocks) { + vec = Vec3.createVectorHelper(d0, d1, d2); + pos = w.rayTraceBlocks(vec3, vec31, true); + } + + if (entity != null && pos != null && pos.hitVec.squareDistanceTo(vec) > closest) { + pos = new MovingObjectPosition(entity); + } else if (entity != null && pos == null) { + pos = new MovingObjectPosition(entity); + } + + return pos; + } + + public static long nanoTime() { + // if ( Configuration.INSTANCE.enableNetworkProfiler ) + // return System.nanoTime(); + return 0; + } + + public static StackType poweredExtraction( + final IEnergySource energy, + final IMEInventory cell, + final StackType request, + final BaseActionSource src + ) { + final StackType possible + = cell.extractItems((StackType) request.copy(), Actionable.SIMULATE, src); + + long retrieved = 0; + if (possible != null) { + retrieved = possible.getStackSize(); + } + + final double availablePower = energy.extractAEPower( + retrieved, Actionable.SIMULATE, PowerMultiplier.CONFIG + ); + + final long itemToExtract = Math.min((long) (availablePower + 0.9), retrieved); + + if (itemToExtract > 0) { + energy.extractAEPower(retrieved, Actionable.MODULATE, PowerMultiplier.CONFIG); + + possible.setStackSize(itemToExtract); + final StackType ret = cell.extractItems(possible, Actionable.MODULATE, src); + + if (ret != null && src.isPlayer()) { + Stats.ItemsExtracted.addToPlayer( + ((PlayerSource) src).player, (int) ret.getStackSize() + ); + } + + return ret; + } + + return null; + } + + public static StackType poweredInsert( + final IEnergySource energy, + final IMEInventory cell, + final StackType input, + final BaseActionSource src + ) { + final StackType possible + = cell.injectItems((StackType) input.copy(), Actionable.SIMULATE, src); + + long stored = input.getStackSize(); + if (possible != null) { + stored -= possible.getStackSize(); + } + + final double availablePower + = energy.extractAEPower(stored, Actionable.SIMULATE, PowerMultiplier.CONFIG); + + final long itemToAdd = Math.min((long) (availablePower + 0.9), stored); + + if (itemToAdd > 0) { + energy.extractAEPower(stored, Actionable.MODULATE, PowerMultiplier.CONFIG); + + if (itemToAdd < input.getStackSize()) { + final long original = input.getStackSize(); + final StackType split = (StackType) input.copy(); + split.decStackSize(itemToAdd); + input.setStackSize(itemToAdd); + split.add(cell.injectItems(input, Actionable.MODULATE, src)); + + if (src.isPlayer()) { + final long diff = original - split.getStackSize(); + Stats.ItemsInserted.addToPlayer( + ((PlayerSource) src).player, (int) diff + ); + } + + return split; + } + + final StackType ret = cell.injectItems(input, Actionable.MODULATE, src); + + if (src.isPlayer()) { + final long diff = ret == null ? input.getStackSize() + : input.getStackSize() - ret.getStackSize(); + Stats.ItemsInserted.addToPlayer(((PlayerSource) src).player, (int) diff); + } + + return ret; + } + + return input; + } + + public static void postChanges( + final IStorageGrid gs, + final ItemStack removed, + final ItemStack added, + final BaseActionSource src + ) { + final IItemList itemChanges + = AEApi.instance().storage().createItemList(); + final IItemList fluidChanges + = AEApi.instance().storage().createFluidList(); + + if (removed != null) { + final IMEInventory myItems + = AEApi.instance().registries().cell().getCellInventory( + removed, null, StorageChannel.ITEMS + ); + + if (myItems != null) { + for (final IAEItemStack is : myItems.getAvailableItems(itemChanges)) { + is.setStackSize(-is.getStackSize()); + } + } + + final IMEInventory myFluids + = AEApi.instance().registries().cell().getCellInventory( + removed, null, StorageChannel.FLUIDS + ); + + if (myFluids != null) { + for (final IAEFluidStack is : myFluids.getAvailableItems(fluidChanges)) { + is.setStackSize(-is.getStackSize()); + } + } + } + + if (added != null) { + final IMEInventory myItems + = AEApi.instance().registries().cell().getCellInventory( + added, null, StorageChannel.ITEMS + ); + + if (myItems != null) { + myItems.getAvailableItems(itemChanges); + } + + final IMEInventory myFluids + = AEApi.instance().registries().cell().getCellInventory( + added, null, StorageChannel.FLUIDS + ); + + if (myFluids != null) { + myFluids.getAvailableItems(fluidChanges); + } + } + + gs.postAlterationOfStoredItems(StorageChannel.ITEMS, itemChanges, src); + } + + public static > void postListChanges( + final IItemList before, + final IItemList after, + final IMEMonitorHandlerReceiver meMonitorPassthrough, + final BaseActionSource source + ) { + final LinkedList changes = new LinkedList(); + + for (final T is : before) { + is.setStackSize(-is.getStackSize()); + } + + for (final T is : after) { + before.add(is); + } + + for (final T is : before) { + if (is.getStackSize() != 0) { + changes.add(is); + } + } + + if (!changes.isEmpty()) { + meMonitorPassthrough.postChange(null, changes, source); + } + } + + public static int generateTileHash(final TileEntity target) { + if (target == null) { + return 0; + } + + int hash = target.hashCode(); + + if (target instanceof ITileStorageMonitorable) { + return 0; + } else if (target instanceof TileEntityChest) { + final TileEntityChest chest = (TileEntityChest) target; + chest.checkForAdjacentChests(); + if (chest.adjacentChestZNeg != null) { + hash ^= chest.adjacentChestZNeg.hashCode(); + } else if (chest.adjacentChestZPos != null) { + hash ^= chest.adjacentChestZPos.hashCode(); + } else if (chest.adjacentChestXPos != null) { + hash ^= chest.adjacentChestXPos.hashCode(); + } else if (chest.adjacentChestXNeg != null) { + hash ^= chest.adjacentChestXNeg.hashCode(); + } + } else if (target instanceof IInventory) { + hash ^= ((IInventory) target).getSizeInventory(); + + if (target instanceof ISidedInventory) { + for (final ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { + final int[] sides = ((ISidedInventory) target) + .getAccessibleSlotsFromSide(dir.ordinal()); + + if (sides == null) { + return 0; + } + + int offset = 0; + for (final int side : sides) { + final int c = (side << (offset % 8)) ^ (1 << dir.ordinal()); + offset++; + hash = c + (hash << 6) + (hash << 16) - hash; + } + } + } + } + + return hash; + } + + public static boolean securityCheck(final GridNode a, final GridNode b) { + if (a.getLastSecurityKey() == -1 && b.getLastSecurityKey() == -1) { + return false; + } else if (a.getLastSecurityKey() == b.getLastSecurityKey()) { + return false; + } + + final boolean a_isSecure = isPowered(a.getGrid()) && a.getLastSecurityKey() != -1; + final boolean b_isSecure = isPowered(b.getGrid()) && b.getLastSecurityKey() != -1; + + if (AEConfig.instance.isFeatureEnabled(AEFeature.LogSecurityAudits)) { + AELog.info( + "Audit: " + a_isSecure + " : " + b_isSecure + " @ " + + a.getLastSecurityKey() + " vs " + b.getLastSecurityKey() + " & " + + a.getPlayerID() + " vs " + b.getPlayerID() + ); + } + + // can't do that son... + if (a_isSecure && b_isSecure) { + return true; + } + + if (!a_isSecure && b_isSecure) { + return checkPlayerPermissions(b.getGrid(), a.getPlayerID()); + } + + if (a_isSecure && !b_isSecure) { + return checkPlayerPermissions(a.getGrid(), b.getPlayerID()); + } + + return false; + } + + private static boolean isPowered(final IGrid grid) { + if (grid == null) { + return false; + } + + final IEnergyGrid eg = grid.getCache(IEnergyGrid.class); + return eg.isNetworkPowered(); + } + + private static boolean checkPlayerPermissions(final IGrid grid, final int playerID) { + if (grid == null) { + return false; + } + + final ISecurityGrid gs = grid.getCache(ISecurityGrid.class); + + if (gs == null) { + return false; + } + + if (!gs.isAvailable()) { + return false; + } + + return !gs.hasPermission(playerID, SecurityPermissions.BUILD); + } + + public static void configurePlayer( + final EntityPlayer player, final ForgeDirection side, final TileEntity tile + ) { + player.yOffset = 1.8f; + + float yaw = 0.0f; + float pitch = 0.0f; + 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; + } + + player.posX = tile.xCoord + 0.5; + player.posY = tile.yCoord + 0.5; + player.posZ = tile.zCoord + 0.5; + + player.rotationPitch = player.prevCameraPitch = player.cameraPitch = pitch; + player.rotationYaw = player.prevCameraYaw = player.cameraYaw = yaw; + } + + public static boolean + canAccess(final AENetworkProxy gridProxy, final BaseActionSource src) { + try { + if (src.isPlayer()) { + return gridProxy.getSecurity().hasPermission( + ((PlayerSource) src).player, SecurityPermissions.BUILD + ); + } else if (src.isMachine()) { + final IActionHost te = ((MachineSource) src).via; + final IGridNode n = te.getActionableNode(); + if (n == null) { + return false; + } + + final int playerID = n.getPlayerID(); + return gridProxy.getSecurity().hasPermission( + playerID, SecurityPermissions.BUILD + ); + } else { + return false; + } + } catch (final GridAccessException gae) { + return false; + } + } + + public static ItemStack extractItemsByRecipe( + final IEnergySource energySrc, + final BaseActionSource mySrc, + final IMEMonitor src, + final World w, + final IRecipe r, + final ItemStack output, + final InventoryCrafting ci, + final ItemStack providedTemplate, + final int slot, + final IItemList items, + final Actionable realForFake, + final IPartitionList filter + ) { + if (energySrc.extractAEPower(1, Actionable.SIMULATE, PowerMultiplier.CONFIG) + > 0.9) { + if (providedTemplate == null) { + return null; + } + + final AEItemStack ae_req = AEItemStack.create(providedTemplate); + ae_req.setStackSize(1); + + if (filter == null || filter.isListed(ae_req)) { + final IAEItemStack ae_ext = src.extractItems(ae_req, realForFake, mySrc); + if (ae_ext != null) { + final ItemStack extracted = ae_ext.getItemStack(); + if (extracted != null) { + energySrc.extractAEPower(1, realForFake, PowerMultiplier.CONFIG); + return extracted; + } + } + } + + final boolean checkFuzzy = ae_req.isOre() + || providedTemplate.getItemDamage() == OreDictionary.WILDCARD_VALUE + || providedTemplate.hasTagCompound() + || providedTemplate.isItemStackDamageable(); + + if (items != null && checkFuzzy) { + for (final IAEItemStack x : items) { + final ItemStack sh = x.getItemStack(); + if ((Platform.isSameItemType(providedTemplate, sh) + || ae_req.sameOre(x)) + && !Platform.isSameItem( + sh, output + )) { // Platform.isSameItemType( sh, providedTemplate ) + final ItemStack cp = Platform.cloneItemStack(sh); + cp.stackSize = 1; + ci.setInventorySlotContents(slot, cp); + if (r.matches(ci, w) + && Platform.isSameItem(r.getCraftingResult(ci), output)) { + final IAEItemStack ax = x.copy(); + ax.setStackSize(1); + if (filter == null || filter.isListed(ax)) { + final IAEItemStack ex + = src.extractItems(ax, realForFake, mySrc); + if (ex != null) { + energySrc.extractAEPower( + 1, realForFake, PowerMultiplier.CONFIG + ); + return ex.getItemStack(); + } + } + } + ci.setInventorySlotContents(slot, providedTemplate); + } + } + } + } + return null; + } + + public static boolean isSameItemType(final ItemStack that, final ItemStack other) { + if (that != null && other != null && that.getItem() == other.getItem()) { + if (that.isItemStackDamageable()) { + return true; + } + return that.getItemDamage() == other.getItemDamage(); + } + return false; + } + + public static boolean + isSameItem(@Nullable final ItemStack left, @Nullable final ItemStack right) { + return left != null && right != null && left.isItemEqual(right); + } + + public static ItemStack cloneItemStack(final ItemStack a) { + return a.copy(); + } + + public static ItemStack getContainerItem(final ItemStack stackInSlot) { + if (stackInSlot == null) { + return null; + } + + final Item i = stackInSlot.getItem(); + if (i == null || !i.hasContainerItem(stackInSlot)) { + if (stackInSlot.stackSize > 1) { + stackInSlot.stackSize--; + return stackInSlot; + } + return null; + } + + ItemStack ci = i.getContainerItem(stackInSlot.copy()); + if (ci != null && ci.isItemStackDamageable() + && ci.getItemDamage() == ci.getMaxDamage()) { + ci = null; + } + + return ci; + } + + public static void notifyBlocksOfNeighbors( + final World worldObj, final int xCoord, final int yCoord, final int zCoord + ) { + if (!worldObj.isRemote) { + TickHandler.INSTANCE.addCallable( + worldObj, new BlockUpdate(xCoord, yCoord, zCoord) + ); + } + } + + public static boolean + canRepair(final AEFeature type, final ItemStack a, final ItemStack b) { + if (b == null || a == null) { + return false; + } + + if (type == AEFeature.CertusQuartzTools) { + final IItemDefinition certusQuartzCrystal + = AEApi.instance().definitions().materials().certusQuartzCrystal(); + + return certusQuartzCrystal.isSameAs(b); + } + + if (type == AEFeature.NetherQuartzTools) { + return Items.quartz == b.getItem(); + } + + return false; + } + + public static Object findPreferred(final ItemStack[] is) { + final IParts parts = AEApi.instance().definitions().parts(); + + for (final ItemStack stack : is) { + if (parts.cableGlass().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableCovered().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableSmart().sameAs(AEColor.Transparent, stack)) { + return stack; + } + + if (parts.cableDense().sameAs(AEColor.Transparent, stack)) { + return stack; + } + } + + return is; + } + + public static void sendChunk(final Chunk c, final int verticalBits) { + try { + final WorldServer ws = (WorldServer) c.worldObj; + final PlayerManager pm = ws.getPlayerManager(); + + if (getOrCreateChunkWatcher == null) { + getOrCreateChunkWatcher = ReflectionHelper.findMethod( + PlayerManager.class, + pm, + new String[] { "getOrCreateChunkWatcher", "func_72690_a" }, + int.class, + int.class, + boolean.class + ); + } + + if (getOrCreateChunkWatcher != null) { + final Object playerInstance + = getOrCreateChunkWatcher.invoke(pm, c.xPosition, c.zPosition, false); + if (playerInstance != null) { + Platform.playerInstance = playerInstance.getClass(); + + if (sendToAllPlayersWatchingChunk == null) { + sendToAllPlayersWatchingChunk = ReflectionHelper.findMethod( + Platform.playerInstance, + playerInstance, + new String[] { "sendToAllPlayersWatchingChunk", + "func_151251_a" }, + Packet.class + ); + } + + if (sendToAllPlayersWatchingChunk != null) { + sendToAllPlayersWatchingChunk.invoke( + playerInstance, new S21PacketChunkData(c, false, verticalBits) + ); + } + } + } + } catch (final Throwable t) { + AELog.debug(t); + } + } + + public static AxisAlignedBB + getPrimaryBox(final ForgeDirection side, final int facadeThickness) { + 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; + } + return AxisAlignedBB.getBoundingBox(0, 0, 0, 1, 1, 1); + } + + public static float getEyeOffset(final EntityPlayer player) { + assert player.worldObj.isRemote: "Valid only on client"; + return (float + ) (player.posY + player.getEyeHeight() - player.getDefaultEyeHeight()); + } + + public static void addStat(final int playerID, final Achievement achievement) { + final EntityPlayer p + = AEApi.instance().registries().players().findPlayer(playerID); + if (p != null) { + p.addStat(achievement, 1); + } + } + + public static boolean isRecipePrioritized(final ItemStack what) { + final IMaterials materials = AEApi.instance().definitions().materials(); + + boolean isPurified = materials.purifiedCertusQuartzCrystal().isSameAs(what); + isPurified |= materials.purifiedFluixCrystal().isSameAs(what); + isPurified |= materials.purifiedNetherQuartzCrystal().isSameAs(what); + + return isPurified; + } } diff --git a/src/main/java/appeng/util/ReadOnlyCollection.java b/src/main/java/appeng/util/ReadOnlyCollection.java index b059e3f1..3dd974e8 100644 --- a/src/main/java/appeng/util/ReadOnlyCollection.java +++ b/src/main/java/appeng/util/ReadOnlyCollection.java @@ -18,44 +18,35 @@ package appeng.util; - -import appeng.api.util.IReadOnlyCollection; - import java.util.Collection; import java.util.Iterator; +import appeng.api.util.IReadOnlyCollection; -public class ReadOnlyCollection implements IReadOnlyCollection -{ +public class ReadOnlyCollection implements IReadOnlyCollection { + private final Collection c; - private final Collection c; + public ReadOnlyCollection(final Collection in) { + this.c = in; + } - public ReadOnlyCollection( final Collection in ) - { - this.c = in; - } + @Override + public Iterator iterator() { + return this.c.iterator(); + } - @Override - public Iterator iterator() - { - return this.c.iterator(); - } + @Override + public int size() { + return this.c.size(); + } - @Override - public int size() - { - return this.c.size(); - } + @Override + public boolean isEmpty() { + return this.c.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.c.isEmpty(); - } - - @Override - public boolean contains( final Object node ) - { - return this.c.contains( node ); - } + @Override + public boolean contains(final 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 6714a881..8152f99e 100644 --- a/src/main/java/appeng/util/ReadableNumberConverter.java +++ b/src/main/java/appeng/util/ReadableNumberConverter.java @@ -1,12 +1,10 @@ package appeng.util; - import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.Format; - /** * Converter class to convert a large number into a SI system. * @@ -14,92 +12,88 @@ import java.text.Format; * @version rv2 * @since rv2 */ -public enum ReadableNumberConverter implements ISlimReadableNumberConverter, IWideReadableNumberConverter -{ - INSTANCE; +public enum ReadableNumberConverter + implements ISlimReadableNumberConverter, IWideReadableNumberConverter { + INSTANCE; - /** - * Defines the base for a division, non-si standard could be 1024 for kilobytes - */ - private static final int DIVISION_BASE = 1000; + /** + * Defines the base for a division, non-si standard could be 1024 for kilobytes + */ + private static final int DIVISION_BASE = 1000; - /** - * String representation of the sorted postfixes - */ - private static final char[] ENCODED_POSTFIXES = "KMGTPE".toCharArray(); + /** + * String representation of the sorted postfixes + */ + private static final char[] ENCODED_POSTFIXES = "KMGTPE".toCharArray(); - private final Format format; + private final Format format; - /** - * Initializes the specific decimal format with special format for negative and positive numbers - */ - ReadableNumberConverter() - { - final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - symbols.setDecimalSeparator( '.' ); - final DecimalFormat format = new DecimalFormat( ".#;0.#" ); - format.setDecimalFormatSymbols( symbols ); - format.setRoundingMode( RoundingMode.DOWN ); + /** + * Initializes the specific decimal format with special format for negative and + * positive numbers + */ + ReadableNumberConverter() { + final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); + symbols.setDecimalSeparator('.'); + final DecimalFormat format = new DecimalFormat(".#;0.#"); + format.setDecimalFormatSymbols(symbols); + format.setRoundingMode(RoundingMode.DOWN); - this.format = format; - } + this.format = format; + } - @Override - public String toSlimReadableForm( final long number ) - { - return this.toReadableFormRestrictedByWidth( number, 3 ); - } + @Override + public String toSlimReadableForm(final long number) { + return this.toReadableFormRestrictedByWidth(number, 3); + } - /** - * restricts a string representation of a number to a specific width - * - * @param number to be formatted number - * @param width width limitation of the resulting number - * @return formatted number restricted by the width limitation - */ - private String toReadableFormRestrictedByWidth( final long number, final int width ) - { - assert number >= 0; + /** + * restricts a string representation of a number to a specific width + * + * @param number to be formatted number + * @param width width limitation of the resulting number + * @return formatted number restricted by the width limitation + */ + private String toReadableFormRestrictedByWidth(final long number, final int width) { + assert number >= 0; - // handles low numbers more efficiently since no format is needed - final String numberString = Long.toString( number ); - int numberSize = numberString.length(); - if( numberSize <= width ) - { - return numberString; - } + // handles low numbers more efficiently since no format is needed + final String numberString = Long.toString(number); + int numberSize = numberString.length(); + if (numberSize <= width) { + return numberString; + } - long base = number; - double last = base * 1000; - int exponent = -1; - String postFix = ""; + long base = number; + double last = base * 1000; + int exponent = -1; + String postFix = ""; - while( numberSize > width ) - { - last = base; - base /= DIVISION_BASE; + while (numberSize > width) { + last = base; + base /= DIVISION_BASE; - exponent++; + exponent++; - // adds +1 due to the postfix - numberSize = Long.toString( base ).length() + 1; - postFix = String.valueOf( ENCODED_POSTFIXES[exponent] ); - } + // adds +1 due to the postfix + numberSize = Long.toString(base).length() + 1; + postFix = String.valueOf(ENCODED_POSTFIXES[exponent]); + } - final String withPrecision = this.format.format( last / DIVISION_BASE ) + postFix; - final String withoutPrecision = Long.toString( base ) + postFix; + final String withPrecision = this.format.format(last / DIVISION_BASE) + postFix; + final String withoutPrecision = Long.toString(base) + postFix; - final String slimResult = ( withPrecision.length() <= width ) ? withPrecision : withoutPrecision; + final String slimResult + = (withPrecision.length() <= width) ? withPrecision : withoutPrecision; - // post condition - assert slimResult.length() <= width; + // post condition + assert slimResult.length() <= width; - return slimResult; - } + return slimResult; + } - @Override - public String toWideReadableForm( final long number ) - { - return this.toReadableFormRestrictedByWidth( number, 4 ); - } + @Override + public String toWideReadableForm(final long number) { + return this.toReadableFormRestrictedByWidth(number, 4); + } } diff --git a/src/main/java/appeng/util/SettingsFrom.java b/src/main/java/appeng/util/SettingsFrom.java index f187f994..5efa2d02 100644 --- a/src/main/java/appeng/util/SettingsFrom.java +++ b/src/main/java/appeng/util/SettingsFrom.java @@ -18,12 +18,10 @@ package appeng.util; +public enum SettingsFrom { + // moved the item, and replaced it. + DISMANTLE_ITEM, -public enum SettingsFrom -{ - // moved the item, and replaced it. - DISMANTLE_ITEM, - - // used memory card? - MEMORY_CARD + // used memory card? + MEMORY_CARD } diff --git a/src/main/java/appeng/util/UUIDMatcher.java b/src/main/java/appeng/util/UUIDMatcher.java index 91d8c83f..c9017e9c 100644 --- a/src/main/java/appeng/util/UUIDMatcher.java +++ b/src/main/java/appeng/util/UUIDMatcher.java @@ -18,33 +18,32 @@ package appeng.util; - import java.util.regex.Pattern; - /** * Regex wrapper for {@link java.util.UUID}s to not rely on try catch */ -public final class UUIDMatcher -{ - /** - * String which is the regular expression for {@link java.util.UUID}s - */ - private static final String UUID_REGEX = "[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; +public final class UUIDMatcher { + /** + * String which is the regular expression for {@link java.util.UUID}s + */ + private static final String UUID_REGEX + = "[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}"; - /** - * Pattern which pre-compiles the {@link appeng.util.UUIDMatcher#UUID_REGEX} - */ - private static final Pattern PATTERN = Pattern.compile( UUID_REGEX ); + /** + * Pattern which pre-compiles the {@link appeng.util.UUIDMatcher#UUID_REGEX} + */ + private static final Pattern PATTERN = Pattern.compile(UUID_REGEX); - /** - * Checks if a potential {@link java.util.UUID} is an {@link java.util.UUID} by applying a regular expression on it. - * - * @param potential to be checked potential {@link java.util.UUID} - * @return true, if the potential {@link java.util.UUID} is indeed an {@link java.util.UUID} - */ - public boolean isUUID( final CharSequence potential ) - { - return PATTERN.matcher( potential ).matches(); - } + /** + * Checks if a potential {@link java.util.UUID} is an {@link java.util.UUID} by + * applying a regular expression on it. + * + * @param potential to be checked potential {@link java.util.UUID} + * @return true, if the potential {@link java.util.UUID} is indeed an {@link + * java.util.UUID} + */ + public boolean isUUID(final CharSequence potential) { + return PATTERN.matcher(potential).matches(); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorBCPipe.java b/src/main/java/appeng/util/inv/AdaptorBCPipe.java index ed08d23e..de18b1b9 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 appeng.api.config.FuzzyMode; import appeng.integration.IntegrationRegistry; @@ -29,97 +30,93 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Iterator; +public class AdaptorBCPipe extends InventoryAdaptor { + private final IBuildCraftTransport buildCraft; + private final TileEntity i; + private final ForgeDirection d; + public AdaptorBCPipe(final TileEntity s, final ForgeDirection dd) { + this.buildCraft = (IBuildCraftTransport + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + if (this.buildCraft.isPipe(s, dd)) { + this.i = s; + this.d = dd; + return; + } + } + this.i = null; + this.d = null; + } -public class AdaptorBCPipe extends InventoryAdaptor -{ - private final IBuildCraftTransport buildCraft; - private final TileEntity i; - private final ForgeDirection d; + @Override + public ItemStack removeItems( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + return null; + } - public AdaptorBCPipe( final TileEntity s, final ForgeDirection dd ) - { - this.buildCraft = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - if( this.buildCraft.isPipe( s, dd ) ) - { - this.i = s; - this.d = dd; - return; - } - } - this.i = null; - this.d = null; - } + @Override + public ItemStack simulateRemove( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + return null; + } - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return null; - } + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + return null; + } - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return null; - } + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + return null; + } - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - return null; - } + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + if (this.i == null) { + return toBeAdded; + } + if (toBeAdded == null) { + return null; + } + if (toBeAdded.stackSize == 0) { + return null; + } - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - return null; - } + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport) + && this.buildCraft.addItemsToPipe(this.i, toBeAdded, this.d)) { + return null; + } + return toBeAdded; + } - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - if( this.i == null ) - { - return toBeAdded; - } - if( toBeAdded == null ) - { - return null; - } - if( toBeAdded.stackSize == 0 ) - { - return null; - } + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + if (this.i == null) { + return toBeSimulated; + } + return null; + } - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) && this.buildCraft.addItemsToPipe( this.i, toBeAdded, this.d ) ) - { - return null; - } - return toBeAdded; - } + @Override + public boolean containsItems() { + return false; + } - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - if( this.i == null ) - { - return toBeSimulated; - } - return null; - } - - @Override - public boolean containsItems() - { - return false; - } - - @Override - public Iterator iterator() - { - return new NullIterator(); - } + @Override + public Iterator iterator() { + return new NullIterator(); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorIInventory.java b/src/main/java/appeng/util/inv/AdaptorIInventory.java index e9776706..58d8a708 100644 --- a/src/main/java/appeng/util/inv/AdaptorIInventory.java +++ b/src/main/java/appeng/util/inv/AdaptorIInventory.java @@ -18,6 +18,7 @@ package appeng.util.inv; +import java.util.Iterator; import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; @@ -25,340 +26,293 @@ import appeng.util.Platform; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public class AdaptorIInventory extends InventoryAdaptor { + private final IInventory i; + private final boolean wrapperEnabled; + public AdaptorIInventory(final IInventory s) { + this.i = s; + this.wrapperEnabled = s instanceof IInventoryWrapper; + } -public class AdaptorIInventory extends InventoryAdaptor -{ + @Override + public ItemStack + removeItems(int amount, ItemStack filter, final IInventoryDestination destination) { + final int s = this.i.getSizeInventory(); + ItemStack rv = null; - private final IInventory i; - private final boolean wrapperEnabled; + for (int x = 0; x < s && amount > 0; x++) { + final ItemStack is = this.i.getStackInSlot(x); + if (is != null && this.canRemoveStackFromSlot(x, is) + && (filter == null || Platform.isSameItemPrecise(is, filter))) { + int boundAmounts = amount; + if (boundAmounts > is.stackSize) { + boundAmounts = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + boundAmounts = 0; + } - public AdaptorIInventory( final IInventory s ) - { - this.i = s; - this.wrapperEnabled = s instanceof IInventoryWrapper; - } + if (boundAmounts > 0) { + if (rv == null) { + rv = is.copy(); + filter = rv; + rv.stackSize = boundAmounts; + amount -= boundAmounts; + } else { + rv.stackSize += boundAmounts; + amount -= boundAmounts; + } - @Override - public ItemStack removeItems( int amount, ItemStack filter, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - ItemStack rv = null; + if (is.stackSize == boundAmounts) { + this.i.setInventorySlotContents(x, null); + this.i.markDirty(); + } else { + final ItemStack po = is.copy(); + po.stackSize -= boundAmounts; + this.i.setInventorySlotContents(x, po); + this.i.markDirty(); + } + } + } + } - for( int x = 0; x < s && amount > 0; x++ ) - { - final ItemStack is = this.i.getStackInSlot( x ); - if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) - { - int boundAmounts = amount; - if( boundAmounts > is.stackSize ) - { - boundAmounts = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - boundAmounts = 0; - } + // if ( rv != null ) + // i.markDirty(); - if( boundAmounts > 0 ) - { - if( rv == null ) - { - rv = is.copy(); - filter = rv; - rv.stackSize = boundAmounts; - amount -= boundAmounts; - } - else - { - rv.stackSize += boundAmounts; - amount -= boundAmounts; - } + return rv; + } - if( is.stackSize == boundAmounts ) - { - this.i.setInventorySlotContents( x, null ); - this.i.markDirty(); - } - else - { - final ItemStack po = is.copy(); - po.stackSize -= boundAmounts; - this.i.setInventorySlotContents( x, po ); - this.i.markDirty(); - } - } - } - } + @Override + public ItemStack simulateRemove( + int amount, final ItemStack filter, final IInventoryDestination destination + ) { + final int s = this.i.getSizeInventory(); + ItemStack rv = null; - // if ( rv != null ) - // i.markDirty(); + for (int x = 0; x < s && amount > 0; x++) { + final ItemStack is = this.i.getStackInSlot(x); + if (is != null && this.canRemoveStackFromSlot(x, is) + && (filter == null || Platform.isSameItemPrecise(is, filter))) { + int boundAmount = amount; + if (boundAmount > is.stackSize) { + boundAmount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + boundAmount = 0; + } - return rv; - } + if (boundAmount > 0) { + if (rv == null) { + rv = is.copy(); + rv.stackSize = boundAmount; + amount -= boundAmount; + } else { + rv.stackSize += boundAmount; + amount -= boundAmount; + } + } + } + } - @Override - public ItemStack simulateRemove( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - ItemStack rv = null; + return rv; + } - for( int x = 0; x < s && amount > 0; x++ ) - { - final ItemStack is = this.i.getStackInSlot( x ); - if( is != null && this.canRemoveStackFromSlot( x, is ) && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) - { - int boundAmount = amount; - if( boundAmount > is.stackSize ) - { - boundAmount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - boundAmount = 0; - } + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + final int s = this.i.getSizeInventory(); + for (int x = 0; x < s; x++) { + final 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; + } - if( boundAmount > 0 ) - { - if( rv == null ) - { - rv = is.copy(); - rv.stackSize = boundAmount; - amount -= boundAmount; - } - else - { - rv.stackSize += boundAmount; - amount -= boundAmount; - } - } - } - } + ItemStack rv = null; + if (newAmount > 0) { + rv = is.copy(); + rv.stackSize = newAmount; - return rv; - } + if (is.stackSize == rv.stackSize) { + this.i.setInventorySlotContents(x, null); + this.i.markDirty(); + } else { + final ItemStack po = is.copy(); + po.stackSize -= rv.stackSize; + this.i.setInventorySlotContents(x, po); + this.i.markDirty(); + } + } - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - for( int x = 0; x < s; x++ ) - { - final 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; - } + if (rv != null) { + // i.markDirty(); + return rv; + } + } + } + return null; + } - ItemStack rv = null; - if( newAmount > 0 ) - { - rv = is.copy(); - rv.stackSize = newAmount; + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + final int s = this.i.getSizeInventory(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.getStackInSlot(x); - if( is.stackSize == rv.stackSize ) - { - this.i.setInventorySlotContents( x, null ); - this.i.markDirty(); - } - else - { - final ItemStack po = is.copy(); - po.stackSize -= rv.stackSize; - this.i.setInventorySlotContents( x, po ); - this.i.markDirty(); - } - } + 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( rv != null ) - { - // i.markDirty(); - return rv; - } - } - } - return null; - } + if (boundAmount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = boundAmount; + return rv; + } + } + } + return null; + } - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final int s = this.i.getSizeInventory(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.getStackInSlot( x ); + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + return this.addItems(toBeAdded, true); + } - 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; - } + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + return this.addItems(toBeSimulated, false); + } - if( boundAmount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = boundAmount; - return rv; - } - } - } - return null; - } + @Override + public boolean containsItems() { + final 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 addItems( final ItemStack toBeAdded ) - { - return this.addItems( toBeAdded, true ); - } + /** + * Adds an {@link ItemStack} to the adapted {@link IInventory}. + *

+ * It respects the inventories stack limit, which can result in not all items added + * and some left ones are returned. The ItemStack next is required for inventories, + * which will fail on isItemValidForSlot() for stacksizes larger than the limit. + * + * @param itemsToAdd itemStack to add to the inventory + * @param modulate true to modulate, false for simulate + * @return the left itemstack, which could not be added + */ + private ItemStack addItems(final ItemStack itemsToAdd, final boolean modulate) { + if (itemsToAdd == null || itemsToAdd.stackSize == 0) { + return null; + } - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - return this.addItems( toBeSimulated, false ); - } + final ItemStack left = itemsToAdd.copy(); + final int stackLimit = itemsToAdd.getMaxStackSize(); + final int perOperationLimit + = Math.min(this.i.getInventoryStackLimit(), stackLimit); + final int inventorySize = this.i.getSizeInventory(); - @Override - public boolean containsItems() - { - final int s = this.i.getSizeInventory(); - for( int x = 0; x < s; x++ ) - { - if( this.i.getStackInSlot( x ) != null ) - { - return true; - } - } - return false; - } + for (int slot = 0; slot < inventorySize; slot++) { + final ItemStack next = left.copy(); + next.stackSize = Math.min(perOperationLimit, next.stackSize); - /** - * Adds an {@link ItemStack} to the adapted {@link IInventory}. - *

- * It respects the inventories stack limit, which can result in not all items added and some left ones are returned. - * The ItemStack next is required for inventories, which will fail on isItemValidForSlot() for stacksizes larger - * than the limit. - * - * @param itemsToAdd itemStack to add to the inventory - * @param modulate true to modulate, false for simulate - * @return the left itemstack, which could not be added - */ - private ItemStack addItems( final ItemStack itemsToAdd, final boolean modulate ) - { - if( itemsToAdd == null || itemsToAdd.stackSize == 0 ) - { - return null; - } + if (this.i.isItemValidForSlot(slot, next)) { + final ItemStack is = this.i.getStackInSlot(slot); + if (is == null) { + left.stackSize -= next.stackSize; - final ItemStack left = itemsToAdd.copy(); - final int stackLimit = itemsToAdd.getMaxStackSize(); - final int perOperationLimit = Math.min( this.i.getInventoryStackLimit(), stackLimit ); - final int inventorySize = this.i.getSizeInventory(); + if (modulate) { + this.i.setInventorySlotContents(slot, next); + this.i.markDirty(); + } - for( int slot = 0; slot < inventorySize; slot++ ) - { - final ItemStack next = left.copy(); - next.stackSize = Math.min( perOperationLimit, next.stackSize ); + if (left.stackSize <= 0) { + return null; + } + } else if (Platform.isSameItemPrecise(is, left) && is.stackSize < perOperationLimit) { + final int room = perOperationLimit - is.stackSize; + final int used = Math.min(left.stackSize, room); - if( this.i.isItemValidForSlot( slot, next ) ) - { - final ItemStack is = this.i.getStackInSlot( slot ); - if( is == null ) - { - left.stackSize -= next.stackSize; + if (modulate) { + is.stackSize += used; + this.i.setInventorySlotContents(slot, is); + this.i.markDirty(); + } - if( modulate ) - { - this.i.setInventorySlotContents( slot, next ); - this.i.markDirty(); - } + left.stackSize -= used; + if (left.stackSize <= 0) { + return null; + } + } + } + } - if( left.stackSize <= 0 ) - { - return null; - } - } - else if( Platform.isSameItemPrecise( is, left ) && is.stackSize < perOperationLimit ) - { - final int room = perOperationLimit - is.stackSize; - final int used = Math.min( left.stackSize, room ); + return left; + } - if( modulate ) - { - is.stackSize += used; - this.i.setInventorySlotContents( slot, is ); - this.i.markDirty(); - } + private boolean canRemoveStackFromSlot(final int x, final ItemStack is) { + if (this.wrapperEnabled) { + return ((IInventoryWrapper) this.i).canRemoveItemFromSlot(x, is); + } + return true; + } - left.stackSize -= used; - if( left.stackSize <= 0 ) - { - return null; - } - } - } - } + @Override + public Iterator iterator() { + return new InvIterator(); + } - return left; - } + private class InvIterator implements Iterator { + private final ItemSlot is = new ItemSlot(); + private int x = 0; - private boolean canRemoveStackFromSlot( final int x, final ItemStack is ) - { - if( this.wrapperEnabled ) - { - return ( (IInventoryWrapper) this.i ).canRemoveItemFromSlot( x, is ); - } - return true; - } + @Override + public boolean hasNext() { + return this.x < AdaptorIInventory.this.i.getSizeInventory(); + } - @Override - public Iterator iterator() - { - return new InvIterator(); - } + @Override + public ItemSlot next() { + final ItemStack iss = AdaptorIInventory.this.i.getStackInSlot(this.x); - private class InvIterator implements Iterator - { + this.is.setExtractable( + AdaptorIInventory.this.canRemoveStackFromSlot(this.x, iss) + ); + this.is.setItemStack(iss); - private final ItemSlot is = new ItemSlot(); - private int x = 0; + this.is.setSlot(this.x); + this.x++; + return this.is; + } - @Override - public boolean hasNext() - { - return this.x < AdaptorIInventory.this.i.getSizeInventory(); - } - - @Override - public ItemSlot next() - { - final ItemStack iss = AdaptorIInventory.this.i.getStackInSlot( this.x ); - - this.is.setExtractable( AdaptorIInventory.this.canRemoveStackFromSlot( this.x, iss ) ); - this.is.setItemStack( iss ); - - this.is.setSlot( this.x ); - this.x++; - return this.is; - } - - @Override - public void remove() - { - // nothing! - } - } + @Override + public void remove() { + // nothing! + } + } } diff --git a/src/main/java/appeng/util/inv/AdaptorList.java b/src/main/java/appeng/util/inv/AdaptorList.java index 7511e116..2a727d56 100644 --- a/src/main/java/appeng/util/inv/AdaptorList.java +++ b/src/main/java/appeng/util/inv/AdaptorList.java @@ -18,6 +18,8 @@ package appeng.util.inv; +import java.util.Iterator; +import java.util.List; import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; @@ -25,197 +27,172 @@ import appeng.util.Platform; import appeng.util.iterators.StackToSlotIterator; import net.minecraft.item.ItemStack; -import java.util.Iterator; -import java.util.List; +public class AdaptorList extends InventoryAdaptor { + private final List i; + public AdaptorList(final List s) { + this.i = s; + } -public class AdaptorList extends InventoryAdaptor -{ + @Override + public ItemStack removeItems( + int amount, final ItemStack filter, final IInventoryDestination destination + ) { + final int s = this.i.size(); + for (int x = 0; x < s; x++) { + final 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)) { + amount = 0; + } - private final List i; + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + is.stackSize -= amount; - public AdaptorList( final List s ) - { - this.i = s; - } + // remove it.. + if (is.stackSize <= 0) { + this.i.remove(x); + } - @Override - public ItemStack removeItems( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - final int s = this.i.size(); - for( int x = 0; x < s; x++ ) - { - final 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 ) ) - { - amount = 0; - } + return rv; + } + } + } + return null; + } - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - is.stackSize -= amount; + @Override + public ItemStack simulateRemove( + int amount, final ItemStack filter, final IInventoryDestination destination + ) { + for (final ItemStack is : this.i) { + if (is != null + && (filter == null || Platform.isSameItemPrecise(is, filter))) { + if (amount > is.stackSize) { + amount = is.stackSize; + } + if (destination != null && !destination.canInsert(is)) { + amount = 0; + } - // remove it.. - if( is.stackSize <= 0 ) - { - this.i.remove( x ); - } + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + return rv; + } + } + } + return null; + } - return rv; - } - } - } - return null; - } + @Override + public ItemStack removeSimilarItems( + int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + final int s = this.i.size(); + for (int x = 0; x < s; x++) { + final ItemStack is = this.i.get(x); + 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; + } - @Override - public ItemStack simulateRemove( int amount, final ItemStack filter, final IInventoryDestination destination ) - { - for( final ItemStack is : this.i ) - { - if( is != null && ( filter == null || Platform.isSameItemPrecise( is, filter ) ) ) - { - if( amount > is.stackSize ) - { - amount = is.stackSize; - } - if( destination != null && !destination.canInsert( is ) ) - { - amount = 0; - } + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + is.stackSize -= amount; - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - return rv; - } - } - } - return null; - } + // remove it.. + if (is.stackSize <= 0) { + this.i.remove(x); + } - @Override - public ItemStack removeSimilarItems( int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final int s = this.i.size(); - for( int x = 0; x < s; x++ ) - { - final ItemStack is = this.i.get( x ); - 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; - } + return rv; + } + } + } + return null; + } - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - is.stackSize -= amount; + @Override + public ItemStack simulateSimilarRemove( + int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + for (final 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; + } - // remove it.. - if( is.stackSize <= 0 ) - { - this.i.remove( x ); - } + if (amount > 0) { + final ItemStack rv = is.copy(); + rv.stackSize = amount; + return rv; + } + } + } + return null; + } - return rv; - } - } - } - return null; - } + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + if (toBeAdded == null) { + return null; + } + if (toBeAdded.stackSize == 0) { + return null; + } - @Override - public ItemStack simulateSimilarRemove( int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - for( final 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; - } + final ItemStack left = toBeAdded.copy(); - if( amount > 0 ) - { - final ItemStack rv = is.copy(); - rv.stackSize = amount; - return rv; - } - } - } - return null; - } + for (final ItemStack is : this.i) { + if (Platform.isSameItem(is, left)) { + is.stackSize += left.stackSize; + return null; + } + } - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - if( toBeAdded == null ) - { - return null; - } - if( toBeAdded.stackSize == 0 ) - { - return null; - } + this.i.add(left); + return null; + } - final ItemStack left = toBeAdded.copy(); + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + return null; + } - for( final ItemStack is : this.i ) - { - if( Platform.isSameItem( is, left ) ) - { - is.stackSize += left.stackSize; - return null; - } - } + @Override + public boolean containsItems() { + for (final ItemStack is : this.i) { + if (is != null) { + return true; + } + } + return false; + } - this.i.add( left ); - return null; - } - - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - return null; - } - - @Override - public boolean containsItems() - { - for( final ItemStack is : this.i ) - { - if( is != null ) - { - return true; - } - } - return false; - } - - @Override - public Iterator iterator() - { - return new StackToSlotIterator( this.i.iterator() ); - } + @Override + public Iterator iterator() { + 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 fee2366c..121f8431 100644 --- a/src/main/java/appeng/util/inv/AdaptorPlayerHand.java +++ b/src/main/java/appeng/util/inv/AdaptorPlayerHand.java @@ -18,6 +18,7 @@ package appeng.util.inv; +import java.util.Iterator; import appeng.api.config.FuzzyMode; import appeng.util.InventoryAdaptor; @@ -26,211 +27,183 @@ import appeng.util.iterators.NullIterator; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -import java.util.Iterator; - - /* * Lets you do simply tests with the players cursor, without messing with the specifics. */ -public class AdaptorPlayerHand extends InventoryAdaptor -{ +public class AdaptorPlayerHand extends InventoryAdaptor { + private final EntityPlayer player; - private final EntityPlayer player; + public AdaptorPlayerHand(final EntityPlayer player) { + this.player = player; + } - public AdaptorPlayerHand( final EntityPlayer player ) - { - this.player = player; - } + @Override + public ItemStack removeItems( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } + if (filter == null || Platform.isSameItemPrecise(filter, hand)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + hand.stackSize -= amount; + if (hand.stackSize <= 0) { + this.player.inventory.setItemStack(null); + } + return result; + } - if( filter == null || Platform.isSameItemPrecise( filter, hand ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - hand.stackSize -= amount; - if( hand.stackSize <= 0 ) - { - this.player.inventory.setItemStack( null ); - } - return result; - } + return null; + } - return null; - } + @Override + public ItemStack simulateRemove( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { + if (filter == null || Platform.isSameItemPrecise(filter, hand)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + return result; + } - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } + return null; + } - if( filter == null || Platform.isSameItemPrecise( filter, hand ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - return result; - } + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } - return null; - } + if (filter == null || Platform.isSameItemFuzzy(filter, hand, fuzzyMode)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + hand.stackSize -= amount; + if (hand.stackSize <= 0) { + this.player.inventory.setItemStack(null); + } + return result; + } - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } + return null; + } - if( filter == null || Platform.isSameItemFuzzy( filter, hand, fuzzyMode ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - hand.stackSize -= amount; - if( hand.stackSize <= 0 ) - { - this.player.inventory.setItemStack( null ); - } - return result; - } + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (hand == null) { + return null; + } - return null; - } + if (filter == null || Platform.isSameItemFuzzy(filter, hand, fuzzyMode)) { + final ItemStack result = hand.copy(); + result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; + return result; + } - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { + return null; + } - final ItemStack hand = this.player.inventory.getItemStack(); - if( hand == null ) - { - return null; - } + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + if (toBeAdded == null) { + return null; + } + if (toBeAdded.stackSize == 0) { + return null; + } + if (this.player == null) { + return toBeAdded; + } + if (this.player.inventory == null) { + return toBeAdded; + } - if( filter == null || Platform.isSameItemFuzzy( filter, hand, fuzzyMode ) ) - { - final ItemStack result = hand.copy(); - result.stackSize = hand.stackSize > amount ? amount : hand.stackSize; - return result; - } + final ItemStack hand = this.player.inventory.getItemStack(); - return null; - } + if (hand != null && !Platform.isSameItemPrecise(toBeAdded, hand)) { + return toBeAdded; + } - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { + int original = 0; + ItemStack newHand = null; + if (hand == null) { + newHand = toBeAdded.copy(); + } else { + newHand = hand; + original = hand.stackSize; + newHand.stackSize += toBeAdded.stackSize; + } - if( toBeAdded == null ) - { - return null; - } - if( toBeAdded.stackSize == 0 ) - { - return null; - } - if( this.player == null ) - { - return toBeAdded; - } - if( this.player.inventory == null ) - { - return toBeAdded; - } + if (newHand.stackSize > newHand.getMaxStackSize()) { + newHand.stackSize = newHand.getMaxStackSize(); + final ItemStack B = toBeAdded.copy(); + B.stackSize -= newHand.stackSize - original; + this.player.inventory.setItemStack(newHand); + return B; + } - final ItemStack hand = this.player.inventory.getItemStack(); + this.player.inventory.setItemStack(newHand); + return null; + } - if( hand != null && !Platform.isSameItemPrecise( toBeAdded, hand ) ) - { - return toBeAdded; - } + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + final ItemStack hand = this.player.inventory.getItemStack(); + if (toBeSimulated == null) { + return null; + } - int original = 0; - ItemStack newHand = null; - if( hand == null ) - { - newHand = toBeAdded.copy(); - } - else - { - newHand = hand; - original = hand.stackSize; - newHand.stackSize += toBeAdded.stackSize; - } + if (hand != null && !Platform.isSameItem(toBeSimulated, hand)) { + return toBeSimulated; + } - if( newHand.stackSize > newHand.getMaxStackSize() ) - { - newHand.stackSize = newHand.getMaxStackSize(); - final ItemStack B = toBeAdded.copy(); - B.stackSize -= newHand.stackSize - original; - this.player.inventory.setItemStack( newHand ); - return B; - } + int original = 0; + ItemStack newHand = null; + if (hand == null) { + newHand = toBeSimulated.copy(); + } else { + newHand = hand.copy(); + original = hand.stackSize; + newHand.stackSize += toBeSimulated.stackSize; + } - this.player.inventory.setItemStack( newHand ); - return null; - } + if (newHand.stackSize > newHand.getMaxStackSize()) { + newHand.stackSize = newHand.getMaxStackSize(); + final ItemStack B = toBeSimulated.copy(); + B.stackSize -= newHand.stackSize - original; + return B; + } - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - final ItemStack hand = this.player.inventory.getItemStack(); - if( toBeSimulated == null ) - { - return null; - } + return null; + } - if( hand != null && !Platform.isSameItem( toBeSimulated, hand ) ) - { - return toBeSimulated; - } + @Override + public boolean containsItems() { + return this.player.inventory.getItemStack() != null; + } - int original = 0; - ItemStack newHand = null; - if( hand == null ) - { - newHand = toBeSimulated.copy(); - } - else - { - newHand = hand.copy(); - original = hand.stackSize; - newHand.stackSize += toBeSimulated.stackSize; - } - - if( newHand.stackSize > newHand.getMaxStackSize() ) - { - newHand.stackSize = newHand.getMaxStackSize(); - final ItemStack B = toBeSimulated.copy(); - B.stackSize -= newHand.stackSize - original; - return B; - } - - return null; - } - - @Override - public boolean containsItems() - { - return this.player.inventory.getItemStack() != null; - } - - @Override - public Iterator iterator() - { - return new NullIterator(); - } + @Override + public Iterator iterator() { + return new NullIterator(); + } } diff --git a/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java b/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java index 57144fd5..97f267ab 100644 --- a/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java +++ b/src/main/java/appeng/util/inv/AdaptorPlayerInventory.java @@ -18,107 +18,88 @@ 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; -public class AdaptorPlayerInventory implements IInventory -{ + public AdaptorPlayerInventory(final IInventory playerInv, final boolean swap) { + if (swap) { + this.src = new WrapperChainedInventory( + new WrapperInventoryRange(playerInv, 9, this.size - 9, false), + new WrapperInventoryRange(playerInv, 0, 9, false) + ); + } else { + this.src = playerInv; + } + } - private final IInventory src; - private final int min = 0; - private final int size = 36; + @Override + public int getSizeInventory() { + return this.size; + } - public AdaptorPlayerInventory( final IInventory playerInv, final boolean swap ) - { + @Override + public ItemStack getStackInSlot(final int var1) { + return this.src.getStackInSlot(var1 + this.min); + } - 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 + public ItemStack decrStackSize(final int var1, final int var2) { + return this.src.decrStackSize(this.min + var1, var2); + } - @Override - public int getSizeInventory() - { - return this.size; - } + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return this.src.getStackInSlotOnClosing(this.min + var1); + } - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return this.src.getStackInSlot( var1 + this.min ); - } + @Override + public void setInventorySlotContents(final int var1, final ItemStack var2) { + this.src.setInventorySlotContents(var1 + this.min, var2); + } - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - return this.src.decrStackSize( this.min + var1, var2 ); - } + @Override + public String getInventoryName() { + return this.src.getInventoryName(); + } - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return this.src.getStackInSlotOnClosing( this.min + var1 ); - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public void setInventorySlotContents( final int var1, final ItemStack var2 ) - { - this.src.setInventorySlotContents( var1 + this.min, var2 ); - } + @Override + public int getInventoryStackLimit() { + return this.src.getInventoryStackLimit(); + } - @Override - public String getInventoryName() - { - return this.src.getInventoryName(); - } + @Override + public void markDirty() { + this.src.markDirty(); + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return this.src.isUseableByPlayer(var1); + } - @Override - public int getInventoryStackLimit() - { - return this.src.getInventoryStackLimit(); - } + @Override + public void openInventory() { + this.src.openInventory(); + } - @Override - public void markDirty() - { - this.src.markDirty(); - } + @Override + public void closeInventory() { + this.src.closeInventory(); + } - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return this.src.isUseableByPlayer( var1 ); - } - - @Override - public void openInventory() - { - this.src.openInventory(); - } - - @Override - public void closeInventory() - { - this.src.closeInventory(); - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.src.isItemValidForSlot( i, itemstack ); - } + @Override + public boolean isItemValidForSlot(final int i, final 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 61a3cf8b..f6c00a69 100644 --- a/src/main/java/appeng/util/inv/IInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IInventoryDestination.java @@ -18,12 +18,8 @@ package appeng.util.inv; - import net.minecraft.item.ItemStack; - -public interface IInventoryDestination -{ - - boolean canInsert( ItemStack stack ); +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 eedab2a7..6a07b472 100644 --- a/src/main/java/appeng/util/inv/IInventoryWrapper.java +++ b/src/main/java/appeng/util/inv/IInventoryWrapper.java @@ -18,12 +18,8 @@ package appeng.util.inv; - import net.minecraft.item.ItemStack; - -public interface IInventoryWrapper -{ - - boolean canRemoveItemFromSlot( int x, ItemStack is ); +public interface IInventoryWrapper { + 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 b58216a4..13883bc3 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptor.java +++ b/src/main/java/appeng/util/inv/IMEAdaptor.java @@ -18,6 +18,7 @@ package appeng.util.inv; +import java.util.Iterator; import appeng.api.AEApi; import appeng.api.config.Actionable; @@ -31,167 +32,166 @@ import appeng.util.item.AEItemStack; import com.google.common.collect.ImmutableList; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public class IMEAdaptor extends InventoryAdaptor { + private final IMEInventory target; + private final BaseActionSource src; + private int maxSlots = 0; + public IMEAdaptor( + final IMEInventory input, final BaseActionSource src + ) { + this.target = input; + this.src = src; + } -public class IMEAdaptor extends InventoryAdaptor -{ + @Override + public Iterator iterator() { + return new IMEAdaptorIterator(this, this.getList()); + } - private final IMEInventory target; - private final BaseActionSource src; - private int maxSlots = 0; + private IItemList getList() { + return this.target.getAvailableItems(AEApi.instance().storage().createItemList()); + } - public IMEAdaptor( final IMEInventory input, final BaseActionSource src ) - { - this.target = input; - this.src = src; - } + @Override + public ItemStack removeItems( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + return this.doRemoveItems(amount, filter, destination, Actionable.MODULATE); + } - @Override - public Iterator iterator() - { - return new IMEAdaptorIterator( this, this.getList() ); - } + private ItemStack doRemoveItems( + final int amount, + final ItemStack filter, + final IInventoryDestination destination, + final Actionable type + ) { + IAEItemStack req = null; - private IItemList getList() - { - return this.target.getAvailableItems( AEApi.instance().storage().createItemList() ); - } + if (filter == null) { + final IItemList list = this.getList(); + if (!list.isEmpty()) { + req = list.getFirstItem(); + } + } else { + req = AEItemStack.create(filter); + } - @Override - public ItemStack removeItems( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return this.doRemoveItems( amount, filter, destination, Actionable.MODULATE ); - } + IAEItemStack out = null; - private ItemStack doRemoveItems( final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type ) - { - IAEItemStack req = null; + if (req != null) { + req.setStackSize(amount); + out = this.target.extractItems(req, type, this.src); + } - if( filter == null ) - { - final IItemList list = this.getList(); - if( !list.isEmpty() ) - { - req = list.getFirstItem(); - } - } - else - { - req = AEItemStack.create( filter ); - } + if (out != null) { + return out.getItemStack(); + } - IAEItemStack out = null; + return null; + } - if( req != null ) - { - req.setStackSize( amount ); - out = this.target.extractItems( req, type, this.src ); - } + @Override + public ItemStack simulateRemove( + final int amount, final ItemStack filter, final IInventoryDestination destination + ) { + return this.doRemoveItems(amount, filter, destination, Actionable.SIMULATE); + } - if( out != null ) - { - return out.getItemStack(); - } + @Override + public ItemStack removeSimilarItems( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + if (filter == null) { + return this.doRemoveItems(amount, null, destination, Actionable.MODULATE); + } + return this.doRemoveItemsFuzzy( + amount, filter, destination, Actionable.MODULATE, fuzzyMode + ); + } - return null; - } + private ItemStack doRemoveItemsFuzzy( + final int amount, + final ItemStack filter, + final IInventoryDestination destination, + final Actionable type, + final FuzzyMode fuzzyMode + ) { + final IAEItemStack reqFilter = AEItemStack.create(filter); + if (reqFilter == null) { + return null; + } - @Override - public ItemStack simulateRemove( final int amount, final ItemStack filter, final IInventoryDestination destination ) - { - return this.doRemoveItems( amount, filter, destination, Actionable.SIMULATE ); - } + IAEItemStack out = null; - @Override - public ItemStack removeSimilarItems( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - if( filter == null ) - { - return this.doRemoveItems( amount, null, destination, Actionable.MODULATE ); - } - return this.doRemoveItemsFuzzy( amount, filter, destination, Actionable.MODULATE, fuzzyMode ); - } + for (final IAEItemStack req : + ImmutableList.copyOf(this.getList().findFuzzy(reqFilter, fuzzyMode))) { + if (req != null) { + req.setStackSize(amount); + out = this.target.extractItems(req, type, this.src); + if (out != null) { + return out.getItemStack(); + } + } + } - private ItemStack doRemoveItemsFuzzy( final int amount, final ItemStack filter, final IInventoryDestination destination, final Actionable type, final FuzzyMode fuzzyMode ) - { - final IAEItemStack reqFilter = AEItemStack.create( filter ); - if( reqFilter == null ) - { - return null; - } + return null; + } - IAEItemStack out = null; + @Override + public ItemStack simulateSimilarRemove( + final int amount, + final ItemStack filter, + final FuzzyMode fuzzyMode, + final IInventoryDestination destination + ) { + if (filter == null) { + return this.doRemoveItems(amount, null, destination, Actionable.SIMULATE); + } + return this.doRemoveItemsFuzzy( + amount, filter, destination, Actionable.SIMULATE, fuzzyMode + ); + } - for( final IAEItemStack req : ImmutableList.copyOf( this.getList().findFuzzy( reqFilter, fuzzyMode ) ) ) - { - if( req != null ) - { - req.setStackSize( amount ); - out = this.target.extractItems( req, type, this.src ); - if( out != null ) - { - return out.getItemStack(); - } - } - } + @Override + public ItemStack addItems(final ItemStack toBeAdded) { + final IAEItemStack in = AEItemStack.create(toBeAdded); + if (in != null) { + final IAEItemStack out + = this.target.injectItems(in, Actionable.MODULATE, this.src); + if (out != null) { + return out.getItemStack(); + } + } + return null; + } - return null; - } + @Override + public ItemStack simulateAdd(final ItemStack toBeSimulated) { + final IAEItemStack in = AEItemStack.create(toBeSimulated); + if (in != null) { + final IAEItemStack out + = this.target.injectItems(in, Actionable.SIMULATE, this.src); + if (out != null) { + return out.getItemStack(); + } + } + return null; + } - @Override - public ItemStack simulateSimilarRemove( final int amount, final ItemStack filter, final FuzzyMode fuzzyMode, final IInventoryDestination destination ) - { - if( filter == null ) - { - return this.doRemoveItems( amount, null, destination, Actionable.SIMULATE ); - } - return this.doRemoveItemsFuzzy( amount, filter, destination, Actionable.SIMULATE, fuzzyMode ); - } + @Override + public boolean containsItems() { + return !this.getList().isEmpty(); + } - @Override - public ItemStack addItems( final ItemStack toBeAdded ) - { - final IAEItemStack in = AEItemStack.create( toBeAdded ); - if( in != null ) - { - final IAEItemStack out = this.target.injectItems( in, Actionable.MODULATE, this.src ); - if( out != null ) - { - return out.getItemStack(); - } - } - return null; - } + int getMaxSlots() { + return this.maxSlots; + } - @Override - public ItemStack simulateAdd( final ItemStack toBeSimulated ) - { - final IAEItemStack in = AEItemStack.create( toBeSimulated ); - if( in != null ) - { - final IAEItemStack out = this.target.injectItems( in, Actionable.SIMULATE, this.src ); - if( out != null ) - { - return out.getItemStack(); - } - } - return null; - } - - @Override - public boolean containsItems() - { - return !this.getList().isEmpty(); - } - - int getMaxSlots() - { - return this.maxSlots; - } - - void setMaxSlots( final int maxSlots ) - { - this.maxSlots = maxSlots; - } + void setMaxSlots(final int maxSlots) { + this.maxSlots = maxSlots; + } } diff --git a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java index 2e422002..201a8df9 100644 --- a/src/main/java/appeng/util/inv/IMEAdaptorIterator.java +++ b/src/main/java/appeng/util/inv/IMEAdaptorIterator.java @@ -18,63 +18,56 @@ package appeng.util.inv; +import java.util.Iterator; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; -import java.util.Iterator; +public final class IMEAdaptorIterator implements Iterator { + private final Iterator stack; + private final ItemSlot slot = new ItemSlot(); + private final IMEAdaptor parent; + private final int containerSize; + private int offset = 0; + private boolean hasNext; -public final class IMEAdaptorIterator implements Iterator -{ - private final Iterator stack; - private final ItemSlot slot = new ItemSlot(); - private final IMEAdaptor parent; - private final int containerSize; + public IMEAdaptorIterator( + final IMEAdaptor parent, final IItemList availableItems + ) { + this.stack = availableItems.iterator(); + this.containerSize = parent.getMaxSlots(); + this.parent = parent; + } - private int offset = 0; - private boolean hasNext; + @Override + public boolean hasNext() { + this.hasNext = this.stack.hasNext(); + return this.offset < this.containerSize || this.hasNext; + } - public IMEAdaptorIterator( final IMEAdaptor parent, final IItemList availableItems ) - { - this.stack = availableItems.iterator(); - this.containerSize = parent.getMaxSlots(); - this.parent = parent; - } + @Override + public ItemSlot next() { + this.slot.setSlot(this.offset); + this.offset++; + this.slot.setExtractable(true); - @Override - public boolean hasNext() - { - this.hasNext = this.stack.hasNext(); - return this.offset < this.containerSize || this.hasNext; - } + if (this.parent.getMaxSlots() < this.offset) { + this.parent.setMaxSlots(this.offset); + } - @Override - public ItemSlot next() - { - this.slot.setSlot( this.offset ); - this.offset++; - this.slot.setExtractable( true ); + if (this.hasNext) { + final IAEItemStack item = this.stack.next(); + this.slot.setAEItemStack(item); + return this.slot; + } - if( this.parent.getMaxSlots() < this.offset ) - { - this.parent.setMaxSlots( this.offset ); - } + this.slot.setItemStack(null); + return this.slot; + } - if( this.hasNext ) - { - final IAEItemStack item = this.stack.next(); - this.slot.setAEItemStack( item ); - return this.slot; - } - - this.slot.setItemStack( null ); - return this.slot; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/inv/IMEInventoryDestination.java b/src/main/java/appeng/util/inv/IMEInventoryDestination.java index 112cc491..107b6eb7 100644 --- a/src/main/java/appeng/util/inv/IMEInventoryDestination.java +++ b/src/main/java/appeng/util/inv/IMEInventoryDestination.java @@ -18,39 +18,31 @@ package appeng.util.inv; - import appeng.api.config.Actionable; import appeng.api.storage.IMEInventory; import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; import net.minecraft.item.ItemStack; +public class IMEInventoryDestination implements IInventoryDestination { + private final IMEInventory me; -public class IMEInventoryDestination implements IInventoryDestination -{ + public IMEInventoryDestination(final IMEInventory o) { + this.me = o; + } - private final IMEInventory me; + @Override + public boolean canInsert(final ItemStack stack) { + if (stack == null) { + return false; + } - public IMEInventoryDestination( final IMEInventory o ) - { - this.me = o; - } + final IAEItemStack failed + = this.me.injectItems(AEItemStack.create(stack), Actionable.SIMULATE, null); - @Override - public boolean canInsert( final ItemStack stack ) - { - - if( stack == null ) - { - return false; - } - - final IAEItemStack failed = this.me.injectItems( AEItemStack.create( stack ), Actionable.SIMULATE, null ); - - if( failed == null ) - { - return true; - } - return failed.getStackSize() != stack.stackSize; - } + 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 5de6f6ee..f9c37578 100644 --- a/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java +++ b/src/main/java/appeng/util/inv/ItemListIgnoreCrafting.java @@ -18,94 +18,77 @@ package appeng.util.inv; +import java.util.Collection; +import java.util.Iterator; import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; -import java.util.Collection; -import java.util.Iterator; +public class ItemListIgnoreCrafting implements IItemList { + private final IItemList target; + public ItemListIgnoreCrafting(final IItemList cla) { + this.target = cla; + } -public class ItemListIgnoreCrafting implements IItemList -{ + @Override + public void add(T option) { + if (option != null && option.isCraftable()) { + option = (T) option.copy(); + option.setCraftable(false); + } - private final IItemList target; + this.target.add(option); + } - public ItemListIgnoreCrafting( final IItemList cla ) - { - this.target = cla; - } + @Override + public T findPrecise(final T i) { + return this.target.findPrecise(i); + } - @Override - public void add( T option ) - { - if( option != null && option.isCraftable() ) - { - option = (T) option.copy(); - option.setCraftable( false ); - } + @Override + public Collection findFuzzy(final T input, final FuzzyMode fuzzy) { + return this.target.findFuzzy(input, fuzzy); + } - this.target.add( option ); - } + @Override + public boolean isEmpty() { + return this.target.isEmpty(); + } - @Override - public T findPrecise( final T i ) - { - return this.target.findPrecise( i ); - } + @Override + public void addStorage(final T option) { + this.target.addStorage(option); + } - @Override - public Collection findFuzzy( final T input, final FuzzyMode fuzzy ) - { - return this.target.findFuzzy( input, fuzzy ); - } + @Override + public void addCrafting(final T option) { + // nothing. + } - @Override - public boolean isEmpty() - { - return this.target.isEmpty(); - } + @Override + public void addRequestable(final T option) { + this.target.addRequestable(option); + } - @Override - public void addStorage( final T option ) - { - this.target.addStorage( option ); - } + @Override + public T getFirstItem() { + return this.target.getFirstItem(); + } - @Override - public void addCrafting( final T option ) - { - // nothing. - } + @Override + public int size() { + return this.target.size(); + } - @Override - public void addRequestable( final T option ) - { - this.target.addRequestable( option ); - } + @Override + public Iterator iterator() { + return this.target.iterator(); + } - @Override - public T getFirstItem() - { - return this.target.getFirstItem(); - } - - @Override - public int size() - { - return this.target.size(); - } - - @Override - public Iterator iterator() - { - return this.target.iterator(); - } - - @Override - public void resetStatus() - { - this.target.resetStatus(); - } + @Override + public void resetStatus() { + this.target.resetStatus(); + } } diff --git a/src/main/java/appeng/util/inv/ItemSlot.java b/src/main/java/appeng/util/inv/ItemSlot.java index 00095927..27e9ad58 100644 --- a/src/main/java/appeng/util/inv/ItemSlot.java +++ b/src/main/java/appeng/util/inv/ItemSlot.java @@ -18,60 +18,56 @@ package appeng.util.inv; - import appeng.api.storage.data.IAEItemStack; import appeng.util.item.AEItemStack; import net.minecraft.item.ItemStack; +public class ItemSlot { + private int slot; + private boolean isExtractable; + // one or the other.. + private IAEItemStack aeItemStack; + private ItemStack itemStack; -public class ItemSlot -{ + public ItemStack getItemStack() { + return this.itemStack == null + ? (this.aeItemStack == null + ? null + : (this.itemStack = this.aeItemStack.getItemStack())) + : this.itemStack; + } - private int slot; - private boolean isExtractable; - // one or the other.. - private IAEItemStack aeItemStack; - private ItemStack itemStack; + public void setItemStack(final ItemStack is) { + this.aeItemStack = null; + this.itemStack = is; + } - 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; + } - public void setItemStack( final ItemStack is ) - { - this.aeItemStack = null; - this.itemStack = is; - } + void setAEItemStack(final IAEItemStack is) { + this.aeItemStack = is; + this.itemStack = null; + } - public IAEItemStack getAEItemStack() - { - return this.aeItemStack == null ? ( this.itemStack == null ? null : ( this.aeItemStack = AEItemStack.create( this.itemStack ) ) ) : this.aeItemStack; - } + public boolean isExtractable() { + return this.isExtractable; + } - void setAEItemStack( final IAEItemStack is ) - { - this.aeItemStack = is; - this.itemStack = null; - } + void setExtractable(final boolean isExtractable) { + this.isExtractable = isExtractable; + } - public boolean isExtractable() - { - return this.isExtractable; - } + public int getSlot() { + return this.slot; + } - void setExtractable( final boolean isExtractable ) - { - this.isExtractable = isExtractable; - } - - public int getSlot() - { - return this.slot; - } - - public void setSlot( final int slot ) - { - this.slot = slot; - } + public void setSlot(final int slot) { + this.slot = slot; + } } diff --git a/src/main/java/appeng/util/inv/WrapperBCPipe.java b/src/main/java/appeng/util/inv/WrapperBCPipe.java index 2c27d1ab..21a39128 100644 --- a/src/main/java/appeng/util/inv/WrapperBCPipe.java +++ b/src/main/java/appeng/util/inv/WrapperBCPipe.java @@ -18,7 +18,6 @@ package appeng.util.inv; - import appeng.integration.IntegrationRegistry; import appeng.integration.IntegrationType; import appeng.integration.abstraction.IBuildCraftTransport; @@ -28,99 +27,76 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.common.util.ForgeDirection; +public class WrapperBCPipe implements IInventory { + private final IBuildCraftTransport bc; + private final TileEntity ad; + private final ForgeDirection dir; -public class WrapperBCPipe implements IInventory -{ + public WrapperBCPipe(final TileEntity te, final ForgeDirection d) { + this.bc = (IBuildCraftTransport + ) IntegrationRegistry.INSTANCE.getInstance(IntegrationType.BuildCraftTransport); + this.ad = te; + this.dir = d; + } - private final IBuildCraftTransport bc; - private final TileEntity ad; - private final ForgeDirection dir; + @Override + public int getSizeInventory() { + return 1; + } - public WrapperBCPipe( final TileEntity te, final ForgeDirection d ) - { - this.bc = (IBuildCraftTransport) IntegrationRegistry.INSTANCE.getInstance( IntegrationType.BuildCraftTransport ); - this.ad = te; - this.dir = d; - } + @Override + public ItemStack getStackInSlot(final int i) { + return null; + } - @Override - public int getSizeInventory() - { - return 1; - } + @Override + public ItemStack decrStackSize(final int i, final int j) { + return null; + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return null; - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return null; + } - @Override - public ItemStack decrStackSize( final int i, final int j ) - { - return null; - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + if (IntegrationRegistry.INSTANCE.isEnabled(IntegrationType.BuildCraftTransport)) { + this.bc.addItemsToPipe(this.ad, itemstack, this.dir); + } + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return null; - } + @Override + public String getInventoryName() { + return "BC Pipe Wrapper"; + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - if( IntegrationRegistry.INSTANCE.isEnabled( IntegrationType.BuildCraftTransport ) ) - { - this.bc.addItemsToPipe( this.ad, itemstack, this.dir ); - } - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public String getInventoryName() - { - return "BC Pipe Wrapper"; - } + @Override + public int getInventoryStackLimit() { + return 64; + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public void markDirty() {} - @Override - public int getInventoryStackLimit() - { - return 64; - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return false; + } - @Override - public void markDirty() - { + @Override + public void openInventory() {} - } + @Override + public void closeInventory() {} - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return false; - } - - @Override - public void openInventory() - { - - } - - @Override - public void closeInventory() - { - - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return this.bc.canAddItemsToPipe( this.ad, itemstack, this.dir ); - } + @Override + public boolean isItemValidForSlot(final int i, final 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 6e76bf0b..0ec6b783 100644 --- a/src/main/java/appeng/util/inv/WrapperChainedInventory.java +++ b/src/main/java/appeng/util/inv/WrapperChainedInventory.java @@ -18,219 +18,177 @@ package appeng.util.inv; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import com.google.common.collect.ImmutableList; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +public class WrapperChainedInventory implements IInventory { + private int fullSize = 0; + private List l; + private Map offsets; + public WrapperChainedInventory(final IInventory... inventories) { + this.setInventory(inventories); + } -public class WrapperChainedInventory implements IInventory -{ + private void setInventory(final IInventory... a) { + this.l = ImmutableList.copyOf(a); + this.calculateSizes(); + } - private int fullSize = 0; - private List l; - private Map offsets; + private void calculateSizes() { + this.offsets = new HashMap(); - public WrapperChainedInventory( final IInventory... inventories ) - { - this.setInventory( inventories ); - } + int offset = 0; + for (final IInventory in : this.l) { + final InvOffset io = new InvOffset(); + io.offset = offset; + io.size = in.getSizeInventory(); + io.i = in; - private void setInventory( final IInventory... a ) - { - this.l = ImmutableList.copyOf( a ); - this.calculateSizes(); - } + for (int y = 0; y < io.size; y++) { + this.offsets.put(y + io.offset, io); + } - private void calculateSizes() - { - this.offsets = new HashMap(); + offset += io.size; + } - int offset = 0; - for( final IInventory in : this.l ) - { - final InvOffset io = new InvOffset(); - io.offset = offset; - io.size = in.getSizeInventory(); - io.i = in; + this.fullSize = offset; + } - for( int y = 0; y < io.size; y++ ) - { - this.offsets.put( y + io.offset, io ); - } + public WrapperChainedInventory(final List inventories) { + this.setInventory(inventories); + } - offset += io.size; - } + private void setInventory(final List a) { + this.l = a; + this.calculateSizes(); + } - this.fullSize = offset; - } + public void cycleOrder() { + if (this.l.size() > 1) { + final 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 WrapperChainedInventory( final List inventories ) - { - this.setInventory( inventories ); - } + public IInventory getInv(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i; + } + return null; + } - private void setInventory( final List a ) - { - this.l = a; - this.calculateSizes(); - } + public int getInvSlot(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return idx - io.offset; + } + return 0; + } - public void cycleOrder() - { - if( this.l.size() > 1 ) - { - final 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 ); - } - } + @Override + public int getSizeInventory() { + return this.fullSize; + } - public IInventory getInv( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i; - } - return null; - } + @Override + public ItemStack getStackInSlot(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.getStackInSlot(idx - io.offset); + } + return null; + } - public int getInvSlot( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return idx - io.offset; - } - return 0; - } + @Override + public ItemStack decrStackSize(final int idx, final int var2) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.decrStackSize(idx - io.offset, var2); + } + return null; + } - @Override - public int getSizeInventory() - { - return this.fullSize; - } + @Override + public ItemStack getStackInSlotOnClosing(final int idx) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.getStackInSlotOnClosing(idx - io.offset); + } + return null; + } - @Override - public ItemStack getStackInSlot( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.getStackInSlot( idx - io.offset ); - } - return null; - } + @Override + public void setInventorySlotContents(final int idx, final ItemStack var2) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + io.i.setInventorySlotContents(idx - io.offset, var2); + } + } - @Override - public ItemStack decrStackSize( final int idx, final int var2 ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.decrStackSize( idx - io.offset, var2 ); - } - return null; - } + @Override + public String getInventoryName() { + return "ChainedInv"; + } - @Override - public ItemStack getStackInSlotOnClosing( final int idx ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.getStackInSlotOnClosing( idx - io.offset ); - } - return null; - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public void setInventorySlotContents( final int idx, final ItemStack var2 ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - io.i.setInventorySlotContents( idx - io.offset, var2 ); - } - } + @Override + public int getInventoryStackLimit() { + int smallest = 64; - @Override - public String getInventoryName() - { - return "ChainedInv"; - } + for (final IInventory i : this.l) { + smallest = Math.min(smallest, i.getInventoryStackLimit()); + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + return smallest; + } - @Override - public int getInventoryStackLimit() - { - int smallest = 64; + @Override + public void markDirty() { + for (final IInventory i : this.l) { + i.markDirty(); + } + } - for( final IInventory i : this.l ) - { - smallest = Math.min( smallest, i.getInventoryStackLimit() ); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return false; + } - return smallest; - } + @Override + public void openInventory() {} - @Override - public void markDirty() - { - for( final IInventory i : this.l ) - { - i.markDirty(); - } - } + @Override + public void closeInventory() {} - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return false; - } + @Override + public boolean isItemValidForSlot(final int idx, final ItemStack itemstack) { + final InvOffset io = this.offsets.get(idx); + if (io != null) { + return io.i.isItemValidForSlot(idx - io.offset, itemstack); + } + return false; + } - @Override - public void openInventory() - { - } - - @Override - public void closeInventory() - { - } - - @Override - public boolean isItemValidForSlot( final int idx, final ItemStack itemstack ) - { - final InvOffset io = this.offsets.get( idx ); - if( io != null ) - { - return io.i.isItemValidForSlot( idx - io.offset, itemstack ); - } - return false; - } - - private static class InvOffset - { - - private int offset; - private int size; - private IInventory i; - } + private static class InvOffset { + private int offset; + private int size; + private IInventory i; + } } diff --git a/src/main/java/appeng/util/inv/WrapperInvSlot.java b/src/main/java/appeng/util/inv/WrapperInvSlot.java index 14c3f21b..d46a2dd5 100644 --- a/src/main/java/appeng/util/inv/WrapperInvSlot.java +++ b/src/main/java/appeng/util/inv/WrapperInvSlot.java @@ -18,120 +18,98 @@ 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 class WrapperInvSlot -{ + public WrapperInvSlot(final IInventory inv) { + this.inv = inv; + } - private final IInventory inv; + public IInventory getWrapper(final int slot) { + return new InternalInterfaceWrapper(this.inv, slot); + } - public WrapperInvSlot( final IInventory inv ) - { - this.inv = inv; - } + protected boolean isItemValid(final ItemStack itemstack) { + return true; + } - public IInventory getWrapper( final int slot ) - { - return new InternalInterfaceWrapper( this.inv, slot ); - } + private class InternalInterfaceWrapper implements IInventory { + private final IInventory inv; + private final int slot; - protected boolean isItemValid( final ItemStack itemstack ) - { - return true; - } + public InternalInterfaceWrapper(final IInventory target, final int slot) { + this.inv = target; + this.slot = slot; + } - private class InternalInterfaceWrapper implements IInventory - { + @Override + public int getSizeInventory() { + return 1; + } - private final IInventory inv; - private final int slot; + @Override + public ItemStack getStackInSlot(final int i) { + return this.inv.getStackInSlot(this.slot); + } - public InternalInterfaceWrapper( final IInventory target, final int slot ) - { - this.inv = target; - this.slot = slot; - } + @Override + public ItemStack decrStackSize(final int i, final int num) { + return this.inv.decrStackSize(this.slot, num); + } - @Override - public int getSizeInventory() - { - return 1; - } + @Override + public ItemStack getStackInSlotOnClosing(final int i) { + return this.inv.getStackInSlotOnClosing(this.slot); + } - @Override - public ItemStack getStackInSlot( final int i ) - { - return this.inv.getStackInSlot( this.slot ); - } + @Override + public void setInventorySlotContents(final int i, final ItemStack itemstack) { + this.inv.setInventorySlotContents(this.slot, itemstack); + } - @Override - public ItemStack decrStackSize( final int i, final int num ) - { - return this.inv.decrStackSize( this.slot, num ); - } + @Override + public String getInventoryName() { + return this.inv.getInventoryName(); + } - @Override - public ItemStack getStackInSlotOnClosing( final int i ) - { - return this.inv.getStackInSlotOnClosing( this.slot ); - } + @Override + public boolean hasCustomInventoryName() { + return this.inv.hasCustomInventoryName(); + } - @Override - public void setInventorySlotContents( final int i, final ItemStack itemstack ) - { - this.inv.setInventorySlotContents( this.slot, itemstack ); - } + @Override + public int getInventoryStackLimit() { + return this.inv.getInventoryStackLimit(); + } - @Override - public String getInventoryName() - { - return this.inv.getInventoryName(); - } + @Override + public void markDirty() { + this.inv.markDirty(); + } - @Override - public boolean hasCustomInventoryName() - { - return this.inv.hasCustomInventoryName(); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer entityplayer) { + return this.inv.isUseableByPlayer(entityplayer); + } - @Override - public int getInventoryStackLimit() - { - return this.inv.getInventoryStackLimit(); - } + @Override + public void openInventory() { + this.inv.openInventory(); + } - @Override - public void markDirty() - { - this.inv.markDirty(); - } + @Override + public void closeInventory() { + this.inv.closeInventory(); + } - @Override - public boolean isUseableByPlayer( final EntityPlayer entityplayer ) - { - return this.inv.isUseableByPlayer( entityplayer ); - } - - @Override - public void openInventory() - { - this.inv.openInventory(); - } - - @Override - public void closeInventory() - { - this.inv.closeInventory(); - } - - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - return WrapperInvSlot.this.isItemValid( itemstack ) && this.inv.isItemValidForSlot( this.slot, itemstack ); - } - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + return WrapperInvSlot.this.isItemValid(itemstack) + && this.inv.isItemValidForSlot(this.slot, itemstack); + } + } } diff --git a/src/main/java/appeng/util/inv/WrapperInventoryRange.java b/src/main/java/appeng/util/inv/WrapperInventoryRange.java index 987463da..ded3f3db 100644 --- a/src/main/java/appeng/util/inv/WrapperInventoryRange.java +++ b/src/main/java/appeng/util/inv/WrapperInventoryRange.java @@ -18,161 +18,135 @@ 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; + private boolean ignoreValidItems = false; + private int[] slots; -public class WrapperInventoryRange implements IInventory -{ + public WrapperInventoryRange( + final IInventory a, final int[] s, final boolean ignoreValid + ) { + this.src = a; + this.setSlots(s); - private final IInventory src; - private boolean ignoreValidItems = false; - private int[] slots; + if (this.getSlots() == null) { + this.setSlots(new int[0]); + } - public WrapperInventoryRange( final IInventory a, final int[] s, final boolean ignoreValid ) - { - this.src = a; - this.setSlots( s ); + this.setIgnoreValidItems(ignoreValid); + } - if( this.getSlots() == null ) - { - this.setSlots( new int[0] ); - } + public WrapperInventoryRange( + final IInventory a, final int min, final int size, final boolean ignoreValid + ) { + this.src = a; + this.setSlots(new int[size]); + for (int x = 0; x < size; x++) { + this.getSlots()[x] = min + x; + } + this.setIgnoreValidItems(ignoreValid); + } - this.setIgnoreValidItems( ignoreValid ); - } + public static String concatLines(final int[] s, final String separator) { + if (s.length > 0) { + final StringBuilder sb = new StringBuilder(); + for (final int value : s) { + if (sb.length() > 0) { + sb.append(separator); + } + sb.append(value); + } + return sb.toString(); + } + return ""; + } - public WrapperInventoryRange( final IInventory a, final int min, final int size, final boolean ignoreValid ) - { - this.src = a; - this.setSlots( new int[size] ); - for( int x = 0; x < size; x++ ) - { - this.getSlots()[x] = min + x; - } - this.setIgnoreValidItems( ignoreValid ); - } + @Override + public int getSizeInventory() { + return this.getSlots().length; + } - public static String concatLines( final int[] s, final String separator ) - { - if( s.length > 0 ) - { - final StringBuilder sb = new StringBuilder(); - for( final int value : s ) - { - if( sb.length() > 0 ) - { - sb.append( separator ); - } - sb.append( value ); - } - return sb.toString(); - } - return ""; - } + @Override + public ItemStack getStackInSlot(final int var1) { + return this.src.getStackInSlot(this.getSlots()[var1]); + } - @Override - public int getSizeInventory() - { - return this.getSlots().length; - } + @Override + public ItemStack decrStackSize(final int var1, final int var2) { + return this.src.decrStackSize(this.getSlots()[var1], var2); + } - @Override - public ItemStack getStackInSlot( final int var1 ) - { - return this.src.getStackInSlot( this.getSlots()[var1] ); - } + @Override + public ItemStack getStackInSlotOnClosing(final int var1) { + return this.src.getStackInSlotOnClosing(this.getSlots()[var1]); + } - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - return this.src.decrStackSize( this.getSlots()[var1], var2 ); - } + @Override + public void setInventorySlotContents(final int var1, final ItemStack var2) { + this.src.setInventorySlotContents(this.getSlots()[var1], var2); + } - @Override - public ItemStack getStackInSlotOnClosing( final int var1 ) - { - return this.src.getStackInSlotOnClosing( this.getSlots()[var1] ); - } + @Override + public String getInventoryName() { + return this.src.getInventoryName(); + } - @Override - public void setInventorySlotContents( final int var1, final ItemStack var2 ) - { - this.src.setInventorySlotContents( this.getSlots()[var1], var2 ); - } + @Override + public boolean hasCustomInventoryName() { + return false; + } - @Override - public String getInventoryName() - { - return this.src.getInventoryName(); - } + @Override + public int getInventoryStackLimit() { + return this.src.getInventoryStackLimit(); + } - @Override - public boolean hasCustomInventoryName() - { - return false; - } + @Override + public void markDirty() { + this.src.markDirty(); + } - @Override - public int getInventoryStackLimit() - { - return this.src.getInventoryStackLimit(); - } + @Override + public boolean isUseableByPlayer(final EntityPlayer var1) { + return this.src.isUseableByPlayer(var1); + } - @Override - public void markDirty() - { - this.src.markDirty(); - } + @Override + public void openInventory() { + this.src.openInventory(); + } - @Override - public boolean isUseableByPlayer( final EntityPlayer var1 ) - { - return this.src.isUseableByPlayer( var1 ); - } + @Override + public void closeInventory() { + this.src.closeInventory(); + } - @Override - public void openInventory() - { - this.src.openInventory(); - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (this.isIgnoreValidItems()) { + return true; + } - @Override - public void closeInventory() - { - this.src.closeInventory(); - } + return this.src.isItemValidForSlot(this.getSlots()[i], itemstack); + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { - if( this.isIgnoreValidItems() ) - { - return true; - } + boolean isIgnoreValidItems() { + return this.ignoreValidItems; + } - return this.src.isItemValidForSlot( this.getSlots()[i], itemstack ); - } + private void setIgnoreValidItems(final boolean ignoreValidItems) { + this.ignoreValidItems = ignoreValidItems; + } - boolean isIgnoreValidItems() - { - return this.ignoreValidItems; - } + int[] getSlots() { + return this.slots; + } - private void setIgnoreValidItems( final boolean ignoreValidItems ) - { - this.ignoreValidItems = ignoreValidItems; - } - - int[] getSlots() - { - return this.slots; - } - - private void setSlots( final int[] slots ) - { - this.slots = slots; - } + private void setSlots(final int[] slots) { + this.slots = slots; + } } diff --git a/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java b/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java index 78b58a9a..510665a6 100644 --- a/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java +++ b/src/main/java/appeng/util/inv/WrapperMCISidedInventory.java @@ -18,60 +18,50 @@ 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 ISidedInventory side; + private final ForgeDirection dir; -public class WrapperMCISidedInventory extends WrapperInventoryRange implements IInventoryWrapper -{ + public WrapperMCISidedInventory(final ISidedInventory a, final ForgeDirection d) { + super(a, a.getAccessibleSlotsFromSide(d.ordinal()), false); + this.side = a; + this.dir = d; + } - private final ISidedInventory side; - private final ForgeDirection dir; + @Override + public ItemStack decrStackSize(final int var1, final int var2) { + if (this.canRemoveItemFromSlot(var1, this.getStackInSlot(var1))) { + return super.decrStackSize(var1, var2); + } + return null; + } - public WrapperMCISidedInventory( final ISidedInventory a, final ForgeDirection d ) - { - super( a, a.getAccessibleSlotsFromSide( d.ordinal() ), false ); - this.side = a; - this.dir = d; - } + @Override + public boolean isItemValidForSlot(final int i, final ItemStack itemstack) { + if (this.isIgnoreValidItems()) { + return true; + } - @Override - public ItemStack decrStackSize( final int var1, final int var2 ) - { - if( this.canRemoveItemFromSlot( var1, this.getStackInSlot( var1 ) ) ) - { - return super.decrStackSize( var1, var2 ); - } - return null; - } + if (this.side.isItemValidForSlot(this.getSlots()[i], itemstack)) { + return this.side.canInsertItem( + this.getSlots()[i], itemstack, this.dir.ordinal() + ); + } - @Override - public boolean isItemValidForSlot( final int i, final ItemStack itemstack ) - { + return false; + } - if( this.isIgnoreValidItems() ) - { - return true; - } + @Override + public boolean canRemoveItemFromSlot(final int i, final ItemStack is) { + if (is == null) { + return false; + } - if( this.side.isItemValidForSlot( this.getSlots()[i], itemstack ) ) - { - return this.side.canInsertItem( this.getSlots()[i], itemstack, this.dir.ordinal() ); - } - - return false; - } - - @Override - public boolean canRemoveItemFromSlot( final int i, final ItemStack is ) - { - if( is == null ) - { - return false; - } - - return this.side.canExtractItem( this.getSlots()[i], is, this.dir.ordinal() ); - } + return this.side.canExtractItem(this.getSlots()[i], is, this.dir.ordinal()); + } } diff --git a/src/main/java/appeng/util/item/AEFluidStack.java b/src/main/java/appeng/util/item/AEFluidStack.java index d4b05a11..afa5be2f 100644 --- a/src/main/java/appeng/util/item/AEFluidStack.java +++ b/src/main/java/appeng/util/item/AEFluidStack.java @@ -18,6 +18,8 @@ package appeng.util.item; +import java.io.*; +import javax.annotation.Nonnull; import appeng.api.config.FuzzyMode; import appeng.api.storage.StorageChannel; @@ -33,352 +35,315 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; -import javax.annotation.Nonnull; -import java.io.*; +public final class AEFluidStack + extends AEStack implements IAEFluidStack, Comparable { + private final int myHash; + private final Fluid fluid; + private IAETagCompound tagCompound; + private AEFluidStack(final AEFluidStack is) { + this.fluid = is.fluid; + this.setStackSize(is.getStackSize()); -public final class AEFluidStack extends AEStack implements IAEFluidStack, Comparable -{ + // priority = is.priority; + this.setCraftable(is.isCraftable()); + this.setCountRequestable(is.getCountRequestable()); - private final int myHash; - private final Fluid fluid; - private IAETagCompound tagCompound; + this.myHash = is.myHash; + } - private AEFluidStack( final AEFluidStack is ) - { + private AEFluidStack(@Nonnull final FluidStack is) { + this.fluid = is.getFluid(); - this.fluid = is.fluid; - this.setStackSize( is.getStackSize() ); + if (this.fluid == null) { + throw new IllegalArgumentException("Fluid is null."); + } - // priority = is.priority; - this.setCraftable( is.isCraftable() ); - this.setCountRequestable( is.getCountRequestable() ); + this.setStackSize(is.amount); + this.setCraftable(false); + this.setCountRequestable(0); - this.myHash = is.myHash; - } + this.myHash = this.fluid.hashCode() + ^ (this.tagCompound == null ? 0 : System.identityHashCode(this.tagCompound)); + } - private AEFluidStack( @Nonnull final FluidStack is ) - { - this.fluid = is.getFluid(); + public static IAEFluidStack loadFluidStackFromNBT(final NBTTagCompound i) { + final ItemStack itemstack = ItemStack.loadItemStackFromNBT(i); + if (itemstack == null) { + return null; + } + final AEFluidStack fluid = AEFluidStack.create(itemstack); + // fluid.priority = i.getInteger( "Priority" ); + fluid.setStackSize(i.getLong("Cnt")); + fluid.setCountRequestable(i.getLong("Req")); + fluid.setCraftable(i.getBoolean("Craft")); + return fluid; + } - if( this.fluid == null ) - { - throw new IllegalArgumentException( "Fluid is null." ); - } + public static AEFluidStack create(final Object a) { + if (a == null) { + return null; + } + if (a instanceof AEFluidStack) { + ((IAEStack) a).copy(); + } + if (a instanceof FluidStack) { + return new AEFluidStack((FluidStack) a); + } + return null; + } - this.setStackSize( is.amount ); - this.setCraftable( false ); - this.setCountRequestable( 0 ); + public static IAEFluidStack loadFluidStackFromPacket(final ByteBuf data) + throws IOException { + final byte mask = data.readByte(); + // byte PriorityType = (byte) (mask & 0x03); + final byte stackType = (byte) ((mask & 0x0C) >> 2); + final byte countReqType = (byte) ((mask & 0x30) >> 4); + final boolean isCraftable = (mask & 0x40) > 0; + final boolean hasTagCompound = (mask & 0x80) > 0; - this.myHash = this.fluid.hashCode() ^ ( this.tagCompound == null ? 0 : System.identityHashCode( this.tagCompound ) ); - } + // don't send this... + final NBTTagCompound d = new NBTTagCompound(); - public static IAEFluidStack loadFluidStackFromNBT( final NBTTagCompound i ) - { - final ItemStack itemstack = ItemStack.loadItemStackFromNBT( i ); - if( itemstack == null ) - { - return null; - } - final AEFluidStack fluid = AEFluidStack.create( itemstack ); - // fluid.priority = i.getInteger( "Priority" ); - fluid.setStackSize( i.getLong( "Cnt" ) ); - fluid.setCountRequestable( i.getLong( "Req" ) ); - fluid.setCraftable( i.getBoolean( "Craft" ) ); - return fluid; - } + final byte len2 = data.readByte(); + final byte[] name = new byte[len2]; + data.readBytes(name, 0, len2); - public static AEFluidStack create( final Object a ) - { - if( a == null ) - { - return null; - } - if( a instanceof AEFluidStack ) - { - ( (IAEStack) a ).copy(); - } - if( a instanceof FluidStack ) - { - return new AEFluidStack( (FluidStack) a ); - } - return null; - } + d.setString("FluidName", new String(name, "UTF-8")); + d.setByte("Count", (byte) 0); - public static IAEFluidStack loadFluidStackFromPacket( final ByteBuf data ) throws IOException - { - final byte mask = data.readByte(); - // byte PriorityType = (byte) (mask & 0x03); - final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 ); - final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 ); - final boolean isCraftable = ( mask & 0x40 ) > 0; - final boolean hasTagCompound = ( mask & 0x80 ) > 0; + if (hasTagCompound) { + final int len = data.readInt(); - // don't send this... - final NBTTagCompound d = new NBTTagCompound(); + final byte[] bd = new byte[len]; + data.readBytes(bd); - final byte len2 = data.readByte(); - final byte[] name = new byte[len2]; - data.readBytes( name, 0, len2 ); + final DataInputStream di = new DataInputStream(new ByteArrayInputStream(bd)); + d.setTag("tag", CompressedStreamTools.read(di)); + } - d.setString( "FluidName", new String( name, "UTF-8" ) ); - d.setByte( "Count", (byte) 0 ); + // long priority = getPacketValue( PriorityType, data ); + final long stackSize = getPacketValue(stackType, data); + final long countRequestable = getPacketValue(countReqType, data); - if( hasTagCompound ) - { - final int len = data.readInt(); + final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT(d); + if (fluidStack == null) { + return null; + } - final byte[] bd = new byte[len]; - data.readBytes( bd ); + final AEFluidStack fluid = AEFluidStack.create(fluidStack); + // fluid.priority = (int) priority; + fluid.setStackSize(stackSize); + fluid.setCountRequestable(countRequestable); + fluid.setCraftable(isCraftable); + return fluid; + } - final DataInputStream di = new DataInputStream( new ByteArrayInputStream( bd ) ); - d.setTag( "tag", CompressedStreamTools.read( di ) ); - } + @Override + public void add(final IAEFluidStack option) { + if (option == null) { + return; + } - // long priority = getPacketValue( PriorityType, data ); - final long stackSize = getPacketValue( stackType, data ); - final long countRequestable = getPacketValue( countReqType, data ); + // if ( priority < ((AEFluidStack) option).priority ) + // priority = ((AEFluidStack) option).priority; - final FluidStack fluidStack = FluidStack.loadFluidStackFromNBT( d ); - if( fluidStack == null ) - { - return null; - } + this.incStackSize(option.getStackSize()); + this.setCountRequestable( + this.getCountRequestable() + option.getCountRequestable() + ); + this.setCraftable(this.isCraftable() || option.isCraftable()); + } - final AEFluidStack fluid = AEFluidStack.create( fluidStack ); - // fluid.priority = (int) priority; - fluid.setStackSize( stackSize ); - fluid.setCountRequestable( countRequestable ); - fluid.setCraftable( isCraftable ); - return fluid; - } + @Override + public void writeToNBT(final NBTTagCompound i) { + /* + * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the + * memory department. + */ - @Override - public void add( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + /* + * NBTBase FluidName = i.getTag( "FluidName" ); NBTBase Count = i.getTag( "Count" + * ); NBTBase Cnt = i.getTag( "Cnt" ); NBTBase Req = i.getTag( "Req" ); NBTBase + * Craft = i.getTag( "Craft" ); + */ - // if ( priority < ((AEFluidStack) option).priority ) - // priority = ((AEFluidStack) option).priority; + /* + * if ( FluidName != null && FluidName instanceof NBTTagString ) ((NBTTagString) + * FluidName).data = (String) this.fluid.getName(); else + */ + i.setString("FluidName", this.fluid.getName()); - this.incStackSize( option.getStackSize() ); - this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); - this.setCraftable( this.isCraftable() || option.isCraftable() ); - } + /* + * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = + * (byte) 0; else + */ + i.setByte("Count", (byte) 0); - @Override - public void writeToNBT( final NBTTagCompound i ) - { - /* - * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the memory department. - */ + /* + * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = + * this.stackSize; else + */ + i.setLong("Cnt", this.getStackSize()); - /* - * NBTBase FluidName = i.getTag( "FluidName" ); NBTBase Count = i.getTag( "Count" ); NBTBase Cnt = i.getTag( - * "Cnt" ); NBTBase Req = i.getTag( "Req" ); NBTBase Craft = i.getTag( "Craft" ); - */ + /* + * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = + * this.stackSize; else + */ + i.setLong("Req", this.getCountRequestable()); - /* - * if ( FluidName != null && FluidName instanceof NBTTagString ) ((NBTTagString) FluidName).data = (String) - * this.fluid.getName(); else - */ - i.setString( "FluidName", this.fluid.getName() ); + /* + * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = + * (byte) (this.isCraftable() ? 1 : 0); else + */ + i.setBoolean("Craft", this.isCraftable()); - /* - * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = (byte) 0; else - */ - i.setByte( "Count", (byte) 0 ); + if (this.tagCompound != null) { + i.setTag("tag", (NBTBase) this.tagCompound); + } else { + i.removeTag("tag"); + } + } - /* - * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = this.stackSize; else - */ - i.setLong( "Cnt", this.getStackSize() ); + @Override + public boolean fuzzyComparison(final Object st, final FuzzyMode mode) { + if (st instanceof FluidStack) { + return ((FluidStack) st).getFluid() == this.fluid; + } - /* - * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = this.stackSize; else - */ - i.setLong( "Req", this.getCountRequestable() ); + if (st instanceof IAEFluidStack) { + return ((IAEFluidStack) st).getFluid() == this.fluid; + } - /* - * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = (byte) (this.isCraftable() ? - * 1 : 0); else - */ - i.setBoolean( "Craft", this.isCraftable() ); + return false; + } - if( this.tagCompound != null ) - { - i.setTag( "tag", (NBTBase) this.tagCompound ); - } - else - { - i.removeTag( "tag" ); - } - } + @Override + public IAEFluidStack copy() { + return new AEFluidStack(this); + } - @Override - public boolean fuzzyComparison( final Object st, final FuzzyMode mode ) - { - if( st instanceof FluidStack ) - { - return ( (FluidStack) st ).getFluid() == this.fluid; - } + @Override + public IAEFluidStack empty() { + final IAEFluidStack dup = this.copy(); + dup.reset(); + return dup; + } - if( st instanceof IAEFluidStack ) - { - return ( (IAEFluidStack) st ).getFluid() == this.fluid; - } + @Override + public IAETagCompound getTagCompound() { + return this.tagCompound; + } - return false; - } + @Override + public boolean isItem() { + return false; + } - @Override - public IAEFluidStack copy() - { - return new AEFluidStack( this ); - } + @Override + public boolean isFluid() { + return true; + } - @Override - public IAEFluidStack empty() - { - final IAEFluidStack dup = this.copy(); - dup.reset(); - return dup; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } - @Override - public IAETagCompound getTagCompound() - { - return this.tagCompound; - } + @Override + public int compareTo(final AEFluidStack b) { + final int diff = this.hashCode() - b.hashCode(); + return diff > 0 ? 1 : (diff < 0 ? -1 : 0); + } - @Override - public boolean isItem() - { - return false; - } + @Override + public int hashCode() { + return this.myHash; + } - @Override - public boolean isFluid() - { - return true; - } + @Override + public boolean equals(final Object ia) { + if (ia instanceof AEFluidStack) { + return ((AEFluidStack) ia).fluid == this.fluid + && this.tagCompound == ((AEFluidStack) ia).tagCompound; + } else if (ia instanceof FluidStack) { + final FluidStack is = (FluidStack) ia; - @Override - public StorageChannel getChannel() - { - return StorageChannel.FLUIDS; - } + if (is.getFluidID() == this.fluid.getID()) { + final NBTTagCompound ta = (NBTTagCompound) this.tagCompound; + final NBTTagCompound tb = is.tag; + if (ta == tb) { + return true; + } - @Override - public int compareTo( final AEFluidStack b ) - { - final int diff = this.hashCode() - b.hashCode(); - return diff > 0 ? 1 : ( diff < 0 ? -1 : 0 ); - } + 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; + } - @Override - public int hashCode() - { - return this.myHash; - } + if ((ta == null && tb != null) || (ta != null && tb == null)) { + return false; + } - @Override - public boolean equals( final Object ia ) - { - if( ia instanceof AEFluidStack ) - { - return ( (AEFluidStack) ia ).fluid == this.fluid && this.tagCompound == ( (AEFluidStack) ia ).tagCompound; - } - else if( ia instanceof FluidStack ) - { - final FluidStack is = (FluidStack) ia; + if (AESharedNBT.isShared(tb)) { + return ta == tb; + } - if( is.getFluidID() == this.fluid.getID() ) - { - final NBTTagCompound ta = (NBTTagCompound) this.tagCompound; - final NBTTagCompound tb = is.tag; - if( ta == tb ) - { - return true; - } + return Platform.NBTEqualityTest(ta, tb); + } + } + return false; + } - 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; - } + @Override + public String toString() { + return this.getFluidStack().toString(); + } - if( ( ta == null && tb != null ) || ( ta != null && tb == null ) ) - { - return false; - } + @Override + public boolean hasTagCompound() { + return this.tagCompound != null; + } - if( AESharedNBT.isShared( tb ) ) - { - return ta == tb; - } + @Override + void writeIdentity(final ByteBuf i) throws IOException { + final byte[] name = this.fluid.getName().getBytes("UTF-8"); + i.writeByte((byte) name.length); + i.writeBytes(name); + } - return Platform.NBTEqualityTest( ta, tb ); - } - } - return false; - } + @Override + void readNBT(final ByteBuf i) throws IOException { + if (this.hasTagCompound()) { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream data = new DataOutputStream(bytes); - @Override - public String toString() - { - return this.getFluidStack().toString(); - } + CompressedStreamTools.write((NBTTagCompound) this.tagCompound, data); - @Override - public boolean hasTagCompound() - { - return this.tagCompound != null; - } + final byte[] tagBytes = bytes.toByteArray(); + final int size = tagBytes.length; - @Override - void writeIdentity( final ByteBuf i ) throws IOException - { - final byte[] name = this.fluid.getName().getBytes( "UTF-8" ); - i.writeByte( (byte) name.length ); - i.writeBytes( name ); - } + i.writeInt(size); + i.writeBytes(tagBytes); + } + } - @Override - void readNBT( final ByteBuf i ) throws IOException - { - if( this.hasTagCompound() ) - { - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream data = new DataOutputStream( bytes ); + @Override + public FluidStack getFluidStack() { + final FluidStack is = new FluidStack( + this.fluid, (int) Math.min(Integer.MAX_VALUE, this.getStackSize()) + ); + if (this.tagCompound != null) { + is.tag = this.tagCompound.getNBTTagCompoundCopy(); + } - CompressedStreamTools.write( (NBTTagCompound) this.tagCompound, data ); + return is; + } - final byte[] tagBytes = bytes.toByteArray(); - final int size = tagBytes.length; - - i.writeInt( size ); - i.writeBytes( tagBytes ); - } - } - - @Override - public FluidStack getFluidStack() - { - final FluidStack is = new FluidStack( this.fluid, (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ) ); - if( this.tagCompound != null ) - { - is.tag = this.tagCompound.getNBTTagCompoundCopy(); - } - - return is; - } - - @Override - public Fluid getFluid() - { - return this.fluid; - } + @Override + public Fluid getFluid() { + return this.fluid; + } } diff --git a/src/main/java/appeng/util/item/AEItemDef.java b/src/main/java/appeng/util/item/AEItemDef.java index 184b8a86..d9c286a1 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 appeng.util.Platform; import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier; @@ -27,196 +28,167 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.util.List; +public class AEItemDef { + static final AESharedNBT LOW_TAG = new AESharedNBT(Integer.MIN_VALUE); + static final AESharedNBT HIGH_TAG = new AESharedNBT(Integer.MAX_VALUE); + private final int itemID; + private final Item item; + private int myHash; + private int def; + private int damageValue; + private int displayDamage; + private int maxDamage; + private AESharedNBT tagCompound; + @SideOnly(Side.CLIENT) + private String displayName; + @SideOnly(Side.CLIENT) + private List tooltip; + @SideOnly(Side.CLIENT) + private UniqueIdentifier uniqueID; + private OreReference isOre; -public class AEItemDef -{ + public AEItemDef(final Item it) { + this.item = it; + this.itemID = Item.getIdFromItem(it); + } - static final AESharedNBT LOW_TAG = new AESharedNBT( Integer.MIN_VALUE ); - static final AESharedNBT HIGH_TAG = new AESharedNBT( Integer.MAX_VALUE ); + AEItemDef copy() { + final AEItemDef t = new AEItemDef(this.getItem()); + t.def = this.def; + t.setDamageValue(this.getDamageValue()); + t.setDisplayDamage(this.getDisplayDamage()); + t.setMaxDamage(this.getMaxDamage()); + t.setTagCompound(this.getTagCompound()); + t.setIsOre(this.getIsOre()); + return t; + } - private final int itemID; - private final Item item; - private int myHash; - private int def; - private int damageValue; - private int displayDamage; - private int maxDamage; - private AESharedNBT tagCompound; - @SideOnly( Side.CLIENT ) - private String displayName; - @SideOnly( Side.CLIENT ) - private List tooltip; - @SideOnly( Side.CLIENT ) - private UniqueIdentifier uniqueID; - private OreReference isOre; + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final AEItemDef other = (AEItemDef) obj; + return other.getDamageValue() == this.getDamageValue() + && other.getItem() == this.getItem() + && this.getTagCompound() == other.getTagCompound(); + } - public AEItemDef( final Item it ) - { - this.item = it; - this.itemID = Item.getIdFromItem( it ); - } + boolean isItem(final ItemStack otherStack) { + // hackery! + final int dmg = this.getDamageValueHack(otherStack); - AEItemDef copy() - { - final AEItemDef t = new AEItemDef( this.getItem() ); - t.def = this.def; - t.setDamageValue( this.getDamageValue() ); - t.setDisplayDamage( this.getDisplayDamage() ); - t.setMaxDamage( this.getMaxDamage() ); - t.setTagCompound( this.getTagCompound() ); - t.setIsOre( this.getIsOre() ); - return t; - } + if (this.getItem() == otherStack.getItem() && dmg == this.getDamageValue()) { + if ((this.getTagCompound() != null) == otherStack.hasTagCompound()) { + return true; + } - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final AEItemDef other = (AEItemDef) obj; - return other.getDamageValue() == this.getDamageValue() && other.getItem() == this.getItem() && this.getTagCompound() == other.getTagCompound(); - } + if (this.getTagCompound() != null && otherStack.hasTagCompound()) { + return Platform.NBTEqualityTest( + this.getTagCompound(), otherStack.getTagCompound() + ); + } - boolean isItem( final ItemStack otherStack ) - { - // hackery! - final int dmg = this.getDamageValueHack( otherStack ); + return true; + } + return false; + } - if( this.getItem() == otherStack.getItem() && dmg == this.getDamageValue() ) - { - if( ( this.getTagCompound() != null ) == otherStack.hasTagCompound() ) - { - return true; - } + int getDamageValueHack(final ItemStack is) { + return Items.blaze_rod.getDamage(is); + } - if( this.getTagCompound() != null && otherStack.hasTagCompound() ) - { - return Platform.NBTEqualityTest( this.getTagCompound(), otherStack.getTagCompound() ); - } + void reHash() { + this.def = this.getItemID() << Platform.DEF_OFFSET | this.getDamageValue(); + this.myHash = this.def + ^ (this.getTagCompound() == null + ? 0 + : System.identityHashCode(this.getTagCompound())); + } - return true; - } - return false; - } + AESharedNBT getTagCompound() { + return this.tagCompound; + } - int getDamageValueHack( final ItemStack is ) - { - return Items.blaze_rod.getDamage( is ); - } + void setTagCompound(final AESharedNBT tagCompound) { + this.tagCompound = tagCompound; + } - void reHash() - { - this.def = this.getItemID() << Platform.DEF_OFFSET | this.getDamageValue(); - this.myHash = this.def ^ ( this.getTagCompound() == null ? 0 : System.identityHashCode( this.getTagCompound() ) ); - } + int getDamageValue() { + return this.damageValue; + } - AESharedNBT getTagCompound() - { - return this.tagCompound; - } + int setDamageValue(final int damageValue) { + this.damageValue = damageValue; + return damageValue; + } - void setTagCompound( final AESharedNBT tagCompound ) - { - this.tagCompound = tagCompound; - } + Item getItem() { + return this.item; + } - int getDamageValue() - { - return this.damageValue; - } + int getDisplayDamage() { + return this.displayDamage; + } - int setDamageValue( final int damageValue ) - { - this.damageValue = damageValue; - return damageValue; - } + void setDisplayDamage(final int displayDamage) { + this.displayDamage = displayDamage; + } - Item getItem() - { - return this.item; - } + String getDisplayName() { + return this.displayName; + } - int getDisplayDamage() - { - return this.displayDamage; - } + void setDisplayName(final String displayName) { + this.displayName = displayName; + } - void setDisplayDamage( final int displayDamage ) - { - this.displayDamage = displayDamage; - } + List getTooltip() { + return this.tooltip; + } - String getDisplayName() - { - return this.displayName; - } + List setTooltip(final List tooltip) { + this.tooltip = tooltip; + return tooltip; + } - void setDisplayName( final String displayName ) - { - this.displayName = displayName; - } + UniqueIdentifier getUniqueID() { + return this.uniqueID; + } - List getTooltip() - { - return this.tooltip; - } + UniqueIdentifier setUniqueID(final UniqueIdentifier uniqueID) { + this.uniqueID = uniqueID; + return uniqueID; + } - List setTooltip( final List tooltip ) - { - this.tooltip = tooltip; - return tooltip; - } + OreReference getIsOre() { + return this.isOre; + } - UniqueIdentifier getUniqueID() - { - return this.uniqueID; - } + void setIsOre(final OreReference isOre) { + this.isOre = isOre; + } - UniqueIdentifier setUniqueID( final UniqueIdentifier uniqueID ) - { - this.uniqueID = uniqueID; - return uniqueID; - } + int getItemID() { + return this.itemID; + } - OreReference getIsOre() - { - return this.isOre; - } + int getMaxDamage() { + return this.maxDamage; + } - void setIsOre( final OreReference isOre ) - { - this.isOre = isOre; - } - - int getItemID() - { - return this.itemID; - } - - int getMaxDamage() - { - return this.maxDamage; - } - - void setMaxDamage( final int maxDamage ) - { - this.maxDamage = maxDamage; - } - - /** - * TODO: Check if replaceable by hashCode(); - */ - int getMyHash() - { - return this.myHash; - } + void setMaxDamage(final int maxDamage) { + this.maxDamage = maxDamage; + } + /** + * TODO: Check if replaceable by hashCode(); + */ + int getMyHash() { + return this.myHash; + } } diff --git a/src/main/java/appeng/util/item/AEItemStack.java b/src/main/java/appeng/util/item/AEItemStack.java index 5c216792..29a0bbb9 100644 --- a/src/main/java/appeng/util/item/AEItemStack.java +++ b/src/main/java/appeng/util/item/AEItemStack.java @@ -18,6 +18,10 @@ package appeng.util.item; +import java.io.*; +import java.security.InvalidParameterException; +import java.util.List; +import javax.annotation.Nullable; import appeng.api.config.FuzzyMode; import appeng.api.storage.StorageChannel; @@ -34,697 +38,640 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; -import javax.annotation.Nullable; -import java.io.*; -import java.security.InvalidParameterException; -import java.util.List; - - -public final class AEItemStack extends AEStack implements IAEItemStack, Comparable -{ - - private AEItemDef def; - - private AEItemStack( final AEItemStack is ) - { - this.setDefinition( is.getDefinition() ); - this.setStackSize( is.getStackSize() ); - this.setCraftable( is.isCraftable() ); - this.setCountRequestable( is.getCountRequestable() ); - } - - private AEItemStack( final ItemStack is ) - { - if( is == null ) - { - throw new InvalidParameterException( "null is not a valid ItemStack for AEItemStack." ); - } - - final Item item = is.getItem(); - if( item == null ) - { - throw new InvalidParameterException( "Contained item is null, thus not a valid ItemStack for AEItemStack." ); - } - - this.setDefinition( new AEItemDef( item ) ); - - if( this.getDefinition().getItem() == null ) - { - throw new InvalidParameterException( "This ItemStack is bad, it has a null item." ); - } - - /* - * Prevent an Item from changing the damage value on me... Either, this or a core mod. - */ - - /* - * Super hackery. - * is.itemID = appeng.api.Materials.matQuartz.itemID; damageValue = is.getItemDamage(); is.itemID = itemID; - */ - - /* - * Kinda hackery - */ - this.getDefinition().setDamageValue( this.getDefinition().getDamageValueHack( is ) ); - this.getDefinition().setDisplayDamage( is.getItemDamageForDisplay() ); - this.getDefinition().setMaxDamage( is.getMaxDamage() ); - - final NBTTagCompound tagCompound = is.getTagCompound(); - if( tagCompound != null ) - { - this.getDefinition().setTagCompound( (AESharedNBT) AESharedNBT.getSharedTagCompound( tagCompound, is ) ); - } - - this.setStackSize( is.stackSize ); - this.setCraftable( false ); - this.setCountRequestable( 0 ); - - this.getDefinition().reHash(); - this.getDefinition().setIsOre( OreHelper.INSTANCE.isOre( is ) ); - } - - public static IAEItemStack loadItemStackFromNBT( final NBTTagCompound i ) - { - if( i == null ) - { - return null; - } - - final ItemStack itemstack = ItemStack.loadItemStackFromNBT( i ); - if( itemstack == null ) - { - return null; - } - - final AEItemStack item = AEItemStack.create( itemstack ); - // item.priority = i.getInteger( "Priority" ); - item.setStackSize( i.getLong( "Cnt" ) ); - item.setCountRequestable( i.getLong( "Req" ) ); - item.setCraftable( i.getBoolean( "Craft" ) ); - return item; - } - - @Nullable - public static AEItemStack create( final ItemStack stack ) - { - if( stack == null ) - { - return null; - } - - return new AEItemStack( stack ); - } - - public static IAEItemStack loadItemStackFromPacket( final ByteBuf data ) throws IOException - { - final byte mask = data.readByte(); - // byte PriorityType = (byte) (mask & 0x03); - final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 ); - final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 ); - final boolean isCraftable = ( mask & 0x40 ) > 0; - final boolean hasTagCompound = ( mask & 0x80 ) > 0; - - // don't send this... - final NBTTagCompound d = new NBTTagCompound(); - - d.setShort( "id", data.readShort() ); - d.setShort( "Damage", data.readShort() ); - d.setByte( "Count", (byte) 0 ); - - if( hasTagCompound ) - { - final int len = data.readInt(); - - final byte[] bd = new byte[len]; - data.readBytes( bd ); - - final ByteArrayInputStream di = new ByteArrayInputStream( bd ); - d.setTag( "tag", CompressedStreamTools.read( new DataInputStream( di ) ) ); - } - - // long priority = getPacketValue( PriorityType, data ); - final long stackSize = getPacketValue( stackType, data ); - final long countRequestable = getPacketValue( countReqType, data ); - - final ItemStack itemstack = ItemStack.loadItemStackFromNBT( d ); - if( itemstack == null ) - { - return null; - } - - final AEItemStack item = AEItemStack.create( itemstack ); - // item.priority = (int) priority; - item.setStackSize( stackSize ); - item.setCountRequestable( countRequestable ); - item.setCraftable( isCraftable ); - return item; - } - - @Override - public void add( final IAEItemStack option ) - { - if( option == null ) - { - return; - } - - // if ( priority < ((AEItemStack) option).priority ) - // priority = ((AEItemStack) option).priority; - - this.incStackSize( option.getStackSize() ); - this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() ); - this.setCraftable( this.isCraftable() || option.isCraftable() ); - } - - @Override - public void writeToNBT( final NBTTagCompound i ) - { - /* - * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the memory department. - */ - - /* - * NBTBase id = i.getTag( "id" ); NBTBase Count = i.getTag( "Count" ); NBTBase Cnt = i.getTag( "Cnt" ); NBTBase - * Req = i.getTag( "Req" ); NBTBase Craft = i.getTag( "Craft" ); NBTBase Damage = i.getTag( "Damage" ); - */ - - /* - * if ( id != null && id instanceof NBTTagShort ) ((NBTTagShort) id).data = (short) this.def.item.itemID; else - */ - i.setShort( "id", (short) Item.itemRegistry.getIDForObject( this.getDefinition().getItem() ) ); - - /* - * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = (byte) 0; else - */ - i.setByte( "Count", (byte) 0 ); - - /* - * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = this.stackSize; else - */ - i.setLong( "Cnt", this.getStackSize() ); - - /* - * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = this.stackSize; else - */ - i.setLong( "Req", this.getCountRequestable() ); - - /* - * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = (byte) (this.isCraftable() ? - * 1 : 0); else - */ - i.setBoolean( "Craft", this.isCraftable() ); - - /* - * if ( Damage != null && Damage instanceof NBTTagShort ) ((NBTTagShort) Damage).data = (short) - * this.def.damageValue; else - */ - i.setShort( "Damage", (short) this.getDefinition().getDamageValue() ); - - if( this.getDefinition().getTagCompound() != null ) - { - i.setTag( "tag", this.getDefinition().getTagCompound() ); - } - else - { - i.removeTag( "tag" ); - } - } - - @Override - public boolean fuzzyComparison( final Object st, final FuzzyMode mode ) - { - if( st instanceof IAEItemStack ) - { - final IAEItemStack o = (IAEItemStack) st; - - if( this.sameOre( o ) ) - { - return true; - } - - if( o.getItem() == this.getItem() ) - { - if( this.getDefinition().getItem().isDamageable() ) - { - final ItemStack a = this.getItemStack(); - final ItemStack b = o.getItemStack(); - - try - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamageForDisplay() > 1 ) == ( b.getItemDamageForDisplay() > 1 ); - } - else - { - final float percentDamageOfA = 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); - final float percentDamageOfB = 1.0f - (float) b.getItemDamageForDisplay() / (float) b.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - catch( final Throwable e ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 ); - } - else - { - final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); - final float percentDamageOfB = (float) b.getItemDamage() / (float) b.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - } - - return this.getItemDamage() == o.getItemDamage(); - } - } - - if( st instanceof ItemStack ) - { - final ItemStack o = (ItemStack) st; - - OreHelper.INSTANCE.sameOre( this, o ); - - if( o.getItem() == this.getItem() ) - { - if( this.getDefinition().getItem().isDamageable() ) - { - final ItemStack a = this.getItemStack(); - - try - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamageForDisplay() > 1 ) == ( o.getItemDamageForDisplay() > 1 ); - } - else - { - final float percentDamageOfA = 1.0f - (float) a.getItemDamageForDisplay() / (float) a.getMaxDamage(); - final float percentDamageOfB = 1.0f - (float) o.getItemDamageForDisplay() / (float) o.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - catch( final Throwable e ) - { - if( mode == FuzzyMode.IGNORE_ALL ) - { - return true; - } - else if( mode == FuzzyMode.PERCENT_99 ) - { - return ( a.getItemDamage() > 1 ) == ( o.getItemDamage() > 1 ); - } - else - { - final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage(); - final float percentDamageOfB = (float) o.getItemDamage() / (float) o.getMaxDamage(); - - return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint ); - } - } - } - - return this.getItemDamage() == o.getItemDamage(); - } - } - - return false; - } - - @Override - public IAEItemStack copy() - { - return new AEItemStack( this ); - } - - @Override - public IAEItemStack empty() - { - final IAEItemStack dup = this.copy(); - dup.reset(); - return dup; - } - - @Override - public IAETagCompound getTagCompound() - { - return this.getDefinition().getTagCompound(); - } - - @Override - public boolean isItem() - { - return true; - } - - @Override - public boolean isFluid() - { - return false; - } - - @Override - public StorageChannel getChannel() - { - return StorageChannel.ITEMS; - } - - @Override - public ItemStack getItemStack() - { - final ItemStack is = new ItemStack( this.getDefinition().getItem(), (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ), this.getDefinition().getDamageValue() ); - if( this.getDefinition().getTagCompound() != null ) - { - is.setTagCompound( this.getDefinition().getTagCompound().getNBTTagCompoundCopy() ); - } - - return is; - } - - @Override - public Item getItem() - { - return this.getDefinition().getItem(); - } - - @Override - public int getItemDamage() - { - return this.getDefinition().getDamageValue(); - } - - @Override - public boolean sameOre( final IAEItemStack is ) - { - return OreHelper.INSTANCE.sameOre( this, is ); - } - - @Override - public boolean isSameType( final IAEItemStack otherStack ) - { - if( otherStack == null ) - { - return false; - } - - return this.getDefinition().equals( ( (AEItemStack) otherStack ).getDefinition() ); - } - - @Override - public boolean isSameType( final ItemStack otherStack ) - { - if( otherStack == null ) - { - return false; - } - - return this.getDefinition().isItem( otherStack ); - } - - @Override - public int hashCode() - { - return this.getDefinition().getMyHash(); - } - - @Override - public boolean equals( final Object ia ) - { - if( ia instanceof AEItemStack ) - { - return ( (AEItemStack) ia ).getDefinition().equals( this.getDefinition() );// && def.tagCompound == - // ((AEItemStack) - // ia).def.tagCompound; - } - else if( ia instanceof ItemStack ) - { - final ItemStack is = (ItemStack) ia; - - if( is.getItem() == this.getDefinition().getItem() && is.getItemDamage() == this.getDefinition().getDamageValue() ) - { - final NBTTagCompound ta = this.getDefinition().getTagCompound(); - final 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( final AEItemStack b ) - { - final int id = this.getDefinition().getItemID() - b.getDefinition().getItemID(); - if( id != 0 ) - { - return id; - } - - final int damageValue = this.getDefinition().getDamageValue() - b.getDefinition().getDamageValue(); - if( damageValue != 0 ) - { - return damageValue; - } - - final int displayDamage = this.getDefinition().getDisplayDamage() - b.getDefinition().getDisplayDamage(); - if( displayDamage != 0 ) - { - return displayDamage; - } - - return ( this.getDefinition().getTagCompound() == b.getDefinition().getTagCompound() ) ? 0 : this.compareNBT( b.getDefinition() ); - } - - private int compareNBT( final AEItemDef b ) - { - final int nbt = this.compare( ( this.getDefinition().getTagCompound() == null ? 0 : this.getDefinition().getTagCompound().getHash() ), ( b.getTagCompound() == null ? 0 : b.getTagCompound().getHash() ) ); - if( nbt == 0 ) - { - return this.compare( System.identityHashCode( this.getDefinition().getTagCompound() ), System.identityHashCode( b.getTagCompound() ) ); - } - return nbt; - } - - private int compare( final int l, final int m ) - { - return l < m ? -1 : ( l > m ? 1 : 0 ); - } - - @SideOnly( Side.CLIENT ) - public List getToolTip() - { - if( this.getDefinition().getTooltip() != null ) - { - return this.getDefinition().getTooltip(); - } - - return this.getDefinition().setTooltip( Platform.getTooltip( this.getItemStack() ) ); - } - - @SideOnly( Side.CLIENT ) - public String getDisplayName() - { - if( this.getDefinition().getDisplayName() == null ) - { - this.getDefinition().setDisplayName( Platform.getItemDisplayName( this.getItemStack() ) ); - } - - return this.getDefinition().getDisplayName(); - } - - @SideOnly( Side.CLIENT ) - public String getModID() - { - if( this.getDefinition().getUniqueID() != null ) - { - return this.getModName( this.getDefinition().getUniqueID() ); - } - - return this.getModName( this.getDefinition().setUniqueID( GameRegistry.findUniqueIdentifierFor( this.getDefinition().getItem() ) ) ); - } - - private String getModName( final UniqueIdentifier uniqueIdentifier ) - { - if( uniqueIdentifier == null ) - { - return "** Null"; - } - - return uniqueIdentifier.modId == null ? "** Null" : uniqueIdentifier.modId; - } - - IAEItemStack getLow( final FuzzyMode fuzzy, final boolean ignoreMeta ) - { - final AEItemStack bottom = new AEItemStack( this ); - final AEItemDef newDef = bottom.setDefinition( bottom.getDefinition().copy() ); - - if( ignoreMeta ) - { - newDef.setDisplayDamage( newDef.setDamageValue( 0 ) ); - newDef.reHash(); - return bottom; - } - - if( newDef.getItem().isDamageable() ) - { - if( fuzzy == FuzzyMode.IGNORE_ALL ) - { - newDef.setDisplayDamage( 0 ); - } - else if( fuzzy == FuzzyMode.PERCENT_99 ) - { - if( this.getDefinition().getDamageValue() == 0 ) - { - newDef.setDisplayDamage( 0 ); - } - else - { - newDef.setDisplayDamage( 1 ); - } - } - else - { - final int breakpoint = fuzzy.calculateBreakPoint( this.getDefinition().getMaxDamage() ); - newDef.setDisplayDamage( breakpoint <= this.getDefinition().getDisplayDamage() ? breakpoint : 0 ); - } - - newDef.setDamageValue( newDef.getDisplayDamage() ); - } - - newDef.setTagCompound( AEItemDef.LOW_TAG ); - newDef.reHash(); - return bottom; - } - - IAEItemStack getHigh( final FuzzyMode fuzzy, final boolean ignoreMeta ) - { - final AEItemStack top = new AEItemStack( this ); - final AEItemDef newDef = top.setDefinition( top.getDefinition().copy() ); - - if( ignoreMeta ) - { - newDef.setDisplayDamage( newDef.setDamageValue( Integer.MAX_VALUE ) ); - newDef.reHash(); - return top; - } - - if( newDef.getItem().isDamageable() ) - { - if( fuzzy == FuzzyMode.IGNORE_ALL ) - { - newDef.setDisplayDamage( this.getDefinition().getMaxDamage() + 1 ); - } - else if( fuzzy == FuzzyMode.PERCENT_99 ) - { - if( this.getDefinition().getDamageValue() == 0 ) - { - newDef.setDisplayDamage( 0 ); - } - else - { - newDef.setDisplayDamage( this.getDefinition().getMaxDamage() + 1 ); - } - } - else - { - final int breakpoint = fuzzy.calculateBreakPoint( this.getDefinition().getMaxDamage() ); - newDef.setDisplayDamage( this.getDefinition().getDisplayDamage() < breakpoint ? breakpoint - 1 : this.getDefinition().getMaxDamage() + 1 ); - } - - newDef.setDamageValue( newDef.getDisplayDamage() ); - } - - newDef.setTagCompound( AEItemDef.HIGH_TAG ); - newDef.reHash(); - return top; - } - - public boolean isOre() - { - return this.getDefinition().getIsOre() != null; - } - - @Override - void writeIdentity( final ByteBuf i ) throws IOException - { - i.writeShort( Item.itemRegistry.getIDForObject( this.getDefinition().getItem() ) ); - i.writeShort( this.getItemDamage() ); - } - - @Override - void readNBT( final ByteBuf i ) throws IOException - { - if( this.hasTagCompound() ) - { - final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - final DataOutputStream data = new DataOutputStream( bytes ); - - CompressedStreamTools.write( (NBTTagCompound) this.getTagCompound(), data ); - - final byte[] tagBytes = bytes.toByteArray(); - final int size = tagBytes.length; - - i.writeInt( size ); - i.writeBytes( tagBytes ); - } - } - - @Override - public boolean hasTagCompound() - { - return this.getDefinition().getTagCompound() != null; - } - - AEItemDef getDefinition() - { - return this.def; - } - - private AEItemDef setDefinition( final AEItemDef def ) - { - this.def = def; - return def; - } +public final class AEItemStack + extends AEStack implements IAEItemStack, Comparable { + private AEItemDef def; + + private AEItemStack(final AEItemStack is) { + this.setDefinition(is.getDefinition()); + this.setStackSize(is.getStackSize()); + this.setCraftable(is.isCraftable()); + this.setCountRequestable(is.getCountRequestable()); + } + + private AEItemStack(final ItemStack is) { + if (is == null) { + throw new InvalidParameterException( + "null is not a valid ItemStack for AEItemStack." + ); + } + + final Item item = is.getItem(); + if (item == null) { + throw new InvalidParameterException( + "Contained item is null, thus not a valid ItemStack for AEItemStack." + ); + } + + this.setDefinition(new AEItemDef(item)); + + if (this.getDefinition().getItem() == null) { + throw new InvalidParameterException( + "This ItemStack is bad, it has a null item." + ); + } + + /* + * Prevent an Item from changing the damage value on me... Either, this or a core + * mod. + */ + + /* + * Super hackery. + * is.itemID = appeng.api.Materials.matQuartz.itemID; damageValue = + * is.getItemDamage(); is.itemID = itemID; + */ + + /* + * Kinda hackery + */ + this.getDefinition().setDamageValue(this.getDefinition().getDamageValueHack(is)); + this.getDefinition().setDisplayDamage(is.getItemDamageForDisplay()); + this.getDefinition().setMaxDamage(is.getMaxDamage()); + + final NBTTagCompound tagCompound = is.getTagCompound(); + if (tagCompound != null) { + this.getDefinition().setTagCompound((AESharedNBT + ) AESharedNBT.getSharedTagCompound(tagCompound, is)); + } + + this.setStackSize(is.stackSize); + this.setCraftable(false); + this.setCountRequestable(0); + + this.getDefinition().reHash(); + this.getDefinition().setIsOre(OreHelper.INSTANCE.isOre(is)); + } + + public static IAEItemStack loadItemStackFromNBT(final NBTTagCompound i) { + if (i == null) { + return null; + } + + final ItemStack itemstack = ItemStack.loadItemStackFromNBT(i); + if (itemstack == null) { + return null; + } + + final AEItemStack item = AEItemStack.create(itemstack); + // item.priority = i.getInteger( "Priority" ); + item.setStackSize(i.getLong("Cnt")); + item.setCountRequestable(i.getLong("Req")); + item.setCraftable(i.getBoolean("Craft")); + return item; + } + + @Nullable + public static AEItemStack create(final ItemStack stack) { + if (stack == null) { + return null; + } + + return new AEItemStack(stack); + } + + public static IAEItemStack loadItemStackFromPacket(final ByteBuf data) + throws IOException { + final byte mask = data.readByte(); + // byte PriorityType = (byte) (mask & 0x03); + final byte stackType = (byte) ((mask & 0x0C) >> 2); + final byte countReqType = (byte) ((mask & 0x30) >> 4); + final boolean isCraftable = (mask & 0x40) > 0; + final boolean hasTagCompound = (mask & 0x80) > 0; + + // don't send this... + final NBTTagCompound d = new NBTTagCompound(); + + d.setShort("id", data.readShort()); + d.setShort("Damage", data.readShort()); + d.setByte("Count", (byte) 0); + + if (hasTagCompound) { + final int len = data.readInt(); + + final byte[] bd = new byte[len]; + data.readBytes(bd); + + final ByteArrayInputStream di = new ByteArrayInputStream(bd); + d.setTag("tag", CompressedStreamTools.read(new DataInputStream(di))); + } + + // long priority = getPacketValue( PriorityType, data ); + final long stackSize = getPacketValue(stackType, data); + final long countRequestable = getPacketValue(countReqType, data); + + final ItemStack itemstack = ItemStack.loadItemStackFromNBT(d); + if (itemstack == null) { + return null; + } + + final AEItemStack item = AEItemStack.create(itemstack); + // item.priority = (int) priority; + item.setStackSize(stackSize); + item.setCountRequestable(countRequestable); + item.setCraftable(isCraftable); + return item; + } + + @Override + public void add(final IAEItemStack option) { + if (option == null) { + return; + } + + // if ( priority < ((AEItemStack) option).priority ) + // priority = ((AEItemStack) option).priority; + + this.incStackSize(option.getStackSize()); + this.setCountRequestable( + this.getCountRequestable() + option.getCountRequestable() + ); + this.setCraftable(this.isCraftable() || option.isCraftable()); + } + + @Override + public void writeToNBT(final NBTTagCompound i) { + /* + * Mojang Fucked this over ; GC Optimization - Ugly Yes, but it saves a lot in the + * memory department. + */ + + /* + * NBTBase id = i.getTag( "id" ); NBTBase Count = i.getTag( "Count" ); NBTBase Cnt + * = i.getTag( "Cnt" ); NBTBase Req = i.getTag( "Req" ); NBTBase Craft = i.getTag( + * "Craft" ); NBTBase Damage = i.getTag( "Damage" ); + */ + + /* + * if ( id != null && id instanceof NBTTagShort ) ((NBTTagShort) id).data = + * (short) this.def.item.itemID; else + */ + i.setShort( + "id", (short) Item.itemRegistry.getIDForObject(this.getDefinition().getItem()) + ); + + /* + * if ( Count != null && Count instanceof NBTTagByte ) ((NBTTagByte) Count).data = + * (byte) 0; else + */ + i.setByte("Count", (byte) 0); + + /* + * if ( Cnt != null && Cnt instanceof NBTTagLong ) ((NBTTagLong) Cnt).data = + * this.stackSize; else + */ + i.setLong("Cnt", this.getStackSize()); + + /* + * if ( Req != null && Req instanceof NBTTagLong ) ((NBTTagLong) Req).data = + * this.stackSize; else + */ + i.setLong("Req", this.getCountRequestable()); + + /* + * if ( Craft != null && Craft instanceof NBTTagByte ) ((NBTTagByte) Craft).data = + * (byte) (this.isCraftable() ? 1 : 0); else + */ + i.setBoolean("Craft", this.isCraftable()); + + /* + * if ( Damage != null && Damage instanceof NBTTagShort ) ((NBTTagShort) + * Damage).data = (short) this.def.damageValue; else + */ + i.setShort("Damage", (short) this.getDefinition().getDamageValue()); + + if (this.getDefinition().getTagCompound() != null) { + i.setTag("tag", this.getDefinition().getTagCompound()); + } else { + i.removeTag("tag"); + } + } + + @Override + public boolean fuzzyComparison(final Object st, final FuzzyMode mode) { + if (st instanceof IAEItemStack) { + final IAEItemStack o = (IAEItemStack) st; + + if (this.sameOre(o)) { + return true; + } + + if (o.getItem() == this.getItem()) { + if (this.getDefinition().getItem().isDamageable()) { + final ItemStack a = this.getItemStack(); + final ItemStack b = o.getItemStack(); + + try { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamageForDisplay() > 1) + == (b.getItemDamageForDisplay() > 1); + } else { + final float percentDamageOfA = 1.0f + - (float) a.getItemDamageForDisplay() + / (float) a.getMaxDamage(); + final float percentDamageOfB = 1.0f + - (float) b.getItemDamageForDisplay() + / (float) b.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) + == (percentDamageOfB > mode.breakPoint); + } + } catch (final Throwable e) { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamage() > 1) == (b.getItemDamage() > 1); + } else { + final float percentDamageOfA + = (float) a.getItemDamage() / (float) a.getMaxDamage(); + final float percentDamageOfB + = (float) b.getItemDamage() / (float) b.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) + == (percentDamageOfB > mode.breakPoint); + } + } + } + + return this.getItemDamage() == o.getItemDamage(); + } + } + + if (st instanceof ItemStack) { + final ItemStack o = (ItemStack) st; + + OreHelper.INSTANCE.sameOre(this, o); + + if (o.getItem() == this.getItem()) { + if (this.getDefinition().getItem().isDamageable()) { + final ItemStack a = this.getItemStack(); + + try { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamageForDisplay() > 1) + == (o.getItemDamageForDisplay() > 1); + } else { + final float percentDamageOfA = 1.0f + - (float) a.getItemDamageForDisplay() + / (float) a.getMaxDamage(); + final float percentDamageOfB = 1.0f + - (float) o.getItemDamageForDisplay() + / (float) o.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) + == (percentDamageOfB > mode.breakPoint); + } + } catch (final Throwable e) { + if (mode == FuzzyMode.IGNORE_ALL) { + return true; + } else if (mode == FuzzyMode.PERCENT_99) { + return (a.getItemDamage() > 1) == (o.getItemDamage() > 1); + } else { + final float percentDamageOfA + = (float) a.getItemDamage() / (float) a.getMaxDamage(); + final float percentDamageOfB + = (float) o.getItemDamage() / (float) o.getMaxDamage(); + + return (percentDamageOfA > mode.breakPoint) + == (percentDamageOfB > mode.breakPoint); + } + } + } + + return this.getItemDamage() == o.getItemDamage(); + } + } + + return false; + } + + @Override + public IAEItemStack copy() { + return new AEItemStack(this); + } + + @Override + public IAEItemStack empty() { + final IAEItemStack dup = this.copy(); + dup.reset(); + return dup; + } + + @Override + public IAETagCompound getTagCompound() { + return this.getDefinition().getTagCompound(); + } + + @Override + public boolean isItem() { + return true; + } + + @Override + public boolean isFluid() { + return false; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public ItemStack getItemStack() { + final ItemStack is = new ItemStack( + this.getDefinition().getItem(), + (int) Math.min(Integer.MAX_VALUE, this.getStackSize()), + this.getDefinition().getDamageValue() + ); + if (this.getDefinition().getTagCompound() != null) { + is.setTagCompound(this.getDefinition().getTagCompound().getNBTTagCompoundCopy( + )); + } + + return is; + } + + @Override + public Item getItem() { + return this.getDefinition().getItem(); + } + + @Override + public int getItemDamage() { + return this.getDefinition().getDamageValue(); + } + + @Override + public boolean sameOre(final IAEItemStack is) { + return OreHelper.INSTANCE.sameOre(this, is); + } + + @Override + public boolean isSameType(final IAEItemStack otherStack) { + if (otherStack == null) { + return false; + } + + return this.getDefinition().equals(((AEItemStack) otherStack).getDefinition()); + } + + @Override + public boolean isSameType(final ItemStack otherStack) { + if (otherStack == null) { + return false; + } + + return this.getDefinition().isItem(otherStack); + } + + @Override + public int hashCode() { + return this.getDefinition().getMyHash(); + } + + @Override + public boolean equals(final Object ia) { + if (ia instanceof AEItemStack) { + return ((AEItemStack) ia) + .getDefinition() + .equals(this.getDefinition()); // && def.tagCompound == + // ((AEItemStack) + // ia).def.tagCompound; + } else if (ia instanceof ItemStack) { + final ItemStack is = (ItemStack) ia; + + if (is.getItem() == this.getDefinition().getItem() + && is.getItemDamage() == this.getDefinition().getDamageValue()) { + final NBTTagCompound ta = this.getDefinition().getTagCompound(); + final 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(final AEItemStack b) { + final int id = this.getDefinition().getItemID() - b.getDefinition().getItemID(); + if (id != 0) { + return id; + } + + final int damageValue + = this.getDefinition().getDamageValue() - b.getDefinition().getDamageValue(); + if (damageValue != 0) { + return damageValue; + } + + final int displayDamage = this.getDefinition().getDisplayDamage() + - b.getDefinition().getDisplayDamage(); + if (displayDamage != 0) { + return displayDamage; + } + + return (this.getDefinition().getTagCompound() + == b.getDefinition().getTagCompound()) + ? 0 + : this.compareNBT(b.getDefinition()); + } + + private int compareNBT(final AEItemDef b) { + final int nbt = this.compare( + (this.getDefinition().getTagCompound() == null + ? 0 + : this.getDefinition().getTagCompound().getHash()), + (b.getTagCompound() == null ? 0 : b.getTagCompound().getHash()) + ); + if (nbt == 0) { + return this.compare( + System.identityHashCode(this.getDefinition().getTagCompound()), + System.identityHashCode(b.getTagCompound()) + ); + } + return nbt; + } + + private int compare(final int l, final int m) { + return l < m ? -1 : (l > m ? 1 : 0); + } + + @SideOnly(Side.CLIENT) + public List getToolTip() { + if (this.getDefinition().getTooltip() != null) { + return this.getDefinition().getTooltip(); + } + + return this.getDefinition().setTooltip(Platform.getTooltip(this.getItemStack())); + } + + @SideOnly(Side.CLIENT) + public String getDisplayName() { + if (this.getDefinition().getDisplayName() == null) { + this.getDefinition().setDisplayName( + Platform.getItemDisplayName(this.getItemStack()) + ); + } + + return this.getDefinition().getDisplayName(); + } + + @SideOnly(Side.CLIENT) + public String getModID() { + if (this.getDefinition().getUniqueID() != null) { + return this.getModName(this.getDefinition().getUniqueID()); + } + + return this.getModName(this.getDefinition().setUniqueID( + GameRegistry.findUniqueIdentifierFor(this.getDefinition().getItem()) + )); + } + + private String getModName(final UniqueIdentifier uniqueIdentifier) { + if (uniqueIdentifier == null) { + return "** Null"; + } + + return uniqueIdentifier.modId == null ? "** Null" : uniqueIdentifier.modId; + } + + IAEItemStack getLow(final FuzzyMode fuzzy, final boolean ignoreMeta) { + final AEItemStack bottom = new AEItemStack(this); + final AEItemDef newDef = bottom.setDefinition(bottom.getDefinition().copy()); + + if (ignoreMeta) { + newDef.setDisplayDamage(newDef.setDamageValue(0)); + newDef.reHash(); + return bottom; + } + + if (newDef.getItem().isDamageable()) { + if (fuzzy == FuzzyMode.IGNORE_ALL) { + newDef.setDisplayDamage(0); + } else if (fuzzy == FuzzyMode.PERCENT_99) { + if (this.getDefinition().getDamageValue() == 0) { + newDef.setDisplayDamage(0); + } else { + newDef.setDisplayDamage(1); + } + } else { + final int breakpoint + = fuzzy.calculateBreakPoint(this.getDefinition().getMaxDamage()); + newDef.setDisplayDamage( + breakpoint <= this.getDefinition().getDisplayDamage() ? breakpoint : 0 + ); + } + + newDef.setDamageValue(newDef.getDisplayDamage()); + } + + newDef.setTagCompound(AEItemDef.LOW_TAG); + newDef.reHash(); + return bottom; + } + + IAEItemStack getHigh(final FuzzyMode fuzzy, final boolean ignoreMeta) { + final AEItemStack top = new AEItemStack(this); + final AEItemDef newDef = top.setDefinition(top.getDefinition().copy()); + + if (ignoreMeta) { + newDef.setDisplayDamage(newDef.setDamageValue(Integer.MAX_VALUE)); + newDef.reHash(); + return top; + } + + if (newDef.getItem().isDamageable()) { + if (fuzzy == FuzzyMode.IGNORE_ALL) { + newDef.setDisplayDamage(this.getDefinition().getMaxDamage() + 1); + } else if (fuzzy == FuzzyMode.PERCENT_99) { + if (this.getDefinition().getDamageValue() == 0) { + newDef.setDisplayDamage(0); + } else { + newDef.setDisplayDamage(this.getDefinition().getMaxDamage() + 1); + } + } else { + final int breakpoint + = fuzzy.calculateBreakPoint(this.getDefinition().getMaxDamage()); + newDef.setDisplayDamage( + this.getDefinition().getDisplayDamage() < breakpoint + ? breakpoint - 1 + : this.getDefinition().getMaxDamage() + 1 + ); + } + + newDef.setDamageValue(newDef.getDisplayDamage()); + } + + newDef.setTagCompound(AEItemDef.HIGH_TAG); + newDef.reHash(); + return top; + } + + public boolean isOre() { + return this.getDefinition().getIsOre() != null; + } + + @Override + void writeIdentity(final ByteBuf i) throws IOException { + i.writeShort(Item.itemRegistry.getIDForObject(this.getDefinition().getItem())); + i.writeShort(this.getItemDamage()); + } + + @Override + void readNBT(final ByteBuf i) throws IOException { + if (this.hasTagCompound()) { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final DataOutputStream data = new DataOutputStream(bytes); + + CompressedStreamTools.write((NBTTagCompound) this.getTagCompound(), data); + + final byte[] tagBytes = bytes.toByteArray(); + final int size = tagBytes.length; + + i.writeInt(size); + i.writeBytes(tagBytes); + } + } + + @Override + public boolean hasTagCompound() { + return this.getDefinition().getTagCompound() != null; + } + + AEItemDef getDefinition() { + return this.def; + } + + private AEItemDef setDefinition(final AEItemDef def) { + this.def = def; + return def; + } } diff --git a/src/main/java/appeng/util/item/AESharedNBT.java b/src/main/java/appeng/util/item/AESharedNBT.java index 2dc14691..44df6942 100644 --- a/src/main/java/appeng/util/item/AESharedNBT.java +++ b/src/main/java/appeng/util/item/AESharedNBT.java @@ -18,6 +18,8 @@ package appeng.util.item; +import java.lang.ref.WeakReference; +import java.util.WeakHashMap; import appeng.api.AEApi; import appeng.api.features.IItemComparison; @@ -27,191 +29,166 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -import java.lang.ref.WeakReference; -import java.util.WeakHashMap; - - /* * this is used for the shared NBT Cache. */ -public class AESharedNBT extends NBTTagCompound implements IAETagCompound -{ +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 SharedSearchObject sso; + private int hash; + private IItemComparison comp; - /* - * Shared Tag Compound Cache. - */ - private static final WeakHashMap> SHARED_TAG_COMPOUND = new WeakHashMap>(); - private final Item item; - private final int meta; - private SharedSearchObject sso; - private int hash; - private IItemComparison comp; + private AESharedNBT(final Item itemID, final int damageValue) { + this.item = itemID; + this.meta = damageValue; + } - private AESharedNBT( final Item itemID, final int damageValue ) - { - this.item = itemID; - this.meta = damageValue; - } + public AESharedNBT(final int fakeValue) { + this.item = null; + this.meta = 0; + this.hash = fakeValue; + } - public AESharedNBT( final int fakeValue ) - { - this.item = null; - this.meta = 0; - this.hash = fakeValue; - } + /* + * Debug purposes. + */ + public static int sharedTagLoad() { + return SHARED_TAG_COMPOUND.size(); + } - /* - * Debug purposes. - */ - public static int sharedTagLoad() - { - return SHARED_TAG_COMPOUND.size(); - } + /* + * Returns an NBT Compound that is used for accelerating comparisons. + */ + static synchronized NBTTagCompound + getSharedTagCompound(final NBTTagCompound tagCompound, final ItemStack s) { + if (tagCompound.hasNoTags()) { + return null; + } - /* - * Returns an NBT Compound that is used for accelerating comparisons. - */ - static synchronized NBTTagCompound getSharedTagCompound( final NBTTagCompound tagCompound, final ItemStack s ) - { - if( tagCompound.hasNoTags() ) - { - return null; - } + final Item item = s.getItem(); + int meta = -1; + if (s.getItem() != null && s.isItemStackDamageable() && s.getHasSubtypes()) { + meta = s.getItemDamage(); + } - final Item item = s.getItem(); - int meta = -1; - if( s.getItem() != null && s.isItemStackDamageable() && s.getHasSubtypes() ) - { - meta = s.getItemDamage(); - } + if (isShared(tagCompound)) { + return tagCompound; + } - if( isShared( tagCompound ) ) - { - return tagCompound; - } + final SharedSearchObject sso = new SharedSearchObject(item, meta, tagCompound); - final SharedSearchObject sso = new SharedSearchObject( item, meta, tagCompound ); + final WeakReference c = SHARED_TAG_COMPOUND.get(sso); + if (c != null) { + final SharedSearchObject cg = c.get(); + if (cg != null) { + return cg.getShared(); // I don't think I really need to check this + } + // as its already certain to exist.. + } - final WeakReference c = SHARED_TAG_COMPOUND.get( sso ); - if( c != null ) - { - final SharedSearchObject cg = c.get(); - if( cg != null ) - { - return cg.getShared(); // I don't think I really need to check this - } - // as its already certain to exist.. - } + final AESharedNBT clone = AESharedNBT.createFromCompound(item, meta, tagCompound); + sso.setCompound((NBTTagCompound) sso.getCompound().copy()); // prevent + // modification + // of data based + // on original + // item. + sso.setShared(clone); + clone.sso = sso; - final AESharedNBT clone = AESharedNBT.createFromCompound( item, meta, tagCompound ); - sso.setCompound( (NBTTagCompound) sso.getCompound().copy() ); // prevent - // modification - // of data based - // on original - // item. - sso.setShared( clone ); - clone.sso = sso; + SHARED_TAG_COMPOUND.put(sso, new WeakReference(sso)); + return clone; + } - 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(final NBTTagCompound ta) { + return ta instanceof AESharedNBT; + } - /* - * returns true if the compound is part of the shared compound system ( and can thus be compared directly ). - */ - public static boolean isShared( final NBTTagCompound ta ) - { - return ta instanceof AESharedNBT; - } + private static AESharedNBT + createFromCompound(final Item itemID, final int damageValue, final NBTTagCompound c) { + final AESharedNBT x = new AESharedNBT(itemID, damageValue); - private static AESharedNBT createFromCompound( final Item itemID, final int damageValue, final NBTTagCompound c ) - { - final AESharedNBT x = new AESharedNBT( itemID, damageValue ); + // c.getTags() + for (final Object o : c.func_150296_c()) { + final String name = (String) o; + x.setTag(name, c.getTag(name).copy()); + } - // c.getTags() - for( final Object o : c.func_150296_c() ) - { - final String name = (String) o; - x.setTag( name, c.getTag( name ).copy() ); - } + x.hash = Platform.NBTOrderlessHash(c); - x.hash = Platform.NBTOrderlessHash( c ); + final ItemStack isc = new ItemStack(itemID, 1, damageValue); + isc.setTagCompound(c); + x.comp + = AEApi.instance().registries().specialComparison().getSpecialComparison(isc); - final ItemStack isc = new ItemStack( itemID, 1, damageValue ); - isc.setTagCompound( c ); - x.comp = AEApi.instance().registries().specialComparison().getSpecialComparison( isc ); + return x; + } - return x; - } + int getHash() { + return this.hash; + } - int getHash() - { - return this.hash; - } + @Override + public NBTTagCompound getNBTTagCompoundCopy() { + return (NBTTagCompound) this.copy(); + } - @Override - public NBTTagCompound getNBTTagCompoundCopy() - { - return (NBTTagCompound) this.copy(); - } + @Override + public IItemComparison getSpecialComparison() { + return this.comp; + } - @Override - public IItemComparison getSpecialComparison() - { - return this.comp; - } + @Override + public boolean equals(final Object par1Obj) { + if (par1Obj instanceof AESharedNBT) { + return this == par1Obj; + } + return super.equals(par1Obj); + } - @Override - public boolean equals( final Object par1Obj ) - { - if( par1Obj instanceof AESharedNBT ) - { - return this == par1Obj; - } - return super.equals( par1Obj ); - } + public boolean matches(final Item item, final int meta, final int orderlessHash) { + return item == this.item && this.meta == meta && this.hash == orderlessHash; + } - public boolean matches( final Item item, final int meta, final int orderlessHash ) - { - return item == this.item && this.meta == meta && this.hash == orderlessHash; - } + public boolean comparePreciseWithRegistry(final AESharedNBT tagCompound) { + if (this == tagCompound) { + return true; + } - public boolean comparePreciseWithRegistry( final AESharedNBT tagCompound ) - { - if( this == tagCompound ) - { - return true; - } + if (this.comp != null && tagCompound.comp != null) { + return this.comp.sameAsPrecise(tagCompound.comp); + } - if( this.comp != null && tagCompound.comp != null ) - { - return this.comp.sameAsPrecise( tagCompound.comp ); - } + return false; + } - return false; - } + public boolean compareFuzzyWithRegistry(final AESharedNBT tagCompound) { + if (this == tagCompound) { + return true; + } + if (tagCompound == null) { + return false; + } - public boolean compareFuzzyWithRegistry( final AESharedNBT tagCompound ) - { - if( this == tagCompound ) - { - return true; - } - if( tagCompound == null ) - { - return false; - } + if (this.comp == tagCompound.comp) { + return true; + } - if( this.comp == tagCompound.comp ) - { - return true; - } + if (this.comp != null) { + return this.comp.sameAsFuzzy(tagCompound.comp); + } - if( this.comp != null ) - { - return this.comp.sameAsFuzzy( tagCompound.comp ); - } - - return false; - } + return false; + } } diff --git a/src/main/java/appeng/util/item/AEStack.java b/src/main/java/appeng/util/item/AEStack.java index 1bdfe896..1b914d77 100644 --- a/src/main/java/appeng/util/item/AEStack.java +++ b/src/main/java/appeng/util/item/AEStack.java @@ -18,181 +18,146 @@ package appeng.util.item; +import java.io.IOException; import appeng.api.storage.data.IAEStack; import io.netty.buffer.ByteBuf; -import java.io.IOException; +public abstract class AEStack implements IAEStack { + private boolean isCraftable; + private long stackSize; + private long countRequestable; + static long getPacketValue(final byte type, final 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; + } -public abstract class AEStack implements IAEStack -{ + return tag.readLong(); + } - private boolean isCraftable; - private long stackSize; - private long countRequestable; + @Override + public long getStackSize() { + return this.stackSize; + } - static long getPacketValue( final byte type, final 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; - } + @Override + public StackType setStackSize(final long ss) { + this.stackSize = ss; + return (StackType) this; + } - return tag.readLong(); - } + @Override + public long getCountRequestable() { + return this.countRequestable; + } - @Override - public long getStackSize() - { - return this.stackSize; - } + @Override + public StackType setCountRequestable(final long countRequestable) { + this.countRequestable = countRequestable; + return (StackType) this; + } - @Override - public StackType setStackSize( final long ss ) - { - this.stackSize = ss; - return (StackType) this; - } + @Override + public boolean isCraftable() { + return this.isCraftable; + } - @Override - public long getCountRequestable() - { - return this.countRequestable; - } + @Override + public StackType setCraftable(final boolean isCraftable) { + this.isCraftable = isCraftable; + return (StackType) this; + } - @Override - public StackType setCountRequestable( final long countRequestable ) - { - this.countRequestable = countRequestable; - return (StackType) this; - } + @Override + public StackType reset() { + this.stackSize = 0; + // priority = Integer.MIN_VALUE; + this.setCountRequestable(0); + this.setCraftable(false); + return (StackType) this; + } - @Override - public boolean isCraftable() - { - return this.isCraftable; - } + @Override + public boolean isMeaningful() { + return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable; + } - @Override - public StackType setCraftable( final boolean isCraftable ) - { - this.isCraftable = isCraftable; - return (StackType) this; - } + @Override + public void incStackSize(final long i) { + this.stackSize += i; + } - @Override - public StackType reset() - { - this.stackSize = 0; - // priority = Integer.MIN_VALUE; - this.setCountRequestable( 0 ); - this.setCraftable( false ); - return (StackType) this; - } + @Override + public void decStackSize(final long i) { + this.stackSize -= i; + } - @Override - public boolean isMeaningful() - { - return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable; - } + @Override + public void incCountRequestable(final long i) { + this.countRequestable += i; + } - @Override - public void incStackSize( final long i ) - { - this.stackSize += i; - } + @Override + public void decCountRequestable(final long i) { + this.countRequestable -= i; + } - @Override - public void decStackSize( final long i ) - { - this.stackSize -= i; - } + @Override + public void writeToPacket(final ByteBuf i) throws IOException { + final 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); - @Override - public void incCountRequestable( final long i ) - { - this.countRequestable += i; - } + i.writeByte(mask); + this.writeIdentity(i); - @Override - public void decCountRequestable( final long i ) - { - this.countRequestable -= i; - } + this.readNBT(i); - @Override - public void writeToPacket( final ByteBuf i ) throws IOException - { - final 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 ); + // putPacketValue( i, priority ); + this.putPacketValue(i, this.stackSize); + this.putPacketValue(i, this.countRequestable); + } - i.writeByte( mask ); - this.writeIdentity( i ); + private byte getType(final long num) { + if (num <= 255) { + return 0; + } else if (num <= 65535) { + return 1; + } else if (num <= 4294967295L) { + return 2; + } else { + return 3; + } + } - this.readNBT( i ); + abstract boolean hasTagCompound(); - // putPacketValue( i, priority ); - this.putPacketValue( i, this.stackSize ); - this.putPacketValue( i, this.countRequestable ); - } + abstract void writeIdentity(ByteBuf i) throws IOException; - private byte getType( final long num ) - { - if( num <= 255 ) - { - return 0; - } - else if( num <= 65535 ) - { - return 1; - } - else if( num <= 4294967295L ) - { - return 2; - } - else - { - return 3; - } - } + abstract void readNBT(ByteBuf i) throws IOException; - abstract boolean hasTagCompound(); - - abstract void writeIdentity( ByteBuf i ) throws IOException; - - abstract void readNBT( ByteBuf i ) throws IOException; - - private void putPacketValue( final ByteBuf tag, final 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 ); - } - } + private void putPacketValue(final ByteBuf tag, final 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); + } + } } diff --git a/src/main/java/appeng/util/item/FluidList.java b/src/main/java/appeng/util/item/FluidList.java index 03810867..1d085eae 100644 --- a/src/main/java/appeng/util/item/FluidList.java +++ b/src/main/java/appeng/util/item/FluidList.java @@ -18,180 +18,157 @@ package appeng.util.item; +import java.util.*; import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; -import java.util.*; +public final class FluidList implements IItemList { + private final Map records + = new HashMap(); + @Override + public void add(final IAEFluidStack option) { + if (option == null) { + return; + } -public final class FluidList implements IItemList -{ + final IAEFluidStack st = this.getFluidRecord(option); - private final Map records = new HashMap(); + if (st != null) { + st.add(option); + return; + } - @Override - public void add( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + final IAEFluidStack opt = option.copy(); - final IAEFluidStack st = this.getFluidRecord( option ); + this.putFluidRecord(opt); + } - if( st != null ) - { - st.add( option ); - return; - } + @Override + public IAEFluidStack findPrecise(final IAEFluidStack fluidStack) { + if (fluidStack == null) { + return null; + } - final IAEFluidStack opt = option.copy(); + return this.getFluidRecord(fluidStack); + } - this.putFluidRecord( opt ); - } + @Override + public Collection + findFuzzy(final IAEFluidStack filter, final FuzzyMode fuzzy) { + if (filter == null) { + return Collections.emptyList(); + } - @Override - public IAEFluidStack findPrecise( final IAEFluidStack fluidStack ) - { - if( fluidStack == null ) - { - return null; - } + return Collections.singletonList(this.findPrecise(filter)); + } - return this.getFluidRecord( fluidStack ); - } + @Override + public boolean isEmpty() { + return !this.iterator().hasNext(); + } - @Override - public Collection findFuzzy( final IAEFluidStack filter, final FuzzyMode fuzzy ) - { - if( filter == null ) - { - return Collections.emptyList(); - } + @Override + public void addStorage(final IAEFluidStack option) { + if (option == null) { + return; + } - return Collections.singletonList( this.findPrecise( filter ) ); - } + final IAEFluidStack st = this.getFluidRecord(option); - @Override - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } + if (st != null) { + st.incStackSize(option.getStackSize()); + return; + } - @Override - public void addStorage( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + final IAEFluidStack opt = option.copy(); - final IAEFluidStack st = this.getFluidRecord( option ); + this.putFluidRecord(opt); + } - if( st != null ) - { - st.incStackSize( option.getStackSize() ); - return; - } + /* + * public synchronized void clean() { Iterator i = iterator(); while + * (i.hasNext()) { StackType AEI = i.next(); if ( !AEI.isMeaningful() ) i.remove(); } + * } + */ - final IAEFluidStack opt = option.copy(); + @Override + public void addCrafting(final IAEFluidStack option) { + if (option == null) { + return; + } - this.putFluidRecord( opt ); - } + final IAEFluidStack st = this.getFluidRecord(option); - /* - * public synchronized void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = - * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } - */ + if (st != null) { + st.setCraftable(true); + return; + } - @Override - public void addCrafting( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + final IAEFluidStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(true); - final IAEFluidStack st = this.getFluidRecord( option ); + this.putFluidRecord(opt); + } - if( st != null ) - { - st.setCraftable( true ); - return; - } + @Override + public void addRequestable(final IAEFluidStack option) { + if (option == null) { + return; + } - final IAEFluidStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( true ); + final IAEFluidStack st = this.getFluidRecord(option); - this.putFluidRecord( opt ); - } + if (st != null) { + st.setCountRequestable( + st.getCountRequestable() + option.getCountRequestable() + ); + return; + } - @Override - public void addRequestable( final IAEFluidStack option ) - { - if( option == null ) - { - return; - } + final IAEFluidStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(false); + opt.setCountRequestable(option.getCountRequestable()); - final IAEFluidStack st = this.getFluidRecord( option ); + this.putFluidRecord(opt); + } - if( st != null ) - { - st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); - return; - } + @Override + public IAEFluidStack getFirstItem() { + for (final IAEFluidStack stackType : this) { + return stackType; + } - final IAEFluidStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( false ); - opt.setCountRequestable( option.getCountRequestable() ); + return null; + } - this.putFluidRecord( opt ); - } + @Override + public int size() { + return this.records.values().size(); + } - @Override - public IAEFluidStack getFirstItem() - { - for( final IAEFluidStack stackType : this ) - { - return stackType; - } + @Override + public Iterator iterator() { + return new MeaningfulFluidIterator(this.records.values().iterator() + ); + } - return null; - } + @Override + public void resetStatus() { + for (final IAEFluidStack i : this) { + i.reset(); + } + } - @Override - public int size() - { - return this.records.values().size(); - } + private IAEFluidStack getFluidRecord(final IAEFluidStack fluid) { + return this.records.get(fluid); + } - @Override - public Iterator iterator() - { - return new MeaningfulFluidIterator( this.records.values().iterator() ); - } - - @Override - public void resetStatus() - { - for( final IAEFluidStack i : this ) - { - i.reset(); - } - } - - private IAEFluidStack getFluidRecord( final IAEFluidStack fluid ) - { - return this.records.get( fluid ); - } - - private IAEFluidStack putFluidRecord( final IAEFluidStack fluid ) - { - return this.records.put( fluid, fluid ); - } + private IAEFluidStack putFluidRecord(final IAEFluidStack fluid) { + return this.records.put(fluid, fluid); + } } diff --git a/src/main/java/appeng/util/item/ItemList.java b/src/main/java/appeng/util/item/ItemList.java index 6a8c7e08..8701a7ea 100644 --- a/src/main/java/appeng/util/item/ItemList.java +++ b/src/main/java/appeng/util/item/ItemList.java @@ -18,210 +18,190 @@ package appeng.util.item; +import java.util.*; +import java.util.concurrent.ConcurrentSkipListMap; import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; -import java.util.concurrent.ConcurrentSkipListMap; +public final class ItemList implements IItemList { + private final NavigableMap records + = new ConcurrentSkipListMap(); + @Override + public void add(final IAEItemStack option) { + if (option == null) { + return; + } -public final class ItemList implements IItemList -{ + final IAEItemStack st = this.records.get(option); - private final NavigableMap records = new ConcurrentSkipListMap(); + if (st != null) { + st.add(option); + return; + } - @Override - public void add( final IAEItemStack option ) - { - if( option == null ) - { - return; - } + final IAEItemStack opt = option.copy(); - final IAEItemStack st = this.records.get( option ); + this.putItemRecord(opt); + } - if( st != null ) - { - st.add( option ); - return; - } + @Override + public IAEItemStack findPrecise(final IAEItemStack itemStack) { + if (itemStack == null) { + return null; + } - final IAEItemStack opt = option.copy(); + return this.records.get(itemStack); + } - this.putItemRecord( opt ); - } + @Override + public Collection + findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) { + if (filter == null) { + return Collections.emptyList(); + } - @Override - public IAEItemStack findPrecise( final IAEItemStack itemStack ) - { - if( itemStack == null ) - { - return null; - } + final AEItemStack ais = (AEItemStack) filter; - return this.records.get( itemStack ); - } + if (ais.isOre()) { + final OreReference or = ais.getDefinition().getIsOre(); - @Override - public Collection findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy ) - { - if( filter == null ) - { - return Collections.emptyList(); - } + if (or.getAEEquivalents().size() == 1) { + final IAEItemStack is = or.getAEEquivalents().get(0); - final AEItemStack ais = (AEItemStack) filter; + return this.findFuzzyDamage( + (AEItemStack) is, + fuzzy, + is.getItemDamage() == OreDictionary.WILDCARD_VALUE + ); + } else { + final Collection output = new LinkedList(); - if( ais.isOre() ) - { - final OreReference or = ais.getDefinition().getIsOre(); + for (final IAEItemStack is : or.getAEEquivalents()) { + output.addAll(this.findFuzzyDamage( + (AEItemStack) is, + fuzzy, + is.getItemDamage() == OreDictionary.WILDCARD_VALUE + )); + } - if( or.getAEEquivalents().size() == 1 ) - { - final IAEItemStack is = or.getAEEquivalents().get( 0 ); + return output; + } + } - return this.findFuzzyDamage( (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ); - } - else - { - final Collection output = new LinkedList(); + return this.findFuzzyDamage(ais, fuzzy, false); + } - for( final IAEItemStack is : or.getAEEquivalents() ) - { - output.addAll( this.findFuzzyDamage( (AEItemStack) is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) ); - } + @Override + public boolean isEmpty() { + return !this.iterator().hasNext(); + } - return output; - } - } + @Override + public void addStorage(final IAEItemStack option) { + if (option == null) { + return; + } - return this.findFuzzyDamage( ais, fuzzy, false ); - } + final IAEItemStack st = this.records.get(option); - @Override - public boolean isEmpty() - { - return !this.iterator().hasNext(); - } + if (st != null) { + st.incStackSize(option.getStackSize()); + return; + } - @Override - public void addStorage( final IAEItemStack option ) - { - if( option == null ) - { - return; - } + final IAEItemStack opt = option.copy(); - final IAEItemStack st = this.records.get( option ); + this.putItemRecord(opt); + } - if( st != null ) - { - st.incStackSize( option.getStackSize() ); - return; - } + /* + * public void clean() { Iterator i = iterator(); while (i.hasNext()) { + * StackType AEI = i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } + */ - final IAEItemStack opt = option.copy(); + @Override + public void addCrafting(final IAEItemStack option) { + if (option == null) { + return; + } - this.putItemRecord( opt ); - } + final IAEItemStack st = this.records.get(option); - /* - * public void clean() { Iterator i = iterator(); while (i.hasNext()) { StackType AEI = - * i.next(); if ( !AEI.isMeaningful() ) i.remove(); } } - */ + if (st != null) { + st.setCraftable(true); + return; + } - @Override - public void addCrafting( final IAEItemStack option ) - { - if( option == null ) - { - return; - } + final IAEItemStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(true); - final IAEItemStack st = this.records.get( option ); + this.putItemRecord(opt); + } - if( st != null ) - { - st.setCraftable( true ); - return; - } + @Override + public void addRequestable(final IAEItemStack option) { + if (option == null) { + return; + } - final IAEItemStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( true ); + final IAEItemStack st = this.records.get(option); - this.putItemRecord( opt ); - } + if (st != null) { + st.setCountRequestable( + st.getCountRequestable() + option.getCountRequestable() + ); + return; + } - @Override - public void addRequestable( final IAEItemStack option ) - { - if( option == null ) - { - return; - } + final IAEItemStack opt = option.copy(); + opt.setStackSize(0); + opt.setCraftable(false); + opt.setCountRequestable(option.getCountRequestable()); - final IAEItemStack st = this.records.get( option ); + this.putItemRecord(opt); + } - if( st != null ) - { - st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() ); - return; - } + @Override + public IAEItemStack getFirstItem() { + for (final IAEItemStack stackType : this) { + return stackType; + } - final IAEItemStack opt = option.copy(); - opt.setStackSize( 0 ); - opt.setCraftable( false ); - opt.setCountRequestable( option.getCountRequestable() ); + return null; + } - this.putItemRecord( opt ); - } + @Override + public int size() { + return this.records.size(); + } - @Override - public IAEItemStack getFirstItem() - { - for( final IAEItemStack stackType : this ) - { - return stackType; - } + @Override + public Iterator iterator() { + return new MeaningfulItemIterator(this.records.values().iterator()); + } - return null; - } + @Override + public void resetStatus() { + for (final IAEItemStack i : this) { + i.reset(); + } + } - @Override - public int size() - { - return this.records.size(); - } + private IAEItemStack putItemRecord(final IAEItemStack itemStack) { + return this.records.put(itemStack, itemStack); + } - @Override - public Iterator iterator() - { - return new MeaningfulItemIterator( this.records.values().iterator() ); - } + private Collection findFuzzyDamage( + final AEItemStack filter, final FuzzyMode fuzzy, final boolean ignoreMeta + ) { + final IAEItemStack low = filter.getLow(fuzzy, ignoreMeta); + final IAEItemStack high = filter.getHigh(fuzzy, ignoreMeta); - @Override - public void resetStatus() - { - for( final IAEItemStack i : this ) - { - i.reset(); - } - } - - private IAEItemStack putItemRecord( final IAEItemStack itemStack ) - { - return this.records.put( itemStack, itemStack ); - } - - private Collection findFuzzyDamage( final AEItemStack filter, final FuzzyMode fuzzy, final boolean ignoreMeta ) - { - final IAEItemStack low = filter.getLow( fuzzy, ignoreMeta ); - final IAEItemStack high = filter.getHigh( fuzzy, ignoreMeta ); - - return this.records.subMap( low, true, high, true ).descendingMap().values(); - } + return this.records.subMap(low, true, high, true).descendingMap().values(); + } } diff --git a/src/main/java/appeng/util/item/ItemModList.java b/src/main/java/appeng/util/item/ItemModList.java index e05303ef..6dfddd79 100644 --- a/src/main/java/appeng/util/item/ItemModList.java +++ b/src/main/java/appeng/util/item/ItemModList.java @@ -18,69 +18,55 @@ package appeng.util.item; +import java.util.Collection; import appeng.api.AEApi; import appeng.api.config.FuzzyMode; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemContainer; -import java.util.Collection; +public class ItemModList implements IItemContainer { + private final IItemContainer backingStore; + private final IItemContainer overrides + = AEApi.instance().storage().createItemList(); + public ItemModList(final IItemContainer backend) { + this.backingStore = backend; + } -public class ItemModList implements IItemContainer -{ + @Override + public void add(final IAEItemStack option) { + IAEItemStack over = this.overrides.findPrecise(option); + if (over == null) { + over = this.backingStore.findPrecise(option); + if (over == null) { + this.overrides.add(option); + } else { + option.add(over); + this.overrides.add(option); + } + } else { + this.overrides.add(option); + } + } - private final IItemContainer backingStore; - private final IItemContainer overrides = AEApi.instance().storage().createItemList(); + @Override + public IAEItemStack findPrecise(final IAEItemStack i) { + final IAEItemStack over = this.overrides.findPrecise(i); + if (over == null) { + return this.backingStore.findPrecise(i); + } + return over; + } - public ItemModList( final IItemContainer backend ) - { - this.backingStore = backend; - } + @Override + public Collection + findFuzzy(final IAEItemStack input, final FuzzyMode fuzzy) { + return this.overrides.findFuzzy(input, fuzzy); + } - @Override - public void add( final IAEItemStack option ) - { - IAEItemStack over = this.overrides.findPrecise( option ); - if( over == null ) - { - over = this.backingStore.findPrecise( option ); - if( over == null ) - { - this.overrides.add( option ); - } - else - { - option.add( over ); - this.overrides.add( option ); - } - } - else - { - this.overrides.add( option ); - } - } - - @Override - public IAEItemStack findPrecise( final IAEItemStack i ) - { - final IAEItemStack over = this.overrides.findPrecise( i ); - if( over == null ) - { - return this.backingStore.findPrecise( i ); - } - return over; - } - - @Override - public Collection findFuzzy( final IAEItemStack input, final FuzzyMode fuzzy ) - { - return this.overrides.findFuzzy( input, fuzzy ); - } - - @Override - public boolean isEmpty() - { - return this.overrides.isEmpty() && this.backingStore.isEmpty(); - } + @Override + public boolean isEmpty() { + return this.overrides.isEmpty() && this.backingStore.isEmpty(); + } } diff --git a/src/main/java/appeng/util/item/MeaningfulFluidIterator.java b/src/main/java/appeng/util/item/MeaningfulFluidIterator.java index cc3e6678..8da9a370 100644 --- a/src/main/java/appeng/util/item/MeaningfulFluidIterator.java +++ b/src/main/java/appeng/util/item/MeaningfulFluidIterator.java @@ -18,58 +18,45 @@ package appeng.util.item; - -import appeng.api.storage.data.IAEStack; - import java.util.Iterator; import java.util.NoSuchElementException; +import appeng.api.storage.data.IAEStack; -public class MeaningfulFluidIterator implements Iterator -{ +public class MeaningfulFluidIterator implements Iterator { + private final Iterator parent; + private T next; - private final Iterator parent; - private T next; + public MeaningfulFluidIterator(final Iterator iterator) { + this.parent = iterator; + } - public MeaningfulFluidIterator( final Iterator iterator ) - { - this.parent = iterator; - } + @Override + public boolean hasNext() { + while (this.parent.hasNext()) { + this.next = this.parent.next(); + if (this.next.isMeaningful()) { + return true; + } else { + this.parent.remove(); // self cleaning :3 + } + } - @Override - public boolean hasNext() - { - while( this.parent.hasNext() ) - { - this.next = this.parent.next(); - if( this.next.isMeaningful() ) - { - return true; - } - else - { - this.parent.remove(); // self cleaning :3 - } - } + this.next = null; + return false; + } - this.next = null; - return false; - } + @Override + public T next() { + if (this.next == null) { + throw new NoSuchElementException(); + } - @Override - public T next() - { - if( this.next == null ) - { - throw new NoSuchElementException(); - } + return this.next; + } - return this.next; - } - - @Override - public void remove() - { - this.parent.remove(); - } + @Override + public void remove() { + this.parent.remove(); + } } diff --git a/src/main/java/appeng/util/item/MeaningfulItemIterator.java b/src/main/java/appeng/util/item/MeaningfulItemIterator.java index d87d9039..92f1e128 100644 --- a/src/main/java/appeng/util/item/MeaningfulItemIterator.java +++ b/src/main/java/appeng/util/item/MeaningfulItemIterator.java @@ -18,59 +18,46 @@ package appeng.util.item; - -import appeng.api.storage.data.IAEItemStack; - import java.util.Iterator; import java.util.NoSuchElementException; +import appeng.api.storage.data.IAEItemStack; -public class MeaningfulItemIterator implements Iterator -{ +public class MeaningfulItemIterator implements Iterator { + private final Iterator parent; + private T next; - private final Iterator parent; - private T next; + public MeaningfulItemIterator(final Iterator iterator) { + this.parent = iterator; + } - public MeaningfulItemIterator( final Iterator iterator ) - { - this.parent = iterator; - } + @Override + public boolean hasNext() { + while (this.parent.hasNext()) { + this.next = this.parent.next(); - @Override - public boolean hasNext() - { - while( this.parent.hasNext() ) - { - this.next = this.parent.next(); + if (this.next.isMeaningful()) { + return true; + } else { + this.parent.remove(); // self cleaning :3 + } + } - if( this.next.isMeaningful() ) - { - return true; - } - else - { - this.parent.remove(); // self cleaning :3 - } - } + this.next = null; + return false; + } - this.next = null; - return false; - } + @Override + public T next() { + if (this.next == null) { + throw new NoSuchElementException(); + } - @Override - public T next() - { - if( this.next == null ) - { - throw new NoSuchElementException(); - } + return this.next; + } - return this.next; - } - - @Override - public void remove() - { - this.parent.remove(); - } + @Override + public void remove() { + this.parent.remove(); + } } diff --git a/src/main/java/appeng/util/item/OreHelper.java b/src/main/java/appeng/util/item/OreHelper.java index bb499de8..4edd323d 100644 --- a/src/main/java/appeng/util/item/OreHelper.java +++ b/src/main/java/appeng/util/item/OreHelper.java @@ -18,6 +18,7 @@ package appeng.util.item; +import java.util.*; import appeng.api.storage.data.IAEItemStack; import com.google.common.cache.CacheBuilder; @@ -27,190 +28,153 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; -import java.util.*; +public class OreHelper { + public static final OreHelper INSTANCE = new OreHelper(); + /** + * A local cache to speed up OreDictionary lookups. + */ + private final LoadingCache> oreDictCache + = CacheBuilder.newBuilder().build(new CacheLoader>() { + @Override + public List load(final String oreName) { + return OreDictionary.getOres(oreName); + } + }); -public class OreHelper -{ + private final Map references + = new HashMap(); - public static final OreHelper INSTANCE = new 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(final ItemStack itemStack) { + final ItemRef ir = new ItemRef(itemStack); - /** - * A local cache to speed up OreDictionary lookups. - */ - private final LoadingCache> oreDictCache = CacheBuilder.newBuilder().build( new CacheLoader>() - { - @Override - public List load( final String oreName ) - { - return OreDictionary.getOres( oreName ); - } - } ); + if (!this.references.containsKey(ir)) { + final OreReference ref = new OreReference(); + final Collection ores = ref.getOres(); + final Collection set = ref.getEquivalents(); - private final Map references = new HashMap(); + final Set toAdd = new HashSet(); - /** - * 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( final ItemStack itemStack ) - { - final ItemRef ir = new ItemRef( itemStack ); + for (final String ore : OreDictionary.getOreNames()) { + // skip ore if it is a match already or null. + if (ore == null || toAdd.contains(ore)) { + continue; + } - if( !this.references.containsKey( ir ) ) - { - final OreReference ref = new OreReference(); - final Collection ores = ref.getOres(); - final Collection set = ref.getEquivalents(); + for (final ItemStack oreItem : this.oreDictCache.getUnchecked(ore)) { + if (OreDictionary.itemMatches(oreItem, itemStack, false)) { + toAdd.add(ore); + break; + } + } + } - final Set toAdd = new HashSet(); + for (final String ore : toAdd) { + set.add(ore); + ores.add(OreDictionary.getOreID(ore)); + } - for( final String ore : OreDictionary.getOreNames() ) - { - // skip ore if it is a match already or null. - if( ore == null || toAdd.contains( ore ) ) - { - continue; - } + if (!set.isEmpty()) { + this.references.put(ir, ref); + } else { + this.references.put(ir, null); + } + } - for( final ItemStack oreItem : this.oreDictCache.getUnchecked( ore ) ) - { - if( OreDictionary.itemMatches( oreItem, itemStack, false ) ) - { - toAdd.add( ore ); - break; - } - } - } + return this.references.get(ir); + } - for( final String ore : toAdd ) - { - set.add( ore ); - ores.add( OreDictionary.getOreID( ore ) ); - } + boolean sameOre(final AEItemStack aeItemStack, final IAEItemStack is) { + final OreReference a = aeItemStack.getDefinition().getIsOre(); + final OreReference b = aeItemStack.getDefinition().getIsOre(); - if( !set.isEmpty() ) - { - this.references.put( ir, ref ); - } - else - { - this.references.put( ir, null ); - } - } + return this.sameOre(a, b); + } - return this.references.get( ir ); - } + public boolean sameOre(final OreReference a, final OreReference b) { + if (a == null || b == null) { + return false; + } - boolean sameOre( final AEItemStack aeItemStack, final IAEItemStack is ) - { - final OreReference a = aeItemStack.getDefinition().getIsOre(); - final OreReference b = aeItemStack.getDefinition().getIsOre(); + if (a == b) { + return true; + } - return this.sameOre( a, b ); - } + final Collection bOres = b.getOres(); + for (final Integer ore : a.getOres()) { + if (bOres.contains(ore)) { + return true; + } + } - public boolean sameOre( final OreReference a, final OreReference b ) - { - if( a == null || b == null ) - { - return false; - } + return false; + } - if( a == b ) - { - return true; - } + boolean sameOre(final AEItemStack aeItemStack, final ItemStack o) { + final OreReference a = aeItemStack.getDefinition().getIsOre(); + if (a == null) { + return false; + } - final Collection bOres = b.getOres(); - for( final Integer ore : a.getOres() ) - { - if( bOres.contains( ore ) ) - { - return true; - } - } + for (final String oreName : a.getEquivalents()) { + for (final ItemStack oreItem : this.oreDictCache.getUnchecked(oreName)) { + if (OreDictionary.itemMatches(oreItem, o, false)) { + return true; + } + } + } - return false; - } + return false; + } - boolean sameOre( final AEItemStack aeItemStack, final ItemStack o ) - { - final OreReference a = aeItemStack.getDefinition().getIsOre(); - if( a == null ) - { - return false; - } + List getCachedOres(final String oreName) { + return this.oreDictCache.getUnchecked(oreName); + } - for( final String oreName : a.getEquivalents() ) - { - for( final ItemStack oreItem : this.oreDictCache.getUnchecked( oreName ) ) - { - if( OreDictionary.itemMatches( oreItem, o, false ) ) - { - return true; - } - } - } + private static class ItemRef { + private final Item ref; + private final int damage; + private final int hash; - return false; - } + ItemRef(final ItemStack stack) { + this.ref = stack.getItem(); - List getCachedOres( final String oreName ) - { - return this.oreDictCache.getUnchecked( oreName ); - } + if (stack.getItem().isDamageable()) { + this.damage = 0; // IGNORED + } else { + this.damage = stack.getItemDamage(); // might be important... + } - private static class ItemRef - { + this.hash = this.ref.hashCode() ^ this.damage; + } - private final Item ref; - private final int damage; - private final int hash; + @Override + public int hashCode() { + return this.hash; + } - ItemRef( final ItemStack stack ) - { - this.ref = stack.getItem(); + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final ItemRef other = (ItemRef) obj; + return this.damage == other.damage && this.ref == other.ref; + } - if( stack.getItem().isDamageable() ) - { - this.damage = 0; // IGNORED - } - else - { - this.damage = stack.getItemDamage(); // might be important... - } - - this.hash = this.ref.hashCode() ^ this.damage; - } - - @Override - public int hashCode() - { - return this.hash; - } - - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final 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 + ']'; - } - } + @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 cba88810..eff7f7db 100644 --- a/src/main/java/appeng/util/item/OreReference.java +++ b/src/main/java/appeng/util/item/OreReference.java @@ -18,49 +18,38 @@ package appeng.util.item; +import java.util.*; import appeng.api.storage.data.IAEItemStack; import net.minecraft.item.ItemStack; -import java.util.*; +public class OreReference { + private final List otherOptions = new LinkedList(); + private final Set ores = new HashSet(); + private List aeOtherOptions = null; + Collection getEquivalents() { + return this.otherOptions; + } -public class OreReference -{ + List getAEEquivalents() { + if (this.aeOtherOptions == null) { + this.aeOtherOptions = new ArrayList(this.otherOptions.size()); - private final List otherOptions = new LinkedList(); - private final Set ores = new HashSet(); - private List aeOtherOptions = null; + // SUMMON AE STACKS! + for (final String oreName : this.otherOptions) { + for (final ItemStack is : OreHelper.INSTANCE.getCachedOres(oreName)) { + if (is.getItem() != null) { + this.aeOtherOptions.add(AEItemStack.create(is)); + } + } + } + } - Collection getEquivalents() - { - return this.otherOptions; - } + return this.aeOtherOptions; + } - List getAEEquivalents() - { - if( this.aeOtherOptions == null ) - { - this.aeOtherOptions = new ArrayList( this.otherOptions.size() ); - - // SUMMON AE STACKS! - for( final String oreName : this.otherOptions ) - { - for( final ItemStack is : OreHelper.INSTANCE.getCachedOres( oreName ) ) - { - if( is.getItem() != null ) - { - this.aeOtherOptions.add( AEItemStack.create( is ) ); - } - } - } - } - - return this.aeOtherOptions; - } - - Collection getOres() - { - return this.ores; - } + Collection getOres() { + return this.ores; + } } diff --git a/src/main/java/appeng/util/item/SharedSearchObject.java b/src/main/java/appeng/util/item/SharedSearchObject.java index 26610d8f..b29fba60 100644 --- a/src/main/java/appeng/util/item/SharedSearchObject.java +++ b/src/main/java/appeng/util/item/SharedSearchObject.java @@ -18,69 +18,58 @@ package appeng.util.item; - import appeng.util.Platform; import net.minecraft.item.Item; import net.minecraft.nbt.NBTTagCompound; +public class SharedSearchObject { + private final int def; + private final int hash; + private AESharedNBT shared; + private NBTTagCompound compound; -public class SharedSearchObject -{ + public SharedSearchObject( + final Item itemID, final int damageValue, final NBTTagCompound tagCompound + ) { + this.def = (damageValue << Platform.DEF_OFFSET) + | Item.itemRegistry.getIDForObject(itemID); + this.hash = Platform.NBTOrderlessHash(tagCompound); + this.setCompound(tagCompound); + } - private final int def; - private final int hash; - private AESharedNBT shared; - private NBTTagCompound compound; + @Override + public int hashCode() { + return this.def ^ this.hash; + } - public SharedSearchObject( final Item itemID, final int damageValue, final NBTTagCompound tagCompound ) - { - this.def = ( damageValue << Platform.DEF_OFFSET ) | Item.itemRegistry.getIDForObject( itemID ); - this.hash = Platform.NBTOrderlessHash( tagCompound ); - this.setCompound( tagCompound ); - } + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this.getClass() != obj.getClass()) { + return false; + } + final SharedSearchObject other = (SharedSearchObject) obj; + if (this.def == other.def && this.hash == other.hash) { + return Platform.NBTEqualityTest(this.getCompound(), other.getCompound()); + } + return false; + } - @Override - public int hashCode() - { - return this.def ^ this.hash; - } + AESharedNBT getShared() { + return this.shared; + } - @Override - public boolean equals( final Object obj ) - { - if( obj == null ) - { - return false; - } - if( this.getClass() != obj.getClass() ) - { - return false; - } - final SharedSearchObject other = (SharedSearchObject) obj; - if( this.def == other.def && this.hash == other.hash ) - { - return Platform.NBTEqualityTest( this.getCompound(), other.getCompound() ); - } - return false; - } + void setShared(final AESharedNBT shared) { + this.shared = shared; + } - AESharedNBT getShared() - { - return this.shared; - } + NBTTagCompound getCompound() { + return this.compound; + } - void setShared( final AESharedNBT shared ) - { - this.shared = shared; - } - - NBTTagCompound getCompound() - { - return this.compound; - } - - void setCompound( final NBTTagCompound compound ) - { - this.compound = compound; - } + void setCompound(final NBTTagCompound compound) { + this.compound = compound; + } } diff --git a/src/main/java/appeng/util/iterators/AEInvIterator.java b/src/main/java/appeng/util/iterators/AEInvIterator.java index 6bd1c96c..73c228a3 100644 --- a/src/main/java/appeng/util/iterators/AEInvIterator.java +++ b/src/main/java/appeng/util/iterators/AEInvIterator.java @@ -18,45 +18,38 @@ package appeng.util.iterators; +import java.util.Iterator; import appeng.api.storage.data.IAEItemStack; import appeng.tile.inventory.AppEngInternalAEInventory; -import java.util.Iterator; +public final class AEInvIterator implements Iterator { + private final AppEngInternalAEInventory inventory; + private final int size; + private int counter = 0; -public final class AEInvIterator implements Iterator -{ - private final AppEngInternalAEInventory inventory; - private final int size; + public AEInvIterator(final AppEngInternalAEInventory inventory) { + this.inventory = inventory; + this.size = this.inventory.getSizeInventory(); + } - private int counter = 0; + @Override + public boolean hasNext() { + return this.counter < this.size; + } - public AEInvIterator( final AppEngInternalAEInventory inventory ) - { - this.inventory = inventory; - this.size = this.inventory.getSizeInventory(); - } + @Override + public IAEItemStack next() { + final IAEItemStack result = this.inventory.getAEStackInSlot(this.counter); - @Override - public boolean hasNext() - { - return this.counter < this.size; - } + this.counter++; - @Override - public IAEItemStack next() - { - final IAEItemStack result = this.inventory.getAEStackInSlot( this.counter ); + return result; + } - this.counter++; - - return result; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/ChainedIterator.java b/src/main/java/appeng/util/iterators/ChainedIterator.java index 93f3769f..b2934def 100644 --- a/src/main/java/appeng/util/iterators/ChainedIterator.java +++ b/src/main/java/appeng/util/iterators/ChainedIterator.java @@ -18,38 +18,31 @@ package appeng.util.iterators; - import java.util.Iterator; +public final class ChainedIterator implements Iterator { + private final T[] list; -public final class ChainedIterator implements Iterator -{ - private final T[] list; + private int offset = 0; - private int offset = 0; + public ChainedIterator(final T... list) { + this.list = list; + } - public ChainedIterator( final T... list ) - { - this.list = list; - } + @Override + public boolean hasNext() { + return this.offset < this.list.length; + } - @Override - public boolean hasNext() - { - return this.offset < this.list.length; - } + @Override + public T next() { + final T result = this.list[this.offset]; + this.offset++; + return result; + } - @Override - public T next() - { - final T result = this.list[this.offset]; - this.offset++; - return result; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/InvIterator.java b/src/main/java/appeng/util/iterators/InvIterator.java index 10d246ef..50db0286 100644 --- a/src/main/java/appeng/util/iterators/InvIterator.java +++ b/src/main/java/appeng/util/iterators/InvIterator.java @@ -18,44 +18,37 @@ package appeng.util.iterators; +import java.util.Iterator; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public final class InvIterator implements Iterator { + private final IInventory inventory; + private final int size; + private int counter = 0; -public final class InvIterator implements Iterator -{ - private final IInventory inventory; - private final int size; + public InvIterator(final IInventory inventory) { + this.inventory = inventory; + this.size = this.inventory.getSizeInventory(); + } - private int counter = 0; + @Override + public boolean hasNext() { + return this.counter < this.size; + } - public InvIterator( final IInventory inventory ) - { - this.inventory = inventory; - this.size = this.inventory.getSizeInventory(); - } + @Override + public ItemStack next() { + final ItemStack result = this.inventory.getStackInSlot(this.counter); + this.counter++; - @Override - public boolean hasNext() - { - return this.counter < this.size; - } + return result; + } - @Override - public ItemStack next() - { - final ItemStack result = this.inventory.getStackInSlot( this.counter ); - this.counter++; - - return result; - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/NullIterator.java b/src/main/java/appeng/util/iterators/NullIterator.java index 3ce3edcc..a2040eba 100644 --- a/src/main/java/appeng/util/iterators/NullIterator.java +++ b/src/main/java/appeng/util/iterators/NullIterator.java @@ -18,28 +18,19 @@ package appeng.util.iterators; - import java.util.Iterator; +public class NullIterator implements Iterator { + @Override + public boolean hasNext() { + return false; + } -public class NullIterator implements Iterator -{ + @Override + public T next() { + return null; + } - @Override - public boolean hasNext() - { - return false; - } - - @Override - public T next() - { - return null; - } - - @Override - public void remove() - { - - } + @Override + public void remove() {} } diff --git a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java index 8d2f0a6c..a845e7ce 100644 --- a/src/main/java/appeng/util/iterators/ProxyNodeIterator.java +++ b/src/main/java/appeng/util/iterators/ProxyNodeIterator.java @@ -18,39 +18,32 @@ package appeng.util.iterators; +import java.util.Iterator; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Iterator; +public final class ProxyNodeIterator implements Iterator { + private final Iterator hosts; + public ProxyNodeIterator(final Iterator hosts) { + this.hosts = hosts; + } -public final class ProxyNodeIterator implements Iterator -{ - private final Iterator hosts; + @Override + public boolean hasNext() { + return this.hosts.hasNext(); + } - public ProxyNodeIterator( final Iterator hosts ) - { - this.hosts = hosts; - } + @Override + public IGridNode next() { + final IGridHost host = this.hosts.next(); + return host.getGridNode(ForgeDirection.UNKNOWN); + } - @Override - public boolean hasNext() - { - return this.hosts.hasNext(); - } - - @Override - public IGridNode next() - { - final IGridHost host = this.hosts.next(); - return host.getGridNode( ForgeDirection.UNKNOWN ); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } + @Override + public void remove() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/iterators/StackToSlotIterator.java b/src/main/java/appeng/util/iterators/StackToSlotIterator.java index b44e143d..d4c0bdab 100644 --- a/src/main/java/appeng/util/iterators/StackToSlotIterator.java +++ b/src/main/java/appeng/util/iterators/StackToSlotIterator.java @@ -18,43 +18,35 @@ package appeng.util.iterators; +import java.util.Iterator; import appeng.util.inv.ItemSlot; import net.minecraft.item.ItemStack; -import java.util.Iterator; +public class StackToSlotIterator implements Iterator { + private final ItemSlot iss = new ItemSlot(); + private final Iterator is; + private int x = 0; + public StackToSlotIterator(final Iterator is) { + this.is = is; + } -public class StackToSlotIterator implements Iterator -{ + @Override + public boolean hasNext() { + return this.is.hasNext(); + } - private final ItemSlot iss = new ItemSlot(); - private final Iterator is; - private int x = 0; + @Override + public ItemSlot next() { + this.iss.setSlot(this.x); + this.x++; + this.iss.setItemStack(this.is.next()); + return this.iss; + } - public StackToSlotIterator( final Iterator is ) - { - this.is = is; - } - - @Override - public boolean hasNext() - { - return this.is.hasNext(); - } - - @Override - public ItemSlot next() - { - this.iss.setSlot( this.x ); - this.x++; - this.iss.setItemStack( this.is.next() ); - return this.iss; - } - - @Override - public void remove() - { - // uhh no. - } + @Override + public void remove() { + // uhh no. + } } diff --git a/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java b/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java index 24598fad..fbaddea2 100644 --- a/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/DefaultPriorityList.java @@ -18,33 +18,26 @@ package appeng.util.prioitylist; - -import appeng.api.storage.data.IAEStack; - import java.util.ArrayList; import java.util.List; +import appeng.api.storage.data.IAEStack; -public class DefaultPriorityList> implements IPartitionList -{ +public class DefaultPriorityList> implements IPartitionList { + private static final List NULL_LIST = new ArrayList(); - private static final List NULL_LIST = new ArrayList(); + @Override + public boolean isListed(final T input) { + return false; + } - @Override - public boolean isListed( final T input ) - { - return false; - } + @Override + public boolean isEmpty() { + return true; + } - @Override - public boolean isEmpty() - { - return true; - } - - @Override - public Iterable getItems() - { - return NULL_LIST; - } + @Override + public Iterable getItems() { + return NULL_LIST; + } } diff --git a/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java b/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java index a2191a36..0e273e76 100644 --- a/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/FuzzyPriorityList.java @@ -18,42 +18,34 @@ 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; -import java.util.Collection; +public class FuzzyPriorityList> implements IPartitionList { + private final IItemList list; + private final FuzzyMode mode; + public FuzzyPriorityList(final IItemList in, final FuzzyMode mode) { + this.list = in; + this.mode = mode; + } -public class FuzzyPriorityList> implements IPartitionList -{ + @Override + public boolean isListed(final T input) { + final Collection out = this.list.findFuzzy(input, this.mode); + return out != null && !out.isEmpty(); + } - private final IItemList list; - private final FuzzyMode mode; + @Override + public boolean isEmpty() { + return this.list.isEmpty(); + } - public FuzzyPriorityList( final IItemList in, final FuzzyMode mode ) - { - this.list = in; - this.mode = mode; - } - - @Override - public boolean isListed( final T input ) - { - final Collection out = this.list.findFuzzy( input, this.mode ); - return out != null && !out.isEmpty(); - } - - @Override - public boolean isEmpty() - { - return this.list.isEmpty(); - } - - @Override - public Iterable getItems() - { - return this.list; - } + @Override + public Iterable getItems() { + return this.list; + } } diff --git a/src/main/java/appeng/util/prioitylist/IPartitionList.java b/src/main/java/appeng/util/prioitylist/IPartitionList.java index 95b27d4a..d9bc1952 100644 --- a/src/main/java/appeng/util/prioitylist/IPartitionList.java +++ b/src/main/java/appeng/util/prioitylist/IPartitionList.java @@ -18,15 +18,12 @@ package appeng.util.prioitylist; - import appeng.api.storage.data.IAEStack; +public interface IPartitionList> { + boolean isListed(T input); -public interface IPartitionList> -{ - boolean isListed( T input ); + boolean isEmpty(); - boolean isEmpty(); - - Iterable getItems(); + Iterable getItems(); } diff --git a/src/main/java/appeng/util/prioitylist/MergedPriorityList.java b/src/main/java/appeng/util/prioitylist/MergedPriorityList.java index 0c59bbd2..0a3a8dab 100644 --- a/src/main/java/appeng/util/prioitylist/MergedPriorityList.java +++ b/src/main/java/appeng/util/prioitylist/MergedPriorityList.java @@ -18,67 +18,54 @@ package appeng.util.prioitylist; - -import appeng.api.storage.data.IAEStack; - import java.util.ArrayList; import java.util.Collection; +import appeng.api.storage.data.IAEStack; -public final class MergedPriorityList> implements IPartitionList -{ +public final class MergedPriorityList> + implements IPartitionList { + private final Collection> positive + = new ArrayList>(); + private final Collection> negative + = new ArrayList>(); - private final Collection> positive = new ArrayList>(); - private final Collection> negative = new ArrayList>(); + public void addNewList(final IPartitionList list, final boolean isWhitelist) { + if (isWhitelist) { + this.positive.add(list); + } else { + this.negative.add(list); + } + } - public void addNewList( final IPartitionList list, final boolean isWhitelist ) - { - if( isWhitelist ) - { - this.positive.add( list ); - } - else - { - this.negative.add( list ); - } - } + @Override + public boolean isListed(final T input) { + for (final IPartitionList l : this.negative) { + if (l.isListed(input)) { + return false; + } + } - @Override - public boolean isListed( final T input ) - { - for( final IPartitionList l : this.negative ) - { - if( l.isListed( input ) ) - { - return false; - } - } + if (!this.positive.isEmpty()) { + for (final IPartitionList l : this.positive) { + if (l.isListed(input)) { + return true; + } + } - if( !this.positive.isEmpty() ) - { - for( final IPartitionList l : this.positive ) - { - if( l.isListed( input ) ) - { - return true; - } - } + return false; + } - return false; - } + return true; + } - return true; - } + @Override + public boolean isEmpty() { + return this.positive.isEmpty() && this.negative.isEmpty(); + } - @Override - public boolean isEmpty() - { - return this.positive.isEmpty() && this.negative.isEmpty(); - } - - @Override - public Iterable getItems() - { - throw new UnsupportedOperationException(); - } + @Override + public Iterable getItems() { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java b/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java index 796fcd9d..8719f6d3 100644 --- a/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java +++ b/src/main/java/appeng/util/prioitylist/PrecisePriorityList.java @@ -18,36 +18,28 @@ package appeng.util.prioitylist; - import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; +public class PrecisePriorityList> implements IPartitionList { + private final IItemList list; -public class PrecisePriorityList> implements IPartitionList -{ + public PrecisePriorityList(final IItemList in) { + this.list = in; + } - private final IItemList list; + @Override + public boolean isListed(final T input) { + return this.list.findPrecise(input) != null; + } - public PrecisePriorityList( final IItemList in ) - { - this.list = in; - } + @Override + public boolean isEmpty() { + return this.list.isEmpty(); + } - @Override - public boolean isListed( final T input ) - { - return this.list.findPrecise( input ) != null; - } - - @Override - public boolean isEmpty() - { - return this.list.isEmpty(); - } - - @Override - public Iterable getItems() - { - return this.list; - } + @Override + public Iterable getItems() { + return this.list; + } } diff --git a/src/main/java/appeng/worldgen/MeteoritePlacer.java b/src/main/java/appeng/worldgen/MeteoritePlacer.java index 86d6a0f1..3ba5f1ec 100644 --- a/src/main/java/appeng/worldgen/MeteoritePlacer.java +++ b/src/main/java/appeng/worldgen/MeteoritePlacer.java @@ -18,6 +18,10 @@ package appeng.worldgen; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -41,540 +45,477 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.oredict.OreDictionary; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; - - -public final class MeteoritePlacer -{ - private static final double PRESSES_SPAWN_CHANCE = 0.7; - private static final int SKYSTONE_SPAWN_LIMIT = 12; - private final Collection validSpawn = new HashSet(); - private final Collection invalidSpawn = new HashSet(); - private final IBlockDefinition skyChestDefinition; - private final IBlockDefinition skyStoneDefinition; - private final MeteoriteBlockPutter putter = new MeteoriteBlockPutter(); - private double meteoriteSize = ( Math.random() * 6.0 ) + 2; - private double realCrater = this.meteoriteSize * 2 + 5; - private double squaredMeteoriteSize = this.meteoriteSize * this.meteoriteSize; - private double crater = this.realCrater * this.realCrater; - private NBTTagCompound settings; - private Fallout type; - - public MeteoritePlacer() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - - this.skyChestDefinition = blocks.skyChest(); - this.skyStoneDefinition = blocks.skyStone(); - - this.validSpawn.add( Blocks.stone ); - this.validSpawn.add( Blocks.cobblestone ); - this.validSpawn.add( Blocks.grass ); - this.validSpawn.add( Blocks.sand ); - this.validSpawn.add( Blocks.dirt ); - this.validSpawn.add( Blocks.gravel ); - this.validSpawn.add( Blocks.netherrack ); - this.validSpawn.add( Blocks.iron_ore ); - this.validSpawn.add( Blocks.gold_ore ); - this.validSpawn.add( Blocks.diamond_ore ); - this.validSpawn.add( Blocks.redstone_ore ); - this.validSpawn.add( Blocks.hardened_clay ); - this.validSpawn.add( Blocks.ice ); - this.validSpawn.add( Blocks.snow ); - this.validSpawn.add( Blocks.stained_hardened_clay ); - - for( final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) - { - this.invalidSpawn.add( skyStoneBlock ); - } - this.invalidSpawn.add( Blocks.planks ); - this.invalidSpawn.add( Blocks.iron_door ); - this.invalidSpawn.add( Blocks.iron_bars ); - this.invalidSpawn.add( Blocks.wooden_door ); - this.invalidSpawn.add( Blocks.brick_block ); - this.invalidSpawn.add( Blocks.clay ); - this.invalidSpawn.add( Blocks.water ); - this.invalidSpawn.add( Blocks.log ); - this.invalidSpawn.add( Blocks.log2 ); - - this.type = new Fallout( this.putter, this.skyStoneDefinition ); - } - - boolean spawnMeteorite( final IMeteoriteWorld w, final NBTTagCompound meteoriteBlob ) - { - this.settings = meteoriteBlob; - - final int x = this.settings.getInteger( "x" ); - final int y = this.settings.getInteger( "y" ); - final int z = this.settings.getInteger( "z" ); - - this.meteoriteSize = this.settings.getDouble( "real_sizeOfMeteorite" ); - this.realCrater = this.settings.getDouble( "realCrater" ); - this.squaredMeteoriteSize = this.settings.getDouble( "sizeOfMeteorite" ); - this.crater = this.settings.getDouble( "crater" ); - - final Block blk = Block.getBlockById( this.settings.getInteger( "blk" ) ); - - if( blk == Blocks.sand ) - { - this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - 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 ) - { - this.type = new FalloutSnow( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - - final int skyMode = this.settings.getInteger( "skyMode" ); - - // creator - if( skyMode > 10 ) - { - this.placeCrater( w, x, y, z ); - } - - this.placeMeteorite( w, x, y, z ); - - // collapse blocks... - if( skyMode > 3 ) - { - this.decay( w, x, y, z ); - } - - w.done(); - return true; - } - - private void placeCrater( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final boolean lava = this.settings.getBoolean( "lava" ); - - final int maxY = 255; - final int minX = w.minX( x - 200 ); - final int maxX = w.maxX( x + 200 ); - final int minZ = w.minZ( z - 200 ); - final int maxZ = w.maxZ( z + 200 ); - - 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++ ) - { - final double dx = i - x; - final double dz = k - z; - final double h = y - this.meteoriteSize + 1 + this.type.adjustCrater(); - - final double distanceFrom = dx * dx + dz * dz; - - if( j > h + distanceFrom * 0.02 ) - { - if( lava && j < y && w.getBlock( x, y - 1, z ).isBlockSolid( w.getWorld(), i, j, k, 0 ) ) - { - if( j > h + distanceFrom * 0.02 ) - { - this.putter.put( w, i, j, k, Blocks.lava ); - } - } - else - { - changed = this.putter.put( w, i, j, k, Platform.AIR_BLOCK ) || changed; - } - } - } - } - } - - for( final 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 ) ) ) ) - { - final Entity e = (Entity) o; - e.setDead(); - } - } - - private void placeMeteorite( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final int meteorXLength = w.minX( x - 8 ); - final int meteorXHeight = w.maxX( x + 8 ); - final int meteorZLength = w.minZ( z - 8 ); - final 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++ ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - - if( dx * dx * 0.7 + dy * dy * ( j > y ? 1.4 : 0.8 ) + dz * dz * 0.7 < this.squaredMeteoriteSize ) - { - for( final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) - { - this.putter.put( w, i, j, k, skyStoneBlock ); - } - } - } - } - } - - if( AEConfig.instance.isFeatureEnabled( AEFeature.SpawnPressesInMeteorites ) ) - { - for( final Block skyChestBlock : this.skyChestDefinition.maybeBlock().asSet() ) - { - this.putter.put( w, x, y, z, skyChestBlock ); - } - - final TileEntity te = w.getTileEntity( x, y, z ); - if( te instanceof IInventory ) - { - final InventoryAdaptor ap = InventoryAdaptor.getAdaptor( te, ForgeDirection.UP ); - - int primary = Math.max( 1, (int) ( Math.random() * 4 ) ); - - if( primary > 3 ) // in case math breaks... - { - primary = 3; - } - - for( int zz = 0; zz < primary; zz++ ) - { - int r = 0; - boolean duplicate = false; - - do - { - duplicate = false; - - if( Math.random() > PRESSES_SPAWN_CHANCE ) - { - r = WorldData.instance().storageData().getNextOrderedValue( "presses" ); - } - else - { - r = (int) ( Math.random() * 1000 ); - } - - ItemStack toAdd = null; - final IMaterials materials = AEApi.instance().definitions().materials(); - - switch( r % 4 ) - { - case 0: - for( final ItemStack calc : materials.calcProcessorPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - case 1: - for( final ItemStack calc : materials.engProcessorPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - case 2: - for( final ItemStack calc : materials.logicProcessorPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - case 3: - for( final ItemStack calc : materials.siliconPress().maybeStack( 1 ).asSet() ) - { - toAdd = calc; - } - break; - default: - } - - if( toAdd != null ) - { - if( ap.simulateRemove( 1, toAdd, null ) == null ) - { - ap.addItems( toAdd ); - } - else - { - duplicate = true; - } - } - } - while( duplicate ); - } - - final int secondary = Math.max( 1, (int) ( Math.random() * 3 ) ); - for( int zz = 0; zz < secondary; zz++ ) - { - switch( (int) ( Math.random() * 1000 ) % 3 ) - { - case 0: - final int amount = (int) ( ( Math.random() * SKYSTONE_SPAWN_LIMIT ) + 1 ); - for( final ItemStack skyStoneStack : this.skyStoneDefinition.maybeStack( amount ).asSet() ) - { - ap.addItems( skyStoneStack ); - } - break; - case 1: - final List possibles = new LinkedList(); - possibles.addAll( OreDictionary.getOres( "nuggetIron" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetCopper" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetTin" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetSilver" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetLead" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetPlatinum" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetNickel" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetAluminium" ) ); - possibles.addAll( OreDictionary.getOres( "nuggetElectrum" ) ); - possibles.add( new ItemStack( net.minecraft.init.Items.gold_nugget ) ); - - ItemStack nugget = Platform.pickRandom( possibles ); - if( nugget != null ) - { - nugget = nugget.copy(); - nugget.stackSize = (int) ( Math.random() * 12 ) + 1; - ap.addItems( nugget ); - } - break; - } - } - } - } - } - - private void decay( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - double randomShit = 0; - - final int meteorXLength = w.minX( x - 30 ); - final int meteorXHeight = w.maxX( x + 30 ); - final int meteorZLength = w.minZ( z - 30 ); - final 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++ ) - { - Block blk = w.getBlock( i, j, k ); - if( blk == Blocks.lava ) - { - continue; - } - - if( blk.isReplaceable( w.getWorld(), i, j, k ) ) - { - blk = Platform.AIR_BLOCK; - final Block blk_b = w.getBlock( i, j + 1, k ); - - if( blk_b != blk ) - { - final 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 ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - final double dist = dx * dx + dy * dy + dz * dz; - - final Block xf = w.getBlock( i, j - 1, k ); - if( !xf.isReplaceable( w.getWorld(), i, j - 1, k ) ) - { - final double extraRange = Math.random() * 0.6; - final double height = this.crater * ( extraRange + 0.2 ) - Math.abs( dist - this.crater * 1.7 ); - - if( xf != blk && height > 0 && Math.random() > 0.6 ) - { - randomShit++; - this.type.getRandomFall( w, i, j, k ); - } - } - } - } - else - { - // decay. - final Block blk_b = w.getBlock( i, j + 1, k ); - if( blk_b == Platform.AIR_BLOCK ) - { - if( Math.random() > 0.4 ) - { - final double dx = i - x; - final double dy = j - y; - final double dz = k - z; - - if( dx * dx + dy * dy + dz * dz < this.crater * 1.6 ) - { - this.type.getRandomInset( w, i, j, k ); - } - } - } - } - } - } - } - } - - double getSqDistance( final int x, final int z ) - { - final int chunkX = this.settings.getInteger( "x" ) - x; - final int chunkZ = this.settings.getInteger( "z" ) - z; - - return chunkX * chunkX + chunkZ * chunkZ; - } - - public boolean spawnMeteorite( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - - if( !w.hasNoSky() ) - { - return false; - } - - Block blk = w.getBlock( x, y, z ); - if( !this.validSpawn.contains( blk ) ) - { - return false; // must spawn on a valid block.. - } - - this.settings = new NBTTagCompound(); - this.settings.setInteger( "x", x ); - this.settings.setInteger( "y", y ); - this.settings.setInteger( "z", z ); - this.settings.setInteger( "blk", Block.getIdFromBlock( blk ) ); - - this.settings.setDouble( "real_sizeOfMeteorite", this.meteoriteSize ); - this.settings.setDouble( "realCrater", this.realCrater ); - this.settings.setDouble( "sizeOfMeteorite", this.squaredMeteoriteSize ); - this.settings.setDouble( "crater", this.crater ); - - this.settings.setBoolean( "lava", Math.random() > 0.9 ); - - if( blk == Blocks.sand ) - { - this.type = new FalloutSand( w, x, y, z, this.putter, this.skyStoneDefinition ); - } - 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 ) - { - 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++ ) - { - blk = w.getBlock( i, j, k ); - if( this.validSpawn.contains( blk ) ) - { - realValidBlocks++; - } - } - } - } - - int validBlocks = 0; - 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 ) ) - { - return false; - } - if( this.validSpawn.contains( blk ) ) - { - validBlocks++; - } - } - } - } - - final int minBLocks = 200; - 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++ ) - { - if( w.canBlockSeeTheSky( i, j, k ) ) - { - skyMode++; - } - } - } - } - - boolean solid = true; - for( int j = y - 15; j < y - 1; j++ ) - { - if( w.getBlock( x, j, z ) == Platform.AIR_BLOCK ) - { - solid = false; - } - } - - if( !solid ) - { - skyMode = 0; - } - - // creator - if( skyMode > 10 ) - { - this.placeCrater( w, x, y, z ); - } - - this.placeMeteorite( w, x, y, z ); - - // collapse blocks... - if( skyMode > 3 ) - { - this.decay( w, x, y, z ); - } - - this.settings.setInteger( "skyMode", skyMode ); - w.done(); - - WorldData.instance().spawnData().addNearByMeteorites( w.getWorld().provider.dimensionId, x >> 4, z >> 4, this.settings ); - return true; - } - return false; - } - - NBTTagCompound getSettings() - { - return this.settings; - } +public final class MeteoritePlacer { + private static final double PRESSES_SPAWN_CHANCE = 0.7; + private static final int SKYSTONE_SPAWN_LIMIT = 12; + private final Collection validSpawn = new HashSet(); + private final Collection invalidSpawn = new HashSet(); + private final IBlockDefinition skyChestDefinition; + private final IBlockDefinition skyStoneDefinition; + private final MeteoriteBlockPutter putter = new MeteoriteBlockPutter(); + private double meteoriteSize = (Math.random() * 6.0) + 2; + private double realCrater = this.meteoriteSize * 2 + 5; + private double squaredMeteoriteSize = this.meteoriteSize * this.meteoriteSize; + private double crater = this.realCrater * this.realCrater; + private NBTTagCompound settings; + private Fallout type; + + public MeteoritePlacer() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + + this.skyChestDefinition = blocks.skyChest(); + this.skyStoneDefinition = blocks.skyStone(); + + this.validSpawn.add(Blocks.stone); + this.validSpawn.add(Blocks.cobblestone); + this.validSpawn.add(Blocks.grass); + this.validSpawn.add(Blocks.sand); + this.validSpawn.add(Blocks.dirt); + this.validSpawn.add(Blocks.gravel); + this.validSpawn.add(Blocks.netherrack); + this.validSpawn.add(Blocks.iron_ore); + this.validSpawn.add(Blocks.gold_ore); + this.validSpawn.add(Blocks.diamond_ore); + this.validSpawn.add(Blocks.redstone_ore); + this.validSpawn.add(Blocks.hardened_clay); + this.validSpawn.add(Blocks.ice); + this.validSpawn.add(Blocks.snow); + this.validSpawn.add(Blocks.stained_hardened_clay); + + for (final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet()) { + this.invalidSpawn.add(skyStoneBlock); + } + this.invalidSpawn.add(Blocks.planks); + this.invalidSpawn.add(Blocks.iron_door); + this.invalidSpawn.add(Blocks.iron_bars); + this.invalidSpawn.add(Blocks.wooden_door); + this.invalidSpawn.add(Blocks.brick_block); + this.invalidSpawn.add(Blocks.clay); + this.invalidSpawn.add(Blocks.water); + this.invalidSpawn.add(Blocks.log); + this.invalidSpawn.add(Blocks.log2); + + this.type = new Fallout(this.putter, this.skyStoneDefinition); + } + + boolean spawnMeteorite(final IMeteoriteWorld w, final NBTTagCompound meteoriteBlob) { + this.settings = meteoriteBlob; + + final int x = this.settings.getInteger("x"); + final int y = this.settings.getInteger("y"); + final int z = this.settings.getInteger("z"); + + this.meteoriteSize = this.settings.getDouble("real_sizeOfMeteorite"); + this.realCrater = this.settings.getDouble("realCrater"); + this.squaredMeteoriteSize = this.settings.getDouble("sizeOfMeteorite"); + this.crater = this.settings.getDouble("crater"); + + final Block blk = Block.getBlockById(this.settings.getInteger("blk")); + + if (blk == Blocks.sand) { + this.type = new FalloutSand(w, x, y, z, this.putter, this.skyStoneDefinition); + } 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) { + this.type = new FalloutSnow(w, x, y, z, this.putter, this.skyStoneDefinition); + } + + final int skyMode = this.settings.getInteger("skyMode"); + + // creator + if (skyMode > 10) { + this.placeCrater(w, x, y, z); + } + + this.placeMeteorite(w, x, y, z); + + // collapse blocks... + if (skyMode > 3) { + this.decay(w, x, y, z); + } + + w.done(); + return true; + } + + private void + placeCrater(final IMeteoriteWorld w, final int x, final int y, final int z) { + final boolean lava = this.settings.getBoolean("lava"); + + final int maxY = 255; + final int minX = w.minX(x - 200); + final int maxX = w.maxX(x + 200); + final int minZ = w.minZ(z - 200); + final int maxZ = w.maxZ(z + 200); + + 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++) { + final double dx = i - x; + final double dz = k - z; + final double h + = y - this.meteoriteSize + 1 + this.type.adjustCrater(); + + final double distanceFrom = dx * dx + dz * dz; + + if (j > h + distanceFrom * 0.02) { + if (lava && j < y + && w.getBlock(x, y - 1, z) + .isBlockSolid(w.getWorld(), i, j, k, 0)) { + if (j > h + distanceFrom * 0.02) { + this.putter.put(w, i, j, k, Blocks.lava); + } + } else { + changed = this.putter.put(w, i, j, k, Platform.AIR_BLOCK) + || changed; + } + } + } + } + } + + for (final 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) + ) + )) { + final Entity e = (Entity) o; + e.setDead(); + } + } + + private void + placeMeteorite(final IMeteoriteWorld w, final int x, final int y, final int z) { + final int meteorXLength = w.minX(x - 8); + final int meteorXHeight = w.maxX(x + 8); + final int meteorZLength = w.minZ(z - 8); + final 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++) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + + if (dx * dx * 0.7 + dy * dy * (j > y ? 1.4 : 0.8) + dz * dz * 0.7 + < this.squaredMeteoriteSize) { + for (final Block skyStoneBlock : + this.skyStoneDefinition.maybeBlock().asSet()) { + this.putter.put(w, i, j, k, skyStoneBlock); + } + } + } + } + } + + if (AEConfig.instance.isFeatureEnabled(AEFeature.SpawnPressesInMeteorites)) { + for (final Block skyChestBlock : + this.skyChestDefinition.maybeBlock().asSet()) { + this.putter.put(w, x, y, z, skyChestBlock); + } + + final TileEntity te = w.getTileEntity(x, y, z); + if (te instanceof IInventory) { + final InventoryAdaptor ap + = InventoryAdaptor.getAdaptor(te, ForgeDirection.UP); + + int primary = Math.max(1, (int) (Math.random() * 4)); + + if (primary > 3) // in case math breaks... + { + primary = 3; + } + + for (int zz = 0; zz < primary; zz++) { + int r = 0; + boolean duplicate = false; + + do { + duplicate = false; + + if (Math.random() > PRESSES_SPAWN_CHANCE) { + r = WorldData.instance().storageData().getNextOrderedValue( + "presses" + ); + } else { + r = (int) (Math.random() * 1000); + } + + ItemStack toAdd = null; + final IMaterials materials + = AEApi.instance().definitions().materials(); + + switch (r % 4) { + case 0: + for (final ItemStack calc : + materials.calcProcessorPress().maybeStack(1).asSet( + )) { + toAdd = calc; + } + break; + case 1: + for (final ItemStack calc : + materials.engProcessorPress().maybeStack(1).asSet( + )) { + toAdd = calc; + } + break; + case 2: + for (final ItemStack calc : + materials.logicProcessorPress().maybeStack(1).asSet( + )) { + toAdd = calc; + } + break; + case 3: + for (final ItemStack calc : + materials.siliconPress().maybeStack(1).asSet()) { + toAdd = calc; + } + break; + default: + } + + if (toAdd != null) { + if (ap.simulateRemove(1, toAdd, null) == null) { + ap.addItems(toAdd); + } else { + duplicate = true; + } + } + } while (duplicate); + } + + final int secondary = Math.max(1, (int) (Math.random() * 3)); + for (int zz = 0; zz < secondary; zz++) { + switch ((int) (Math.random() * 1000) % 3) { + case 0: + final int amount + = (int) ((Math.random() * SKYSTONE_SPAWN_LIMIT) + 1); + for (final ItemStack skyStoneStack : + this.skyStoneDefinition.maybeStack(amount).asSet()) { + ap.addItems(skyStoneStack); + } + break; + case 1: + final List possibles = new LinkedList(); + possibles.addAll(OreDictionary.getOres("nuggetIron")); + possibles.addAll(OreDictionary.getOres("nuggetCopper")); + possibles.addAll(OreDictionary.getOres("nuggetTin")); + possibles.addAll(OreDictionary.getOres("nuggetSilver")); + possibles.addAll(OreDictionary.getOres("nuggetLead")); + possibles.addAll(OreDictionary.getOres("nuggetPlatinum")); + possibles.addAll(OreDictionary.getOres("nuggetNickel")); + possibles.addAll(OreDictionary.getOres("nuggetAluminium")); + possibles.addAll(OreDictionary.getOres("nuggetElectrum")); + possibles.add( + new ItemStack(net.minecraft.init.Items.gold_nugget) + ); + + ItemStack nugget = Platform.pickRandom(possibles); + if (nugget != null) { + nugget = nugget.copy(); + nugget.stackSize = (int) (Math.random() * 12) + 1; + ap.addItems(nugget); + } + break; + } + } + } + } + } + + private void decay(final IMeteoriteWorld w, final int x, final int y, final int z) { + double randomShit = 0; + + final int meteorXLength = w.minX(x - 30); + final int meteorXHeight = w.maxX(x + 30); + final int meteorZLength = w.minZ(z - 30); + final 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++) { + Block blk = w.getBlock(i, j, k); + if (blk == Blocks.lava) { + continue; + } + + if (blk.isReplaceable(w.getWorld(), i, j, k)) { + blk = Platform.AIR_BLOCK; + final Block blk_b = w.getBlock(i, j + 1, k); + + if (blk_b != blk) { + final 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) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + final double dist = dx * dx + dy * dy + dz * dz; + + final Block xf = w.getBlock(i, j - 1, k); + if (!xf.isReplaceable(w.getWorld(), i, j - 1, k)) { + final double extraRange = Math.random() * 0.6; + final double height = this.crater * (extraRange + 0.2) + - Math.abs(dist - this.crater * 1.7); + + if (xf != blk && height > 0 && Math.random() > 0.6) { + randomShit++; + this.type.getRandomFall(w, i, j, k); + } + } + } + } else { + // decay. + final Block blk_b = w.getBlock(i, j + 1, k); + if (blk_b == Platform.AIR_BLOCK) { + if (Math.random() > 0.4) { + final double dx = i - x; + final double dy = j - y; + final double dz = k - z; + + if (dx * dx + dy * dy + dz * dz < this.crater * 1.6) { + this.type.getRandomInset(w, i, j, k); + } + } + } + } + } + } + } + } + + double getSqDistance(final int x, final int z) { + final int chunkX = this.settings.getInteger("x") - x; + final int chunkZ = this.settings.getInteger("z") - z; + + return chunkX * chunkX + chunkZ * chunkZ; + } + + public boolean + spawnMeteorite(final IMeteoriteWorld w, final int x, final int y, final int z) { + if (!w.hasNoSky()) { + return false; + } + + Block blk = w.getBlock(x, y, z); + if (!this.validSpawn.contains(blk)) { + return false; // must spawn on a valid block.. + } + + this.settings = new NBTTagCompound(); + this.settings.setInteger("x", x); + this.settings.setInteger("y", y); + this.settings.setInteger("z", z); + this.settings.setInteger("blk", Block.getIdFromBlock(blk)); + + this.settings.setDouble("real_sizeOfMeteorite", this.meteoriteSize); + this.settings.setDouble("realCrater", this.realCrater); + this.settings.setDouble("sizeOfMeteorite", this.squaredMeteoriteSize); + this.settings.setDouble("crater", this.crater); + + this.settings.setBoolean("lava", Math.random() > 0.9); + + if (blk == Blocks.sand) { + this.type = new FalloutSand(w, x, y, z, this.putter, this.skyStoneDefinition); + } 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) { + 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++) { + blk = w.getBlock(i, j, k); + if (this.validSpawn.contains(blk)) { + realValidBlocks++; + } + } + } + } + + int validBlocks = 0; + 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)) { + return false; + } + if (this.validSpawn.contains(blk)) { + validBlocks++; + } + } + } + } + + final int minBLocks = 200; + 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++) { + if (w.canBlockSeeTheSky(i, j, k)) { + skyMode++; + } + } + } + } + + boolean solid = true; + for (int j = y - 15; j < y - 1; j++) { + if (w.getBlock(x, j, z) == Platform.AIR_BLOCK) { + solid = false; + } + } + + if (!solid) { + skyMode = 0; + } + + // creator + if (skyMode > 10) { + this.placeCrater(w, x, y, z); + } + + this.placeMeteorite(w, x, y, z); + + // collapse blocks... + if (skyMode > 3) { + this.decay(w, x, y, z); + } + + this.settings.setInteger("skyMode", skyMode); + w.done(); + + WorldData.instance().spawnData().addNearByMeteorites( + w.getWorld().provider.dimensionId, x >> 4, z >> 4, this.settings + ); + return true; + } + return false; + } + + NBTTagCompound getSettings() { + return this.settings; + } } diff --git a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java index ee2901af..6ace174f 100644 --- a/src/main/java/appeng/worldgen/MeteoriteWorldGen.java +++ b/src/main/java/appeng/worldgen/MeteoriteWorldGen.java @@ -18,6 +18,7 @@ package appeng.worldgen; +import java.util.Random; import appeng.api.features.IWorldGen.WorldGenType; import appeng.core.AEConfig; @@ -32,127 +33,122 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; -import java.util.Random; +public final class MeteoriteWorldGen implements IWorldGenerator { + @Override + public void generate( + final Random r, + final int chunkX, + final int chunkZ, + final World w, + final IChunkProvider chunkGenerator, + final IChunkProvider chunkProvider + ) { + if (WorldGenRegistry.INSTANCE.isWorldGenEnabled(WorldGenType.Meteorites, w)) { + // add new meteorites? + if (r.nextFloat() < AEConfig.instance.meteoriteSpawnChance) { + final int x = r.nextInt(16) + (chunkX << 4); + final int z = r.nextInt(16) + (chunkZ << 4); + final int depth = 180 + r.nextInt(20); + TickHandler.INSTANCE.addCallable(w, new MeteoriteSpawn(x, depth, z)); + } else { + TickHandler.INSTANCE.addCallable( + w, new MeteoriteSpawn(chunkX << 4, 128, chunkZ << 4) + ); + } + } else { + WorldData.instance().compassData().service().updateArea(w, chunkX, chunkZ); + } + } -public final class MeteoriteWorldGen implements IWorldGenerator -{ - @Override - public void generate( final Random r, final int chunkX, final int chunkZ, final World w, final IChunkProvider chunkGenerator, final IChunkProvider chunkProvider ) - { - if( WorldGenRegistry.INSTANCE.isWorldGenEnabled( WorldGenType.Meteorites, w ) ) - { - // add new meteorites? - if( r.nextFloat() < AEConfig.instance.meteoriteSpawnChance ) - { - final int x = r.nextInt( 16 ) + ( chunkX << 4 ); - final int z = r.nextInt( 16 ) + ( chunkZ << 4 ); + private boolean tryMeteorite(final World w, int depth, final int x, final int z) { + for (int tries = 0; tries < 20; tries++) { + final MeteoritePlacer mp = new MeteoritePlacer(); - final int depth = 180 + r.nextInt( 20 ); - TickHandler.INSTANCE.addCallable( w, new MeteoriteSpawn( x, depth, z ) ); - } - else - { - TickHandler.INSTANCE.addCallable( w, new MeteoriteSpawn( chunkX << 4, 128, chunkZ << 4 ) ); - } - } - else - { - WorldData.instance().compassData().service().updateArea( w, chunkX, chunkZ ); - } - } + if (mp.spawnMeteorite(new ChunkOnly(w, x >> 4, z >> 4), x, depth, z)) { + final int px = x >> 4; + final int pz = z >> 4; - private boolean tryMeteorite( final World w, int depth, final int x, final int z ) - { - for( int tries = 0; tries < 20; tries++ ) - { - final MeteoritePlacer mp = new MeteoritePlacer(); + 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( mp.spawnMeteorite( new ChunkOnly( w, x >> 4, z >> 4 ), x, depth, z ) ) - { - final int px = x >> 4; - final int pz = z >> 4; + if (WorldData.instance().spawnData().hasGenerated( + w.provider.dimensionId, cx, cz + )) { + final MeteoritePlacer mp2 = new MeteoritePlacer(); + mp2.spawnMeteorite( + new ChunkOnly(w, cx, cz), mp.getSettings() + ); + } + } + } + } - 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; - } + return true; + } - if( WorldData.instance().spawnData().hasGenerated( w.provider.dimensionId, cx, cz ) ) - { - final MeteoritePlacer mp2 = new MeteoritePlacer(); - mp2.spawnMeteorite( new ChunkOnly( w, cx, cz ), mp.getSettings() ); - } - } - } - } + depth -= 15; + if (depth < 40) { + return false; + } + } - return true; - } + return false; + } - depth -= 15; - if( depth < 40 ) - { - return false; - } - } + private Iterable + getNearByMeteorites(final World w, final int chunkX, final int chunkZ) { + return WorldData.instance().spawnData().getNearByMeteorites( + w.provider.dimensionId, chunkX, chunkZ + ); + } - return false; - } + private class MeteoriteSpawn implements IWorldCallable { + private final int x; + private final int z; + private final int depth; - private Iterable getNearByMeteorites( final World w, final int chunkX, final int chunkZ ) - { - return WorldData.instance().spawnData().getNearByMeteorites( w.provider.dimensionId, chunkX, chunkZ ); - } + public MeteoriteSpawn(final int x, final int depth, final int z) { + this.x = x; + this.z = z; + this.depth = depth; + } - private class MeteoriteSpawn implements IWorldCallable - { + @Override + public Object call(final World world) throws Exception { + final int chunkX = this.x >> 4; + final int chunkZ = this.z >> 4; - private final int x; - private final int z; - private final int depth; + double minSqDist = Double.MAX_VALUE; - public MeteoriteSpawn( final int x, final int depth, final int z ) - { - this.x = x; - this.z = z; - this.depth = depth; - } + // near by meteorites! + for (final NBTTagCompound data : + MeteoriteWorldGen.this.getNearByMeteorites(world, chunkX, chunkZ)) { + final MeteoritePlacer mp = new MeteoritePlacer(); + mp.spawnMeteorite(new ChunkOnly(world, chunkX, chunkZ), data); - @Override - public Object call( final World world ) throws Exception - { - final int chunkX = this.x >> 4; - final int chunkZ = this.z >> 4; + minSqDist = Math.min(minSqDist, mp.getSqDistance(this.x, this.z)); + } - double minSqDist = Double.MAX_VALUE; + final boolean isCluster = (minSqDist < 30 * 30) + && Platform.getRandomFloat() < AEConfig.instance.meteoriteClusterChance; - // near by meteorites! - for( final NBTTagCompound data : MeteoriteWorldGen.this.getNearByMeteorites( world, chunkX, chunkZ ) ) - { - final MeteoritePlacer mp = new MeteoritePlacer(); - mp.spawnMeteorite( new ChunkOnly( world, chunkX, chunkZ ), data ); + if (minSqDist > AEConfig.instance.minMeteoriteDistanceSq || isCluster) { + MeteoriteWorldGen.this.tryMeteorite(world, this.depth, this.x, this.z); + } - minSqDist = Math.min( minSqDist, mp.getSqDistance( this.x, this.z ) ); - } + WorldData.instance().spawnData().setGenerated( + world.provider.dimensionId, chunkX, chunkZ + ); + WorldData.instance().compassData().service().updateArea( + world, chunkX, chunkZ + ); - final boolean isCluster = ( minSqDist < 30 * 30 ) && Platform.getRandomFloat() < AEConfig.instance.meteoriteClusterChance; - - if( minSqDist > AEConfig.instance.minMeteoriteDistanceSq || isCluster ) - { - MeteoriteWorldGen.this.tryMeteorite( world, this.depth, this.x, this.z ); - } - - WorldData.instance().spawnData().setGenerated( world.provider.dimensionId, chunkX, chunkZ ); - WorldData.instance().compassData().service().updateArea( world, chunkX, chunkZ ); - - return null; - } - } + return null; + } + } } diff --git a/src/main/java/appeng/worldgen/QuartzWorldGen.java b/src/main/java/appeng/worldgen/QuartzWorldGen.java index 5dbde893..715362f2 100644 --- a/src/main/java/appeng/worldgen/QuartzWorldGen.java +++ b/src/main/java/appeng/worldgen/QuartzWorldGen.java @@ -18,6 +18,7 @@ package appeng.worldgen; +import java.util.Random; import appeng.api.AEApi; import appeng.api.definitions.IBlockDefinition; @@ -32,59 +33,69 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.feature.WorldGenMinable; -import java.util.Random; +public final class QuartzWorldGen implements IWorldGenerator { + private final WorldGenMinable oreNormal; + private final WorldGenMinable oreCharged; + public QuartzWorldGen() { + final IBlocks blocks = AEApi.instance().definitions().blocks(); + final IBlockDefinition oreDefinition = blocks.quartzOre(); + final IBlockDefinition chargedDefinition = blocks.quartzOreCharged(); -public final class QuartzWorldGen implements IWorldGenerator -{ - private final WorldGenMinable oreNormal; - private final WorldGenMinable oreCharged; + final Block ore = oreDefinition.maybeBlock().orNull(); + final Block charged = chargedDefinition.maybeBlock().orNull(); - public QuartzWorldGen() - { - final IBlocks blocks = AEApi.instance().definitions().blocks(); - final IBlockDefinition oreDefinition = blocks.quartzOre(); - final IBlockDefinition chargedDefinition = blocks.quartzOreCharged(); + this.oreNormal = new WorldGenMinable( + ore, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone + ); + this.oreCharged = new WorldGenMinable( + charged, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone + ); + } - final Block ore = oreDefinition.maybeBlock().orNull(); - final Block charged = chargedDefinition.maybeBlock().orNull(); + @Override + public void generate( + final Random r, + final int chunkX, + final int chunkZ, + final World w, + final IChunkProvider chunkGenerator, + final IChunkProvider chunkProvider + ) { + int seaLevel = w.provider.getAverageGroundLevel() + 1; - this.oreNormal = new WorldGenMinable( ore, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone ); - this.oreCharged = new WorldGenMinable( charged, 0, AEConfig.instance.quartzOresPerCluster, Blocks.stone ); - } + if (seaLevel < 20) { + final int x = (chunkX << 4) + 8; + final int z = (chunkZ << 4) + 8; + seaLevel = w.getHeightValue(x, z); + } - @Override - public void generate( final Random r, final int chunkX, final int chunkZ, final World w, final IChunkProvider chunkGenerator, final IChunkProvider chunkProvider ) - { - int seaLevel = w.provider.getAverageGroundLevel() + 1; + if (this.oreNormal == null || this.oreCharged == null) { + return; + } - if( seaLevel < 20 ) - { - final int x = ( chunkX << 4 ) + 8; - final int z = ( chunkZ << 4 ) + 8; - seaLevel = w.getHeightValue( x, z ); - } + final double oreDepthMultiplier + = AEConfig.instance.quartzOresClusterAmount * seaLevel / 64; + final int scale = (int) Math.round( + r.nextGaussian() * Math.sqrt(oreDepthMultiplier) + oreDepthMultiplier + ); - if( this.oreNormal == null || this.oreCharged == null ) - { - return; - } + for (int x = 0; x < (r.nextBoolean() ? scale * 2 : scale) / 2; ++x) { + final boolean isCharged + = r.nextFloat() > AEConfig.instance.spawnChargedChance; + final WorldGenMinable whichOre = isCharged ? this.oreCharged : this.oreNormal; - final double oreDepthMultiplier = AEConfig.instance.quartzOresClusterAmount * seaLevel / 64; - final int scale = (int) Math.round( r.nextGaussian() * Math.sqrt( oreDepthMultiplier ) + oreDepthMultiplier ); - - for( int x = 0; x < ( r.nextBoolean() ? scale * 2 : scale ) / 2; ++x ) - { - final boolean isCharged = r.nextFloat() > AEConfig.instance.spawnChargedChance; - final WorldGenMinable whichOre = isCharged ? this.oreCharged : this.oreNormal; - - if( WorldGenRegistry.INSTANCE.isWorldGenEnabled( isCharged ? WorldGenType.ChargedCertusQuartz : WorldGenType.CertusQuartz, w ) ) - { - final int cx = chunkX * 16 + r.nextInt( 22 ); - final int cy = r.nextInt( 40 * seaLevel / 64 ) + r.nextInt( 22 * seaLevel / 64 ) + 12 * seaLevel / 64; - final int cz = chunkZ * 16 + r.nextInt( 22 ); - whichOre.generate( w, r, cx, cy, cz ); - } - } - } + if (WorldGenRegistry.INSTANCE.isWorldGenEnabled( + isCharged ? WorldGenType.ChargedCertusQuartz + : WorldGenType.CertusQuartz, + w + )) { + final int cx = chunkX * 16 + r.nextInt(22); + final int cy = r.nextInt(40 * seaLevel / 64) + + r.nextInt(22 * seaLevel / 64) + 12 * seaLevel / 64; + final int cz = chunkZ * 16 + r.nextInt(22); + whichOre.generate(w, r, cx, cy, cz); + } + } + } } diff --git a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java index f3229e1c..1ab4942e 100644 --- a/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java +++ b/src/main/java/appeng/worldgen/meteorite/ChunkOnly.java @@ -1,104 +1,91 @@ package appeng.worldgen.meteorite; - import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; +public class ChunkOnly extends StandardWorld { + private final Chunk target; + private final int cx; + private final int cz; + private int verticalBits = 0; -public class ChunkOnly extends StandardWorld -{ + public ChunkOnly(final World w, final int cx, final int cz) { + super(w); + this.target = w.getChunkFromChunkCoords(cx, cz); + this.cx = cx; + this.cz = cz; + } - private final Chunk target; - private final int cx; - private final int cz; - private int verticalBits = 0; + @Override + public int minX(final int in) { + return Math.max(in, this.cx << 4); + } - public ChunkOnly( final World w, final int cx, final int cz ) - { - super( w ); - this.target = w.getChunkFromChunkCoords( cx, cz ); - this.cx = cx; - this.cz = cz; - } + @Override + public int minZ(final int in) { + return Math.max(in, this.cz << 4); + } - @Override - public int minX( final int in ) - { - return Math.max( in, this.cx << 4 ); - } + @Override + public int maxX(final int in) { + return Math.min(in, (this.cx + 1) << 4); + } - @Override - public int minZ( final int in ) - { - return Math.max( in, this.cz << 4 ); - } + @Override + public int maxZ(final int in) { + return Math.min(in, (this.cz + 1) << 4); + } - @Override - public int maxX( final int in ) - { - return Math.min( in, ( this.cx + 1 ) << 4 ); - } + @Override + public int getBlockMetadata(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.target.getBlockMetadata(x & 0xF, y, z & 0xF); + } + return 0; + } - @Override - public int maxZ( final int in ) - { - return Math.min( in, ( this.cz + 1 ) << 4 ); - } + @Override + public Block getBlock(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.target.getBlock(x & 0xF, y, z & 0xF); + } + return Platform.AIR_BLOCK; + } - @Override - public int getBlockMetadata( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.target.getBlockMetadata( x & 0xF, y, z & 0xF ); - } - return 0; - } + @Override + public void setBlock(final int x, final int y, final int z, final Block blk) { + if (this.range(x, y, z)) { + this.verticalBits |= 1 << (y >> 4); + this.getWorld().setBlock(x, y, z, blk, 0, 1); + } + } - @Override - public Block getBlock( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.target.getBlock( x & 0xF, y, z & 0xF ); - } - return Platform.AIR_BLOCK; - } + @Override + public void setBlock( + final int x, + final int y, + final int z, + final Block block, + final int meta, + final int flags + ) { + if (this.range(x, y, z)) { + this.verticalBits |= 1 << (y >> 4); + this.getWorld().setBlock(x, y, z, block, meta, flags & (~2)); + } + } - @Override - public void setBlock( final int x, final int y, final int z, final Block blk ) - { - if( this.range( x, y, z ) ) - { - this.verticalBits |= 1 << ( y >> 4 ); - this.getWorld().setBlock( x, y, z, blk, 0, 1 ); - } - } + @Override + public void done() { + if (this.verticalBits != 0) { + Platform.sendChunk(this.target, this.verticalBits); + } + } - @Override - public void setBlock( final int x, final int y, final int z, final Block block, final int meta, final int flags ) - { - if( this.range( x, y, z ) ) - { - this.verticalBits |= 1 << ( y >> 4 ); - this.getWorld().setBlock( x, y, z, block, meta, flags & ( ~2 ) ); - } - } - - @Override - public void done() - { - if( this.verticalBits != 0 ) - { - Platform.sendChunk( this.target, this.verticalBits ); - } - } - - @Override - public boolean range( final int x, final int y, final int z ) - { - return this.cx == ( x >> 4 ) && this.cz == ( z >> 4 ); - } + @Override + public boolean range(final int x, final int y, final int z) { + return this.cx == (x >> 4) && this.cz == (z >> 4); + } } diff --git a/src/main/java/appeng/worldgen/meteorite/Fallout.java b/src/main/java/appeng/worldgen/meteorite/Fallout.java index e0be26ab..ab3cde03 100644 --- a/src/main/java/appeng/worldgen/meteorite/Fallout.java +++ b/src/main/java/appeng/worldgen/meteorite/Fallout.java @@ -1,78 +1,57 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.init.Blocks; +public class Fallout { + private final MeteoriteBlockPutter putter; + private final IBlockDefinition skyStoneDefinition; -public class Fallout -{ - private final MeteoriteBlockPutter putter; - private final IBlockDefinition skyStoneDefinition; + public Fallout( + final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition + ) { + this.putter = putter; + this.skyStoneDefinition = skyStoneDefinition; + } - public Fallout( final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - this.putter = putter; - this.skyStoneDefinition = skyStoneDefinition; - } + public int adjustCrater() { + return 0; + } - public int adjustCrater() - { - return 0; - } + public void + getRandomFall(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > 0.9) { + this.putter.put(w, x, y, z, Blocks.stone); + } else if (a > 0.8) { + this.putter.put(w, x, y, z, Blocks.cobblestone); + } else if (a > 0.7) { + this.putter.put(w, x, y, z, Blocks.dirt); + } else { + this.putter.put(w, x, y, z, Blocks.gravel); + } + } - public void getRandomFall( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > 0.9 ) - { - this.putter.put( w, x, y, z, Blocks.stone ); - } - else if( a > 0.8 ) - { - this.putter.put( w, x, y, z, Blocks.cobblestone ); - } - else if( a > 0.7 ) - { - this.putter.put( w, x, y, z, Blocks.dirt ); - } - else - { - this.putter.put( w, x, y, z, Blocks.gravel ); - } - } - - public void getRandomInset( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > 0.9 ) - { - this.putter.put( w, x, y, z, Blocks.cobblestone ); - } - else if( a > 0.8 ) - { - this.putter.put( w, x, y, z, Blocks.stone ); - } - else if( a > 0.7 ) - { - this.putter.put( w, x, y, z, Blocks.grass ); - } - else if( a > 0.6 ) - { - for( final Block skyStoneBlock : this.skyStoneDefinition.maybeBlock().asSet() ) - { - this.putter.put( w, x, y, z, skyStoneBlock ); - } - } - else if( a > 0.5 ) - { - this.putter.put( w, x, y, z, Blocks.gravel ); - } - else - { - this.putter.put( w, x, y, z, Platform.AIR_BLOCK ); - } - } + public void + getRandomInset(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > 0.9) { + this.putter.put(w, x, y, z, Blocks.cobblestone); + } else if (a > 0.8) { + this.putter.put(w, x, y, z, Blocks.stone); + } else if (a > 0.7) { + this.putter.put(w, x, y, z, Blocks.grass); + } else if (a > 0.6) { + for (final Block skyStoneBlock : + this.skyStoneDefinition.maybeBlock().asSet()) { + this.putter.put(w, x, y, z, skyStoneBlock); + } + } else if (a > 0.5) { + this.putter.put(w, x, y, z, Blocks.gravel); + } else { + this.putter.put(w, x, y, z, Platform.AIR_BLOCK); + } + } } diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java index e3660c20..7e0c6d5f 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutCopy.java @@ -1,63 +1,57 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import appeng.util.Platform; import net.minecraft.block.Block; +public class FalloutCopy extends Fallout { + private static final double SPECIFIED_BLOCK_THRESHOLD = 0.9; + private static final double AIR_BLOCK_THRESHOLD = 0.8; + private static final double BLOCK_THRESHOLD_STEP = 0.1; -public class FalloutCopy extends Fallout -{ - private static final double SPECIFIED_BLOCK_THRESHOLD = 0.9; - private static final double AIR_BLOCK_THRESHOLD = 0.8; - private static final double BLOCK_THRESHOLD_STEP = 0.1; + private final Block block; + private final int meta; + private final MeteoriteBlockPutter putter; - private final Block block; - private final int meta; - private final MeteoriteBlockPutter putter; + public FalloutCopy( + final IMeteoriteWorld w, + final int x, + final int y, + final int z, + final MeteoriteBlockPutter putter, + final IBlockDefinition skyStoneDefinition + ) { + super(putter, skyStoneDefinition); + this.putter = putter; + this.block = w.getBlock(x, y, z); + this.meta = w.getBlockMetadata(x, y, z); + } - public FalloutCopy( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( putter, skyStoneDefinition ); - this.putter = putter; - this.block = w.getBlock( x, y, z ); - this.meta = w.getBlockMetadata( x, y, z ); - } + @Override + public void + getRandomFall(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > SPECIFIED_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, this.block, this.meta); + } else { + this.getOther(w, x, y, z, a); + } + } - @Override - public void getRandomFall( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > SPECIFIED_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, this.block, this.meta ); - } - else - { - this.getOther( w, x, y, z, a ); - } - } + public void getOther( + final IMeteoriteWorld w, final int x, final int y, final int z, final double a + ) {} - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - - } - - @Override - public void getRandomInset( final IMeteoriteWorld w, final int x, final int y, final int z ) - { - final double a = Math.random(); - if( a > SPECIFIED_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, this.block, this.meta ); - } - else if( a > AIR_BLOCK_THRESHOLD ) - { - this.putter.put( w, x, y, z, Platform.AIR_BLOCK ); - } - else - { - this.getOther( w, x, y, z, a - BLOCK_THRESHOLD_STEP ); - } - } + @Override + public void + getRandomInset(final IMeteoriteWorld w, final int x, final int y, final int z) { + final double a = Math.random(); + if (a > SPECIFIED_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, this.block, this.meta); + } else if (a > AIR_BLOCK_THRESHOLD) { + this.putter.put(w, x, y, z, Platform.AIR_BLOCK); + } else { + this.getOther(w, x, y, z, a - BLOCK_THRESHOLD_STEP); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java index fe1ad5dd..348c227b 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSand.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSand.java @@ -1,33 +1,35 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import net.minecraft.init.Blocks; +public class FalloutSand extends FalloutCopy { + private static final double GLASS_THRESHOLD = 0.66; + private final MeteoriteBlockPutter putter; -public class FalloutSand extends FalloutCopy -{ - private static final double GLASS_THRESHOLD = 0.66; - private final MeteoriteBlockPutter putter; + public FalloutSand( + final IMeteoriteWorld w, + final int x, + final int y, + final int z, + final MeteoriteBlockPutter putter, + final IBlockDefinition skyStoneDefinition + ) { + super(w, x, y, z, putter, skyStoneDefinition); + this.putter = putter; + } - public FalloutSand( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( w, x, y, z, putter, skyStoneDefinition ); - this.putter = putter; - } + @Override + public int adjustCrater() { + return 2; + } - @Override - public int adjustCrater() - { - return 2; - } - - @Override - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - if( a > GLASS_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.glass ); - } - } + @Override + public void getOther( + final IMeteoriteWorld w, final int x, final int y, final int z, final double a + ) { + 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 7030a568..40ce7f08 100644 --- a/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java +++ b/src/main/java/appeng/worldgen/meteorite/FalloutSnow.java @@ -1,38 +1,38 @@ package appeng.worldgen.meteorite; - import appeng.api.definitions.IBlockDefinition; import net.minecraft.init.Blocks; +public class FalloutSnow extends FalloutCopy { + private static final double SNOW_THRESHOLD = 0.7; + private static final double ICE_THRESHOLD = 0.5; + private final MeteoriteBlockPutter putter; -public class FalloutSnow extends FalloutCopy -{ - private static final double SNOW_THRESHOLD = 0.7; - private static final double ICE_THRESHOLD = 0.5; - private final MeteoriteBlockPutter putter; + public FalloutSnow( + final IMeteoriteWorld w, + final int x, + final int y, + final int z, + final MeteoriteBlockPutter putter, + final IBlockDefinition skyStoneDefinition + ) { + super(w, x, y, z, putter, skyStoneDefinition); + this.putter = putter; + } - public FalloutSnow( final IMeteoriteWorld w, final int x, final int y, final int z, final MeteoriteBlockPutter putter, final IBlockDefinition skyStoneDefinition ) - { - super( w, x, y, z, putter, skyStoneDefinition ); - this.putter = putter; - } + @Override + public int adjustCrater() { + return 2; + } - @Override - public int adjustCrater() - { - return 2; - } - - @Override - public void getOther( final IMeteoriteWorld w, final int x, final int y, final int z, final double a ) - { - if( a > SNOW_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.snow ); - } - else if( a > ICE_THRESHOLD ) - { - this.putter.put( w, x, y, z, Blocks.ice ); - } - } + @Override + public void getOther( + final IMeteoriteWorld w, final int x, final int y, final int z, final double a + ) { + if (a > SNOW_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.snow); + } else if (a > ICE_THRESHOLD) { + this.putter.put(w, x, y, z, Blocks.ice); + } + } } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java b/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java index 34eda3de..12b43ba9 100644 --- a/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java +++ b/src/main/java/appeng/worldgen/meteorite/IMeteoriteWorld.java @@ -1,36 +1,33 @@ package appeng.worldgen.meteorite; - import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public interface IMeteoriteWorld { + int minX(int in); -public interface IMeteoriteWorld -{ - int minX( int in ); + int minZ(int in); - int minZ( int in ); + int maxX(int in); - int maxX( int in ); + int maxZ(int in); - int maxZ( int in ); + boolean hasNoSky(); - boolean hasNoSky(); + int getBlockMetadata(int x, int y, int z); - int getBlockMetadata( int x, int y, int z ); + Block getBlock(int x, int y, int z); - Block getBlock( int x, int y, int z ); + boolean canBlockSeeTheSky(int i, int j, int k); - boolean canBlockSeeTheSky( int i, int j, int k ); + TileEntity getTileEntity(int x, int y, int z); - TileEntity getTileEntity( int x, int y, int z ); + World getWorld(); - World getWorld(); + void setBlock(int i, int j, int k, Block blk); - void setBlock( int i, int j, int k, Block blk ); + void setBlock(int i, int j, int k, Block block, int meta, int l); - void setBlock( int i, int j, int k, Block block, int meta, int l ); - - void done(); + void done(); } \ No newline at end of file diff --git a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java index e27aa48e..9c53c429 100644 --- a/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java +++ b/src/main/java/appeng/worldgen/meteorite/MeteoriteBlockPutter.java @@ -1,32 +1,32 @@ package appeng.worldgen.meteorite; - import net.minecraft.block.Block; import net.minecraft.init.Blocks; +public class MeteoriteBlockPutter { + public boolean + put(final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk) { + final Block original = w.getBlock(i, j, k); -public class MeteoriteBlockPutter -{ - public boolean put( final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk ) - { - final Block original = w.getBlock( i, j, k ); + if (original == Blocks.bedrock || original == blk) { + return false; + } - if( original == Blocks.bedrock || original == blk ) - { - return false; - } + w.setBlock(i, j, k, blk); + return true; + } - w.setBlock( i, j, k, blk ); - return true; - } + void + put(final IMeteoriteWorld w, + final int i, + final int j, + final int k, + final Block blk, + final int meta) { + if (w.getBlock(i, j, k) == Blocks.bedrock) { + return; + } - void put( final IMeteoriteWorld w, final int i, final int j, final int k, final Block blk, final int meta ) - { - if( w.getBlock( i, j, k ) == Blocks.bedrock ) - { - return; - } - - w.setBlock( i, j, k, blk, meta, 3 ); - } + w.setBlock(i, j, k, blk, meta, 3); + } } diff --git a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java index 7425ba12..52e934e5 100644 --- a/src/main/java/appeng/worldgen/meteorite/StandardWorld.java +++ b/src/main/java/appeng/worldgen/meteorite/StandardWorld.java @@ -1,124 +1,104 @@ package appeng.worldgen.meteorite; - import appeng.util.Platform; import net.minecraft.block.Block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; +public class StandardWorld implements IMeteoriteWorld { + private final World w; -public class StandardWorld implements IMeteoriteWorld -{ + public StandardWorld(final World w) { + this.w = w; + } - private final World w; + @Override + public int minX(final int in) { + return in; + } - public StandardWorld( final World w ) - { - this.w = w; - } + @Override + public int minZ(final int in) { + return in; + } - @Override - public int minX( final int in ) - { - return in; - } + @Override + public int maxX(final int in) { + return in; + } - @Override - public int minZ( final int in ) - { - return in; - } + @Override + public int maxZ(final int in) { + return in; + } - @Override - public int maxX( final int in ) - { - return in; - } + @Override + public boolean hasNoSky() { + return !this.getWorld().provider.hasNoSky; + } - @Override - public int maxZ( final int in ) - { - return in; - } + @Override + public int getBlockMetadata(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getBlockMetadata(x, y, z); + } + return 0; + } - @Override - public boolean hasNoSky() - { - return !this.getWorld().provider.hasNoSky; - } + @Override + public Block getBlock(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getBlock(x, y, z); + } + return Platform.AIR_BLOCK; + } - @Override - public int getBlockMetadata( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getBlockMetadata( x, y, z ); - } - return 0; - } + @Override + public boolean canBlockSeeTheSky(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().canBlockSeeTheSky(x, y, z); + } + return false; + } - @Override - public Block getBlock( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getBlock( x, y, z ); - } - return Platform.AIR_BLOCK; - } + @Override + public TileEntity getTileEntity(final int x, final int y, final int z) { + if (this.range(x, y, z)) { + return this.getWorld().getTileEntity(x, y, z); + } + return null; + } - @Override - public boolean canBlockSeeTheSky( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().canBlockSeeTheSky( x, y, z ); - } - return false; - } + @Override + public World getWorld() { + return this.w; + } - @Override - public TileEntity getTileEntity( final int x, final int y, final int z ) - { - if( this.range( x, y, z ) ) - { - return this.getWorld().getTileEntity( x, y, z ); - } - return null; - } + @Override + public void setBlock(final int x, final int y, final int z, final Block blk) { + if (this.range(x, y, z)) { + this.getWorld().setBlock(x, y, z, blk); + } + } - @Override - public World getWorld() - { - return this.w; - } + @Override + public void setBlock( + final int x, + final int y, + final int z, + final Block block, + final int meta, + final int flags + ) { + if (this.range(x, y, z)) { + this.getWorld().setBlock(x, y, z, block, meta, flags); + } + } - @Override - public void setBlock( final int x, final int y, final int z, final Block blk ) - { - if( this.range( x, y, z ) ) - { - this.getWorld().setBlock( x, y, z, blk ); - } - } + @Override + public void done() {} - @Override - public void setBlock( final int x, final int y, final int z, final Block block, final int meta, final int flags ) - { - if( this.range( x, y, z ) ) - { - this.getWorld().setBlock( x, y, z, block, meta, flags ); - } - } - - @Override - public void done() - { - - } - - public boolean range( final int x, final int y, final int z ) - { - return true; - } + public boolean range(final int x, final int y, final int z) { + return true; + } } diff --git a/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java b/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java index f66575b0..07d09b4c 100644 --- a/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java +++ b/src/test/java/appeng/core/worlddata/MeteorDataNameEncoderTest.java @@ -18,11 +18,9 @@ package appeng.core.worlddata; - import org.junit.Assert; import org.junit.Test; - /** * Tests for {@link MeteorDataNameEncoder} * @@ -30,36 +28,39 @@ import org.junit.Test; * @version rv3 - 06.06.2015 * @since rv3 06.06.2015 */ -public class MeteorDataNameEncoderTest -{ - private static final int WITHOUT_DIMENSION = -5; - private static final int WITHOUT_CHUNK_X = 0; - private static final int WITHOUT_CHUNK_Z = 13; - private static final String WITHOUT_EXPECTED = "-5_0_13.dat"; +public class MeteorDataNameEncoderTest { + private static final int WITHOUT_DIMENSION = -5; + private static final int WITHOUT_CHUNK_X = 0; + private static final int WITHOUT_CHUNK_Z = 13; + private static final String WITHOUT_EXPECTED = "-5_0_13.dat"; - private static final int WITH_DIMENSION = 3; - private static final int WITH_CHUNK_X = 32; - private static final int WITH_CHUNK_Z = -64; - private static final String WITH_EXPECTED = "3_2_-4.dat"; + private static final int WITH_DIMENSION = 3; + private static final int WITH_CHUNK_X = 32; + private static final int WITH_CHUNK_Z = -64; + private static final String WITH_EXPECTED = "3_2_-4.dat"; - private final MeteorDataNameEncoder encoderWithZeroShifting = new MeteorDataNameEncoder( 0 ); - private final MeteorDataNameEncoder encoderWithFourShifting = new MeteorDataNameEncoder( 4 ); + private final MeteorDataNameEncoder encoderWithZeroShifting + = new MeteorDataNameEncoder(0); + private final MeteorDataNameEncoder encoderWithFourShifting + = new MeteorDataNameEncoder(4); - @Test - public void testEncoderWithoutShifting() - { - final String expected = WITHOUT_EXPECTED; - final String actual = this.encoderWithZeroShifting.encode( WITHOUT_DIMENSION, WITHOUT_CHUNK_X, WITHOUT_CHUNK_Z ); + @Test + public void testEncoderWithoutShifting() { + final String expected = WITHOUT_EXPECTED; + final String actual = this.encoderWithZeroShifting.encode( + WITHOUT_DIMENSION, WITHOUT_CHUNK_X, WITHOUT_CHUNK_Z + ); - Assert.assertEquals( expected, actual ); - } + Assert.assertEquals(expected, actual); + } - @Test - public void testEncoderWithShifting() - { - final String expected = WITH_EXPECTED; - final String actual = this.encoderWithFourShifting.encode( WITH_DIMENSION, WITH_CHUNK_X, WITH_CHUNK_Z ); + @Test + public void testEncoderWithShifting() { + final String expected = WITH_EXPECTED; + final String actual = this.encoderWithFourShifting.encode( + WITH_DIMENSION, WITH_CHUNK_X, WITH_CHUNK_Z + ); - Assert.assertEquals( expected, actual ); - } + Assert.assertEquals(expected, actual); + } } diff --git a/src/test/java/appeng/services/version/ModVersionFetcherTest.java b/src/test/java/appeng/services/version/ModVersionFetcherTest.java index c6f20e1e..ffd88c62 100644 --- a/src/test/java/appeng/services/version/ModVersionFetcherTest.java +++ b/src/test/java/appeng/services/version/ModVersionFetcherTest.java @@ -18,48 +18,41 @@ package appeng.services.version; - import org.junit.Assert; import org.junit.Test; - /** * @author thatsIch * @version rv3 - 16.05.2015 * @since rv3 16.05.2015 */ -public class ModVersionFetcherTest -{ - // private static final ModVersionFetcher FETCHER = new ModVersionFetcher( ) +public class ModVersionFetcherTest { + // private static final ModVersionFetcher FETCHER = new ModVersionFetcher( ) - private final ModVersionFetcher indev; - private final ModVersionFetcher pullRequest; - private final ModVersionFetcher working; + private final ModVersionFetcher indev; + private final ModVersionFetcher pullRequest; + private final ModVersionFetcher working; - public ModVersionFetcherTest() - { - final VersionParser parser = new VersionParser(); + public ModVersionFetcherTest() { + final VersionParser parser = new VersionParser(); - this.indev = new ModVersionFetcher( "@version@", parser ); - this.pullRequest = new ModVersionFetcher( "pr", parser ); - this.working = new ModVersionFetcher( "rv2-beta-8", parser ); - } + this.indev = new ModVersionFetcher("@version@", parser); + this.pullRequest = new ModVersionFetcher("pr", parser); + this.working = new ModVersionFetcher("rv2-beta-8", parser); + } - @Test - public void testInDev() throws Exception - { - Assert.assertEquals( this.indev.get(), new DoNotCheckVersion() ); - } + @Test + public void testInDev() throws Exception { + Assert.assertEquals(this.indev.get(), new DoNotCheckVersion()); + } - @Test - public void testPR() throws Exception - { - Assert.assertEquals( this.pullRequest.get(), new DoNotCheckVersion() ); - } + @Test + public void testPR() throws Exception { + Assert.assertEquals(this.pullRequest.get(), new DoNotCheckVersion()); + } - @Test - public void testWorking() throws Exception - { - Assert.assertEquals( this.working.get(), new DefaultVersion( 2, Channel.Beta, 8 ) ); - } + @Test + public void testWorking() throws Exception { + Assert.assertEquals(this.working.get(), new DefaultVersion(2, Channel.Beta, 8)); + } } diff --git a/src/test/java/appeng/services/version/VersionParserTest.java b/src/test/java/appeng/services/version/VersionParserTest.java index 3590a297..55b440cc 100644 --- a/src/test/java/appeng/services/version/VersionParserTest.java +++ b/src/test/java/appeng/services/version/VersionParserTest.java @@ -1,102 +1,87 @@ package appeng.services.version; +import static org.junit.Assert.*; import appeng.services.version.exceptions.*; import org.junit.Test; -import static org.junit.Assert.*; - - /** * Tests for {@link VersionParser} */ -public final class VersionParserTest -{ - private static final String GITHUB_VERSION = "rv2.beta.8"; - private static final String GITHUB_INVALID_REVISION = "2.beta.8"; - private static final String GITHUB_INVALID_CHANNEL = "rv2.gamma.8"; - private static final String GITHUB_INVALID_BUILD = "rv2.beta.b8"; - private static final String MOD_VERSION = "rv2-beta-8"; - private static final String MOD_INVALID_REVISION = "2-beta-8"; - private static final String MOD_INVALID_CHANNEL = "rv2-gamma-8"; - private static final String MOD_INVALID_BUILD = "rv2-beta-b8"; - private static final String GENERIC_MISSING_SEPARATOR = "foobar"; - private static final String GENERIC_INVALID_VERSION = "foo-bar"; +public final class VersionParserTest { + private static final String GITHUB_VERSION = "rv2.beta.8"; + private static final String GITHUB_INVALID_REVISION = "2.beta.8"; + private static final String GITHUB_INVALID_CHANNEL = "rv2.gamma.8"; + private static final String GITHUB_INVALID_BUILD = "rv2.beta.b8"; + private static final String MOD_VERSION = "rv2-beta-8"; + private static final String MOD_INVALID_REVISION = "2-beta-8"; + private static final String MOD_INVALID_CHANNEL = "rv2-gamma-8"; + private static final String MOD_INVALID_BUILD = "rv2-beta-b8"; + private static final String GENERIC_MISSING_SEPARATOR = "foobar"; + private static final String GENERIC_INVALID_VERSION = "foo-bar"; - private static final DefaultVersion VERSION = new DefaultVersion( 2, Channel.Beta, 8 ); + private static final DefaultVersion VERSION = new DefaultVersion(2, Channel.Beta, 8); - private final VersionParser parser; + private final VersionParser parser; - public VersionParserTest() - { - this.parser = new VersionParser(); - } + public VersionParserTest() { + this.parser = new VersionParser(); + } - @Test - public void testSameParsedGitHub() throws VersionCheckerException - { - final Version version = this.parser.parse( GITHUB_VERSION ); + @Test + public void testSameParsedGitHub() throws VersionCheckerException { + final Version version = this.parser.parse(GITHUB_VERSION); - assertEquals( version, version ); - } + assertEquals(version, version); + } - @Test - public void testParseGitHub() throws VersionCheckerException - { - assertTrue( this.parser.parse( GITHUB_VERSION ).equals( VERSION ) ); - } + @Test + public void testParseGitHub() throws VersionCheckerException { + assertTrue(this.parser.parse(GITHUB_VERSION).equals(VERSION)); + } - @Test( expected = InvalidRevisionException.class ) - public void parseGH_InvalidRevision() throws VersionCheckerException - { - assertFalse( this.parser.parse( GITHUB_INVALID_REVISION ).equals( VERSION ) ); - } + @Test(expected = InvalidRevisionException.class) + public void parseGH_InvalidRevision() throws VersionCheckerException { + assertFalse(this.parser.parse(GITHUB_INVALID_REVISION).equals(VERSION)); + } - @Test( expected = InvalidChannelException.class ) - public void parseGH_InvalidChannel() throws VersionCheckerException - { - assertFalse( this.parser.parse( GITHUB_INVALID_CHANNEL ).equals( VERSION ) ); - } + @Test(expected = InvalidChannelException.class) + public void parseGH_InvalidChannel() throws VersionCheckerException { + assertFalse(this.parser.parse(GITHUB_INVALID_CHANNEL).equals(VERSION)); + } - @Test( expected = InvalidBuildException.class ) - public void parseGH_InvalidBuild() throws VersionCheckerException - { - assertFalse( this.parser.parse( GITHUB_INVALID_BUILD ).equals( VERSION ) ); - } + @Test(expected = InvalidBuildException.class) + public void parseGH_InvalidBuild() throws VersionCheckerException { + assertFalse(this.parser.parse(GITHUB_INVALID_BUILD).equals(VERSION)); + } - @Test - public void testParseMod() throws VersionCheckerException - { - assertTrue( this.parser.parse( MOD_VERSION ).equals( VERSION ) ); - } + @Test + public void testParseMod() throws VersionCheckerException { + assertTrue(this.parser.parse(MOD_VERSION).equals(VERSION)); + } - @Test( expected = InvalidRevisionException.class ) - public void parseMod_InvalidRevision() throws VersionCheckerException - { - assertFalse( this.parser.parse( MOD_INVALID_REVISION ).equals( VERSION ) ); - } + @Test(expected = InvalidRevisionException.class) + public void parseMod_InvalidRevision() throws VersionCheckerException { + assertFalse(this.parser.parse(MOD_INVALID_REVISION).equals(VERSION)); + } - @Test( expected = InvalidChannelException.class ) - public void parseMod_InvalidChannel() throws VersionCheckerException - { - assertFalse( this.parser.parse( MOD_INVALID_CHANNEL ).equals( VERSION ) ); - } + @Test(expected = InvalidChannelException.class) + public void parseMod_InvalidChannel() throws VersionCheckerException { + assertFalse(this.parser.parse(MOD_INVALID_CHANNEL).equals(VERSION)); + } - @Test( expected = InvalidBuildException.class ) - public void parseMod_InvalidBuild() throws VersionCheckerException - { - assertFalse( this.parser.parse( MOD_INVALID_BUILD ).equals( VERSION ) ); - } + @Test(expected = InvalidBuildException.class) + public void parseMod_InvalidBuild() throws VersionCheckerException { + assertFalse(this.parser.parse(MOD_INVALID_BUILD).equals(VERSION)); + } - @Test( expected = MissingSeparatorException.class ) - public void parseGeneric_MissingSeparator() throws VersionCheckerException - { - assertFalse( this.parser.parse( GENERIC_MISSING_SEPARATOR ).equals( VERSION ) ); - } + @Test(expected = MissingSeparatorException.class) + public void parseGeneric_MissingSeparator() throws VersionCheckerException { + assertFalse(this.parser.parse(GENERIC_MISSING_SEPARATOR).equals(VERSION)); + } - @Test( expected = InvalidVersionException.class ) - public void parseGeneric_InvalidVersion() throws VersionCheckerException - { - assertFalse( this.parser.parse( GENERIC_INVALID_VERSION ).equals( VERSION ) ); - } + @Test(expected = InvalidVersionException.class) + public void parseGeneric_InvalidVersion() throws VersionCheckerException { + assertFalse(this.parser.parse(GENERIC_INVALID_VERSION).equals(VERSION)); + } } diff --git a/src/test/java/appeng/services/version/VersionTest.java b/src/test/java/appeng/services/version/VersionTest.java index 9f89fef5..aef71a13 100644 --- a/src/test/java/appeng/services/version/VersionTest.java +++ b/src/test/java/appeng/services/version/VersionTest.java @@ -18,11 +18,9 @@ package appeng.services.version; - import org.junit.Assert; import org.junit.Test; - /** * Tests for {@link Version} * @@ -30,87 +28,84 @@ import org.junit.Test; * @version rv3 - 16.05.2015 * @since rv3 16.05.2015 */ -public final class VersionTest -{ - private static final Version DEFAULT_VERSION_RV2_BETA_8 = new DefaultVersion( 2, Channel.Beta, 8 ); - private static final Version DEFAULT_VERSION_RV2_BETA_9 = new DefaultVersion( 2, Channel.Beta, 9 ); - private static final Version DEFAULT_VERSION_RV3_BETA_8 = new DefaultVersion( 3, Channel.Beta, 8 ); - private static final Version DEFAULT_VERSION_RV2_ALPHA_8 = new DefaultVersion( 2, Channel.Alpha, 8 ); - private static final Version DO_NOT_CHECK_VERSION = new DoNotCheckVersion(); - private static final Version MISSING_VERSION = new MissingVersion(); +public final class VersionTest { + private static final Version DEFAULT_VERSION_RV2_BETA_8 + = new DefaultVersion(2, Channel.Beta, 8); + private static final Version DEFAULT_VERSION_RV2_BETA_9 + = new DefaultVersion(2, Channel.Beta, 9); + private static final Version DEFAULT_VERSION_RV3_BETA_8 + = new DefaultVersion(3, Channel.Beta, 8); + private static final Version DEFAULT_VERSION_RV2_ALPHA_8 + = new DefaultVersion(2, Channel.Alpha, 8); + private static final Version DO_NOT_CHECK_VERSION = new DoNotCheckVersion(); + private static final Version MISSING_VERSION = new MissingVersion(); - @Test - public void testDevBuild() - { - Assert.assertEquals( DO_NOT_CHECK_VERSION.formatted(), "dev build" ); - } + @Test + public void testDevBuild() { + Assert.assertEquals(DO_NOT_CHECK_VERSION.formatted(), "dev build"); + } - @Test - public void testMissingBuild() - { - Assert.assertEquals( MISSING_VERSION.formatted(), "missing" ); - } + @Test + public void testMissingBuild() { + Assert.assertEquals(MISSING_VERSION.formatted(), "missing"); + } - @Test - public void compareVersionToDoNotCheck() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs( DO_NOT_CHECK_VERSION ) ); - Assert.assertTrue( DO_NOT_CHECK_VERSION.isNewerAs( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } + @Test + public void compareVersionToDoNotCheck() { + Assert.assertFalse(DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs(DO_NOT_CHECK_VERSION)); + Assert.assertTrue(DO_NOT_CHECK_VERSION.isNewerAs(DEFAULT_VERSION_RV2_ALPHA_8)); + } - @Test - public void compareVersionToMissingVersion() - { - Assert.assertTrue( DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs( MISSING_VERSION ) ); - Assert.assertFalse( MISSING_VERSION.isNewerAs( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } + @Test + public void compareVersionToMissingVersion() { + Assert.assertTrue(DEFAULT_VERSION_RV2_ALPHA_8.isNewerAs(MISSING_VERSION)); + Assert.assertFalse(MISSING_VERSION.isNewerAs(DEFAULT_VERSION_RV2_ALPHA_8)); + } - @Test - public void compareTwoDefaultVersions() - { - Assert.assertTrue( DEFAULT_VERSION_RV2_BETA_8.isNewerAs( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } + @Test + public void compareTwoDefaultVersions() { + Assert.assertTrue(DEFAULT_VERSION_RV2_BETA_8.isNewerAs(DEFAULT_VERSION_RV2_ALPHA_8 + )); + } - @Test - public void testEqualsNonVersion() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_ALPHA_8.equals( new Object() ) ); - } + @Test + public void testEqualsNonVersion() { + Assert.assertFalse(DEFAULT_VERSION_RV2_ALPHA_8.equals(new Object())); + } - @Test - public void testEqualsUnequalBuild() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_BETA_8.equals( DEFAULT_VERSION_RV2_BETA_9 ) ); - } + @Test + public void testEqualsUnequalBuild() { + Assert.assertFalse(DEFAULT_VERSION_RV2_BETA_8.equals(DEFAULT_VERSION_RV2_BETA_9)); + } - @Test - public void testEqualsUnequalChannel() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_BETA_8.equals( DEFAULT_VERSION_RV2_ALPHA_8 ) ); - } + @Test + public void testEqualsUnequalChannel() { + Assert.assertFalse(DEFAULT_VERSION_RV2_BETA_8.equals(DEFAULT_VERSION_RV2_ALPHA_8) + ); + } - @Test - public void testEqualsUnequalRevision() - { - Assert.assertFalse( DEFAULT_VERSION_RV2_BETA_8.equals( DEFAULT_VERSION_RV3_BETA_8 ) ); - } + @Test + public void testEqualsUnequalRevision() { + Assert.assertFalse(DEFAULT_VERSION_RV2_BETA_8.equals(DEFAULT_VERSION_RV3_BETA_8)); + } - @Test - public void testUnequalHash() - { - Assert.assertNotEquals( DEFAULT_VERSION_RV2_BETA_8.hashCode(), DEFAULT_VERSION_RV2_ALPHA_8.hashCode() ); - } + @Test + public void testUnequalHash() { + Assert.assertNotEquals( + DEFAULT_VERSION_RV2_BETA_8.hashCode(), DEFAULT_VERSION_RV2_ALPHA_8.hashCode() + ); + } - @Test - public void testToString() - { - Assert.assertEquals( DEFAULT_VERSION_RV2_BETA_8.toString(), "Version{revision=2, channel=Beta, build=8}" ); - } - - @Test - public void testFormatted() - { - Assert.assertEquals( DEFAULT_VERSION_RV2_BETA_8.formatted(), "rv2-beta-8" ); - } + @Test + public void testToString() { + Assert.assertEquals( + DEFAULT_VERSION_RV2_BETA_8.toString(), + "Version{revision=2, channel=Beta, build=8}" + ); + } + @Test + public void testFormatted() { + Assert.assertEquals(DEFAULT_VERSION_RV2_BETA_8.formatted(), "rv2-beta-8"); + } } diff --git a/src/test/java/appeng/util/SlimReadableNumberConverterTest.java b/src/test/java/appeng/util/SlimReadableNumberConverterTest.java index 16413a31..4657756d 100644 --- a/src/test/java/appeng/util/SlimReadableNumberConverterTest.java +++ b/src/test/java/appeng/util/SlimReadableNumberConverterTest.java @@ -1,10 +1,8 @@ package appeng.util; - -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; /** * Test for {@link ISlimReadableNumberConverter} @@ -13,115 +11,107 @@ import static org.junit.Assert.assertEquals; * @version rv2 * @since rv2 */ -public final class SlimReadableNumberConverterTest -{ - private static final long NUMBER_NEG_999999 = -999999L; - private static final String RESULT_NEG_999999 = "-0M"; +public final class SlimReadableNumberConverterTest { + private static final long NUMBER_NEG_999999 = -999999L; + private static final String RESULT_NEG_999999 = "-0M"; - private static final long NUMBER_NEG_9999 = -9999L; - private static final String RESULT_NEG_9999 = "-9K"; + private static final long NUMBER_NEG_9999 = -9999L; + private static final String RESULT_NEG_9999 = "-9K"; - private static final long NUMBER_NEG_999 = -999L; - private static final String RESULT_NEG_999 = "-0K"; + private static final long NUMBER_NEG_999 = -999L; + private static final String RESULT_NEG_999 = "-0K"; - private static final long NUMBER_0 = 0L; - private static final String RESULT_0 = "0"; + private static final long NUMBER_0 = 0L; + private static final String RESULT_0 = "0"; - private static final long NUMBER_999 = 999L; - private static final String RESULT_999 = "999"; + private static final long NUMBER_999 = 999L; + private static final String RESULT_999 = "999"; - private static final long NUMBER_9999 = 9999L; - private static final String RESULT_9999 = "9K"; + private static final long NUMBER_9999 = 9999L; + private static final String RESULT_9999 = "9K"; - private static final long NUMBER_10000 = 10000L; - private static final String RESULT_10000 = "10K"; + private static final long NUMBER_10000 = 10000L; + private static final String RESULT_10000 = "10K"; - private static final long NUMBER_10500 = 10500L; - private static final String RESULT_10500 = "10K"; + private static final long NUMBER_10500 = 10500L; + private static final String RESULT_10500 = "10K"; - private static final long NUMBER_155555 = 155555L; - private static final String RESULT_155555 = ".1M"; + private static final long NUMBER_155555 = 155555L; + private static final String RESULT_155555 = ".1M"; - private static final long NUMBER_9999999 = 9999999L; - private static final String RESULT_9999999 = "9M"; + private static final long NUMBER_9999999 = 9999999L; + private static final String RESULT_9999999 = "9M"; - private static final long NUMBER_10000000 = 10000000L; - private static final String RESULT_10000000 = "10M"; + private static final long NUMBER_10000000 = 10000000L; + private static final String RESULT_10000000 = "10M"; - private static final long NUMBER_155555555 = 155555555L; - private static final String RESULT_155555555 = ".1G"; + private static final long NUMBER_155555555 = 155555555L; + private static final String RESULT_155555555 = ".1G"; - private final ISlimReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + private final ISlimReadableNumberConverter converter + = ReadableNumberConverter.INSTANCE; - @Test( expected = AssertionError.class ) - public void testConvertNeg999999() - { - assertEquals( RESULT_NEG_999999, this.converter.toSlimReadableForm( NUMBER_NEG_999999 ) ); - } + @Test(expected = AssertionError.class) + public void testConvertNeg999999() { + assertEquals( + RESULT_NEG_999999, this.converter.toSlimReadableForm(NUMBER_NEG_999999) + ); + } - @Test( expected = AssertionError.class ) - public void testConvertNeg9999() - { - assertEquals( RESULT_NEG_9999, this.converter.toSlimReadableForm( NUMBER_NEG_9999 ) ); - } + @Test(expected = AssertionError.class) + public void testConvertNeg9999() { + assertEquals(RESULT_NEG_9999, this.converter.toSlimReadableForm(NUMBER_NEG_9999)); + } - @Test( expected = AssertionError.class ) - public void testConvertNeg999() - { - assertEquals( RESULT_NEG_999, this.converter.toSlimReadableForm( NUMBER_NEG_999 ) ); - } + @Test(expected = AssertionError.class) + public void testConvertNeg999() { + assertEquals(RESULT_NEG_999, this.converter.toSlimReadableForm(NUMBER_NEG_999)); + } - @Test - public void testConvert0() - { - assertEquals( RESULT_0, this.converter.toSlimReadableForm( NUMBER_0 ) ); - } + @Test + public void testConvert0() { + assertEquals(RESULT_0, this.converter.toSlimReadableForm(NUMBER_0)); + } - @Test - public void testConvert999() - { - assertEquals( RESULT_999, this.converter.toSlimReadableForm( NUMBER_999 ) ); - } + @Test + public void testConvert999() { + assertEquals(RESULT_999, this.converter.toSlimReadableForm(NUMBER_999)); + } - @Test - public void testConvert9999() - { - assertEquals( RESULT_9999, this.converter.toSlimReadableForm( NUMBER_9999 ) ); - } + @Test + public void testConvert9999() { + assertEquals(RESULT_9999, this.converter.toSlimReadableForm(NUMBER_9999)); + } - @Test - public void testConvert10000() - { - assertEquals( RESULT_10000, this.converter.toSlimReadableForm( NUMBER_10000 ) ); - } + @Test + public void testConvert10000() { + assertEquals(RESULT_10000, this.converter.toSlimReadableForm(NUMBER_10000)); + } - @Test - public void testConvert10500() - { - assertEquals( RESULT_10500, this.converter.toSlimReadableForm( NUMBER_10500 ) ); - } + @Test + public void testConvert10500() { + assertEquals(RESULT_10500, this.converter.toSlimReadableForm(NUMBER_10500)); + } - @Test - public void testConvert155555() - { - assertEquals( RESULT_155555, this.converter.toSlimReadableForm( NUMBER_155555 ) ); - } + @Test + public void testConvert155555() { + assertEquals(RESULT_155555, this.converter.toSlimReadableForm(NUMBER_155555)); + } - @Test - public void testConvert9999999() - { - assertEquals( RESULT_9999999, this.converter.toSlimReadableForm( NUMBER_9999999 ) ); - } + @Test + public void testConvert9999999() { + assertEquals(RESULT_9999999, this.converter.toSlimReadableForm(NUMBER_9999999)); + } - @Test - public void testConvert10000000() - { - assertEquals( RESULT_10000000, this.converter.toSlimReadableForm( NUMBER_10000000 ) ); - } + @Test + public void testConvert10000000() { + assertEquals(RESULT_10000000, this.converter.toSlimReadableForm(NUMBER_10000000)); + } - @Test - public void testConvert155555555() - { - assertEquals( RESULT_155555555, this.converter.toSlimReadableForm( NUMBER_155555555 ) ); - } + @Test + public void testConvert155555555() { + assertEquals( + RESULT_155555555, this.converter.toSlimReadableForm(NUMBER_155555555) + ); + } } diff --git a/src/test/java/appeng/util/UUIDMatcherTest.java b/src/test/java/appeng/util/UUIDMatcherTest.java index 54e52c18..16cc1da5 100644 --- a/src/test/java/appeng/util/UUIDMatcherTest.java +++ b/src/test/java/appeng/util/UUIDMatcherTest.java @@ -18,44 +18,37 @@ package appeng.util; - -import org.junit.Test; - import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import org.junit.Test; /** * Tests for {@link UUIDMatcher} */ -public final class UUIDMatcherTest -{ - private static final String IS_UUID = "03ba29a1-d6bd-32ba-90b2-375e4d65abc9"; - private static final String NO_UUID = "no"; - private static final String INVALID_UUID = "g3ba29a1-d6bd-32ba-90b2-375e4d65abc9"; +public final class UUIDMatcherTest { + private static final String IS_UUID = "03ba29a1-d6bd-32ba-90b2-375e4d65abc9"; + private static final String NO_UUID = "no"; + private static final String INVALID_UUID = "g3ba29a1-d6bd-32ba-90b2-375e4d65abc9"; - private final UUIDMatcher matcher; + private final UUIDMatcher matcher; - public UUIDMatcherTest() - { - this.matcher = new UUIDMatcher(); - } + public UUIDMatcherTest() { + this.matcher = new UUIDMatcher(); + } - @Test - public void testUUID_shouldPass() - { - assertTrue( this.matcher.isUUID( IS_UUID ) ); - } + @Test + public void testUUID_shouldPass() { + assertTrue(this.matcher.isUUID(IS_UUID)); + } - @Test - public void testNoUUD_shouldPass() - { - assertFalse( this.matcher.isUUID( NO_UUID ) ); - } + @Test + public void testNoUUD_shouldPass() { + assertFalse(this.matcher.isUUID(NO_UUID)); + } - @Test - public void testInvalidUUID_shouldPass() - { - assertFalse( this.matcher.isUUID( INVALID_UUID ) ); - } + @Test + public void testInvalidUUID_shouldPass() { + assertFalse(this.matcher.isUUID(INVALID_UUID)); + } } diff --git a/src/test/java/appeng/util/WideReadableNumberConverterTest.java b/src/test/java/appeng/util/WideReadableNumberConverterTest.java index 6b047af5..8bf66c78 100644 --- a/src/test/java/appeng/util/WideReadableNumberConverterTest.java +++ b/src/test/java/appeng/util/WideReadableNumberConverterTest.java @@ -1,10 +1,8 @@ package appeng.util; - -import org.junit.Test; - import static org.junit.Assert.assertEquals; +import org.junit.Test; /** * Test for {@link IWideReadableNumberConverter} @@ -13,115 +11,107 @@ import static org.junit.Assert.assertEquals; * @version rv2 * @since rv2 */ -public final class WideReadableNumberConverterTest -{ - private static final long NUMBER_NEG_999999 = -999999L; - private static final String RESULT_NEG_999999 = "-0M"; +public final class WideReadableNumberConverterTest { + private static final long NUMBER_NEG_999999 = -999999L; + private static final String RESULT_NEG_999999 = "-0M"; - private static final long NUMBER_NEG_9999 = -9999L; - private static final String RESULT_NEG_9999 = "-9K"; + private static final long NUMBER_NEG_9999 = -9999L; + private static final String RESULT_NEG_9999 = "-9K"; - private static final long NUMBER_NEG_999 = -999L; - private static final String RESULT_NEG_999 = "-999"; + private static final long NUMBER_NEG_999 = -999L; + private static final String RESULT_NEG_999 = "-999"; - private static final long NUMBER_0 = 0L; - private static final String RESULT_0 = "0"; + private static final long NUMBER_0 = 0L; + private static final String RESULT_0 = "0"; - private static final long NUMBER_999 = 999L; - private static final String RESULT_999 = "999"; + private static final long NUMBER_999 = 999L; + private static final String RESULT_999 = "999"; - private static final long NUMBER_9999 = 9999L; - private static final String RESULT_9999 = "9999"; + private static final long NUMBER_9999 = 9999L; + private static final String RESULT_9999 = "9999"; - private static final long NUMBER_10000 = 10000L; - private static final String RESULT_10000 = "10K"; + private static final long NUMBER_10000 = 10000L; + private static final String RESULT_10000 = "10K"; - private static final long NUMBER_10500 = 10500L; - private static final String RESULT_10500 = "10K"; + private static final long NUMBER_10500 = 10500L; + private static final String RESULT_10500 = "10K"; - private static final long NUMBER_155555 = 155555L; - private static final String RESULT_155555 = "155K"; + private static final long NUMBER_155555 = 155555L; + private static final String RESULT_155555 = "155K"; - private static final long NUMBER_9999999 = 9999999L; - private static final String RESULT_9999999 = "9.9M"; + private static final long NUMBER_9999999 = 9999999L; + private static final String RESULT_9999999 = "9.9M"; - private static final long NUMBER_10000000 = 10000000L; - private static final String RESULT_10000000 = "10M"; + private static final long NUMBER_10000000 = 10000000L; + private static final String RESULT_10000000 = "10M"; - private static final long NUMBER_155555555 = 155555555L; - private static final String RESULT_155555555 = "155M"; + private static final long NUMBER_155555555 = 155555555L; + private static final String RESULT_155555555 = "155M"; - private final IWideReadableNumberConverter converter = ReadableNumberConverter.INSTANCE; + private final IWideReadableNumberConverter converter + = ReadableNumberConverter.INSTANCE; - @Test( expected = AssertionError.class ) - public void testConvertNeg999999() - { - assertEquals( RESULT_NEG_999999, this.converter.toWideReadableForm( NUMBER_NEG_999999 ) ); - } + @Test(expected = AssertionError.class) + public void testConvertNeg999999() { + assertEquals( + RESULT_NEG_999999, this.converter.toWideReadableForm(NUMBER_NEG_999999) + ); + } - @Test( expected = AssertionError.class ) - public void testConvertNeg9999() - { - assertEquals( RESULT_NEG_9999, this.converter.toWideReadableForm( NUMBER_NEG_9999 ) ); - } + @Test(expected = AssertionError.class) + public void testConvertNeg9999() { + assertEquals(RESULT_NEG_9999, this.converter.toWideReadableForm(NUMBER_NEG_9999)); + } - @Test( expected = AssertionError.class ) - public void testConvertNeg999() - { - assertEquals( RESULT_NEG_999, this.converter.toWideReadableForm( NUMBER_NEG_999 ) ); - } + @Test(expected = AssertionError.class) + public void testConvertNeg999() { + assertEquals(RESULT_NEG_999, this.converter.toWideReadableForm(NUMBER_NEG_999)); + } - @Test - public void testConvert0() - { - assertEquals( RESULT_0, this.converter.toWideReadableForm( NUMBER_0 ) ); - } + @Test + public void testConvert0() { + assertEquals(RESULT_0, this.converter.toWideReadableForm(NUMBER_0)); + } - @Test - public void testConvert999() - { - assertEquals( RESULT_999, this.converter.toWideReadableForm( NUMBER_999 ) ); - } + @Test + public void testConvert999() { + assertEquals(RESULT_999, this.converter.toWideReadableForm(NUMBER_999)); + } - @Test - public void testConvert9999() - { - assertEquals( RESULT_9999, this.converter.toWideReadableForm( NUMBER_9999 ) ); - } + @Test + public void testConvert9999() { + assertEquals(RESULT_9999, this.converter.toWideReadableForm(NUMBER_9999)); + } - @Test - public void testConvert10000() - { - assertEquals( RESULT_10000, this.converter.toWideReadableForm( NUMBER_10000 ) ); - } + @Test + public void testConvert10000() { + assertEquals(RESULT_10000, this.converter.toWideReadableForm(NUMBER_10000)); + } - @Test - public void testConvert10500() - { - assertEquals( RESULT_10500, this.converter.toWideReadableForm( NUMBER_10500 ) ); - } + @Test + public void testConvert10500() { + assertEquals(RESULT_10500, this.converter.toWideReadableForm(NUMBER_10500)); + } - @Test - public void testConvert155555() - { - assertEquals( RESULT_155555, this.converter.toWideReadableForm( NUMBER_155555 ) ); - } + @Test + public void testConvert155555() { + assertEquals(RESULT_155555, this.converter.toWideReadableForm(NUMBER_155555)); + } - @Test - public void testConvert9999999() - { - assertEquals( RESULT_9999999, this.converter.toWideReadableForm( NUMBER_9999999 ) ); - } + @Test + public void testConvert9999999() { + assertEquals(RESULT_9999999, this.converter.toWideReadableForm(NUMBER_9999999)); + } - @Test - public void testConvert10000000() - { - assertEquals( RESULT_10000000, this.converter.toWideReadableForm( NUMBER_10000000 ) ); - } + @Test + public void testConvert10000000() { + assertEquals(RESULT_10000000, this.converter.toWideReadableForm(NUMBER_10000000)); + } - @Test - public void testConvert155555555() - { - assertEquals( RESULT_155555555, this.converter.toWideReadableForm( NUMBER_155555555 ) ); - } + @Test + public void testConvert155555555() { + assertEquals( + RESULT_155555555, this.converter.toWideReadableForm(NUMBER_155555555) + ); + } } From ce2277c8eca0def0a06fb6ba53a5aa5adb053b7a Mon Sep 17 00:00:00 2001 From: LordMZTE Date: Sat, 3 Dec 2022 16:04:40 +0100 Subject: [PATCH 4/4] feat: initial very glitchy transition plane implementation --- .gitignore | 3 +- austri3Fix.md | 2 + .../block/legacy/BlockTransitionPlane.java | 59 ++ .../client/gui/widgets/GuiImgButton.java | 4 +- .../client/gui/widgets/GuiTabButton.java | 2 +- .../client/gui/widgets/GuiToggleButton.java | 2 +- .../client/texture/ExtraBlockTextures.java | 21 +- .../core/api/definitions/ApiBlocks.java | 4 + .../tile/legacy/TileTransitionPlane.java | 827 ++++++++++++++++++ .../textures/blocks/BlockTransitionPlane.png | Bin 0 -> 398 bytes .../blocks/BlockTransitionPlaneBottom.png | Bin 0 -> 398 bytes .../blocks/BlockTransitionPlaneNoPower.png | Bin 0 -> 410 bytes .../blocks/BlockTransitionPlaneNormal.png | Bin 0 -> 345 bytes .../BlockTransitionPlaneNormal.png.mcmeta | 23 + .../blocks/BlockTransitionPlaneOff.png | Bin 0 -> 296 bytes .../blocks/BlockTransitionPlaneSide.png | Bin 0 -> 438 bytes 16 files changed, 922 insertions(+), 25 deletions(-) create mode 100644 austri3Fix.md create mode 100644 src/main/java/appeng/block/legacy/BlockTransitionPlane.java create mode 100644 src/main/java/appeng/tile/legacy/TileTransitionPlane.java create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlane.png create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneBottom.png create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneNoPower.png create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneNormal.png create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneNormal.png.mcmeta create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneOff.png create mode 100644 src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneSide.png diff --git a/.gitignore b/.gitignore index a7f14823..2f7c082d 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ !LICENSE !CONTRIBUTING.md !CHANGELOG.md +!austri3Fix.md # include sourcecode !src/ @@ -30,4 +31,4 @@ !codeformat/ # exclude vim files -*.swp \ No newline at end of file +*.swp diff --git a/austri3Fix.md b/austri3Fix.md new file mode 100644 index 00000000..7c395d2b --- /dev/null +++ b/austri3Fix.md @@ -0,0 +1,2 @@ +- we demultiblocked the transition plane +- transition plane doesn't collect items diff --git a/src/main/java/appeng/block/legacy/BlockTransitionPlane.java b/src/main/java/appeng/block/legacy/BlockTransitionPlane.java new file mode 100644 index 00000000..bfac5ce8 --- /dev/null +++ b/src/main/java/appeng/block/legacy/BlockTransitionPlane.java @@ -0,0 +1,59 @@ +package appeng.block.legacy; + +import java.util.EnumSet; + +import appeng.block.AEBaseTileBlock; +import appeng.core.features.AEFeature; +import appeng.tile.legacy.TileTransitionPlane; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.entity.Entity; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +public class BlockTransitionPlane extends AEBaseTileBlock { + public BlockTransitionPlane() { + super(Material.iron); + this.isOpaque = true; + this.setTileEntity(TileTransitionPlane.class); + this.setFeature(EnumSet.of(AEFeature.Legacy)); + } + + @Override + public void onEntityCollidedWithBlock(World w, int x, int y, int z, Entity entitiy) { + if (entitiy instanceof EntityItem) { + TileEntity te = w.getTileEntity(x, y, z); + if (te instanceof TileTransitionPlane) { + // TODO: WTF + //((TileTransitionPlane) te).addItem((EntityItem) entitiy); + } + } + } + + @Override + public void onNeighborBlockChange( + World world, + int x, + int y, + int z, + Block neighbor + ) { + TileEntity te = world.getTileEntity(x, y, z); + if (te instanceof TileTransitionPlane) { + ((TileTransitionPlane)te).reqEat(); + } + } + + //@Override + //public IIcon getIcon(int side, int meta) { + // if (side == 0) { + // return AppEngTextureRegistry.Blocks.GenericBottom.get(); + // } else if (side == 1) { + // return AppEngTextureRegistry.Blocks.GenericTop.get(); + // } else { + // return side == 2 ? AppEngTextureRegistry.Blocks.BlockTransPlane.get() + // : AppEngTextureRegistry.Blocks.GenericSide.get(); + // } + //} +} diff --git a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java index 20409248..89073d81 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiImgButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiImgButton.java @@ -580,7 +580,7 @@ public class GuiImgButton extends GuiButton implements ITooltip { } par1Minecraft.renderEngine.bindTexture( - ExtraBlockTextures.GuiTexture("guis/states.png") + ExtraBlockTextures.guiTexture("guis/states.png") ); this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width @@ -602,7 +602,7 @@ public class GuiImgButton extends GuiButton implements ITooltip { } par1Minecraft.renderEngine.bindTexture( - ExtraBlockTextures.GuiTexture("guis/states.png") + ExtraBlockTextures.guiTexture("guis/states.png") ); this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width diff --git a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java index b2f7e2b5..4ae8cf72 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiTabButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiTabButton.java @@ -80,7 +80,7 @@ public class GuiTabButton extends GuiButton implements ITooltip { if (this.visible) { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); minecraft.renderEngine.bindTexture( - ExtraBlockTextures.GuiTexture("guis/states.png") + ExtraBlockTextures.guiTexture("guis/states.png") ); this.field_146123_n = x >= this.xPosition && y >= this.yPosition && x < this.xPosition + this.width && y < this.yPosition + this.height; diff --git a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java index d85a673e..ab58742a 100644 --- a/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java +++ b/src/main/java/appeng/client/gui/widgets/GuiToggleButton.java @@ -68,7 +68,7 @@ public class GuiToggleButton extends GuiButton implements ITooltip { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); par1Minecraft.renderEngine.bindTexture( - ExtraBlockTextures.GuiTexture("guis/states.png") + ExtraBlockTextures.guiTexture("guis/states.png") ); this.field_146123_n = par2 >= this.xPosition && par3 >= this.yPosition && par2 < this.xPosition + this.width diff --git a/src/main/java/appeng/client/texture/ExtraBlockTextures.java b/src/main/java/appeng/client/texture/ExtraBlockTextures.java index ef00a137..6c1811df 100644 --- a/src/main/java/appeng/client/texture/ExtraBlockTextures.java +++ b/src/main/java/appeng/client/texture/ExtraBlockTextures.java @@ -1,26 +1,7 @@ -/* - * This file is part of Applied Energistics 2. - * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. - * - * Applied Energistics 2 is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Applied Energistics 2 is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Applied Energistics 2. If not, see . - */ - package appeng.client.texture; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; -import jdk.nashorn.internal.ir.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.IIcon; @@ -153,7 +134,7 @@ public enum ExtraBlockTextures { this.name = name; } - public static ResourceLocation GuiTexture(final String string) { + public static ResourceLocation guiTexture(final String string) { return new ResourceLocation("appliedenergistics2", "textures/" + string); } diff --git a/src/main/java/appeng/core/api/definitions/ApiBlocks.java b/src/main/java/appeng/core/api/definitions/ApiBlocks.java index e8a3da5a..22d614f0 100644 --- a/src/main/java/appeng/core/api/definitions/ApiBlocks.java +++ b/src/main/java/appeng/core/api/definitions/ApiBlocks.java @@ -33,6 +33,7 @@ import appeng.block.legacy.BlockCraftMonitor; import appeng.block.legacy.BlockCraftTerminal; import appeng.block.legacy.BlockLegacyController; import appeng.block.legacy.BlockTerminal; +import appeng.block.legacy.BlockTransitionPlane; import appeng.block.legacy.BlockWirelessAccessPoint; import appeng.block.misc.*; import appeng.block.networking.*; @@ -137,6 +138,7 @@ public final class ApiBlocks implements IBlocks { private final ITileDefinition craftMonitor; private final ITileDefinition legacyController; private final ITileDefinition legacyWirelessAccessPoint; + private final ITileDefinition transitionPlane; public ApiBlocks(final DefinitionConstructor constructor) { final BlockLightDetector lightDetector = new BlockLightDetector(); @@ -312,6 +314,8 @@ public final class ApiBlocks implements IBlocks { = constructor.registerTileDefinition(new BlockLegacyController()); this.legacyWirelessAccessPoint = constructor.registerTileDefinition(new BlockWirelessAccessPoint()); + this.transitionPlane + = constructor.registerTileDefinition(new BlockTransitionPlane()); } @Override diff --git a/src/main/java/appeng/tile/legacy/TileTransitionPlane.java b/src/main/java/appeng/tile/legacy/TileTransitionPlane.java new file mode 100644 index 00000000..a2ef9179 --- /dev/null +++ b/src/main/java/appeng/tile/legacy/TileTransitionPlane.java @@ -0,0 +1,827 @@ +package appeng.tile.legacy; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import appeng.api.config.Actionable; +import appeng.api.config.PowerMultiplier; +import appeng.api.networking.GridFlags; +import appeng.api.networking.IGrid; +import appeng.api.networking.energy.IEnergyGrid; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.networking.security.MachineSource; +import appeng.api.networking.storage.IStorageGrid; +import appeng.api.storage.data.IAEItemStack; +import appeng.core.sync.packets.PacketTransitionEffect; +import appeng.me.GridAccessException; +import appeng.server.ServerHelper; +import appeng.tile.TileEvent; +import appeng.tile.events.TileEventType; +import appeng.tile.grid.AENetworkTile; +import appeng.util.Platform; +import appeng.util.item.AEItemStack; +import net.minecraft.block.Block; +import net.minecraft.block.material.Material; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.world.WorldServer; +import net.minecraftforge.common.util.FakePlayerFactory; +import net.minecraftforge.common.util.ForgeDirection; + +public class TileTransitionPlane extends AENetworkTile { + List buffer = new ArrayList<>(); + int delay = 0; + int trys = 0; + boolean wasPulse = false; + static Set unbreakables = new HashSet<>(); + private final BaseActionSource mySrc = new MachineSource(this); + + public TileTransitionPlane() { + // TODO: WTF + //super.hasPower = false; + this.getProxy().setValidSides(EnumSet.allOf(ForgeDirection.class)); + this.getProxy().setFlags(GridFlags.REQUIRE_CHANNEL); + this.getProxy().setIdlePowerUsage(1.0); + } + + // TODO: WTF + //public void setOrientationBySide( + // EntityPlayer player, int side, float hitX, float hitY, float hitZ + //) { + // super.setOrientationBySide(player, side, hitX, hitY, hitZ); + // ForgeDirection getForward() = ForgeDirection.getOrientation(side); + // WorldCoord pos + // = new WorldCoord(this.xCoord, this.yCoord, this.zCoord); + // pos.add(getForward(), -1); + // this.worldObj.getTileEntity(pos.x, pos.y, pos.z); + // MinecraftForge.EVENT_BUS.post( + // new GridTileConnectivityEvent(this, this.worldObj, this.getLocation()) + // ); + //} + + // TODO: WTF + //public boolean syncStyle(IAppEngNetworkTile.SyncTime st) { + // return true; + //} + + @TileEvent(TileEventType.TICK) + public void updateTileEntity() { + if (this.getProxy().isActive() && this.delay++ > 320) { + if (this.eatBlock()) { + this.delay = 0; + } + + try { + IGrid gi = this.getProxy().getGrid(); + + if (gi != null) { + while (!this.buffer.isEmpty()) { + IAEItemStack aeitem = this.buffer.get(0); + this.buffer.remove(0); + IStorageGrid storage = this.getProxy().getStorage(); + IEnergyGrid energy = this.getProxy().getEnergy(); + IAEItemStack overflow = Platform.poweredInsert( + energy, storage.getItemInventory(), aeitem, this.mySrc + ); + if (overflow != null) { + this.buffer.add(overflow); + break; + } + + if (this.buffer.isEmpty()) { + this.markForUpdate(); + } + } + if (this.buffer.isEmpty()) { + this.reqEat(); + } + } + } catch (GridAccessException e) { + // :P + } + } + } + + // TODO: WTF + //public void ddItem(EntityItem entitiy) { + // if (this.isAccepting()) { + // ItemStack is = entitiy.getEntityItem(); + // if (this.Buffer.isEmpty() && this.getProxy().isActive() && + // Platform.isServer() + // && is != null) { + // IGrid gi = this.getProxy().getGrid(); + // if (gi != null && !entitiy.isDead) { + // int howMany = gi.usePowerForAddition(is.stackSize, 1); + // if (howMany > 0) { + // IMEInventory ca = gi.getCellArray(); + // if (ca != null) { + // ItemStack toAdd = is.splitStack(howMany); + // toAdd = Platform.refundEnergy( + // gi, Platform.addItems(ca, toAdd), "Transiton Plane" + // ); + // if (toAdd != null) { + // is.stackSize += toAdd.stackSize; + // } + + // try { + // float var10009 = (float) entitiy.posX; + // AppEng.getInstance().SideProxy.sendToAllNearExcept( + // (EntityPlayer) null, + // entitiy.posX, + // entitiy.posY, + // entitiy.posZ, + // 64.0, + // this.field_70331_k, + // (new PacketTransitionPlane( + // var10009, + // (float) entitiy.posY, + // (float) entitiy.posZ, + // this.getForward(), + // false + // )) + // .getPacket() + // ); + // } catch (IOException var8) {} + + // if (is.stackSize > 0) { + // this.Buffer.add(is.copy()); + // this.markForUpdate(); + // } + + // entitiy.setDead(); + // } + // } + // } + // } + // } + //} + + public boolean isAccepting() { + this.wasPulse = false; + return true; + } + + // TODO: WTF + //public static void blacklist(int itemID, int damageValue) { + // unbreakables.add(damageValue << 16 | itemID); + //} + + public boolean notUnbreakable(Block block, int damageValue) { + if (block != Blocks.air && block.getMaterial() != Material.air + && block.getMaterial() != Material.lava + && block.getMaterial() != Material.water) { + return !unbreakables.contains(block); + } else { + return false; + } + } + + public boolean eatBlock() { + if (this.isAccepting() && this.getProxy().isActive() && Platform.isServer() + // TODO: WTF + /*&& this.isValid()*/) { + int x = this.xCoord + this.getForward().offsetX; + int y = this.yCoord + this.getForward().offsetY; + int z = this.zCoord + this.getForward().offsetZ; + Block bid = this.worldObj.getBlock(x, y, z); + int meta = this.worldObj.getBlockMetadata(x, y, z); + if (!this.worldObj.isAirBlock(x, y, z) && this.worldObj.blockExists(x, y, z) + && this.buffer.isEmpty() && bid != Blocks.air + && this.notUnbreakable(bid, meta) && bid != Blocks.bedrock + && this.worldObj.canMineBlock( + FakePlayerFactory.getMinecraft((WorldServer) this.worldObj), x, y, z + )) { + float hardness = bid.getBlockHardness(this.worldObj, x, y, z); + if ((double) hardness >= 0.0) { + ItemStack[] out = Platform.getBlockDrops(this.worldObj, x, y, z); + float total = 1.0F + hardness; + ItemStack[] arr$ = out; + int len$ = out.length; + for (len$ = 0; len$ < len$; ++len$) { + ItemStack is = arr$[len$]; + total += (float) is.stackSize; + } + + boolean hasPower = false; + try { + hasPower = this.getProxy().getEnergy().extractAEPower( + total, Actionable.MODULATE, PowerMultiplier.CONFIG + ) + > total - 0.1; + } catch (GridAccessException e1) { + // :P + } + if (hasPower) { + this.worldObj.setBlockToAir(x, y, z); + this.trys = 0; + + ServerHelper.proxy.sendToAllNearExcept( + null, + this.xCoord, + this.yCoord, + this.zCoord, + 64, + this.getTile().getWorldObj(), + new PacketTransitionEffect( + this.xCoord + this.getForward().offsetX + 0.5, + this.yCoord + this.getForward().offsetY + 0.5, + this.zCoord + this.getForward().offsetZ + 0.5, + this.getForward(), + false + ) + ); + + arr$ = out; + len$ = out.length; + + for (int i$ = 0; i$ < len$; ++i$) { + //ItemStack is = arr$[i$]; + //is = Platform.addItems(ca, is); + //if (is != null) { + // this.Buffer.add(is); + // this.markForUpdate(); + //} + if (arr$[i$] == null) + continue; + + this.buffer.add(AEItemStack.create(arr$[i$])); + } + + try { + IGrid gi = this.getProxy().getGrid(); + + if (gi != null) { + while (!this.buffer.isEmpty()) { + IAEItemStack aeitem = this.buffer.get(0); + this.buffer.remove(0); + IStorageGrid storage = this.getProxy().getStorage(); + IEnergyGrid energy = this.getProxy().getEnergy(); + IAEItemStack overflow = Platform.poweredInsert( + energy, + storage.getItemInventory(), + aeitem, + this.mySrc + ); + if (overflow != null) { + this.buffer.add(overflow); + break; + } + + if (this.buffer.isEmpty()) { + this.markForUpdate(); + } + } + if (this.buffer.isEmpty()) { + this.reqEat(); + } + } + } catch (GridAccessException e) { + // :P + } + } + } + } + } + + return true; + } + + public void reqEat() { + this.delay += 9999; + } + + // TODO: WTF + //public void onNeighborBlockChange() { + // this.reqEat(); + // this.trys = 0; + //} + + //public void setPowerStatus(boolean _hasPower) { + // super.setPowerStatus(_hasPower); + // this.reqEat(); + //} + + //public void onUpdateRedstone() { + // super.onUpdateRedstone(); + // this.reqEat(); + //} + + //public void pulseRedStone() { + // super.pulseRedStone(); + // this.wasPulse = true; + // this.reqEat(); + //} + + // TODO: multiblock + //boolean linesUp(int x, int y, int z) { + // TileEntity te = this.worldObj.getTileEntity(x, y, z); + // if (te instanceof TileTransitionPlane) { + // return ((TileTransitionPlane) te).getForward() == this.getForward(); + // } else { + // return false; + // } + //} + + // TODO: WTF + //public void placedBy(EntityLivingBase entityliving) { + // byte rotation = (byte + // ) (MathHelper.floor_double( + // (double) (entityliving.rotationYaw * 4.0F / 360.0F) + 2.5 + // ) + // & 3); + // if (entityliving.rotationPitch > 65.0F) { + // rotation = 4; + // } else if (entityliving.rotationPitch < -65.0F) { + // rotation = 5; + // } + + // //this.getForward() = this.getDirectionFromAERotation(rotation); + // this.getForward() = ForgeDirection.getOrientation(rotation); + //} + + // TODO: WTF + //private Icon defTextures(ForgeDirection side) { + // if (side == this.getForward().getOpposite()) { + // return AppEngTextureRegistry.Blocks.GenericBottom.get(); + // } else if (side == ForgeDirection.DOWN) { + // return AppEngTextureRegistry.Blocks.GenericTop.get(); + // } else { + // return side == ForgeDirection.UP + // ? AppEngTextureRegistry.Blocks.GenericTop.get() + // : AppEngTextureRegistry.Blocks.GenericSide.get(); + // } + //} + + //public Icon getBlockTextureFromSide(ForgeDirection side) { + // Icon frontFace = this.isMachineActive() + // ? AppEngTextureRegistry.Blocks.BlockTransPlane.get() + // : AppEngTextureRegistry.Blocks.BlockTransPlaneOff.get(); + // return this.getForward() == side ? frontFace : this.defTextures(side); + //} + + @Override + public void writeToNBT(NBTTagCompound par1nbtTagCompound) { + super.writeToNBT(par1nbtTagCompound); + NBTTagList items = new NBTTagList(); + + for (int x = 0; x < this.buffer.size(); ++x) { + NBTTagCompound item = new NBTTagCompound(); + this.buffer.get(x).writeToNBT(item); + items.appendTag(item); + } + + par1nbtTagCompound.setTag("items", items); + } + + @Override + public void readFromNBT(NBTTagCompound par1nbtTagCompound) { + super.readFromNBT(par1nbtTagCompound); + NBTTagList items = par1nbtTagCompound.getTagList("items", 10); + + for (int x = 0; x < items.tagCount(); ++x) { + this.buffer.add(AEItemStack.loadItemStackFromNBT(items.getCompoundTagAt(x))); + } + } + + // TODO: WTF + //@SideOnly(Side.CLIENT) + //public void renderTexturedPlate( + // float[] offset, + // float[] Left, + // float[] Up, + // float[] texOffset, + // float[] texDiff, + // Icon icon, + // int lightX, + // int lightY, + // int lightZ, + // boolean rev + //) { + // Tessellator tess = Tessellator.instance; + // float[] p1 = new float[5]; + // float[] p2 = new float[5]; + // float[] p3 = new float[5]; + // float[] p4 = new float[5]; + // p1[0] = offset[0]; + // p1[1] = offset[1]; + // p1[2] = offset[2]; + // p1[3] = icon.getInterpolatedU((double) texOffset[0]); + // p1[4] = icon.getInterpolatedV((double) texOffset[1]); + // p2[0] = offset[0] + Left[0]; + // p2[1] = offset[1] + Left[1]; + // p2[2] = offset[2] + Left[2]; + // p2[3] = icon.getInterpolatedU((double) (texOffset[0] + texDiff[0])); + // p2[4] = icon.getInterpolatedV((double) texOffset[1]); + // p3[0] = offset[0] + Left[0] + Up[0]; + // p3[1] = offset[1] + Left[1] + Up[1]; + // p3[2] = offset[2] + Left[2] + Up[2]; + // p3[3] = icon.getInterpolatedU((double) (texOffset[0] + texDiff[0])); + // p3[4] = icon.getInterpolatedV((double) (texOffset[1] + texDiff[1])); + // p4[0] = offset[0] + Up[0]; + // p4[1] = offset[1] + Up[1]; + // p4[2] = offset[2] + Up[2]; + // p4[3] = icon.getInterpolatedU((double) texOffset[0]); + // p4[4] = icon.getInterpolatedV((double) (texOffset[1] + texDiff[1])); + // tess.setBrightness( + // this.getBlockType().getMixedBrightnessForBlock(this.worldObj, lightX, + // lightY, lightZ) + // ); + // if (rev) { + // tess.addVertexWithUV( + // (double) p4[0], + // (double) p4[1], + // (double) p4[2], + // (double) p4[3], + // (double) p4[4] + // ); + // tess.addVertexWithUV( + // (double) p3[0], + // (double) p3[1], + // (double) p3[2], + // (double) p3[3], + // (double) p3[4] + // ); + // tess.addVertexWithUV( + // (double) p2[0], + // (double) p2[1], + // (double) p2[2], + // (double) p2[3], + // (double) p2[4] + // ); + // tess.addVertexWithUV( + // (double) p1[0], + // (double) p1[1], + // (double) p1[2], + // (double) p1[3], + // (double) p1[4] + // ); + // } else { + // tess.addVertexWithUV( + // (double) p1[0], + // (double) p1[1], + // (double) p1[2], + // (double) p1[3], + // (double) p1[4] + // ); + // tess.addVertexWithUV( + // (double) p2[0], + // (double) p2[1], + // (double) p2[2], + // (double) p2[3], + // (double) p2[4] + // ); + // tess.addVertexWithUV( + // (double) p3[0], + // (double) p3[1], + // (double) p3[2], + // (double) p3[3], + // (double) p3[4] + // ); + // tess.addVertexWithUV( + // (double) p4[0], + // (double) p4[1], + // (double) p4[2], + // (double) p4[3], + // (double) p4[4] + // ); + // } + //} + + // TODO: WTF + //public float[] p(float a, float b, float c) { + // float[] t = new float[] { a, b, c }; + // return t; + //} + + //public float[] t(float a, float b) { + // float[] t = new float[] { a, b }; + // return t; + //} + + // TODO: WTF + //@SideOnly(Side.CLIENT) + //public boolean renderWorldBlock( + // IBlockAccess world, + // int x, + // int y, + // int z, + // Block block, + // int modelId, + // RenderBlocks renderer + //) { + // renderer.setRenderBounds( + // this.getForward() == ForgeDirection.WEST ? 9.999999747378752E-5 : 0.0, + // this.getForward() == ForgeDirection.DOWN ? 9.999999747378752E-5 : 0.0, + // this.getForward() == ForgeDirection.NORTH ? 9.999999747378752E-5 : 0.0, + // this.getForward() == ForgeDirection.EAST ? 0.9998999834060669 : 1.0, + // this.getForward() == ForgeDirection.UP ? 0.9998999834060669 : 1.0, + // this.getForward() == ForgeDirection.SOUTH ? 0.9998999834060669 : 1.0 + // ); + // renderer.uvRotateTop = 0; + // renderer.uvRotateBottom = 3; + // renderer.uvRotateEast = 1; + // renderer.uvRotateNorth = 2; + // renderer.uvRotateSouth = 1; + // renderer.uvRotateWest = 2; + // renderer.renderStandardBlock(block, x, y, z); + // renderer.uvRotateBottom = renderer.uvRotateEast = renderer.uvRotateNorth + // = renderer.uvRotateSouth = renderer.uvRotateTop = renderer.uvRotateWest + // = 0; + // renderer.setRenderBounds(0.0, 0.0, 0.0, 1.0, 1.0, 1.0); + // IIcon icon = AppEngTextureRegistry.Blocks.BlockFrame.get(); + // float offsetPerPixel = 0.0625F; + // boolean rev; + // float zX; + // if (this.getForward() == ForgeDirection.NORTH + // || this.getForward() == ForgeDirection.SOUTH) { + // rev = this.getForward() == ForgeDirection.NORTH; + // zX = 1.0F; + // if (rev) { + // zX = 0.0F; + // } + + // if (!this.linesUp(x - 1, y, z)) { + // this.renderTexturedPlate( + // this.p((float) x, (float) y, (float) z + zX), + // this.p(offsetPerPixel, 0.0F, 0.0F), + // this.p(0.0F, 1.0F, 0.0F), + // this.t(0.0F, 0.0F), + // this.t(1.0F, 16.0F), + // icon, + // x, + // y, + // z + (rev ? -1 : 1), + // rev + // ); + // } + + // if (!this.linesUp(x + 1, y, z)) { + // this.renderTexturedPlate( + // this.p((float) x + 15.0F * offsetPerPixel, (float) y, (float) z + + // zX), this.p(offsetPerPixel, 0.0F, 0.0F), this.p(0.0F, 1.0F, 0.0F), + // this.t(15.0F, 0.0F), + // this.t(1.0F, 16.0F), + // icon, + // x, + // y, + // z + (rev ? -1 : 1), + // rev + // ); + // } + + // if (!this.linesUp(x, y - 1, z)) { + // this.renderTexturedPlate( + // this.p((float) x, (float) y, (float) z + zX), + // this.p(1.0F, 0.0F, 0.0F), + // this.p(0.0F, offsetPerPixel, 0.0F), + // this.t(0.0F, 0.0F), + // this.t(16.0F, 1.0F), + // icon, + // x, + // y, + // z + (rev ? -1 : 1), + // rev + // ); + // } + + // if (!this.linesUp(x, y + 1, z)) { + // this.renderTexturedPlate( + // this.p((float) x, (float) y + 15.0F * offsetPerPixel, (float) z + + // zX), this.p(1.0F, 0.0F, 0.0F), this.p(0.0F, offsetPerPixel, 0.0F), + // this.t(0.0F, 15.0F), + // this.t(16.0F, 1.0F), + // icon, + // x, + // y, + // z + (rev ? -1 : 1), + // rev + // ); + // } + // } + + // if (this.getForward() == ForgeDirection.EAST + // || this.getForward() == ForgeDirection.WEST) { + // rev = this.getForward() == ForgeDirection.EAST; + // zX = 0.0F; + // if (rev) { + // zX = 1.0F; + // } + + // if (!this.linesUp(x, y, z - 1)) { + // this.renderTexturedPlate( + // this.p((float) x + zX, (float) y, (float) z), + // this.p(0.0F, 0.0F, offsetPerPixel), + // this.p(0.0F, 1.0F, 0.0F), + // this.t(0.0F, 0.0F), + // this.t(1.0F, 16.0F), + // icon, + // x + (rev ? 1 : -1), + // y, + // z, + // rev + // ); + // } + + // if (!this.linesUp(x, y, z + 1)) { + // this.renderTexturedPlate( + // this.p((float) x + zX, (float) y, (float) z + 15.0F * + // offsetPerPixel), this.p(0.0F, 0.0F, offsetPerPixel), + // this.p(0.0F, 1.0F, 0.0F), + // this.t(15.0F, 0.0F), + // this.t(1.0F, 16.0F), + // icon, + // x + (rev ? 1 : -1), + // y, + // z, + // rev + // ); + // } + + // if (!this.linesUp(x, y - 1, z)) { + // this.renderTexturedPlate( + // this.p((float) x + zX, (float) y, (float) z), + // this.p(0.0F, 0.0F, 1.0F), + // this.p(0.0F, offsetPerPixel, 0.0F), + // this.t(0.0F, 0.0F), + // this.t(16.0F, 1.0F), + // icon, + // x + (rev ? 1 : -1), + // y, + // z, + // rev + // ); + // } + + // if (!this.linesUp(x, y + 1, z)) { + // this.renderTexturedPlate( + // this.p((float) x + zX, (float) y + 15.0F * offsetPerPixel, (float) + // z), this.p(0.0F, 0.0F, 1.0F), this.p(0.0F, offsetPerPixel, 0.0F), + // this.t(0.0F, 15.0F), + // this.t(16.0F, 1.0F), + // icon, + // x + (rev ? 1 : -1), + // y, + // z, + // rev + // ); + // } + // } + + // if (this.getForward() == ForgeDirection.UP + // || this.getForward() == ForgeDirection.DOWN) { + // rev = this.getForward() == ForgeDirection.UP; + // zX = 1.0F; + // if (!rev) { + // zX = 0.0F; + // } + + // if (!this.linesUp(x - 1, y, z)) { + // this.renderTexturedPlate( + // this.p((float) x, (float) y + zX, (float) z), + // this.p(offsetPerPixel, 0.0F, 0.0F), + // this.p(0.0F, 0.0F, 1.0F), + // this.t(0.0F, 0.0F), + // this.t(1.0F, 16.0F), + // icon, + // x, + // y + (rev ? 1 : -1), + // z, + // rev + // ); + // } + + // if (!this.linesUp(x + 1, y, z)) { + // this.renderTexturedPlate( + // this.p((float) x + 15.0F * offsetPerPixel, (float) y + zX, (float) + // z), this.p(offsetPerPixel, 0.0F, 0.0F), this.p(0.0F, 0.0F, 1.0F), + // this.t(15.0F, 0.0F), + // this.t(1.0F, 16.0F), + // icon, + // x, + // y + (rev ? 1 : -1), + // z, + // rev + // ); + // } + + // if (!this.linesUp(x, y, z - 1)) { + // this.renderTexturedPlate( + // this.p((float) x, (float) y + zX, (float) z), + // this.p(1.0F, 0.0F, 0.0F), + // this.p(0.0F, 0.0F, offsetPerPixel), + // this.t(0.0F, 0.0F), + // this.t(16.0F, 1.0F), + // icon, + // x, + // y + (rev ? 1 : -1), + // z, + // rev + // ); + // } + + // if (!this.linesUp(x, y, z + 1)) { + // this.renderTexturedPlate( + // this.p((float) x, (float) y + zX, (float) z + 15.0F * + // offsetPerPixel), this.p(1.0F, 0.0F, 0.0F), this.p(0.0F, 0.0F, + // offsetPerPixel), this.t(0.0F, 15.0F), this.t(16.0F, 1.0F), icon, x, + // y + (rev ? 1 : -1), + // z, + // rev + // ); + // } + // } + + // return true; + //} + + // TODO: WTF + //public boolean isBlockNormalCube() { + // return true; + //} + + //public boolean handleTilePacket(DataInputStream stream) throws IOException { + // ForgeDirection oldOrientation = this.getForward(); + // boolean oldHasPower = super.hasPower; + // byte rotation = stream.readByte(); + // this.getForward() = this.getDirectionFromAERotation(rotation); + // byte flags = stream.readByte(); + // super.hasPower = (flags & 1) == 1; + // if ((flags & 2) == 2) { + // if (this.Buffer.isEmpty()) { + // this.Buffer.add(new ItemStack(Item.field_77669_D)); + // } + // } else { + // this.Buffer.clear(); + // } + + // return oldHasPower != super.hasPower || oldOrientation != this.getForward(); + //} + + //public void configureTilePacket(DataOutputStream data) throws IOException { + // data.writeByte(this.getAERotationFromDirection(this.getForward())); + // byte flags = 0; + // byte flags = (byte) (flags | (super.hasPower ? 1 : 0)); + // flags = (byte) (flags | (this.Buffer.isEmpty() ? 0 : 2)); + // data.writeByte(flags); + //} + + // TODO: WTF + //public void addCollidingBlockToList( + // World world, + // int x, + // int y, + // int z, + // AxisAlignedBB axisalignedbb, + // List arraylist, + // Entity par7Entity + //) { + // AppEngMultiBlock blk = (AppEngMultiBlock) this.getBlockType(); + // if (par7Entity instanceof EntityItem && this.isMachineActive() + // && this.Buffer.isEmpty()) { + // blk.func_71905_a( + // this.getForward() == ForgeDirection.WEST ? 0.005F : 0.0F, + // this.getForward() == ForgeDirection.DOWN ? 0.005F : 0.0F, + // this.getForward() == ForgeDirection.NORTH ? 0.005F : 0.0F, + // this.getForward() == ForgeDirection.EAST ? 0.995F : 1.0F, + // this.getForward() == ForgeDirection.UP ? 0.995F : 1.0F, + // this.getForward() == ForgeDirection.SOUTH ? 0.995F : 1.0F + // ); + // blk.configureCollidingBlockToList( + // world, x, y, z, axisalignedbb, arraylist, par7Entity + // ); + // blk.func_71905_a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + // } else { + // blk.func_71905_a(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + // blk.configureCollidingBlockToList( + // world, x, y, z, axisalignedbb, arraylist, par7Entity + // ); + // } + //} + + // TODO: this is to avoid Z-fighting. Put into renderer? + //@Override + //public AxisAlignedBB[] getSelectedBoundingBoxsFromPool( + // World world, int x, int y, int z + //) { + // return new AxisAlignedBB[] { AxisAlignedBB.getBoundingBox( + // this.getForward() == ForgeDirection.WEST ? 0.004999999888241291 : 0.0, + // this.getForward() == ForgeDirection.DOWN ? 0.004999999888241291 : 0.0, + // this.getForward() == ForgeDirection.NORTH ? 0.004999999888241291 : 0.0, + // this.getForward() == ForgeDirection.EAST ? 0.9950000047683716 : 1.0, + // this.getForward() == ForgeDirection.UP ? 0.9950000047683716 : 1.0, + // this.getForward() == ForgeDirection.SOUTH ? 0.9950000047683716 : 1.0 + // ) }; + //} + + //public void setPrimaryOrientation(ForgeDirection s) { + // this.orientation = s; + // MinecraftForge.EVENT_BUS.post( + // new GridTileConnectivityEvent(this, this.getWorld(), this.getLocation()) + // ); + //} +} diff --git a/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlane.png b/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlane.png new file mode 100644 index 0000000000000000000000000000000000000000..7ec66578158e7a321dc0d6e99aeaeb072c4130f4 GIT binary patch literal 398 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!73?$#)eFPF8om~%3A2F8tJP2|NnnClN={dJ!6u$y9>Ac^&9L@rd$YKTt zzGWcH*nVeaK2Xr!)5S4_<9c#}NJvl+5TykaGBUfjO)xPiNDpW2OC7#SEE z>lzsA8XAQdSXdbwTNzsD8kkxc7+iBbxgSMCZhlH;S|wbAfk}vwv6TT3ndlmr0X2NR z%Do<_K?-C;aDG}zd16s2LqK9?UWuNcYluRbv7V`(p@G4dqJ=eN`=0SqpttBVD!s|NqYv?RyDS&zR)x?!qm9{m20zhqJ&VvY3H^ zZy5+Pw%=Kq4-~Zbba4#fxSpIK5)u>yL}>wqjLhzB6HE*W(gPX|=190G@VK{laL$ra z(VVkO#<0ZlpiXI0#(XKsC2?}191KoVwPdSO8NLFIQY~?fC`m~yNwrEYN(E93Mh1q) zx(3F&hDIR<7FNc_R)!Y32Bua92G?9q?nlv(o1c=IRteW&U=m_vY-IpMCb|Y@Kn-87 za<2z!kOJ8doS#-wo>-L15RjOeSEA?V8lq5UtY@lcXkhTAXdzG)gQu&X%Q~loCIDqY BYh3^U literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneNoPower.png b/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneNoPower.png new file mode 100644 index 0000000000000000000000000000000000000000..95799d238e210fa735ef6f1de3c848b6dc3b4da1 GIT binary patch literal 410 zcmV;L0cHM)P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D02*{fSaefwW^{L9 za%BKeVQFr3E>1;MAa*k@H7+qQF!XYv0003ANkl)+2hV9+y8sK>w+N`B zM?bGx6uiizjzIEXh>z(7ilIHaEx1m=d!ZKzh;2qdfVT~;$j6j>;lTiKVpXv1dk|Q2 z{|;UgXl^Ews2|IcnXhz!jMl|?&B`EDrN}yzP`I|h%+HEXA@0D(l`XVw;goeOfZvAB z9FVVeAfcS#`ZLjIMZk6T=;Z3a+U)laU;CG~(PB*b2XYe*N-W2vIRF3v07*qoM6N<$ Ef(b0BNdN!< literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneNormal.png b/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneNormal.png new file mode 100644 index 0000000000000000000000000000000000000000..f3ea5ceeb6034bb886d73c9b46f228a3a10b6b2f GIT binary patch literal 345 zcmeAS@N?(olHy`uVBq!ia0vp^0t^g{3><7g)~=v$en5&P-O<;Pfnj4m_n$;oAfL0q zBeIx*f$tCqGm2_>H2?*rN?apKg7ec#$`gxH83GbB^GfvmTtgJfjP*?Q3=Isv6fFd* zy6WlT7*Y}U_Uu8fLk1$O7XvgJ|NZ~(=FZydo0A=;e%>{|e{|?77F{ud1z35r_Z^QHk z2F@1tx}KF)nQ96SOb;8I4d3#u0xK;@@;Q6h9jw&Ca@n(m2W%M`x%gs$1_U@XupD9* zKOQ2_!7;(1;z7UR-gvN<56@@Jvj?*b4AdCqn3!yun47nAPiSE9W$5YI8ROuPAfzx| ZI)T^XPiEn9PQRm%JP-b4f4$e=nA;(H z?ODTP=gTbWZl??Fw_NyOc8fzv$On^)^pUXO@geCw{EN}Aw literal 0 HcmV?d00001 diff --git a/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneSide.png b/src/main/resources/assets/appliedenergistics2/textures/blocks/BlockTransitionPlaneSide.png new file mode 100644 index 0000000000000000000000000000000000000000..6c7e4831f00092a2dd623bf67ad9459ea03435c6 GIT binary patch literal 438 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJOS+@4BLl<6e(pbstU$g(vPY0F z14ES>14Ba#1H&(%P{RubhEf9thF1v;3|2E37{m+a>!~(0G-#;Ey4VVSyJMySIh+L^k;M!Qe9J(XvHi}XUXZc~`OR4l}sqx!r49 z{saW3Id1C^Qz^E+$In#AS<3zX@l2r6swJ)wB`Jv|saDBFsX&Us$iUE8*T7iU&?v;f z!phj#%FsgBz|_jX;F{~n{U{o8^HVa@D&ZOoOhSx|tqg$3MAyI!sNw5X?)5+oQXm_G t^V3So6N^$A0unRxO7#3(Llnx4^-T2)4Gg{%Ed;7!@O1TaS?83{1OV!5doch2 literal 0 HcmV?d00001