diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..e62822fbb --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# This is the universal Text Editor Configuration +# for all GTNewHorizons projects +# See: https://editorconfig.org/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{bat,ini}] +end_of_line = crlf + +[*.{dtd,json,mcmeta,md,sh,svg,xml,xsd,xsl,yaml,yml}] +indent_size = 2 + +[*.lang] +trim_trailing_whitespace = false diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..2efee981c --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,2 @@ +# Ignore spotlessApply reformat +df4ad8e370d65b575411a271c7e827e72db09fe8 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..fd2792b6c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,44 @@ +* text eol=lf + +*.[jJ][aA][rR] binary + +*.[pP][nN][gG] binary +*.[jJ][pP][gG] binary +*.[jJ][pP][eE][gG] binary +*.[gG][iI][fF] binary +*.[tT][iI][fF] binary +*.[tT][iI][fF][fF] binary +*.[iI][cC][oO] binary +*.[sS][vV][gG] text +*.[eE][pP][sS] binary +*.[xX][cC][fF] binary + +*.[kK][aA][rR] binary +*.[mM]4[aA] binary +*.[mM][iI][dD] binary +*.[mM][iI][dD][iI] binary +*.[mM][pP]3 binary +*.[oO][gG][gG] binary +*.[rR][aA] binary + +*.7[zZ] binary +*.[gG][zZ] binary +*.[tT][aA][rR] binary +*.[tT][gG][zZ] binary +*.[zZ][iI][pP] binary + +*.[tT][cC][nN] binary +*.[sS][oO] binary +*.[dD][lL][lL] binary +*.[dD][yY][lL][iI][bB] binary +*.[pP][sS][dD] binary +*.[tT][tT][fF] binary +*.[oO][tT][fF] binary + +*.[pP][aA][tT][cC][hH] -text + +*.[bB][aA][tT] text eol=crlf +*.[cC][mM][dD] text eol=crlf +*.[pP][sS]1 text eol=crlf + +*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary diff --git a/.github/scripts/test-no-error-reports.sh b/.github/scripts/test-no-error-reports.sh new file mode 100755 index 000000000..84c1e5d65 --- /dev/null +++ b/.github/scripts/test-no-error-reports.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +RUNDIR="run" +CRASH="crash-reports" +SERVERLOG="server.log" + +if [[ -d $RUNDIR/$CRASH ]]; then + echo "Crash reports detected:" + cat $RUNDIR/$CRASH/crash*.txt + exit 1 +fi + +if grep --quiet "Fatal errors were detected" $SERVERLOG; then + echo "Fatal errors detected:" + cat server.log + exit 1 +fi + +if grep --quiet "The state engine was in incorrect state ERRORED and forced into state SERVER_STOPPED" $SERVERLOG; then + echo "Server force stopped:" + cat server.log + exit 1 +fi + +if ! grep --quiet -Po '.+Done \(.+\)\! For help, type "help" or "\?"' $SERVERLOG; then + echo "Server didn't finish startup:" + cat server.log + exit 1 +fi + +echo "No crash reports detected" +exit 0 + diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml new file mode 100644 index 000000000..3ee2f686f --- /dev/null +++ b/.github/workflows/build-and-test.yml @@ -0,0 +1,13 @@ + +name: Build and test + +on: + pull_request: + branches: [ master, main ] + push: + branches: [ master, main ] + +jobs: + build-and-test: + uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/build-and-test.yml@master + secrets: inherit diff --git a/.github/workflows/release-tags.yml b/.github/workflows/release-tags.yml new file mode 100644 index 000000000..e4c0be6b0 --- /dev/null +++ b/.github/workflows/release-tags.yml @@ -0,0 +1,14 @@ + +name: Release tagged build + +on: + push: + tags: [ '*' ] + +permissions: + contents: write + +jobs: + release-tags: + uses: GTNewHorizons/GTNH-Actions-Workflows/.github/workflows/release-tags.yml@master + secrets: inherit diff --git a/.gitignore b/.gitignore index b3a32312f..48c525b13 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,32 @@ -/* -!/.gitignore -!/src -!/gradle -!/gradlew -!/gradlew.bat -!/README.md -!/License.txt -!/build.gradle -!/build.bat -!/build.sh -!/build.properties \ No newline at end of file +.gradle +.settings +/.idea/ +/.vscode/ +/run/ +/build/ +/eclipse/ +.classpath +.project +/bin/ +/config/ +/crash-reports/ +/logs/ +options.txt +/saves/ +usernamecache.json +banned-ips.json +banned-players.json +eula.txt +ops.json +server.properties +servers.dat +usercache.json +whitelist.json +/out/ +*.iml +*.ipr +*.iws +src/main/resources/mixins.*.json +*.bat +*.DS_Store +!gradlew.bat diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index e69de29bb..000000000 diff --git a/CHANGELOG-2.1.1.0.md b/CHANGELOG-2.1.1.0.md new file mode 100644 index 000000000..0c7336ab5 --- /dev/null +++ b/CHANGELOG-2.1.1.0.md @@ -0,0 +1,45 @@ + +# ExtraCells2 + +Changelog of ExtraCells2. + + +### [#23 Refactored Oredictionary export bus to use internal AE item stack hash](https://github.com/GTNewHorizons/ExtraCells2/pull/23) +**Merge pull request #23 from repo-alt/rv2** +* Refactored Oredictionary export bus to use internal AE item stack hash + +[d0027489e7c8bda](https://github.com/GTNewHorizons/ExtraCells2/commit/d0027489e7c8bda) +by Martin Robertz *2020-12-26 17:28:02* +### [#24 Drastically improve Fluid Storage Bus performance](https://github.com/GTNewHorizons/ExtraCells2/pull/24) +**Merge pull request #24 from PanSzelescik/rv2** +* Drastically improve Fluid Storage Bus performance + +[b5382340b4c23d2](https://github.com/GTNewHorizons/ExtraCells2/commit/b5382340b4c23d2) +by Martin Robertz *2020-12-30 16:40:31* +### [#26 remove the registration of the fluid pattern for every fluid](https://github.com/GTNewHorizons/ExtraCells2/pull/26) +**Merge pull request #26 from boubou19/rv2** +* remove the registration of the fluid pattern for every fluid + +[c9194185a749887](https://github.com/GTNewHorizons/ExtraCells2/commit/c9194185a749887) +by Martin Robertz *2021-01-08 21:58:28* +### No issue +**remove the registration of the fluid pattern for every fluid** + +[e8cc89baca7d2db](https://github.com/GTNewHorizons/ExtraCells2/commit/e8cc89baca7d2db) +by boubou19 *2021-01-08 16:27:32* + +**obsolete API removed (ThE jar is in the libs anyway)** + +[de78dd1b8ac1e51](https://github.com/GTNewHorizons/ExtraCells2/commit/de78dd1b8ac1e51) +by repo_alt *2021-01-08 15:30:19* + +**Drastically improve Fluid Storage Bus performance** + +[08783250828df18](https://github.com/GTNewHorizons/ExtraCells2/commit/08783250828df18) +by PanSzelescik *2020-12-29 17:19:33* + +**Refactored Oredictionary export bus to use internal AE item stack hash** + +[aca86edcb261ca9](https://github.com/GTNewHorizons/ExtraCells2/commit/aca86edcb261ca9) +by repo_alt *2020-12-26 14:40:59* + diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 000000000..a6b5f68cd --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,3 @@ +# Any Github changes require admin approval +/.github/** @GTNewHorizons/admin + diff --git a/License.txt b/LICENSE.txt similarity index 100% rename from License.txt rename to LICENSE.txt diff --git a/README.md b/README.md index 62759280a..a4f87726f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,10 @@ ExtraCells 2 ========== -A mighty Add-On for Applied Energistics 2 +A mighty Add-On for Applied Energistics 2. To build this, download the project (ZIP or fork or whatever) and execute the build.bat/build.sh. The build files will be in /build/lib/ Thanks to arbrarsyed for ForgeGradle, to AlgorithmX2 for his massive support and his *amazing* API, cyntain and tgame14 for some very cool textures and Vexatos, crafteverywhere, SSCXM and VeryBigBro for the cool localizations! -Dmod: [![Build Status](http://shadowcity.net:8080/job/ecrv2/badge/icon)](http://shadowcity.net:8080/job/ecrv2/) - -ExtraCells 2 is licensed under the MIT license. +ExtraCells 2 is licensed under the MIT license. This is the GTNH fork. diff --git a/build.bat b/build.bat deleted file mode 100644 index cd611c6f9..000000000 --- a/build.bat +++ /dev/null @@ -1 +0,0 @@ -gradlew clean setupCIWorkSpace build \ No newline at end of file diff --git a/build.gradle b/build.gradle index 059ee0af8..e57a16f9f 100644 --- a/build.gradle +++ b/build.gradle @@ -1,151 +1,5 @@ -buildscript { - repositories { - mavenCentral() - maven { - name = "forge" - url = "http://files.minecraftforge.net/maven" - } - maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" - } - } - dependencies { - classpath 'net.minecraftforge.gradle:ForgeGradle:1.2-SNAPSHOT' - } -} - - -apply plugin: 'scala' -apply plugin: 'forge' -apply plugin: 'idea' - -sourceCompatibility = JavaVersion.VERSION_1_6 -targetCompatibility = JavaVersion.VERSION_1_6 - -ext.buildProps = file "build.properties" - -version = "NIGHTLY" -if (System.getenv("BUILD_NUMBER") != null) { - version = "${System.getenv("BUILD_NUMBER")}" -} -if (System.getenv("DRONE_BUILD_NUMBER") != null) { - version = "${System.getenv("DRONE_BUILD_NUMBER")}" -} - -buildProps.withReader { - def prop = new Properties() - prop.load(it) - ext.config = new ConfigSlurper().parse prop -} - -version = "${config.version.minecraft}-${config.version.mod.major}.${config.version.mod.minor}.${config.version.mod.revis}b" + getBuildNumber() -group = "extracells" -archivesBaseName = "ExtraCells" -def actualVersion = version - -logger.lifecycle "$archivesBaseName-$version" -logger.lifecycle "" + version - -minecraft { - version = "${config.version.minecraft}-${config.version.forge}-${config.version.minecraft}" - runDir = "../../MinecraftDebug/run_client" -} - -repositories { - maven { - name 'Mobius Repo' - url "http://mobiusstrip.eu/maven" - } - maven { - name 'CB Repo' - url "http://chickenbones.net/maven/" - } - - maven { - name 'Open Computers' - url "http://maven.cil.li/" - } - - maven { - name = 'IGW' - url = "http://maven.k-4u.nl/" - } - - ivy { - name "BuildCraft" - artifactPattern "http://www.mod-buildcraft.com/releases/BuildCraft/[revision]/[module]-[revision]-[classifier].[ext]" - } - - ivy { - name 'WirelessCraftingTerminal' - artifactPattern "http://addons-origin.cursecdn.com/files/${config.cf.wc}/[module]-[revision].[ext]" - } - -} - -dependencies { - compile ("appeng:appliedenergistics2:${config.version.ae}:api"){ - transitive = false - } - compile ("appeng:appliedenergistics2:${config.version.ae}:dev"){ - transitive = false - } - compile ("mcp.mobius.waila:Waila:${config.version.waila}"){ - transitive = false - } - compile "li.cil.oc:OpenComputers:${config.version.oc}:dev" - compile "codechicken:CodeChickenLib:${config.version.minecraft}-${config.version.ccl}:dev" - compile "codechicken:CodeChickenCore:${config.version.minecraft}-${config.version.ccc}:dev" - compile "codechicken:NotEnoughItems:${config.version.minecraft}-${config.version.nei}:dev" - compile "igwmod:IGW-Mod-${config.version.minecraft}:${config.version.igw}:userdev" - - compile name: "buildcraft", version: "${config.version.bc}", classifier: "dev", ext: 'jar' - - compile name: 'WirelessCraftingTerminal', version: config.version.wc, ext: 'jar' -} - -processResources { - from(sourceSets.main.resources.srcDirs) { - include '**/*.lang' - include '**/*.info' - include '**/*.properties' - - expand 'version': project.version, 'mcversion': project.minecraft.version - } - - from(sourceSets.main.resources.srcDirs) { - include '**/*.lang' - include '**/*.info' - include '**/*.properties' - - expand 'version': "${config.version.mod.major}.${config.version.mod.minor}.${config.version.mod.revis}", 'mcversion': project.minecraft.version - } -} - -task deobfJar(type: Jar) { - from sourceSets.main.output - from sourceSets.main.scala - from sourceSets.main.java - appendix = 'deobf' -} - -artifacts { - archives deobfJar -} - -def getBuildNumber() { - if (System.getenv("BUILD_NUMBER") != null) { - return "${System.getenv("BUILD_NUMBER")}" - } - else if (System.getenv("DRONE_BUILD_NUMBER") != null) { - return "${System.getenv("DRONE_BUILD_NUMBER")}" - } - return "NIGHTLY" -} +//version: 1707058017 -idea { - module { - outputDir = file('build/classes/main') - } +plugins { + id 'com.gtnewhorizons.gtnhconvention' } diff --git a/build.properties b/build.properties deleted file mode 100644 index 03e6fbc82..000000000 --- a/build.properties +++ /dev/null @@ -1,17 +0,0 @@ -dir.development=./ -dir.mcp=${dir.development}forge/mcp -version.minecraft=1.7.10 -version.forge=10.13.4.1614 -version.mod.major=2 -version.mod.minor=3 -version.mod.revis=14 -version.ae=rv3-beta-6 -version.oc=MC1.7.10-1.5.22.46 -version.bc=7.1.14 -version.waila=1.5.10_1.7.10 -version.ccl=1.1.3.140 -version.ccc=1.0.7.+ -version.nei=1.0.5.+ -version.igw=1.1.3-18 -version.wc=1.7.10-rv3-1.8.7.1b-deobf -cf.wc=2307/524 diff --git a/build.sh b/build.sh deleted file mode 100644 index cd611c6f9..000000000 --- a/build.sh +++ /dev/null @@ -1 +0,0 @@ -gradlew clean setupCIWorkSpace build \ No newline at end of file diff --git a/dependencies.gradle b/dependencies.gradle new file mode 100644 index 000000000..6c6313b4d --- /dev/null +++ b/dependencies.gradle @@ -0,0 +1,17 @@ +// Add your dependencies here + +dependencies { + api('com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-423-GTNH:dev') + api('com.github.GTNewHorizons:AE2FluidCraft-Rework:1.3.21-gtnh:dev') + compileOnly('com.github.GTNewHorizons:NotEnoughItems:2.6.19-GTNH:dev') {transitive=false} + compileOnly('com.github.GTNewHorizons:ThaumicEnergistics:1.6.22-GTNH:dev') {transitive=false} + compileOnly('com.github.GTNewHorizons:CodeChickenLib:1.3.0:dev') {transitive=false} + compileOnly('com.github.GTNewHorizons:waila:1.8.1:dev') {transitive=false} + compileOnly('com.github.GTNewHorizons:WirelessCraftingTerminal:1.11.6:dev') {transitive=false} + compileOnly('com.github.GTNewHorizons:OpenComputers:1.10.18-GTNH:dev') {transitive=false} + compileOnly('com.github.GTNewHorizons:BuildCraft:7.1.39:dev') {transitive=false} + + compileOnly('thaumcraft:Thaumcraft:1.7.10-4.2.3.5:dev') {transitive=false} + compileOnly('curse.maven:mekanism-268560:2475797') + compileOnly('igwmod:IGW-Mod-1.7.10:1.1.3-18:userdev') {transitive=false} +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 000000000..95a1fd243 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,203 @@ +# ExampleMod tag to use as Blowdryer (Spotless, etc.) settings version, leave empty to disable. +# LOCAL to test local config updates. +gtnh.settings.blowdryerTag = 0.2.0 + +# Human-readable mod name, available for mcmod.info population. +modName = Extra Cells + +# Case-sensitive identifier string, available for mcmod.info population and used for automatic mixin JSON generation. +# Conventionally lowercase. +modId = extracells + +# Root package of the mod, used to find various classes in other properties, +# mcmod.info substitution, enabling assertions in run tasks, etc. +modGroup = extracells + +# Whether to use modGroup as the maven publishing group. +# Due to a history of using JitPack, the default is com.github.GTNewHorizons for all mods. +useModGroupForPublishing = false + +# Updates your build.gradle and settings.gradle automatically whenever an update is available. +autoUpdateBuildScript = false + +# Version of Minecraft to target +minecraftVersion = 1.7.10 + +# Version of Minecraft Forge to target +forgeVersion = 10.13.4.1614 + +# Specify an MCP channel for dependency deobfuscation and the deobfParams task. +channel = stable + +# Specify an MCP mappings version for dependency deobfuscation and the deobfParams task. +mappingsVersion = 12 + +# Defines other MCP mappings for dependency deobfuscation. +remoteMappings = https\://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/ + +# Select a default username for testing your mod. You can always override this per-run by running +# `./gradlew runClient --username=AnotherPlayer`, or configuring this command in your IDE. +developmentEnvironmentUserName = Developer + +# Enables using modern Java syntax (up to version 17) via Jabel, while still targeting JVM 8. +# See https://github.com/bsideup/jabel for details on how this works. +enableModernJavaSyntax = false + +# Enables injecting missing generics into the decompiled source code for a better coding experience. +# Turns most publicly visible List, Map, etc. into proper List, Map types. +enableGenericInjection = false + +# Generate a class with a String field for the mod version named as defined below. +# If generateGradleTokenClass is empty or not missing, no such class will be generated. +# If gradleTokenVersion is empty or missing, the field will not be present in the class. +generateGradleTokenClass = + +# Name of the token containing the project's current version to generate/replace. +gradleTokenVersion = GRADLETOKEN_VERSION + +# [DEPRECATED] Mod ID replacement token. +gradleTokenModId = + +# [DEPRECATED] Mod name replacement token. +gradleTokenModName = + +# [DEPRECATED] Mod Group replacement token. +gradleTokenGroupName = + +# [DEPRECATED] +# Multiple source files can be defined here by providing a comma-separated list: Class1.java,Class2.java,Class3.java +# public static final String VERSION = "GRADLETOKEN_VERSION"; +# The string's content will be replaced with your mod's version when compiled. You should use this to specify your mod's +# version in @Mod([...], version = VERSION, [...]). +# Leave these properties empty to skip individual token replacements. +replaceGradleTokenInFile = Extracells.scala + +# In case your mod provides an API for other mods to implement you may declare its package here. Otherwise, you can +# leave this property empty. +# Example value: (apiPackage = api) + (modGroup = com.myname.mymodid) -> com.myname.mymodid.api +apiPackage = api + +# Specify the configuration file for Forge's access transformers here. It must be placed into /src/main/resources/META-INF/ +# There can be multiple files in a space-separated list. +# Example value: mymodid_at.cfg nei_at.cfg +accessTransformersFile = + +# Provides setup for Mixins if enabled. If you don't know what mixins are: Keep it disabled! +usesMixins = false + +# Set to a non-empty string to configure mixins in a separate source set under src/VALUE, instead of src/main. +# This can speed up compile times thanks to not running the mixin annotation processor on all input sources. +# Mixin classes will have access to "main" classes, but not the other way around. +separateMixinSourceSet = + +# Adds some debug arguments like verbose output and class export. +usesMixinDebug = false + +# Specify the location of your implementation of IMixinConfigPlugin. Leave it empty otherwise. +mixinPlugin = + +# Specify the package that contains all of your Mixins. You may only place Mixins in this package or the build will fail! +mixinsPackage = + +# Specify the core mod entry class if you use a core mod. This class must implement IFMLLoadingPlugin! +# This parameter is for legacy compatibility only +# Example value: (coreModClass = asm.FMLPlugin) + (modGroup = com.myname.mymodid) -> com.myname.mymodid.asm.FMLPlugin +coreModClass = + +# If your project is only a consolidation of mixins or a core mod and does NOT contain a 'normal' mod ( = some class +# that is annotated with @Mod) you want this to be true. When in doubt: leave it on false! +containsMixinsAndOrCoreModOnly = false + +# Enables Mixins even if this mod doesn't use them, useful if one of the dependencies uses mixins. +forceEnableMixins = false + +# If enabled, you may use 'shadowCompile' for dependencies. They will be integrated into your jar. It is your +# responsibility to check the license and request permission for distribution if required. +usesShadowedDependencies = false + +# If disabled, won't remove unused classes from shadowed dependencies. Some libraries use reflection to access +# their own classes, making the minimization unreliable. +minimizeShadowedDependencies = true + +# If disabled, won't rename the shadowed classes. +relocateShadowedDependencies = true + +# Adds CurseMaven, Modrinth, and some more well-known 1.7.10 repositories. +includeWellKnownRepositories = true + +# A list of repositories to exclude from the includeWellKnownRepositories setting. Should be a space separated +# list of strings, with the acceptable keys being(case does not matter): +# cursemaven +# modrinth +excludeWellKnownRepositories = + +# Change these to your Maven coordinates if you want to publish to a custom Maven repository instead of the default GTNH Maven. +# Authenticate with the MAVEN_USER and MAVEN_PASSWORD environment variables. +# If you need a more complex setup disable maven publishing here and add a publishing repository to addon.gradle. +usesMavenPublishing = true + +# Maven repository to publish the mod to. +# mavenPublishUrl = https\://nexus.gtnewhorizons.com/repository/releases/ + +# Publishing to Modrinth requires you to set the MODRINTH_TOKEN environment variable to your current Modrinth API token. +# +# The project's ID on Modrinth. Can be either the slug or the ID. +# Leave this empty if you don't want to publish to Modrinth. +modrinthProjectId = + +# The project's relations on Modrinth. You can use this to refer to other projects on Modrinth. +# Syntax: scope1-type1:name1;scope2-type2:name2;... +# Where scope can be one of [required, optional, incompatible, embedded], +# type can be one of [project, version], +# and the name is the Modrinth project or version slug/id of the other mod. +# Example: required-project:fplib;optional-project:gasstation;incompatible-project:gregtech +# Note: GTNH Mixins is automatically set as a required dependency if usesMixins = true +modrinthRelations = + +# Publishing to CurseForge requires you to set the CURSEFORGE_TOKEN environment variable to one of your CurseForge API tokens. +# +# The project's numeric ID on CurseForge. You can find this in the About Project box. +# Leave this empty if you don't want to publish on CurseForge. +curseForgeProjectId = + +# The project's relations on CurseForge. You can use this to refer to other projects on CurseForge. +# Syntax: type1:name1;type2:name2;... +# Where type can be one of [requiredDependency, embeddedLibrary, optionalDependency, tool, incompatible], +# and the name is the CurseForge project slug of the other mod. +# Example: requiredDependency:railcraft;embeddedLibrary:cofhlib;incompatible:buildcraft +# Note: UniMixins is automatically set as a required dependency if usesMixins = true. +curseForgeRelations = + +# Optional parameter to customize the produced artifacts. Use this to preserve artifact naming when migrating older +# projects. New projects should not use this parameter. +customArchiveBaseName = ExtraCells + +# Optional parameter to have the build automatically fail if an illegal version is used. +# This can be useful if you e.g. only want to allow versions in the form of '1.1.xxx'. +# The check is ONLY performed if the version is a git tag. +# Note: the specified string must be escaped, so e.g. 1\\.1\\.\\d+ instead of 1\.1\.\d+ +# versionPattern = + +# Uncomment to prevent the source code from being published. +# noPublishedSources = true + +# Uncomment this to disable Spotless checks. +# This should only be uncommented to keep it easier to sync with upstream/other forks. +# That is, if there is no other active fork/upstream, NEVER change this. +# disableSpotless = true + +# Uncomment this to disable Checkstyle checks (currently wildcard import check). +disableCheckstyle = true + +# Override the IDEA build type. Valid values are: "" (leave blank, do not override), "idea" (force use native IDEA build), "gradle" +# (force use delegated build). +# This is meant to be set in $HOME/.gradle/gradle.properties. +# e.g. add "systemProp.org.gradle.project.ideaOverrideBuildType=idea" will override the build type to be native build. +# WARNING: If you do use this option, it will overwrite whatever you have in your existing projects. This might not be what you want! +# Usually there is no need to uncomment this here as other developers do not necessarily use the same build type as you. +# ideaOverrideBuildType = idea + +# Whether IDEA should run spotless checks when pressing the Build button. +# This is meant to be set in $HOME/.gradle/gradle.properties. +# ideaCheckSpotlessOnBuild = true + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index b76121670..2c3521197 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 678d9d8de..09523c0e5 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Wed Jul 02 15:54:47 CDT 2014 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.0-bin.zip diff --git a/gradlew b/gradlew index 91a7e269e..f5feea6d6 100755 --- a/gradlew +++ b/gradlew @@ -1,79 +1,130 @@ -#!/usr/bin/env bash +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum -warn ( ) { +warn () { echo "$*" -} +} >&2 -die ( ) { +die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -82,83 +133,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 8a0b282aa..9d21a2183 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,4 +1,22 @@ -@if "%DEBUG%" == "" @echo off +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -8,26 +26,30 @@ @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -35,54 +57,36 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/jitpack.yml b/jitpack.yml new file mode 100644 index 000000000..09bbb514f --- /dev/null +++ b/jitpack.yml @@ -0,0 +1,2 @@ +before_install: + - ./gradlew setupCIWorkspace \ No newline at end of file diff --git a/repositories.gradle b/repositories.gradle new file mode 100644 index 000000000..fbe787324 --- /dev/null +++ b/repositories.gradle @@ -0,0 +1,26 @@ +// Add any additional repositories for your dependencies here + +repositories { + maven { + name 'GTNH Maven' + url 'http://jenkins.usrv.eu:8081/nexus/content/groups/public/' + allowInsecureProtocol + } + maven { + name 'mightypirates' + url 'https://maven.cil.li/' + metadataSources { + mavenPom() + artifact() + } + } + maven { + url 'https://cursemaven.com' + content { + includeGroup 'curse.maven' + } + } + maven { + url 'https://jitpack.io' + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..54797868d --- /dev/null +++ b/settings.gradle @@ -0,0 +1,23 @@ + +pluginManagement { + repositories { + maven { + // RetroFuturaGradle + name "GTNH Maven" + url "https://nexus.gtnewhorizons.com/repository/public/" + mavenContent { + includeGroup("com.gtnewhorizons") + includeGroupByRegex("com\\.gtnewhorizons\\..+") + } + } + gradlePluginPortal() + mavenCentral() + mavenLocal() + } +} + +plugins { + id 'com.gtnewhorizons.gtnhsettingsconvention' version '1.0.25' +} + + diff --git a/src/api/java/mekanism/api/Chunk3D.java b/src/api/java/mekanism/api/Chunk3D.java deleted file mode 100644 index f469d5db5..000000000 --- a/src/api/java/mekanism/api/Chunk3D.java +++ /dev/null @@ -1,118 +0,0 @@ -package mekanism.api; - -import net.minecraft.entity.Entity; -import net.minecraft.world.ChunkCoordIntPair; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; - -/** - * Chunk3D - an integer-based way to keep track of and perform operations on chunks in a Minecraft-based environment. This also takes - * in account the dimension the chunk is in. - * @author aidancbrady - * - */ -public class Chunk3D -{ - public int dimensionId; - - public int xCoord; - public int zCoord; - - /** - * Creates a Chunk3D object from the given x and z coordinates, as well as a dimension. - * @param x - chunk x location - * @param z - chunk z location - * @param dimension - the dimension this Chunk3D is in - */ - public Chunk3D(int x, int z, int dimension) - { - xCoord = x; - zCoord = z; - - dimensionId = dimension; - } - - /** - * Creates a Chunk3D from an entity based on it's location and dimension. - * @param entity - the entity to get the Chunk3D object from - */ - public Chunk3D(Entity entity) - { - xCoord = ((int)entity.posX) >> 4; - zCoord = ((int)entity.posZ) >> 4; - - dimensionId = entity.dimension; - } - - /** - * Creates a Chunk3D from a Coord4D based on it's coordinates and dimension. - * @param coord - the Coord4D object to get this Chunk3D from - */ - public Chunk3D(Coord4D coord) - { - xCoord = coord.xCoord >> 4; - zCoord = coord.zCoord >> 4; - - dimensionId = coord.dimensionId; - } - - /** - * Whether or not this chunk exists in the given world. - * @param world - the world to check in - * @return if the chunk exists - */ - public boolean exists(World world) - { - return world.getChunkProvider().chunkExists(xCoord, zCoord); - } - - /** - * Gets a Chunk object corresponding to this Chunk3D's coordinates. - * @param world - the world to get the Chunk object from - * @return the corresponding Chunk object - */ - public Chunk getChunk(World world) - { - return world.getChunkFromChunkCoords(xCoord, zCoord); - } - - /** - * Returns this Chunk3D in the Minecraft-based ChunkCoordIntPair format. - * @return this Chunk3D as a ChunkCoordIntPair - */ - public ChunkCoordIntPair toPair() - { - return new ChunkCoordIntPair(xCoord, zCoord); - } - - @Override - public Coord4D clone() - { - return new Coord4D(xCoord, zCoord, dimensionId); - } - - @Override - public String toString() - { - return "[Chunk3D: " + xCoord + ", " + zCoord + ", dim=" + dimensionId + "]"; - } - - @Override - public boolean equals(Object obj) - { - return obj instanceof Chunk3D && - ((Chunk3D)obj).xCoord == xCoord && - ((Chunk3D)obj).zCoord == zCoord && - ((Chunk3D)obj).dimensionId == dimensionId; - } - - @Override - public int hashCode() - { - int code = 1; - code = 31 * code + xCoord; - code = 31 * code + zCoord; - code = 31 * code + dimensionId; - return code; - } -} diff --git a/src/api/java/mekanism/api/Coord4D.java b/src/api/java/mekanism/api/Coord4D.java deleted file mode 100644 index 1bda3815c..000000000 --- a/src/api/java/mekanism/api/Coord4D.java +++ /dev/null @@ -1,402 +0,0 @@ -package mekanism.api; - -import java.util.ArrayList; - -import net.minecraft.block.Block; -import net.minecraft.entity.Entity; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MathHelper; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraft.world.chunk.Chunk; -import net.minecraftforge.common.util.ForgeDirection; -import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint; - -import io.netty.buffer.ByteBuf; - -/** - * Coord4D - an integer-based way to keep track of and perform operations on blocks in a Minecraft-based environment. This also takes - * in account the dimension the coordinate is in. - * @author aidancbrady - * - */ -public class Coord4D -{ - public int xCoord; - public int yCoord; - public int zCoord; - - public int dimensionId; - - /** - * Creates a Coord4D WITHOUT a dimensionId. Don't use unless absolutely necessary. - * @param x - x coordinate - * @param y - y coordinate - * @param z - z coordinate - */ - public Coord4D(int x, int y, int z) - { - xCoord = x; - yCoord = y; - zCoord = z; - - dimensionId = 0; - } - - /** - * Creates a Coord4D from an entity's position, rounded down. - * @param entity - entity to create the Coord4D from - */ - public Coord4D(Entity entity) - { - xCoord = (int)entity.posX; - yCoord = (int)entity.posY; - zCoord = (int)entity.posZ; - - dimensionId = entity.worldObj.provider.dimensionId; - } - - /** - * Creates a Coord4D from the defined x, y, z, and dimension values. - * @param x - x coordinate - * @param y - y coordinate - * @param z - z coordinate - * @param dimension - dimension ID - */ - public Coord4D(int x, int y, int z, int dimension) - { - xCoord = x; - yCoord = y; - zCoord = z; - - dimensionId = dimension; - } - - /** - * Gets the metadata of the block representing this Coord4D. - * @param world - world this Coord4D is in - * @return the metadata of this Coord4D's block - */ - public int getMetadata(IBlockAccess world) - { - return world.getBlockMetadata(xCoord, yCoord, zCoord); - } - - /** - * Gets the TileEntity of the block representing this Coord4D. - * @param world - world this Coord4D is in - * @return the TileEntity of this Coord4D's block - */ - public TileEntity getTileEntity(IBlockAccess world) - { - if(world instanceof World && !exists((World)world)) - { - return null; - } - - return world.getTileEntity(xCoord, yCoord, zCoord); - } - - /** - * Gets the Block value of the block representing this Coord4D. - * @param world - world this Coord4D is in - * @return the Block value of this Coord4D's block - */ - public Block getBlock(IBlockAccess world) - { - if(world instanceof World && !exists((World)world)) - { - return null; - } - - return world.getBlock(xCoord, yCoord, zCoord); - } - - /** - * Writes this Coord4D's data to an NBTTagCompound. - * @param nbtTags - tag compound to write to - * @return the tag compound with this Coord4D's data - */ - public NBTTagCompound write(NBTTagCompound nbtTags) - { - nbtTags.setInteger("x", xCoord); - nbtTags.setInteger("y", yCoord); - nbtTags.setInteger("z", zCoord); - nbtTags.setInteger("dimensionId", dimensionId); - - return nbtTags; - } - - /** - * Writes this Coord4D's data to an ArrayList for packet transfer. - * @param data - the ArrayList to add the data to - */ - public void write(ArrayList data) - { - data.add(xCoord); - data.add(yCoord); - data.add(zCoord); - data.add(dimensionId); - } - - /** - * Writes this Coord4D's data to a ByteBuf for packet transfer. - * @param dataStream - the ByteBuf to add the data to - */ - public void write(ByteBuf dataStream) - { - dataStream.writeInt(xCoord); - dataStream.writeInt(yCoord); - dataStream.writeInt(zCoord); - dataStream.writeInt(dimensionId); - } - - /** - * Translates this Coord4D by the defined x, y, and z values. - * @param x - x value to translate - * @param y - y value to translate - * @param z - z value to translate - * @return translated Coord4D - */ - public Coord4D translate(int x, int y, int z) - { - xCoord += x; - yCoord += y; - zCoord += z; - - return this; - } - - /** - * Creates and returns a new Coord4D translated to the defined offsets of the side. - * @param side - side to translate this Coord4D to - * @return translated Coord4D - */ - public Coord4D getFromSide(ForgeDirection side) - { - return getFromSide(side, 1); - } - - /** - * Creates and returns a new Coord4D translated to the defined offsets of the side by the defined amount. - * @param side - side to translate this Coord4D to - * @param amount - how far to translate this Coord4D - * @return translated Coord4D - */ - public Coord4D getFromSide(ForgeDirection side, int amount) - { - return new Coord4D(xCoord+(side.offsetX*amount), yCoord+(side.offsetY*amount), zCoord+(side.offsetZ*amount), dimensionId); - } - - public ItemStack getStack(IBlockAccess world) - { - Block block = getBlock(world); - - if(block == null || block == Blocks.air) - { - return null; - } - - return new ItemStack(block, 1, getMetadata(world)); - } - - /** - * Returns a new Coord4D from a defined TileEntity's xCoord, yCoord and zCoord values. - * @param tileEntity - TileEntity at the location that will represent this Coord4D - * @return the Coord4D object from the TileEntity - */ - public static Coord4D get(TileEntity tileEntity) - { - return new Coord4D(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord, tileEntity.getWorldObj().provider.dimensionId); - } - - /** - * Returns a new Coord4D from a tag compound. - * @param data - tag compound to read from - * @return the Coord4D from the tag compound - */ - public static Coord4D read(NBTTagCompound tag) - { - return new Coord4D(tag.getInteger("x"), tag.getInteger("y"), tag.getInteger("z"), tag.getInteger("id")); - } - - /** - * Returns a new Coord4D from a ByteBuf. - * @param dataStream - data input to read from - * @return the Coord4D from the data input - */ - public static Coord4D read(ByteBuf dataStream) - { - return new Coord4D(dataStream.readInt(), dataStream.readInt(), dataStream.readInt(), dataStream.readInt()); - } - - /** - * Creates and returns a new Coord4D with values representing the difference between the defined Coord4D - * @param other - the Coord4D to subtract from this - * @return a Coord4D representing the distance between the defined Coord4D - */ - public Coord4D difference(Coord4D other) - { - return new Coord4D(xCoord-other.xCoord, yCoord-other.yCoord, zCoord-other.zCoord, dimensionId); - } - - /** - * A method used to find the ForgeDirection represented by the distance of the defined Coord4D. Most likely won't have many - * applicable uses. - * @param other - Coord4D to find the side difference of - * @return ForgeDirection representing the side the defined relative Coord4D is on to this - */ - public ForgeDirection sideDifference(Coord4D other) - { - Coord4D diff = difference(other); - - for(ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) - { - if(side.offsetX == diff.xCoord && side.offsetY == diff.yCoord && side.offsetZ == diff.zCoord) - { - return side; - } - } - - return ForgeDirection.UNKNOWN; - } - - /** - * Gets the distance to a defined Coord4D. - * @param obj - the Coord4D to find the distance to - * @return the distance to the defined Coord4D - */ - public int distanceTo(Coord4D obj) - { - int subX = xCoord - obj.xCoord; - int subY = yCoord - obj.yCoord; - int subZ = zCoord - obj.zCoord; - return (int)MathHelper.sqrt_double(subX * subX + subY * subY + subZ * subZ); - } - - /** - * Whether or not the defined side of this Coord4D is visible. - * @param side - side to check - * @param world - world this Coord4D is in - * @return - */ - public boolean sideVisible(ForgeDirection side, IBlockAccess world) - { - return world.isAirBlock(xCoord+side.offsetX, yCoord+side.offsetY, zCoord+side.offsetZ); - } - - /** - * Gets a TargetPoint with the defined range from this Coord4D with the appropriate coordinates and dimension ID. - * @param range - the range the packet can be sent in of this Coord4D - * @return TargetPoint relative to this Coord4D - */ - public TargetPoint getTargetPoint(double range) - { - return new TargetPoint(dimensionId, xCoord, yCoord, zCoord, range); - } - - /** - * Steps this Coord4D in the defined side's offset without creating a new value. - * @param side - side to step towards - * @return this Coord4D - */ - public Coord4D step(ForgeDirection side) - { - return translate(side.offsetX, side.offsetY, side.offsetZ); - } - - /** - * Whether or not the chunk this Coord4D is in exists and is loaded. - * @param world - world this Coord4D is in - * @return the chunk of this Coord4D - */ - public boolean exists(World world) - { - return world.getChunkProvider().chunkExists(xCoord >> 4, zCoord >> 4); - } - - /** - * Gets the chunk this Coord4D is in. - * @param world - world this Coord4D is in - * @return the chunk of this Coord4D - */ - public Chunk getChunk(World world) - { - return world.getChunkFromBlockCoords(xCoord, zCoord); - } - - /** - * Gets the Chunk3D object with chunk coordinates correlating to this Coord4D's location - * @return Chunk3D with correlating chunk coordinates. - */ - public Chunk3D getChunk3D() - { - return new Chunk3D(this); - } - - /** - * Whether or not the block this Coord4D represents is an air block. - * @param world - world this Coord4D is in - * @return if this Coord4D is an air block - */ - public boolean isAirBlock(IBlockAccess world) - { - return world.isAirBlock(xCoord, yCoord, zCoord); - } - - /** - * Whether or not this block this Coord4D represents is replaceable. - * @param world - world this Coord4D is in - * @return if this Coord4D is replaceable - */ - public boolean isReplaceable(IBlockAccess world) - { - return getBlock(world).isReplaceable(world, xCoord, yCoord, zCoord); - } - - /** - * Gets a bounding box that contains the area this Coord4D would take up in a world. - * @return this Coord4D's bounding box - */ - public AxisAlignedBB getBoundingBox() - { - return AxisAlignedBB.getBoundingBox(xCoord, yCoord, zCoord, xCoord+1, yCoord+1, zCoord+1); - } - - @Override - public Coord4D clone() - { - return new Coord4D(xCoord, yCoord, zCoord, dimensionId); - } - - @Override - public String toString() - { - return "[Coord4D: " + xCoord + ", " + yCoord + ", " + zCoord + ", dim=" + dimensionId + "]"; - } - - @Override - public boolean equals(Object obj) - { - return obj instanceof Coord4D && - ((Coord4D)obj).xCoord == xCoord && - ((Coord4D)obj).yCoord == yCoord && - ((Coord4D)obj).zCoord == zCoord && - ((Coord4D)obj).dimensionId == dimensionId; - } - - @Override - public int hashCode() - { - int code = 1; - code = 31 * code + xCoord; - code = 31 * code + yCoord; - code = 31 * code + zCoord; - code = 31 * code + dimensionId; - return code; - } -} \ No newline at end of file diff --git a/src/api/java/mekanism/api/EnumColor.java b/src/api/java/mekanism/api/EnumColor.java deleted file mode 100644 index df9ba7433..000000000 --- a/src/api/java/mekanism/api/EnumColor.java +++ /dev/null @@ -1,112 +0,0 @@ -package mekanism.api; - -import net.minecraft.util.StatCollector; - -/** - * Simple color enum for adding colors to in-game GUI strings of text. - * @author AidanBrady - * - */ -public enum EnumColor -{ - BLACK("\u00a70", "black", "Black", new int[] {0, 0, 0}, 0), - DARK_BLUE("\u00a71", "darkBlue", "Blue", new int[] {0, 0, 170}, 4), - DARK_GREEN("\u00a72", "darkGreen", "Green", new int[] {0, 170, 0}, 2), - DARK_AQUA("\u00a73", "darkAqua", "Cyan", new int[] {0, 255, 255}, 6), - DARK_RED("\u00a74", "darkRed", null, new int[] {170, 0, 0}, -1), - PURPLE("\u00a75", "purple", "Purple", new int[] {170, 0, 170}, 5), - ORANGE("\u00a76", "orange", "Orange", new int[] {255, 170, 0}, 14), - GREY("\u00a77", "grey", "LightGray", new int[] {170, 170, 170}, 7), - DARK_GREY("\u00a78", "darkGrey", "Gray", new int[] {85, 85, 85}, 8), - INDIGO("\u00a79", "indigo", "LightBlue", new int[] {85, 85, 255}, 12), - BRIGHT_GREEN("\u00a7a", "brightGreen", "Lime", new int[] {85, 255, 85}, 10), - AQUA("\u00a7b", "aqua", null, new int[] {85, 255, 255}, -1), - RED("\u00a7c", "red", "Red", new int[] {255, 0, 0}, 1), - PINK("\u00a7d", "pink", "Magenta", new int[] {255, 85, 255}, 13), - YELLOW("\u00a7e", "yellow", "Yellow", new int[] {255, 255, 85}, 11), - WHITE("\u00a7f", "white", "White", new int[] {255, 255, 255}, 15), - //Extras for dye-completeness - BROWN("\u00a76", "brown", "Brown", new int[] {150, 75, 0}, 3), - BRIGHT_PINK("\u00a7d", "brightPink", "Pink", new int[] {255, 192, 203}, 9); - - public static EnumColor[] DYES = new EnumColor[] {BLACK, RED, DARK_GREEN, BROWN, DARK_BLUE, PURPLE, DARK_AQUA, GREY, DARK_GREY, BRIGHT_PINK, BRIGHT_GREEN, YELLOW, INDIGO, PINK, ORANGE, WHITE}; - - /** The color code that will be displayed */ - public final String code; - - public final int[] rgbCode; - - public final int mcMeta; - - /** A friendly name of the color. */ - public String unlocalizedName; - - public String dyeName; - - private EnumColor(String s, String n, String dye, int[] rgb, int meta) - { - code = s; - unlocalizedName = n; - dyeName = dye; - rgbCode = rgb; - mcMeta = meta; - } - - /** - * Gets the localized name of this color by translating the unlocalized name. - * @return localized name - */ - public String getLocalizedName() - { - return StatCollector.translateToLocal("color." + unlocalizedName); - } - - public String getDyeName() - { - return StatCollector.translateToLocal("dye." + unlocalizedName); - } - - public String getOreDictName() - { - return dyeName; - } - - /** - * Gets the name of this color with it's color prefix code. - * @return the color's name and color prefix - */ - public String getName() - { - return code + getLocalizedName(); - } - - public String getDyedName() - { - return code + getDyeName(); - } - - /** - * Gets the 0-1 of this color's RGB value by dividing by 255 (used for OpenGL coloring). - * @param index - R:0, G:1, B:2 - * @return the color value - */ - public float getColor(int index) - { - return (float)rgbCode[index]/255F; - } - - /** - * Gets the value of this color mapped to MC in-game item colors present in dyes and wool. - * @return mc meta value - */ - public int getMetaValue() - { - return mcMeta; - } - - @Override - public String toString() - { - return code; - } -} diff --git a/src/api/java/mekanism/api/IClientTicker.java b/src/api/java/mekanism/api/IClientTicker.java deleted file mode 100644 index 228897370..000000000 --- a/src/api/java/mekanism/api/IClientTicker.java +++ /dev/null @@ -1,8 +0,0 @@ -package mekanism.api; - -public interface IClientTicker -{ - public void clientTick(); - - public boolean needsTicks(); -} diff --git a/src/api/java/mekanism/api/IConfigurable.java b/src/api/java/mekanism/api/IConfigurable.java deleted file mode 100644 index 512fabf43..000000000 --- a/src/api/java/mekanism/api/IConfigurable.java +++ /dev/null @@ -1,27 +0,0 @@ -package mekanism.api; - -import net.minecraft.entity.player.EntityPlayer; - -/** - * Implement this in your TileEntity class if your block can be modified by a Configurator. - * @author aidancbrady - * - */ -public interface IConfigurable -{ - /** - * Called when a player shift-right clicks this block with a Configurator. - * @param player - the player who clicked the block - * @param side - the side the block was clicked on - * @return whether or not an action was performed - */ - public boolean onSneakRightClick(EntityPlayer player, int side); - - /** - * Called when a player right clicks this block with a Configurator. - * @param player - the player who clicked the block - * @param side - the side the block was clicked on - * @return whether or not an action was performed - */ - public boolean onRightClick(EntityPlayer player, int side); -} diff --git a/src/api/java/mekanism/api/IFilterAccess.java b/src/api/java/mekanism/api/IFilterAccess.java deleted file mode 100644 index abdcf29a8..000000000 --- a/src/api/java/mekanism/api/IFilterAccess.java +++ /dev/null @@ -1,31 +0,0 @@ -package mekanism.api; - -import net.minecraft.nbt.NBTTagCompound; - -/** - * Implement this in your TileEntity class if you wish for Mekanism filters to be able to store any of their - * information. - * @author aidancbrady - * - */ -public interface IFilterAccess -{ - /** - * Collects the TileEntity's filter card data into the parameterized NBTTagCompound. - * @param nbtTags - the NBTTagCompound of the filter card ItemStack - * @return the NBTTagCompound that now contains the TileEntity's filter card data - */ - public NBTTagCompound getFilterData(NBTTagCompound nbtTags); - - /** - * Retrieves the TileEntity's data contained in the filter card based on the given NBTTagCompopund. - * @param nbtTags - the NBTTagCompound of the filter card ItemStack - */ - public void setFilterData(NBTTagCompound nbtTags); - - /** - * A String name of this TileEntity that will be displayed as the type of data on the filter card. - * @return the String name of this TileEntity - */ - public String getDataType(); -} diff --git a/src/api/java/mekanism/api/IHeatTransfer.java b/src/api/java/mekanism/api/IHeatTransfer.java deleted file mode 100644 index da682e116..000000000 --- a/src/api/java/mekanism/api/IHeatTransfer.java +++ /dev/null @@ -1,28 +0,0 @@ -package mekanism.api; - -import net.minecraftforge.common.util.ForgeDirection; - -public interface IHeatTransfer -{ - /**The value of the zero point of our temperature scale in kelvin*/ - public static final double AMBIENT_TEMP = 300; - - /**The heat transfer coefficient for air*/ - public static final double AIR_INVERSE_COEFFICIENT = 10000; - - public double getTemp(); - - public double getInverseConductionCoefficient(); - - public double getInsulationCoefficient(ForgeDirection side); - - public void transferHeatTo(double heat); - - public double[] simulateHeat(); - - public double applyTemperatureChange(); - - public boolean canConnectHeat(ForgeDirection side); - - public IHeatTransfer getAdjacent(ForgeDirection side); -} diff --git a/src/api/java/mekanism/api/IMekWrench.java b/src/api/java/mekanism/api/IMekWrench.java deleted file mode 100644 index 6ac4b052e..000000000 --- a/src/api/java/mekanism/api/IMekWrench.java +++ /dev/null @@ -1,8 +0,0 @@ -package mekanism.api; - -import net.minecraft.entity.player.EntityPlayer; - -public interface IMekWrench -{ - public boolean canUseWrench(EntityPlayer player, int x, int y, int z); -} diff --git a/src/api/java/mekanism/api/ISalinationSolar.java b/src/api/java/mekanism/api/ISalinationSolar.java deleted file mode 100644 index 20e3e1ecf..000000000 --- a/src/api/java/mekanism/api/ISalinationSolar.java +++ /dev/null @@ -1,11 +0,0 @@ -package mekanism.api; - -/** - * Implement this class in a TileEntity if you wish for it to be able to heat up a Salination Plant. - * @author aidancbrady - * - */ -public interface ISalinationSolar -{ - public boolean seesSun(); -} diff --git a/src/api/java/mekanism/api/ItemRetriever.java b/src/api/java/mekanism/api/ItemRetriever.java deleted file mode 100644 index c2820f0bc..000000000 --- a/src/api/java/mekanism/api/ItemRetriever.java +++ /dev/null @@ -1,112 +0,0 @@ -package mekanism.api; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -/** - * Use this class's 'getItem()' method to retrieve ItemStacks from the 'Mekanism' - * class. - * @author AidanBrady - * - */ -public final class ItemRetriever -{ - /** The 'MekanismItems' class that items are retrieved from. */ - private static Class MekanismItems; - - /** The 'MekanismBlocks' class that blocks are retrieved from. */ - private static Class MekanismBlocks; - - /** - * Attempts to retrieve an ItemStack of an item with the declared identifier. - * - * Mekanism identifiers follow an easy-to-remember pattern. All identifiers - * are identical to the String returned by 'getItemName().' None include spaces, - * and all start with a capital letter. The name that shows up in-game can be - * stripped down to identifier form by removing spaces and all non-alphabetic - * characters (,./'=-_). Below is an example: - * - * ItemStack enrichedAlloy = ItemRetriever.getItem("EnrichedAlloy"); - * - * Note that for items or blocks that have specific metadata you will need to create - * a new ItemStack with that specified value, as this will only return an ItemStack - * with the meta value '0.' - * - * Make sure you run this in or after FMLPostInitializationEvent runs, because most - * items are registered when FMLInitializationEvent runs. However, some items ARE - * registered later in order to hook into other mods. In a rare circumstance you may - * have to add "after:Mekanism" in the @Mod 'dependencies' annotation. - * - * @param identifier - a String to be searched in the 'MekanismItems' class - * @return an ItemStack of the declared identifier, otherwise null. - */ - public static ItemStack getItem(String identifier) - { - try { - if(MekanismItems == null) - { - MekanismItems = Class.forName("mekanism.common.MekanismItems"); - } - - Object ret = MekanismItems.getField(identifier).get(null); - - if(ret instanceof Item) - { - return new ItemStack((Item)ret, 1); - } - else { - return null; - } - } catch(Exception e) { - System.err.println("Error retrieving item with identifier '" + identifier + "': " + e.getMessage()); - return null; - } - } - - /** - * Attempts to retrieve an ItemStack of a block with the declared identifier. - * - * Mekanism identifiers follow an easy-to-remember pattern. All identifiers - * are identical to the String returned by 'getItemName().' None include spaces, - * and all start with a capital letter. The name that shows up in-game can be - * stripped down to identifier form by removing spaces and all non-alphabetic - * characters (,./'=-_). Below is an example: - * - * ItemStack enrichedAlloy = ItemRetriever.getItem("EnrichedAlloy"); - * - * Note that for items or blocks that have specific metadata you will need to create - * a new ItemStack with that specified value, as this will only return an ItemStack - * with the meta value '0.' - * - * Make sure you run this in or after FMLPostInitializationEvent runs, because most - * items are registered when FMLInitializationEvent runs. However, some items ARE - * registered later in order to hook into other mods. In a rare circumstance you may - * have to add "after:Mekanism" in the @Mod 'dependencies' annotation. - * - * @param identifier - a String to be searched in the 'MekanismBlocks' class - * @return an ItemStack of the declared identifier, otherwise null. - */ - public static ItemStack getBlock(String identifier) - { - try { - if(MekanismBlocks == null) - { - MekanismBlocks = Class.forName("mekanism.common.MekanismBlocks"); - } - - Object ret = MekanismBlocks.getField(identifier).get(null); - - if(ret instanceof Block) - { - return new ItemStack((Block)ret, 1); - } - else { - return null; - } - } catch(Exception e) { - System.err.println("Error retrieving block with identifier '" + identifier + "': " + e.getMessage()); - return null; - } - } -} diff --git a/src/api/java/mekanism/api/MekanismAPI.java b/src/api/java/mekanism/api/MekanismAPI.java deleted file mode 100644 index 9f8c87a68..000000000 --- a/src/api/java/mekanism/api/MekanismAPI.java +++ /dev/null @@ -1,47 +0,0 @@ -package mekanism.api; - -import java.util.HashSet; -import java.util.Set; - -import mekanism.api.util.BlockInfo; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraftforge.oredict.OreDictionary; -import cpw.mods.fml.common.eventhandler.Event; - -public class MekanismAPI -{ - //Add a BlockInfo value here if you don't want a certain block to be picked up by cardboard boxes - private static Set cardboardBoxIgnore = new HashSet(); - - public static boolean isBlockCompatible(Item item, int meta) - { - for(BlockInfo i : cardboardBoxIgnore) - { - if(i.block == Block.getBlockFromItem(item) && (i.meta == OreDictionary.WILDCARD_VALUE || i.meta == meta)) - { - return false; - } - } - - return true; - } - - public static void addBoxBlacklist(Block block, int meta) - { - cardboardBoxIgnore.add(new BlockInfo(block, meta)); - } - - public static void removeBoxBlacklist(Block block, int meta) - { - cardboardBoxIgnore.remove(new BlockInfo(block, meta)); - } - - public static Set getBoxIgnore() - { - return cardboardBoxIgnore; - } - - public static class BoxBlacklistEvent extends Event {} -} diff --git a/src/api/java/mekanism/api/MekanismConfig.java b/src/api/java/mekanism/api/MekanismConfig.java deleted file mode 100644 index cf6c2e767..000000000 --- a/src/api/java/mekanism/api/MekanismConfig.java +++ /dev/null @@ -1,129 +0,0 @@ -package mekanism.api; - -import java.util.HashMap; -import java.util.Map; - -import mekanism.api.util.UnitDisplayUtils.EnergyType; -import mekanism.api.util.UnitDisplayUtils.TempType; - -public class MekanismConfig -{ - public static class general - { - public static boolean updateNotifications = true; - public static boolean controlCircuitOreDict = true; - public static boolean logPackets = false; - public static boolean dynamicTankEasterEgg = false; - public static boolean voiceServerEnabled = true; - public static boolean cardboardSpawners = true; - public static boolean enableWorldRegeneration = true; - public static boolean creativeOverrideElectricChest = true; - public static boolean spawnBabySkeletons = true; - public static int obsidianTNTBlastRadius = 12; - public static int osmiumPerChunk = 12; - public static int copperPerChunk = 16; - public static int tinPerChunk = 14; - public static int saltPerChunk = 2; - public static int obsidianTNTDelay = 100; - public static int UPDATE_DELAY = 10; - public static int VOICE_PORT = 36123; - public static int maxUpgradeMultiplier = 10; - public static int userWorldGenVersion = 0; - public static double ENERGY_PER_REDSTONE = 10000; - public static int ETHENE_BURN_TIME = 40; - public static double DISASSEMBLER_USAGE = 10; - public static EnergyType activeType = EnergyType.J; - public static TempType tempUnit = TempType.K; - public static double TO_IC2; - public static double TO_TE; - public static double FROM_H2; - public static double FROM_IC2; - public static double FROM_TE; - public static int laserRange; - public static double laserEnergyNeededPerHardness; - public static double minerSilkMultiplier = 6; - public static boolean blacklistIC2; - public static boolean blacklistRF; - public static boolean destroyDisabledBlocks; - public static boolean enableAmbientLighting; - public static int ambientLightingLevel; - public static boolean prefilledPortableTanks; - } - - public static class client - { - public static boolean enablePlayerSounds = true; - public static boolean enableMachineSounds = true; - public static boolean fancyUniversalCableRender = true; - public static boolean holidays = true; - public static float baseSoundVolume = 1F; - public static boolean machineEffects = true; - public static boolean oldTransmitterRender = false; - public static boolean replaceSoundsWhenResuming = true; - public static boolean renderCTM = true; - } - - public static class machines - { - private static Map config = new HashMap(); - - public static boolean isEnabled(String type) - { - return config.get(type) != null && config.get(type); - } - - public static void setEntry(String type, boolean enabled) - { - config.put(type, enabled); - } - } - - public static class usage - { - public static double enrichmentChamberUsage; - public static double osmiumCompressorUsage; - public static double combinerUsage; - public static double crusherUsage; - public static double factoryUsage; - public static double metallurgicInfuserUsage; - public static double purificationChamberUsage; - public static double energizedSmelterUsage; - public static double digitalMinerUsage; - public static double electricPumpUsage; - public static double rotaryCondensentratorUsage; - public static double oxidationChamberUsage; - public static double chemicalInfuserUsage; - public static double chemicalInjectionChamberUsage; - public static double precisionSawmillUsage; - public static double chemicalDissolutionChamberUsage; - public static double chemicalWasherUsage; - public static double chemicalCrystallizerUsage; - public static double seismicVibratorUsage; - public static double pressurizedReactionBaseUsage; - public static double fluidicPlenisherUsage; - public static double laserUsage; - public static double gasCentrifugeUsage; - public static double heavyWaterElectrolysisUsage; - } - - public static class generators - { - public static double advancedSolarGeneration; - public static double bioGeneration; - public static double heatGeneration; - public static double heatGenerationLava; - public static double heatGenerationNether; - public static double solarGeneration; - - public static double windGenerationMin; - public static double windGenerationMax; - - public static int windGenerationMinY; - public static int windGenerationMaxY; - } - - public static class tools - { - public static double armorSpawnRate; - } -} diff --git a/src/api/java/mekanism/api/Pos3D.java b/src/api/java/mekanism/api/Pos3D.java deleted file mode 100644 index 1e22afcdd..000000000 --- a/src/api/java/mekanism/api/Pos3D.java +++ /dev/null @@ -1,282 +0,0 @@ -package mekanism.api; - -import net.minecraft.entity.Entity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.AxisAlignedBB; -import net.minecraft.util.MathHelper; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; - -/** - * Pos3D - a way of performing operations on objects in a three dimensional environment. - * @author aidancbrady - * - */ -public class Pos3D -{ - public double xPos; - public double yPos; - public double zPos; - - public Pos3D() - { - this(0, 0, 0); - } - - public Pos3D(Vec3 vec) - { - xPos = vec.xCoord; - yPos = vec.yCoord; - zPos = vec.zCoord; - } - - public Pos3D(double x, double y, double z) - { - xPos = x; - yPos = y; - zPos = z; - } - - public Pos3D(Coord4D coord) - { - xPos = coord.xCoord; - yPos = coord.yCoord; - zPos = coord.zCoord; - } - - /** - * Creates a Pos3D with an entity's posX, posY, and posZ values. - * @param entity - entity to create the Pos3D from - */ - public Pos3D(Entity entity) - { - this(entity.posX, entity.posY, entity.posZ); - } - - /** - * Creates a Pos3D with a TileEntity's xCoord, yCoord and zCoord values. - * @param tileEntity - TileEntity to create the Pos3D from - */ - public Pos3D(TileEntity tileEntity) - { - this(tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); - } - - /** - * Creates and returns a Pos3D with values representing the difference between this and the Pos3D in the parameters. - * @param pos - Pos3D to subtract - * @return difference of the two Pos3Ds - */ - public Pos3D diff(Pos3D pos) - { - return new Pos3D(xPos-pos.xPos, yPos-pos.yPos, zPos-pos.zPos); - } - - /** - * Creates a new Pos3D from the motion of an entity. - * @param entity - * @return - */ - public static Pos3D fromMotion(Entity entity) - { - return new Pos3D(entity.motionX, entity.motionY, entity.motionZ); - } - - /** - * Centres a block-derived Pos3D - */ - public Pos3D centre() - { - return translate(0.5, 0.5, 0.5); - } - - /** - * Translates this Pos3D by the defined values. - * @param x - amount to translate on the x axis - * @param y - amount to translate on the y axis - * @param z - amount to translate on the z axis - * @return the translated Pos3D - */ - public Pos3D translate(double x, double y, double z) - { - xPos += x; - yPos += y; - zPos += z; - - return this; - } - - /** - * Performs the same operation as translate(x, y, z), but with a Pos3D value instead. - * @param pos - Pos3D value to translate by - * @return translated Pos3D - */ - public Pos3D translate(Pos3D pos) - { - return translate(pos.xPos, pos.yPos, pos.zPos); - } - - /** - * Performs the same operation as translate(x, y, z), but by a set amount in a ForgeDirection - */ - public Pos3D translate(ForgeDirection direction, double amount) - { - return translate(direction.offsetX * amount, direction.offsetY * amount, direction.offsetZ * amount); - } - - /** - * Performs the same operation as translate(x, y, z), but by a set amount in a ForgeDirection - */ - public Pos3D translateExcludingSide(ForgeDirection direction, double amount) - { - if(direction.offsetX == 0) xPos += amount; - if(direction.offsetY == 0) yPos += amount; - if(direction.offsetZ == 0) zPos += amount; - - return this; - } - - /** - * Returns the distance between this and the defined Pos3D. - * @param pos - the Pos3D to find the distance to - * @return the distance between this and the defined Pos3D - */ - public double distance(Pos3D pos) - { - double subX = xPos - pos.xPos; - double subY = yPos - pos.yPos; - double subZ = zPos - pos.zPos; - return MathHelper.sqrt_double(subX * subX + subY * subY + subZ * subZ); - } - - /** - * Rotates this Pos3D by the defined yaw value. - * @param yaw - yaw to rotate by - * @return rotated Pos3D - */ - public Pos3D rotateYaw(double yaw) - { - double yawRadians = Math.toRadians(yaw); - - double x = xPos; - double z = zPos; - - if(yaw != 0) - { - xPos = x * Math.cos(yawRadians) - z * Math.sin(yawRadians); - zPos = z * Math.cos(yawRadians) + x * Math.sin(yawRadians); - } - - return this; - } - - public Pos3D rotatePitch(double pitch) - { - double pitchRadians = Math.toRadians(pitch); - - double y = yPos; - double z = zPos; - - if(pitch != 0) - { - yPos = y * Math.cos(pitchRadians) - z * Math.sin(pitchRadians); - zPos = z * Math.cos(pitchRadians) + y * Math.sin(pitchRadians); - } - - return this; - } - - public Pos3D rotate(double yaw, double pitch) - { - double yawRadians = Math.toRadians(yaw); - double pitchRadians = Math.toRadians(pitch); - - double x = xPos; - double y = yPos; - double z = zPos; - - xPos = x * Math.cos(yawRadians) - z * Math.sin(yawRadians); - yPos = y * Math.cos(pitchRadians) - z * Math.sin(pitchRadians); - zPos = (z * Math.cos(yawRadians) + x * Math.sin(yawRadians)) * (z * Math.cos(pitchRadians) + y * Math.sin(pitchRadians)); - - return this; - } - - public Pos3D multiply(Pos3D pos) - { - xPos *= pos.xPos; - yPos *= pos.yPos; - zPos *= pos.zPos; - - return this; - } - - /** - * Scales this Pos3D by the defined x, y, an z values. - * @param x - x value to scale by - * @param y - y value to scale by - * @param z - z value to scale by - * @return scaled Pos3D - */ - public Pos3D scale(double x, double y, double z) - { - xPos *= x; - yPos *= y; - zPos *= z; - - return this; - } - - /** - * Performs the same operation as scale(x, y, z), but with a value representing all three dimensions. - * @param scale - value to scale by - * @return scaled Pos3D - */ - public Pos3D scale(double scale) - { - return scale(scale, scale, scale); - } - - public static AxisAlignedBB getAABB(Pos3D pos1, Pos3D pos2) - { - return AxisAlignedBB.getBoundingBox( - Math.min(pos1.xPos, pos2.xPos), - Math.min(pos1.yPos, pos2.yPos), - Math.min(pos1.zPos, pos2.zPos), - Math.max(pos1.xPos, pos2.xPos), - Math.max(pos1.yPos, pos2.yPos), - Math.max(pos1.zPos, pos2.zPos) - ); - } - - @Override - public Pos3D clone() - { - return new Pos3D(xPos, yPos, zPos); - } - - @Override - public String toString() - { - return "[Pos3D: " + xPos + ", " + yPos + ", " + zPos + "]"; - } - - @Override - public boolean equals(Object obj) - { - return obj instanceof Pos3D && - ((Pos3D)obj).xPos == xPos && - ((Pos3D)obj).yPos == yPos && - ((Pos3D)obj).zPos == zPos; - } - - @Override - public int hashCode() - { - int code = 1; - code = 31 * code + new Double(xPos).hashCode(); - code = 31 * code + new Double(yPos).hashCode(); - code = 31 * code + new Double(zPos).hashCode(); - return code; - } -} diff --git a/src/api/java/mekanism/api/Range4D.java b/src/api/java/mekanism/api/Range4D.java deleted file mode 100644 index 40905a66d..000000000 --- a/src/api/java/mekanism/api/Range4D.java +++ /dev/null @@ -1,114 +0,0 @@ -package mekanism.api; - -import net.minecraft.entity.player.EntityPlayer; -import cpw.mods.fml.common.FMLCommonHandler; - -public class Range4D -{ - public int dimensionId; - - public int xMin; - public int yMin; - public int zMin; - public int xMax; - public int yMax; - public int zMax; - - public Range4D(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int dimension) - { - xMin = minX; - yMin = minY; - zMin = minZ; - xMax = maxX; - yMax = maxY; - zMax = maxZ; - - dimensionId = dimension; - } - - public Range4D(Chunk3D chunk) - { - xMin = chunk.xCoord*16; - yMin = 0; - zMin = chunk.zCoord*16; - xMax = xMin+16; - yMax = 255; - zMax = zMin+16; - - dimensionId = chunk.dimensionId; - } - - public Range4D(Coord4D coord) - { - xMin = coord.xCoord; - yMin = coord.yCoord; - zMin = coord.zCoord; - - xMax = coord.xCoord+1; - yMax = coord.yCoord+1; - zMax = coord.zCoord+1; - - dimensionId = coord.dimensionId; - } - - public static Range4D getChunkRange(EntityPlayer player) - { - int radius = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().getViewDistance(); - - return new Range4D(new Chunk3D(player)).expandChunks(radius); - } - - public Range4D expandChunks(int chunks) - { - xMin -= chunks*16; - xMax += chunks*16; - zMin -= chunks*16; - zMax += chunks*16; - - return this; - } - - public boolean intersects(Range4D range) - { - return (xMax+1 - 1.E-05D > range.xMin) && (range.xMax+1 - 1.E-05D > xMin) && (yMax+1 - 1.E-05D > range.yMin) && (range.yMax+1 - 1.E-05D > yMin) && (zMax+1 - 1.E-05D > range.zMin) && (range.zMax+1 - 1.E-05D > zMin); - } - - @Override - public Range4D clone() - { - return new Range4D(xMin, yMin, zMin, xMax, yMax, zMax, dimensionId); - } - - @Override - public String toString() - { - return "[Range4D: " + xMin + ", " + yMin + ", " + zMin + ", " + xMax + ", " + yMax + ", " + zMax + ", dim=" + dimensionId + "]"; - } - - @Override - public boolean equals(Object obj) - { - return obj instanceof Range4D && - ((Range4D)obj).xMin == xMin && - ((Range4D)obj).yMin == yMin && - ((Range4D)obj).zMin == zMin && - ((Range4D)obj).xMax == xMax && - ((Range4D)obj).yMax == yMax && - ((Range4D)obj).zMax == zMax && - ((Range4D)obj).dimensionId == dimensionId; - } - - @Override - public int hashCode() - { - int code = 1; - code = 31 * code + xMin; - code = 31 * code + yMin; - code = 31 * code + zMin; - code = 31 * code + xMax; - code = 31 * code + yMax; - code = 31 * code + zMax; - code = 31 * code + dimensionId; - return code; - } -} diff --git a/src/api/java/mekanism/api/TabProxy.java b/src/api/java/mekanism/api/TabProxy.java deleted file mode 100644 index c562c0247..000000000 --- a/src/api/java/mekanism/api/TabProxy.java +++ /dev/null @@ -1,42 +0,0 @@ -package mekanism.api; - -import net.minecraft.creativetab.CreativeTabs; - -/** - * Class used to indirectly reference the Mekanism creative tab. - * @author AidanBrady - * - */ -public final class TabProxy -{ - /** The 'Mekanism' class where the tab instance is stored. */ - public static Class Mekanism; - - /** - * Attempts to get the Mekanism creative tab instance from the 'Mekanism' class. Will return - * the tab if the mod is loaded, but otherwise will return the defined 'preferred' creative tab. This way - * you don't need to worry about NPEs! - * @return Mekanism creative tab if can, otherwise preferred tab - */ - public static CreativeTabs tabMekanism(CreativeTabs preferred) - { - try { - if(Mekanism == null) - { - Mekanism = Class.forName("mekanism.common.Mekanism"); - } - - Object ret = Mekanism.getField("tabMekanism").get(null); - - if(ret instanceof CreativeTabs) - { - return (CreativeTabs)ret; - } - - return preferred; - } catch(Exception e) { - System.err.println("Error retrieving Mekanism creative tab."); - return preferred; - } - } -} diff --git a/src/api/java/mekanism/api/energy/EnergizedItemManager.java b/src/api/java/mekanism/api/energy/EnergizedItemManager.java deleted file mode 100644 index 165bdf608..000000000 --- a/src/api/java/mekanism/api/energy/EnergizedItemManager.java +++ /dev/null @@ -1,60 +0,0 @@ -package mekanism.api.energy; - -import net.minecraft.item.ItemStack; - -public class EnergizedItemManager -{ - /** - * Discharges an IEnergizedItem with the defined amount of energy. - * @param itemStack - ItemStack to discharge - * @param amount - amount of energy to discharge from the item, usually the total amount of energy needed in a TileEntity - * @return amount of energy discharged - */ - public static double discharge(ItemStack itemStack, double amount) - { - if(itemStack != null) - { - if(itemStack.getItem() instanceof IEnergizedItem) - { - IEnergizedItem energizedItem = (IEnergizedItem)itemStack.getItem(); - - if(energizedItem.canSend(itemStack)) - { - double energyToUse = Math.min(energizedItem.getMaxTransfer(itemStack), Math.min(energizedItem.getEnergy(itemStack), amount)); - energizedItem.setEnergy(itemStack, energizedItem.getEnergy(itemStack) - energyToUse); - - return energyToUse; - } - } - } - - return 0; - } - - /** - * Charges an IEnergizedItem with the defined amount of energy. - * @param itemStack - ItemStack to charge - * @param amount - amount of energy to charge the item with, usually the total amount of energy stored in a TileEntity - * @return amount of energy charged - */ - public static double charge(ItemStack itemStack, double amount) - { - if(itemStack != null) - { - if(itemStack.getItem() instanceof IEnergizedItem) - { - IEnergizedItem energizedItem = (IEnergizedItem)itemStack.getItem(); - - if(energizedItem.canReceive(itemStack)) - { - double energyToSend = Math.min(energizedItem.getMaxTransfer(itemStack), Math.min(energizedItem.getMaxEnergy(itemStack) - energizedItem.getEnergy(itemStack), amount)); - energizedItem.setEnergy(itemStack, energizedItem.getEnergy(itemStack) + energyToSend); - - return energyToSend; - } - } - } - - return 0; - } -} diff --git a/src/api/java/mekanism/api/energy/EnergyStack.java b/src/api/java/mekanism/api/energy/EnergyStack.java deleted file mode 100644 index 3f5762186..000000000 --- a/src/api/java/mekanism/api/energy/EnergyStack.java +++ /dev/null @@ -1,14 +0,0 @@ -package mekanism.api.energy; - -/** - * Created by ben on 27/03/15. - */ -public class EnergyStack -{ - public double amount; - - public EnergyStack(double newAmount) - { - amount = newAmount; - } -} diff --git a/src/api/java/mekanism/api/energy/ICableOutputter.java b/src/api/java/mekanism/api/energy/ICableOutputter.java deleted file mode 100644 index 015379c03..000000000 --- a/src/api/java/mekanism/api/energy/ICableOutputter.java +++ /dev/null @@ -1,18 +0,0 @@ -package mekanism.api.energy; - -import net.minecraftforge.common.util.ForgeDirection; - -/** - * Implement this if your TileEntity is capable of outputting energy to cables, overriding Mekanism's default implementation. - * @author AidanBrady - * - */ -public interface ICableOutputter -{ - /** - * Whether or not this block can output to a cable on a specific side. - * @param side - side to check - * @return if the block can output - */ - public boolean canOutputTo(ForgeDirection side); -} diff --git a/src/api/java/mekanism/api/energy/IEnergizedItem.java b/src/api/java/mekanism/api/energy/IEnergizedItem.java deleted file mode 100644 index b67254597..000000000 --- a/src/api/java/mekanism/api/energy/IEnergizedItem.java +++ /dev/null @@ -1,59 +0,0 @@ -package mekanism.api.energy; - -import net.minecraft.item.ItemStack; - -/** - * Implement this in an item's class if it should be able to store electricity. - * @author aidancbrady - * - */ -public interface IEnergizedItem -{ - /** - * Gets and returns the amount of energy stored in this item. - * @param itemStack - the ItemStack to check - * @return energy stored - */ - public double getEnergy(ItemStack itemStack); - - /** - * Sets this item's stored energy value to a new amount. - * @param itemStack - the ItemStack who's energy value is to be change - * @param amount - new amount of energy - */ - public void setEnergy(ItemStack itemStack, double amount); - - /** - * Gets and returns this item's maximum amount of energy that can be stored. - * @param itemStack - the ItemStack to check - * @return maximum energy - */ - public double getMaxEnergy(ItemStack itemStack); - - /** - * Gets and returns how much energy this item can transfer to and from charging slots. - * @param itemStack - the ItemStack to check - * @return transfer amount - */ - public double getMaxTransfer(ItemStack itemStack); - - /** - * Gets and returns whether or not this item can receive energy from a charging slot. - * @param itemStack - the ItemStack to check - * @return if the item can receive energy - */ - public boolean canReceive(ItemStack itemStack); - - /** - * Gets and returns whether or not this item can send energy to a charging slot. - * @param itemStack - the ItemStack to check - * @return if the item can send energy - */ - public boolean canSend(ItemStack itemStack); - - /** - * Returns whether or not this item contains metadata-specific subtypes instead of using metadata for damage display. - * @return if the item contains metadata-specific subtypes - */ - public boolean isMetadataSpecific(ItemStack itemStack); -} diff --git a/src/api/java/mekanism/api/energy/IStrictEnergyAcceptor.java b/src/api/java/mekanism/api/energy/IStrictEnergyAcceptor.java deleted file mode 100644 index 53edc68e6..000000000 --- a/src/api/java/mekanism/api/energy/IStrictEnergyAcceptor.java +++ /dev/null @@ -1,25 +0,0 @@ -package mekanism.api.energy; - -import net.minecraftforge.common.util.ForgeDirection; - -/** - * Implement this if your TileEntity can accept energy at a floating-point double value from Universal Cables. - * @author AidanBrady - * - */ -public interface IStrictEnergyAcceptor extends IStrictEnergyStorage -{ - /** - * Transfer a certain amount of energy to this acceptor. - * @param amount - amount to transfer - * @return energy used - */ - public double transferEnergyToAcceptor(ForgeDirection side, double amount); - - /** - * Whether or not this tile entity accepts energy from a certain side. - * @param side - side to check - * @return if tile entity accepts energy - */ - public boolean canReceiveEnergy(ForgeDirection side); -} diff --git a/src/api/java/mekanism/api/energy/IStrictEnergyStorage.java b/src/api/java/mekanism/api/energy/IStrictEnergyStorage.java deleted file mode 100644 index fd560fa18..000000000 --- a/src/api/java/mekanism/api/energy/IStrictEnergyStorage.java +++ /dev/null @@ -1,27 +0,0 @@ -package mekanism.api.energy; - -/** - * Mekanism-specific energy storage for TileEntities, already implemented in IStrictEnergyAcceptor. - * @author aidancbrady - * - */ -public interface IStrictEnergyStorage -{ - /** - * Gets the amount of energy this TileEntity is currently storing. - * @return stored energy - */ - public double getEnergy(); - - /** - * Sets the amount of stored energy of this TileEntity to a new amount. - * @param energy - new energy value - */ - public void setEnergy(double energy); - - /** - * Gets the maximum amount of energy this TileEntity can store. - * @return maximum energy - */ - public double getMaxEnergy(); -} diff --git a/src/api/java/mekanism/api/energy/package-info.java b/src/api/java/mekanism/api/energy/package-info.java deleted file mode 100644 index 8f3d3716e..000000000 --- a/src/api/java/mekanism/api/energy/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|energy") -package mekanism.api.energy; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/mekanism/api/gas/Gas.java b/src/api/java/mekanism/api/gas/Gas.java deleted file mode 100644 index f05be52c6..000000000 --- a/src/api/java/mekanism/api/gas/Gas.java +++ /dev/null @@ -1,221 +0,0 @@ -package mekanism.api.gas; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.IIcon; -import net.minecraft.util.StatCollector; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; - -/** - * Gas - a class used to set specific properties of gasses when used or seen in-game. - * @author aidancbrady - * - */ -public class Gas -{ - private String name; - - private String unlocalizedName; - - private Fluid fluid; - - private IIcon icon; - - private boolean visible = true; - - private boolean from_fluid = false; - - /** - * Creates a new Gas object with a defined name or key value. - * @param s - name or key to associate this Gas with - */ - public Gas(String s) - { - unlocalizedName = name = s; - } - - /** - * Creates a new Gas object that corresponds to the given Fluid - */ - public Gas(Fluid f) - { - unlocalizedName = name = f.getName(); - icon = f.getStillIcon(); - fluid = f; - from_fluid = true; - } - - /** - * Gets the name (key) of this Gas. This is NOT a translated or localized display name. - * @return this Gas's name or key - */ - public String getName() - { - return name; - } - - /** - * Whether or not this is a visible gas. - * @return if this gas is visible - */ - public boolean isVisible() - { - return visible; - } - - /** - * Sets this gas's "visible" state to a new value. Setting it to 'false' will treat this gas as an internal gas, and it will not be displayed or accessed by other mods. - * @param v - new visible state - * @return this Gas object - */ - public Gas setVisible(boolean v) - { - visible = v; - - return this; - } - - /** - * Gets the unlocalized name of this Gas. - * @return this Gas's unlocalized name - */ - public String getUnlocalizedName() - { - return "gas." + unlocalizedName; - } - - /** - * Translates this Gas's unlocalized name and returns it as localized. - * @return this Gas's localized name - */ - public String getLocalizedName() - { - return StatCollector.translateToLocal(getUnlocalizedName()); - } - - /** - * Sets the unlocalized name of this Gas. - * @param s - unlocalized name to set - * @return this Gas object - */ - public Gas setUnlocalizedName(String s) - { - unlocalizedName = s; - - return this; - } - - /** - * Gets the IIcon associated with this Gas. - * @return associated IIcon - */ - public IIcon getIcon() - { - if(from_fluid) - { - return this.getFluid().getIcon(); - } - - return icon; - } - - /** - * Sets this gas's icon. - * @param i - IIcon to associate with this Gas - * @return this Gas object - */ - public Gas setIcon(IIcon i) - { - icon = i; - - if(hasFluid()) - { - fluid.setIcons(getIcon()); - } - - from_fluid = false; - - return this; - } - - /** - * Gets the ID associated with this gas. - * @return the associated gas ID - */ - public int getID() - { - return GasRegistry.getGasID(this); - } - - /** - * Writes this Gas to a defined tag compound. - * @param nbtTags - tag compound to write this Gas to - * @return the tag compound this gas was written to - */ - public NBTTagCompound write(NBTTagCompound nbtTags) - { - nbtTags.setString("gasName", getName()); - - return nbtTags; - } - - /** - * Returns the Gas stored in the defined tag compound. - * @param nbtTags - tag compound to get the Gas from - * @return Gas stored in the tag compound - */ - public static Gas readFromNBT(NBTTagCompound nbtTags) - { - if(nbtTags == null || nbtTags.hasNoTags()) - { - return null; - } - - return GasRegistry.getGas(nbtTags.getString("gasName")); - } - - /** - * Whether or not this Gas has an associated fluid. - * @return if this gas has a fluid - */ - public boolean hasFluid() - { - return fluid != null; - } - - /** - * Gets the fluid associated with this Gas. - * @return fluid associated with this gas - */ - public Fluid getFluid() - { - return fluid; - } - - /** - * Registers a new fluid out of this Gas or gets one from the FluidRegistry. - * @return this Gas object - */ - public Gas registerFluid() - { - if(fluid == null) - { - if(FluidRegistry.getFluid(getName()) == null) - { - fluid = new Fluid(getName()).setGaseous(true); - FluidRegistry.registerFluid(fluid); - } - else { - fluid = FluidRegistry.getFluid(getName()); - } - } - - return this; - } - - @Override - public String toString() - { - return name; - } -} diff --git a/src/api/java/mekanism/api/gas/GasRegistry.java b/src/api/java/mekanism/api/gas/GasRegistry.java deleted file mode 100644 index 25db9667e..000000000 --- a/src/api/java/mekanism/api/gas/GasRegistry.java +++ /dev/null @@ -1,113 +0,0 @@ -package mekanism.api.gas; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraftforge.fluids.Fluid; - -public class GasRegistry -{ - private static ArrayList registeredGasses = new ArrayList(); - - /** - * Register a new gas into GasRegistry. - * @param gas - Gas to register - * @return the gas that has been registered, pulled right out of GasRegistry - */ - public static Gas register(Gas gas) - { - if(gas == null) - { - return null; - } - - registeredGasses.add(gas); - - return getGas(gas.getName()); - } - - /** - * Gets the gas associated with the defined ID. - * @param id - ID to check - * @return gas associated with defined ID - */ - public static Gas getGas(int id) - { - if(id == -1) - { - return null; - } - - return registeredGasses.get(id); - } - - /** - * Gets the gas associated with the defined fluid. - * @param f - fluid to check - * @return the gas associated with the fluid - */ - public static Gas getGas(Fluid f) - { - for(Gas gas : getRegisteredGasses()) - { - if(gas.hasFluid() && gas.getFluid() == f) - { - return gas; - } - } - - return null; - } - - /** - * Whether or not GasRegistry contains a gas with the specified name - * @param name - name to check - * @return if GasRegistry contains a gas with the defined name - */ - public static boolean containsGas(String name) - { - return getGas(name) != null; - } - - /** - * Gets the list of all gasses registered in GasRegistry. - * @return a cloned list of all registered gasses - */ - public static List getRegisteredGasses() - { - return (List)registeredGasses.clone(); - } - - /** - * Gets the gas associated with the specified name. - * @param name - name of the gas to get - * @return gas associated with the name - */ - public static Gas getGas(String name) - { - for(Gas gas : registeredGasses) - { - if(gas.getName().toLowerCase().equals(name.toLowerCase())) - { - return gas; - } - } - - return null; - } - - /** - * Gets the gas ID of a specified gas. - * @param gas - gas to get the ID from - * @return gas ID - */ - public static int getGasID(Gas gas) - { - if(gas == null || !containsGas(gas.getName())) - { - return -1; - } - - return registeredGasses.indexOf(gas); - } -} diff --git a/src/api/java/mekanism/api/gas/GasStack.java b/src/api/java/mekanism/api/gas/GasStack.java deleted file mode 100644 index 05e5ae689..000000000 --- a/src/api/java/mekanism/api/gas/GasStack.java +++ /dev/null @@ -1,132 +0,0 @@ -package mekanism.api.gas; - -import net.minecraft.nbt.NBTTagCompound; - -/** - * GasStack - a specified amount of a defined Gas with certain properties. - * @author aidancbrady - * - */ -public class GasStack -{ - private Gas type; - - public int amount; - - /** - * Creates a new GasStack with a defined gas ID and quantity. - * @param id - gas ID to associate this GasStack to, will perform a GasRegistry lookup in the constructor - * @param quantity - amount of gas to be referenced in this GasStack - */ - public GasStack(int id, int quantity) - { - type = GasRegistry.getGas(id); - amount = quantity; - } - - /** - * Creates a new GasStack with a defined Gas type and quantity. - * @param gas - gas type of the stack - * @param quantity - amount of gas to be referenced in this GasStack - */ - public GasStack(Gas gas, int quantity) - { - type = gas; - amount = quantity; - } - - private GasStack() {} - - /** - * Gets the Gas type of this GasStack. - * @return this GasStack's Gas type - */ - public Gas getGas() - { - return type; - } - - public GasStack withAmount(int newAmount) - { - amount = newAmount; - - return this; - } - - /** - * Writes this GasStack to a defined tag compound. - * @param nbtTags - tag compound to write to - * @return tag compound with this GasStack's data - */ - public NBTTagCompound write(NBTTagCompound nbtTags) - { - type.write(nbtTags); - nbtTags.setInteger("amount", amount); - - return nbtTags; - } - - /** - * Reads this GasStack's data from a defined tag compound. - * @param nbtTags - tag compound to read from - */ - public void read(NBTTagCompound nbtTags) - { - type = Gas.readFromNBT(nbtTags); - amount = nbtTags.getInteger("amount"); - } - - /** - * Returns the GasStack stored in the defined tag compound, or null if it doesn't exist. - * @param nbtTags - tag compound to read from - * @return GasStack stored in the tag compound - */ - public static GasStack readFromNBT(NBTTagCompound nbtTags) - { - if(nbtTags == null || nbtTags.hasNoTags()) - { - return null; - } - - GasStack stack = new GasStack(); - stack.read(nbtTags); - - if(stack.getGas() == null || stack.amount <= 0) - { - return null; - } - - return stack; - } - - /** - * Returns a copied form of this GasStack. - * @return copied GasStack - */ - public GasStack copy() - { - return new GasStack(type, amount); - } - - /** - * Whether or not this GasStack's gas type is equal to the other defined GasStack. - * @param stack - GasStack to check - * @return if the GasStacks contain the same gas type - */ - public boolean isGasEqual(GasStack stack) - { - return stack != null && getGas() == stack.getGas(); - } - - @Override - public String toString() - { - return "[" + type + ", " + amount + "]"; - } - - @Override - public int hashCode() - { - return type == null ? 0 : type.getID(); - } -} diff --git a/src/api/java/mekanism/api/gas/GasTank.java b/src/api/java/mekanism/api/gas/GasTank.java deleted file mode 100644 index a5d4c20b3..000000000 --- a/src/api/java/mekanism/api/gas/GasTank.java +++ /dev/null @@ -1,252 +0,0 @@ -package mekanism.api.gas; - -import net.minecraft.nbt.NBTTagCompound; - -/** - * An optional way of managing and/or storing gasses. Would be very useful in TileEntity and Entity gas storage. - * @author aidancbrady - * - */ -public class GasTank -{ - public GasStack stored; - - private int maxGas; - - private GasTank() {} - - /** - * Creates a tank with a defined capacity. - * @param max - the maximum amount of gas this GasTank can hold - */ - public GasTank(int max) - { - maxGas = max; - } - - /** - * Sets this tank's GasStack value to a new value. Will cap the amount to this GasTank's capacity. - * @param stack - value to set this tank's GasStack value to - */ - public void setGas(GasStack stack) - { - stored = stack; - - if(stored != null) - { - stored.amount = Math.min(getMaxGas(), stored.amount); - } - } - - /** - * Draws a specified amount of gas out of this tank. - * @param amount - amount to draw - * @param doDraw - if the gas should actually be removed from this tank - * @return gas taken from this GasTank as a GasStack value - */ - public GasStack draw(int amount, boolean doDraw) - { - if(stored == null || amount <= 0) - { - return null; - } - - GasStack ret = new GasStack(getGas().getGas(), Math.min(getStored(), amount)); - - if(ret.amount > 0) - { - if(doDraw) - { - stored.amount -= ret.amount; - - if(stored.amount <= 0) - { - stored = null; - } - } - - return ret; - } - - return null; - } - - /** - * Adds a specified amount of gas to this tank. - * @param amount - the GasStack for this tank to receive - * @param doReceive - if the gas should actually be added to this tank - * @return the amount of gas accepted by this tank - */ - public int receive(GasStack amount, boolean doReceive) - { - if(amount == null || (stored != null && !(stored.amount != getMaxGas() && stored.isGasEqual(amount)))) - { - return 0; - } - - int toFill = Math.min(getMaxGas()-getStored(), amount.amount); - - if(doReceive) - { - if(stored == null) - { - stored = amount.copy().withAmount(getStored()+toFill); - } - else { - stored.amount = Math.min(getMaxGas(), getStored()+amount.amount); - } - } - - return toFill; - } - - /** - * If this GasTank can receive the specified type of gas. Will return false if this tank does not need anymore gas. - * @param gas - gas to check - * @return if this GasTank can accept the defined gas - */ - public boolean canReceive(Gas gas) - { - if(getNeeded() == 0 || stored != null && (gas != null && gas != stored.getGas())) - { - return false; - } - - return true; - } - - /** - * If this GasTank can receive the specified type of gas. Will return TRUE if this tank does not need anymore gas. - * @param gas - gas to check - * @return if this GasTank can accept the defined gas - */ - public boolean canReceiveType(Gas gas) - { - if(stored != null && (gas != null && gas != stored.getGas())) - { - return false; - } - - return true; - } - - /** - * If this GasTank can be drawn of the specified type of gas. Will return false if this tank does not contain any gas. - * @param gas - gas to check - * @return if this GasTank can be drawn of the defined gas - */ - public boolean canDraw(Gas gas) - { - if(stored == null || (gas != null && gas != stored.getGas())) - { - return false; - } - - return true; - } - - /** - * Gets the amount of gas needed by this GasTank. - * @return - */ - public int getNeeded() - { - return getMaxGas()-getStored(); - } - - /** - * Gets the maximum amount of gas this tank can hold. - * @return - max gas - */ - public int getMaxGas() - { - return maxGas; - } - - /** - * Sets the maximum amount of gas this tank can hold - */ - public void setMaxGas(int capacity) - { - maxGas = capacity; - } - - /** - * Gets the GasStack held by this GasTank. - * @return - GasStakc held by this tank - */ - public GasStack getGas() - { - return stored; - } - - /** - * Gets the type of gas currently stored in this GasTank. - * @return gas type contained - */ - public Gas getGasType() - { - return stored != null ? stored.getGas() : null; - } - - /** - * Gets the amount of gas stored by this GasTank. - * @return amount of gas stored - */ - public int getStored() - { - return stored != null ? stored.amount : 0; - } - - /** - * Writes this tank to a defined tag compound. - * @param nbtTags - tag compound to write to - * @return tag compound with this tank's data - */ - public NBTTagCompound write(NBTTagCompound nbtTags) - { - if(stored != null && stored.getGas() != null) - { - nbtTags.setTag("stored", stored.write(new NBTTagCompound())); - } - - nbtTags.setInteger("maxGas", maxGas); - - return nbtTags; - } - - /** - * Reads this tank's data from a defined tag compound. - * @param nbtTags - tag compound to read from - */ - public void read(NBTTagCompound nbtTags) - { - if(nbtTags.hasKey("stored")) - { - stored = GasStack.readFromNBT(nbtTags.getCompoundTag("stored")); - } - - if(nbtTags.hasKey("maxGas") && nbtTags.getInteger("maxGas") != 0) - { - maxGas = nbtTags.getInteger("maxGas"); - } - } - - /** - * Returns the tank stored in the defined tag compound, or null if it doesn't exist. - * @param nbtTags - tag compound to read from - * @return tank stored in the tag compound - */ - public static GasTank readFromNBT(NBTTagCompound nbtTags) - { - if(nbtTags == null || nbtTags.hasNoTags()) - { - return null; - } - - GasTank tank = new GasTank(); - tank.read(nbtTags); - - return tank; - } -} diff --git a/src/api/java/mekanism/api/gas/IGasHandler.java b/src/api/java/mekanism/api/gas/IGasHandler.java deleted file mode 100644 index e06952317..000000000 --- a/src/api/java/mekanism/api/gas/IGasHandler.java +++ /dev/null @@ -1,47 +0,0 @@ -package mekanism.api.gas; - -import net.minecraftforge.common.util.ForgeDirection; - -/** - * Implement this if your tile entity accepts gas from an external source. - * @author AidanBrady - * - */ -public interface IGasHandler -{ - /** - * Transfer a certain amount of gas to this block. - * @param stack - gas to add - * @return gas added - */ - public int receiveGas(ForgeDirection side, GasStack stack, boolean doTransfer); - - @Deprecated - public int receiveGas(ForgeDirection side, GasStack stack); - - /** - * Draws a certain amount of gas from this block. - * @param amount - amount to draw - * @return gas drawn - */ - public GasStack drawGas(ForgeDirection side, int amount, boolean doTransfer); - - @Deprecated - public GasStack drawGas(ForgeDirection side, int amount); - - /** - * Whether or not this block can accept gas from a certain side. - * @param side - side to check - * @param type - type of gas to check - * @return if block accepts gas - */ - public boolean canReceiveGas(ForgeDirection side, Gas type); - - /** - * Whether or not this block can be drawn of gas from a certain side. - * @param side - side to check - * @param type - type of gas to check - * @return if block can be drawn of gas - */ - public boolean canDrawGas(ForgeDirection side, Gas type); -} diff --git a/src/api/java/mekanism/api/gas/IGasItem.java b/src/api/java/mekanism/api/gas/IGasItem.java deleted file mode 100644 index 9c7d33230..000000000 --- a/src/api/java/mekanism/api/gas/IGasItem.java +++ /dev/null @@ -1,81 +0,0 @@ -package mekanism.api.gas; - -import net.minecraft.item.ItemStack; - -/** - * Implement this in your item class if it can store or transfer certain gasses. - * @author AidanBrady - * - */ -public interface IGasItem -{ - /** - * Gets the rate of transfer this item can handle. - * @return - */ - public int getRate(ItemStack itemstack); - - /** - * Adds a defined amount of a certain gas to an item. - * @param itemstack - the itemstack to add gas to - * @param type - the type of gas to add - * @param amount - the amount of gas to add - * @return the gas that was accepted by the item - */ - public int addGas(ItemStack itemstack, GasStack stack); - - /** - * Removes the defined amount of a certain gas from the item. - * @param itemstack - the itemstack to remove gas from - * @param type - the type of gas to remove - * @param amount - the amount of gas to remove - * @return the gas that was removed by the item - */ - public GasStack removeGas(ItemStack itemstack, int amount); - - /** - * Whether or not this storage tank be given a specific gas. - * @param itemstack - the itemstack to check - * @param type - the type of gas the tank can possibly receive - * @return if the item be charged - */ - public boolean canReceiveGas(ItemStack itemstack, Gas type); - - /** - * Whether or not this item can give a gas receiver a certain type of gas. - * @param itemstack - the itemstack to check - * @param type - the type of gas the tank can provide - * @return if the item can provide gas - */ - public boolean canProvideGas(ItemStack itemstack, Gas type); - - /** - * Get the gas of a declared type. - * @param type - type of gas - * @param data - ItemStack parameter if necessary - * @return gas stored - */ - public GasStack getGas(ItemStack itemstack); - - /** - * Set the gas of a declared type to a new amount; - * @param type - type of gas - * @param data - ItemStack parameter if necessary - * @param amount - amount to store - */ - public void setGas(ItemStack itemstack, GasStack stack); - - /** - * Gets the maximum amount of gas this tile entity can store. - * @param type - type of gas - * @param data - ItemStack parameter if necessary - * @return maximum gas - */ - public int getMaxGas(ItemStack itemstack); - - /** - * Returns whether or not this item contains metadata-specific subtypes instead of using metadata for damage display. - * @return if the item contains metadata-specific subtypes - */ - public boolean isMetadataSpecific(ItemStack itemstack); -} diff --git a/src/api/java/mekanism/api/gas/ITubeConnection.java b/src/api/java/mekanism/api/gas/ITubeConnection.java deleted file mode 100644 index b669fedda..000000000 --- a/src/api/java/mekanism/api/gas/ITubeConnection.java +++ /dev/null @@ -1,18 +0,0 @@ -package mekanism.api.gas; - -import net.minecraftforge.common.util.ForgeDirection; - -/** - * Implement this if your block can connect to Pressurized Tubes. - * @author AidanBrady - * - */ -public interface ITubeConnection -{ - /** - * Whether or not a tube can connect to a certain orientation. - * @param side - orientation to check - * @return if a tube can connect - */ - public boolean canTubeConnect(ForgeDirection side); -} diff --git a/src/api/java/mekanism/api/gas/OreGas.java b/src/api/java/mekanism/api/gas/OreGas.java deleted file mode 100644 index 316169c2a..000000000 --- a/src/api/java/mekanism/api/gas/OreGas.java +++ /dev/null @@ -1,38 +0,0 @@ -package mekanism.api.gas; - -import net.minecraft.util.StatCollector; - -public class OreGas extends Gas -{ - private String oreName; - private OreGas cleanGas; - - public OreGas(String s, String name) - { - super(s); - - oreName = name; - } - - public boolean isClean() - { - return getCleanGas() == null; - } - - public OreGas getCleanGas() - { - return cleanGas; - } - - public OreGas setCleanGas(OreGas gas) - { - cleanGas = gas; - - return this; - } - - public String getOreName() - { - return StatCollector.translateToLocal(oreName); - } -} diff --git a/src/api/java/mekanism/api/gas/package-info.java b/src/api/java/mekanism/api/gas/package-info.java deleted file mode 100644 index 4418451ff..000000000 --- a/src/api/java/mekanism/api/gas/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|gas") -package mekanism.api.gas; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/mekanism/api/infuse/InfuseObject.java b/src/api/java/mekanism/api/infuse/InfuseObject.java deleted file mode 100644 index a86c02f1a..000000000 --- a/src/api/java/mekanism/api/infuse/InfuseObject.java +++ /dev/null @@ -1,21 +0,0 @@ -package mekanism.api.infuse; - -/** - * InfuseObject - an object associated with an ItemStack that can modify a Metallurgic Infuser's internal infuse. - * @author AidanBrady - * - */ -public class InfuseObject -{ - /** The type of infuse this item stores */ - public InfuseType type; - - /** How much infuse this item stores */ - public int stored; - - public InfuseObject(InfuseType infusion, int i) - { - type = infusion; - stored = i; - } -} diff --git a/src/api/java/mekanism/api/infuse/InfuseRegistry.java b/src/api/java/mekanism/api/infuse/InfuseRegistry.java deleted file mode 100644 index 308b9c5be..000000000 --- a/src/api/java/mekanism/api/infuse/InfuseRegistry.java +++ /dev/null @@ -1,113 +0,0 @@ -package mekanism.api.infuse; - -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.item.ItemStack; - -/** - * Use this class to add a new object that registers as an infuse object. - * @author AidanBrady - * - */ -public class InfuseRegistry -{ - /** The (private) map of ItemStacks and their related InfuseObjects. */ - private static Map infuseObjects = new HashMap(); - - /** The (private) map of infuse names and their corresponding InfuseTypes. */ - private static Map infuseTypes = new HashMap(); - - /** - * Registers an InfuseType into the registry. Call this in PreInit! - * @param infuse - */ - public static void registerInfuseType(InfuseType infuse) - { - if(infuseTypes.containsKey(infuse.name)) - { - return; - } - - infuseTypes.put(infuse.name, infuse); - } - - /** - * Gets an InfuseType from it's name, or null if it doesn't exist. - * @param name - the name of the InfuseType to get - * @return the name's corresponding InfuseType - */ - public static InfuseType get(String name) - { - if(name.equals("null")) - { - return null; - } - - return infuseTypes.get(name); - } - - /** - * Whether or not the registry contains a correspondent InfuseType to a name. - * @param name - the name to check - * @return if the name has a coorespondent InfuseType - */ - public static boolean contains(String name) - { - return get(name) != null; - } - - /** - * Registers a block or item that serves as an infuse object. An infuse object will store a certain type and amount of infuse, - * and will deliver this amount to the Metallurgic Infuser's buffer of infuse. The item's stack size will be decremented when - * it is placed in the Metallurgic Infuser's infuse slot, and the machine can accept the type and amount of infuse stored in the - * object. - * @param itemStack - stack the infuse object is linked to -- stack size is ignored - * @param infuseObject - the infuse object with the type and amount data - */ - public static void registerInfuseObject(ItemStack itemStack, InfuseObject infuseObject) - { - if(getObject(itemStack) != null) - { - return; - } - - infuseObjects.put(itemStack, infuseObject); - } - - /** - * Gets the InfuseObject data from an ItemStack. - * @param itemStack - the ItemStack to check - * @return the ItemStack's InfuseObject - */ - public static InfuseObject getObject(ItemStack itemStack) - { - for(Map.Entry obj : infuseObjects.entrySet()) - { - if(itemStack.isItemEqual(obj.getKey())) - { - return obj.getValue(); - } - } - - return null; - } - - /** - * Gets the private map for InfuseObjects. - * @return private InfuseObject map - */ - public static final Map getObjectMap() - { - return infuseObjects; - } - - /** - * Gets the private map for InfuseTypes. - * @return private InfuseType map - */ - public static final Map getInfuseMap() - { - return infuseTypes; - } -} diff --git a/src/api/java/mekanism/api/infuse/InfuseType.java b/src/api/java/mekanism/api/infuse/InfuseType.java deleted file mode 100644 index 1f5215cb7..000000000 --- a/src/api/java/mekanism/api/infuse/InfuseType.java +++ /dev/null @@ -1,47 +0,0 @@ -package mekanism.api.infuse; - -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; - -/** - * The types of infuse currently available in Mekanism. - * @author AidanBrady - * - */ -public final class InfuseType -{ - /** The name of this infusion */ - public String name; - - /** The location of this infuse's GUI texture */ - public ResourceLocation texture; - - /** The infuse's GUI texture X offset. */ - public int texX; - - /** The infuse's GUI texture Y offset. */ - public int texY; - - /** The unlocalized name of this type. */ - public String unlocalizedName; - - public InfuseType(String s, ResourceLocation location, int x, int y) - { - name = s; - texture = location; - texX = x; - texY = y; - } - - public InfuseType setUnlocalizedName(String name) - { - unlocalizedName = name; - - return this; - } - - public String getLocalizedName() - { - return StatCollector.translateToLocal(unlocalizedName); - } -} diff --git a/src/api/java/mekanism/api/infuse/package-info.java b/src/api/java/mekanism/api/infuse/package-info.java deleted file mode 100644 index 871899688..000000000 --- a/src/api/java/mekanism/api/infuse/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|infuse") -package mekanism.api.infuse; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/mekanism/api/lasers/ILaserReceptor.java b/src/api/java/mekanism/api/lasers/ILaserReceptor.java deleted file mode 100644 index 641f3ca0c..000000000 --- a/src/api/java/mekanism/api/lasers/ILaserReceptor.java +++ /dev/null @@ -1,10 +0,0 @@ -package mekanism.api.lasers; - -import net.minecraftforge.common.util.ForgeDirection; - -public interface ILaserReceptor -{ - public void receiveLaserEnergy(double energy, ForgeDirection side); - - public boolean canLasersDig(); -} diff --git a/src/api/java/mekanism/api/lasers/package-info.java b/src/api/java/mekanism/api/lasers/package-info.java deleted file mode 100644 index b45693745..000000000 --- a/src/api/java/mekanism/api/lasers/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|laser") -package mekanism.api.lasers; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/mekanism/api/package-info.java b/src/api/java/mekanism/api/package-info.java deleted file mode 100644 index 2b9fcabca..000000000 --- a/src/api/java/mekanism/api/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|core") -package mekanism.api; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/mekanism/api/reactor/IFusionReactor.java b/src/api/java/mekanism/api/reactor/IFusionReactor.java deleted file mode 100644 index 9d9d96de9..000000000 --- a/src/api/java/mekanism/api/reactor/IFusionReactor.java +++ /dev/null @@ -1,66 +0,0 @@ -package mekanism.api.reactor; - -import mekanism.api.IHeatTransfer; -import mekanism.api.gas.GasTank; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidTank; - -public interface IFusionReactor extends IHeatTransfer -{ - public void addTemperatureFromEnergyInput(double energyAdded); - - public void simulate(); - - public FluidTank getWaterTank(); - - public FluidTank getSteamTank(); - - public GasTank getDeuteriumTank(); - - public GasTank getTritiumTank(); - - public GasTank getFuelTank(); - - public double getBufferedEnergy(); - - public void setBufferedEnergy(double energy); - - public double getPlasmaTemp(); - - public void setPlasmaTemp(double temp); - - public double getCaseTemp(); - - public void setCaseTemp(double temp); - - public double getBufferSize(); - - public void formMultiblock(); - - public boolean isFormed(); - - public void setInjectionRate(int rate); - - public int getInjectionRate(); - - public boolean isBurning(); - - public void setBurning(boolean burn); - - public int getMinInjectionRate(boolean active); - - public double getMaxPlasmaTemperature(boolean active); - - public double getMaxCasingTemperature(boolean active); - - public double getIgnitionTemperature(boolean active); - - public double getPassiveGeneration(boolean active, boolean current); - - public int getSteamPerTick(boolean current); - - public void updateTemperatures(); - - public ItemStack[] getInventory(); -} diff --git a/src/api/java/mekanism/api/reactor/INeutronCapture.java b/src/api/java/mekanism/api/reactor/INeutronCapture.java deleted file mode 100644 index 6171a7f74..000000000 --- a/src/api/java/mekanism/api/reactor/INeutronCapture.java +++ /dev/null @@ -1,6 +0,0 @@ -package mekanism.api.reactor; - -public interface INeutronCapture extends IReactorBlock -{ - public int absorbNeutrons(int neutrons); -} diff --git a/src/api/java/mekanism/api/reactor/IReactorBlock.java b/src/api/java/mekanism/api/reactor/IReactorBlock.java deleted file mode 100644 index b3b85188d..000000000 --- a/src/api/java/mekanism/api/reactor/IReactorBlock.java +++ /dev/null @@ -1,12 +0,0 @@ -package mekanism.api.reactor; - - -public interface IReactorBlock -{ - public boolean isFrame(); - - public void setReactor(IFusionReactor reactor); - - public IFusionReactor getReactor(); - -} diff --git a/src/api/java/mekanism/api/reactor/package-info.java b/src/api/java/mekanism/api/reactor/package-info.java deleted file mode 100644 index 6a00fc693..000000000 --- a/src/api/java/mekanism/api/reactor/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|reactor") -package mekanism.api.reactor; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/mekanism/api/recipe/RecipeHelper.java b/src/api/java/mekanism/api/recipe/RecipeHelper.java deleted file mode 100644 index 1040aa2c9..000000000 --- a/src/api/java/mekanism/api/recipe/RecipeHelper.java +++ /dev/null @@ -1,319 +0,0 @@ -package mekanism.api.recipe; - -import java.lang.reflect.Method; - -import mekanism.api.gas.GasStack; -import mekanism.api.infuse.InfuseType; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.FluidStack; - -/** - * SET TO BE REMOVED NEXT MINOR MEKANISM VERSION, PLEASE USE IMC INSTEAD. - * Use this handy class to add recipes to Mekanism machinery. - * @author AidanBrady - * - */ -@Deprecated -public final class RecipeHelper -{ - /** - * Add an Enrichment Chamber recipe. - * @param input - input ItemStack - * @param output - output ItemStack - */ - public static void addEnrichmentChamberRecipe(ItemStack input, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addEnrichmentChamberRecipe", ItemStack.class, ItemStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add an Osmium Compressor recipe. - * @param input - input ItemStack - * @param output - output ItemStack - */ - public static void addOsmiumCompressorRecipe(ItemStack input, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addOsmiumCompressorRecipe", ItemStack.class, ItemStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Combiner recipe. - * @param input - input ItemStack - * @param output - output ItemStack - */ - public static void addCombinerRecipe(ItemStack input, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addCombinerRecipe", ItemStack.class, ItemStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Crusher recipe. - * @param input - input ItemStack - * @param output - output ItemStack - */ - public static void addCrusherRecipe(ItemStack input, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addCrusherRecipe", ItemStack.class, ItemStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Purification Chamber recipe. - * @param input - input ItemStack - * @param output - output ItemStack - */ - public static void addPurificationChamberRecipe(ItemStack input, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addPurificationChamberRecipe", ItemStack.class, ItemStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Chemical Oxidizer recipe. - * @param input - input ItemStack - * @param output - output GasStack - */ - public static void addChemicalOxidizerRecipe(ItemStack input, GasStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addChemicalOxidizerRecipe", ItemStack.class, GasStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Chemical Infuser recipe. - * @param leftInput - left input GasStack - * @param rightInput - right input GasStack - * @param output - output GasStack - */ - public static void addChemicalInfuserRecipe(GasStack leftInput, GasStack rightInput, GasStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addChemicalInfuserRecipe", GasStack.class, GasStack.class, GasStack.class); - m.invoke(null, leftInput, rightInput, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Precision Sawmill recipe. - * @param input - input ItemStack - * @param primaryOutput - guaranteed output - * @param secondaryOutput - possible extra output - * @param chance - probability of obtaining extra output - */ - public static void addPrecisionSawmillRecipe(ItemStack input, ItemStack primaryOutput, ItemStack secondaryOutput, double chance) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addPrecisionSawmillRecipe", ItemStack.class, ItemStack.class, ItemStack.class, Double.TYPE); - m.invoke(null, input, primaryOutput, secondaryOutput, chance); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Precision Sawmill recipe with no chance output - * @param input - input ItemStack - * @param primaryOutput - guaranteed output - */ - public static void addPrecisionSawmillRecipe(ItemStack input, ItemStack primaryOutput) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addPrecisionSawmillRecipe", ItemStack.class, ItemStack.class); - m.invoke(null, input, primaryOutput); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Chemical Injection Chamber recipe. - * @param input - input AdvancedInput - * @param output - output ItemStack - */ - public static void addChemicalInjectionChamberRecipe(ItemStack input, String gasName, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addChemicalInjectionChamberRecipe", ItemStack.class, String.class, ItemStack.class); - m.invoke(null, input, gasName, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add an Electrolytic Separator recipe. - * @param input - input FluidStack - * @param energy - required energy - * @param leftOutput - left output GasStack - * @param rightOutput - right output GasStack - */ - public static void addElectrolyticSeparatorRecipe(FluidStack input, double energy, GasStack leftOutput, GasStack rightOutput) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addElectrolyticSeparatorRecipe", FluidStack.class, Double.TYPE, GasStack.class, GasStack.class); - m.invoke(null, input, energy, leftOutput, rightOutput); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Chemical Dissolution Chamber recipe. - * @param input - input ItemStack - * @param output - output GasStack - */ - public static void addChemicalDissolutionChamberRecipe(ItemStack input, GasStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addChemicalDissolutionChamberRecipe", ItemStack.class, GasStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Chemical Washer recipe. - * @param input - input GasStack - * @param output - output GasStack - */ - public static void addChemicalWasherRecipe(GasStack input, GasStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addChemicalWasherRecipe", GasStack.class, GasStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Chemical Crystallizer recipe. - * @param input - input GasStack - * @param output - output ItemStack - */ - public static void addChemicalCrystallizerRecipe(GasStack input, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addChemicalCrystallizerRecipe", GasStack.class, ItemStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Metallurgic Infuser recipe. - * @param infuse - which Infuse to use - * @param amount - how much Infuse to use - * @param input - input ItemStack - * @param output - output ItemStack - */ - public static void addMetallurgicInfuserRecipe(InfuseType infuse, int amount, ItemStack input, ItemStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addMetallurgicInfuserRecipe", InfuseType.class, Integer.TYPE, ItemStack.class, ItemStack.class); - m.invoke(null, infuse, amount, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Pressurized Reaction Chamber recipe. - * @param inputSolid - input ItemStack - * @param inputFluid - input FluidStack - * @param inputGas - input GasStack - * @param outputSolid - output ItemStack - * @param outputGas - output GasStack - * @param extraEnergy - extra energy needed by the recipe - * @param ticks - amount of ticks it takes for this recipe to complete - */ - public static void addPRCRecipe(ItemStack inputSolid, FluidStack inputFluid, GasStack inputGas, ItemStack outputSolid, GasStack outputGas, double extraEnergy, int ticks) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addPRCRecipe", ItemStack.class, FluidStack.class, GasStack.class, ItemStack.class, GasStack.class, Double.TYPE, Integer.TYPE); - m.invoke(null, inputSolid, inputFluid, inputGas, outputSolid, outputGas, extraEnergy, ticks); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Solar Evaporation Plant recipe. - * @param input - input GasStack - * @param output - output GasStack - */ - public static void addSolarEvaporationRecipe(FluidStack input, FluidStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addSolarEvaporationRecipe", FluidStack.class, FluidStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } - - /** - * Add a Solar Neutron Activator recipe. - * @param input - input GasStack - * @param output - output GasStack - */ - public static void addSolarNeutronRecipe(GasStack input, GasStack output) - { - try { - Class recipeClass = Class.forName("mekanism.common.recipe.RecipeHandler"); - Method m = recipeClass.getMethod("addSolarEvaporationRecipe", GasStack.class, GasStack.class); - m.invoke(null, input, output); - } catch(Exception e) { - System.err.println("Error while adding recipe: " + e.getMessage()); - } - } -} diff --git a/src/api/java/mekanism/api/recipe/package-info.java b/src/api/java/mekanism/api/recipe/package-info.java deleted file mode 100644 index f166da475..000000000 --- a/src/api/java/mekanism/api/recipe/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|recipe") -package mekanism.api.recipe; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/mekanism/api/util/BlockInfo.java b/src/api/java/mekanism/api/util/BlockInfo.java deleted file mode 100644 index 2cb40d7df..000000000 --- a/src/api/java/mekanism/api/util/BlockInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -package mekanism.api.util; - -import net.minecraft.block.Block; -import net.minecraft.item.ItemStack; - -public class BlockInfo -{ - public Block block; - public int meta; - - public BlockInfo(Block b, int j) - { - block = b; - meta = j; - } - - public static BlockInfo get(ItemStack stack) - { - return new BlockInfo(Block.getBlockFromItem(stack.getItem()), stack.getItemDamage()); - } - - @Override - public boolean equals(Object obj) - { - return obj instanceof BlockInfo && - ((BlockInfo)obj).block == block && - ((BlockInfo)obj).meta == meta; - } - - @Override - public int hashCode() - { - int code = 1; - code = 31 * code + block.getUnlocalizedName().hashCode(); - code = 31 * code + meta; - return code; - } -} \ No newline at end of file diff --git a/src/api/java/mekanism/api/util/ItemInfo.java b/src/api/java/mekanism/api/util/ItemInfo.java deleted file mode 100644 index f27065b66..000000000 --- a/src/api/java/mekanism/api/util/ItemInfo.java +++ /dev/null @@ -1,38 +0,0 @@ -package mekanism.api.util; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public class ItemInfo -{ - public Item item; - public int meta; - - public ItemInfo(Item i, int j) - { - item = i; - meta = j; - } - - public static ItemInfo get(ItemStack stack) - { - return new ItemInfo(stack.getItem(), stack.getItemDamage()); - } - - @Override - public boolean equals(Object obj) - { - return obj instanceof ItemInfo && - ((ItemInfo)obj).item == item && - ((ItemInfo)obj).meta == meta; - } - - @Override - public int hashCode() - { - int code = 1; - code = 31 * code + System.identityHashCode(item); - code = 7 * code + meta; - return code; - } -} diff --git a/src/api/java/mekanism/api/util/ListUtils.java b/src/api/java/mekanism/api/util/ListUtils.java deleted file mode 100644 index e20807c53..000000000 --- a/src/api/java/mekanism/api/util/ListUtils.java +++ /dev/null @@ -1,282 +0,0 @@ -package mekanism.api.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -public class ListUtils -{ - public static List inverse(List list) - { - List toReturn = new ArrayList(); - - for(int i = list.size() - 1; i >= 0; i--) - { - toReturn.add(list.get(i)); - } - - return toReturn; - } - - public static List cap(List list, int cap) - { - List toReturn = new ArrayList(); - - if(list.size() <= cap) - { - toReturn = copy(list); - } - else { - int count = 0; - - for(V obj : list) - { - count++; - - toReturn.add(obj); - - if(count == cap) - { - break; - } - } - } - - return toReturn; - } - - public static List copy(List list) - { - List toReturn = new ArrayList(); - - for(V obj : list) - { - toReturn.add(obj); - } - - return toReturn; - } - - public static List merge(List listOne, List listTwo) - { - List newList = new ArrayList(); - - for(V obj : listOne) - { - newList.add(obj); - } - - for(V obj : listTwo) - { - newList.add(obj); - } - - return newList; - } - - public static List capRemains(List list, int cap) - { - List toReturn = new ArrayList(); - - if(list.size() <= cap) - { - return toReturn; - } - else { - List inverse = inverse(list); - - int iterNeeded = list.size() - cap; - int count = 0; - - for(V obj : list) - { - count++; - - toReturn.add(obj); - - if(count == iterNeeded) - { - break; - } - } - - return toReturn; - } - } - - public static ArrayList> split(List list, int divide) - { - int remain = list.size() % divide; - int size = (list.size() - remain) / divide; - - ArrayList> toReturn = new ArrayList>(); - - for(int i = 0; i < divide; i++) - { - toReturn.add(i, new ArrayList()); - } - - for(List iterSet : toReturn) - { - List removed = new ArrayList(); - - int toAdd = size; - - if(remain > 0) - { - remain--; - toAdd++; - } - - for(V obj : list) - { - if(toAdd == 0) - { - break; - } - - iterSet.add(obj); - removed.add(obj); - toAdd--; - } - - for(V obj : removed) - { - list.remove(obj); - } - } - - return toReturn; - } - - public static V getTop(List list) - { - for(V obj : list) - { - return obj; - } - - return null; - } - - public static List asList(Set set) - { - return (List)Arrays.asList(set.toArray()); - } - - public static List asList(V... values) - { - return (List)Arrays.asList(values); - } - - public static double[] splitDouble(int size, double num) - { - double[] split = new double[size]; - - for(int i = 0; i < size; i++) - { - double remain = num%size; - double ret = (num-remain)/size; - ret += remain; - - split[i] = ret; - num -= remain; - } - - return split; - } - - public static double[] percent(double[] values) - { - double[] ret = new double[values.length]; - double total = 0; - - for(double d : values) total += d; - - for(int i = 0; i < values.length; i++) - { - ret[i] = values[i]/total; - } - - return ret; - } - - public static int[] calcPercentInt(double[] percent, int val) - { - int[] ret = new int[percent.length]; - - for(int i = 0; i < percent.length; i++) - { - ret[i] = (int)Math.round(val*percent[i]); - } - - int newTotal = 0; - for(int i : ret) newTotal += i; - - int diff = val-newTotal; - - if(diff != val) - { - for(int i = 0; i < ret.length; i++) - { - int num = ret[i]; - - if(diff < 0 && num == 0) - { - continue; - } - - if(diff > 0) - { - ret[i]++; - diff--; - } - else if(diff < 0) - { - ret[i]--; - diff++; - } - - if(diff == 0) - { - return ret; - } - } - } - - return ret; - } - - public static int[] splitInt(int size, int num) - { - int[] split = new int[size]; - - for(int i = 0; i < size; i++) - { - int remain = num%size; - int ret = (num-remain)/size; - ret += remain; - - split[i] = ret; - num -= remain; - } - - return split; - } - - public static double[] percent(int[] values) - { - double[] ret = new double[values.length]; - double total = 0; - - for(double d : values) total += d; - - for(int i = 0; i < values.length; i++) - { - ret[i] = values[i]/total; - } - - return ret; - } -} diff --git a/src/api/java/mekanism/api/util/StackUtils.java b/src/api/java/mekanism/api/util/StackUtils.java deleted file mode 100644 index b3a3aca92..000000000 --- a/src/api/java/mekanism/api/util/StackUtils.java +++ /dev/null @@ -1,253 +0,0 @@ -package mekanism.api.util; - -import java.util.ArrayList; -import java.util.List; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraftforge.oredict.OreDictionary; - -public final class StackUtils -{ - public static List split(ItemStack stack) - { - if(stack == null || stack.stackSize == 0) - { - return null; - } - - List ret = new ArrayList(); - - if(stack.stackSize == 1) - { - ret.add(stack); - return ret; - } - - int remain = stack.stackSize % 2; - int split = (int)((float)(stack.stackSize)/2F); - - ret.add(size(stack, split+remain)); - ret.add(size(stack, split)); - - return ret; - } - - public static Item getItem(ItemStack stack) - { - if(stack == null) - { - return null; - } - - return stack.getItem(); - } - - public static boolean diffIgnoreNull(ItemStack stack1, ItemStack stack2) - { - if(stack1 == null || stack2 == null) - { - return false; - } - - return stack1.getItem() != stack2.getItem() || stack1.getItemDamage() != stack2.getItemDamage(); - } - - public static boolean equalsWildcard(ItemStack wild, ItemStack check) - { - if(wild == null || check == null) - { - return check == wild; - } - return wild.getItem() == check.getItem() && (wild.getItemDamage() == OreDictionary.WILDCARD_VALUE || wild.getItemDamage() == check.getItemDamage()); - } - - public static boolean equalsWildcardWithNBT(ItemStack wild, ItemStack check) - { - return equalsWildcard(wild, check) && (wild.stackTagCompound == null ? check.stackTagCompound == null : (wild.stackTagCompound == check.stackTagCompound || wild.stackTagCompound.equals(check.stackTagCompound))); - } - - public static List even(ItemStack stack1, ItemStack stack2) - { - ArrayList ret = new ArrayList(); - - if(getSize(stack1) == getSize(stack2) || Math.abs(getSize(stack1)-getSize(stack2)) == 1) - { - ret.add(stack1); - ret.add(stack2); - - return ret; - } - - if(getSize(stack1) > getSize(stack2)) - { - int diff = getSize(stack1)-getSize(stack2); - - List split = split(size(stack1, diff)); - - ret.add(subtract(stack1, split.get(0))); - ret.add(add(stack2, split.get(0))); - } - else if(getSize(stack2) > getSize(stack1)) - { - int diff = getSize(stack2)-getSize(stack1); - - List split = split(size(stack2, diff)); - - ret.add(subtract(stack2, split.get(0))); - ret.add(add(stack1, split.get(0))); - } - - return ret; - } - - public static ItemStack add(ItemStack stack1, ItemStack stack2) - { - if(stack1 == null) - { - return stack2; - } - else if(stack2 == null) - { - return stack1; - } - - return size(stack1, getSize(stack1)+getSize(stack2)); - } - - public static ItemStack subtract(ItemStack stack1, ItemStack stack2) - { - if(stack1 == null) - { - return null; - } - else if(stack2 == null) - { - return stack1; - } - - return size(stack1, getSize(stack1)-getSize(stack2)); - } - - public static ItemStack size(ItemStack stack, int size) - { - if(size <= 0 || stack == null) - { - return null; - } - - ItemStack ret = stack.copy(); - ret.stackSize = size; - return ret; - } - - public static ItemStack copy(ItemStack stack) - { - if(stack == null) - { - return null; - } - - return stack.copy(); - } - - public static int getSize(ItemStack stack) - { - return stack != null ? stack.stackSize : 0; - } - - public static List getMergeRejects(ItemStack[] orig, ItemStack[] toAdd) - { - List ret = new ArrayList(); - - for(int i = 0; i < toAdd.length; i++) - { - if(toAdd[i] != null) - { - ItemStack reject = getMergeReject(orig[i], toAdd[i]); - - if(reject != null) - { - ret.add(reject); - } - } - } - - return ret; - } - - public static void merge(ItemStack[] orig, ItemStack[] toAdd) - { - for(int i = 0; i < toAdd.length; i++) - { - if(toAdd[i] != null) - { - orig[i] = merge(orig[i], toAdd[i]); - } - } - } - - public static ItemStack merge(ItemStack orig, ItemStack toAdd) - { - if(orig == null) - { - return toAdd; - } - - if(toAdd == null) - { - return orig; - } - - if(!orig.isItemEqual(toAdd) || !ItemStack.areItemStackTagsEqual(orig, toAdd)) - { - return orig; - } - - return StackUtils.size(orig, Math.min(orig.getMaxStackSize(), orig.stackSize+toAdd.stackSize)); - } - - public static ItemStack getMergeReject(ItemStack orig, ItemStack toAdd) - { - if(orig == null) - { - return null; - } - - if(toAdd == null) - { - return orig; - } - - if(!orig.isItemEqual(toAdd) || !ItemStack.areItemStackTagsEqual(orig, toAdd)) - { - return orig; - } - - int newSize = orig.stackSize+toAdd.stackSize; - - if(newSize > orig.getMaxStackSize()) - { - return StackUtils.size(orig, newSize-orig.getMaxStackSize()); - } - else { - return StackUtils.size(orig, newSize); - } - } - - public static boolean contains(ItemStack container, ItemStack contained) - { - return equalsWildcardWithNBT(contained, container) && container.stackSize >= contained.stackSize; - } - - public static int hashItemStack(ItemStack stack) - { - if(stack == null || stack.getItem() == null) - { - return -1; - } - - String name = stack.getItemDamage() == OreDictionary.WILDCARD_VALUE ? stack.getItem().getUnlocalizedName() : stack.getItem().getUnlocalizedName(stack); - return name.hashCode() << 8 | stack.getItemDamage(); - } -} diff --git a/src/api/java/mekanism/api/util/UnitDisplayUtils.java b/src/api/java/mekanism/api/util/UnitDisplayUtils.java deleted file mode 100644 index 9dd3e282d..000000000 --- a/src/api/java/mekanism/api/util/UnitDisplayUtils.java +++ /dev/null @@ -1,295 +0,0 @@ -package mekanism.api.util; - -/** - * Code taken from UE and modified to fit Mekanism. - */ -public class UnitDisplayUtils -{ - public static enum ElectricUnit - { - JOULES("Joule", "J"), - REDSTONE_FLUX("Redstone Flux", "RF"), - MINECRAFT_JOULES("Minecraft Joule", "MJ"), - ELECTRICAL_UNITS("Electrical Unit", "EU"); - - public String name; - public String symbol; - - private ElectricUnit(String s, String s1) - { - name = s; - symbol = s1; - } - - public String getPlural() - { - return this == REDSTONE_FLUX ? name : name + "s"; - } - } - - public static enum TemperatureUnit - { - KELVIN("Kelvin", "K", 0, 1), - CELSIUS("Celsius", "°C", 273.15, 1), - RANKINE("Rankine", "R", 0, 9D/5D), - FAHRENHEIT("Fahrenheit", "°F", 459.67, 9D/5D), - AMBIENT("Ambient", "+STP", 300, 1); - - public String name; - public String symbol; - double zeroOffset; - double intervalSize; - - private TemperatureUnit(String s, String s1, double offset, double size) - { - name = s; - symbol = s1; - zeroOffset = offset; - intervalSize = size; - } - - public double convertFromK(double T) - { - return (T * intervalSize) - zeroOffset; - } - - public double convertToK(double T) - { - return (T + zeroOffset) / intervalSize; - } - } - - /** Metric system of measurement. */ - public static enum MeasurementUnit - { - FEMTO("Femto", "f", 0.000000000000001D), - PICO("Pico", "p", 0.000000000001D), - NANO("Nano", "n", 0.000000001D), - MICRO("Micro", "u", 0.000001D), - MILLI("Milli", "m", 0.001D), - BASE("", "", 1), - KILO("Kilo", "k", 1000D), - MEGA("Mega", "M", 1000000D), - GIGA("Giga", "G", 1000000000D), - TERA("Tera", "T", 1000000000000D), - PETA("Peta", "P", 1000000000000000D), - EXA("Exa", "E", 1000000000000000000D), - ZETTA("Zetta", "Z", 1000000000000000000000D), - YOTTA("Yotta", "Y", 1000000000000000000000000D); - - /** long name for the unit */ - public String name; - - /** short unit version of the unit */ - public String symbol; - - /** Point by which a number is consider to be of this unit */ - public double value; - - private MeasurementUnit(String s, String s1, double v) - { - name = s; - symbol = s1; - value = v; - } - - public String getName(boolean getShort) - { - if(getShort) - { - return symbol; - } - else { - return name; - } - } - - public double process(double d) - { - return d / value; - } - - public boolean above(double d) - { - return d > value; - } - - public boolean below(double d) - { - return d < value; - } - } - - /** - * Displays the unit as text. Does handle negative numbers, and will place a negative sign in - * front of the output string showing this. Use string.replace to remove the negative sign if - * unwanted - */ - public static String getDisplay(double value, ElectricUnit unit, int decimalPlaces, boolean isShort) - { - String unitName = unit.name; - String prefix = ""; - - if(value < 0) - { - value = Math.abs(value); - prefix = "-"; - } - - if(isShort) - { - unitName = unit.symbol; - } - else if(value > 1) - { - unitName = unit.getPlural(); - } - - if(value == 0) - { - return value + " " + unitName; - } - else { - for(int i = 0; i < MeasurementUnit.values().length; i++) - { - MeasurementUnit lowerMeasure = MeasurementUnit.values()[i]; - - if(lowerMeasure.below(value) && lowerMeasure.ordinal() == 0) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; - } - - if(lowerMeasure.ordinal() + 1 >= MeasurementUnit.values().length) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; - } - - MeasurementUnit upperMeasure = MeasurementUnit.values()[i + 1]; - - if((lowerMeasure.above(value) && upperMeasure.below(value)) || lowerMeasure.value == value) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + " " + lowerMeasure.getName(isShort) + unitName; - } - } - } - - return prefix + roundDecimals(value, decimalPlaces) + " " + unitName; - } - - public static String getDisplayShort(double value, ElectricUnit unit) - { - return getDisplay(value, unit, 2, true); - } - - public static String getDisplayShort(double value, ElectricUnit unit, int decimalPlaces) - { - return getDisplay(value, unit, decimalPlaces, true); - } - - public static String getDisplaySimple(double value, ElectricUnit unit, int decimalPlaces) - { - if(value > 1) - { - if(decimalPlaces < 1) - { - return (int)value + " " + unit.getPlural(); - } - - return roundDecimals(value, decimalPlaces) + " " + unit.getPlural(); - } - - if(decimalPlaces < 1) - { - return (int)value + " " + unit.name; - } - - return roundDecimals(value, decimalPlaces) + " " + unit.name; - } - - public static String getDisplay(double T, TemperatureUnit unit, int decimalPlaces, boolean isShort) - { - String unitName = unit.name; - String prefix = ""; - - double value = unit.convertFromK(T); - - if(value < 0) - { - value = Math.abs(value); - prefix = "-"; - } - - if(isShort) - { - unitName = unit.symbol; - } - - if(value == 0) - { - return value + (isShort ? "" : " ") + unitName; - } - else { - for(int i = 0; i < MeasurementUnit.values().length; i++) - { - MeasurementUnit lowerMeasure = MeasurementUnit.values()[i]; - - if(lowerMeasure.below(value) && lowerMeasure.ordinal() == 0) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + (isShort ? "" : " ") + lowerMeasure.getName(isShort) + unitName; - } - - if(lowerMeasure.ordinal() + 1 >= MeasurementUnit.values().length) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + (isShort ? "" : " ") + lowerMeasure.getName(isShort) + unitName; - } - - MeasurementUnit upperMeasure = MeasurementUnit.values()[i + 1]; - - if((lowerMeasure.above(value) && upperMeasure.below(value)) || lowerMeasure.value == value) - { - return prefix + roundDecimals(lowerMeasure.process(value), decimalPlaces) + (isShort ? "" : " ") + lowerMeasure.getName(isShort) + unitName; - } - } - } - - return prefix + roundDecimals(value, decimalPlaces) + (isShort ? "" : " ") + unitName; - } - - public static String getDisplayShort(double value, TemperatureUnit unit) - { - return getDisplay(value, unit, 2, true); - } - - public static String getDisplayShort(double value, TemperatureUnit unit, int decimalPlaces) - { - return getDisplay(value, unit, decimalPlaces, true); - } - - public static double roundDecimals(double d, int decimalPlaces) - { - int j = (int)(d*Math.pow(10, decimalPlaces)); - return j/Math.pow(10, decimalPlaces); - } - - public static double roundDecimals(double d) - { - return roundDecimals(d, 2); - } - - public static enum EnergyType - { - J, - RF, - EU, - MJ - } - - public static enum TempType - { - K, - C, - R, - F, - STP - } -} diff --git a/src/api/java/mekanism/api/util/package-info.java b/src/api/java/mekanism/api/util/package-info.java deleted file mode 100644 index e5253bcbc..000000000 --- a/src/api/java/mekanism/api/util/package-info.java +++ /dev/null @@ -1,3 +0,0 @@ -@API(apiVersion = "8.0.0", owner = "Mekanism", provides = "MekanismAPI|util") -package mekanism.api.util; -import cpw.mods.fml.common.API; \ No newline at end of file diff --git a/src/api/java/thaumcraft/api/BlockCoordinates.java b/src/api/java/thaumcraft/api/BlockCoordinates.java deleted file mode 100644 index 27a28f8fa..000000000 --- a/src/api/java/thaumcraft/api/BlockCoordinates.java +++ /dev/null @@ -1,108 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -public class BlockCoordinates implements Comparable -{ - public int x; - - /** the y coordinate */ - public int y; - - /** the z coordinate */ - public int z; - - public BlockCoordinates() {} - - public BlockCoordinates(int par1, int par2, int par3) - { - this.x = par1; - this.y = par2; - this.z = par3; - } - - public BlockCoordinates(TileEntity tile) - { - this.x = tile.xCoord; - this.y = tile.yCoord; - this.z = tile.zCoord; - } - - public BlockCoordinates(BlockCoordinates par1ChunkCoordinates) - { - this.x = par1ChunkCoordinates.x; - this.y = par1ChunkCoordinates.y; - this.z = par1ChunkCoordinates.z; - } - - public boolean equals(Object par1Obj) - { - if (!(par1Obj instanceof BlockCoordinates)) - { - return false; - } - else - { - BlockCoordinates coordinates = (BlockCoordinates)par1Obj; - return this.x == coordinates.x && this.y == coordinates.y && this.z == coordinates.z ; - } - } - - public int hashCode() - { - return this.x + this.y << 8 + this.z << 16; - } - - /** - * Compare the coordinate with another coordinate - */ - public int compareWorldCoordinate(BlockCoordinates par1) - { - return this.y == par1.y ? (this.z == par1.z ? this.x - par1.x : this.z - par1.z) : this.y - par1.y; - } - - public void set(int par1, int par2, int par3, int d) - { - this.x = par1; - this.y = par2; - this.z = par3; - } - - /** - * Returns the squared distance between this coordinates and the coordinates given as argument. - */ - public float getDistanceSquared(int par1, int par2, int par3) - { - float f = (float)(this.x - par1); - float f1 = (float)(this.y - par2); - float f2 = (float)(this.z - par3); - return f * f + f1 * f1 + f2 * f2; - } - - /** - * Return the squared distance between this coordinates and the ChunkCoordinates given as argument. - */ - public float getDistanceSquaredToWorldCoordinates(BlockCoordinates par1ChunkCoordinates) - { - return this.getDistanceSquared(par1ChunkCoordinates.x, par1ChunkCoordinates.y, par1ChunkCoordinates.z); - } - - public int compareTo(Object par1Obj) - { - return this.compareWorldCoordinate((BlockCoordinates)par1Obj); - } - - public void readNBT(NBTTagCompound nbt) { - this.x = nbt.getInteger("b_x"); - this.y = nbt.getInteger("b_y"); - this.z = nbt.getInteger("b_z"); - } - - public void writeNBT(NBTTagCompound nbt) { - nbt.setInteger("b_x",x); - nbt.setInteger("b_y",y); - nbt.setInteger("b_z",z); - } - -} diff --git a/src/api/java/thaumcraft/api/IArchitect.java b/src/api/java/thaumcraft/api/IArchitect.java deleted file mode 100644 index c733af5ef..000000000 --- a/src/api/java/thaumcraft/api/IArchitect.java +++ /dev/null @@ -1,27 +0,0 @@ -package thaumcraft.api; - -import java.util.ArrayList; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -public interface IArchitect { - - /** - * Returns a list of blocks that should be highlighted in world. - */ - public ArrayList getArchitectBlocks(ItemStack stack, World world, - int x, int y, int z, int side, EntityPlayer player); - - /** - * which axis should be displayed. - */ - public boolean showAxis(ItemStack stack, World world, EntityPlayer player, int side, EnumAxis axis); - - public enum EnumAxis { - X, // east / west - Y, // up / down - Z; // north / south - } -} diff --git a/src/api/java/thaumcraft/api/IGoggles.java b/src/api/java/thaumcraft/api/IGoggles.java deleted file mode 100644 index 2f53d8163..000000000 --- a/src/api/java/thaumcraft/api/IGoggles.java +++ /dev/null @@ -1,22 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; - -/** - * - * @author Azanor - * - * Equipped head slot items that extend this class will be able to perform most functions that - * goggles of revealing can apart from view nodes which is handled by IRevealer. - * - */ - -public interface IGoggles { - - /* - * If this method returns true things like block essentia contents will be shown. - */ - public boolean showIngamePopups(ItemStack itemstack, EntityLivingBase player); - -} diff --git a/src/api/java/thaumcraft/api/IRepairable.java b/src/api/java/thaumcraft/api/IRepairable.java deleted file mode 100644 index 48c6dff9d..000000000 --- a/src/api/java/thaumcraft/api/IRepairable.java +++ /dev/null @@ -1,13 +0,0 @@ -package thaumcraft.api; - - - -/** - * @author Azanor - * Items, armor and tools with this interface can receive the Repair enchantment. - * Repairs 1 point of durability every 10 seconds (2 for repair II) - */ -public interface IRepairable { - - -} diff --git a/src/api/java/thaumcraft/api/IRepairableExtended.java b/src/api/java/thaumcraft/api/IRepairableExtended.java deleted file mode 100644 index 33827124e..000000000 --- a/src/api/java/thaumcraft/api/IRepairableExtended.java +++ /dev/null @@ -1,17 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - - - -/** - * @author Azanor - * Items, armor and tools with this interface can receive the Repair enchantment. - * Repairs 1 point of durability every 10 seconds (2 for repair II) - */ -public interface IRepairableExtended extends IRepairable { - - public boolean doRepair(ItemStack stack, EntityPlayer player, int enchantlevel); - -} diff --git a/src/api/java/thaumcraft/api/IRunicArmor.java b/src/api/java/thaumcraft/api/IRunicArmor.java deleted file mode 100644 index 5dd311006..000000000 --- a/src/api/java/thaumcraft/api/IRunicArmor.java +++ /dev/null @@ -1,22 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.item.ItemStack; - -/** - * - * @author Azanor - * - * Armor or bauble slot items that implement this interface can provide runic shielding. - * Recharging, hardening, etc. is handled internally by thaumcraft. - * - */ - -public interface IRunicArmor { - - /** - * returns how much charge this item can provide. This is the base shielding value - any hardening is stored and calculated internally. - */ - public int getRunicCharge(ItemStack itemstack); - - -} diff --git a/src/api/java/thaumcraft/api/IScribeTools.java b/src/api/java/thaumcraft/api/IScribeTools.java deleted file mode 100644 index 8800fa577..000000000 --- a/src/api/java/thaumcraft/api/IScribeTools.java +++ /dev/null @@ -1,14 +0,0 @@ -package thaumcraft.api; - - -/** - * - * @author Azanor - * - * Interface used to identify scribing tool items used in research table - * - */ - -public interface IScribeTools { - -} diff --git a/src/api/java/thaumcraft/api/IVisDiscountGear.java b/src/api/java/thaumcraft/api/IVisDiscountGear.java deleted file mode 100644 index 3793ea3e5..000000000 --- a/src/api/java/thaumcraft/api/IVisDiscountGear.java +++ /dev/null @@ -1,20 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import thaumcraft.api.aspects.Aspect; - - - - -/** - * @author Azanor - * ItemArmor with this interface will grant a discount to the vis cost of actions the wearer performs with casting wands. - * The amount returned is the percentage by which the cost is discounted. There is a built-int max discount of 50%, but - * individual items really shouldn't have a discount more than 5% - */ -public interface IVisDiscountGear { - - int getVisDiscount(ItemStack stack, EntityPlayer player, Aspect aspect); - -} diff --git a/src/api/java/thaumcraft/api/IWarpingGear.java b/src/api/java/thaumcraft/api/IWarpingGear.java deleted file mode 100644 index e7415ab73..000000000 --- a/src/api/java/thaumcraft/api/IWarpingGear.java +++ /dev/null @@ -1,22 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -/** - * - * @author Azanor - * - * Armor, held items or bauble slot items that implement this interface add warp when equipped or held. - * - */ - -public interface IWarpingGear { - - /** - * returns how much warp this item adds while worn or held. - */ - public int getWarp(ItemStack itemstack, EntityPlayer player); - - -} diff --git a/src/api/java/thaumcraft/api/ItemApi.java b/src/api/java/thaumcraft/api/ItemApi.java deleted file mode 100644 index 25dda2826..000000000 --- a/src/api/java/thaumcraft/api/ItemApi.java +++ /dev/null @@ -1,70 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import cpw.mods.fml.common.FMLLog; - -/** - * @author Azanor - * - * This is used to gain access to the items in my mod. - * I only give some examples and it will probably still - * require a bit of work for you to get hold of everything you need. - * - */ -public class ItemApi { - - public static ItemStack getItem(String itemString, int meta) { - ItemStack item = null; - - try { - String itemClass = "thaumcraft.common.config.ConfigItems"; - Object obj = Class.forName(itemClass).getField(itemString).get(null); - if (obj instanceof Item) { - item = new ItemStack((Item) obj,1,meta); - } else if (obj instanceof ItemStack) { - item = (ItemStack) obj; - } - } catch (Exception ex) { - FMLLog.warning("[Thaumcraft] Could not retrieve item identified by: " + itemString); - } - - return item; - } - - public static ItemStack getBlock(String itemString, int meta) { - ItemStack item = null; - - try { - String itemClass = "thaumcraft.common.config.ConfigBlocks"; - Object obj = Class.forName(itemClass).getField(itemString).get(null); - if (obj instanceof Block) { - item = new ItemStack((Block) obj,1,meta); - } else if (obj instanceof ItemStack) { - item = (ItemStack) obj; - } - } catch (Exception ex) { - FMLLog.warning("[Thaumcraft] Could not retrieve block identified by: " + itemString); - } - - return item; - } - - /** - * - * Some examples - * - * Casting Wands: - * itemWandCasting - * - * Resources: - * itemEssence, itemWispEssence, itemResource, itemShard, itemNugget, - * itemNuggetChicken, itemNuggetBeef, itemNuggetPork, itemTripleMeatTreat - * - * Research: - * itemResearchNotes, itemInkwell, itemThaumonomicon - * - */ - -} diff --git a/src/api/java/thaumcraft/api/ItemRunic.java b/src/api/java/thaumcraft/api/ItemRunic.java deleted file mode 100644 index 80251f599..000000000 --- a/src/api/java/thaumcraft/api/ItemRunic.java +++ /dev/null @@ -1,21 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public class ItemRunic extends Item implements IRunicArmor { - - int charge; - - public ItemRunic (int charge) - { - super(); - this.charge = charge; - } - - @Override - public int getRunicCharge(ItemStack itemstack) { - return charge; - } - -} diff --git a/src/api/java/thaumcraft/api/LICENSE b/src/api/java/thaumcraft/api/LICENSE deleted file mode 100644 index 01aa7a1ee..000000000 --- a/src/api/java/thaumcraft/api/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Azanor - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this API software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/api/java/thaumcraft/api/README.md b/src/api/java/thaumcraft/api/README.md deleted file mode 100644 index b88c1cc60..000000000 --- a/src/api/java/thaumcraft/api/README.md +++ /dev/null @@ -1,10 +0,0 @@ -thaumcraft-api -============== - -Thaumcraft Api - - - -This is just to create an easy to access place for the api code. - -I will still place the zips on the minecraft forum post for the "official" version of the api - the code here will usually be for dev versions. diff --git a/src/api/java/thaumcraft/api/ThaumcraftApi.java b/src/api/java/thaumcraft/api/ThaumcraftApi.java deleted file mode 100644 index fbf78801e..000000000 --- a/src/api/java/thaumcraft/api/ThaumcraftApi.java +++ /dev/null @@ -1,588 +0,0 @@ -package thaumcraft.api; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import net.minecraft.block.Block; -import net.minecraft.enchantment.Enchantment; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.Item.ToolMaterial; -import net.minecraft.item.ItemArmor.ArmorMaterial; -import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.EnumHelper; -import net.minecraftforge.oredict.OreDictionary; -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; -import thaumcraft.api.crafting.CrucibleRecipe; -import thaumcraft.api.crafting.InfusionEnchantmentRecipe; -import thaumcraft.api.crafting.InfusionRecipe; -import thaumcraft.api.crafting.ShapedArcaneRecipe; -import thaumcraft.api.crafting.ShapelessArcaneRecipe; -import thaumcraft.api.internal.DummyInternalMethodHandler; -import thaumcraft.api.internal.IInternalMethodHandler; -import thaumcraft.api.internal.WeightedRandomLoot; -import thaumcraft.api.research.IScanEventHandler; -import thaumcraft.api.research.ResearchCategories; -import thaumcraft.api.research.ResearchCategoryList; -import thaumcraft.api.research.ResearchItem; -import thaumcraft.api.research.ResearchPage; - - -/** - * @author Azanor - * - * - * IMPORTANT: If you are adding your own aspects to items it is a good idea to do it AFTER Thaumcraft adds its aspects, otherwise odd things may happen. - * - */ -public class ThaumcraftApi { - - //Materials - public static ToolMaterial toolMatThaumium = EnumHelper.addToolMaterial("THAUMIUM", 3, 400, 7F, 2, 22); - public static ToolMaterial toolMatVoid = EnumHelper.addToolMaterial("VOID", 4, 150, 8F, 3, 10); - public static ToolMaterial toolMatElemental = EnumHelper.addToolMaterial("THAUMIUM_ELEMENTAL", 3, 1500, 10F, 3, 18); - public static ArmorMaterial armorMatThaumium = EnumHelper.addArmorMaterial("THAUMIUM", 25, new int[] { 2, 6, 5, 2 }, 25); - public static ArmorMaterial armorMatSpecial = EnumHelper.addArmorMaterial("SPECIAL", 25, new int[] { 1, 3, 2, 1 }, 25); - public static ArmorMaterial armorMatThaumiumFortress = EnumHelper.addArmorMaterial("FORTRESS", 40, new int[] { 3, 7, 6, 3 }, 25); - public static ArmorMaterial armorMatVoid = EnumHelper.addArmorMaterial("VOID", 10, new int[] { 3, 7, 6, 3 }, 10); - public static ArmorMaterial armorMatVoidFortress = EnumHelper.addArmorMaterial("VOIDFORTRESS", 18, new int[] { 4, 8, 7, 4 }, 10); - - //Enchantment references - public static int enchantFrugal; - public static int enchantPotency; - public static int enchantWandFortune; - public static int enchantHaste; - public static int enchantRepair; - - //Miscellaneous - /** - * Portable Hole Block-id Blacklist. - * Simply add the block-id's of blocks you don't want the portable hole to go through. - */ - public static ArrayList portableHoleBlackList = new ArrayList(); - - //Internal (Do not alter this unless you like pretty explosions) - //Calling methods from this will only work properly once Thaumcraft is past the FMLPreInitializationEvent phase. - public static IInternalMethodHandler internalMethods = new DummyInternalMethodHandler(); - - //RESEARCH///////////////////////////////////////// - public static ArrayList scanEventhandlers = new ArrayList(); - public static ArrayList scanEntities = new ArrayList(); - public static class EntityTagsNBT { - public EntityTagsNBT(String name, Object value) { - this.name = name; - this.value = value; - } - public String name; - public Object value; - } - public static class EntityTags { - public EntityTags(String entityName, AspectList aspects, EntityTagsNBT... nbts) { - this.entityName = entityName; - this.nbts = nbts; - this.aspects = aspects; - } - public String entityName; - public EntityTagsNBT[] nbts; - public AspectList aspects; - } - - /** - * not really working atm, so ignore it for now - * @param scanEventHandler - */ - public static void registerScanEventhandler(IScanEventHandler scanEventHandler) { - scanEventhandlers.add(scanEventHandler); - } - - /** - * This is used to add aspects to entities which you can then scan using a thaumometer. - * Also used to calculate vis drops from mobs. - * @param entityName - * @param aspects - * @param nbt you can specify certain nbt keys and their values - * to differentiate between mobs.
For example the normal and wither skeleton: - *
ThaumcraftApi.registerEntityTag("Skeleton", (new AspectList()).add(Aspect.DEATH, 5)); - *
ThaumcraftApi.registerEntityTag("Skeleton", (new AspectList()).add(Aspect.DEATH, 8), new NBTTagByte("SkeletonType",(byte) 1)); - */ - public static void registerEntityTag(String entityName, AspectList aspects, EntityTagsNBT... nbt ) { - scanEntities.add(new EntityTags(entityName,aspects,nbt)); - } - - //RECIPES///////////////////////////////////////// - private static ArrayList craftingRecipes = new ArrayList(); - private static HashMap smeltingBonus = new HashMap(); - - /** - * This method is used to determine what bonus items are generated when the infernal furnace smelts items - * @param in The input of the smelting operation. e.g. new ItemStack(Block.oreGold) - * @param out The bonus item that can be produced from the smelting operation e.g. new ItemStack(nuggetGold,0,0). - * Stacksize should be 0 unless you want to guarantee that at least 1 item is always produced. - */ - public static void addSmeltingBonus(ItemStack in, ItemStack out) { - smeltingBonus.put( - Arrays.asList(in.getItem(),in.getItemDamage()), - new ItemStack(out.getItem(),0,out.getItemDamage())); - } - - /** - * This method is used to determine what bonus items are generated when the infernal furnace smelts items - * @param in The ore dictionary input of the smelting operation. e.g. "oreGold" - * @param out The bonus item that can be produced from the smelting operation e.g. new ItemStack(nuggetGold,0,0). - * Stacksize should be 0 unless you want to guarantee that at least 1 item is always produced. - */ - public static void addSmeltingBonus(String in, ItemStack out) { - smeltingBonus.put( in, new ItemStack(out.getItem(),0,out.getItemDamage())); - } - - /** - * Returns the bonus item produced from a smelting operation in the infernal furnace - * @param in The input of the smelting operation. e.g. new ItemStack(oreGold) - * @return the The bonus item that can be produced - */ - public static ItemStack getSmeltingBonus(ItemStack in) { - ItemStack out = smeltingBonus.get(Arrays.asList(in.getItem(),in.getItemDamage())); - if (out==null) { - out = smeltingBonus.get(Arrays.asList(in.getItem(),OreDictionary.WILDCARD_VALUE)); - } - if (out==null) { - String od = OreDictionary.getOreName( OreDictionary.getOreID(in)); - out = smeltingBonus.get(od); - } - return out; - } - - public static List getCraftingRecipes() { - return craftingRecipes; - } - - /** - * @param research the research key required for this recipe to work. Leave blank if it will work without research - * @param result the recipe output - * @param aspects the vis cost per aspect. - * @param recipe The recipe. Format is exactly the same as vanilla recipes. Input itemstacks are NBT sensitive. - */ - public static ShapedArcaneRecipe addArcaneCraftingRecipe(String research, ItemStack result, AspectList aspects, Object ... recipe) - { - ShapedArcaneRecipe r= new ShapedArcaneRecipe(research, result, aspects, recipe); - craftingRecipes.add(r); - return r; - } - - /** - * @param research the research key required for this recipe to work. Leave blank if it will work without research - * @param result the recipe output - * @param aspects the vis cost per aspect - * @param recipe The recipe. Format is exactly the same as vanilla shapeless recipes. Input itemstacks are NBT sensitive. - */ - public static ShapelessArcaneRecipe addShapelessArcaneCraftingRecipe(String research, ItemStack result, AspectList aspects, Object ... recipe) - { - ShapelessArcaneRecipe r = new ShapelessArcaneRecipe(research, result, aspects, recipe); - craftingRecipes.add(r); - return r; - } - - /** - * @param research the research key required for this recipe to work. Leave blank if it will work without research - * @param result the recipe output. It can either be an itemstack or an nbt compound tag that will be added to the central item - * @param instability a number that represents the N in 1000 chance for the infusion altar to spawn an - * instability effect each second while the crafting is in progress - * @param aspects the essentia cost per aspect. - * @param aspects input the central item to be infused - * @param recipe An array of items required to craft this. Input itemstacks are NBT sensitive. - * Infusion crafting components are automatically "fuzzy" and the oredict will be checked for possible matches. - * - */ - public static InfusionRecipe addInfusionCraftingRecipe(String research, Object result, int instability, AspectList aspects, ItemStack input,ItemStack[] recipe) - { - if (!(result instanceof ItemStack || result instanceof Object[])) return null; - InfusionRecipe r= new InfusionRecipe(research, result, instability, aspects, input, recipe); - craftingRecipes.add(r); - return r; - } - - /** - * @param research the research key required for this recipe to work. Leave blank if it will work without research - * @param enchantment the enchantment that will be applied to the item - * @param instability a number that represents the N in 1000 chance for the infusion altar to spawn an - * instability effect each second while the crafting is in progress - * @param aspects the essentia cost per aspect. - * @param recipe An array of items required to craft this. Input itemstacks are NBT sensitive. - * Infusion crafting components are automatically "fuzzy" and the oredict will be checked for possible matches. - * - */ - public static InfusionEnchantmentRecipe addInfusionEnchantmentRecipe(String research, Enchantment enchantment, int instability, AspectList aspects, ItemStack[] recipe) - { - InfusionEnchantmentRecipe r= new InfusionEnchantmentRecipe(research, enchantment, instability, aspects, recipe); - craftingRecipes.add(r); - return r; - } - - /** - * @param stack the recipe result - * @return the recipe - */ - public static InfusionRecipe getInfusionRecipe(ItemStack res) { - for (Object r:getCraftingRecipes()) { - if (r instanceof InfusionRecipe) { - if (((InfusionRecipe)r).getRecipeOutput() instanceof ItemStack) { - if (((ItemStack) ((InfusionRecipe)r).getRecipeOutput()).isItemEqual(res)) - return (InfusionRecipe)r; - } - } - } - return null; - } - - - /** - * @param key the research key required for this recipe to work. - * @param result the output result - * @param catalyst an itemstack of the catalyst or a string if it is an ore dictionary item - * @param cost the vis cost - * @param tags the aspects required to craft this - */ - public static CrucibleRecipe addCrucibleRecipe(String key, ItemStack result, Object catalyst, AspectList tags) { - CrucibleRecipe rc = new CrucibleRecipe(key, result, catalyst, tags); - getCraftingRecipes().add(rc); - return rc; - } - - - /** - * @param stack the recipe result - * @return the recipe - */ - public static CrucibleRecipe getCrucibleRecipe(ItemStack stack) { - for (Object r:getCraftingRecipes()) { - if (r instanceof CrucibleRecipe) { - if (((CrucibleRecipe)r).getRecipeOutput().isItemEqual(stack)) - return (CrucibleRecipe)r; - } - } - return null; - } - - /** - * @param hash the unique recipe code - * @return the recipe - */ - public static CrucibleRecipe getCrucibleRecipeFromHash(int hash) { - for (Object r:getCraftingRecipes()) { - if (r instanceof CrucibleRecipe) { - if (((CrucibleRecipe)r).hash==hash) - return (CrucibleRecipe)r; - } - } - return null; - } - - /** - * Used by the thaumonomicon drilldown feature. - * @param stack the item - * @return the thaumcraft recipe key that produces that item. - */ - private static HashMap keyCache = new HashMap(); - - public static Object[] getCraftingRecipeKey(EntityPlayer player, ItemStack stack) { - int[] key = new int[] {Item.getIdFromItem(stack.getItem()),stack.getItemDamage()}; - if (keyCache.containsKey(key)) { - if (keyCache.get(key)==null) return null; - if (ThaumcraftApiHelper.isResearchComplete(player.getCommandSenderName(), (String)(keyCache.get(key))[0])) - return keyCache.get(key); - else - return null; - } - for (ResearchCategoryList rcl:ResearchCategories.researchCategories.values()) { - for (ResearchItem ri:rcl.research.values()) { - if (ri.getPages()==null) continue; - for (int a=0;a objectTags = new ConcurrentHashMap(); - public static ConcurrentHashMap groupedObjectTags = new ConcurrentHashMap(); - - /** - * Checks to see if the passed item/block already has aspects associated with it. - * @param id - * @param meta - * @return - */ - public static boolean exists(Item item, int meta) { - AspectList tmp = ThaumcraftApi.objectTags.get(Arrays.asList(item,meta)); - if (tmp==null) { - tmp = ThaumcraftApi.objectTags.get(Arrays.asList(item,OreDictionary.WILDCARD_VALUE)); - if (meta==OreDictionary.WILDCARD_VALUE && tmp==null) { - int index=0; - do { - tmp = ThaumcraftApi.objectTags.get(Arrays.asList(item,index)); - index++; - } while (index<16 && tmp==null); - } - if (tmp==null) return false; - } - - return true; - } - - /** - * Used to assign apsects to the given item/block. Here is an example of the declaration for cobblestone:

- * ThaumcraftApi.registerObjectTag(new ItemStack(Blocks.cobblestone), (new AspectList()).add(Aspect.ENTROPY, 1).add(Aspect.EARTH, 1)); - * @param item the item passed. Pass OreDictionary.WILDCARD_VALUE if all damage values of this item/block should have the same aspects - * @param aspects A ObjectTags object of the associated aspects - */ - public static void registerObjectTag(ItemStack item, AspectList aspects) { - if (aspects==null) aspects=new AspectList(); - try { - objectTags.put(Arrays.asList(item.getItem(),item.getItemDamage()), aspects); - } catch (Exception e) {} - } - - - /** - * Used to assign apsects to the given item/block. Here is an example of the declaration for cobblestone:

- * ThaumcraftApi.registerObjectTag(new ItemStack(Blocks.cobblestone), new int[]{0,1}, (new AspectList()).add(Aspect.ENTROPY, 1).add(Aspect.EARTH, 1)); - * @param item - * @param meta A range of meta values if you wish to lump several item meta's together as being the "same" item (i.e. stair orientations) - * @param aspects A ObjectTags object of the associated aspects - */ - public static void registerObjectTag(ItemStack item, int[] meta, AspectList aspects) { - if (aspects==null) aspects=new AspectList(); - try { - objectTags.put(Arrays.asList(item.getItem(),meta[0]), aspects); - for (int m:meta) { - groupedObjectTags.put(Arrays.asList(item.getItem(),m), meta); - } - - } catch (Exception e) {} - } - - /** - * Used to assign apsects to the given ore dictionary item. - * @param oreDict the ore dictionary name - * @param aspects A ObjectTags object of the associated aspects - */ - public static void registerObjectTag(String oreDict, AspectList aspects) { - if (aspects==null) aspects=new AspectList(); - ArrayList ores = OreDictionary.getOres(oreDict); - if (ores!=null && ores.size()>0) { - for (ItemStack ore:ores) { - try { - objectTags.put(Arrays.asList(ore.getItem(), ore.getItemDamage()), aspects); - } catch (Exception e) {} - } - } - } - - /** - * Used to assign aspects to the given item/block. - * Attempts to automatically generate aspect tags by checking registered recipes. - * Here is an example of the declaration for pistons:

- * ThaumcraftApi.registerComplexObjectTag(new ItemStack(Blocks.cobblestone), (new AspectList()).add(Aspect.MECHANISM, 2).add(Aspect.MOTION, 4)); - * IMPORTANT - this should only be used if you are not happy with the default aspects the object would be assigned. - * @param item, pass OreDictionary.WILDCARD_VALUE to meta if all damage values of this item/block should have the same aspects - * @param aspects A ObjectTags object of the associated aspects - */ - public static void registerComplexObjectTag(ItemStack item, AspectList aspects ) { - if (!exists(item.getItem(),item.getItemDamage())) { - AspectList tmp = ThaumcraftApiHelper.generateTags(item.getItem(), item.getItemDamage()); - if (tmp != null && tmp.size()>0) { - for(Aspect tag:tmp.getAspects()) { - aspects.add(tag, tmp.getAmount(tag)); - } - } - registerObjectTag(item,aspects); - } else { - AspectList tmp = ThaumcraftApiHelper.getObjectAspects(item); - for(Aspect tag:aspects.getAspects()) { - tmp.merge(tag, tmp.getAmount(tag)); - } - registerObjectTag(item,tmp); - } - } - - //WARP /////////////////////////////////////////////////////////////////////////////////////// - private static HashMap warpMap = new HashMap(); - - /** - * This method is used to determine how much warp is gained if the item is crafted. The warp - * added is "sticky" warp - * @param craftresult The item crafted - * @param amount how much warp is gained - */ - public static void addWarpToItem(ItemStack craftresult, int amount) { - warpMap.put(Arrays.asList(craftresult.getItem(),craftresult.getItemDamage()),amount); - } - - /** - * This method is used to determine how much permanent warp is gained if the research is completed - * @param in The item crafted - * @param amount how much warp is gained - */ - public static void addWarpToResearch(String research, int amount) { - warpMap.put(research, amount); - } - - /** - * Returns how much warp is gained from the item or research passed in - * @param in itemstack or string - * @return how much warp it will give - */ - public static int getWarp(Object in) { - if (in==null) return 0; - if (in instanceof ItemStack && warpMap.containsKey(Arrays.asList(((ItemStack)in).getItem(),((ItemStack)in).getItemDamage()))) { - return warpMap.get(Arrays.asList(((ItemStack)in).getItem(),((ItemStack)in).getItemDamage())); - } else - if (in instanceof String && warpMap.containsKey((String)in)) { - return warpMap.get((String)in); - } - return 0; - } - - //LOOT BAGS ////////////////////////////////////////////////////////////////////////////////////////// - - /** - * Used to add possible loot to treasure bags. As a reference, the weight of gold coins are 2000 - * and a diamond is 50. - * The weights are the same for all loot bag types - the only difference is how many items the bag - * contains. - * @param item - * @param weight - * @param bagTypes array of which type of bag to add this loot to. Multiple types can be specified - * 0 = common, 1 = uncommon, 2 = rare - */ - public static void addLootBagItem(ItemStack item, int weight, int... bagTypes) { - if (bagTypes==null || bagTypes.length==0) - WeightedRandomLoot.lootBagCommon.add(new WeightedRandomLoot(item,weight)); - else { - for (int rarity:bagTypes) { - switch(rarity) { - case 0: WeightedRandomLoot.lootBagCommon.add(new WeightedRandomLoot(item,weight)); break; - case 1: WeightedRandomLoot.lootBagUncommon.add(new WeightedRandomLoot(item,weight)); break; - case 2: WeightedRandomLoot.lootBagRare.add(new WeightedRandomLoot(item,weight)); break; - } - } - } - } - - //CROPS ////////////////////////////////////////////////////////////////////////////////////////// - - /** - * To define mod crops you need to use FMLInterModComms in your @Mod.Init method. - * There are two 'types' of crops you can add. Standard crops and clickable crops. - * - * Standard crops work like normal vanilla crops - they grow until a certain metadata - * value is reached and you harvest them by destroying the block and collecting the blocks. - * You need to create and ItemStack that tells the golem what block id and metadata represents - * the crop when fully grown. Sending a metadata of [OreDictionary.WILDCARD_VALUE] will mean the metadata won't get - * checked. - * Example for vanilla wheat: - * FMLInterModComms.sendMessage("Thaumcraft", "harvestStandardCrop", new ItemStack(Block.crops,1,7)); - * - * Clickable crops are crops that you right click to gather their bounty instead of destroying them. - * As for standard crops, you need to create and ItemStack that tells the golem what block id - * and metadata represents the crop when fully grown. The golem will trigger the blocks onBlockActivated method. - * Sending a metadata of [OreDictionary.WILDCARD_VALUE] will mean the metadata won't get checked. - * Example (this will technically do nothing since clicking wheat does nothing, but you get the idea): - * FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(Block.crops,1,7)); - * - * Stacked crops (like reeds) are crops that you wish the bottom block should remain after harvesting. - * As for standard crops, you need to create and ItemStack that tells the golem what block id - * and metadata represents the crop when fully grown. Sending a metadata of [OreDictionary.WILDCARD_VALUE] will mean the actualy md won't get - * checked. If it has the order upgrade it will only harvest if the crop is more than one block high. - * Example: - * FMLInterModComms.sendMessage("Thaumcraft", "harvestStackedCrop", new ItemStack(Block.reed,1,7)); - */ - - //NATIVE CLUSTERS ////////////////////////////////////////////////////////////////////////////////// - - /** - * You can define certain ores that will have a chance to produce native clusters via FMLInterModComms - * in your @Mod.Init method using the "nativeCluster" string message. - * The format should be: - * "[ore item/block id],[ore item/block metadata],[cluster item/block id],[cluster item/block metadata],[chance modifier float]" - * - * NOTE: The chance modifier is a multiplier applied to the default chance for that cluster to be produced (default 27.5% for a pickaxe of the core) - * - * Example for vanilla iron ore to produce one of my own native iron clusters (assuming default id's) at double the default chance: - * FMLInterModComms.sendMessage("Thaumcraft", "nativeCluster","15,0,25016,16,2.0"); - */ - - //LAMP OF GROWTH BLACKLIST /////////////////////////////////////////////////////////////////////////// - /** - * You can blacklist crops that should not be effected by the Lamp of Growth via FMLInterModComms - * in your @Mod.Init method using the "lampBlacklist" itemstack message. - * Sending a metadata of [OreDictionary.WILDCARD_VALUE] will mean the metadata won't get checked. - * Example for vanilla wheat: - * FMLInterModComms.sendMessage("Thaumcraft", "lampBlacklist", new ItemStack(Block.crops,1,OreDictionary.WILDCARD_VALUE)); - */ - - //DIMENSION BLACKLIST /////////////////////////////////////////////////////////////////////////// - /** - * You can blacklist a dimension to not spawn certain thaumcraft features - * in your @Mod.Init method using the "dimensionBlacklist" string message in the format "[dimension]:[level]" - * The level values are as follows: - * [0] stop all tc spawning and generation - * [1] allow ore and node generation (and node special features) - * [2] allow mob spawning - * [3] allow ore and node gen + mob spawning (and node special features) - * Example: - * FMLInterModComms.sendMessage("Thaumcraft", "dimensionBlacklist", "15:1"); - */ - - //BIOME BLACKLIST /////////////////////////////////////////////////////////////////////////// - /** - * You can blacklist a biome to not spawn certain thaumcraft features - * in your @Mod.Init method using the "biomeBlacklist" string message in the format "[biome id]:[level]" - * The level values are as follows: - * [0] stop all tc spawning and generation - * [1] allow ore and node generation (and node special features) - * [2] allow mob spawning - * [3] allow ore and node gen + mob spawning (and node special features) - * Example: - * FMLInterModComms.sendMessage("Thaumcraft", "biomeBlacklist", "180:2"); - */ - - //CHAMPION MOB WHITELIST /////////////////////////////////////////////////////////////////////////// - /** - * You can whitelist an entity class so it can rarely spawn champion versions in your @Mod.Init method using - * the "championWhiteList" string message in the format "[Entity]:[level]" - * The entity must extend EntityMob. - * [Entity] is in a similar format to what is used for mob spawners and such (see EntityList.class for vanilla examples). - * The [level] value indicate how rare the champion version will be - the higher the number the more common. - * The number roughly equals the [n] in 100 chance of a mob being a champion version. - * You can give 0 or negative numbers to allow champions to spawn with a very low chance only in particularly dangerous places. - * However anything less than about -2 will probably result in no spawns at all. - * Example: - * FMLInterModComms.sendMessage("Thaumcraft", "championWhiteList", "Thaumcraft.Wisp:1"); - */ -} diff --git a/src/api/java/thaumcraft/api/ThaumcraftApiHelper.java b/src/api/java/thaumcraft/api/ThaumcraftApiHelper.java deleted file mode 100644 index 77d55885d..000000000 --- a/src/api/java/thaumcraft/api/ThaumcraftApiHelper.java +++ /dev/null @@ -1,467 +0,0 @@ -package thaumcraft.api; - -import java.util.HashMap; -import java.util.Iterator; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.MathHelper; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.Vec3; -import net.minecraft.world.IBlockAccess; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.oredict.OreDictionary; -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; -import thaumcraft.api.aspects.IEssentiaTransport; - -public class ThaumcraftApiHelper { - - public static AspectList cullTags(AspectList temp) { - AspectList temp2 = new AspectList(); - for (Aspect tag:temp.getAspects()) { - if (tag!=null) - temp2.add(tag, temp.getAmount(tag)); - } - while (temp2!=null && temp2.size()>6) { - Aspect lowest = null; - float low = Short.MAX_VALUE; - for (Aspect tag:temp2.getAspects()) { - if (tag==null) continue; - float ta=temp2.getAmount(tag); - if (tag.isPrimal()) { - ta *= .9f; - } else { - if (!tag.getComponents()[0].isPrimal()) { - ta *= 1.1f; - if (!tag.getComponents()[0].getComponents()[0].isPrimal()) { - ta *= 1.05f; - } - if (!tag.getComponents()[0].getComponents()[1].isPrimal()) { - ta *= 1.05f; - } - } - if (!tag.getComponents()[1].isPrimal()) { - ta *= 1.1f; - if (!tag.getComponents()[1].getComponents()[0].isPrimal()) { - ta *= 1.05f; - } - if (!tag.getComponents()[1].getComponents()[1].isPrimal()) { - ta *= 1.05f; - } - } - } - - if (ta allAspects= new HashMap(); - private static HashMap allCompoundAspects= new HashMap(); - - public static AspectList getAllAspects(int amount) { - if (allAspects.get(amount)==null) { - AspectList al = new AspectList(); - for (Aspect aspect:Aspect.aspects.values()) { - al.add(aspect, amount); - } - allAspects.put(amount, al); - } - return allAspects.get(amount); - } - - public static AspectList getAllCompoundAspects(int amount) { - if (allCompoundAspects.get(amount)==null) { - AspectList al = new AspectList(); - for (Aspect aspect:Aspect.getCompoundAspects()) { - al.add(aspect, amount); - } - allCompoundAspects.put(amount, al); - } - return allCompoundAspects.get(amount); - } - - - /** - * Use to subtract vis from a wand for most operations - * Wands store vis differently so "real" vis costs need to be multiplied by 100 before calling this method - * @param wand the wand itemstack - * @param player the player using the wand - * @param cost the cost of the operation. - * @param doit actually subtract the vis from the wand if true - if false just simulate the result - * @param crafting is this a crafting operation or not - if - * false then things like frugal and potency will apply to the costs - * @return was the vis successfully subtracted - */ - public static boolean consumeVisFromWand(ItemStack wand, EntityPlayer player, - AspectList cost, boolean doit, boolean crafting) { - return ThaumcraftApi.internalMethods.consumeVisFromWand(wand, player, cost, doit, crafting); - } - - /** - * Subtract vis for use by a crafting mechanic. Costs are calculated slightly - * differently and things like the frugal enchant is ignored - * Must NOT be multiplied by 100 - send the actual vis cost - * @param wand the wand itemstack - * @param player the player using the wand - * @param cost the cost of the operation. - * @param doit actually subtract the vis from the wand if true - if false just simulate the result - * @return was the vis successfully subtracted - */ - public static boolean consumeVisFromWandCrafting(ItemStack wand, EntityPlayer player, - AspectList cost, boolean doit) { - return ThaumcraftApi.internalMethods.consumeVisFromWandCrafting(wand, player, cost, doit); - } - - /** - * Subtract vis from a wand the player is carrying. Works like consumeVisFromWand in that actual vis - * costs should be multiplied by 100. The costs are handled like crafting however and things like - * frugal don't effect them - * @param player the player using the wand - * @param cost the cost of the operation. - * @return was the vis successfully subtracted - */ - public static boolean consumeVisFromInventory(EntityPlayer player, AspectList cost) { - return ThaumcraftApi.internalMethods.consumeVisFromInventory(player, cost); - } - - - /** - * This adds permanents or temporary warp to a player. It will automatically be synced clientside - * @param player the player using the wand - * @param amount how much warp to add. Negative amounts are only valid for temporary warp - * @param temporary add temporary warp instead of permanent - */ - public static void addWarpToPlayer(EntityPlayer player, int amount, boolean temporary) { - ThaumcraftApi.internalMethods.addWarpToPlayer(player, amount, temporary); - } - - /** - * This "sticky" warp to a player. Sticky warp is permanent warp that can be removed. - * It will automatically be synced clientside - * @param player the player using the wand - * @param amount how much warp to add. Can have negative amounts. - */ - public static void addStickyWarpToPlayer(EntityPlayer player, int amount) { - ThaumcraftApi.internalMethods.addStickyWarpToPlayer(player, amount); - } - - public static MovingObjectPosition rayTraceIgnoringSource(World world, Vec3 v1, Vec3 v2, - boolean bool1, boolean bool2, boolean bool3) - { - if (!Double.isNaN(v1.xCoord) && !Double.isNaN(v1.yCoord) && !Double.isNaN(v1.zCoord)) - { - if (!Double.isNaN(v2.xCoord) && !Double.isNaN(v2.yCoord) && !Double.isNaN(v2.zCoord)) - { - int i = MathHelper.floor_double(v2.xCoord); - int j = MathHelper.floor_double(v2.yCoord); - int k = MathHelper.floor_double(v2.zCoord); - int l = MathHelper.floor_double(v1.xCoord); - int i1 = MathHelper.floor_double(v1.yCoord); - int j1 = MathHelper.floor_double(v1.zCoord); - Block block = world.getBlock(l, i1, j1); - int k1 = world.getBlockMetadata(l, i1, j1); - - MovingObjectPosition movingobjectposition2 = null; - k1 = 200; - - while (k1-- >= 0) - { - if (Double.isNaN(v1.xCoord) || Double.isNaN(v1.yCoord) || Double.isNaN(v1.zCoord)) - { - return null; - } - - if (l == i && i1 == j && j1 == k) - { - continue; - } - - boolean flag6 = true; - boolean flag3 = true; - boolean flag4 = true; - double d0 = 999.0D; - double d1 = 999.0D; - double d2 = 999.0D; - - if (i > l) - { - d0 = (double)l + 1.0D; - } - else if (i < l) - { - d0 = (double)l + 0.0D; - } - else - { - flag6 = false; - } - - if (j > i1) - { - d1 = (double)i1 + 1.0D; - } - else if (j < i1) - { - d1 = (double)i1 + 0.0D; - } - else - { - flag3 = false; - } - - if (k > j1) - { - d2 = (double)j1 + 1.0D; - } - else if (k < j1) - { - d2 = (double)j1 + 0.0D; - } - else - { - flag4 = false; - } - - double d3 = 999.0D; - double d4 = 999.0D; - double d5 = 999.0D; - double d6 = v2.xCoord - v1.xCoord; - double d7 = v2.yCoord - v1.yCoord; - double d8 = v2.zCoord - v1.zCoord; - - if (flag6) - { - d3 = (d0 - v1.xCoord) / d6; - } - - if (flag3) - { - d4 = (d1 - v1.yCoord) / d7; - } - - if (flag4) - { - d5 = (d2 - v1.zCoord) / d8; - } - - boolean flag5 = false; - byte b0; - - if (d3 < d4 && d3 < d5) - { - if (i > l) - { - b0 = 4; - } - else - { - b0 = 5; - } - - v1.xCoord = d0; - v1.yCoord += d7 * d3; - v1.zCoord += d8 * d3; - } - else if (d4 < d5) - { - if (j > i1) - { - b0 = 0; - } - else - { - b0 = 1; - } - - v1.xCoord += d6 * d4; - v1.yCoord = d1; - v1.zCoord += d8 * d4; - } - else - { - if (k > j1) - { - b0 = 2; - } - else - { - b0 = 3; - } - - v1.xCoord += d6 * d5; - v1.yCoord += d7 * d5; - v1.zCoord = d2; - } - - Vec3 vec32 = Vec3.createVectorHelper(v1.xCoord, v1.yCoord, v1.zCoord); - l = (int)(vec32.xCoord = (double)MathHelper.floor_double(v1.xCoord)); - - if (b0 == 5) - { - --l; - ++vec32.xCoord; - } - - i1 = (int)(vec32.yCoord = (double)MathHelper.floor_double(v1.yCoord)); - - if (b0 == 1) - { - --i1; - ++vec32.yCoord; - } - - j1 = (int)(vec32.zCoord = (double)MathHelper.floor_double(v1.zCoord)); - - if (b0 == 3) - { - --j1; - ++vec32.zCoord; - } - - Block block1 = world.getBlock(l, i1, j1); - int l1 = world.getBlockMetadata(l, i1, j1); - - if (!bool2 || block1.getCollisionBoundingBoxFromPool(world, l, i1, j1) != null) - { - if (block1.canCollideCheck(l1, bool1)) - { - MovingObjectPosition movingobjectposition1 = block1.collisionRayTrace(world, l, i1, j1, v1, v2); - - if (movingobjectposition1 != null) - { - return movingobjectposition1; - } - } - else - { - movingobjectposition2 = new MovingObjectPosition(l, i1, j1, b0, v1, false); - } - } - } - - return bool3 ? movingobjectposition2 : null; - } - else - { - return null; - } - } - else - { - return null; - } - } -} diff --git a/src/api/java/thaumcraft/api/TileThaumcraft.java b/src/api/java/thaumcraft/api/TileThaumcraft.java deleted file mode 100644 index 56ccae872..000000000 --- a/src/api/java/thaumcraft/api/TileThaumcraft.java +++ /dev/null @@ -1,63 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -import net.minecraft.tileentity.TileEntity; - -/** - * - * @author azanor - * - * Custom tile entity class I use for most of my tile entities. Setup in such a way that only - * the nbt data within readCustomNBT / writeCustomNBT will be sent to the client when the tile - * updates. Apart from all the normal TE data that gets sent that is. - * - */ -public class TileThaumcraft extends TileEntity { - - //NBT stuff - - @Override - public void readFromNBT(NBTTagCompound nbttagcompound) - { - super.readFromNBT(nbttagcompound); - readCustomNBT(nbttagcompound); - } - - public void readCustomNBT(NBTTagCompound nbttagcompound) - { - //TODO - } - - @Override - public void writeToNBT(NBTTagCompound nbttagcompound) - { - super.writeToNBT(nbttagcompound); - writeCustomNBT(nbttagcompound); - } - - public void writeCustomNBT(NBTTagCompound nbttagcompound) - { - //TODO - } - - //Client Packet stuff - @Override - public Packet getDescriptionPacket() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeCustomNBT(nbttagcompound); - return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, -999, nbttagcompound); - } - - @Override - public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { - super.onDataPacket(net, pkt); - this.readCustomNBT(pkt.func_148857_g()); - } - - - - -} diff --git a/src/api/java/thaumcraft/api/WorldCoordinates.java b/src/api/java/thaumcraft/api/WorldCoordinates.java deleted file mode 100644 index 6c620af5a..000000000 --- a/src/api/java/thaumcraft/api/WorldCoordinates.java +++ /dev/null @@ -1,117 +0,0 @@ -package thaumcraft.api; - -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; - -public class WorldCoordinates implements Comparable -{ - public int x; - - /** the y coordinate */ - public int y; - - /** the z coordinate */ - public int z; - - public int dim; - - public WorldCoordinates() {} - - public WorldCoordinates(int par1, int par2, int par3, int d) - { - this.x = par1; - this.y = par2; - this.z = par3; - this.dim = d; - } - - public WorldCoordinates(TileEntity tile) - { - this.x = tile.xCoord; - this.y = tile.yCoord; - this.z = tile.zCoord; - this.dim = tile.getWorldObj().provider.dimensionId; - } - - public WorldCoordinates(WorldCoordinates par1ChunkCoordinates) - { - this.x = par1ChunkCoordinates.x; - this.y = par1ChunkCoordinates.y; - this.z = par1ChunkCoordinates.z; - this.dim = par1ChunkCoordinates.dim; - } - - public boolean equals(Object par1Obj) - { - if (!(par1Obj instanceof WorldCoordinates)) - { - return false; - } - else - { - WorldCoordinates coordinates = (WorldCoordinates)par1Obj; - return this.x == coordinates.x && this.y == coordinates.y && this.z == coordinates.z && this.dim == coordinates.dim ; - } - } - - public int hashCode() - { - return this.x + this.y << 8 + this.z << 16 + this.dim << 24; - } - - /** - * Compare the coordinate with another coordinate - */ - public int compareWorldCoordinate(WorldCoordinates par1) - { - return this.dim == par1.dim ? ( - this.y == par1.y ? (this.z == par1.z ? this.x - par1.x : this.z - par1.z) : this.y - par1.y) : -1; - } - - public void set(int par1, int par2, int par3, int d) - { - this.x = par1; - this.y = par2; - this.z = par3; - this.dim = d; - } - - /** - * Returns the squared distance between this coordinates and the coordinates given as argument. - */ - public float getDistanceSquared(int par1, int par2, int par3) - { - float f = (float)(this.x - par1); - float f1 = (float)(this.y - par2); - float f2 = (float)(this.z - par3); - return f * f + f1 * f1 + f2 * f2; - } - - /** - * Return the squared distance between this coordinates and the ChunkCoordinates given as argument. - */ - public float getDistanceSquaredToWorldCoordinates(WorldCoordinates par1ChunkCoordinates) - { - return this.getDistanceSquared(par1ChunkCoordinates.x, par1ChunkCoordinates.y, par1ChunkCoordinates.z); - } - - public int compareTo(Object par1Obj) - { - return this.compareWorldCoordinate((WorldCoordinates)par1Obj); - } - - public void readNBT(NBTTagCompound nbt) { - this.x = nbt.getInteger("w_x"); - this.y = nbt.getInteger("w_y"); - this.z = nbt.getInteger("w_z"); - this.dim = nbt.getInteger("w_d"); - } - - public void writeNBT(NBTTagCompound nbt) { - nbt.setInteger("w_x",x); - nbt.setInteger("w_y",y); - nbt.setInteger("w_z",z); - nbt.setInteger("w_d",dim); - } - -} diff --git a/src/api/java/thaumcraft/api/aspects/Aspect.java b/src/api/java/thaumcraft/api/aspects/Aspect.java deleted file mode 100644 index 0ea13f5ec..000000000 --- a/src/api/java/thaumcraft/api/aspects/Aspect.java +++ /dev/null @@ -1,201 +0,0 @@ -package thaumcraft.api.aspects; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; - -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; - -import org.apache.commons.lang3.text.WordUtils; - -public class Aspect { - - String tag; - Aspect[] components; - int color; - private String chatcolor; - ResourceLocation image; - int blend; - - /** - * Use this constructor to register your own aspects. - * @param tag the key that will be used to reference this aspect, as well as its latin display name - * @param color color to display the tag in - * @param components the aspects this one is formed from - * @param image ResourceLocation pointing to a 32x32 icon of the aspect - * @param blend GL11 blendmode (1 or 771). Used for rendering nodes. Default is 1 - */ - public Aspect(String tag, int color, Aspect[] components, ResourceLocation image, int blend) { - if (aspects.containsKey(tag)) throw new IllegalArgumentException(tag+" already registered!"); - this.tag = tag; - this.components = components; - this.color = color; - this.image = image; - this.blend = blend; - aspects.put(tag, this); - } - - /** - * Shortcut constructor I use for the default aspects - you shouldn't be using this. - */ - public Aspect(String tag, int color, Aspect[] components) { - this(tag,color,components,new ResourceLocation("thaumcraft","textures/aspects/"+tag.toLowerCase()+".png"),1); - } - - /** - * Shortcut constructor I use for the default aspects - you shouldn't be using this. - */ - public Aspect(String tag, int color, Aspect[] components, int blend) { - this(tag,color,components,new ResourceLocation("thaumcraft","textures/aspects/"+tag.toLowerCase()+".png"),blend); - } - - /** - * Shortcut constructor I use for the primal aspects - - * you shouldn't use this as making your own primal aspects will break all the things. - */ - public Aspect(String tag, int color, String chatcolor, int blend) { - this(tag,color,(Aspect[])null, blend); - this.setChatcolor(chatcolor); - } - - public int getColor() { - return color; - } - - public String getName() { - return WordUtils.capitalizeFully(tag); - } - - public String getLocalizedDescription() { - return StatCollector.translateToLocal("tc.aspect."+tag); - } - - public String getTag() { - return tag; - } - - public void setTag(String tag) { - this.tag = tag; - } - - public Aspect[] getComponents() { - return components; - } - - public void setComponents(Aspect[] components) { - this.components = components; - } - - public ResourceLocation getImage() { - return image; - } - - public static Aspect getAspect(String tag) { - return aspects.get(tag); - } - - public int getBlend() { - return blend; - } - - public void setBlend(int blend) { - this.blend = blend; - } - - public boolean isPrimal() { - return getComponents()==null || getComponents().length!=2; - } - - /////////////////////////////// - public static ArrayList getPrimalAspects() { - ArrayList primals = new ArrayList(); - Collection pa = aspects.values(); - for (Aspect aspect:pa) { - if (aspect.isPrimal()) primals.add(aspect); - } - return primals; - } - - public static ArrayList getCompoundAspects() { - ArrayList compounds = new ArrayList(); - Collection pa = aspects.values(); - for (Aspect aspect:pa) { - if (!aspect.isPrimal()) compounds.add(aspect); - } - return compounds; - } - - public String getChatcolor() { - return chatcolor; - } - - public void setChatcolor(String chatcolor) { - this.chatcolor = chatcolor; - } - - - /////////////////////////////// - public static LinkedHashMap aspects = new LinkedHashMap(); - - //PRIMAL - public static final Aspect AIR = new Aspect("aer",0xffff7e,"e",1); - public static final Aspect EARTH = new Aspect("terra",0x56c000,"2",1); - public static final Aspect FIRE = new Aspect("ignis",0xff5a01,"c",1); - public static final Aspect WATER = new Aspect("aqua",0x3cd4fc,"3",1); - public static final Aspect ORDER = new Aspect("ordo",0xd5d4ec,"7",1); - public static final Aspect ENTROPY = new Aspect("perditio",0x404040,"8",771); - - //SECONDARY - public static final Aspect VOID = new Aspect("vacuos",0x888888, new Aspect[] {AIR, ENTROPY},771); - public static final Aspect LIGHT = new Aspect("lux",0xfff663, new Aspect[] {AIR, FIRE}); - public static final Aspect WEATHER = new Aspect("tempestas",0xFFFFFF, new Aspect[] {AIR, WATER}); - public static final Aspect MOTION = new Aspect("motus",0xcdccf4, new Aspect[] {AIR, ORDER}); - public static final Aspect COLD = new Aspect("gelum",0xe1ffff, new Aspect[] {FIRE, ENTROPY}); - public static final Aspect CRYSTAL = new Aspect("vitreus",0x80ffff, new Aspect[] {EARTH, ORDER}); - public static final Aspect LIFE = new Aspect("victus",0xde0005, new Aspect[] {WATER, EARTH}); - public static final Aspect POISON = new Aspect("venenum",0x89f000, new Aspect[] {WATER, ENTROPY}); - public static final Aspect ENERGY = new Aspect("potentia",0xc0ffff, new Aspect[] {ORDER, FIRE}); - public static final Aspect EXCHANGE = new Aspect("permutatio",0x578357, new Aspect[] {ENTROPY, ORDER}); -// public static final Aspect ?? = new Aspect("??",0xcdccf4, new Aspect[] {AIR, EARTH}); -// public static final Aspect ?? = new Aspect("??",0xcdccf4, new Aspect[] {FIRE, EARTH}); -// public static final Aspect ?? = new Aspect("??",0xcdccf4, new Aspect[] {FIRE, WATER}); -// public static final Aspect ?? = new Aspect("??",0xcdccf4, new Aspect[] {ORDER, WATER}); -// public static final Aspect ?? = new Aspect("??",0xcdccf4, new Aspect[] {EARTH, ENTROPY}); - - //TERTIARY - public static final Aspect METAL = new Aspect("metallum",0xb5b5cd, new Aspect[] {EARTH, CRYSTAL}); - public static final Aspect DEATH = new Aspect("mortuus",0x887788, new Aspect[] {LIFE, ENTROPY}); - public static final Aspect FLIGHT = new Aspect("volatus",0xe7e7d7, new Aspect[] {AIR, MOTION}); - public static final Aspect DARKNESS = new Aspect("tenebrae",0x222222, new Aspect[] {VOID, LIGHT}); - public static final Aspect SOUL = new Aspect("spiritus",0xebebfb, new Aspect[] {LIFE, DEATH}); - public static final Aspect HEAL = new Aspect("sano",0xff2f34, new Aspect[] {LIFE, ORDER}); - public static final Aspect TRAVEL = new Aspect("iter",0xe0585b, new Aspect[] {MOTION, EARTH}); - public static final Aspect ELDRITCH = new Aspect("alienis",0x805080, new Aspect[] {VOID, DARKNESS}); - public static final Aspect MAGIC = new Aspect("praecantatio",0x9700c0, new Aspect[] {VOID, ENERGY}); - public static final Aspect AURA = new Aspect("auram",0xffc0ff, new Aspect[] {MAGIC, AIR}); - public static final Aspect TAINT = new Aspect("vitium",0x800080, new Aspect[] {MAGIC, ENTROPY}); - public static final Aspect SLIME = new Aspect("limus",0x01f800, new Aspect[] {LIFE, WATER}); - public static final Aspect PLANT = new Aspect("herba",0x01ac00, new Aspect[] {LIFE, EARTH}); - public static final Aspect TREE = new Aspect("arbor",0x876531, new Aspect[] {AIR, PLANT}); - public static final Aspect BEAST = new Aspect("bestia",0x9f6409, new Aspect[] {MOTION, LIFE}); - public static final Aspect FLESH = new Aspect("corpus",0xee478d, new Aspect[] {DEATH, BEAST}); - public static final Aspect UNDEAD = new Aspect("exanimis",0x3a4000, new Aspect[] {MOTION, DEATH}); - public static final Aspect MIND = new Aspect("cognitio",0xffc2b3, new Aspect[] {FIRE, SOUL}); - public static final Aspect SENSES = new Aspect("sensus",0x0fd9ff, new Aspect[] {AIR, SOUL}); - public static final Aspect MAN = new Aspect("humanus",0xffd7c0, new Aspect[] {BEAST, MIND}); - public static final Aspect CROP = new Aspect("messis",0xe1b371, new Aspect[] {PLANT, MAN}); - public static final Aspect MINE = new Aspect("perfodio",0xdcd2d8, new Aspect[] {MAN, EARTH}); - public static final Aspect TOOL = new Aspect("instrumentum",0x4040ee, new Aspect[] {MAN, ORDER}); - public static final Aspect HARVEST = new Aspect("meto",0xeead82, new Aspect[] {CROP, TOOL}); - public static final Aspect WEAPON = new Aspect("telum",0xc05050, new Aspect[] {TOOL, FIRE}); - public static final Aspect ARMOR = new Aspect("tutamen",0x00c0c0, new Aspect[] {TOOL, EARTH}); - public static final Aspect HUNGER = new Aspect("fames",0x9a0305, new Aspect[] {LIFE, VOID}); - public static final Aspect GREED = new Aspect("lucrum",0xe6be44, new Aspect[] {MAN, HUNGER}); - public static final Aspect CRAFT = new Aspect("fabrico",0x809d80, new Aspect[] {MAN, TOOL}); - public static final Aspect CLOTH = new Aspect("pannus",0xeaeac2, new Aspect[] {TOOL, BEAST}); - public static final Aspect MECHANISM = new Aspect("machina",0x8080a0, new Aspect[] {MOTION, TOOL}); - public static final Aspect TRAP = new Aspect("vinculum",0x9a8080, new Aspect[] {MOTION, ENTROPY}); - - -} diff --git a/src/api/java/thaumcraft/api/aspects/AspectList.java b/src/api/java/thaumcraft/api/aspects/AspectList.java deleted file mode 100644 index b57814104..000000000 --- a/src/api/java/thaumcraft/api/aspects/AspectList.java +++ /dev/null @@ -1,292 +0,0 @@ -package thaumcraft.api.aspects; - -import java.io.Serializable; -import java.util.LinkedHashMap; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import thaumcraft.api.ThaumcraftApiHelper; - -public class AspectList implements Serializable { - - public LinkedHashMap aspects = new LinkedHashMap();//aspects associated with this object - - - /** - * this creates a new aspect list with preloaded values based off the aspects of the given item. - * @param the itemstack of the given item - */ - public AspectList(ItemStack stack) { - try { - AspectList temp = ThaumcraftApiHelper.getObjectAspects(stack); - if (temp!=null) - for (Aspect tag:temp.getAspects()) { - add(tag,temp.getAmount(tag)); - } - } catch (Exception e) {} - } - - public AspectList() { - } - - public AspectList copy() { - AspectList out = new AspectList(); - for (Aspect a:this.getAspects()) - out.add(a, this.getAmount(a)); - return out; - } - - /** - * @return the amount of different aspects in this collection - */ - public int size() { - return aspects.size(); - } - - /** - * @return the amount of total vis in this collection - */ - public int visSize() { - int q = 0; - - for (Aspect as:aspects.keySet()) { - q+=this.getAmount(as); - } - - return q; - } - - /** - * @return an array of all the aspects in this collection - */ - public Aspect[] getAspects() { - Aspect[] q = new Aspect[1]; - return aspects.keySet().toArray(q); - } - - /** - * @return an array of all the aspects in this collection - */ - public Aspect[] getPrimalAspects() { - AspectList t = new AspectList(); - for (Aspect as:aspects.keySet()) { - if (as.isPrimal()) { - t.add(as,1); - } - } - Aspect[] q = new Aspect[1]; - return t.aspects.keySet().toArray(q); - } - - /** - * @return an array of all the aspects in this collection sorted by name - */ - public Aspect[] getAspectsSorted() { - try { - Aspect[] out = aspects.keySet().toArray(new Aspect[]{}); - boolean change=false; - do { - change=false; - for(int a=0;a0) { - out[a] = e2; - out[a+1] = e1; - change = true; - break; - } - } - } while (change==true); - return out; - } catch (Exception e) { - return this.getAspects(); - } - } - - /** - * @return an array of all the aspects in this collection sorted by amount - */ - public Aspect[] getAspectsSortedAmount() { - try { - Aspect[] out = aspects.keySet().toArray(new Aspect[1]); - boolean change=false; - do { - change=false; - for(int a=0;a0 && e2>0 && e2>e1) { - Aspect ea = out[a]; - Aspect eb = out[a+1]; - out[a] = eb; - out[a+1] = ea; - change = true; - break; - } - } - } while (change==true); - return out; - } catch (Exception e) { - return this.getAspects(); - } - } - - /** - * @param key - * @return the amount associated with the given aspect in this collection - */ - public int getAmount(Aspect key) { - return aspects.get(key)==null?0:aspects.get(key); - } - - /** - * Reduces the amount of an aspect in this collection by the given amount. - * @param key - * @param amount - * @return - */ - public boolean reduce(Aspect key, int amount) { - if (getAmount(key)>=amount) { - int am = getAmount(key)-amount; - aspects.put(key, am); - return true; - } - return false; - } - - /** - * Reduces the amount of an aspect in this collection by the given amount. - * If reduced to 0 or less the aspect will be removed completely. - * @param key - * @param amount - * @return - */ - public AspectList remove(Aspect key, int amount) { - int am = getAmount(key)-amount; - if (am<=0) aspects.remove(key); else - this.aspects.put(key, am); - return this; - } - - /** - * Simply removes the aspect from the list - * @param key - * @param amount - * @return - */ - public AspectList remove(Aspect key) { - aspects.remove(key); - return this; - } - - /** - * Adds this aspect and amount to the collection. - * If the aspect exists then its value will be increased by the given amount. - * @param aspect - * @param amount - * @return - */ - public AspectList add(Aspect aspect, int amount) { - if (this.aspects.containsKey(aspect)) { - int oldamount = this.aspects.get(aspect); - amount+=oldamount; - } - this.aspects.put( aspect, amount ); - return this; - } - - - /** - * Adds this aspect and amount to the collection. - * If the aspect exists then only the highest of the old or new amount will be used. - * @param aspect - * @param amount - * @return - */ - public AspectList merge(Aspect aspect, int amount) { - if (this.aspects.containsKey(aspect)) { - int oldamount = this.aspects.get(aspect); - if (amount0?aspects:null; - } - return null; - } - - @Override - public void setAspects(ItemStack itemstack, AspectList aspects) { - if (!itemstack.hasTagCompound()) itemstack.setTagCompound(new NBTTagCompound()); - aspects.writeToNBT(itemstack.getTagCompound()); - } -*/ \ No newline at end of file diff --git a/src/api/java/thaumcraft/api/aspects/IEssentiaTransport.java b/src/api/java/thaumcraft/api/aspects/IEssentiaTransport.java deleted file mode 100644 index fecbc1608..000000000 --- a/src/api/java/thaumcraft/api/aspects/IEssentiaTransport.java +++ /dev/null @@ -1,100 +0,0 @@ -package thaumcraft.api.aspects; - -import net.minecraftforge.common.util.ForgeDirection; - - -/** - * @author Azanor - * This interface is used by tiles that use or transport vis. - * Only tiles that implement this interface will be able to connect to vis conduits or other thaumic devices - */ -public interface IEssentiaTransport { - /** - * Is this tile able to connect to other vis users/sources on the specified side? - * @param face - * @return - */ - public boolean isConnectable(ForgeDirection face); - - /** - * Is this side used to input essentia? - * @param face - * @return - */ - boolean canInputFrom(ForgeDirection face); - - /** - * Is this side used to output essentia? - * @param face - * @return - */ - boolean canOutputTo(ForgeDirection face); - - /** - * Sets the amount of suction this block will apply - * @param suction - */ - public void setSuction(Aspect aspect, int amount); - - /** - * Returns the type of suction this block is applying. - * @param loc - * the location from where the suction is being checked - * @return - * a return type of null indicates the suction is untyped and the first thing available will be drawn - */ - public Aspect getSuctionType(ForgeDirection face); - - /** - * Returns the strength of suction this block is applying. - * @param loc - * the location from where the suction is being checked - * @return - */ - public int getSuctionAmount(ForgeDirection face); - - /** - * remove the specified amount of essentia from this transport tile - * @return how much was actually taken - */ - public int takeEssentia(Aspect aspect, int amount, ForgeDirection face); - - /** - * add the specified amount of essentia to this transport tile - * @return how much was actually added - */ - public int addEssentia(Aspect aspect, int amount, ForgeDirection face); - - /** - * What type of essentia this contains - * @param face - * @return - */ - public Aspect getEssentiaType(ForgeDirection face); - - /** - * How much essentia this block contains - * @param face - * @return - */ - public int getEssentiaAmount(ForgeDirection face); - - - - /** - * Essentia will not be drawn from this container unless the suction exceeds this amount. - * @return the amount - */ - public int getMinimumSuction(); - - /** - * Return true if you want the conduit to extend a little further into the block. - * Used by jars and alembics that have smaller than normal hitboxes - * @return - */ - boolean renderExtendedTube(); - - - -} - diff --git a/src/api/java/thaumcraft/api/crafting/CrucibleRecipe.java b/src/api/java/thaumcraft/api/crafting/CrucibleRecipe.java deleted file mode 100644 index 595b6e53c..000000000 --- a/src/api/java/thaumcraft/api/crafting/CrucibleRecipe.java +++ /dev/null @@ -1,91 +0,0 @@ -package thaumcraft.api.crafting; - -import java.util.ArrayList; - -import net.minecraft.item.ItemStack; -import net.minecraftforge.oredict.OreDictionary; -import thaumcraft.api.ThaumcraftApiHelper; -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; - -public class CrucibleRecipe { - - private ItemStack recipeOutput; - - public Object catalyst; - public AspectList aspects; - public String key; - - public int hash; - - public CrucibleRecipe(String researchKey, ItemStack result, Object cat, AspectList tags) { - recipeOutput = result; - this.aspects = tags; - this.key = researchKey; - this.catalyst = cat; - if (cat instanceof String) { - this.catalyst = OreDictionary.getOres((String) cat); - } - String hc = researchKey + result.toString(); - for (Aspect tag:tags.getAspects()) { - hc += tag.getTag()+tags.getAmount(tag); - } - if (cat instanceof ItemStack) { - hc += ((ItemStack)cat).toString(); - } else - if (cat instanceof ArrayList && ((ArrayList)catalyst).size()>0) { - for (ItemStack is :(ArrayList)catalyst) { - hc += is.toString(); - } - } - - hash = hc.hashCode(); - } - - - - public boolean matches(AspectList itags, ItemStack cat) { - if (catalyst instanceof ItemStack && - !ThaumcraftApiHelper.itemMatches((ItemStack) catalyst,cat,false)) { - return false; - } else - if (catalyst instanceof ArrayList && ((ArrayList)catalyst).size()>0) { - ItemStack[] ores = ((ArrayList)catalyst).toArray(new ItemStack[]{}); - if (!ThaumcraftApiHelper.containsMatch(false, new ItemStack[]{cat},ores)) return false; - } - if (itags==null) return false; - for (Aspect tag:aspects.getAspects()) { - if (itags.getAmount(tag))catalyst).size()>0) { - ItemStack[] ores = ((ArrayList)catalyst).toArray(new ItemStack[]{}); - if (ThaumcraftApiHelper.containsMatch(false, new ItemStack[]{cat},ores)) return true; - } - return false; - } - - public AspectList removeMatching(AspectList itags) { - AspectList temptags = new AspectList(); - temptags.aspects.putAll(itags.aspects); - - for (Aspect tag:aspects.getAspects()) { - temptags.remove(tag, aspects.getAmount(tag)); - } - - itags = temptags; - return itags; - } - - public ItemStack getRecipeOutput() { - return recipeOutput; - } - - -} diff --git a/src/api/java/thaumcraft/api/crafting/IArcaneRecipe.java b/src/api/java/thaumcraft/api/crafting/IArcaneRecipe.java deleted file mode 100644 index bb5036d20..000000000 --- a/src/api/java/thaumcraft/api/crafting/IArcaneRecipe.java +++ /dev/null @@ -1,35 +0,0 @@ -package thaumcraft.api.crafting; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import thaumcraft.api.aspects.AspectList; - -public interface IArcaneRecipe -{ - - - /** - * Used to check if a recipe matches current crafting inventory - * @param player - */ - boolean matches(IInventory var1, World world, EntityPlayer player); - - /** - * Returns an Item that is the result of this recipe - */ - ItemStack getCraftingResult(IInventory var1); - - /** - * Returns the size of the recipe area - */ - int getRecipeSize(); - - ItemStack getRecipeOutput(); - AspectList getAspects(); - AspectList getAspects(IInventory var1); - String getResearch(); - - -} diff --git a/src/api/java/thaumcraft/api/crafting/IInfusionStabiliser.java b/src/api/java/thaumcraft/api/crafting/IInfusionStabiliser.java deleted file mode 100644 index d137ff24e..000000000 --- a/src/api/java/thaumcraft/api/crafting/IInfusionStabiliser.java +++ /dev/null @@ -1,19 +0,0 @@ -package thaumcraft.api.crafting; - -import net.minecraft.world.World; - -/** - * - * @author Azanor - * - * Blocks that implement this interface act as infusion crafting stabilisers like candles and skulls - * - */ -public interface IInfusionStabiliser { - - /** - * returns true if the block can stabilise things - */ - public boolean canStabaliseInfusion(World world, int x, int y, int z); - -} diff --git a/src/api/java/thaumcraft/api/crafting/InfusionEnchantmentRecipe.java b/src/api/java/thaumcraft/api/crafting/InfusionEnchantmentRecipe.java deleted file mode 100644 index bdc5f5053..000000000 --- a/src/api/java/thaumcraft/api/crafting/InfusionEnchantmentRecipe.java +++ /dev/null @@ -1,154 +0,0 @@ -package thaumcraft.api.crafting; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; - -import net.minecraft.enchantment.Enchantment; -import net.minecraft.enchantment.EnchantmentHelper; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraftforge.oredict.OreDictionary; -import thaumcraft.api.ThaumcraftApiHelper; -import thaumcraft.api.aspects.AspectList; - -public class InfusionEnchantmentRecipe -{ - - public AspectList aspects; - public String research; - public ItemStack[] components; - public Enchantment enchantment; - public int recipeXP; - public int instability; - - public InfusionEnchantmentRecipe(String research, Enchantment input, int inst, - AspectList aspects2, ItemStack[] recipe) { - this.research = research; - this.enchantment = input; - this.aspects = aspects2; - this.components = recipe; - this.instability = inst; - this.recipeXP = Math.max(1, input.getMinEnchantability(1)/3); - } - - /** - * Used to check if a recipe matches current crafting inventory - * @param player - */ - public boolean matches(ArrayList input, ItemStack central, World world, EntityPlayer player) { - if (research.length()>0 && !ThaumcraftApiHelper.isResearchComplete(player.getCommandSenderName(), research)) { - return false; - } - - if (!enchantment.canApply(central) || !central.getItem().isItemTool(central)) { - return false; - } - - Map map1 = EnchantmentHelper.getEnchantments(central); - Iterator iterator = map1.keySet().iterator(); - while (iterator.hasNext()) - { - int j1 = ((Integer)iterator.next()).intValue(); - Enchantment ench = Enchantment.enchantmentsList[j1]; - if (j1 == enchantment.effectId && - EnchantmentHelper.getEnchantmentLevel(j1, central)>=ench.getMaxLevel()) - return false; - if (enchantment.effectId != ench.effectId && - (!enchantment.canApplyTogether(ench) || - !ench.canApplyTogether(enchantment))) { - return false; - } - } - - ItemStack i2 = null; - - ArrayList ii = new ArrayList(); - for (ItemStack is:input) { - ii.add(is.copy()); - } - - for (ItemStack comp:components) { - boolean b=false; - for (int a=0;a input, ItemStack central, World world, EntityPlayer player) { - if (getRecipeInput()==null) return false; - - if (research.length()>0 && !ThaumcraftApiHelper.isResearchComplete(player.getCommandSenderName(), research)) { - return false; - } - - ItemStack i2 = central.copy(); - if (getRecipeInput().getItemDamage()==OreDictionary.WILDCARD_VALUE) { - i2.setItemDamage(OreDictionary.WILDCARD_VALUE); - } - - if (!areItemStacksEqual(i2, getRecipeInput(), true)) return false; - - ArrayList ii = new ArrayList(); - for (ItemStack is:input) { - ii.add(is.copy()); - } - - for (ItemStack comp:getComponents()) { - boolean b=false; - for (int a=0;a itemMap = new HashMap(); - - for (; idx < recipe.length; idx += 2) - { - Character chr = (Character)recipe[idx]; - Object in = recipe[idx + 1]; - - if (in instanceof ItemStack) - { - itemMap.put(chr, ((ItemStack)in).copy()); - } - else if (in instanceof Item) - { - itemMap.put(chr, new ItemStack((Item)in)); - } - else if (in instanceof Block) - { - itemMap.put(chr, new ItemStack((Block)in, 1, OreDictionary.WILDCARD_VALUE)); - } - else if (in instanceof String) - { - itemMap.put(chr, OreDictionary.getOres((String)in)); - } - else - { - String ret = "Invalid shaped ore recipe: "; - for (Object tmp : recipe) - { - ret += tmp + ", "; - } - ret += output; - throw new RuntimeException(ret); - } - } - - input = new Object[width * height]; - int x = 0; - for (char chr : shape.toCharArray()) - { - input[x++] = itemMap.get(chr); - } - } - - @Override - public ItemStack getCraftingResult(IInventory var1){ return output.copy(); } - - @Override - public int getRecipeSize(){ return input.length; } - - @Override - public ItemStack getRecipeOutput(){ return output; } - - @Override - public boolean matches(IInventory inv, World world, EntityPlayer player) - { - if (research.length()>0 && !ThaumcraftApiHelper.isResearchComplete(player.getCommandSenderName(), research)) { - return false; - } - for (int x = 0; x <= MAX_CRAFT_GRID_WIDTH - width; x++) - { - for (int y = 0; y <= MAX_CRAFT_GRID_HEIGHT - height; ++y) - { - if (checkMatch(inv, x, y, false)) - { - return true; - } - - if (mirrored && checkMatch(inv, x, y, true)) - { - return true; - } - } - } - - return false; - } - - private boolean checkMatch(IInventory inv, int startX, int startY, boolean mirror) - { - for (int x = 0; x < MAX_CRAFT_GRID_WIDTH; x++) - { - for (int y = 0; y < MAX_CRAFT_GRID_HEIGHT; y++) - { - int subX = x - startX; - int subY = y - startY; - Object target = null; - - if (subX >= 0 && subY >= 0 && subX < width && subY < height) - { - if (mirror) - { - target = input[width - subX - 1 + subY * width]; - } - else - { - target = input[subX + subY * width]; - } - } - - ItemStack slot = ThaumcraftApiHelper.getStackInRowAndColumn(inv, x, y); - - if (target instanceof ItemStack) - { - if (!checkItemEquals((ItemStack)target, slot)) - { - return false; - } - } - else if (target instanceof ArrayList) - { - boolean matched = false; - - for (ItemStack item : (ArrayList)target) - { - matched = matched || checkItemEquals(item, slot); - } - - if (!matched) - { - return false; - } - } - else if (target == null && slot != null) - { - return false; - } - } - } - - return true; - } - - private boolean checkItemEquals(ItemStack target, ItemStack input) - { - if (input == null && target != null || input != null && target == null) - { - return false; - } - return (target.getItem() == input.getItem() && - (!target.hasTagCompound() || ThaumcraftApiHelper.areItemStackTagsEqualForCrafting(input,target)) && - (target.getItemDamage() == OreDictionary.WILDCARD_VALUE|| target.getItemDamage() == input.getItemDamage())); - } - - public ShapedArcaneRecipe setMirrored(boolean mirror) - { - mirrored = mirror; - return this; - } - - /** - * 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; - } - - @Override - public AspectList getAspects() { - return aspects; - } - - @Override - public AspectList getAspects(IInventory inv) { - return aspects; - } - - @Override - public String getResearch() { - return research; - } -} diff --git a/src/api/java/thaumcraft/api/crafting/ShapelessArcaneRecipe.java b/src/api/java/thaumcraft/api/crafting/ShapelessArcaneRecipe.java deleted file mode 100644 index 3b1eaeb80..000000000 --- a/src/api/java/thaumcraft/api/crafting/ShapelessArcaneRecipe.java +++ /dev/null @@ -1,161 +0,0 @@ -package thaumcraft.api.crafting; - -import java.util.ArrayList; -import java.util.Iterator; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; -import net.minecraftforge.oredict.OreDictionary; -import thaumcraft.api.ThaumcraftApiHelper; -import thaumcraft.api.aspects.AspectList; - -public class ShapelessArcaneRecipe implements IArcaneRecipe -{ - private ItemStack output = null; - private ArrayList input = new ArrayList(); - - public AspectList aspects = null; - public String research; - - public ShapelessArcaneRecipe(String research, Block result, AspectList aspects, Object... recipe){ this(research,new ItemStack(result),aspects, recipe); } - public ShapelessArcaneRecipe(String research, Item result, AspectList aspects, Object... recipe){ this(research,new ItemStack(result),aspects, recipe); } - - public ShapelessArcaneRecipe(String research, ItemStack result, AspectList aspects, Object... recipe) - { - output = result.copy(); - this.research = research; - this.aspects = aspects; - for (Object in : recipe) - { - if (in instanceof ItemStack) - { - input.add(((ItemStack)in).copy()); - } - else if (in instanceof Item) - { - input.add(new ItemStack((Item)in)); - } - else if (in instanceof Block) - { - input.add(new ItemStack((Block)in)); - } - else if (in instanceof String) - { - input.add(OreDictionary.getOres((String)in)); - } - else - { - String ret = "Invalid shapeless ore recipe: "; - for (Object tmp : recipe) - { - ret += tmp + ", "; - } - ret += output; - throw new RuntimeException(ret); - } - } - } - - @Override - public int getRecipeSize(){ return input.size(); } - - @Override - public ItemStack getRecipeOutput(){ return output; } - - @Override - public ItemStack getCraftingResult(IInventory var1){ return output.copy(); } - - @Override - public boolean matches(IInventory var1, World world, EntityPlayer player) - { - if (research.length()>0 && !ThaumcraftApiHelper.isResearchComplete(player.getCommandSenderName(), research)) { - return false; - } - - ArrayList required = new ArrayList(input); - - for (int x = 0; x < 9; x++) - { - ItemStack slot = var1.getStackInSlot(x); - - if (slot != null) - { - boolean inRecipe = false; - Iterator req = required.iterator(); - - while (req.hasNext()) - { - boolean match = false; - - Object next = req.next(); - - if (next instanceof ItemStack) - { - match = checkItemEquals((ItemStack)next, slot); - } - else if (next instanceof ArrayList) - { - for (ItemStack item : (ArrayList)next) - { - match = match || checkItemEquals(item, slot); - } - } - - if (match) - { - inRecipe = true; - required.remove(next); - break; - } - } - - if (!inRecipe) - { - return false; - } - } - } - - return required.isEmpty(); - } - - private boolean checkItemEquals(ItemStack target, ItemStack input) - { - if (input == null && target != null || input != null && target == null) - { - return false; - } - return (target.getItem() == input.getItem() && - (!target.hasTagCompound() || ThaumcraftApiHelper.areItemStackTagsEqualForCrafting(input,target)) && - (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 AspectList getAspects() { - return aspects; - } - - @Override - public AspectList getAspects(IInventory inv) { - return aspects; - } - - @Override - public String getResearch() { - return research; - } -} diff --git a/src/api/java/thaumcraft/api/damagesource/DamageSourceIndirectThaumcraftEntity.java b/src/api/java/thaumcraft/api/damagesource/DamageSourceIndirectThaumcraftEntity.java deleted file mode 100644 index 1562d052f..000000000 --- a/src/api/java/thaumcraft/api/damagesource/DamageSourceIndirectThaumcraftEntity.java +++ /dev/null @@ -1,32 +0,0 @@ -package thaumcraft.api.damagesource; - -import net.minecraft.entity.Entity; -import net.minecraft.util.DamageSource; -import net.minecraft.util.EntityDamageSourceIndirect; - -public class DamageSourceIndirectThaumcraftEntity extends EntityDamageSourceIndirect { - - private boolean fireDamage; - private float hungerDamage; - private boolean isUnblockable; - - - public DamageSourceIndirectThaumcraftEntity(String par1Str, - Entity par2Entity, Entity par3Entity) { - super(par1Str, par2Entity, par3Entity); - } - - - public DamageSource setFireDamage() - { - this.fireDamage = true; - return this; - } - - public DamageSource setDamageBypassesArmor() - { - this.isUnblockable = true; - this.hungerDamage = 0.0F; - return this; - } -} diff --git a/src/api/java/thaumcraft/api/damagesource/DamageSourceThaumcraft.java b/src/api/java/thaumcraft/api/damagesource/DamageSourceThaumcraft.java deleted file mode 100644 index bb55672b7..000000000 --- a/src/api/java/thaumcraft/api/damagesource/DamageSourceThaumcraft.java +++ /dev/null @@ -1,47 +0,0 @@ -package thaumcraft.api.damagesource; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.util.DamageSource; -import net.minecraft.util.EntityDamageSource; - -public class DamageSourceThaumcraft extends DamageSource -{ - - public static DamageSource taint = new DamageSourceThaumcraft("taint").setDamageBypassesArmor().setMagicDamage(); - public static DamageSource tentacle = new DamageSourceThaumcraft("tentacle"); - public static DamageSource swarm = new DamageSourceThaumcraft("swarm"); - public static DamageSource dissolve = new DamageSourceThaumcraft("dissolve").setDamageBypassesArmor(); - - protected DamageSourceThaumcraft(String par1Str) { - super(par1Str); - } - - /** This kind of damage can be blocked or not. */ - private boolean isUnblockable = false; - private boolean isDamageAllowedInCreativeMode = false; - private float hungerDamage = 0.3F; - - /** This kind of damage is based on fire or not. */ - private boolean fireDamage; - - /** This kind of damage is based on a projectile or not. */ - private boolean projectile; - - /** - * Whether this damage source will have its damage amount scaled based on the current difficulty. - */ - private boolean difficultyScaled; - private boolean magicDamage = false; - private boolean explosion = false; - - public static DamageSource causeSwarmDamage(EntityLivingBase par0EntityLiving) - { - return new EntityDamageSource("swarm", par0EntityLiving); - } - - public static DamageSource causeTentacleDamage(EntityLivingBase par0EntityLiving) - { - return new EntityDamageSource("tentacle", par0EntityLiving); - } - -} diff --git a/src/api/java/thaumcraft/api/entities/IEldritchMob.java b/src/api/java/thaumcraft/api/entities/IEldritchMob.java deleted file mode 100644 index 79fc75b57..000000000 --- a/src/api/java/thaumcraft/api/entities/IEldritchMob.java +++ /dev/null @@ -1,5 +0,0 @@ -package thaumcraft.api.entities; - -public interface IEldritchMob { - -} diff --git a/src/api/java/thaumcraft/api/entities/ITaintedMob.java b/src/api/java/thaumcraft/api/entities/ITaintedMob.java deleted file mode 100644 index 83fb1fcbd..000000000 --- a/src/api/java/thaumcraft/api/entities/ITaintedMob.java +++ /dev/null @@ -1,5 +0,0 @@ -package thaumcraft.api.entities; - -public interface ITaintedMob { - -} diff --git a/src/api/java/thaumcraft/api/internal/DummyInternalMethodHandler.java b/src/api/java/thaumcraft/api/internal/DummyInternalMethodHandler.java deleted file mode 100644 index 9af8c30e1..000000000 --- a/src/api/java/thaumcraft/api/internal/DummyInternalMethodHandler.java +++ /dev/null @@ -1,78 +0,0 @@ -package thaumcraft.api.internal; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; - -public class DummyInternalMethodHandler implements IInternalMethodHandler { - - @Override - public void generateVisEffect(int dim, int x, int y, int z, int x2, int y2, int z2, int color) { - - } - - @Override - public boolean isResearchComplete(String username, String researchkey) { - return false; - } - - @Override - public boolean hasDiscoveredAspect(String username, Aspect aspect) { - return false; - } - - @Override - public AspectList getDiscoveredAspects(String username) { - return null; - } - - @Override - public ItemStack getStackInRowAndColumn(Object instance, int row, int column) { - return null; - } - - @Override - public AspectList getObjectAspects(ItemStack is) { - return null; - } - - @Override - public AspectList getBonusObjectTags(ItemStack is, AspectList ot) { - return null; - } - - @Override - public AspectList generateTags(Item item, int meta) { - return null; - } - - @Override - public boolean consumeVisFromWand(ItemStack wand, EntityPlayer player, - AspectList cost, boolean doit, boolean crafting) { - return false; - } - - @Override - public boolean consumeVisFromWandCrafting(ItemStack wand, - EntityPlayer player, AspectList cost, boolean doit) { - return false; - } - - @Override - public boolean consumeVisFromInventory(EntityPlayer player, AspectList cost) { - return false; - } - - @Override - public void addWarpToPlayer(EntityPlayer player, int amount, boolean temporary) { - } - - @Override - public void addStickyWarpToPlayer(EntityPlayer player, int amount) { - } - - - -} diff --git a/src/api/java/thaumcraft/api/internal/IInternalMethodHandler.java b/src/api/java/thaumcraft/api/internal/IInternalMethodHandler.java deleted file mode 100644 index 73fce669e..000000000 --- a/src/api/java/thaumcraft/api/internal/IInternalMethodHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package thaumcraft.api.internal; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; - -public interface IInternalMethodHandler { - - public void generateVisEffect(int dim, int x, int y, int z, int x2, int y2, int z2, int color); - public boolean isResearchComplete(String username, String researchkey); - public ItemStack getStackInRowAndColumn(Object instance, int row, int column); - public AspectList getObjectAspects(ItemStack is); - public AspectList getBonusObjectTags(ItemStack is,AspectList ot); - public AspectList generateTags(Item item, int meta); - public boolean consumeVisFromWand(ItemStack wand, EntityPlayer player, AspectList cost, boolean doit, boolean crafting); - public boolean consumeVisFromWandCrafting(ItemStack wand,EntityPlayer player, AspectList cost, boolean doit); - public boolean consumeVisFromInventory(EntityPlayer player, AspectList cost); - public void addWarpToPlayer(EntityPlayer player, int amount,boolean temporary); - public void addStickyWarpToPlayer(EntityPlayer player, int amount); - public boolean hasDiscoveredAspect(String username, Aspect aspect); - public AspectList getDiscoveredAspects(String username); - -} diff --git a/src/api/java/thaumcraft/api/internal/WeightedRandomLoot.java b/src/api/java/thaumcraft/api/internal/WeightedRandomLoot.java deleted file mode 100644 index 4ac6ee7d9..000000000 --- a/src/api/java/thaumcraft/api/internal/WeightedRandomLoot.java +++ /dev/null @@ -1,24 +0,0 @@ -package thaumcraft.api.internal; - -import java.util.ArrayList; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.WeightedRandom; - - -public class WeightedRandomLoot extends WeightedRandom.Item { - - /** The Item/Block ID to generate in the bag. */ - public ItemStack item; - - public WeightedRandomLoot(ItemStack stack, int weight) - { - super(weight); - this.item = stack; - } - - public static ArrayList lootBagCommon = new ArrayList(); - public static ArrayList lootBagUncommon = new ArrayList(); - public static ArrayList lootBagRare = new ArrayList(); - -} diff --git a/src/api/java/thaumcraft/api/nodes/INode.java b/src/api/java/thaumcraft/api/nodes/INode.java deleted file mode 100644 index 61da1f77a..000000000 --- a/src/api/java/thaumcraft/api/nodes/INode.java +++ /dev/null @@ -1,53 +0,0 @@ -package thaumcraft.api.nodes; - -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; -import thaumcraft.api.aspects.IAspectContainer; - -public interface INode extends IAspectContainer { - - /** - * Unique identifier to distinguish nodes. Normal node id's are based on world id and coordinates - * @return - */ - public String getId(); - - public AspectList getAspectsBase(); - - /** - * Return the type of node - * @return - */ - public NodeType getNodeType(); - - /** - * Set the type of node - * @return - */ - public void setNodeType(NodeType nodeType); - - /** - * Set the node modifier - * @return - */ - public void setNodeModifier(NodeModifier nodeModifier); - - /** - * Return the node modifier - * @return - */ - public NodeModifier getNodeModifier(); - - /** - * Return the maximum capacity of each aspect the node can hold - * @return - */ - public int getNodeVisBase(Aspect aspect); - - /** - * Set the maximum capacity of each aspect the node can hold - * @return - */ - public void setNodeVisBase(Aspect aspect, short nodeVisBase); - -} diff --git a/src/api/java/thaumcraft/api/nodes/IRevealer.java b/src/api/java/thaumcraft/api/nodes/IRevealer.java deleted file mode 100644 index 14a19b54d..000000000 --- a/src/api/java/thaumcraft/api/nodes/IRevealer.java +++ /dev/null @@ -1,22 +0,0 @@ -package thaumcraft.api.nodes; - -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.item.ItemStack; - -/** - * - * @author Azanor - * - * Equipped head slot items that extend this class will make nodes visible in world. - * - */ - -public interface IRevealer { - - /* - * If this method returns true the nodes will be visible. - */ - public boolean showNodes(ItemStack itemstack, EntityLivingBase player); - - -} diff --git a/src/api/java/thaumcraft/api/nodes/NodeModifier.java b/src/api/java/thaumcraft/api/nodes/NodeModifier.java deleted file mode 100644 index 885b8678a..000000000 --- a/src/api/java/thaumcraft/api/nodes/NodeModifier.java +++ /dev/null @@ -1,6 +0,0 @@ -package thaumcraft.api.nodes; - -public enum NodeModifier -{ - BRIGHT, PALE, FADING -} \ No newline at end of file diff --git a/src/api/java/thaumcraft/api/nodes/NodeType.java b/src/api/java/thaumcraft/api/nodes/NodeType.java deleted file mode 100644 index 355324b51..000000000 --- a/src/api/java/thaumcraft/api/nodes/NodeType.java +++ /dev/null @@ -1,6 +0,0 @@ -package thaumcraft.api.nodes; - -public enum NodeType -{ - NORMAL, UNSTABLE, DARK, TAINTED, HUNGRY, PURE -} \ No newline at end of file diff --git a/src/api/java/thaumcraft/api/package-info.java b/src/api/java/thaumcraft/api/package-info.java deleted file mode 100644 index cceaf891f..000000000 --- a/src/api/java/thaumcraft/api/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@API(owner = "Thaumcraft", apiVersion = "4.2.2.0", provides = "Thaumcraft|API") -package thaumcraft.api; - -import cpw.mods.fml.common.API; diff --git a/src/api/java/thaumcraft/api/potions/PotionFluxTaint.java b/src/api/java/thaumcraft/api/potions/PotionFluxTaint.java deleted file mode 100644 index b950de0ef..000000000 --- a/src/api/java/thaumcraft/api/potions/PotionFluxTaint.java +++ /dev/null @@ -1,67 +0,0 @@ -package thaumcraft.api.potions; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.potion.Potion; -import net.minecraft.util.ResourceLocation; -import thaumcraft.api.damagesource.DamageSourceThaumcraft; -import thaumcraft.api.entities.ITaintedMob; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public class PotionFluxTaint extends Potion -{ - public static PotionFluxTaint instance = null; // will be instantiated at runtime - private int statusIconIndex = -1; - - public PotionFluxTaint(int par1, boolean par2, int par3) - { - super(par1,par2,par3); - setIconIndex(0, 0); - } - - public static void init() - { - instance.setPotionName("potion.fluxtaint"); - instance.setIconIndex(3, 1); - instance.setEffectiveness(0.25D); - } - - @Override - public boolean isBadEffect() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public int getStatusIconIndex() { - Minecraft.getMinecraft().renderEngine.bindTexture(rl); - return super.getStatusIconIndex(); - } - - static final ResourceLocation rl = new ResourceLocation("thaumcraft","textures/misc/potions.png"); - - @Override - public void performEffect(EntityLivingBase target, int par2) { - if (target instanceof ITaintedMob) { - target.heal(1); - } else - if (!target.isEntityUndead() && !(target instanceof EntityPlayer)) - { - target.attackEntityFrom(DamageSourceThaumcraft.taint, 1); - } - else - if (!target.isEntityUndead() && (target.getMaxHealth() > 1 || (target instanceof EntityPlayer))) - { - target.attackEntityFrom(DamageSourceThaumcraft.taint, 1); - } - } - - public boolean isReady(int par1, int par2) - { - int k = 40 >> par2; - return k > 0 ? par1 % k == 0 : true; - } - -} diff --git a/src/api/java/thaumcraft/api/potions/PotionVisExhaust.java b/src/api/java/thaumcraft/api/potions/PotionVisExhaust.java deleted file mode 100644 index cd7fc18cd..000000000 --- a/src/api/java/thaumcraft/api/potions/PotionVisExhaust.java +++ /dev/null @@ -1,48 +0,0 @@ -package thaumcraft.api.potions; - -import net.minecraft.client.Minecraft; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.potion.Potion; -import net.minecraft.util.ResourceLocation; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public class PotionVisExhaust extends Potion -{ - public static PotionVisExhaust instance = null; // will be instantiated at runtime - private int statusIconIndex = -1; - - public PotionVisExhaust(int par1, boolean par2, int par3) - { - super(par1,par2,par3); - setIconIndex(0, 0); - } - - public static void init() - { - instance.setPotionName("potion.visexhaust"); - instance.setIconIndex(5, 1); - instance.setEffectiveness(0.25D); - } - - @Override - public boolean isBadEffect() { - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public int getStatusIconIndex() { - Minecraft.getMinecraft().renderEngine.bindTexture(rl); - return super.getStatusIconIndex(); - } - - static final ResourceLocation rl = new ResourceLocation("thaumcraft","textures/misc/potions.png"); - - @Override - public void performEffect(EntityLivingBase target, int par2) { - - } - - -} diff --git a/src/api/java/thaumcraft/api/research/IScanEventHandler.java b/src/api/java/thaumcraft/api/research/IScanEventHandler.java deleted file mode 100644 index d0efac5fc..000000000 --- a/src/api/java/thaumcraft/api/research/IScanEventHandler.java +++ /dev/null @@ -1,9 +0,0 @@ -package thaumcraft.api.research; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -public interface IScanEventHandler { - ScanResult scanPhenomena(ItemStack stack, World world, EntityPlayer player); -} diff --git a/src/api/java/thaumcraft/api/research/ResearchCategories.java b/src/api/java/thaumcraft/api/research/ResearchCategories.java deleted file mode 100644 index 82309b369..000000000 --- a/src/api/java/thaumcraft/api/research/ResearchCategories.java +++ /dev/null @@ -1,101 +0,0 @@ -package thaumcraft.api.research; - -import java.util.Collection; -import java.util.LinkedHashMap; - -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; - -import org.apache.logging.log4j.Level; - -import cpw.mods.fml.common.FMLLog; - -public class ResearchCategories { - - //Research - public static LinkedHashMap researchCategories = new LinkedHashMap (); - - /** - * @param key - * @return the research item linked to this key - */ - public static ResearchCategoryList getResearchList(String key) { - return researchCategories.get(key); - } - - /** - * @param key - * @return the name of the research category linked to this key. - * Must be stored as localization information in the LanguageRegistry. - */ - public static String getCategoryName(String key) { - return StatCollector.translateToLocal("tc.research_category."+key); - } - - /** - * @param key the research key - * @return the ResearchItem object. - */ - public static ResearchItem getResearch(String key) { - Collection rc = researchCategories.values(); - for (Object cat:rc) { - Collection rl = ((ResearchCategoryList)cat).research.values(); - for (Object ri:rl) { - if ((((ResearchItem)ri).key).equals(key)) return (ResearchItem)ri; - } - } - return null; - } - - /** - * This should only be done at the PostInit stage - * @param key the key used for this category - * @param icon the icon to be used for the research category tab - * @param background the resource location of the background image to use for this category - * @return the name of the research linked to this key - */ - public static void registerCategory(String key, ResourceLocation icon, ResourceLocation background) { - if (getResearchList(key)==null) { - ResearchCategoryList rl = new ResearchCategoryList(icon, background); - researchCategories.put(key, rl); - } - } - - public static void addResearch(ResearchItem ri) { - ResearchCategoryList rl = getResearchList(ri.category); - if (rl!=null && !rl.research.containsKey(ri.key)) { - - if (!ri.isVirtual()) { - for (ResearchItem rr:rl.research.values()) { - if (rr.displayColumn == ri.displayColumn && rr.displayRow == ri.displayRow) { - FMLLog.log(Level.FATAL, "[Thaumcraft] Research ["+ri.getName()+"] not added as it overlaps with existing research ["+rr.getName()+"]"); - return; - } - } - } - - - rl.research.put(ri.key, ri); - - if (ri.displayColumn < rl.minDisplayColumn) - { - rl.minDisplayColumn = ri.displayColumn; - } - - if (ri.displayRow < rl.minDisplayRow) - { - rl.minDisplayRow = ri.displayRow; - } - - if (ri.displayColumn > rl.maxDisplayColumn) - { - rl.maxDisplayColumn = ri.displayColumn; - } - - if (ri.displayRow > rl.maxDisplayRow) - { - rl.maxDisplayRow = ri.displayRow; - } - } - } -} diff --git a/src/api/java/thaumcraft/api/research/ResearchCategoryList.java b/src/api/java/thaumcraft/api/research/ResearchCategoryList.java deleted file mode 100644 index 7eed0101e..000000000 --- a/src/api/java/thaumcraft/api/research/ResearchCategoryList.java +++ /dev/null @@ -1,37 +0,0 @@ -package thaumcraft.api.research; - -import java.util.HashMap; -import java.util.Map; - -import net.minecraft.util.ResourceLocation; - -public class ResearchCategoryList { - - /** Is the smallest column used on the GUI. */ - public int minDisplayColumn; - - /** Is the smallest row used on the GUI. */ - public int minDisplayRow; - - /** Is the biggest column used on the GUI. */ - public int maxDisplayColumn; - - /** Is the biggest row used on the GUI. */ - public int maxDisplayRow; - - /** display variables **/ - public ResourceLocation icon; - public ResourceLocation background; - - public ResearchCategoryList(ResourceLocation icon, ResourceLocation background) { - this.icon = icon; - this.background = background; - } - - //Research - public Map research = new HashMap(); - - - - -} diff --git a/src/api/java/thaumcraft/api/research/ResearchItem.java b/src/api/java/thaumcraft/api/research/ResearchItem.java deleted file mode 100644 index 1d5fd8bf5..000000000 --- a/src/api/java/thaumcraft/api/research/ResearchItem.java +++ /dev/null @@ -1,369 +0,0 @@ -package thaumcraft.api.research; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; - -public class ResearchItem -{ - /** - * A short string used as a key for this research. Must be unique - */ - public final String key; - - /** - * A short string used as a reference to the research category to which this must be added. - */ - public final String category; - - /** - * The aspect tags and their values required to complete this research - */ - public final AspectList tags; - - /** - * This links to any research that needs to be completed before this research can be discovered or learnt. - */ - public String[] parents = null; - - /** - * Like parent above, but a line will not be displayed in the thaumonomicon linking them. Just used to prevent clutter. - */ - public String[] parentsHidden = null; - /** - * any research linked to this that will be unlocked automatically when this research is complete - */ - public String[] siblings = null; - - /** - * the horizontal position of the research icon - */ - public final int displayColumn; - - /** - * the vertical position of the research icon - */ - public final int displayRow; - - /** - * the icon to be used for this research - */ - public final ItemStack icon_item; - - /** - * the icon to be used for this research - */ - public final ResourceLocation icon_resource; - - /** - * How large the research grid is. Valid values are 1 to 3. - */ - private int complexity; - - /** - * Special research has a spiky border. Used for important research milestones. - */ - private boolean isSpecial; - - /** - * Research that can be directly purchased with RP in normal research difficulty. - */ - private boolean isSecondary; - - /** - * This indicates if the research should use a circular icon border. Usually used for "passive" research - * that doesn't have recipes and grants passive effects, or that unlock automatically. - */ - private boolean isRound; - - /** - * Stub research cannot be discovered by normal means, but can be unlocked via the sibling system. - */ - private boolean isStub; - - /** - * This indicated that the research is completely hidden and cannot be discovered by any - * player-controlled means. The recipes will never show up in the thaumonomicon. - * Usually used to unlock "hidden" recipes via sibling unlocking, like - * the various cap and rod combos for wands. - */ - private boolean isVirtual; - - - - /** - * Concealed research does not display in the thaumonomicon until parent researches are discovered. - */ - private boolean isConcealed; - - /** - * Hidden research can only be discovered via scanning or knowledge fragments - */ - private boolean isHidden; - - /** - * This is the same as isHidden, except it cannot be discovered with knowledge fragments, only scanning. - */ - private boolean isLost; - - /** - * These research items will automatically unlock for all players on game start - */ - private boolean isAutoUnlock; - - /** - * Scanning these items will have a chance of revealing hidden knowledge in the thaumonomicon - */ - private ItemStack[] itemTriggers; - - /** - * Scanning these entities will have a chance of revealing hidden knowledge in the thaumonomicon - */ - private String[] entityTriggers; - - /** - * Scanning things with these aspects will have a chance of revealing hidden knowledge in the thaumonomicon - */ - private Aspect[] aspectTriggers; - - private ResearchPage[] pages = null; - - public ResearchItem(String key, String category) - { - this.key = key; - this.category = category; - this.tags = new AspectList(); - this.icon_resource = null; - this.icon_item = null; - this.displayColumn = 0; - this.displayRow = 0; - this.setVirtual(); - - } - - public ResearchItem(String key, String category, AspectList tags, int col, int row, int complex, ResourceLocation icon) - { - this.key = key; - this.category = category; - this.tags = tags; - this.icon_resource = icon; - this.icon_item = null; - this.displayColumn = col; - this.displayRow = row; - this.complexity = complex; - if (complexity < 1) this.complexity = 1; - if (complexity > 3) this.complexity = 3; - } - - public ResearchItem(String key, String category, AspectList tags, int col, int row, int complex, ItemStack icon) - { - this.key = key; - this.category = category; - this.tags = tags; - this.icon_item = icon; - this.icon_resource = null; - this.displayColumn = col; - this.displayRow = row; - this.complexity = complex; - if (complexity < 1) this.complexity = 1; - if (complexity > 3) this.complexity = 3; - } - - public ResearchItem setSpecial() - { - this.isSpecial = true; - return this; - } - - public ResearchItem setStub() - { - this.isStub = true; - return this; - } - - public ResearchItem setLost() - { - this.isLost = true; - return this; - } - - public ResearchItem setConcealed() - { - this.isConcealed = true; - return this; - } - - public ResearchItem setHidden() - { - this.isHidden = true; - return this; - } - - public ResearchItem setVirtual() - { - this.isVirtual = true; - return this; - } - - public ResearchItem setParents(String... par) - { - this.parents = par; - return this; - } - - - - public ResearchItem setParentsHidden(String... par) - { - this.parentsHidden = par; - return this; - } - - public ResearchItem setSiblings(String... sib) - { - this.siblings = sib; - return this; - } - - public ResearchItem setPages(ResearchPage... par) - { - this.pages = par; - return this; - } - - public ResearchPage[] getPages() { - return pages; - } - - public ResearchItem setItemTriggers(ItemStack... par) - { - this.itemTriggers = par; - return this; - } - - public ResearchItem setEntityTriggers(String... par) - { - this.entityTriggers = par; - return this; - } - - public ResearchItem setAspectTriggers(Aspect... par) - { - this.aspectTriggers = par; - return this; - } - - public ItemStack[] getItemTriggers() { - return itemTriggers; - } - - public String[] getEntityTriggers() { - return entityTriggers; - } - - public Aspect[] getAspectTriggers() { - return aspectTriggers; - } - - public ResearchItem registerResearchItem() - { - ResearchCategories.addResearch(this); - return this; - } - - public String getName() - { - return StatCollector.translateToLocal("tc.research_name."+key); - } - - public String getText() - { - return StatCollector.translateToLocal("tc.research_text."+key); - } - - public boolean isSpecial() - { - return this.isSpecial; - } - - public boolean isStub() - { - return this.isStub; - } - - public boolean isLost() - { - return this.isLost; - } - - public boolean isConcealed() - { - return this.isConcealed; - } - - public boolean isHidden() - { - return this.isHidden; - } - - public boolean isVirtual() - { - return this.isVirtual; - } - - public boolean isAutoUnlock() { - return isAutoUnlock; - } - - public ResearchItem setAutoUnlock() - { - this.isAutoUnlock = true; - return this; - } - - public boolean isRound() { - return isRound; - } - - public ResearchItem setRound() { - this.isRound = true; - return this; - } - - public boolean isSecondary() { - return isSecondary; - } - - public ResearchItem setSecondary() { - this.isSecondary = true; - return this; - } - - public int getComplexity() { - return complexity; - } - - public ResearchItem setComplexity(int complexity) { - this.complexity = complexity; - return this; - } - - /** - * @return the aspect aspects ordinal with the highest value. Used to determine scroll color and similar things - */ - public Aspect getResearchPrimaryTag() { - Aspect aspect=null; - int highest=0; - if (tags!=null) - for (Aspect tag:tags.getAspects()) { - if (tags.getAmount(tag)>highest) { - aspect=tag; - highest=tags.getAmount(tag); - }; - } - return aspect; - } - -} diff --git a/src/api/java/thaumcraft/api/research/ResearchPage.java b/src/api/java/thaumcraft/api/research/ResearchPage.java deleted file mode 100644 index fdada843e..000000000 --- a/src/api/java/thaumcraft/api/research/ResearchPage.java +++ /dev/null @@ -1,193 +0,0 @@ -package thaumcraft.api.research; - -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.item.crafting.FurnaceRecipes; -import net.minecraft.item.crafting.IRecipe; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; -import thaumcraft.api.aspects.AspectList; -import thaumcraft.api.crafting.CrucibleRecipe; -import thaumcraft.api.crafting.IArcaneRecipe; -import thaumcraft.api.crafting.InfusionEnchantmentRecipe; -import thaumcraft.api.crafting.InfusionRecipe; - -public class ResearchPage { - public static enum PageType - { - TEXT, - TEXT_CONCEALED, - IMAGE, - CRUCIBLE_CRAFTING, - ARCANE_CRAFTING, - ASPECTS, - NORMAL_CRAFTING, - INFUSION_CRAFTING, - COMPOUND_CRAFTING, - INFUSION_ENCHANTMENT, - SMELTING - } - - public PageType type = PageType.TEXT; - - public String text=null; - public String research=null; - public ResourceLocation image=null; - public AspectList aspects=null; - public Object recipe=null; - public ItemStack recipeOutput=null; - - /** - * @param text this can (but does not have to) be a reference to a localization variable, not the actual text. - */ - public ResearchPage(String text) { - this.type = PageType.TEXT; - this.text = text; - } - - /** - * @param research this page will only be displayed if the player has discovered this research - * @param text this can (but does not have to) be a reference to a localization variable, not the actual text. - */ - public ResearchPage(String research, String text) { - this.type = PageType.TEXT_CONCEALED; - this.research = research; - this.text = text; - } - - /** - * @param recipe a vanilla crafting recipe. - */ - public ResearchPage(IRecipe recipe) { - this.type = PageType.NORMAL_CRAFTING; - this.recipe = recipe; - this.recipeOutput = recipe.getRecipeOutput(); - } - - /** - * @param recipe a collection of vanilla crafting recipes. - */ - public ResearchPage(IRecipe[] recipe) { - this.type = PageType.NORMAL_CRAFTING; - this.recipe = recipe; - } - - /** - * @param recipe a collection of arcane crafting recipes. - */ - public ResearchPage(IArcaneRecipe[] recipe) { - this.type = PageType.ARCANE_CRAFTING; - this.recipe = recipe; - } - - /** - * @param recipe a collection of arcane crafting recipes. - */ - public ResearchPage(CrucibleRecipe[] recipe) { - this.type = PageType.CRUCIBLE_CRAFTING; - this.recipe = recipe; - } - - /** - * @param recipe a collection of infusion crafting recipes. - */ - public ResearchPage(InfusionRecipe[] recipe) { - this.type = PageType.INFUSION_CRAFTING; - this.recipe = recipe; - } - - /** - * @param recipe a compound crafting recipe. - */ - public ResearchPage(List recipe) { - this.type = PageType.COMPOUND_CRAFTING; - this.recipe = recipe; - } - - /** - * @param recipe an arcane worktable crafting recipe. - */ - public ResearchPage(IArcaneRecipe recipe) { - this.type = PageType.ARCANE_CRAFTING; - this.recipe = recipe; - this.recipeOutput = recipe.getRecipeOutput(); - } - - /** - * @param recipe an alchemy crafting recipe. - */ - public ResearchPage(CrucibleRecipe recipe) { - this.type = PageType.CRUCIBLE_CRAFTING; - this.recipe = recipe; - this.recipeOutput = recipe.getRecipeOutput(); - } - - /** - * @param recipe a furnace smelting crafting recipe. - */ - public ResearchPage(ItemStack input) { - this.type = PageType.SMELTING; - this.recipe = input; - this.recipeOutput = FurnaceRecipes.smelting().getSmeltingResult(input); - } - - /** - * @param recipe an infusion crafting recipe. - */ - public ResearchPage(InfusionRecipe recipe) { - this.type = PageType.INFUSION_CRAFTING; - this.recipe = recipe; - if (recipe.getRecipeOutput() instanceof ItemStack) { - this.recipeOutput = (ItemStack) recipe.getRecipeOutput(); - } else { - this.recipeOutput = recipe.getRecipeInput(); - } - } - - /** - * @param recipe an infusion crafting recipe. - */ - public ResearchPage(InfusionEnchantmentRecipe recipe) { - this.type = PageType.INFUSION_ENCHANTMENT; - this.recipe = recipe; -// if (recipe.recipeOutput instanceof ItemStack) { -// this.recipeOutput = (ItemStack) recipe.recipeOutput; -// } else { -// this.recipeOutput = recipe.recipeInput; -// } - } - - /** - * @param image - * @param caption this can (but does not have to) be a reference to a localization variable, not the actual text. - */ - public ResearchPage(ResourceLocation image, String caption) { - this.type = PageType.IMAGE; - this.image = image; - this.text = caption; - } - - /** - * This function should really not be called directly - used internally - */ - public ResearchPage(AspectList as) { - this.type = PageType.ASPECTS; - this.aspects = as; - } - - /** - * returns a localized text of the text field (if one exists). Returns the text field itself otherwise. - * @return - */ - public String getTranslatedText() { - String ret=""; - if (text != null) { - ret = StatCollector.translateToLocal(text); - if (ret.isEmpty()) ret = text; - } - return ret; - } - - -} diff --git a/src/api/java/thaumcraft/api/research/ScanResult.java b/src/api/java/thaumcraft/api/research/ScanResult.java deleted file mode 100644 index e1498f310..000000000 --- a/src/api/java/thaumcraft/api/research/ScanResult.java +++ /dev/null @@ -1,39 +0,0 @@ -package thaumcraft.api.research; - -import net.minecraft.entity.Entity; - -public class ScanResult { - public byte type = 0; //1=blocks,2=entities,3=phenomena - public int id; - public int meta; - public Entity entity; - public String phenomena; - - public ScanResult(byte type, int blockId, int blockMeta, Entity entity, - String phenomena) { - super(); - this.type = type; - this.id = blockId; - this.meta = blockMeta; - this.entity = entity; - this.phenomena = phenomena; - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof ScanResult) { - ScanResult sr = (ScanResult) obj; - if (type != sr.type) - return false; - if (type == 1 - && (id != sr.id || meta != sr.meta)) - return false; - if (type == 2 && entity.getEntityId() != sr.entity.getEntityId()) - return false; - if (type == 3 && !phenomena.equals(sr.phenomena)) - return false; - } - return true; - } - -} diff --git a/src/api/java/thaumcraft/api/visnet/TileVisNode.java b/src/api/java/thaumcraft/api/visnet/TileVisNode.java deleted file mode 100644 index 204879e6e..000000000 --- a/src/api/java/thaumcraft/api/visnet/TileVisNode.java +++ /dev/null @@ -1,188 +0,0 @@ -package thaumcraft.api.visnet; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.HashMap; - -import thaumcraft.api.TileThaumcraft; -import thaumcraft.api.WorldCoordinates; -import thaumcraft.api.aspects.Aspect; - -/** - * @author Azanor - * - * The tile entity used by nodes in the vis energy network. A node is either a source (like an aura node), - * a transport relay or vis receiver (like the infernal furnace). - * - */ -public abstract class TileVisNode extends TileThaumcraft { - - WeakReference parent = null; - ArrayList> children = new ArrayList>(); - - /** - * @return the WorldCoordinates location of where this node is located - */ - public WorldCoordinates getLocation() { - return new WorldCoordinates(this); - } - - /** - * @return the number of blocks away this node will check for parent nodes to connect to. - */ - public abstract int getRange(); - - /** - * @return true if this is the source or root node of the vis network. - */ - public abstract boolean isSource(); - - /** - * This method should never be called directly. Use VisNetHandler.drainVis() instead - * @param aspect what aspect to drain - * @param vis how much to drain - * @return how much was actually drained - */ - public int consumeVis(Aspect aspect, int vis) { - if (VisNetHandler.isNodeValid(getParent())) { - int out = getParent().get().consumeVis(aspect, vis); - if (out>0) { - triggerConsumeEffect(aspect); - } - return out; - } - return 0; - } - - public void removeThisNode() { - for (WeakReference n:getChildren()) { - if (n!=null && n.get()!=null) { - n.get().removeThisNode(); - } - } - - children = new ArrayList>(); - if (VisNetHandler.isNodeValid(this.getParent())) { - this.getParent().get().nodeRefresh=true; - } - this.setParent(null); - this.parentChanged(); - - if (this.isSource()) { - HashMap> sourcelist = VisNetHandler.sources.get(worldObj.provider.dimensionId); - if (sourcelist==null) { - sourcelist = new HashMap>(); - } - sourcelist.remove(getLocation()); - VisNetHandler.sources.put( worldObj.provider.dimensionId, sourcelist ); - } - - worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); - } - - - - @Override - public void invalidate() { - removeThisNode(); - super.invalidate(); - } - - public void triggerConsumeEffect(Aspect aspect) { } - - /** - * @return - */ - public WeakReference getParent() { - return parent; - } - - /** - * @return - */ - public WeakReference getRootSource() { - return VisNetHandler.isNodeValid(getParent()) ? - getParent().get().getRootSource() : this.isSource() ? - new WeakReference(this) : null; - } - - /** - * @param parent - */ - public void setParent(WeakReference parent) { - this.parent = parent; - } - - /** - * @return - */ - public ArrayList> getChildren() { - return children; - } - - @Override - public boolean canUpdate() { - return true; - } - - protected int nodeCounter = 0; - private boolean nodeRegged = false; - public boolean nodeRefresh = false; - - @Override - public void updateEntity() { - - if (!worldObj.isRemote && ((nodeCounter++) % 40==0 || nodeRefresh)) { - //check for changes - if (!nodeRefresh && children.size()>0) { - for (WeakReference n:children) { - if (n==null || n.get()==null || !VisNetHandler.canNodeBeSeen(this, n.get())) { - nodeRefresh=true; - break; - } - } - } - - //refresh linked nodes - if (nodeRefresh) { - for (WeakReference n:children) { - if (n.get()!=null) { - n.get().nodeRefresh=true; - } - } - children.clear(); - parent=null; - } - - //redo stuff - if (isSource() && !nodeRegged) { - VisNetHandler.addSource(getWorldObj(), this); - nodeRegged = true; - } else - if (!isSource() && !VisNetHandler.isNodeValid(getParent())) { - setParent(VisNetHandler.addNode(getWorldObj(), this)); - nodeRefresh=true; - } - - if (nodeRefresh) { - worldObj.markBlockForUpdate(xCoord, yCoord, zCoord); - parentChanged(); - } - nodeRefresh=false; - } - - } - - public void parentChanged() { } - - /** - * @return the type of shard this is attuned to: - * none -1, air 0, fire 1, water 2, earth 3, order 4, entropy 5 - * Should return -1 for most implementations - */ - public byte getAttunement() { - return -1; - } - - -} diff --git a/src/api/java/thaumcraft/api/visnet/VisNetHandler.java b/src/api/java/thaumcraft/api/visnet/VisNetHandler.java deleted file mode 100644 index 7ac4c6994..000000000 --- a/src/api/java/thaumcraft/api/visnet/VisNetHandler.java +++ /dev/null @@ -1,282 +0,0 @@ -package thaumcraft.api.visnet; - -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.HashMap; - -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.MovingObjectPosition.MovingObjectType; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import thaumcraft.api.ThaumcraftApi; -import thaumcraft.api.ThaumcraftApiHelper; -import thaumcraft.api.WorldCoordinates; -import thaumcraft.api.aspects.Aspect; - -public class VisNetHandler { - - // NODE DRAINING - /** - * This method drains vis from a relay or source near the passed in - * location. The amount received can be less than the amount requested so - * take that into account. - * - * @param world - * @param x the x position of the draining block or entity - * @param y the y position of the draining block or entity - * @param z the z position of the draining block or entity - * @param aspect what aspect to drain - * @param amount how much to drain - * @return how much was actually drained - */ - public static int drainVis(World world, int x, int y, int z, Aspect aspect, int amount) { - - int drainedAmount = 0; - - WorldCoordinates drainer = new WorldCoordinates(x, y, z, - world.provider.dimensionId); - if (!nearbyNodes.containsKey(drainer)) { - calculateNearbyNodes(world, x, y, z); - } - - ArrayList> nodes = nearbyNodes.get(drainer); - if (nodes!=null && nodes.size()>0) - for (WeakReference noderef : nodes) { - - TileVisNode node = noderef.get(); - - if (node == null) continue; - - int a = node.consumeVis(aspect, amount); - drainedAmount += a; - amount -= a; - if (a>0) { - int color = Aspect.getPrimalAspects().indexOf(aspect); - generateVisEffect(world.provider.dimensionId, x, y, z, node.xCoord, node.yCoord, node.zCoord, color); - } - if (amount <= 0) { - break; - } - } - - return drainedAmount; - } - - public static void generateVisEffect(int dim, int x, int y, int z, int x2, int y2, int z2, int color) { - ThaumcraftApi.internalMethods.generateVisEffect(dim, x, y, z, x2, y2, z2, color); - } - - public static HashMap>> sources = new HashMap>>(); - - public static void addSource(World world, TileVisNode vs) { - HashMap> sourcelist = sources - .get(world.provider.dimensionId); - if (sourcelist == null) { - sourcelist = new HashMap>(); - } - sourcelist.put(vs.getLocation(), new WeakReference(vs)); - sources.put(world.provider.dimensionId, sourcelist); - nearbyNodes.clear(); - } - - public static boolean isNodeValid(WeakReference node) { - if (node == null || node.get() == null || node.get().isInvalid()) - return false; - return true; - } - - public static WeakReference addNode(World world, TileVisNode vn) { - WeakReference ref = new WeakReference(vn); - - HashMap> sourcelist = sources - .get(world.provider.dimensionId); - if (sourcelist == null) { - sourcelist = new HashMap>(); - return null; - } - - ArrayList nearby = new ArrayList(); - - for (WeakReference root : sourcelist.values()) { - if (!isNodeValid(root)) - continue; - - TileVisNode source = root.get(); - - float r = inRange(world, vn.getLocation(), source.getLocation(), - vn.getRange()); - if (r > 0) { - nearby.add(new Object[] { source, r - vn.getRange() * 2 }); - } - - nearby = findClosestNodes(vn, source, nearby); - cache.clear(); - } - - float dist = Float.MAX_VALUE; - TileVisNode closest = null; - if (nearby.size() > 0) { - for (Object[] o : nearby) { - if ((Float) o[1] < dist && - (vn.getAttunement() == -1 || ((TileVisNode) o[0]).getAttunement() == -1 || - vn.getAttunement() == ((TileVisNode) o[0]).getAttunement())//) { - && canNodeBeSeen(vn,(TileVisNode)o[0])) { - dist = (Float) o[1]; - closest = (TileVisNode) o[0]; - } - } - } - if (closest != null) { - closest.getChildren().add(ref); - nearbyNodes.clear(); - return new WeakReference(closest); - } - - return null; - } - - static ArrayList cache = new ArrayList(); - public static ArrayList findClosestNodes(TileVisNode target, - TileVisNode parent, ArrayList in) { - - if (cache.size() > 512 || cache.contains(new WorldCoordinates(parent))) return in; - cache.add(new WorldCoordinates(parent)); - - for (WeakReference childWR : parent.getChildren()) { - TileVisNode child = childWR.get(); - - if (child != null && !child.equals(target) && !child.equals(parent)) { - float r2 = inRange(child.getWorldObj(), child.getLocation(), - target.getLocation(), target.getRange()); - if (r2 > 0) { - in.add(new Object[] { child, r2 }); - } - - in = findClosestNodes(target, child, in); - } - } - return in; - } - - private static float inRange(World world, WorldCoordinates cc1, - WorldCoordinates cc2, int range) { - float distance = cc1.getDistanceSquaredToWorldCoordinates(cc2); - return distance > range * range ? -1 : distance; - } - - private static HashMap>> nearbyNodes = new HashMap>>(); - - private static void calculateNearbyNodes(World world, int x, int y, int z) { - - HashMap> sourcelist = sources - .get(world.provider.dimensionId); - if (sourcelist == null) { - sourcelist = new HashMap>(); - return; - } - - ArrayList> cn = new ArrayList>(); - WorldCoordinates drainer = new WorldCoordinates(x, y, z, - world.provider.dimensionId); - - ArrayList nearby = new ArrayList(); - - for (WeakReference root : sourcelist.values()) { - - if (!isNodeValid(root)) - continue; - - TileVisNode source = root.get(); - - TileVisNode closest = null; - float range = Float.MAX_VALUE; - - float r = inRange(world, drainer, source.getLocation(), - source.getRange()); - if (r > 0) { - range = r; - closest = source; - } - - ArrayList> children = new ArrayList>(); - children = getAllChildren(source,children); - - for (WeakReference child : children) { - TileVisNode n = child.get(); - if (n != null && !n.equals(root)) { - - float r2 = inRange(n.getWorldObj(), n.getLocation(), - drainer, n.getRange()); - if (r2 > 0 && r2 < range) { - range = r2; - closest = n; - } - } - } - - if (closest != null) { - - cn.add(new WeakReference(closest)); - } - } - - nearbyNodes.put(drainer, cn); - } - - private static ArrayList> getAllChildren(TileVisNode source, ArrayList> list) { - for (WeakReference child : source.getChildren()) { - TileVisNode n = child.get(); - - if (n != null && n.getWorldObj()!=null && isChunkLoaded(n.getWorldObj(), n.xCoord, n.zCoord)) { - list.add(child); - list = getAllChildren(n,list); - } - } - return list; - } - - public static boolean isChunkLoaded(World world, int x, int z) { - int xx = x >> 4; - int zz = z >> 4; - return world.getChunkProvider().chunkExists(xx, zz); - } - - public static boolean canNodeBeSeen(TileVisNode source,TileVisNode target) - { - MovingObjectPosition mop = ThaumcraftApiHelper.rayTraceIgnoringSource(source.getWorldObj(), - Vec3.createVectorHelper(source.xCoord+.5, source.yCoord+.5,source.zCoord+.5), - Vec3.createVectorHelper(target.xCoord+.5, target.yCoord+.5,target.zCoord+.5), - false, true, false); - return mop == null || (mop.typeOfHit==MovingObjectType.BLOCK && - mop.blockX==target.xCoord && mop.blockY==target.yCoord && mop.blockZ==target.zCoord); - } - - // public static HashMap> - // noderef = new HashMap>(); - // - // public static TileVisNode getClosestNodeWithinRadius(World world, int x, - // int y, int z, int radius) { - // TileVisNode out = null; - // WorldCoordinates wc = null; - // float cd = Float.MAX_VALUE; - // for (int sx = x - radius; sx <= x + radius; sx++) { - // for (int sy = y - radius; sy <= y + radius; sy++) { - // for (int sz = z - radius; sz <= z + radius; sz++) { - // wc = new WorldCoordinates(sx,sy,sz,world.provider.dimensionId); - // if (noderef.containsKey(wc)) { - // float d = wc.getDistanceSquared(x, y, z); - // if (d=types.length) { - FocusUpgradeType[] temp = new FocusUpgradeType[id+1]; - System.arraycopy(types, 0, temp, 0, id); - types = temp; - } - - types[id] = this; - } - - public String getLocalizedName() { - return StatCollector.translateToLocal(name); - } - - public String getLocalizedText() { - return StatCollector.translateToLocal(text); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof FocusUpgradeType) { - return this.id == ((FocusUpgradeType)obj).id; - } else return false; - } - - // basic upgrade types - public static FocusUpgradeType potency = new FocusUpgradeType( 0, - new ResourceLocation("thaumcraft", "textures/foci/potency.png"), - "focus.upgrade.potency.name","focus.upgrade.potency.text", - new AspectList().add(Aspect.WEAPON,1)); - - public static FocusUpgradeType frugal = new FocusUpgradeType( 1, - new ResourceLocation("thaumcraft", "textures/foci/frugal.png"), - "focus.upgrade.frugal.name","focus.upgrade.frugal.text", - new AspectList().add(Aspect.HUNGER,1)); - - public static FocusUpgradeType treasure = new FocusUpgradeType( 2, - new ResourceLocation("thaumcraft", "textures/foci/treasure.png"), - "focus.upgrade.treasure.name","focus.upgrade.treasure.text", - new AspectList().add(Aspect.GREED,1)); - - public static FocusUpgradeType enlarge = new FocusUpgradeType( 3, - new ResourceLocation("thaumcraft", "textures/foci/enlarge.png"), - "focus.upgrade.enlarge.name","focus.upgrade.enlarge.text", - new AspectList().add(Aspect.TRAVEL,1)); - - public static FocusUpgradeType alchemistsfire = new FocusUpgradeType( 4, - new ResourceLocation("thaumcraft", "textures/foci/alchemistsfire.png"), - "focus.upgrade.alchemistsfire.name","focus.upgrade.alchemistsfire.text", - new AspectList().add(Aspect.ENERGY,1).add(Aspect.SLIME,1)); - - public static FocusUpgradeType alchemistsfrost = new FocusUpgradeType( 5, - new ResourceLocation("thaumcraft", "textures/foci/alchemistsfrost.png"), - "focus.upgrade.alchemistsfrost.name","focus.upgrade.alchemistsfrost.text", - new AspectList().add(Aspect.COLD,1).add(Aspect.TRAP,1)); - - public static FocusUpgradeType architect = new FocusUpgradeType( 6, - new ResourceLocation("thaumcraft", "textures/foci/architect.png"), - "focus.upgrade.architect.name","focus.upgrade.architect.text", - new AspectList().add(Aspect.CRAFT,1)); - - public static FocusUpgradeType extend = new FocusUpgradeType( 7, - new ResourceLocation("thaumcraft", "textures/foci/extend.png"), - "focus.upgrade.extend.name","focus.upgrade.extend.text", - new AspectList().add(Aspect.EXCHANGE,1)); - - public static FocusUpgradeType silktouch = new FocusUpgradeType( 8, - new ResourceLocation("thaumcraft", "textures/foci/silktouch.png"), - "focus.upgrade.silktouch.name","focus.upgrade.silktouch.text", - new AspectList().add(Aspect.GREED,1)); - - -} diff --git a/src/api/java/thaumcraft/api/wands/IWandRodOnUpdate.java b/src/api/java/thaumcraft/api/wands/IWandRodOnUpdate.java deleted file mode 100644 index 4ef8c8494..000000000 --- a/src/api/java/thaumcraft/api/wands/IWandRodOnUpdate.java +++ /dev/null @@ -1,16 +0,0 @@ -package thaumcraft.api.wands; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; - -/** - * - * @author azanor - * - * Implemented by a class that you wish to be called whenever a wand with this rod performs its - * update tick. - * - */ -public interface IWandRodOnUpdate { - void onUpdate(ItemStack itemstack, EntityPlayer player); -} diff --git a/src/api/java/thaumcraft/api/wands/IWandTriggerManager.java b/src/api/java/thaumcraft/api/wands/IWandTriggerManager.java deleted file mode 100644 index 7c299deb4..000000000 --- a/src/api/java/thaumcraft/api/wands/IWandTriggerManager.java +++ /dev/null @@ -1,15 +0,0 @@ -package thaumcraft.api.wands; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -public interface IWandTriggerManager { - - /** - * This class will be called by wands with the proper parameters. It is up to you to decide what to do with them. - */ - public boolean performTrigger(World world, ItemStack wand, EntityPlayer player, - int x, int y, int z, int side, int event); - -} diff --git a/src/api/java/thaumcraft/api/wands/IWandable.java b/src/api/java/thaumcraft/api/wands/IWandable.java deleted file mode 100644 index aeb9bac79..000000000 --- a/src/api/java/thaumcraft/api/wands/IWandable.java +++ /dev/null @@ -1,25 +0,0 @@ -package thaumcraft.api.wands; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -/** - * - * @author azanor - * - * Add this to a tile entity that you wish wands to interact with in some way. - * - */ - -public interface IWandable { - - public int onWandRightClick(World world, ItemStack wandstack, EntityPlayer player, int x, int y, int z, int side, int md); - - public ItemStack onWandRightClick(World world, ItemStack wandstack, EntityPlayer player); - - public void onUsingWandTick(ItemStack wandstack, EntityPlayer player, int count); - - public void onWandStoppedUsing(ItemStack wandstack, World world, EntityPlayer player, int count); - -} diff --git a/src/api/java/thaumcraft/api/wands/ItemFocusBasic.java b/src/api/java/thaumcraft/api/wands/ItemFocusBasic.java deleted file mode 100644 index e8938e915..000000000 --- a/src/api/java/thaumcraft/api/wands/ItemFocusBasic.java +++ /dev/null @@ -1,276 +0,0 @@ -package thaumcraft.api.wands; - -import java.text.DecimalFormat; -import java.util.LinkedHashMap; -import java.util.List; - -import net.minecraft.entity.Entity; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.EnumRarity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.util.IIcon; -import net.minecraft.util.MovingObjectPosition; -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; -import thaumcraft.api.aspects.Aspect; -import thaumcraft.api.aspects.AspectList; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -public class ItemFocusBasic extends Item { - - public ItemFocusBasic () - { - super(); - maxStackSize = 1; - canRepair=false; - this.setMaxDamage(0); - } - - public IIcon icon; - - @SideOnly(Side.CLIENT) - @Override - public IIcon getIconFromDamage(int par1) { - return icon; - } - - @Override - public boolean isDamageable() { - return false; - } - - @Override - public void addInformation(ItemStack stack,EntityPlayer player, List list, boolean par4) { - AspectList al = this.getVisCost(stack); - if (al!=null && al.size()>0) { - list.add(StatCollector.translateToLocal(isVisCostPerTick(stack)?"item.Focus.cost2":"item.Focus.cost1")); - for (Aspect aspect:al.getAspectsSorted()) { - DecimalFormat myFormatter = new DecimalFormat("#####.##"); - String amount = myFormatter.format(al.getAmount(aspect)/100f); - list.add(" \u00A7"+aspect.getChatcolor()+aspect.getName()+"\u00A7r x "+ amount); - } - } - addFocusInformation(stack,player,list,par4); - } - - public void addFocusInformation(ItemStack focusstack,EntityPlayer player, List list, boolean par4) { - LinkedHashMap map = new LinkedHashMap(); - for (short id:this.getAppliedUpgrades(focusstack)) { - if (id>=0) { - int amt = 1; - if (map.containsKey(id)) { - amt = map.get(id) + 1; - } - map.put(id, amt); - } - } - for (Short id:map.keySet()) { - list.add(EnumChatFormatting.DARK_PURPLE +FocusUpgradeType.types[id].getLocalizedName()+ - (map.get(id)>1?" "+StatCollector.translateToLocal("enchantment.level." + map.get(id)):"")); - } - } - - /** - * Purely for display on the focus tooltip (see addInformation method above) - */ - public boolean isVisCostPerTick(ItemStack focusstack) { - return false; - } - - @Override - public EnumRarity getRarity(ItemStack focusstack) - { - return EnumRarity.rare; - } - - /** - * What color will the focus orb be rendered on the held wand - */ - public int getFocusColor(ItemStack focusstack) { - return 0; - } - - - /** - * Does the focus have ornamentation like the focus of the nine hells. Ornamentation is a standard icon rendered in a cross around the focus - */ - public IIcon getOrnament(ItemStack focusstack) { - // TODO Auto-generated method stub - return null; - } - - /** - * An icon to be rendered inside the focus itself - */ - public IIcon getFocusDepthLayerIcon(ItemStack focusstack) { - // TODO Auto-generated method stub - return null; - } - - public enum WandFocusAnimation { - WAVE, CHARGE; - } - - public WandFocusAnimation getAnimation(ItemStack focusstack) { - return WandFocusAnimation.WAVE; - } - - /** - * Just insert two alphanumeric characters before this string in your focus item class - */ - public String getSortingHelper(ItemStack focusstack) { - String out=""; - for (short id:this.getAppliedUpgrades(focusstack)) { - out = out + id; - } - return out; - } - - - /** - * How much vis does this focus consume per activation. - */ - public AspectList getVisCost(ItemStack focusstack) { - return null; - } - - /** - * This returns how many milliseconds must pass before the focus can be activated again. - */ - public int getActivationCooldown(ItemStack focusstack) { - return 0; - } - - /** - * Used by foci like equal trade to determine their area in artchitect mode - */ - public int getMaxAreaSize(ItemStack focusstack) { - return 1; - } - - /** - * What upgrades can be applied to this focus for ranks 1 to 5 - */ - public FocusUpgradeType[] getPossibleUpgradesByRank(ItemStack focusstack, int rank) { - return null; - } - - /** - * What upgrades does the focus currently have - */ - public short[] getAppliedUpgrades(ItemStack focusstack) { - short[] l = new short[] {-1,-1,-1,-1,-1}; - NBTTagList nbttaglist = getFocusUpgradeTagList(focusstack); - if (nbttaglist == null) - { - return l; - } - else - { - for (int j = 0; j < nbttaglist.tagCount(); ++j) - { - if (j>=5) break; - l[j] = nbttaglist.getCompoundTagAt(j).getShort("id"); - } - - return l; - } - } - - public boolean applyUpgrade(ItemStack focusstack, FocusUpgradeType type, int rank) { - short[] upgrades = getAppliedUpgrades(focusstack); - if (upgrades[rank-1]!=-1 || rank<1 || rank>5) { - return false; - } - upgrades[rank-1] = type.id; - setFocusUpgradeTagList(focusstack, upgrades); - return true; - } - - /** - * Use this method to define custom logic about which upgrades can be applied. This can be used to set up upgrade "trees" - * that make certain upgrades available only when others are unlocked first, when certain research is completed, or similar logic. - * - */ - public boolean canApplyUpgrade(ItemStack focusstack, EntityPlayer player, FocusUpgradeType type, int rank) { - return true; - } - - /** - * Does this focus have the passed upgrade type - */ - public boolean isUpgradedWith(ItemStack focusstack, FocusUpgradeType focusUpgradetype) { - return getUpgradeLevel(focusstack,focusUpgradetype)>0; - } - - /** - * What level is the passed upgrade type on the focus. If it is not present it returns 0 - */ - public int getUpgradeLevel(ItemStack focusstack, FocusUpgradeType focusUpgradetype) { - short[] list = getAppliedUpgrades(focusstack); - int level=0; - for (short id:list) { - if (id == focusUpgradetype.id) - { - level++; - } - } - return level; - } - - public ItemStack onFocusRightClick(ItemStack wandstack, World world,EntityPlayer player, MovingObjectPosition movingobjectposition) { - // TODO Auto-generated method stub - return null; - } - - public void onUsingFocusTick(ItemStack wandstack, EntityPlayer player,int count) { - // TODO Auto-generated method stub - } - - public void onPlayerStoppedUsingFocus(ItemStack wandstack, World world, EntityPlayer player, int count) { - // TODO Auto-generated method stub - - } - - public boolean onFocusBlockStartBreak(ItemStack wandstack, int x, int y,int z, EntityPlayer player) { - // TODO Auto-generated method stub - return false; - } - - /** - * Internal helper methods - */ - private NBTTagList getFocusUpgradeTagList(ItemStack focusstack) - { - return focusstack.stackTagCompound == null ? null : focusstack.stackTagCompound.getTagList("upgrade", 10); - } - - private void setFocusUpgradeTagList(ItemStack focusstack, short[] upgrades) { - if (!focusstack.hasTagCompound()) - focusstack.setTagCompound(new NBTTagCompound()); - NBTTagCompound nbttagcompound = focusstack.getTagCompound(); - NBTTagList tlist = new NBTTagList(); - nbttagcompound.setTag("upgrade", tlist); - for (short id : upgrades) { - NBTTagCompound f = new NBTTagCompound(); - f.setShort("id", id); - tlist.appendTag(f); - } - } - - @Override - public void onUpdate(ItemStack stack, World world, Entity entity, int p_77663_4_, boolean p_77663_5_) { - if (stack.stackTagCompound !=null && stack.stackTagCompound.hasKey("ench")) { - stack.stackTagCompound.removeTag("ench"); - } - super.onUpdate(stack, world, entity, p_77663_4_, p_77663_5_); - } - - - -} diff --git a/src/api/java/thaumcraft/api/wands/StaffRod.java b/src/api/java/thaumcraft/api/wands/StaffRod.java deleted file mode 100644 index e7ae90f06..000000000 --- a/src/api/java/thaumcraft/api/wands/StaffRod.java +++ /dev/null @@ -1,48 +0,0 @@ -package thaumcraft.api.wands; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -/** - * - * @author Azanor - * - * This class is used to keep the material information for the various rods. - * It is also used to generate the wand recipes ingame. - * - */ -public class StaffRod extends WandRod { - - boolean runes=false; - - public StaffRod(String tag, int capacity, ItemStack item, int craftCost) { - super(tag+"_staff", capacity, item, craftCost); - this.texture = new ResourceLocation("thaumcraft","textures/models/wand_rod_"+tag+".png"); - } - - public StaffRod(String tag, int capacity, ItemStack item, int craftCost, - IWandRodOnUpdate onUpdate, ResourceLocation texture) { - super(tag+"_staff", capacity, item, craftCost, onUpdate, texture); - } - - public StaffRod(String tag, int capacity, ItemStack item, int craftCost, - IWandRodOnUpdate onUpdate) { - super(tag+"_staff", capacity, item, craftCost, onUpdate); - this.texture = new ResourceLocation("thaumcraft","textures/models/wand_rod_"+tag+".png"); - } - - public StaffRod(String tag, int capacity, ItemStack item, int craftCost, - ResourceLocation texture) { - super(tag+"_staff", capacity, item, craftCost, texture); - } - - public boolean hasRunes() { - return runes; - } - - public void setRunes(boolean hasRunes) { - this.runes = hasRunes; - } - - -} diff --git a/src/api/java/thaumcraft/api/wands/WandCap.java b/src/api/java/thaumcraft/api/wands/WandCap.java deleted file mode 100644 index 17b4581cd..000000000 --- a/src/api/java/thaumcraft/api/wands/WandCap.java +++ /dev/null @@ -1,129 +0,0 @@ -package thaumcraft.api.wands; - -import java.util.LinkedHashMap; -import java.util.List; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import thaumcraft.api.aspects.Aspect; - -/** - * This class is used to keep the material information for the various caps. - * It is also used to generate the wand recipes ingame. - * @author Azanor - * - */ -public class WandCap { - - private String tag; - - /** - * Cost to craft this wand. Combined with the rod cost. - */ - private int craftCost; - - /** - * the amount by which all aspect costs are multiplied - */ - float baseCostModifier; - - /** - * specifies a list of primal aspects that use the special discount figure instead of the normal discount. - */ - List specialCostModifierAspects; - - /** - * the amount by which the specified aspect costs are multiplied - */ - float specialCostModifier; - - /** - * The texture that will be used for the ingame wand cap - */ - ResourceLocation texture; - - /** - * the actual item that makes up this cap and will be used to generate the wand recipes - */ - ItemStack item; - - public static LinkedHashMap caps = new LinkedHashMap(); - - public WandCap (String tag, float discount, ItemStack item, int craftCost) { - this.setTag(tag); - this.baseCostModifier = discount; - this.specialCostModifierAspects = null; - texture = new ResourceLocation("thaumcraft","textures/models/wand_cap_"+getTag()+".png"); - this.item=item; - this.setCraftCost(craftCost); - caps.put(tag, this); - } - - public WandCap (String tag, float discount, List specialAspects, float discountSpecial, ItemStack item, int craftCost) { - this.setTag(tag); - this.baseCostModifier = discount; - this.specialCostModifierAspects = specialAspects; - this.specialCostModifier = discountSpecial; - texture = new ResourceLocation("thaumcraft","textures/models/wand_cap_"+getTag()+".png"); - this.item=item; - this.setCraftCost(craftCost); - caps.put(tag, this); - } - - public float getBaseCostModifier() { - return baseCostModifier; - } - - public List getSpecialCostModifierAspects() { - return specialCostModifierAspects; - } - - public float getSpecialCostModifier() { - return specialCostModifier; - } - - public ResourceLocation getTexture() { - return texture; - } - - public void setTexture(ResourceLocation texture) { - this.texture = texture; - } - - public String getTag() { - return tag; - } - - public void setTag(String tag) { - this.tag = tag; - } - - - public ItemStack getItem() { - return item; - } - - public void setItem(ItemStack item) { - this.item = item; - } - - public int getCraftCost() { - return craftCost; - } - - public void setCraftCost(int craftCost) { - this.craftCost = craftCost; - } - - /** - * The research a player needs to have finished to be able to craft a wand with this cap. - */ - public String getResearch() { - return "CAP_"+getTag(); - } - - // Some examples: - // WandCap WAND_CAP_IRON = new WandCap("iron", 1.1f, Arrays.asList(Aspect.ORDER),1, new ItemStack(ConfigItems.itemWandCap,1,0),1); - // WandCap WAND_CAP_GOLD = new WandCap("gold", 1f, new ItemStack(ConfigItems.itemWandCap,1,1),3); - -} diff --git a/src/api/java/thaumcraft/api/wands/WandRod.java b/src/api/java/thaumcraft/api/wands/WandRod.java deleted file mode 100644 index 85954e464..000000000 --- a/src/api/java/thaumcraft/api/wands/WandRod.java +++ /dev/null @@ -1,158 +0,0 @@ -package thaumcraft.api.wands; - -import java.util.LinkedHashMap; - -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; - -/** - * - * @author Azanor - * - * This class is used to keep the material information for the various rods. - * It is also used to generate the wand recipes ingame. - * - */ -public class WandRod { - - - private String tag; - - /** - * Cost to craft this wand. Combined with the rod cost. - */ - private int craftCost; - - /** - * The amount of vis that can be stored - this number is actually multiplied - * by 100 for use by the wands internals - */ - int capacity; - - /** - * The texture that will be used for the ingame wand rod - */ - protected ResourceLocation texture; - - /** - * the actual item that makes up this rod and will be used to generate the wand recipes - */ - ItemStack item; - - /** - * A class that will be called whenever the wand onUpdate tick is run - */ - IWandRodOnUpdate onUpdate; - - /** - * Does the rod glow in the dark? - */ - boolean glow; - - public static LinkedHashMap rods = new LinkedHashMap(); - - public WandRod (String tag, int capacity, ItemStack item, int craftCost, ResourceLocation texture) { - this.setTag(tag); - this.capacity = capacity; - this.texture = texture; - this.item=item; - this.setCraftCost(craftCost); - rods.put(tag, this); - } - - public WandRod (String tag, int capacity, ItemStack item, int craftCost, IWandRodOnUpdate onUpdate, ResourceLocation texture) { - this.setTag(tag); - this.capacity = capacity; - this.texture = texture; - this.item=item; - this.setCraftCost(craftCost); - rods.put(tag, this); - this.onUpdate = onUpdate; - } - - public WandRod (String tag, int capacity, ItemStack item, int craftCost) { - this.setTag(tag); - this.capacity = capacity; - this.texture = new ResourceLocation("thaumcraft","textures/models/wand_rod_"+getTag()+".png"); - this.item=item; - this.setCraftCost(craftCost); - rods.put(tag, this); - } - - public WandRod (String tag, int capacity, ItemStack item, int craftCost, IWandRodOnUpdate onUpdate) { - this.setTag(tag); - this.capacity = capacity; - this.texture = new ResourceLocation("thaumcraft","textures/models/wand_rod_"+getTag()+".png"); - this.item=item; - this.setCraftCost(craftCost); - rods.put(tag, this); - this.onUpdate = onUpdate; - } - - public String getTag() { - return tag; - } - - public void setTag(String tag) { - this.tag = tag; - } - - public int getCapacity() { - return capacity; - } - - public void setCapacity(int capacity) { - this.capacity = capacity; - } - - public ResourceLocation getTexture() { - return texture; - } - - public void setTexture(ResourceLocation texture) { - this.texture = texture; - } - - public ItemStack getItem() { - return item; - } - - public void setItem(ItemStack item) { - this.item = item; - } - - public int getCraftCost() { - return craftCost; - } - - public void setCraftCost(int craftCost) { - this.craftCost = craftCost; - } - - public IWandRodOnUpdate getOnUpdate() { - return onUpdate; - } - - public void setOnUpdate(IWandRodOnUpdate onUpdate) { - this.onUpdate = onUpdate; - } - - public boolean isGlowing() { - return glow; - } - - public void setGlowing(boolean hasGlow) { - this.glow = hasGlow; - } - - /** - * The research a player needs to have finished to be able to craft a wand with this rod. - */ - public String getResearch() { - return "ROD_"+getTag(); - } - - // Some examples: - // WandRod WAND_ROD_WOOD = new WandRod("wood",25,new ItemStack(Item.stick),1); - // WandRod WAND_ROD_BLAZE = new WandRod("blaze",100,new ItemStack(Item.blazeRod),7,new WandRodBlazeOnUpdate()); -} diff --git a/src/api/java/thaumcraft/api/wands/WandTriggerRegistry.java b/src/api/java/thaumcraft/api/wands/WandTriggerRegistry.java deleted file mode 100644 index 7224e12fb..000000000 --- a/src/api/java/thaumcraft/api/wands/WandTriggerRegistry.java +++ /dev/null @@ -1,126 +0,0 @@ -package thaumcraft.api.wands; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -import net.minecraft.block.Block; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; - -/** - * This class serves a similar function to IWandable in that it allows wands to interact - * with object in the world. In this case it is most useful for adding interaction with non-mod - * blocks where you can't control what happens in their code. - * Example where it is used is in crafting the thaumonomicon from a bookshelf and the - * crucible from a cauldron - * - * @author azanor - * - */ -public class WandTriggerRegistry { - - private static HashMap> triggers = new HashMap>(); - private static final String DEFAULT = "default"; - - /** - * Registers an action to perform when a casting wand right clicks on a specific block. - * A manager class needs to be created that implements IWandTriggerManager. - * @param manager - * @param event a logical number that you can use to differentiate different events or actions - * @param block - * @param meta send -1 as a wildcard value for all possible meta values - * @param modid a unique identifier. It is best to register your own triggers using your mod id to avoid conflicts with mods that register triggers for the same block - */ - public static void registerWandBlockTrigger(IWandTriggerManager manager, int event, Block block, int meta, String modid) { - if (!triggers.containsKey(modid)) { - triggers.put(modid, new HashMap()); - } - HashMap temp = triggers.get(modid); - temp.put(Arrays.asList(block,meta),Arrays.asList(manager,event)); - triggers.put(modid, temp); - } - - /** - * for legacy support - */ - public static void registerWandBlockTrigger(IWandTriggerManager manager, int event, Block block, int meta) { - registerWandBlockTrigger(manager, event, block, meta, DEFAULT); - } - - /** - * Checks all trigger registries if one exists for the given block and meta - * @param block - * @param meta - * @return - */ - public static boolean hasTrigger(Block block, int meta) { - for (String modid:triggers.keySet()) { - HashMap temp = triggers.get(modid); - if (temp.containsKey(Arrays.asList(block,meta)) || - temp.containsKey(Arrays.asList(block,-1))) return true; - } - return false; - } - - /** - * modid sensitive version - */ - public static boolean hasTrigger(Block block, int meta, String modid) { - if (!triggers.containsKey(modid)) return false; - HashMap temp = triggers.get(modid); - if (temp.containsKey(Arrays.asList(block,meta)) || - temp.containsKey(Arrays.asList(block,-1))) return true; - return false; - } - - - /** - * This is called by the onItemUseFirst function in wands. - * Parameters and return value functions like you would expect for that function. - * @param world - * @param wand - * @param player - * @param x - * @param y - * @param z - * @param side - * @param block - * @param meta - * @return - */ - public static boolean performTrigger(World world, ItemStack wand, EntityPlayer player, - int x, int y, int z, int side, Block block, int meta) { - - for (String modid:triggers.keySet()) { - HashMap temp = triggers.get(modid); - List l = temp.get(Arrays.asList(block,meta)); - if (l==null) l = temp.get(Arrays.asList(block,-1)); - if (l==null) continue; - - IWandTriggerManager manager = (IWandTriggerManager) l.get(0); - int event = (Integer) l.get(1); - boolean result = manager.performTrigger(world, wand, player, x, y, z, side, event); - if (result) return true; - } - return false; - } - - /** - * modid sensitive version - */ - public static boolean performTrigger(World world, ItemStack wand, EntityPlayer player, - int x, int y, int z, int side, Block block, int meta, String modid) { - if (!triggers.containsKey(modid)) return false; - HashMap temp = triggers.get(modid); - List l = temp.get(Arrays.asList(block,meta)); - if (l==null) l = temp.get(Arrays.asList(block,-1)); - if (l==null) return false; - - IWandTriggerManager manager = (IWandTriggerManager) l.get(0); - int event = (Integer) l.get(1); - return manager.performTrigger(world, wand, player, x, y, z, side, event); - } - -} diff --git a/src/api/java/thaumicenergistics/api/IThEBlocks.java b/src/api/java/thaumicenergistics/api/IThEBlocks.java deleted file mode 100644 index 4eeacde7c..000000000 --- a/src/api/java/thaumicenergistics/api/IThEBlocks.java +++ /dev/null @@ -1,20 +0,0 @@ -package thaumicenergistics.api; - -public abstract class IThEBlocks -{ - public IThEItemDescription EssentiaProvider; - - public IThEItemDescription InfusionProvider; - - public IThEItemDescription IronGearBox; - - public IThEItemDescription ThaumiumGearBox; - - public IThEItemDescription EssentiaCellWorkbench; - - public IThEItemDescription ArcaneAssembler; - - public IThEItemDescription KnowledgeInscriber; - - public IThEItemDescription EssentiaVibrationChamber; -} diff --git a/src/api/java/thaumicenergistics/api/IThEConfig.java b/src/api/java/thaumicenergistics/api/IThEConfig.java deleted file mode 100644 index 83c75a1f3..000000000 --- a/src/api/java/thaumicenergistics/api/IThEConfig.java +++ /dev/null @@ -1,38 +0,0 @@ -package thaumicenergistics.api; - -public interface IThEConfig -{ - /** - * Controls if the Essentia Provider is allowed to be crafted. - */ - public boolean allowedToCraftEssentiaProvider(); - - /** - * Controls if the Infusion Provider is allowed to be crafted. - */ - public boolean allowedToCraftInfusionProvider(); - - /** - * Controls if Certus Quartz can be duped in the crucible. - */ - public boolean allowedToDuplicateCertusQuartz(); - - /** - * If true essentia gas will be blacklisted from ExtraCells. - * - * @return - */ - public boolean blacklistEssentiaFluidInExtraCells(); - - /** - * Controls the conversion ratio of essentia/fluid.
- * 1 essentia unit is converted to this many mb's of fluid. - */ - public int conversionMultiplier(); - - /** - * If true the iron and thaumium gearbox's will be rendered as a standard - * block. - */ - public boolean gearboxModelDisabled(); -} diff --git a/src/api/java/thaumicenergistics/api/IThEEssentiaContainerPermission.java b/src/api/java/thaumicenergistics/api/IThEEssentiaContainerPermission.java deleted file mode 100644 index d31755cf6..000000000 --- a/src/api/java/thaumicenergistics/api/IThEEssentiaContainerPermission.java +++ /dev/null @@ -1,14 +0,0 @@ -package thaumicenergistics.api; - -public interface IThEEssentiaContainerPermission -{ - /** - * Can the container be partially filled? - */ - public boolean canHoldPartialAmount(); - - /** - * The maximum amount this container can hold - */ - public int maximumCapacity(); -} diff --git a/src/api/java/thaumicenergistics/api/IThEEssentiaGas.java b/src/api/java/thaumicenergistics/api/IThEEssentiaGas.java deleted file mode 100644 index 7f011a839..000000000 --- a/src/api/java/thaumicenergistics/api/IThEEssentiaGas.java +++ /dev/null @@ -1,21 +0,0 @@ -package thaumicenergistics.api; - -import net.minecraftforge.fluids.Fluid; -import thaumcraft.api.aspects.Aspect; - -public interface IThEEssentiaGas -{ - /** - * Get the aspect this gas is based off of. - * - * @return - */ - public Aspect getAspect(); - - /** - * Gets the fluid form of the gas. - * - * @return - */ - public Fluid getFluid(); -} diff --git a/src/api/java/thaumicenergistics/api/IThEInteractionHelper.java b/src/api/java/thaumicenergistics/api/IThEInteractionHelper.java deleted file mode 100644 index 106bbad06..000000000 --- a/src/api/java/thaumicenergistics/api/IThEInteractionHelper.java +++ /dev/null @@ -1,54 +0,0 @@ -package thaumicenergistics.api; - -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; - -/** - * Contains misc functionality intended to help other moders interact with ThE. - * - * @author Nividica - * - */ -public interface IThEInteractionHelper -{ - /** - * Converts an amount of milibuckets to an amount of Essentia. - * - * @return - */ - public abstract long convertEssentiaAmountToFluidAmount( long essentiaAmount ); - - /** - * Converts an amount of Essentia to an amount of milibuckets. - * - * @return - */ - public abstract long convertFluidAmountToEssentiaAmount( long milibuckets ); - - /** - * Returns the Arcane Crafting Terminals GUI class. - */ - @SideOnly(Side.CLIENT) - public abstract Class getArcaneCraftingTerminalGUIClass(); - - /** - * Opens the wireless gui for the specified player. - * The item the player is holding is used for the settings and power. - * - * @param player - */ - public abstract void openWirelessTerminalGui( final EntityPlayer player, final IThEWirelessEssentiaTerminal terminalInterface ); - - /** - * Attempts to set the Arcane Crafting Terminals recipe to the items - * specified for the current player. - * The items array should be of size 9. Items will be placed in the crafting - * grid according - * to index where 0 = Top-Left, 1 = Top-Middle, 2 = Top-Right, etc. - * Nulls are allowed. - */ - @SideOnly(Side.CLIENT) - public abstract void setArcaneCraftingTerminalRecipe( ItemStack[] items ); -} diff --git a/src/api/java/thaumicenergistics/api/IThEItemDescription.java b/src/api/java/thaumicenergistics/api/IThEItemDescription.java deleted file mode 100644 index e3db34916..000000000 --- a/src/api/java/thaumicenergistics/api/IThEItemDescription.java +++ /dev/null @@ -1,45 +0,0 @@ -package thaumicenergistics.api; - -import net.minecraft.block.Block; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; - -public interface IThEItemDescription -{ - - /** - * Gets the block of this item if it has one. - * - * @return - */ - public Block getBlock(); - - /** - * Gets the damage, or meta, value of the item. - * - * @return - */ - public int getDamage(); - - /** - * Gets the item. - * - * @return - */ - public Item getItem(); - - /** - * Gets a stack of size 1. - * - * @return - */ - public ItemStack getStack(); - - /** - * Gets a stack of the specified size. - * - * @param amount - * @return - */ - public ItemStack getStacks( int amount ); -} diff --git a/src/api/java/thaumicenergistics/api/IThEItems.java b/src/api/java/thaumicenergistics/api/IThEItems.java deleted file mode 100644 index b8813ff75..000000000 --- a/src/api/java/thaumicenergistics/api/IThEItems.java +++ /dev/null @@ -1,34 +0,0 @@ -package thaumicenergistics.api; - -public abstract class IThEItems -{ - public IThEItemDescription CoalescenceCore; - - public IThEItemDescription DiffusionCore; - - public IThEItemDescription EssentiaCell_16k; - - public IThEItemDescription EssentiaCell_1k; - - public IThEItemDescription EssentiaCell_4k; - - public IThEItemDescription EssentiaCell_64k; - - public IThEItemDescription EssentiaCell_Casing; - - public IThEItemDescription EssentiaStorageComponent_16k; - - public IThEItemDescription EssentiaStorageComponent_1k; - - public IThEItemDescription EssentiaStorageComponent_4k; - - public IThEItemDescription EssentiaStorageComponent_64k; - - public IThEItemDescription IronGear; - - public IThEItemDescription WirelessEssentiaTerminal; - - public IThEItemDescription KnowledgeCore; - - public IThEItemDescription WandFocusAEWrench; -} diff --git a/src/api/java/thaumicenergistics/api/IThEParts.java b/src/api/java/thaumicenergistics/api/IThEParts.java deleted file mode 100644 index 9d17aee67..000000000 --- a/src/api/java/thaumicenergistics/api/IThEParts.java +++ /dev/null @@ -1,22 +0,0 @@ -package thaumicenergistics.api; - -public abstract class IThEParts -{ - public IThEItemDescription ArcaneCrafting_Terminal; - - public IThEItemDescription Essentia_ExportBus; - - public IThEItemDescription Essentia_ImportBus; - - public IThEItemDescription Essentia_LevelEmitter; - - public IThEItemDescription Essentia_StorageBus; - - public IThEItemDescription Essentia_Terminal; - - public IThEItemDescription VisRelay_Interface; - - public IThEItemDescription Essentia_StorageMonitor; - - public IThEItemDescription Essentia_ConversionMonitor; -} diff --git a/src/api/java/thaumicenergistics/api/IThETransportPermissions.java b/src/api/java/thaumicenergistics/api/IThETransportPermissions.java deleted file mode 100644 index fb8b83f09..000000000 --- a/src/api/java/thaumicenergistics/api/IThETransportPermissions.java +++ /dev/null @@ -1,103 +0,0 @@ -package thaumicenergistics.api; - -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import thaumcraft.api.aspects.IAspectContainer; -import thaumcraft.api.aspects.IEssentiaContainerItem; - -/** - * Defines what items and tile entities ThaumicEnergistics is allowed to - * interact with. - * - * @author Nividica - * - */ -public interface IThETransportPermissions -{ - - /** - * Adds a tile entity to both inject & extract whitelists. - * The tile must implement the interface {@link IAspectContainer}
- * Capacity is required to function properly. - * - * @param tileClass - * @return True if added to the lists, False if not. - */ - public boolean addAspectContainerTileToBothPermissions( Class tileClass, int capacity ); - - /** - * Adds a tile entity to the extract whitelist. - * The tile must implement the interface {@link IAspectContainer}
- * Note: Capacity can be 0 if the tile doesn't truely 'contain' essentia. - * - * @param tileClass - * @return True if added to the list or already present, False otherwise. - */ - public boolean addAspectContainerTileToExtractPermissions( Class tileClass, int capacity ); - - /** - * Adds a tile entity to the inject whitelist. - * The tile must implement the interface {@link IAspectContainer}
- * Capacity is required to function properly. - * - * @param tileClass - * @return True if added to the list, False if not. - */ - public boolean addAspectContainerTileToInjectPermissions( Class tileClass, int capacity ); - - /** - * Adds an item to the whitelist that must match the specified damage - * value. - * - * @param itemClass - * @param capacity - * @param damageValue - * @param canHoldPartialAmount - */ - public void addEssentiaContainerItemToTransportPermissions( Class itemClass, int capacity, int damageValue, - boolean canHoldPartialAmount ); - - /** - * Adds the specified item to the whitelist. - * - * @param containerItem - * @param capacity - * @param canHoldPartialAmount - */ - public void addEssentiaContainerItemToTransportPermissions( ItemStack containerItem, int capacity, boolean canHoldPartialAmount ); - - /** - * Checks if the container can be extracted from - * - * @param container - * @return - */ - public boolean canExtractFromAspectContainerTile( final IAspectContainer container ); - - /** - * Checks if the container can be injected into - * - * @param container - * @return - */ - public boolean canInjectToAspectContainerTile( IAspectContainer container ); - - /** - * Returns the registered capacity of the specified container. - * - * @param container - * @return Registered capacity, or -1 if not registered. - */ - public int getAspectContainerTileCapacity( IAspectContainer container ); - - /** - * Gets the information about the container as it was registered to the - * whitelist. - * - * @param itemClass - * @param damageValue - * @return Info if was registered, null otherwise. - */ - public IThEEssentiaContainerPermission getEssentiaContainerInfo( Class itemClass, int damageValue ); -} diff --git a/src/api/java/thaumicenergistics/api/IThEWirelessEssentiaTerminal.java b/src/api/java/thaumicenergistics/api/IThEWirelessEssentiaTerminal.java deleted file mode 100644 index 665806117..000000000 --- a/src/api/java/thaumicenergistics/api/IThEWirelessEssentiaTerminal.java +++ /dev/null @@ -1,26 +0,0 @@ -package thaumicenergistics.api; - -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import appeng.api.features.INetworkEncodable; -import appeng.api.implementations.items.IAEItemPowerStorage; - -/** - * Provides the required functionality of a wireless terminal. - * Presumably this interface would be implemented on an Item, but that is - * not a requirement. - * - * @author Nividica - * - */ -public interface IThEWirelessEssentiaTerminal - extends INetworkEncodable, IAEItemPowerStorage -{ - /** - * Gets the tag used to store the terminal data. - * - * @param terminalItemstack - * @return - */ - public NBTTagCompound getWETerminalTag( ItemStack terminalItemstack ); -} diff --git a/src/api/java/thaumicenergistics/api/ThEApi.java b/src/api/java/thaumicenergistics/api/ThEApi.java deleted file mode 100644 index e66f5037b..000000000 --- a/src/api/java/thaumicenergistics/api/ThEApi.java +++ /dev/null @@ -1,81 +0,0 @@ -package thaumicenergistics.api; - -import java.lang.reflect.Method; -import java.util.List; -import com.google.common.collect.ImmutableList; - -/** - * Thaumic Energistics API - */ -public abstract class ThEApi -{ - protected static ThEApi api = null; - - /** - * Gets the Thaumic Energistics API. - * Note: Only available after the PREINIT event. - */ - public static ThEApi instance() - { - // Have we already retrieved the api? - if( ThEApi.api == null ) - { - try - { - // Attempt to locate the API implementation - Class clazz = Class.forName( "thaumicenergistics.implementaion.ThEAPIImplementation" ); - - // Get the instance method - Method instanceAccessor = clazz.getMethod( "instance" ); - - // Attempt to get the API instance - ThEApi.api = (ThEApi)instanceAccessor.invoke( null ); - } - catch( Throwable e ) - { - // Unable to locate the API, return null - return null; - } - } - - return ThEApi.api; - } - - /** - * Blocks - */ - public abstract IThEBlocks blocks(); - - /** - * Configuration - */ - public abstract IThEConfig config(); - - /** - * Essentia Gasses - */ - public abstract ImmutableList> essentiaGases(); - - /** - * Gets the ThE interaction manager - * - * @return - */ - public abstract IThEInteractionHelper interact(); - - /** - * Items - */ - public abstract IThEItems items(); - - /** - * Cable Parts - */ - public abstract IThEParts parts(); - - /** - * Transport Permissions. - */ - public abstract IThETransportPermissions transportPermissions(); - -} diff --git a/src/main/resources/ExtraCells2.png b/src/main/resources/ExtraCells2.png new file mode 100644 index 000000000..d7457fc45 Binary files /dev/null and b/src/main/resources/ExtraCells2.png differ diff --git a/src/main/resources/assets/extracells/lang/en_US.lang b/src/main/resources/assets/extracells/lang/en_US.lang index 84678cb13..dc0466b87 100644 --- a/src/main/resources/assets/extracells/lang/en_US.lang +++ b/src/main/resources/assets/extracells/lang/en_US.lang @@ -1,13 +1,16 @@ -//**********// -//EXTRACELLS// -//**********// +############ +#EXTRACELLS# +############ -//Items +#Items extracells.item.storage.physical.256k.name=ME 256k Storage extracells.item.storage.physical.1024k.name=ME 1024k Storage extracells.item.storage.physical.4096k.name=ME 4096k Storage extracells.item.storage.physical.16384k.name=ME 16384k Storage extracells.item.storage.physical.container.name=ME Block Container +extracells.item.storage.physical.advanced.singularity.name=ME Digital Singularity +extracells.item.storage.physical.advanced.quantum.name=ME Quantum Storage +extracells.item.storage.physical.void.name=ME Void Storage extracells.item.storage.fluid.1k.name=ME 1k Fluid Storage extracells.item.storage.fluid.4k.name=ME 4k Fluid Storage extracells.item.storage.fluid.16k.name=ME 16k Fluid Storage @@ -51,14 +54,14 @@ extracells.item.terminal.universal.wireless.name=Wireless Universal Terminal extracells.item.fluid.pattern=ME Fluid Pattern [WIP] extracells.item.oc.upgrade.name=ME Upgrade -//Creative Tab +#Creative Tab itemGroup.Extra_Cells=Extra Cells 2 -//Item Groups +#Item Groups extracells.fluid.IO=ME Fluid Export/Import Bus extracells.fluid.plane=ME Fluid Annihilation/Formation Plane -//Parts +#Parts extracells.part.fluid.export.name=ME Fluid Export Bus extracells.part.fluid.import.name=ME Fluid Import Bus extracells.part.fluid.storage.name=ME Fluid Storage Bus @@ -79,16 +82,20 @@ extracells.part.gas.levelemitter.name=ME Gas Level Emitter extracells.part.gas.conversion.monitor.name=ME Gas Conversion Monitor extracells.part.gas.monitor.name=ME Gas Storage Monitor -//Blocks +#Blocks extracells.block.certustank=Certus Quartz Tank extracells.block.walrus.name=Walrus extracells.block.fluidcrafter.name=ME Fluid Assembler extracells.block.fluidinterface.name=ME Fluid Interface extracells.block.fluidfiller.name=ME Fluid Auto Filler +tile.extracells.block.craftingstorage.256k.name=256k Crafting Storage +tile.extracells.block.craftingstorage.1024k.name=1024k Crafting Storage +tile.extracells.block.craftingstorage.4096k.name=4096k Crafting Storage +tile.extracells.block.craftingstorage.16384k.name=16384k Crafting Storage tile.extracells.block.vibrantchamberfluid.name=Fluid Vibration Chamber tile.extracells.block.hardmedrive.name=Blast resistant ME Drive [WIP] -//Tooltips and Chat-Messages +#Tooltips and Chat-Messages extracells.tooltip.amount=Amount extracells.tooltip.fluid=Fluid extracells.tooltip.storage.physical.types=%s of %s item types used. @@ -120,5 +127,6 @@ extracells.tooltip.essentia=Essentia extracells.tooltip.installed=Installed: extracells.tooltip.crafting=Crafting -//Buttons +#Buttons extracells.gui.craft=Craft +extracells.gui.fluid.storage=Fluid Storage Bus diff --git a/src/main/resources/assets/extracells/lang/ru_RU.lang b/src/main/resources/assets/extracells/lang/ru_RU.lang index b6e5010a1..c72085a4d 100644 --- a/src/main/resources/assets/extracells/lang/ru_RU.lang +++ b/src/main/resources/assets/extracells/lang/ru_RU.lang @@ -16,24 +16,43 @@ extracells.item.storage.fluid.256k.name=МЭ 256Кб жидкостное хра extracells.item.storage.fluid.1024k.name=МЭ 1024kб жидкостное хранилище extracells.item.storage.fluid.4096k.name=МЭ 4096kб жидкостное хранилище extracells.item.storage.fluid.portable.name=МЭ переносное жидкостное хранилище +extracells.item.storage.gas.1k.name=ME 1Кб газовое хранилище +extracells.item.storage.gas.4k.name=ME 4Кб газовое хранилище +extracells.item.storage.gas.16k.name=ME 16Кб газовое хранилище +extracells.item.storage.gas.64k.name=ME 64Кб газовое хранилище +extracells.item.storage.gas.256k.name=ME 256Кб газовое хранилище +extracells.item.storage.gas.1024k.name=ME 1024Кб газовое хранилище +extracells.item.storage.gas.4096k.name=ME 4096Кб газовое хранилище +extracells.item.storage.gas.portable.name=МЭ переносное газовое хранилище extracells.item.storage.component.physical.256k.name=256Кб МЭ компонент хранилища extracells.item.storage.component.physical.1024k.name=1024Кб МЭ компонент хранилища extracells.item.storage.component.physical.4096k.name=4096Кб МЭ компонент хранилища extracells.item.storage.component.physical.16384k.name=16384Кб МЭ компонент хранилища -extracells.item.storage.component.fluid.1k.name=1Кб МЭ жидкостный компонент хранилища -extracells.item.storage.component.fluid.4k.name=4Кб МЭ жидкостный компонент хранилища -extracells.item.storage.component.fluid.16k.name=16Кб МЭ жидкостный компонент хранилища -extracells.item.storage.component.fluid.64k.name=64Кб МЭ жидкостный компонент хранилища -extracells.item.storage.component.fluid.256k.name=256Кб МЭ жидкостный компонент хранилища +extracells.item.storage.component.fluid.1k.name=1Кб МЭ компонент жидкостного хранилища +extracells.item.storage.component.fluid.4k.name=4Кб МЭ компонент жидкостного хранилища +extracells.item.storage.component.fluid.16k.name=16Кб МЭ компонент жидкостного хранилища +extracells.item.storage.component.fluid.64k.name=64Кб МЭ компонент жидкостного хранилища +extracells.item.storage.component.fluid.256k.name=256Кб МЭ компонент жидкостного хранилища extracells.item.storage.component.fluid.1024k.name=1024kб МЭ жидкостный компонент хранилища extracells.item.storage.component.fluid.4096k.name=4096kб МЭ жидкостный компонент хранилища +extracells.item.storage.component.gas.1k.name=1Кб МЭ компонент газового хранилища +extracells.item.storage.component.gas.4k.name=4Кб МЭ компонент газового хранилища +extracells.item.storage.component.gas.16k.name=16Кб МЭ компонент газового хранилища +extracells.item.storage.component.gas.64k.name=64Кб МЭ компонент газового хранилища +extracells.item.storage.component.gas.256k.name=256Кб МЭ компонент газового хранилища +extracells.item.storage.component.gas.1024k.name=1024Кб МЭ компонент газового хранилища +extracells.item.storage.component.gas.4096k.name=4096Кб МЭ компонент газового хранилища extracells.item.storage.casing.physical.name=Продвинутый корпус хранилища -extracells.item.storage.casing.fluid.name=Жидкостный корпус хранилища +extracells.item.storage.casing.fluid.name=Корпус хранилища жидкостей +extracells.item.storage.casing.gas.name=Корпус хранилища газов extracells.item.terminal.fluid.wireless.name=Беспроводной МЭ жидкостный терминал +extracells.item.terminal.gas.wireless.name=Беспроводной МЭ газовый терминал +extracells.item.terminal.universal.wireless.name=Беспроводной МЭ универсальный терминал extracells.item.fluid.pattern=МЭ жидкостный шаблон [WIP] +extracells.item.oc.upgrade.name=МЭ улучшение //Creative Tab -itemGroup.Extra_Cells=Extra Cells +itemGroup.Extra_Cells=Extra Cells 2 //Item Groups extracells.fluid.IO=МЭ жидкостная шина экспорта/импорта @@ -52,6 +71,13 @@ extracells.part.battery.name=Прикрепляющийся МЭ энергет extracells.part.fluid.conversion.monitor.name=МЭ жидкостный монитор преобразования extracells.part.fluid.monitor.name=МЭ жидкостный монитор хранения extracells.part.oredict.export.name=МЭ шина экспорта по словарю руд +extracells.part.gas.export.name=МЭ газовая шина экспорта +extracells.part.gas.import.name=МЭ газовая шина импорта +extracells.part.gas.terminal.name=МЭ газовый терминал +extracells.part.gas.storage.name=МЭ газовая шина хранения +extracells.part.gas.levelemitter.name=МЭ газовый излучатель уровня +extracells.part.gas.conversion.monitor.name=МЭ газовый монитор преобразования +extracells.part.gas.monitor.name=МЭ газовый монитор хранения //Blocks extracells.block.certustank=Резервуар из истинного кварца @@ -59,6 +85,10 @@ extracells.block.walrus.name=Морж extracells.block.fluidcrafter.name=МЭ жидкостный сборщик extracells.block.fluidinterface.name=МЭ жидкостный интерфейс extracells.block.fluidfiller.name=МЭ жидкостный авто-заполнитель +tile.extracells.block.craftingstorage.256k.name=256k хранилище создания +tile.extracells.block.craftingstorage.1024k.name=1024k хранилище создания +tile.extracells.block.craftingstorage.4096k.name=4096k хранилище создания +tile.extracells.block.craftingstorage.16384k.name=16384k хранилище создания tile.extracells.block.vibrantchamberfluid.name=Жидкостная вибрационная камера tile.extracells.block.hardmedrive.name=Взрывоустойчивый МЭ накопитель @@ -71,6 +101,9 @@ extracells.tooltip.storage.physical.bytes=%s из %s байт предметов extracells.tooltip.storage.fluid.bytes=%s из %s байт жидкостей использовано. extracells.tooltip.storage.fluid.content=содержит %s мВ жидкости. extracells.tooltip.storage.physical.content=содержит %s предметов(-а). +extracells.tooltip.storage.gas.bytes=%s из %s байт газов использовано. +extracells.tooltip.storage.gas.content=содержит %s газов. +extracells.tooltip.storage.gas.types=%s из %s типов газов использовано. extracells.tooltip.direction.0=Низ extracells.tooltip.direction.1=Верх extracells.tooltip.direction.2=Север @@ -84,6 +117,12 @@ extracells.tooltip.storage.container.2=Режим: Равноценный обм extracells.tooltip.onlyblocks=Вы не можете размещать предметы! Положите блок в БЛОК-контейнер extracells.tooltip.save=Сохранить extracells.tooltip.oredict=Имя словаря руд +extracells.tooltip.mode=Режим +extracells.tooltip.item=Предмет +extracells.tooltip.gas=Газ +extracells.tooltip.essentia=Эссенция +extracells.tooltip.installed=Установлен: +extracells.tooltip.crafting=Создание //Buttons -extracells.gui.craft=Создать \ No newline at end of file +extracells.gui.craft=Создать diff --git a/src/main/resources/assets/extracells/lang/zh_CN.lang b/src/main/resources/assets/extracells/lang/zh_CN.lang index b3a50c9a3..e9e6e6e58 100644 --- a/src/main/resources/assets/extracells/lang/zh_CN.lang +++ b/src/main/resources/assets/extracells/lang/zh_CN.lang @@ -1,62 +1,67 @@ -//**********// -//EXTRACELLS// -//**********// +############ +#EXTRACELLS# +############ -//Items -extracells.item.storage.physical.256k.name=ME 256k存储元件 -extracells.item.storage.physical.1024k.name=ME 1024k存储元件 -extracells.item.storage.physical.4096k.name=ME 4096k存储元件 -extracells.item.storage.physical.16384k.name=ME 16384k存储元件 +#Items +extracells.item.storage.physical.256k.name=256K-ME存储元件 +extracells.item.storage.physical.1024k.name=1024K-ME存储元件 +extracells.item.storage.physical.4096k.name=4096K-ME存储元件 +extracells.item.storage.physical.16384k.name=16384K-ME存储元件 extracells.item.storage.physical.container.name=ME方块容器 -extracells.item.storage.fluid.1k.name=ME 1k流体存储元件 -extracells.item.storage.fluid.4k.name=ME 4k流体存储元件 -extracells.item.storage.fluid.16k.name=ME 16k流体存储元件 -extracells.item.storage.fluid.64k.name=ME 64k流体存储元件 -extracells.item.storage.fluid.256k.name=ME 256k流体存储元件 -extracells.item.storage.fluid.1024k.name=ME 1024k流体存储元件 -extracells.item.storage.fluid.4096k.name=ME 4096k流体存储元件 -extracells.item.storage.fluid.portable.name=ME流体便携元件 -extracells.item.storage.gas.1k.name=ME 1k气体存储元件 -extracells.item.storage.gas.4k.name=ME 4k气体存储元件 -extracells.item.storage.gas.16k.name=ME 16k气体存储元件 -extracells.item.storage.gas.64k.name=ME 64k气体存储元件 -extracells.item.storage.gas.256k.name=ME 256k气体存储元件 -extracells.item.storage.gas.1024k.name=ME 1024k气体存储元件 -extracells.item.storage.gas.4096k.name=ME 4096k气体存储元件 -extracells.item.storage.gas.portable.name=ME气体便携元件 -extracells.item.storage.component.physical.256k.name=256k ME存储组件 -extracells.item.storage.component.physical.1024k.name=1024k ME存储组件 -extracells.item.storage.component.physical.4096k.name=4096k ME存储组件 -extracells.item.storage.component.physical.16384k.name=16384k ME存储组件 -extracells.item.storage.component.fluid.1k.name=1k ME流体存储组件 -extracells.item.storage.component.fluid.4k.name=4k ME流体存储组件 -extracells.item.storage.component.fluid.16k.name=16k ME流体存储组件 -extracells.item.storage.component.fluid.64k.name=64k ME流体存储组件 -extracells.item.storage.component.fluid.256k.name=256k ME流体存储组件 -extracells.item.storage.component.fluid.1024k.name=1024k ME流体存储组件 -extracells.item.storage.component.fluid.4096k.name=4096k ME流体存储组件 -extracells.item.storage.component.gas.1k.name=1k ME气体存储组件 -extracells.item.storage.component.gas.4k.name=4k ME气体存储组件 -extracells.item.storage.component.gas.16k.name=16k ME气体存储组件 -extracells.item.storage.component.gas.64k.name=64k ME气体存储组件 -extracells.item.storage.component.gas.256k.name=256k ME气体存储组件 -extracells.item.storage.component.gas.1024k.name=1024k ME气体存储组件 -extracells.item.storage.component.gas.4096k.name=4096k ME气体存储组件 +extracells.item.storage.physical.advanced.singularity.name=ME数字奇点 +extracells.item.storage.physical.advanced.quantum.name=ME量子存储元件 +extracells.item.storage.physical.void.name=ME虚空存储元件 +extracells.item.storage.fluid.1k.name=1K-ME流体存储元件 +extracells.item.storage.fluid.4k.name=4K-ME流体存储元件 +extracells.item.storage.fluid.16k.name=16K-ME流体存储元件 +extracells.item.storage.fluid.64k.name=64K-ME流体存储元件 +extracells.item.storage.fluid.256k.name=256K-ME流体存储元件 +extracells.item.storage.fluid.1024k.name=1024K-ME流体存储元件 +extracells.item.storage.fluid.4096k.name=4096K-ME流体存储元件 +extracells.item.storage.fluid.portable.name=ME流体便携式元件 +extracells.item.storage.gas.1k.name=1K-ME气体存储元件 +extracells.item.storage.gas.4k.name=4K-ME气体存储元件 +extracells.item.storage.gas.16k.name=16K-ME气体存储元件 +extracells.item.storage.gas.64k.name=64K-ME气体存储元件 +extracells.item.storage.gas.256k.name=256K-ME气体存储元件 +extracells.item.storage.gas.1024k.name=1024K-ME气体存储元件 +extracells.item.storage.gas.4096k.name=4096K-ME气体存储元件 +extracells.item.storage.gas.portable.name=ME气体便携式元件 +extracells.item.storage.component.physical.256k.name=256K-ME存储组件 +extracells.item.storage.component.physical.1024k.name=1024K-ME存储组件 +extracells.item.storage.component.physical.4096k.name=4096K-ME存储组件 +extracells.item.storage.component.physical.16384k.name=16384K-ME存储组件 +extracells.item.storage.component.fluid.1k.name=1K-ME流体存储组件 +extracells.item.storage.component.fluid.4k.name=4K-ME流体存储组件 +extracells.item.storage.component.fluid.16k.name=16K-ME流体存储组件 +extracells.item.storage.component.fluid.64k.name=64K-ME流体存储组件 +extracells.item.storage.component.fluid.256k.name=256K-ME流体存储组件 +extracells.item.storage.component.fluid.1024k.name=1024K-ME流体存储组件 +extracells.item.storage.component.fluid.4096k.name=4096K-ME流体存储组件 +extracells.item.storage.component.gas.1k.name=1K-ME气体存储组件 +extracells.item.storage.component.gas.4k.name=4K-ME气体存储组件 +extracells.item.storage.component.gas.16k.name=16K-ME气体存储组件 +extracells.item.storage.component.gas.64k.name=64K-ME气体存储组件 +extracells.item.storage.component.gas.256k.name=256K-ME气体存储组件 +extracells.item.storage.component.gas.1024k.name=1024K-ME气体存储组件 +extracells.item.storage.component.gas.4096k.name=4096K-ME气体存储组件 extracells.item.storage.casing.physical.name=高级存储外壳 extracells.item.storage.casing.fluid.name=流体存储外壳 extracells.item.storage.casing.gas.name=气体存储外壳 extracells.item.terminal.fluid.wireless.name=无线ME流体终端 +extracells.item.terminal.gas.wireless.name=无线ME气体终端 +extracells.item.terminal.universal.wireless.name=无线ME通用终端 extracells.item.fluid.pattern=ME流体模板[WIP] -extracells.item.oc.upgrade.name=ME升级模块 +extracells.item.oc.upgrade.name=ME升级 -//Creative Tab +#Creative Tab itemGroup.Extra_Cells=更多存储单元2 -//Item Groups +#Item Groups extracells.fluid.IO=ME流体输出/输入总线 extracells.fluid.plane=ME流体成型/破坏面板 -//Parts +#Parts extracells.part.fluid.export.name=ME流体输出总线 extracells.part.fluid.import.name=ME流体输入总线 extracells.part.fluid.storage.name=ME流体存储总线 @@ -65,32 +70,43 @@ extracells.part.fluid.plane.annihilation.name=ME流体破坏面板 extracells.part.fluid.plane.formation.name=ME流体成型面板 extracells.part.fluid.levelemitter.name=ME流体发信器 extracells.part.drive.name=ME驱动固定器 -extracells.part.battery.name=ME能量单元固定器 -extracells.part.fluid.conversion.monitor.name=ME流体交换监控器 +extracells.part.battery.name=ME能源元件固定器 +extracells.part.fluid.conversion.monitor.name=ME流体交互监控器 extracells.part.fluid.monitor.name=ME流体存储监控器 extracells.part.oredict.export.name=ME矿典输出总线 extracells.part.gas.export.name=ME气体输出总线 extracells.part.gas.import.name=ME气体输入总线 extracells.part.gas.terminal.name=ME气体终端 +extracells.part.gas.storage.name=ME气体存储总线 +extracells.part.gas.levelemitter.name=ME气体发信器 +extracells.part.gas.conversion.monitor.name=ME气体交互监控器 +extracells.part.gas.monitor.name=ME气体存储监控器 -//Blocks +#Blocks extracells.block.certustank=赛特斯石英水槽 extracells.block.walrus.name=海象 extracells.block.fluidcrafter.name=ME流体装配室 extracells.block.fluidinterface.name=ME流体接口 extracells.block.fluidfiller.name=ME流体自动装填器 +tile.extracells.block.craftingstorage.256k.name=256k合成存储器 +tile.extracells.block.craftingstorage.1024k.name=1024k合成存储器 +tile.extracells.block.craftingstorage.4096k.name=4096k合成存储器 +tile.extracells.block.craftingstorage.16384k.name=16384k合成存储器 tile.extracells.block.vibrantchamberfluid.name=流体谐振仓 tile.extracells.block.hardmedrive.name=防爆ME驱动器[WIP] -//Tooltips and Chat-Messages +#Tooltips and Chat-Messages extracells.tooltip.amount=总量 extracells.tooltip.fluid=流体 -extracells.tooltip.storage.physical.types=%s/%s个物品类型已使用。 -extracells.tooltip.storage.fluid.types=%s/%s个流体类型已使用。 -extracells.tooltip.storage.physical.bytes=%s/%s物品字节已使用。 -extracells.tooltip.storage.fluid.bytes=%s/%s流体字节已使用。 -extracells.tooltip.storage.fluid.content=存有%smB的流体。 -extracells.tooltip.storage.physical.content=存有%s个物品。 +extracells.tooltip.storage.physical.types=%s/%s个物品类型已使用. +extracells.tooltip.storage.fluid.types=%s/%s个流体类型已使用. +extracells.tooltip.storage.physical.bytes=%s/%s物品字节已使用. +extracells.tooltip.storage.fluid.bytes=%s/%s流体字节已使用. +extracells.tooltip.storage.fluid.content=存有%smB的流体. +extracells.tooltip.storage.physical.content=存有%s个物品. +extracells.tooltip.storage.gas.bytes=%s/%s气体字节已使用. +extracells.tooltip.storage.gas.content=存有%smB气体. +extracells.tooltip.storage.gas.types=%s/%s气体类型已使用. extracells.tooltip.direction.0=下 extracells.tooltip.direction.1=上 extracells.tooltip.direction.2=北 @@ -101,13 +117,16 @@ extracells.tooltip.empty1=空 extracells.tooltip.storage.container.0=模式:放置模式 extracells.tooltip.storage.container.1=模式:替换模式(1*1) extracells.tooltip.storage.container.2=模式:替换模式(3*3) -extracells.tooltip.onlyblocks=你不能放置物品!请在§4方块§r容器中放入方块 +extracells.tooltip.onlyblocks=你不能放置物品! 请在§4方块§r容器中放入方块 extracells.tooltip.save=保存 -extracells.tooltip.oredict=矿物词典名字 +extracells.tooltip.oredict=矿物词典名称 extracells.tooltip.mode=模式 extracells.tooltip.item=物品 extracells.tooltip.gas=气体 extracells.tooltip.essentia=源质 +extracells.tooltip.installed=已安装: +extracells.tooltip.crafting=正在合成 -//Buttons -extracells.gui.craft=Craft +#Buttons +extracells.gui.craft=合成 +extracells.gui.fluid.storage=流体存储总线 \ No newline at end of file diff --git a/src/main/resources/assets/extracells/recipes/storagecell.recipe b/src/main/resources/assets/extracells/recipes/storagecell.recipe index b461b2c0f..4560e9bf4 100644 --- a/src/main/resources/assets/extracells/recipes/storagecell.recipe +++ b/src/main/resources/assets/extracells/recipes/storagecell.recipe @@ -77,6 +77,24 @@ shapeless= ec:fluidCasing ec:cell4096kPartFluid -> ec:fluidCell4096k + +shapeless= + ae2:BlockCraftingUnit:0 ec:physCell256k + -> ec:craftingStorage256k + +shapeless= + ae2:BlockCraftingUnit:0 ec:physCell1024k + -> ec:craftingStorage1024k + +shapeless= + ae2:BlockCraftingUnit:0 ec:physCell4096k + -> ec:craftingStorage4096k + +shapeless= + ae2:BlockCraftingUnit:0 ec:physCell16384k + -> ec:craftingStorage16384k + + shaped= ae2:BlockQuartzGlass oredictionary:dustFluix ae2:BlockQuartzGlass, oredictionary:dustFluix ec:cell1kPartFluid oredictionary:dustFluix, diff --git a/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluid.png b/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluid.png index ae39680af..15665f52f 100644 Binary files a/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluid.png and b/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluid.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFront.png b/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFront.png index 944359a05..5cad9c690 100644 Binary files a/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFront.png and b/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFront.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFrontOn.png b/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFrontOn.png index 1127e3787..d88f63ba0 100644 Binary files a/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFrontOn.png and b/src/main/resources/assets/extracells/textures/blocks/VibrationChamberFluidFrontOn.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.1024k.fit.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.1024k.fit.png new file mode 100644 index 000000000..9e4c67aa0 Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.1024k.fit.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.1024k.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.1024k.png new file mode 100644 index 000000000..07acb093a Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.1024k.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.16384k.fit.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.16384k.fit.png new file mode 100644 index 000000000..a96db317c Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.16384k.fit.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.16384k.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.16384k.png new file mode 100644 index 000000000..fb8f78d2e Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.16384k.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.256k.fit.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.256k.fit.png new file mode 100644 index 000000000..3358b4fb8 Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.256k.fit.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.256k.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.256k.png new file mode 100644 index 000000000..ccbeab1cf Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.256k.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.4096k.fit.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.4096k.fit.png new file mode 100644 index 000000000..0c16b7935 Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.4096k.fit.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/crafting.storage.4096k.png b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.4096k.png new file mode 100644 index 000000000..d7768d1fa Binary files /dev/null and b/src/main/resources/assets/extracells/textures/blocks/crafting.storage.4096k.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/fluid.filler.png b/src/main/resources/assets/extracells/textures/blocks/fluid.filler.png index 4fa4cc52c..32de61b8a 100644 Binary files a/src/main/resources/assets/extracells/textures/blocks/fluid.filler.png and b/src/main/resources/assets/extracells/textures/blocks/fluid.filler.png differ diff --git a/src/main/resources/assets/extracells/textures/blocks/walrus.png b/src/main/resources/assets/extracells/textures/blocks/walrus.png index 7e6ef55c6..65e05da0b 100644 Binary files a/src/main/resources/assets/extracells/textures/blocks/walrus.png and b/src/main/resources/assets/extracells/textures/blocks/walrus.png differ diff --git a/src/main/resources/assets/extracells/textures/gui/oredictexport.png b/src/main/resources/assets/extracells/textures/gui/oredictexport.png index 52afc4fe9..c7255be1a 100644 Binary files a/src/main/resources/assets/extracells/textures/gui/oredictexport.png and b/src/main/resources/assets/extracells/textures/gui/oredictexport.png differ diff --git a/src/main/resources/assets/extracells/textures/gui/storagebusfluid.png b/src/main/resources/assets/extracells/textures/gui/storagebusfluid.png index 9d3522ad0..7e945c3aa 100644 Binary files a/src/main/resources/assets/extracells/textures/gui/storagebusfluid.png and b/src/main/resources/assets/extracells/textures/gui/storagebusfluid.png differ diff --git a/src/main/resources/assets/extracells/textures/gui/vibrationchamberfluid.png b/src/main/resources/assets/extracells/textures/gui/vibrationchamberfluid.png index 1fa4b4036..ec44ca263 100644 Binary files a/src/main/resources/assets/extracells/textures/gui/vibrationchamberfluid.png and b/src/main/resources/assets/extracells/textures/gui/vibrationchamberfluid.png differ diff --git a/src/main/resources/assets/extracells/textures/items/storage.physical.advanced.quantum.png b/src/main/resources/assets/extracells/textures/items/storage.physical.advanced.quantum.png new file mode 100644 index 000000000..9000d664e Binary files /dev/null and b/src/main/resources/assets/extracells/textures/items/storage.physical.advanced.quantum.png differ diff --git a/src/main/resources/assets/extracells/textures/items/storage.physical.advanced.singularity.png b/src/main/resources/assets/extracells/textures/items/storage.physical.advanced.singularity.png new file mode 100644 index 000000000..d730291d6 Binary files /dev/null and b/src/main/resources/assets/extracells/textures/items/storage.physical.advanced.singularity.png differ diff --git a/src/main/resources/assets/extracells/textures/items/storage.physical.void.png b/src/main/resources/assets/extracells/textures/items/storage.physical.void.png new file mode 100644 index 000000000..f37326358 Binary files /dev/null and b/src/main/resources/assets/extracells/textures/items/storage.physical.void.png differ diff --git a/src/main/resources/mcmod.info b/src/main/resources/mcmod.info index b5fdcbf09..de95c2844 100644 --- a/src/main/resources/mcmod.info +++ b/src/main/resources/mcmod.info @@ -1,16 +1,19 @@ -[ { - "modid": "extracells", - "name": "Extra Cells 2", - "description": "Adds new ME Storage Cells and some other cool stuff to AE 2.", - "version": "${version}", - "mcversion": "${mcversion}", - "url": "http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/1289077-ae-add-on-m3gas-extracells-2-1-x-2-2-x", - "updateUrl": "", - "authorList": ["M3gaFr3ak", "DrummerMC"], - "credits": "Textures by PaleoCrafter and Cyntain", - "logoFile": "", - "screenshots": [], - "dependencies": ["Applied Energistics 2"] + "modListVersion": 2, + "modList": [{ + "modid": "${modId}", + "name": "${modName}", + "description": "Adds a giant walrus", + "version": "${modVersion}", + "mcversion": "${minecraftVersion}", + "url": "http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/1289077-ae-add-on-m3gas-extracells-2-1-x-2-2-x", + "updateUrl": "", + "authorList": ["M3gaFr3ak", "DrummerMC"], + "credits": "Textures by PaleoCrafter and Cyntain", + "logoFile": "ExtraCells2.png", + "screenshots": [], + "requiredMods": ["appliedenergistics2"], + "dependencies": ["appliedenergistics2", "LogisticsPipes|Main", "Waila"], + "useDependencyInformation": true + }] } -] diff --git a/src/main/resources/version.properties b/src/main/resources/version.properties deleted file mode 100644 index 63b915631..000000000 --- a/src/main/resources/version.properties +++ /dev/null @@ -1 +0,0 @@ -extracells.version=${version} \ No newline at end of file diff --git a/src/main/scala/extracells/ExtraCellsApiInstance.java b/src/main/scala/extracells/ExtraCellsApiInstance.java index 1081d64a7..f5556214e 100644 --- a/src/main/scala/extracells/ExtraCellsApiInstance.java +++ b/src/main/scala/extracells/ExtraCellsApiInstance.java @@ -1,5 +1,17 @@ package extracells; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.AEApi; import appeng.api.implementations.tiles.IWirelessAccessPoint; import appeng.api.networking.IGrid; @@ -31,356 +43,324 @@ import extracells.wireless.WirelessTermRegistry; import mekanism.api.gas.Gas; import mekanism.api.gas.GasStack; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import java.util.ArrayList; -import java.util.List; public class ExtraCellsApiInstance implements ExtraCellsApi { - public static final ExtraCellsApi instance = new ExtraCellsApiInstance(); - - private final List> blacklistShowClass = new ArrayList>(); - private final List blacklistShowFluid = new ArrayList(); - private final List> blacklistStorageClass = new ArrayList>(); - private final List blacklistStorageFluid = new ArrayList(); - - @Override - public void addFluidToShowBlacklist(Class clazz) { - if (clazz == null || clazz == Fluid.class) - return; - this.blacklistShowClass.add(clazz); - } - - @Override - public void addFluidToShowBlacklist(Fluid fluid) { - if (fluid == null) - return; - this.blacklistShowFluid.add(fluid); - } - - @Override - public void addFluidToStorageBlacklist(Class clazz) { - if (clazz == null || clazz == Fluid.class) - return; - this.blacklistStorageClass.add(clazz); - } - - @Override - public void addFluidToStorageBlacklist(Fluid fluid) { - if (fluid == null) - return; - this.blacklistStorageFluid.add(fluid); - } - - @Override - public IBlockDefinition blocks() { - return BlockDefinition.instance; - } - - @Override - public boolean canFluidSeeInTerminal(Fluid fluid) { - if (fluid == null) - return false; - if (this.blacklistShowFluid.contains(fluid)) - return false; - for (Class clazz : this.blacklistShowClass) { - if (clazz.isInstance(fluid)) - return false; - } - return true; - } - - @Override - public boolean canStoreFluid(Fluid fluid) { - if (fluid == null) - return false; - if (this.blacklistStorageFluid.contains(fluid)) - return false; - for (Class clazz : this.blacklistStorageClass) { - if (clazz.isInstance(fluid)) - return false; - } - return true; - } - - /** - * @deprecated Incorrect spelling - */ - @Override - @Deprecated - public String getVerion() { - return Extracells.VERSION(); - } - - @Override - public String getVersion() { - return Extracells.VERSION(); - } - - @Override - public IWirelessFluidTermHandler getWirelessFluidTermHandler(ItemStack is) { - return (IWirelessFluidTermHandler) getWirelessTermHandler(is); - } - - @Override - public IWirelessGasFluidTermHandler getWirelessTermHandler(ItemStack is) { - return WirelessTermRegistry.getWirelessTermHandler(is); - } - - @Override - public boolean isWirelessFluidTerminal(ItemStack is) { - return WirelessTermRegistry.isWirelessItem(is); - } - - @Override - public IItemDefinition items() { - return ItemDefinition.instance; - } - - @Override - public ItemStack openPortableCellGui (EntityPlayer player, ItemStack stack, World world){ - return openPortableFluidCellGui(player, stack, world); - } - - @Override - public ItemStack openPortableFluidCellGui(EntityPlayer player, ItemStack stack, World world) { - if (world.isRemote || stack == null || stack.getItem() == null) - return stack; - Item item = stack.getItem(); - if (!(item instanceof IPortableFluidStorageCell)) - return stack; - ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler(stack); - if (!(cellHandler instanceof FluidCellHandler)) - return stack; - IMEInventoryHandler handler = ((FluidCellHandler) cellHandler).getCellInventoryPlayer(stack, player); - if (!(handler instanceof HandlerItemStorageFluid)) { - return stack; - } - IMEMonitor fluidInventory = new MEMonitorHandler(handler, StorageChannel.FLUIDS); - GuiHandler.launchGui(GuiHandler.getGuiId(3), player, new Object[]{fluidInventory, item}); - return stack; - } - - @Override - public ItemStack openPortableGasCellGui(EntityPlayer player, ItemStack stack, World world) { - if (world.isRemote || stack == null || stack.getItem() == null) - return stack; - Item item = stack.getItem(); - if (!(item instanceof IPortableGasStorageCell)) - return stack; - ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler(stack); - if (!(cellHandler instanceof GasCellHandler)) - return stack; - IMEInventoryHandler handler = ((GasCellHandler) cellHandler).getCellInventoryPlayer(stack, player); - if (!(handler instanceof HandlerItemStorageGas)) { - return stack; - } - IMEMonitor fluidInventory = new MEMonitorHandler(handler, StorageChannel.FLUIDS); - GuiHandler.launchGui(GuiHandler.getGuiId(6), player, new Object[]{fluidInventory, item}); - return stack; - } - - @Override - public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack stack, World world) { - return openWirelessFluidTerminal(player, stack, world); - } - - @Override - public ItemStack openWirelessFluidTerminal(EntityPlayer player, ItemStack stack, World world) { - if (world.isRemote) - return stack; - if (!isWirelessFluidTerminal(stack)) - return stack; - IWirelessGasFluidTermHandler handler = getWirelessTermHandler(stack); - if (!handler.hasPower(player, 1.0D, stack)) - return stack; - Long key; - try { - key = Long.parseLong(handler.getEncryptionKey(stack)); - } catch (Throwable ignored) { - return stack; - } - return openWirelessTerminal(player, stack, world, (int) player.posX, (int) player.posY, (int) player.posZ, key); - } - - @Override - public ItemStack openWirelessGasTerminal(EntityPlayer player, ItemStack itemStack, World world) { - if (world.isRemote) - return itemStack; - if (!isWirelessFluidTerminal(itemStack)) - return itemStack; - IWirelessGasFluidTermHandler handler = getWirelessTermHandler(itemStack); - if (!handler.hasPower(player, 1.0D, itemStack)) - return itemStack; - Long key; - try { - key = Long.parseLong(handler.getEncryptionKey(itemStack)); - } catch (Throwable ignored) { - return itemStack; - } - int x = (int) player.posX; - int y = (int) player.posY; - int z = (int) player.posZ; - IGridHost securityTerminal = (IGridHost) AEApi.instance().registries().locatable().getLocatableBy(key); - if (securityTerminal == null) - return itemStack; - IGridNode gridNode = securityTerminal.getGridNode(ForgeDirection.UNKNOWN); - if (gridNode == null) - return itemStack; - IGrid grid = gridNode.getGrid(); - if (grid == null) - return itemStack; - for (IGridNode node : grid.getMachines((Class) AEApi.instance().definitions().blocks().wireless().maybeEntity().get())) { - IWirelessAccessPoint accessPoint = (IWirelessAccessPoint) node.getMachine(); - WorldCoord distance = accessPoint.getLocation().subtract(x, y, z); - int squaredDistance = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z; - if (squaredDistance <= accessPoint.getRange() * accessPoint.getRange()) { - IStorageGrid gridCache = grid.getCache(IStorageGrid.class); - if (gridCache != null) { - IMEMonitor fluidInventory = gridCache.getFluidInventory(); - if (fluidInventory != null) { - GuiHandler.launchGui(GuiHandler.getGuiId(5), player, new Object[]{ - fluidInventory, getWirelessTermHandler(itemStack)}); - } - } - } - } - return itemStack; - } - - @Deprecated - @Override - public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack itemStack, World world, int x, int y, int z, Long key) { - if (world.isRemote) - return itemStack; - IGridHost securityTerminal = (IGridHost) AEApi.instance().registries().locatable().getLocatableBy(key); - if (securityTerminal == null) - return itemStack; - IGridNode gridNode = securityTerminal - .getGridNode(ForgeDirection.UNKNOWN); - if (gridNode == null) - return itemStack; - IGrid grid = gridNode.getGrid(); - if (grid == null) - return itemStack; - for (IGridNode node : grid.getMachines((Class) AEApi.instance().definitions().blocks().wireless().maybeEntity().get())) { - IWirelessAccessPoint accessPoint = (IWirelessAccessPoint) node - .getMachine(); - WorldCoord distance = accessPoint.getLocation().subtract(x, y, z); - int squaredDistance = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z; - if (squaredDistance <= accessPoint.getRange() * accessPoint.getRange()) { - IStorageGrid gridCache = grid.getCache(IStorageGrid.class); - if (gridCache != null) { - IMEMonitor fluidInventory = gridCache.getFluidInventory(); - if (fluidInventory != null) { - GuiHandler.launchGui(GuiHandler.getGuiId(1), player, new Object[]{ - fluidInventory, getWirelessFluidTermHandler(itemStack)}); - } - } - } - } - return itemStack; - } - - @Override - public IPartDefinition parts() { - return PartDefinition.instance; - } - - @Override - public void registerWirelessTermHandler(IWirelessGasFluidTermHandler handler) { - WirelessTermRegistry.registerWirelessTermHandler(handler); - } - - @Override - public void registerWirelessFluidTermHandler(IWirelessFluidTermHandler handler) { - registerWirelessTermHandler(handler); - } - - /** - * @deprecated Incorrect spelling - */ - @Override - @Deprecated - public void registryWirelessFluidTermHandler(IWirelessFluidTermHandler handler) { - registerWirelessFluidTermHandler(handler); - } - - @Override - public void registerFuelBurnTime(Fluid fuel, int burnTime) { - FuelBurnTime.registerFuel(fuel, burnTime); - } - - @Override - public boolean isGasStack(IAEFluidStack stack) { - return stack != null && isGasStack(stack.getFluidStack()); - } - - @Override - public boolean isGasStack(FluidStack stack) { - return stack != null && isGas(stack.getFluid()); - } - - @Override - public boolean isGas(Fluid fluid) { - return fluid != null && Integration.Mods.MEKANISMGAS.isEnabled() && checkGas(fluid); - } - - @Override - public Object createGasStack(IAEFluidStack stack) { - return Integration.Mods.MEKANISMGAS.isEnabled() ? createGasFromFluidStack(stack) : null; - } - - @Override - public IAEFluidStack createFluidStackFromGas(Object gasStack) { - return isMekEnabled() ? createFluidStackFromGasStack(gasStack): null; - } - - @Override - public Fluid getGasFluid(Object gas) { - return isMekEnabled() ? createFluidFromGas(gas) : null; - } - - @Override - public void addExternalStorageInterface(IExternalGasStorageHandler esh) { - if(isMekEnabled()) - GasStorageRegistry.addExternalStorageInterface(esh); - } - - @Override - public IExternalGasStorageHandler getHandler(TileEntity te, ForgeDirection opposite, BaseActionSource mySrc) { - return isMekEnabled() ? GasStorageRegistry.getHandler(te, opposite, mySrc) : null; - } - - @Optional.Method(modid = "MekanismAPI|gas") - private IAEFluidStack createFluidStackFromGasStack(Object gasStack){ - return gasStack instanceof GasStack ? GasUtil.createAEFluidStack((GasStack) gasStack) : null; - } - - @Optional.Method(modid = "MekanismAPI|gas") - private Fluid createFluidFromGas(Object gas){ - return gas instanceof Gas ? MekanismGas.getFluidGasMap().containsKey(gas) ? MekanismGas.getFluidGasMap().get(gas) : null : null; - } - - @Optional.Method(modid = "MekanismAPI|gas") - private Object createGasFromFluidStack(IAEFluidStack stack) { - return stack == null ? null : GasUtil.getGasStack(stack.getFluidStack()); - } - - @Optional.Method(modid = "MekanismAPI|gas") - private boolean checkGas(Fluid fluid) { - return fluid instanceof MekanismGas.GasFluid; - } - - private boolean isMekEnabled(){ - return Integration.Mods.MEKANISMGAS.isEnabled(); - } + public static final ExtraCellsApi instance = new ExtraCellsApiInstance(); + + private final List> blacklistShowClass = new ArrayList>(); + private final List blacklistShowFluid = new ArrayList(); + private final List> blacklistStorageClass = new ArrayList>(); + private final List blacklistStorageFluid = new ArrayList(); + + @Override + public void addFluidToShowBlacklist(Class clazz) { + if (clazz == null || clazz == Fluid.class) return; + this.blacklistShowClass.add(clazz); + } + + @Override + public void addFluidToShowBlacklist(Fluid fluid) { + if (fluid == null) return; + this.blacklistShowFluid.add(fluid); + } + + @Override + public void addFluidToStorageBlacklist(Class clazz) { + if (clazz == null || clazz == Fluid.class) return; + this.blacklistStorageClass.add(clazz); + } + + @Override + public void addFluidToStorageBlacklist(Fluid fluid) { + if (fluid == null) return; + this.blacklistStorageFluid.add(fluid); + } + + @Override + public IBlockDefinition blocks() { + return BlockDefinition.instance; + } + + @Override + public boolean canFluidSeeInTerminal(Fluid fluid) { + if (fluid == null) return false; + if (this.blacklistShowFluid.contains(fluid)) return false; + for (Class clazz : this.blacklistShowClass) { + if (clazz.isInstance(fluid)) return false; + } + return true; + } + + @Override + public boolean canStoreFluid(Fluid fluid) { + if (fluid == null) return false; + if (this.blacklistStorageFluid.contains(fluid)) return false; + for (Class clazz : this.blacklistStorageClass) { + if (clazz.isInstance(fluid)) return false; + } + return true; + } + + /** + * @deprecated Incorrect spelling + */ + @Override + @Deprecated + public String getVerion() { + return Extracells.VERSION(); + } + + @Override + public String getVersion() { + return Extracells.VERSION(); + } + + @Override + public IWirelessFluidTermHandler getWirelessFluidTermHandler(ItemStack is) { + return (IWirelessFluidTermHandler) getWirelessTermHandler(is); + } + + @Override + public IWirelessGasFluidTermHandler getWirelessTermHandler(ItemStack is) { + return WirelessTermRegistry.getWirelessTermHandler(is); + } + + @Override + public boolean isWirelessFluidTerminal(ItemStack is) { + return WirelessTermRegistry.isWirelessItem(is); + } + + @Override + public IItemDefinition items() { + return ItemDefinition.instance; + } + + @Override + public ItemStack openPortableCellGui(EntityPlayer player, ItemStack stack, World world) { + return openPortableFluidCellGui(player, stack, world); + } + + @Override + public ItemStack openPortableFluidCellGui(EntityPlayer player, ItemStack stack, World world) { + if (world.isRemote || stack == null || stack.getItem() == null) return stack; + Item item = stack.getItem(); + if (!(item instanceof IPortableFluidStorageCell)) return stack; + ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler(stack); + if (!(cellHandler instanceof FluidCellHandler)) return stack; + IMEInventoryHandler handler = ((FluidCellHandler) cellHandler) + .getCellInventoryPlayer(stack, player); + if (!(handler instanceof HandlerItemStorageFluid)) { + return stack; + } + IMEMonitor fluidInventory = new MEMonitorHandler(handler, StorageChannel.FLUIDS); + GuiHandler.launchGui(GuiHandler.getGuiId(3), player, new Object[] { fluidInventory, item }); + return stack; + } + + @Override + public ItemStack openPortableGasCellGui(EntityPlayer player, ItemStack stack, World world) { + if (world.isRemote || stack == null || stack.getItem() == null) return stack; + Item item = stack.getItem(); + if (!(item instanceof IPortableGasStorageCell)) return stack; + ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler(stack); + if (!(cellHandler instanceof GasCellHandler)) return stack; + IMEInventoryHandler handler = ((GasCellHandler) cellHandler) + .getCellInventoryPlayer(stack, player); + if (!(handler instanceof HandlerItemStorageGas)) { + return stack; + } + IMEMonitor fluidInventory = new MEMonitorHandler(handler, StorageChannel.FLUIDS); + GuiHandler.launchGui(GuiHandler.getGuiId(6), player, new Object[] { fluidInventory, item }); + return stack; + } + + @Override + public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack stack, World world) { + return openWirelessFluidTerminal(player, stack, world); + } + + @Override + public ItemStack openWirelessFluidTerminal(EntityPlayer player, ItemStack stack, World world) { + if (world.isRemote) return stack; + if (!isWirelessFluidTerminal(stack)) return stack; + IWirelessGasFluidTermHandler handler = getWirelessTermHandler(stack); + if (!handler.hasPower(player, 1.0D, stack)) return stack; + Long key; + try { + key = Long.parseLong(handler.getEncryptionKey(stack)); + } catch (Throwable ignored) { + return stack; + } + return openWirelessTerminal(player, stack, world, (int) player.posX, (int) player.posY, (int) player.posZ, key); + } + + @Override + public ItemStack openWirelessGasTerminal(EntityPlayer player, ItemStack itemStack, World world) { + if (world.isRemote) return itemStack; + if (!isWirelessFluidTerminal(itemStack)) return itemStack; + IWirelessGasFluidTermHandler handler = getWirelessTermHandler(itemStack); + if (!handler.hasPower(player, 1.0D, itemStack)) return itemStack; + Long key; + try { + key = Long.parseLong(handler.getEncryptionKey(itemStack)); + } catch (Throwable ignored) { + return itemStack; + } + int x = (int) player.posX; + int y = (int) player.posY; + int z = (int) player.posZ; + IGridHost securityTerminal = (IGridHost) AEApi.instance().registries().locatable().getLocatableBy(key); + if (securityTerminal == null) return itemStack; + IGridNode gridNode = securityTerminal.getGridNode(ForgeDirection.UNKNOWN); + if (gridNode == null) return itemStack; + IGrid grid = gridNode.getGrid(); + if (grid == null) return itemStack; + for (IGridNode node : grid.getMachines( + (Class) AEApi.instance().definitions().blocks().wireless().maybeEntity().get())) { + IWirelessAccessPoint accessPoint = (IWirelessAccessPoint) node.getMachine(); + WorldCoord distance = accessPoint.getLocation().subtract(x, y, z); + int squaredDistance = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z; + if (squaredDistance <= accessPoint.getRange() * accessPoint.getRange()) { + IStorageGrid gridCache = grid.getCache(IStorageGrid.class); + if (gridCache != null) { + IMEMonitor fluidInventory = gridCache.getFluidInventory(); + if (fluidInventory != null) { + GuiHandler.launchGui( + GuiHandler.getGuiId(5), + player, + new Object[] { fluidInventory, getWirelessTermHandler(itemStack) }); + } + } + } + } + return itemStack; + } + + @Deprecated + @Override + public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack itemStack, World world, int x, int y, int z, + Long key) { + if (world.isRemote) return itemStack; + IGridHost securityTerminal = (IGridHost) AEApi.instance().registries().locatable().getLocatableBy(key); + if (securityTerminal == null) return itemStack; + IGridNode gridNode = securityTerminal.getGridNode(ForgeDirection.UNKNOWN); + if (gridNode == null) return itemStack; + IGrid grid = gridNode.getGrid(); + if (grid == null) return itemStack; + for (IGridNode node : grid.getMachines( + (Class) AEApi.instance().definitions().blocks().wireless().maybeEntity().get())) { + IWirelessAccessPoint accessPoint = (IWirelessAccessPoint) node.getMachine(); + WorldCoord distance = accessPoint.getLocation().subtract(x, y, z); + int squaredDistance = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z; + if (squaredDistance <= accessPoint.getRange() * accessPoint.getRange()) { + IStorageGrid gridCache = grid.getCache(IStorageGrid.class); + if (gridCache != null) { + IMEMonitor fluidInventory = gridCache.getFluidInventory(); + if (fluidInventory != null) { + GuiHandler.launchGui( + GuiHandler.getGuiId(1), + player, + new Object[] { fluidInventory, getWirelessFluidTermHandler(itemStack) }); + } + } + } + } + return itemStack; + } + + @Override + public IPartDefinition parts() { + return PartDefinition.instance; + } + + @Override + public void registerWirelessTermHandler(IWirelessGasFluidTermHandler handler) { + WirelessTermRegistry.registerWirelessTermHandler(handler); + } + + @Override + public void registerWirelessFluidTermHandler(IWirelessFluidTermHandler handler) { + registerWirelessTermHandler(handler); + } + + /** + * @deprecated Incorrect spelling + */ + @Override + @Deprecated + public void registryWirelessFluidTermHandler(IWirelessFluidTermHandler handler) { + registerWirelessFluidTermHandler(handler); + } + + @Override + public void registerFuelBurnTime(Fluid fuel, int burnTime) { + FuelBurnTime.registerFuel(fuel, burnTime); + } + + @Override + public boolean isGasStack(IAEFluidStack stack) { + return stack != null && isGasStack(stack.getFluidStack()); + } + + @Override + public boolean isGasStack(FluidStack stack) { + return stack != null && isGas(stack.getFluid()); + } + + @Override + public boolean isGas(Fluid fluid) { + return fluid != null && Integration.Mods.MEKANISMGAS.isEnabled() && checkGas(fluid); + } + + @Override + public Object createGasStack(IAEFluidStack stack) { + return Integration.Mods.MEKANISMGAS.isEnabled() ? createGasFromFluidStack(stack) : null; + } + + @Override + public IAEFluidStack createFluidStackFromGas(Object gasStack) { + return isMekEnabled() ? createFluidStackFromGasStack(gasStack) : null; + } + + @Override + public Fluid getGasFluid(Object gas) { + return isMekEnabled() ? createFluidFromGas(gas) : null; + } + + @Override + public void addExternalStorageInterface(IExternalGasStorageHandler esh) { + if (isMekEnabled()) GasStorageRegistry.addExternalStorageInterface(esh); + } + + @Override + public IExternalGasStorageHandler getHandler(TileEntity te, ForgeDirection opposite, BaseActionSource mySrc) { + return isMekEnabled() ? GasStorageRegistry.getHandler(te, opposite, mySrc) : null; + } + + @Optional.Method(modid = "MekanismAPI|gas") + private IAEFluidStack createFluidStackFromGasStack(Object gasStack) { + return gasStack instanceof GasStack ? GasUtil.createAEFluidStack((GasStack) gasStack) : null; + } + + @Optional.Method(modid = "MekanismAPI|gas") + private Fluid createFluidFromGas(Object gas) { + return gas instanceof Gas + ? MekanismGas.getFluidGasMap().containsKey(gas) ? MekanismGas.getFluidGasMap().get(gas) : null + : null; + } + + @Optional.Method(modid = "MekanismAPI|gas") + private Object createGasFromFluidStack(IAEFluidStack stack) { + return stack == null ? null : GasUtil.getGasStack(stack.getFluidStack()); + } + + @Optional.Method(modid = "MekanismAPI|gas") + private boolean checkGas(Fluid fluid) { + return fluid instanceof MekanismGas.GasFluid; + } + + private boolean isMekEnabled() { + return Integration.Mods.MEKANISMGAS.isEnabled(); + } } diff --git a/src/main/scala/extracells/Extracells.scala b/src/main/scala/extracells/Extracells.scala index 115e33a86..079857374 100644 --- a/src/main/scala/extracells/Extracells.scala +++ b/src/main/scala/extracells/Extracells.scala @@ -1,92 +1,156 @@ package extracells -import java.io.File - import appeng.api.AEApi import cpw.mods.fml.client.registry.RenderingRegistry import cpw.mods.fml.common.Mod.EventHandler -import cpw.mods.fml.common.event.{FMLInitializationEvent, FMLPostInitializationEvent, FMLPreInitializationEvent} +import cpw.mods.fml.common.event.{ + FMLInitializationEvent, + FMLModIdMappingEvent, + FMLPostInitializationEvent, + FMLPreInitializationEvent +} import cpw.mods.fml.common.network.NetworkRegistry import cpw.mods.fml.common.{FMLCommonHandler, Loader, Mod, SidedProxy} import extracells.integration.Integration +import extracells.integration.ae2fc.FluidCraft import extracells.network.{ChannelHandler, GuiHandler} import extracells.proxy.CommonProxy import extracells.registries.ItemEnum import extracells.render.RenderHandler -import extracells.util.{ExtraCellsEventHandler, FluidCellHandler, NameHandler} +import extracells.util.{ + AdvancedCellHandler, + ExtraCellsEventHandler, + FluidCellHandler, + NameHandler +} +import extracells.util.AdvancedCellHandler +import extracells.util.VoidCellHandler import extracells.wireless.AEWirelessTermHandler import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.ItemStack import net.minecraftforge.common.MinecraftForge import net.minecraftforge.common.config.Configuration -@Mod(modid = "extracells", name = "Extra Cells", modLanguage = "scala", dependencies = "after:LogisticsPipes|Main;after:Waila;required-after:appliedenergistics2") -object Extracells { - - - @SidedProxy(clientSide = "extracells.proxy.ClientProxy", serverSide = "extracells.proxy.CommonProxy") - var proxy: CommonProxy = null - - var VERSION = "" - - var bcBurnTimeMultiplicator = 4; - - var configFolder: File = null - var shortenedBuckets = true - var dynamicTypes = true - val integration = new Integration - - val ModTab = new CreativeTabs("Extra_Cells") { - - override def getIconItemStack = new ItemStack(ItemEnum.FLUIDSTORAGE.getItem) - - override def getTabIconItem = ItemEnum.FLUIDSTORAGE.getItem - } - - @EventHandler - def init(event: FMLInitializationEvent) { - AEApi.instance.registries.recipes.addNewSubItemResolver(new NameHandler) - AEApi.instance.registries.wireless.registerWirelessHandler(new AEWirelessTermHandler) - AEApi.instance.registries.cell.addCellHandler(new FluidCellHandler) - val handler = new ExtraCellsEventHandler - FMLCommonHandler.instance.bus.register(handler) - MinecraftForge.EVENT_BUS.register(handler) - proxy.registerMovables - proxy.registerRenderers - proxy.registerTileEntities - proxy.registerFluidBurnTimes - proxy.addRecipes(configFolder) - ChannelHandler.registerMessages - RenderingRegistry.registerBlockHandler(new RenderHandler(RenderingRegistry.getNextAvailableRenderId)) - integration.init - } - - @EventHandler - def postInit(event: FMLPostInitializationEvent) { - integration.postInit - } - - @EventHandler - def preInit(event: FMLPreInitializationEvent) { - VERSION = Loader.instance.activeModContainer.getVersion - configFolder = event.getModConfigurationDirectory - - NetworkRegistry.INSTANCE.registerGuiHandler(this, GuiHandler) - - - - // Config - val config = new Configuration(new File(configFolder.getPath + File.separator + "AppliedEnergistics2" + File.separator + "extracells.cfg")) - config.load - shortenedBuckets = config.get("Tooltips", "shortenedBuckets", true, "Shall the guis shorten large mB values?").getBoolean(true) - dynamicTypes = config.get("Storage Cells", "dynamicTypes", true, "Should the mount of bytes needed for a new type depend on the cellsize?").getBoolean(true) - integration.loadConfig(config) - +import java.io.File - config.save +@Mod( + modid = "extracells", + name = "Extra Cells", + version = "GRADLETOKEN_VERSION", + modLanguage = "scala", + dependencies = + "after:LogisticsPipes|Main;after:Waila;required-after:appliedenergistics2" +) +object Extracells { - proxy.registerItems - proxy.registerBlocks - integration.preInit - } + @SidedProxy( + clientSide = "extracells.proxy.ClientProxy", + serverSide = "extracells.proxy.CommonProxy" + ) + var proxy: CommonProxy = null + + var VERSION = "" + var basePartSpeed = 125 + var bcBurnTimeMultiplicator = 4 + var terminalUpdateInterval = 20 + var configFolder: File = null + var shortenedBuckets = true + var dynamicTypes = true + val integration = new Integration + + val ModTab = new CreativeTabs("Extra_Cells") { + override def getIconItemStack = new ItemStack(ItemEnum.FLUIDSTORAGE.getItem) + override def getTabIconItem = ItemEnum.FLUIDSTORAGE.getItem + } + + @EventHandler + def init(event: FMLInitializationEvent) { + AEApi.instance.registries.recipes.addNewSubItemResolver(new NameHandler) + AEApi.instance.registries.wireless + .registerWirelessHandler(new AEWirelessTermHandler) + AEApi.instance.registries.cell.addCellHandler(new FluidCellHandler) + AEApi.instance.registries.cell.addCellHandler(new AdvancedCellHandler) + AEApi.instance.registries.cell.addCellHandler(new VoidCellHandler) + val handler = new ExtraCellsEventHandler + FMLCommonHandler.instance.bus.register(handler) + MinecraftForge.EVENT_BUS.register(handler) + proxy.registerMovables() + proxy.registerRenderers() + proxy.registerTileEntities() + proxy.registerFluidBurnTimes() + proxy.addRecipes(configFolder) + ChannelHandler.registerMessages() + RenderingRegistry.registerBlockHandler( + new RenderHandler(RenderingRegistry.getNextAvailableRenderId) + ) + integration.init() + } + + @EventHandler + def postInit(event: FMLPostInitializationEvent) { + integration.postInit() + } + + @EventHandler + def preInit(event: FMLPreInitializationEvent) { + VERSION = Loader.instance.activeModContainer.getVersion + configFolder = event.getModConfigurationDirectory + + NetworkRegistry.INSTANCE.registerGuiHandler(this, GuiHandler) + + // Config + val config = new Configuration( + new File( + configFolder.getPath + File.separator + "AppliedEnergistics2" + File.separator + "extracells.cfg" + ) + ) + config.load() + shortenedBuckets = config + .get( + "Tooltips", + "shortenedBuckets", + true, + "Shall the guis shorten large mB values?" + ) + .getBoolean(true) + dynamicTypes = config + .get( + "Storage Cells", + "dynamicTypes", + true, + "Should the mount of bytes needed for a new type depend on the cellsize?" + ) + .getBoolean(true) + terminalUpdateInterval = config + .get( + "Terminal", + "Interval", + 20, + "How often is the fluid in the terminal updated?" + ) + .getInt(20) + basePartSpeed = config + .get( + "BaseFluidPart", + "Interval", + 125, + "Base fluid part import export speed " + ) + .getInt(125) + + integration.loadConfig(config) + + config.save() + + proxy.registerItems() + proxy.registerBlocks() + integration.preInit() + } + + @EventHandler + def handleRemap(event: FMLModIdMappingEvent): Unit = { + if (Integration.Mods.FLUIDCRAFT.isEnabled) { + FluidCraft.onRemapEvent(event) + } + } } diff --git a/src/main/scala/extracells/api/ECApi.java b/src/main/scala/extracells/api/ECApi.java index 062ddc55e..7648c0cd8 100644 --- a/src/main/scala/extracells/api/ECApi.java +++ b/src/main/scala/extracells/api/ECApi.java @@ -2,17 +2,15 @@ public class ECApi { - public static ExtraCellsApi instance() { - if (instance == null) { - try { - instance = (ExtraCellsApi) Class - .forName("extracells.ExtraCellsApiInstance") - .getField("instance").get(null); - } catch (Exception e) {} - } - return instance; - } - - private static ExtraCellsApi instance = null; + public static ExtraCellsApi instance() { + if (instance == null) { + try { + instance = (ExtraCellsApi) Class.forName("extracells.ExtraCellsApiInstance").getField("instance") + .get(null); + } catch (Exception e) {} + } + return instance; + } + private static ExtraCellsApi instance = null; } diff --git a/src/main/scala/extracells/api/ExtraCellsApi.java b/src/main/scala/extracells/api/ExtraCellsApi.java index 8b2601b0e..cd679181a 100644 --- a/src/main/scala/extracells/api/ExtraCellsApi.java +++ b/src/main/scala/extracells/api/ExtraCellsApi.java @@ -1,10 +1,5 @@ package extracells.api; -import appeng.api.networking.security.BaseActionSource; -import appeng.api.storage.data.IAEFluidStack; -import extracells.api.definitions.IBlockDefinition; -import extracells.api.definitions.IItemDefinition; -import extracells.api.definitions.IPartDefinition; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; @@ -13,114 +8,121 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.data.IAEFluidStack; +import extracells.api.definitions.IBlockDefinition; +import extracells.api.definitions.IItemDefinition; +import extracells.api.definitions.IPartDefinition; + public interface ExtraCellsApi { - public void addFluidToShowBlacklist(Class clazz); + public void addFluidToShowBlacklist(Class clazz); + + public void addFluidToShowBlacklist(Fluid fluid); - public void addFluidToShowBlacklist(Fluid fluid); + public void addFluidToStorageBlacklist(Class clazz); - public void addFluidToStorageBlacklist(Class clazz); + public void addFluidToStorageBlacklist(Fluid fluid); - public void addFluidToStorageBlacklist(Fluid fluid); + public IBlockDefinition blocks(); - public IBlockDefinition blocks(); + public boolean canFluidSeeInTerminal(Fluid fluid); - public boolean canFluidSeeInTerminal(Fluid fluid); + public boolean canStoreFluid(Fluid fluid); - public boolean canStoreFluid(Fluid fluid); + /** + * @deprecated incorrect spelling + */ + @Deprecated + public String getVerion(); - /** - * @deprecated incorrect spelling - */ - @Deprecated - public String getVerion(); + public String getVersion(); - public String getVersion(); + @Deprecated + public IWirelessFluidTermHandler getWirelessFluidTermHandler(ItemStack is); - @Deprecated - public IWirelessFluidTermHandler getWirelessFluidTermHandler(ItemStack is); + public IWirelessGasFluidTermHandler getWirelessTermHandler(ItemStack is); - public IWirelessGasFluidTermHandler getWirelessTermHandler(ItemStack is); + public boolean isWirelessFluidTerminal(ItemStack is); - public boolean isWirelessFluidTerminal(ItemStack is); + public IItemDefinition items(); - public IItemDefinition items(); + @Deprecated + public ItemStack openPortableCellGui(EntityPlayer player, ItemStack stack, World world); - @Deprecated - public ItemStack openPortableCellGui(EntityPlayer player, ItemStack stack, World world); + public ItemStack openPortableGasCellGui(EntityPlayer player, ItemStack stack, World world); - public ItemStack openPortableGasCellGui(EntityPlayer player, ItemStack stack, World world); + public ItemStack openPortableFluidCellGui(EntityPlayer player, ItemStack stack, World world); - public ItemStack openPortableFluidCellGui(EntityPlayer player, ItemStack stack, World world); + @Deprecated + public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack stack, World world); - @Deprecated - public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack stack, World world); + public ItemStack openWirelessFluidTerminal(EntityPlayer player, ItemStack stack, World world); - public ItemStack openWirelessFluidTerminal(EntityPlayer player, ItemStack stack, World world); + public ItemStack openWirelessGasTerminal(EntityPlayer player, ItemStack stack, World world); - public ItemStack openWirelessGasTerminal(EntityPlayer player, ItemStack stack, World world); + @Deprecated + public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack stack, World world, int x, int y, int z, + Long key); - @Deprecated - public ItemStack openWirelessTerminal(EntityPlayer player, ItemStack stack, World world, int x, int y, int z, Long key); + public IPartDefinition parts(); - public IPartDefinition parts(); + public void registerWirelessTermHandler(IWirelessGasFluidTermHandler handler); - public void registerWirelessTermHandler(IWirelessGasFluidTermHandler handler); + @Deprecated + public void registerWirelessFluidTermHandler(IWirelessFluidTermHandler handler); - @Deprecated - public void registerWirelessFluidTermHandler(IWirelessFluidTermHandler handler); + /** + * @deprecated incorrect spelling + */ + @Deprecated + public void registryWirelessFluidTermHandler(IWirelessFluidTermHandler handler); - /** - * @deprecated incorrect spelling - */ - @Deprecated - public void registryWirelessFluidTermHandler(IWirelessFluidTermHandler handler); + public void registerFuelBurnTime(Fluid fuel, int burnTime); - public void registerFuelBurnTime(Fluid fuel, int burnTime); + public boolean isGasStack(IAEFluidStack stack); - public boolean isGasStack(IAEFluidStack stack); + public boolean isGasStack(FluidStack stack); - public boolean isGasStack(FluidStack stack); + public boolean isGas(Fluid fluid); - public boolean isGas(Fluid fluid); + /** + * Converts an IAEFluid stack to a GasStack + * + * @param fluidStack + * @return GasStack + */ + public Object createGasStack(IAEFluidStack fluidStack); - /** - * Converts an IAEFluid stack to a GasStack - * - * @param fluidStack - * @return GasStack + /** + * Create the fluidstack from the specific gas + * + * @param gasStack + * @return FluidStack */ - public Object createGasStack(IAEFluidStack fluidStack); + public IAEFluidStack createFluidStackFromGas(Object gasStack); - /** - * Create the fluidstack from the specific gas - * - * @param gasStack - * @return FluidStack + /** + * Create the ec fluid from the specific gas + * + * @param gas + * @return Fluid */ - public IAEFluidStack createFluidStackFromGas(Object gasStack); + public Fluid getGasFluid(Object gas); - /** - * Create the ec fluid from the specific gas - * - * @param gas - * @return Fluid + /** + * A registry for StorageBus interactions + * + * @param esh storage handler + */ + void addExternalStorageInterface(IExternalGasStorageHandler esh); + + /** + * @param te tile entity + * @param opposite direction + * @param mySrc source + * + * @return the handler for a given tile / forge direction */ - public Fluid getGasFluid(Object gas); - - /** - * A registry for StorageBus interactions - * - * @param esh storage handler - */ - void addExternalStorageInterface( IExternalGasStorageHandler esh ); - - /** - * @param te tile entity - * @param opposite direction - * @param mySrc source - * - * @return the handler for a given tile / forge direction - */ - IExternalGasStorageHandler getHandler(TileEntity te, ForgeDirection opposite, BaseActionSource mySrc ); + IExternalGasStorageHandler getHandler(TileEntity te, ForgeDirection opposite, BaseActionSource mySrc); } diff --git a/src/main/scala/extracells/api/IECTileEntity.java b/src/main/scala/extracells/api/IECTileEntity.java index 9d27b214d..b2f65be9e 100644 --- a/src/main/scala/extracells/api/IECTileEntity.java +++ b/src/main/scala/extracells/api/IECTileEntity.java @@ -5,8 +5,7 @@ public interface IECTileEntity extends IGridHost { - DimensionalCoord getLocation(); - - double getPowerUsage(); + DimensionalCoord getLocation(); + double getPowerUsage(); } diff --git a/src/main/scala/extracells/api/IExternalGasStorageHandler.java b/src/main/scala/extracells/api/IExternalGasStorageHandler.java index f5797c6f6..3c0ba5302 100644 --- a/src/main/scala/extracells/api/IExternalGasStorageHandler.java +++ b/src/main/scala/extracells/api/IExternalGasStorageHandler.java @@ -1,19 +1,17 @@ package extracells.api; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; import appeng.api.networking.security.BaseActionSource; import appeng.api.storage.IExternalStorageRegistry; import appeng.api.storage.IMEInventory; import appeng.api.storage.data.IAEFluidStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.util.ForgeDirection; - /** * A Registration Record for {@link IExternalStorageRegistry} */ -public interface IExternalGasStorageHandler -{ +public interface IExternalGasStorageHandler { /** * if this can handle the provided inventory, return true. ( Generally skipped by AE, and it just calls getInventory @@ -24,17 +22,17 @@ public interface IExternalGasStorageHandler * * @return true, if it can get a handler via getInventory */ - boolean canHandle(TileEntity te, ForgeDirection d, BaseActionSource mySrc ); + boolean canHandle(TileEntity te, ForgeDirection d, BaseActionSource mySrc); /** * if this can handle the given inventory, return the a IMEInventory implementing class for it, if not return null - * - * @param te to be handled tile entity - * @param d direction - * @param src source + * + * @param te to be handled tile entity + * @param d direction + * @param src source * * @return The Handler for the inventory */ - IMEInventory getInventory(TileEntity te, ForgeDirection d, BaseActionSource src ); -} \ No newline at end of file + IMEInventory getInventory(TileEntity te, ForgeDirection d, BaseActionSource src); +} diff --git a/src/main/scala/extracells/api/IFluidInterface.java b/src/main/scala/extracells/api/IFluidInterface.java index 504991950..3d71e6c90 100644 --- a/src/main/scala/extracells/api/IFluidInterface.java +++ b/src/main/scala/extracells/api/IFluidInterface.java @@ -8,14 +8,13 @@ public interface IFluidInterface { - public Fluid getFilter(ForgeDirection side); + public Fluid getFilter(ForgeDirection side); - public IFluidTank getFluidTank(ForgeDirection side); + public IFluidTank getFluidTank(ForgeDirection side); - public IInventory getPatternInventory(); + public IInventory getPatternInventory(); - public void setFilter(ForgeDirection side, Fluid fluid); - - public void setFluidTank(ForgeDirection side, FluidStack fluid); + public void setFilter(ForgeDirection side, Fluid fluid); + public void setFluidTank(ForgeDirection side, FluidStack fluid); } diff --git a/src/main/scala/extracells/api/IFluidStorageCell.java b/src/main/scala/extracells/api/IFluidStorageCell.java index dab8e37c5..e38d98733 100644 --- a/src/main/scala/extracells/api/IFluidStorageCell.java +++ b/src/main/scala/extracells/api/IFluidStorageCell.java @@ -1,23 +1,26 @@ package extracells.api; -import appeng.api.storage.ICellWorkbenchItem; +import java.util.ArrayList; + import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; -import java.util.ArrayList; +import appeng.api.storage.ICellWorkbenchItem; public interface IFluidStorageCell extends ICellWorkbenchItem { - /** - * - * @param ItemStack - * @return the Fluid Filter. An empty ArrayList or null if the cell accepts - * all Fluids - */ - public ArrayList getFilter(ItemStack is); + /** + * + * @param ItemStack + * @return the Fluid Filter. An empty ArrayList or null if the cell accepts all Fluids + */ + public ArrayList getFilter(ItemStack is); - public int getMaxBytes(ItemStack is); + public int getMaxBytes(ItemStack is); - public int getMaxTypes(ItemStack is); + public int getMaxTypes(ItemStack is); + public default double idleDrain(ItemStack is) { + return 0.0; + } } diff --git a/src/main/scala/extracells/api/IGasStorageCell.java b/src/main/scala/extracells/api/IGasStorageCell.java index 7a2918de4..1c75e76a9 100644 --- a/src/main/scala/extracells/api/IGasStorageCell.java +++ b/src/main/scala/extracells/api/IGasStorageCell.java @@ -1,23 +1,22 @@ package extracells.api; -import appeng.api.storage.ICellWorkbenchItem; +import java.util.ArrayList; + import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; -import java.util.ArrayList; +import appeng.api.storage.ICellWorkbenchItem; public interface IGasStorageCell extends ICellWorkbenchItem { - /** - * - * @param ItemStack - * @return the Fluid Filter. An empty ArrayList or null if the cell accepts - * all Gas - */ - public ArrayList getFilter(ItemStack is); - - public int getMaxBytes(ItemStack is); + /** + * + * @param ItemStack + * @return the Fluid Filter. An empty ArrayList or null if the cell accepts all Gas + */ + public ArrayList getFilter(ItemStack is); - public int getMaxTypes(ItemStack is); + public int getMaxBytes(ItemStack is); + public int getMaxTypes(ItemStack is); } diff --git a/src/main/scala/extracells/api/IHandlerFluidStorage.java b/src/main/scala/extracells/api/IHandlerFluidStorage.java index 785fdb5a4..a2580aba7 100644 --- a/src/main/scala/extracells/api/IHandlerFluidStorage.java +++ b/src/main/scala/extracells/api/IHandlerFluidStorage.java @@ -2,14 +2,13 @@ public interface IHandlerFluidStorage { - boolean isFormatted(); + boolean isFormatted(); - int totalBytes(); + int totalBytes(); - int totalTypes(); + int totalTypes(); - int usedBytes(); - - int usedTypes(); + int usedBytes(); + int usedTypes(); } diff --git a/src/main/scala/extracells/api/IPortableFluidStorageCell.java b/src/main/scala/extracells/api/IPortableFluidStorageCell.java index 8965bb47f..3a36e8ae6 100644 --- a/src/main/scala/extracells/api/IPortableFluidStorageCell.java +++ b/src/main/scala/extracells/api/IPortableFluidStorageCell.java @@ -5,8 +5,7 @@ public interface IPortableFluidStorageCell extends IFluidStorageCell { - public boolean hasPower(EntityPlayer player, double amount, ItemStack is); - - public boolean usePower(EntityPlayer player, double amount, ItemStack is); + public boolean hasPower(EntityPlayer player, double amount, ItemStack is); + public boolean usePower(EntityPlayer player, double amount, ItemStack is); } diff --git a/src/main/scala/extracells/api/IPortableGasStorageCell.java b/src/main/scala/extracells/api/IPortableGasStorageCell.java index 1b180cb6e..2871e542e 100644 --- a/src/main/scala/extracells/api/IPortableGasStorageCell.java +++ b/src/main/scala/extracells/api/IPortableGasStorageCell.java @@ -5,8 +5,7 @@ public interface IPortableGasStorageCell extends IGasStorageCell { - public boolean hasPower(EntityPlayer player, double amount, ItemStack is); - - public boolean usePower(EntityPlayer player, double amount, ItemStack is); + public boolean hasPower(EntityPlayer player, double amount, ItemStack is); + public boolean usePower(EntityPlayer player, double amount, ItemStack is); } diff --git a/src/main/scala/extracells/api/IStorageCellAdvanced.java b/src/main/scala/extracells/api/IStorageCellAdvanced.java new file mode 100644 index 000000000..f1a9565d6 --- /dev/null +++ b/src/main/scala/extracells/api/IStorageCellAdvanced.java @@ -0,0 +1,77 @@ +package extracells.api; + +import javax.annotation.Nullable; + +import net.minecraft.item.ItemStack; + +import appeng.api.storage.ICellWorkbenchItem; +import appeng.api.storage.data.IAEItemStack; + +/** + * Any item which implements this can be treated as an IMEInventory via Util.getCell / Util.isCell It automatically + * handles the internals and NBT data, which is both nice, and bad for you! + *

+ * Good cause it means you don't have to do anything, bad because you have little to no control over it. + *

+ * This implementation is a mirror of the standard AE2 item cell type, but allows for any amount of types (within + * reason) and larger byte amounts. + */ +public interface IStorageCellAdvanced extends ICellWorkbenchItem { + + /** + * It wont work if the return is not a multiple of 8. The limit is ({@link Long#MAX_VALUE}) / 8. + * + * @param cellItem item + * @return number of bytes + */ + long getBytes(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); + + /** + * 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 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); + + /** + * @param i item + * @return drain in ae/t this storage cell will use. + */ + double getIdleDrain(@Nullable ItemStack i); +} diff --git a/src/main/scala/extracells/api/IStorageCellVoid.java b/src/main/scala/extracells/api/IStorageCellVoid.java new file mode 100644 index 000000000..5ec973706 --- /dev/null +++ b/src/main/scala/extracells/api/IStorageCellVoid.java @@ -0,0 +1,31 @@ +package extracells.api; + +import javax.annotation.Nullable; + +import net.minecraft.item.ItemStack; + +import appeng.api.storage.ICellWorkbenchItem; +import appeng.api.storage.data.IAEItemStack; + +// Copy of IStorageCell +public interface IStorageCellVoid extends ICellWorkbenchItem { + + int getBytes(ItemStack cellItem); + + int getBytesPerType(ItemStack cellItem); + + int getTotalTypes(ItemStack cellItem); + + boolean isBlackListed(ItemStack cellItem, IAEItemStack requestedAddition); + + boolean storableInStorageCell(); + + boolean isStorageCell(ItemStack i); + + default double getIdleDrain(@Nullable ItemStack i) { + // provided for API backwards compatibility + return getIdleDrain(); + } + + double getIdleDrain(); +} diff --git a/src/main/scala/extracells/api/IWirelessFluidTermHandler.java b/src/main/scala/extracells/api/IWirelessFluidTermHandler.java index 265ec993e..0f7828554 100644 --- a/src/main/scala/extracells/api/IWirelessFluidTermHandler.java +++ b/src/main/scala/extracells/api/IWirelessFluidTermHandler.java @@ -1,7 +1,4 @@ package extracells.api; public interface IWirelessFluidTermHandler extends IWirelessGasFluidTermHandler { - - - } diff --git a/src/main/scala/extracells/api/IWirelessGasFluidTermHandler.java b/src/main/scala/extracells/api/IWirelessGasFluidTermHandler.java index cda2f4068..5169ff302 100644 --- a/src/main/scala/extracells/api/IWirelessGasFluidTermHandler.java +++ b/src/main/scala/extracells/api/IWirelessGasFluidTermHandler.java @@ -1,10 +1,10 @@ package extracells.api; - -import appeng.api.features.INetworkEncodable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +import appeng.api.features.INetworkEncodable; + public interface IWirelessGasFluidTermHandler extends INetworkEncodable { boolean canHandle(ItemStack is); diff --git a/src/main/scala/extracells/api/IWirelessGasTermHandler.java b/src/main/scala/extracells/api/IWirelessGasTermHandler.java index db85eece7..77e697806 100644 --- a/src/main/scala/extracells/api/IWirelessGasTermHandler.java +++ b/src/main/scala/extracells/api/IWirelessGasTermHandler.java @@ -1,6 +1,4 @@ package extracells.api; - public interface IWirelessGasTermHandler extends IWirelessGasFluidTermHandler { - } diff --git a/src/main/scala/extracells/api/crafting/IFluidCraftingPatternDetails.java b/src/main/scala/extracells/api/crafting/IFluidCraftingPatternDetails.java index b720ce596..1b1e7aa44 100644 --- a/src/main/scala/extracells/api/crafting/IFluidCraftingPatternDetails.java +++ b/src/main/scala/extracells/api/crafting/IFluidCraftingPatternDetails.java @@ -5,8 +5,7 @@ public interface IFluidCraftingPatternDetails extends ICraftingPatternDetails { - public IAEFluidStack[] getCondensedFluidInputs(); - - public IAEFluidStack[] getFluidInputs(); + public IAEFluidStack[] getCondensedFluidInputs(); + public IAEFluidStack[] getFluidInputs(); } diff --git a/src/main/scala/extracells/api/definitions/IBlockDefinition.java b/src/main/scala/extracells/api/definitions/IBlockDefinition.java index c5e4e3933..679658812 100644 --- a/src/main/scala/extracells/api/definitions/IBlockDefinition.java +++ b/src/main/scala/extracells/api/definitions/IBlockDefinition.java @@ -4,13 +4,21 @@ public interface IBlockDefinition { - ITileDefinition blockInterface(); + ITileDefinition blockInterface(); - ITileDefinition certusTank(); + ITileDefinition certusTank(); - ITileDefinition fluidCrafter(); + ITileDefinition fluidCrafter(); - ITileDefinition fluidFiller(); + ITileDefinition fluidFiller(); - ITileDefinition walrus(); + ITileDefinition walrus(); + + ITileDefinition craftingStorage256k(); + + ITileDefinition craftingStorage1024k(); + + ITileDefinition craftingStorage4096k(); + + ITileDefinition craftingStorage16384k(); } diff --git a/src/main/scala/extracells/api/definitions/IItemDefinition.java b/src/main/scala/extracells/api/definitions/IItemDefinition.java index f9c709b7e..56ddbdc04 100644 --- a/src/main/scala/extracells/api/definitions/IItemDefinition.java +++ b/src/main/scala/extracells/api/definitions/IItemDefinition.java @@ -1,66 +1,73 @@ package extracells.api.definitions; - public interface IItemDefinition { - // Fluid Storage Components - appeng.api.definitions.IItemDefinition cell1kPartFluid(); + // Fluid Storage Components + appeng.api.definitions.IItemDefinition cell1kPartFluid(); + + appeng.api.definitions.IItemDefinition cell4kPartFluid(); + + appeng.api.definitions.IItemDefinition cell16kPartFluid(); + + appeng.api.definitions.IItemDefinition cell64kPartFluid(); + + appeng.api.definitions.IItemDefinition cell256kPartFluid(); - appeng.api.definitions.IItemDefinition cell4kPartFluid(); + appeng.api.definitions.IItemDefinition cell1024kPartFluid(); - appeng.api.definitions.IItemDefinition cell16kPartFluid(); + appeng.api.definitions.IItemDefinition cell4096kPartFluid(); - appeng.api.definitions.IItemDefinition cell64kPartFluid(); + // Physical Storage Components + appeng.api.definitions.IItemDefinition cell256kPart(); - appeng.api.definitions.IItemDefinition cell256kPartFluid(); + appeng.api.definitions.IItemDefinition cell1024kPart(); - appeng.api.definitions.IItemDefinition cell1024kPartFluid(); + appeng.api.definitions.IItemDefinition cell4096kPart(); - appeng.api.definitions.IItemDefinition cell4096kPartFluid(); + appeng.api.definitions.IItemDefinition cell16384kPart(); - // Physical Storage Components - appeng.api.definitions.IItemDefinition cell256kPart(); + // Fluid Storage Casing + appeng.api.definitions.IItemDefinition fluidCasing(); - appeng.api.definitions.IItemDefinition cell1024kPart(); + // Fluid Cells + appeng.api.definitions.IItemDefinition fluidCell1k(); - appeng.api.definitions.IItemDefinition cell4096kPart(); + appeng.api.definitions.IItemDefinition fluidCell4k(); - appeng.api.definitions.IItemDefinition cell16384kPart(); + appeng.api.definitions.IItemDefinition fluidCell16k(); - // Fluid Storage Casing - appeng.api.definitions.IItemDefinition fluidCasing(); + appeng.api.definitions.IItemDefinition fluidCell64k(); - // Fluid Cells - appeng.api.definitions.IItemDefinition fluidCell1k(); + appeng.api.definitions.IItemDefinition fluidCell256k(); - appeng.api.definitions.IItemDefinition fluidCell4k(); + appeng.api.definitions.IItemDefinition fluidCell1024k(); - appeng.api.definitions.IItemDefinition fluidCell16k(); + appeng.api.definitions.IItemDefinition fluidCell4096k(); - appeng.api.definitions.IItemDefinition fluidCell64k(); + appeng.api.definitions.IItemDefinition fluidCellPortable(); - appeng.api.definitions.IItemDefinition fluidCell256k(); + // Physical Storage Casing + appeng.api.definitions.IItemDefinition physCasing(); - appeng.api.definitions.IItemDefinition fluidCell1024k(); + // Physical Cells + appeng.api.definitions.IItemDefinition physCell256k(); - appeng.api.definitions.IItemDefinition fluidCell4096k(); + appeng.api.definitions.IItemDefinition physCell1024k(); - appeng.api.definitions.IItemDefinition fluidCellPortable(); + appeng.api.definitions.IItemDefinition physCell4096k(); - // Physical Storage Casing - appeng.api.definitions.IItemDefinition physCasing(); + appeng.api.definitions.IItemDefinition physCell16384k(); - // Physical Cells - appeng.api.definitions.IItemDefinition physCell256k(); + appeng.api.definitions.IItemDefinition physCellContainer(); - appeng.api.definitions.IItemDefinition physCell1024k(); + appeng.api.definitions.IItemDefinition physCellAdvancedSingularity(); - appeng.api.definitions.IItemDefinition physCell4096k(); + appeng.api.definitions.IItemDefinition physCellAdvancedQuantum(); - appeng.api.definitions.IItemDefinition physCell16384k(); + appeng.api.definitions.IItemDefinition physCellVoid(); - appeng.api.definitions.IItemDefinition physCellContainer(); + // MISC + appeng.api.definitions.IItemDefinition wirelessFluidTerminal(); - // MISC - appeng.api.definitions.IItemDefinition wirelessFluidTerminal(); + appeng.api.definitions.IItemDefinition itemFluidPattern(); } diff --git a/src/main/scala/extracells/api/definitions/IPartDefinition.java b/src/main/scala/extracells/api/definitions/IPartDefinition.java index 7e7a301ff..1f44cf843 100644 --- a/src/main/scala/extracells/api/definitions/IPartDefinition.java +++ b/src/main/scala/extracells/api/definitions/IPartDefinition.java @@ -1,31 +1,30 @@ package extracells.api.definitions; - public interface IPartDefinition { - appeng.api.definitions.IItemDefinition partBattery(); + appeng.api.definitions.IItemDefinition partBattery(); - appeng.api.definitions.IItemDefinition partConversionMonitor(); + appeng.api.definitions.IItemDefinition partConversionMonitor(); - appeng.api.definitions.IItemDefinition partDrive(); + appeng.api.definitions.IItemDefinition partDrive(); - appeng.api.definitions.IItemDefinition partFluidAnnihilationPlane(); + appeng.api.definitions.IItemDefinition partFluidAnnihilationPlane(); - appeng.api.definitions.IItemDefinition partFluidExportBus(); + appeng.api.definitions.IItemDefinition partFluidExportBus(); - appeng.api.definitions.IItemDefinition partFluidFormationPlane(); + appeng.api.definitions.IItemDefinition partFluidFormationPlane(); - appeng.api.definitions.IItemDefinition partFluidImportBus(); + appeng.api.definitions.IItemDefinition partFluidImportBus(); - appeng.api.definitions.IItemDefinition partFluidLevelEmitter(); + appeng.api.definitions.IItemDefinition partFluidLevelEmitter(); - appeng.api.definitions.IItemDefinition partFluidStorageBus(); + appeng.api.definitions.IItemDefinition partFluidStorageBus(); - appeng.api.definitions.IItemDefinition partFluidTerminal(); + appeng.api.definitions.IItemDefinition partFluidTerminal(); - appeng.api.definitions.IItemDefinition partInterface(); + appeng.api.definitions.IItemDefinition partInterface(); - appeng.api.definitions.IItemDefinition partOreDictExportBus(); + appeng.api.definitions.IItemDefinition partOreDictExportBus(); - appeng.api.definitions.IItemDefinition partStorageMonitor(); + appeng.api.definitions.IItemDefinition partStorageMonitor(); } diff --git a/src/main/scala/extracells/block/BlockCertusTank.java b/src/main/scala/extracells/block/BlockCertusTank.java index 7b59c3bcf..59ad46bbf 100644 --- a/src/main/scala/extracells/block/BlockCertusTank.java +++ b/src/main/scala/extracells/block/BlockCertusTank.java @@ -1,11 +1,5 @@ package extracells.block; -import appeng.api.implementations.items.IAEWrench; -import buildcraft.api.tools.IToolWrench; -import extracells.network.ChannelHandler; -import extracells.registries.BlockEnum; -import extracells.render.RenderHandler; -import extracells.tileentity.TileEntityCertusTank; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -21,199 +15,192 @@ import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; +import appeng.api.implementations.items.IAEWrench; +import buildcraft.api.tools.IToolWrench; +import extracells.network.ChannelHandler; +import extracells.registries.BlockEnum; +import extracells.render.RenderHandler; +import extracells.tileentity.TileEntityCertusTank; + public class BlockCertusTank extends BlockEC { - IIcon breakIcon; - IIcon topIcon; - IIcon bottomIcon; - IIcon sideIcon; - IIcon sideMiddleIcon; - IIcon sideTopIcon; - IIcon sideBottomIcon; - - public BlockCertusTank() { - super(Material.glass, 2.0F, 10.0F); - setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 1.0F, 0.9375F); - } - - @Override - public boolean canRenderInPass(int pass) { - RenderHandler.renderPass = pass; - return true; - } - - @Override - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityCertusTank(); - } - - public ItemStack getDropWithNBT(World world, int x, int y, int z) { - NBTTagCompound tileEntity = new NBTTagCompound(); - TileEntity worldTE = world.getTileEntity(x, y, z); - if (worldTE != null && worldTE instanceof TileEntityCertusTank) { - ItemStack dropStack = new ItemStack( - BlockEnum.CERTUSTANK.getBlock(), 1); - - ((TileEntityCertusTank) worldTE) - .writeToNBTWithoutCoords(tileEntity); - - if (!tileEntity.hasKey("Empty")) { - dropStack.setTagCompound(new NBTTagCompound()); - dropStack.stackTagCompound.setTag("tileEntity", tileEntity); - } - return dropStack; - - } - return null; - } - - @Override - public IIcon getIcon(int side, int b) { - switch (b) { - case 1: - return this.sideTopIcon; - case 2: - return this.sideBottomIcon; - case 3: - return this.sideMiddleIcon; - default: - return side == 0 ? this.bottomIcon : side == 1 ? this.topIcon - : this.sideIcon; - } - } - - @Override - public String getLocalizedName() { - return StatCollector.translateToLocal(getUnlocalizedName() + ".name"); - } - - @Override - public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { - return getDropWithNBT(world, x, y, z); - } - - @Override - public int getRenderBlockPass() { - return 1; - } - - @Override - public int getRenderType() { - return RenderHandler.getId(); - } - - @Override - public String getUnlocalizedName() { - return super.getUnlocalizedName().replace("tile.", ""); - } - - @Override - public boolean isOpaqueCube() { - return false; - } - - @Override - public boolean onBlockActivated(World worldObj, int x, int y, int z, - EntityPlayer entityplayer, int blockID, float offsetX, - float offsetY, float offsetZ) { - ItemStack current = entityplayer.inventory.getCurrentItem(); - - if (entityplayer.isSneaking() && current != null) { - try { - if (current.getItem() instanceof IToolWrench - && ((IToolWrench) current.getItem()).canWrench( - entityplayer, x, y, z)) { - dropBlockAsItem(worldObj, x, y, z, - getDropWithNBT(worldObj, x, y, z)); - worldObj.setBlockToAir(x, y, z); - ((IToolWrench) current.getItem()).wrenchUsed(entityplayer, - x, y, z); - return true; - } - } catch (Throwable e) { - // No IToolWrench - } - if (current.getItem() instanceof IAEWrench - && ((IAEWrench) current.getItem()).canWrench(current, - entityplayer, x, y, z)) { - dropBlockAsItem(worldObj, x, y, z, - getDropWithNBT(worldObj, x, y, z)); - worldObj.setBlockToAir(x, y, z); - return true; - } - - } - if (current != null) { - FluidStack liquid = FluidContainerRegistry.getFluidForFilledItem(current); - TileEntityCertusTank tank = (TileEntityCertusTank) worldObj.getTileEntity(x, y, z); - - if (liquid != null) { - int amountFilled = tank.fill(ForgeDirection.UNKNOWN, liquid, true); - - if (amountFilled != 0 - && !entityplayer.capabilities.isCreativeMode) { - if (current.stackSize > 1) { - entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem].stackSize -= 1; - entityplayer.inventory.addItemStackToInventory(current.getItem().getContainerItem(current)); - } else { - entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = current.getItem().getContainerItem(current); - } - } - - return true; - - // Handle empty containers - } else { - - FluidStack available = tank.getTankInfo(ForgeDirection.UNKNOWN)[0].fluid; - if (available != null) { - ItemStack filled = FluidContainerRegistry.fillFluidContainer(available, current); - - liquid = FluidContainerRegistry.getFluidForFilledItem(filled); - - if (liquid != null) { - if (!entityplayer.capabilities.isCreativeMode) { - if (current.stackSize > 1) { - if (!entityplayer.inventory.addItemStackToInventory(filled)) { - return false; - } else { - entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem].stackSize -= 1; - } - } else { - entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = filled; - } - } - tank.drain(ForgeDirection.UNKNOWN, liquid.amount, true); - return true; - } - } - } - } - return false; - } - - @Override - public void onNeighborBlockChange(World world, int x, int y, int z, - Block neighborBlock) { - if (!world.isRemote) { - - ChannelHandler.sendPacketToAllPlayers(world.getTileEntity(x, y, z).getDescriptionPacket(), world); - } - } - - @Override - public void registerBlockIcons(IIconRegister iconregister) { - this.breakIcon = iconregister.registerIcon("extracells:certustank"); - this.topIcon = iconregister.registerIcon("extracells:CTankTop"); - this.bottomIcon = iconregister.registerIcon("extracells:CTankBottom"); - this.sideIcon = iconregister.registerIcon("extracells:CTankSide"); - this.sideMiddleIcon = iconregister.registerIcon("extracells:CTankSideMiddle"); - this.sideTopIcon = iconregister.registerIcon("extracells:CTankSideTop"); - this.sideBottomIcon = iconregister.registerIcon("extracells:CTankSideBottom"); - } - - @Override - public boolean renderAsNormalBlock() { - return false; - } + IIcon breakIcon; + IIcon topIcon; + IIcon bottomIcon; + IIcon sideIcon; + IIcon sideMiddleIcon; + IIcon sideTopIcon; + IIcon sideBottomIcon; + + public BlockCertusTank() { + super(Material.glass, 2.0F, 10.0F); + setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 1.0F, 0.9375F); + } + + @Override + public boolean canRenderInPass(int pass) { + RenderHandler.renderPass = pass; + return true; + } + + @Override + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityCertusTank(); + } + + public ItemStack getDropWithNBT(World world, int x, int y, int z) { + NBTTagCompound tileEntity = new NBTTagCompound(); + TileEntity worldTE = world.getTileEntity(x, y, z); + if (worldTE instanceof TileEntityCertusTank) { + ItemStack dropStack = new ItemStack(BlockEnum.CERTUSTANK.getBlock(), 1); + + ((TileEntityCertusTank) worldTE).writeToNBTWithoutCoords(tileEntity); + + if (!tileEntity.hasKey("Empty")) { + dropStack.setTagCompound(new NBTTagCompound()); + dropStack.stackTagCompound.setTag("tileEntity", tileEntity); + } + return dropStack; + } + return null; + } + + @Override + public IIcon getIcon(int side, int b) { + switch (b) { + case 1: + return this.sideTopIcon; + case 2: + return this.sideBottomIcon; + case 3: + return this.sideMiddleIcon; + default: + return side == 0 ? this.bottomIcon : side == 1 ? this.topIcon : this.sideIcon; + } + } + + @Override + public String getLocalizedName() { + return StatCollector.translateToLocal(getUnlocalizedName() + ".name"); + } + + @Override + public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { + return getDropWithNBT(world, x, y, z); + } + + @Override + public int getRenderBlockPass() { + return 1; + } + + @Override + public int getRenderType() { + return RenderHandler.getId(); + } + + @Override + public String getUnlocalizedName() { + return super.getUnlocalizedName().replace("tile.", ""); + } + + @Override + public boolean isOpaqueCube() { + return false; + } + + @Override + public boolean onBlockActivated(World worldObj, int x, int y, int z, EntityPlayer entityplayer, int blockID, + float offsetX, float offsetY, float offsetZ) { + ItemStack current = entityplayer.inventory.getCurrentItem(); + + if (entityplayer.isSneaking() && current != null) { + try { + if (current.getItem() instanceof IToolWrench + && ((IToolWrench) current.getItem()).canWrench(entityplayer, x, y, z)) { + dropBlockAsItem(worldObj, x, y, z, getDropWithNBT(worldObj, x, y, z)); + worldObj.setBlockToAir(x, y, z); + ((IToolWrench) current.getItem()).wrenchUsed(entityplayer, x, y, z); + return true; + } + } catch (Throwable e) { + // No IToolWrench + } + if (current.getItem() instanceof IAEWrench + && ((IAEWrench) current.getItem()).canWrench(current, entityplayer, x, y, z)) { + dropBlockAsItem(worldObj, x, y, z, getDropWithNBT(worldObj, x, y, z)); + worldObj.setBlockToAir(x, y, z); + return true; + } + } + if (current != null) { + FluidStack liquid = FluidContainerRegistry.getFluidForFilledItem(current); + TileEntityCertusTank tank = (TileEntityCertusTank) worldObj.getTileEntity(x, y, z); + + if (liquid != null) { + int amountFilled = tank.fill(ForgeDirection.UNKNOWN, liquid, true); + + if (amountFilled != 0 && !entityplayer.capabilities.isCreativeMode) { + if (current.stackSize > 1) { + entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem].stackSize -= 1; + entityplayer.inventory.addItemStackToInventory(current.getItem().getContainerItem(current)); + } else { + entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = current.getItem() + .getContainerItem(current); + } + } + + return true; + + // Handle empty containers + } else { + + FluidStack available = tank.getTankInfo(ForgeDirection.UNKNOWN)[0].fluid; + if (available != null) { + ItemStack filled = FluidContainerRegistry.fillFluidContainer(available, current); + + liquid = FluidContainerRegistry.getFluidForFilledItem(filled); + + if (liquid != null) { + tank.drain(ForgeDirection.UNKNOWN, liquid.amount, true); + if (!entityplayer.capabilities.isCreativeMode) { + if (current.stackSize == 1) { + entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = filled; + } else { + entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem].stackSize--; + if (!entityplayer.inventory.addItemStackToInventory(filled)) + entityplayer.entityDropItem(filled, 0); + } + } + return true; + } + } + } + } + return false; + } + + @Override + public void onNeighborBlockChange(World world, int x, int y, int z, Block neighborBlock) { + if (!world.isRemote) { + + ChannelHandler.sendPacketToAllPlayers(world.getTileEntity(x, y, z).getDescriptionPacket(), world); + } + } + + @Override + public void registerBlockIcons(IIconRegister iconregister) { + this.breakIcon = iconregister.registerIcon("extracells:certustank"); + this.topIcon = iconregister.registerIcon("extracells:CTankTop"); + this.bottomIcon = iconregister.registerIcon("extracells:CTankBottom"); + this.sideIcon = iconregister.registerIcon("extracells:CTankSide"); + this.sideMiddleIcon = iconregister.registerIcon("extracells:CTankSideMiddle"); + this.sideTopIcon = iconregister.registerIcon("extracells:CTankSideTop"); + this.sideBottomIcon = iconregister.registerIcon("extracells:CTankSideBottom"); + } + + @Override + public boolean renderAsNormalBlock() { + return false; + } } diff --git a/src/main/scala/extracells/block/BlockCraftingStorage.java b/src/main/scala/extracells/block/BlockCraftingStorage.java new file mode 100644 index 000000000..b382498b7 --- /dev/null +++ b/src/main/scala/extracells/block/BlockCraftingStorage.java @@ -0,0 +1,67 @@ +package extracells.block; + +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; + +import extracells.Extracells; +import extracells.tileentity.TileEntityCraftingStorage; + +public class BlockCraftingStorage extends appeng.block.crafting.BlockCraftingStorage { + + private static IIcon[] icons = new IIcon[8]; + + public BlockCraftingStorage() { + this.setTileEntity(TileEntityCraftingStorage.class); + this.setCreativeTab(Extracells.ModTab()); + this.hasSubtypes = true; + this.setBlockName("blockCraftingStorage"); + } + + @Override + public String getUnlocalizedName(ItemStack is) { + return this.getItemUnlocalizedName(is); + } + + protected String getItemUnlocalizedName(ItemStack is) { + return super.getUnlocalizedName(is); + } + + public void registerBlockIcons(IIconRegister ir) { + icons[0] = ir.registerIcon("extracells:crafting.storage.256k"); + icons[1] = ir.registerIcon("extracells:crafting.storage.256k.fit"); + + icons[2] = ir.registerIcon("extracells:crafting.storage.1024k"); + icons[3] = ir.registerIcon("extracells:crafting.storage.1024k.fit"); + + icons[4] = ir.registerIcon("extracells:crafting.storage.4096k"); + icons[5] = ir.registerIcon("extracells:crafting.storage.4096k.fit"); + + icons[6] = ir.registerIcon("extracells:crafting.storage.16384k"); + icons[7] = ir.registerIcon("extracells:crafting.storage.16384k.fit"); + } + + @Override + public IIcon getIcon(int side, int meta) { + switch (meta & (~4)) { + case 0: + return icons[0]; + case 1: + return icons[2]; + case 2: + return icons[4]; + case 3: + return icons[6]; + case 8: + return icons[1]; + case 1 | 8: + return icons[3]; + case 2 | 8: + return icons[5]; + case 3 | 8: + return icons[7]; + default: + return null; + } + } +} diff --git a/src/main/scala/extracells/block/BlockEC.java b/src/main/scala/extracells/block/BlockEC.java index c01154b97..5506b1eeb 100644 --- a/src/main/scala/extracells/block/BlockEC.java +++ b/src/main/scala/extracells/block/BlockEC.java @@ -3,7 +3,6 @@ import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; - public abstract class BlockEC extends BlockContainer { protected BlockEC(Material material, float hardness, float resistance) { @@ -15,5 +14,4 @@ protected BlockEC(Material material, float hardness, float resistance) { protected BlockEC(Material material) { super(material); } - } diff --git a/src/main/scala/extracells/block/BlockFluidCrafter.java b/src/main/scala/extracells/block/BlockFluidCrafter.java index 31a72c370..34c824117 100644 --- a/src/main/scala/extracells/block/BlockFluidCrafter.java +++ b/src/main/scala/extracells/block/BlockFluidCrafter.java @@ -1,13 +1,7 @@ package extracells.block; -import appeng.api.AEApi; -import appeng.api.config.SecurityPermissions; -import appeng.api.implementations.items.IAEWrench; -import appeng.api.networking.IGridNode; -import buildcraft.api.tools.IToolWrench; -import extracells.network.GuiHandler; -import extracells.tileentity.TileEntityFluidCrafter; -import extracells.util.PermissionUtil; +import java.util.Random; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -22,154 +16,146 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import java.util.Random; +import appeng.api.AEApi; +import appeng.api.config.SecurityPermissions; +import appeng.api.implementations.items.IAEWrench; +import appeng.api.networking.IGridNode; +import buildcraft.api.tools.IToolWrench; +import extracells.network.GuiHandler; +import extracells.tileentity.TileEntityFluidCrafter; +import extracells.util.PermissionUtil; public class BlockFluidCrafter extends BlockEC { - IIcon icon; - - public BlockFluidCrafter() { - super(Material.iron, 2.0F, 10.0F); - } - - @Override - public void breakBlock(World world, int x, int y, int z, Block par5, - int par6) { - dropItems(world, x, y, z); - super.breakBlock(world, x, y, z, par5, par6); - } - - @Override - public TileEntity createNewTileEntity(World world, int meta) { - return new TileEntityFluidCrafter(); - } - - private void dropItems(World world, int x, int y, int z) { - Random rand = new Random(); - - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (!(tileEntity instanceof TileEntityFluidCrafter)) { - return; - } - IInventory inventory = ((TileEntityFluidCrafter) tileEntity).inventory; - - for (int i = 0; i < inventory.getSizeInventory(); i++) { - ItemStack item = inventory.getStackInSlot(i); - - if (item != null && item.stackSize > 0) { - float rx = rand.nextFloat() * 0.8F + 0.1F; - float ry = rand.nextFloat() * 0.8F + 0.1F; - float rz = rand.nextFloat() * 0.8F + 0.1F; - - EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z - + rz, item.copy()); - - if (item.hasTagCompound()) { - entityItem.getEntityItem().setTagCompound( - (NBTTagCompound) item.getTagCompound().copy()); - } - - float factor = 0.05F; - entityItem.motionX = rand.nextGaussian() * factor; - entityItem.motionY = rand.nextGaussian() * factor + 0.2F; - entityItem.motionZ = rand.nextGaussian() * factor; - world.spawnEntityInWorld(entityItem); - item.stackSize = 0; - } - } - } - - @Override - public IIcon getIcon(int side, int b) { - return this.icon; - } - - @Override - public String getLocalizedName() { - return StatCollector.translateToLocal(getUnlocalizedName() + ".name"); - } - - @Override - public String getUnlocalizedName() { - return super.getUnlocalizedName().replace("tile.", ""); - } - - @Override - public boolean onBlockActivated(World world, int x, int y, int z, - EntityPlayer player, int side, float p_149727_7_, - float p_149727_8_, float p_149727_9_) { - if (world.isRemote) - return false; - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof TileEntityFluidCrafter) - if (!PermissionUtil.hasPermission(player, - SecurityPermissions.BUILD, - ((TileEntityFluidCrafter) tile).getGridNode())) - return false; - ItemStack current = player.inventory.getCurrentItem(); - if (player.isSneaking() && current != null) { - try { - if (current.getItem() instanceof IToolWrench - && ((IToolWrench) current.getItem()).canWrench(player, - x, y, z)) { - dropBlockAsItem(world, x, y, z, new ItemStack(this)); - world.setBlockToAir(x, y, z); - ((IToolWrench) current.getItem()).wrenchUsed(player, x, y, - z); - return true; - } - } catch (Throwable e) { - // No IToolWrench - } - if (current.getItem() instanceof IAEWrench - && ((IAEWrench) current.getItem()).canWrench(current, - player, x, y, z)) { - dropBlockAsItem(world, x, y, z, new ItemStack(this)); - world.setBlockToAir(x, y, z); - return true; - } - } - GuiHandler.launchGui(0, player, world, x, y, z); - return true; - } - - @Override - public void onBlockPlacedBy(World world, int x, int y, int z, - EntityLivingBase entity, ItemStack stack) { - if (world.isRemote) - return; - TileEntity tile = world.getTileEntity(x, y, z); - if (tile != null) { - if (tile instanceof TileEntityFluidCrafter) { - IGridNode node = ((TileEntityFluidCrafter) tile).getGridNode(); - if (entity != null && entity instanceof EntityPlayer) { - EntityPlayer player = (EntityPlayer) entity; - node.setPlayerID(AEApi.instance().registries().players() - .getID(player)); - } - node.updateState(); - } - } - } - - @Override - public void onBlockPreDestroy(World world, int x, int y, int z, int meta) { - if (world.isRemote) - return; - TileEntity tile = world.getTileEntity(x, y, z); - if (tile != null) { - if (tile instanceof TileEntityFluidCrafter) { - IGridNode node = ((TileEntityFluidCrafter) tile).getGridNode(); - if (node != null) { - node.destroy(); - } - } - } - } - - @Override - public void registerBlockIcons(IIconRegister iconregister) { - this.icon = iconregister.registerIcon("extracells:fluid.crafter"); - } - + IIcon icon; + + public BlockFluidCrafter() { + super(Material.iron, 2.0F, 10.0F); + } + + @Override + public void breakBlock(World world, int x, int y, int z, Block par5, int par6) { + dropItems(world, x, y, z); + super.breakBlock(world, x, y, z, par5, par6); + } + + @Override + public TileEntity createNewTileEntity(World world, int meta) { + return new TileEntityFluidCrafter(); + } + + private void dropItems(World world, int x, int y, int z) { + Random rand = new Random(); + + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (!(tileEntity instanceof TileEntityFluidCrafter)) { + return; + } + IInventory inventory = ((TileEntityFluidCrafter) tileEntity).inventory; + + for (int i = 0; i < inventory.getSizeInventory(); i++) { + ItemStack item = inventory.getStackInSlot(i); + + if (item != null && item.stackSize > 0) { + float rx = rand.nextFloat() * 0.8F + 0.1F; + float ry = rand.nextFloat() * 0.8F + 0.1F; + float rz = rand.nextFloat() * 0.8F + 0.1F; + + EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, item.copy()); + + if (item.hasTagCompound()) { + entityItem.getEntityItem().setTagCompound((NBTTagCompound) item.getTagCompound().copy()); + } + + float factor = 0.05F; + entityItem.motionX = rand.nextGaussian() * factor; + entityItem.motionY = rand.nextGaussian() * factor + 0.2F; + entityItem.motionZ = rand.nextGaussian() * factor; + world.spawnEntityInWorld(entityItem); + item.stackSize = 0; + } + } + } + + @Override + public IIcon getIcon(int side, int b) { + return this.icon; + } + + @Override + public String getLocalizedName() { + return StatCollector.translateToLocal(getUnlocalizedName() + ".name"); + } + + @Override + public String getUnlocalizedName() { + return super.getUnlocalizedName().replace("tile.", ""); + } + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float p_149727_7_, + float p_149727_8_, float p_149727_9_) { + if (world.isRemote) return false; + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof TileEntityFluidCrafter) if (!PermissionUtil + .hasPermission(player, SecurityPermissions.BUILD, ((TileEntityFluidCrafter) tile).getGridNode())) + return false; + ItemStack current = player.inventory.getCurrentItem(); + if (player.isSneaking() && current != null) { + try { + if (current.getItem() instanceof IToolWrench + && ((IToolWrench) current.getItem()).canWrench(player, x, y, z)) { + dropBlockAsItem(world, x, y, z, new ItemStack(this)); + world.setBlockToAir(x, y, z); + ((IToolWrench) current.getItem()).wrenchUsed(player, x, y, z); + return true; + } + } catch (Throwable e) { + // No IToolWrench + } + if (current.getItem() instanceof IAEWrench + && ((IAEWrench) current.getItem()).canWrench(current, player, x, y, z)) { + dropBlockAsItem(world, x, y, z, new ItemStack(this)); + world.setBlockToAir(x, y, z); + return true; + } + } + GuiHandler.launchGui(0, player, world, x, y, z); + return true; + } + + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack) { + if (world.isRemote) return; + TileEntity tile = world.getTileEntity(x, y, z); + if (tile != null) { + if (tile instanceof TileEntityFluidCrafter) { + IGridNode node = ((TileEntityFluidCrafter) tile).getGridNode(); + if (entity != null && entity instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) entity; + node.setPlayerID(AEApi.instance().registries().players().getID(player)); + } + node.updateState(); + } + } + } + + @Override + public void onBlockPreDestroy(World world, int x, int y, int z, int meta) { + if (world.isRemote) return; + TileEntity tile = world.getTileEntity(x, y, z); + if (tile != null) { + if (tile instanceof TileEntityFluidCrafter) { + IGridNode node = ((TileEntityFluidCrafter) tile).getGridNode(); + if (node != null) { + node.destroy(); + } + } + } + } + + @Override + public void registerBlockIcons(IIconRegister iconregister) { + this.icon = iconregister.registerIcon("extracells:fluid.crafter"); + } } diff --git a/src/main/scala/extracells/block/BlockHardMEDrive.scala b/src/main/scala/extracells/block/BlockHardMEDrive.scala index e0dc8c3e1..8546a69a9 100644 --- a/src/main/scala/extracells/block/BlockHardMEDrive.scala +++ b/src/main/scala/extracells/block/BlockHardMEDrive.scala @@ -27,9 +27,13 @@ import net.minecraft.util.{IIcon, MathHelper} import net.minecraft.world.World import net.minecraftforge.common.util.ForgeDirection - -object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.rock, 2.0F, 1000000.0F) with TGuiBlock{ - +object BlockHardMEDrive + extends BlockEC( + net.minecraft.block.material.Material.rock, + 2.0f, + 1000000.0f + ) + with TGuiBlock { var frontIcon: IIcon = null var sideIcon: IIcon = null @@ -37,7 +41,13 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro var topIcon: IIcon = null @SideOnly(Side.CLIENT) - override def getClientGuiElement(player: EntityPlayer, world: World, x: Int, y: Int, z: Int): Any = { + override def getClientGuiElement( + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = { val tile = world.getTileEntity(x, y, z) if (tile == null || player == null) return null tile match { @@ -48,7 +58,13 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro } } - override def getServerGuiElement(player: EntityPlayer, world: World, x: Int, y: Int, z: Int): Any = { + override def getServerGuiElement( + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = { val tile = world.getTileEntity(x, y, z) if (tile == null || player == null) return null tile match { @@ -59,14 +75,22 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro } } - //Only needed because BlockEnum is in java. not in scala + // Only needed because BlockEnum is in java. not in scala val instance = this setBlockName("block.hardmedrive"); - override def createNewTileEntity(world : World, meta : Int): TileEntity = new TileEntityHardMeDrive() + override def createNewTileEntity(world: World, meta: Int): TileEntity = + new TileEntityHardMeDrive() - override def breakBlock(world: World, x: Int, y: Int, z: Int, block: Block, par6: Int) { + override def breakBlock( + world: World, + x: Int, + y: Int, + z: Int, + block: Block, + par6: Int + ) { dropItems(world, x, y, z) super.breakBlock(world, x, y, z, block, par6) } @@ -77,23 +101,27 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro if (!(tileEntity.isInstanceOf[TileEntityHardMeDrive])) { return } - val inventory: IInventory = (tileEntity.asInstanceOf[TileEntityHardMeDrive]).getInventory + val inventory: IInventory = + (tileEntity.asInstanceOf[TileEntityHardMeDrive]).getInventory var i: Int = 0 while (i < inventory.getSizeInventory) { val item: ItemStack = inventory.getStackInSlot(i) if (item != null && item.stackSize > 0) { - val rx: Float = rand.nextFloat * 0.8F + 0.1F - val ry: Float = rand.nextFloat * 0.8F + 0.1F - val rz: Float = rand.nextFloat * 0.8F + 0.1F - val entityItem: EntityItem = new EntityItem(world, x + rx, y + ry, z + rz, item.copy) + val rx: Float = rand.nextFloat * 0.8f + 0.1f + val ry: Float = rand.nextFloat * 0.8f + 0.1f + val rz: Float = rand.nextFloat * 0.8f + 0.1f + val entityItem: EntityItem = + new EntityItem(world, x + rx, y + ry, z + rz, item.copy) if (item.hasTagCompound) { - entityItem.getEntityItem.setTagCompound(item.getTagCompound.copy.asInstanceOf[NBTTagCompound]) + entityItem.getEntityItem.setTagCompound( + item.getTagCompound.copy.asInstanceOf[NBTTagCompound] + ) } - val factor: Float = 0.05F + val factor: Float = 0.05f entityItem.motionX = rand.nextGaussian * factor - entityItem.motionY = rand.nextGaussian * factor + 0.2F + entityItem.motionY = rand.nextGaussian * factor + 0.2f entityItem.motionZ = rand.nextGaussian * factor world.spawnEntityInWorld(entityItem) item.stackSize = 0 @@ -103,25 +131,52 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro } } - override def onBlockActivated(world: World, x: Int, y: Int, z: Int, player: EntityPlayer, side: Int, p_149727_7_ : Float, p_149727_8_ : Float, p_149727_9_ : Float): Boolean = { + override def onBlockActivated( + world: World, + x: Int, + y: Int, + z: Int, + player: EntityPlayer, + side: Int, + p_149727_7_ : Float, + p_149727_8_ : Float, + p_149727_9_ : Float + ): Boolean = { if (world.isRemote) return false val tile: TileEntity = world.getTileEntity(x, y, z) - if (tile.isInstanceOf[TileEntityHardMeDrive]) if (!PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (tile.asInstanceOf[TileEntityHardMeDrive]).getGridNode(ForgeDirection.UNKNOWN))) return false + if (tile.isInstanceOf[TileEntityHardMeDrive]) + if ( + !PermissionUtil.hasPermission( + player, + SecurityPermissions.BUILD, + (tile + .asInstanceOf[TileEntityHardMeDrive]) + .getGridNode(ForgeDirection.UNKNOWN) + ) + ) return false val current: ItemStack = player.inventory.getCurrentItem if (player.isSneaking && current != null) { try { - if (current.getItem.isInstanceOf[IToolWrench] && (current.getItem.asInstanceOf[IToolWrench]).canWrench(player, x, y, z)) { + if ( + current.getItem.isInstanceOf[IToolWrench] && (current.getItem + .asInstanceOf[IToolWrench]) + .canWrench(player, x, y, z) + ) { dropBlockAsItem(world, x, y, z, new ItemStack(this)) world.setBlockToAir(x, y, z) - (current.getItem.asInstanceOf[IToolWrench]).wrenchUsed(player, x, y, z) + (current.getItem + .asInstanceOf[IToolWrench]) + .wrenchUsed(player, x, y, z) return true } + } catch { + case e: Throwable => {} } - catch { - case e: Throwable => { - } - } - if (current.getItem.isInstanceOf[IAEWrench] && (current.getItem.asInstanceOf[IAEWrench]).canWrench(current, player, x, y, z)) { + if ( + current.getItem.isInstanceOf[IAEWrench] && (current.getItem + .asInstanceOf[IAEWrench]) + .canWrench(current, player, x, y, z) + ) { dropBlockAsItem(world, x, y, z, new ItemStack(this)) world.setBlockToAir(x, y, z) return true @@ -131,58 +186,82 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro return true } - override def onBlockPlacedBy(world: World, x: Int, y: Int, z: Int, entity: EntityLivingBase, stack: ItemStack) { + override def onBlockPlacedBy( + world: World, + x: Int, + y: Int, + z: Int, + entity: EntityLivingBase, + stack: ItemStack + ) { super.onBlockPlacedBy(world, x, y, z, entity, stack); - val l = MathHelper.floor_double(entity.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; + val l = + MathHelper.floor_double(entity.rotationYaw * 4.0f / 360.0f + 0.5d) & 3; - if (!entity.isSneaking()) - { - if (l == 0) - { + if (!entity.isSneaking()) { + if (l == 0) { world.setBlockMetadataWithNotify(x, y, z, 2, 2); } - if (l == 1) - { + if (l == 1) { world.setBlockMetadataWithNotify(x, y, z, 5, 2); } - if (l == 2) - { + if (l == 2) { world.setBlockMetadataWithNotify(x, y, z, 3, 2); } - if (l == 3) - { + if (l == 3) { world.setBlockMetadataWithNotify(x, y, z, 4, 2); } - } else - { - if (l == 0) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(2).getOpposite().ordinal(), 2); + } else { + if (l == 0) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(2).getOpposite().ordinal(), + 2 + ); } - if (l == 1) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(5).getOpposite().ordinal(), 2); + if (l == 1) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(5).getOpposite().ordinal(), + 2 + ); } - if (l == 2) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(3).getOpposite().ordinal(), 2); + if (l == 2) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(3).getOpposite().ordinal(), + 2 + ); } - if (l == 3) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(4).getOpposite().ordinal(), 2); + if (l == 3) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(4).getOpposite().ordinal(), + 2 + ); } } if (world.isRemote) return val tile: TileEntity = world.getTileEntity(x, y, z) if (tile != null) { if (tile.isInstanceOf[TileEntityHardMeDrive]) { - val node: IGridNode = (tile.asInstanceOf[TileEntityHardMeDrive]).getGridNode(ForgeDirection.UNKNOWN) + val node: IGridNode = (tile + .asInstanceOf[TileEntityHardMeDrive]) + .getGridNode(ForgeDirection.UNKNOWN) if (entity != null && entity.isInstanceOf[EntityPlayer]) { val player: EntityPlayer = entity.asInstanceOf[EntityPlayer] node.setPlayerID(AEApi.instance.registries.players.getID(player)) @@ -192,12 +271,20 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro } } - override def onBlockPreDestroy(world: World, x: Int, y: Int, z: Int, meta: Int) { + override def onBlockPreDestroy( + world: World, + x: Int, + y: Int, + z: Int, + meta: Int + ) { if (world.isRemote) return val tile: TileEntity = world.getTileEntity(x, y, z) if (tile != null) { if (tile.isInstanceOf[TileEntityHardMeDrive]) { - val node: IGridNode = (tile.asInstanceOf[TileEntityHardMeDrive]).getGridNode(ForgeDirection.UNKNOWN) + val node: IGridNode = (tile + .asInstanceOf[TileEntityHardMeDrive]) + .getGridNode(ForgeDirection.UNKNOWN) if (node != null) { node.destroy } @@ -207,11 +294,11 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro @SideOnly(Side.CLIENT) override def getIcon(side: Int, metadata: Int) = { - if(side == metadata) + if (side == metadata) frontIcon - else if(side == 0) + else if (side == 0) bottomIcon - else if(side == 1) + else if (side == 1) topIcon else sideIcon @@ -225,6 +312,6 @@ object BlockHardMEDrive extends BlockEC(net.minecraft.block.material.Material.ro topIcon = register.registerIcon("extracells:machine.top"); } - override def getRenderType : Int = RendererHardMEDrive.getRenderId + override def getRenderType: Int = RendererHardMEDrive.getRenderId } diff --git a/src/main/scala/extracells/block/BlockVibrationChamberFluid.java b/src/main/scala/extracells/block/BlockVibrationChamberFluid.java index 7b220736e..b22796716 100644 --- a/src/main/scala/extracells/block/BlockVibrationChamberFluid.java +++ b/src/main/scala/extracells/block/BlockVibrationChamberFluid.java @@ -1,13 +1,5 @@ package extracells.block; -import appeng.api.AEApi; -import appeng.api.networking.IGridNode; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import extracells.container.ContainerVibrationChamberFluid; -import extracells.gui.GuiVibrationChamberFluid; -import extracells.network.GuiHandler; -import extracells.tileentity.TileEntityVibrationChamberFluid; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; @@ -20,18 +12,27 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import appeng.api.AEApi; +import appeng.api.networking.IGridNode; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.container.ContainerVibrationChamberFluid; +import extracells.gui.GuiVibrationChamberFluid; +import extracells.network.GuiHandler; +import extracells.tileentity.TileEntityVibrationChamberFluid; + public class BlockVibrationChamberFluid extends BlockEC implements TGuiBlock { private IIcon[] icons = new IIcon[3]; - public BlockVibrationChamberFluid(){ + public BlockVibrationChamberFluid() { super(Material.iron, 2.0F, 10.0F); } @Override - public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float p_149727_7_, float p_149727_8_, float p_149727_9_) { - if (world.isRemote) - return false; + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float p_149727_7_, + float p_149727_8_, float p_149727_9_) { + if (world.isRemote) return false; GuiHandler.launchGui(0, player, world, x, y, z); return true; } @@ -52,24 +53,20 @@ public void registerBlockIcons(IIconRegister IIconRegister) { @SideOnly(Side.CLIENT) @Override public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side) { - if(side == world.getBlockMetadata(x, y, z)){ - TileEntity tile = world.getTileEntity(x,y, z); - if(!(tile instanceof TileEntityVibrationChamberFluid)) - return icons[0]; + if (side == world.getBlockMetadata(x, y, z)) { + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof TileEntityVibrationChamberFluid)) return icons[0]; TileEntityVibrationChamberFluid chamberFluid = (TileEntityVibrationChamberFluid) tile; if (chamberFluid.getBurnTime() > 0 && chamberFluid.getBurnTime() < (chamberFluid.getBurnTimeTotal())) return icons[2]; - else - return icons[1]; - }else - return icons[0]; + else return icons[1]; + } else return icons[0]; } @SideOnly(Side.CLIENT) @Override - public IIcon getIcon(int side, int meta){ - switch (side) - { + public IIcon getIcon(int side, int meta) { + switch (side) { case 4: return icons[1]; default: @@ -79,85 +76,91 @@ public IIcon getIcon(int side, int meta){ @SideOnly(Side.CLIENT) @Override - public Object getClientGuiElement(EntityPlayer player, World world, int x, int y, int z){ + public Object getClientGuiElement(EntityPlayer player, World world, int x, int y, int z) { TileEntity tileEntity = world.getTileEntity(x, y, z); - if(tileEntity != null && tileEntity instanceof TileEntityVibrationChamberFluid) - return new GuiVibrationChamberFluid(player, (TileEntityVibrationChamberFluid)tileEntity); + if (tileEntity != null && tileEntity instanceof TileEntityVibrationChamberFluid) + return new GuiVibrationChamberFluid(player, (TileEntityVibrationChamberFluid) tileEntity); return null; } @Override - public Object getServerGuiElement(EntityPlayer player, World world, int x, int y, int z){ + public Object getServerGuiElement(EntityPlayer player, World world, int x, int y, int z) { TileEntity tileEntity = world.getTileEntity(x, y, z); - if(tileEntity != null && tileEntity instanceof TileEntityVibrationChamberFluid) - return new ContainerVibrationChamberFluid(player.inventory, (TileEntityVibrationChamberFluid)tileEntity); + if (tileEntity != null && tileEntity instanceof TileEntityVibrationChamberFluid) + return new ContainerVibrationChamberFluid(player.inventory, (TileEntityVibrationChamberFluid) tileEntity); return null; } @Override public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack) { super.onBlockPlacedBy(world, x, y, z, entity, stack); - if(world == null) - return; + if (world == null) return; - if(entity != null){ + if (entity != null) { int l = MathHelper.floor_double(entity.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; - if (!entity.isSneaking()) - { - if (l == 0) - { + if (!entity.isSneaking()) { + if (l == 0) { world.setBlockMetadataWithNotify(x, y, z, 2, 2); } - if (l == 1) - { + if (l == 1) { world.setBlockMetadataWithNotify(x, y, z, 5, 2); } - if (l == 2) - { + if (l == 2) { world.setBlockMetadataWithNotify(x, y, z, 3, 2); } - if (l == 3) - { + if (l == 3) { world.setBlockMetadataWithNotify(x, y, z, 4, 2); } - } else - { - if (l == 0) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(2).getOpposite().ordinal(), 2); + } else { + if (l == 0) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(2).getOpposite().ordinal(), + 2); } - if (l == 1) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(5).getOpposite().ordinal(), 2); + if (l == 1) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(5).getOpposite().ordinal(), + 2); } - if (l == 2) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(3).getOpposite().ordinal(), 2); + if (l == 2) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(3).getOpposite().ordinal(), + 2); } - if (l == 3) - { - world.setBlockMetadataWithNotify(x, y, z, ForgeDirection.getOrientation(4).getOpposite().ordinal(), 2); + if (l == 3) { + world.setBlockMetadataWithNotify( + x, + y, + z, + ForgeDirection.getOrientation(4).getOpposite().ordinal(), + 2); } } - }else - world.setBlockMetadataWithNotify(x, y, z, 2, 2); + } else world.setBlockMetadataWithNotify(x, y, z, 2, 2); - if (world.isRemote) - return; + if (world.isRemote) return; TileEntity tile = world.getTileEntity(x, y, z); if (tile != null) { if (tile instanceof TileEntityVibrationChamberFluid) { IGridNode node = ((TileEntityVibrationChamberFluid) tile).getGridNodeWithoutUpdate(); if (entity != null && entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) entity; - node.setPlayerID(AEApi.instance().registries().players() - .getID(player)); + node.setPlayerID(AEApi.instance().registries().players().getID(player)); } node.updateState(); } @@ -166,8 +169,7 @@ public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase e @Override public void onBlockPreDestroy(World world, int x, int y, int z, int meta) { - if (world.isRemote) - return; + if (world.isRemote) return; TileEntity tile = world.getTileEntity(x, y, z); if (tile != null) { if (tile instanceof TileEntityVibrationChamberFluid) { @@ -178,5 +180,4 @@ public void onBlockPreDestroy(World world, int x, int y, int z, int meta) { } } } - } diff --git a/src/main/scala/extracells/block/BlockWalrus.java b/src/main/scala/extracells/block/BlockWalrus.java index 9589d1a86..4be69cb0d 100644 --- a/src/main/scala/extracells/block/BlockWalrus.java +++ b/src/main/scala/extracells/block/BlockWalrus.java @@ -1,6 +1,5 @@ package extracells.block; -import extracells.tileentity.TileEntityWalrus; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; @@ -10,80 +9,78 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; +import extracells.tileentity.TileEntityWalrus; + public class BlockWalrus extends BlockEC { - public BlockWalrus() { - super(Material.clay, 2.0F, 10.0F); - } + public BlockWalrus() { + super(Material.clay, 2.0F, 10.0F); + } - @Override - public TileEntity createNewTileEntity(World world, int meta) { - return new TileEntityWalrus(); - } + @Override + public TileEntity createNewTileEntity(World world, int meta) { + return new TileEntityWalrus(); + } - @Override - public int getRenderType() { - return -1; - } + @Override + public int getRenderType() { + return -1; + } - @Override - public String getUnlocalizedName() { - return super.getUnlocalizedName().replace("tile.", ""); - } + @Override + public String getUnlocalizedName() { + return super.getUnlocalizedName().replace("tile.", ""); + } - @Override - public boolean isOpaqueCube() { - return false; - } + @Override + public boolean isOpaqueCube() { + return false; + } - @Override - public void onBlockPlacedBy(World world, int x, int y, int z, - EntityLivingBase player, ItemStack itemstack) { - int l = MathHelper - .floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack itemstack) { + int l = MathHelper.floor_double(player.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; - if (l == 0) { - world.setBlockMetadataWithNotify(x, y, z, 2, 2); - } + if (l == 0) { + world.setBlockMetadataWithNotify(x, y, z, 2, 2); + } - if (l == 1) { - world.setBlockMetadataWithNotify(x, y, z, 5, 2); - } + if (l == 1) { + world.setBlockMetadataWithNotify(x, y, z, 5, 2); + } - if (l == 2) { - world.setBlockMetadataWithNotify(x, y, z, 3, 2); - } + if (l == 2) { + world.setBlockMetadataWithNotify(x, y, z, 3, 2); + } - if (l == 3) { - world.setBlockMetadataWithNotify(x, y, z, 4, 2); - } - } + if (l == 3) { + world.setBlockMetadataWithNotify(x, y, z, 4, 2); + } + } - @Override - public boolean renderAsNormalBlock() { - return false; - } + @Override + public boolean renderAsNormalBlock() { + return false; + } - @Override - public void setBlockBoundsBasedOnState(IBlockAccess blockAccess, int x, - int y, int z) { - switch (ForgeDirection.getOrientation(blockAccess.getBlockMetadata(x, - y, z))) { - case NORTH: - setBlockBounds(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 1.0F); - break; - case EAST: - setBlockBounds(0.0F, 0.0F, 0.0F, 2.0F, 1.0F, 1.0F); - break; - case SOUTH: - setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 2.0F); - break; - case WEST: - setBlockBounds(-1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - break; - default: - setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - break; - } - } + @Override + public void setBlockBoundsBasedOnState(IBlockAccess blockAccess, int x, int y, int z) { + switch (ForgeDirection.getOrientation(blockAccess.getBlockMetadata(x, y, z))) { + case NORTH: + setBlockBounds(0.0F, 0.0F, -1.0F, 1.0F, 1.0F, 1.0F); + break; + case EAST: + setBlockBounds(0.0F, 0.0F, 0.0F, 2.0F, 1.0F, 1.0F); + break; + case SOUTH: + setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 2.0F); + break; + case WEST: + setBlockBounds(-1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + default: + setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + } + } } diff --git a/src/main/scala/extracells/block/ECBaseBlock.java b/src/main/scala/extracells/block/ECBaseBlock.java index e30954593..edef3692f 100644 --- a/src/main/scala/extracells/block/ECBaseBlock.java +++ b/src/main/scala/extracells/block/ECBaseBlock.java @@ -1,18 +1,7 @@ package extracells.block; -import appeng.api.AEApi; -import appeng.api.config.SecurityPermissions; -import appeng.api.implementations.items.IAEWrench; -import appeng.api.networking.IGridNode; -import buildcraft.api.tools.IToolWrench; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import extracells.api.IECTileEntity; -import extracells.network.GuiHandler; -import extracells.tileentity.IListenerTile; -import extracells.tileentity.TileEntityFluidFiller; -import extracells.tileentity.TileEntityFluidInterface; -import extracells.util.PermissionUtil; +import java.util.Random; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; @@ -27,205 +16,192 @@ import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; -import java.util.Random; +import appeng.api.AEApi; +import appeng.api.config.SecurityPermissions; +import appeng.api.implementations.items.IAEWrench; +import appeng.api.networking.IGridNode; +import buildcraft.api.tools.IToolWrench; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.api.IECTileEntity; +import extracells.network.GuiHandler; +import extracells.tileentity.IListenerTile; +import extracells.tileentity.TileEntityFluidFiller; +import extracells.tileentity.TileEntityFluidInterface; +import extracells.util.PermissionUtil; public class ECBaseBlock extends BlockEC { - private IIcon[] icons = new IIcon[2]; - - public ECBaseBlock() { - super(Material.iron, 2.0F, 10.0F); - } - - @Override - public void breakBlock(World world, int x, int y, int z, Block par5, - int par6) { - dropPatter(world, x, y, z); - super.breakBlock(world, x, y, z, par5, par6); - } - - @Override - public TileEntity createNewTileEntity(World world, int meta) { - switch (meta) { - case 0: - return new TileEntityFluidInterface(); - case 1: - return new TileEntityFluidFiller(); - default: - return null; - } - - } - - @Override - public int damageDropped(int p_149692_1_) { - return p_149692_1_; - } - - private void dropPatter(World world, int x, int y, int z) { - Random rand = new Random(); - - TileEntity tileEntity = world.getTileEntity(x, y, z); - if (!(tileEntity instanceof TileEntityFluidInterface)) { - return; - } - IInventory inventory = ((TileEntityFluidInterface) tileEntity).inventory; - - for (int i = 0; i < inventory.getSizeInventory(); i++) { - ItemStack item = inventory.getStackInSlot(i); - - if (item != null && item.stackSize > 0) { - float rx = rand.nextFloat() * 0.8F + 0.1F; - float ry = rand.nextFloat() * 0.8F + 0.1F; - float rz = rand.nextFloat() * 0.8F + 0.1F; - - EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z - + rz, item.copy()); - - if (item.hasTagCompound()) { - entityItem.getEntityItem().setTagCompound( - (NBTTagCompound) item.getTagCompound().copy()); - } - - float factor = 0.05F; - entityItem.motionX = rand.nextGaussian() * factor; - entityItem.motionY = rand.nextGaussian() * factor + 0.2F; - entityItem.motionZ = rand.nextGaussian() * factor; - world.spawnEntityInWorld(entityItem); - item.stackSize = 0; - } - } - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getIcon(int side, int meta) { - if (meta >= 0 && meta + 1 <= this.icons.length) { - return this.icons[meta]; - } - return null; - } - - @Override - public boolean onBlockActivated(World world, int x, int y, int z, - EntityPlayer player, int side, float p_149727_7_, - float p_149727_8_, float p_149727_9_) { - if (world.isRemote) - return false; - Random rand = new Random(); - switch (world.getBlockMetadata(x, y, z)) { - case 0: - case 1: - TileEntity tile = world.getTileEntity(x, y, z); - if (tile instanceof IECTileEntity) - if (!PermissionUtil.hasPermission(player, - SecurityPermissions.BUILD, ((IECTileEntity) tile) - .getGridNode(ForgeDirection.UNKNOWN))) - return false; - ItemStack current = player.getCurrentEquippedItem(); - if (player.isSneaking() && current != null) { - try { - if (current.getItem() instanceof IToolWrench - && ((IToolWrench) current.getItem()).canWrench( - player, x, y, z)) { - ItemStack block = new ItemStack(this, 1, - world.getBlockMetadata(x, y, z)); - if (tile != null - && tile instanceof TileEntityFluidInterface) { - block.setTagCompound(((TileEntityFluidInterface) tile) - .writeFilter(new NBTTagCompound())); - } - dropBlockAsItem(world, x, y, z, block); - world.setBlockToAir(x, y, z); - ((IToolWrench) current.getItem()).wrenchUsed(player, x, - y, z); - return true; - } - } catch (Throwable e) { - // No IToolWrench - } - if (current.getItem() instanceof IAEWrench - && ((IAEWrench) current.getItem()).canWrench(current, - player, x, y, z)) { - ItemStack block = new ItemStack(this, 1, - world.getBlockMetadata(x, y, z));; - if (tile != null - && tile instanceof TileEntityFluidInterface) { - block.setTagCompound(((TileEntityFluidInterface) tile) - .writeFilter(new NBTTagCompound())); - } - dropBlockAsItem(world, x, y, z, block); - world.setBlockToAir(x, y, z); - return true; - } - - } - GuiHandler.launchGui(0, player, world, x, y, z); - return true; - default: - return false; - } - } - - @Override - public void onBlockPlacedBy(World world, int x, int y, int z, - EntityLivingBase entity, ItemStack stack) { - if (world.isRemote) - return; - switch (world.getBlockMetadata(x, y, z)) { - case 0: - case 1: - TileEntity tile = world.getTileEntity(x, y, z); - if (tile != null) { - if (tile instanceof IECTileEntity) { - IGridNode node = ((IECTileEntity) tile) - .getGridNode(ForgeDirection.UNKNOWN); - if (entity != null && entity instanceof EntityPlayer) { - EntityPlayer player = (EntityPlayer) entity; - node.setPlayerID(AEApi.instance().registries() - .players().getID(player)); - } - node.updateState(); - } - if (tile instanceof IListenerTile) - ((IListenerTile) tile).registerListener(); - } - return; - default: - return; - } - } - - @Override - public void onBlockPreDestroy(World world, int x, int y, int z, int meta) { - if (world.isRemote) - return; - switch (meta) { - case 0: - case 1: - TileEntity tile = world.getTileEntity(x, y, z); - if (tile != null) { - if (tile instanceof IECTileEntity) { - IGridNode node = ((IECTileEntity) tile) - .getGridNode(ForgeDirection.UNKNOWN); - if (node != null) { - node.destroy(); - } - } - if (tile instanceof IListenerTile) - ((IListenerTile) tile).removeListener(); - } - return; - default: - return; - } - - } - - @Override - @SideOnly(Side.CLIENT) - public void registerBlockIcons(IIconRegister register) { - this.icons[0] = register.registerIcon("extracells:fluid.interface"); - this.icons[1] = register.registerIcon("extracells:fluid.filler"); - } + private IIcon[] icons = new IIcon[2]; + + public ECBaseBlock() { + super(Material.iron, 2.0F, 10.0F); + } + + @Override + public void breakBlock(World world, int x, int y, int z, Block par5, int par6) { + dropPatter(world, x, y, z); + super.breakBlock(world, x, y, z, par5, par6); + } + + @Override + public TileEntity createNewTileEntity(World world, int meta) { + switch (meta) { + case 0: + return new TileEntityFluidInterface(); + case 1: + return new TileEntityFluidFiller(); + default: + return null; + } + } + + @Override + public int damageDropped(int p_149692_1_) { + return p_149692_1_; + } + + private void dropPatter(World world, int x, int y, int z) { + Random rand = new Random(); + + TileEntity tileEntity = world.getTileEntity(x, y, z); + if (!(tileEntity instanceof TileEntityFluidInterface)) { + return; + } + IInventory inventory = ((TileEntityFluidInterface) tileEntity).inventory; + + for (int i = 0; i < inventory.getSizeInventory(); i++) { + ItemStack item = inventory.getStackInSlot(i); + + if (item != null && item.stackSize > 0) { + float rx = rand.nextFloat() * 0.8F + 0.1F; + float ry = rand.nextFloat() * 0.8F + 0.1F; + float rz = rand.nextFloat() * 0.8F + 0.1F; + + EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, item.copy()); + + if (item.hasTagCompound()) { + entityItem.getEntityItem().setTagCompound((NBTTagCompound) item.getTagCompound().copy()); + } + + float factor = 0.05F; + entityItem.motionX = rand.nextGaussian() * factor; + entityItem.motionY = rand.nextGaussian() * factor + 0.2F; + entityItem.motionZ = rand.nextGaussian() * factor; + world.spawnEntityInWorld(entityItem); + item.stackSize = 0; + } + } + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIcon(int side, int meta) { + if (meta >= 0 && meta + 1 <= this.icons.length) { + return this.icons[meta]; + } + return null; + } + + @Override + public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float p_149727_7_, + float p_149727_8_, float p_149727_9_) { + switch (world.getBlockMetadata(x, y, z)) { + case 0: + case 1: + if (world.isRemote) return true; + TileEntity tile = world.getTileEntity(x, y, z); + if (tile instanceof IECTileEntity) if (!PermissionUtil.hasPermission( + player, + SecurityPermissions.BUILD, + ((IECTileEntity) tile).getGridNode(ForgeDirection.UNKNOWN))) + return false; + ItemStack current = player.getCurrentEquippedItem(); + if (player.isSneaking() && current != null) { + try { + if (current.getItem() instanceof IToolWrench + && ((IToolWrench) current.getItem()).canWrench(player, x, y, z)) { + ItemStack block = new ItemStack(this, 1, world.getBlockMetadata(x, y, z)); + if (tile != null && tile instanceof TileEntityFluidInterface) { + block.setTagCompound( + ((TileEntityFluidInterface) tile).writeFilter(new NBTTagCompound())); + } + dropBlockAsItem(world, x, y, z, block); + world.setBlockToAir(x, y, z); + ((IToolWrench) current.getItem()).wrenchUsed(player, x, y, z); + return true; + } + } catch (Throwable e) { + // No IToolWrench + } + if (current.getItem() instanceof IAEWrench + && ((IAEWrench) current.getItem()).canWrench(current, player, x, y, z)) { + ItemStack block = new ItemStack(this, 1, world.getBlockMetadata(x, y, z));; + if (tile != null && tile instanceof TileEntityFluidInterface) { + block.setTagCompound(((TileEntityFluidInterface) tile).writeFilter(new NBTTagCompound())); + } + dropBlockAsItem(world, x, y, z, block); + world.setBlockToAir(x, y, z); + return true; + } + } + GuiHandler.launchGui(0, player, world, x, y, z); + return true; + default: + return false; + } + } + + @Override + public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack stack) { + if (world.isRemote) return; + switch (world.getBlockMetadata(x, y, z)) { + case 0: + case 1: + TileEntity tile = world.getTileEntity(x, y, z); + if (tile != null) { + if (tile instanceof IECTileEntity) { + IGridNode node = ((IECTileEntity) tile).getGridNode(ForgeDirection.UNKNOWN); + if (entity != null && entity instanceof EntityPlayer) { + EntityPlayer player = (EntityPlayer) entity; + node.setPlayerID(AEApi.instance().registries().players().getID(player)); + } + node.updateState(); + } + if (tile instanceof IListenerTile) ((IListenerTile) tile).registerListener(); + } + return; + default: + return; + } + } + + @Override + public void onBlockPreDestroy(World world, int x, int y, int z, int meta) { + if (world.isRemote) return; + switch (meta) { + case 0: + case 1: + TileEntity tile = world.getTileEntity(x, y, z); + if (tile != null) { + if (tile instanceof IECTileEntity) { + IGridNode node = ((IECTileEntity) tile).getGridNode(ForgeDirection.UNKNOWN); + if (node != null) { + node.destroy(); + } + } + if (tile instanceof IListenerTile) ((IListenerTile) tile).removeListener(); + } + return; + default: + return; + } + } + + @Override + @SideOnly(Side.CLIENT) + public void registerBlockIcons(IIconRegister register) { + this.icons[0] = register.registerIcon("extracells:fluid.interface"); + this.icons[1] = register.registerIcon("extracells:fluid.filler"); + } } diff --git a/src/main/scala/extracells/block/TGuiBlock.scala b/src/main/scala/extracells/block/TGuiBlock.scala index 2e2e54fd4..c28e2b4e2 100644 --- a/src/main/scala/extracells/block/TGuiBlock.scala +++ b/src/main/scala/extracells/block/TGuiBlock.scala @@ -4,12 +4,23 @@ import cpw.mods.fml.relauncher.{Side, SideOnly} import net.minecraft.entity.player.EntityPlayer import net.minecraft.world.World - trait TGuiBlock { @SideOnly(Side.CLIENT) - def getClientGuiElement(player: EntityPlayer, world: World, x: Int, y: Int, z: Int) : Any = null + def getClientGuiElement( + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = null - def getServerGuiElement(player: EntityPlayer, world: World, x: Int, y: Int, z: Int): Any = null + def getServerGuiElement( + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = null } diff --git a/src/main/scala/extracells/container/ContainerBusFluidIO.java b/src/main/scala/extracells/container/ContainerBusFluidIO.java index 5dc62cf72..c5c6754ce 100644 --- a/src/main/scala/extracells/container/ContainerBusFluidIO.java +++ b/src/main/scala/extracells/container/ContainerBusFluidIO.java @@ -1,5 +1,11 @@ package extracells.container; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + import appeng.api.AEApi; import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.INetworkTool; @@ -8,92 +14,88 @@ import extracells.container.slot.SlotRespective; import extracells.gui.GuiBusFluidIO; import extracells.part.PartFluidIO; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; public class ContainerBusFluidIO extends Container { - private PartFluidIO part; - private GuiBusFluidIO guiBusFluidIO; - - public ContainerBusFluidIO(PartFluidIO part, EntityPlayer player) { - this.part = part; - for (int i = 0; i < 4; i++) - addSlotToContainer(new SlotRespective(part.getUpgradeInventory(), i, 187, i * 18 + 8)); - bindPlayerInventory(player.inventory); - - for (int i = 0; i < player.inventory.getSizeInventory(); i++) { - ItemStack stack = player.inventory.getStackInSlot(i); - if (stack != null && AEApi.instance().definitions().items().networkTool().isSameAs(stack)) { - DimensionalCoord coord = part.getHost().getLocation(); - IGuiItem guiItem = (IGuiItem) stack.getItem(); - INetworkTool networkTool = (INetworkTool) guiItem.getGuiObject(stack, coord.getWorld(), coord.x, coord.y, coord.z); - for (int j = 0; j < 3; j++) { - for (int k = 0; k < 3; k++) { - addSlotToContainer(new SlotNetworkTool(networkTool, j + k * 3, 187 + k * 18, j * 18 + 102)); - } - } - return; - } - } - } - - protected void bindPlayerInventory(IInventory inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 102)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 160)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return part.isValid(); - } - - @Override - protected void retrySlotClick(int par1, int par2, boolean par3, EntityPlayer par4EntityPlayer) { - // NOPE - } - - public void setGui(GuiBusFluidIO _guiBusFluidIO) { - this.guiBusFluidIO = _guiBusFluidIO; - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - if (this.guiBusFluidIO != null && this.guiBusFluidIO.shiftClick(getSlot(slotnumber).getStack())) - return ((Slot) this.inventorySlots.get(slotnumber)).getStack(); - - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (slotnumber < 36) { - if (!mergeItemStack(itemstack1, 36, this.inventorySlots.size(), - true)) { - return null; - } - } else if (!mergeItemStack(itemstack1, 0, 36, false)) { - return itemstack1; - } - - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } - - return itemstack; - } + + private PartFluidIO part; + private GuiBusFluidIO guiBusFluidIO; + + public ContainerBusFluidIO(PartFluidIO part, EntityPlayer player) { + this.part = part; + for (int i = 0; i < 4; i++) + addSlotToContainer(new SlotRespective(part.getUpgradeInventory(), i, 187, i * 18 + 8)); + bindPlayerInventory(player.inventory); + + for (int i = 0; i < player.inventory.getSizeInventory(); i++) { + ItemStack stack = player.inventory.getStackInSlot(i); + if (stack != null && AEApi.instance().definitions().items().networkTool().isSameAs(stack)) { + DimensionalCoord coord = part.getHost().getLocation(); + IGuiItem guiItem = (IGuiItem) stack.getItem(); + INetworkTool networkTool = (INetworkTool) guiItem + .getGuiObject(stack, coord.getWorld(), coord.x, coord.y, coord.z); + for (int j = 0; j < 3; j++) { + for (int k = 0; k < 3; k++) { + addSlotToContainer(new SlotNetworkTool(networkTool, j + k * 3, 187 + k * 18, j * 18 + 102)); + } + } + return; + } + } + } + + protected void bindPlayerInventory(IInventory inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 102)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 160)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return part.isValid(); + } + + @Override + protected void retrySlotClick(int par1, int par2, boolean par3, EntityPlayer par4EntityPlayer) { + // NOPE + } + + public void setGui(GuiBusFluidIO _guiBusFluidIO) { + this.guiBusFluidIO = _guiBusFluidIO; + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + if (this.guiBusFluidIO != null && this.guiBusFluidIO.shiftClick(getSlot(slotnumber).getStack())) + return ((Slot) this.inventorySlots.get(slotnumber)).getStack(); + + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (slotnumber < 36) { + if (!mergeItemStack(itemstack1, 36, this.inventorySlots.size(), true)) { + return null; + } + } else if (!mergeItemStack(itemstack1, 0, 36, false)) { + return itemstack1; + } + + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } + + return itemstack; + } } diff --git a/src/main/scala/extracells/container/ContainerBusFluidStorage.java b/src/main/scala/extracells/container/ContainerBusFluidStorage.java index a66ed327a..c7a3bfa84 100644 --- a/src/main/scala/extracells/container/ContainerBusFluidStorage.java +++ b/src/main/scala/extracells/container/ContainerBusFluidStorage.java @@ -1,5 +1,11 @@ package extracells.container; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + import appeng.api.AEApi; import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.INetworkTool; @@ -8,88 +14,83 @@ import extracells.container.slot.SlotRespective; import extracells.gui.GuiBusFluidStorage; import extracells.part.PartFluidStorage; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; public class ContainerBusFluidStorage extends Container { - private GuiBusFluidStorage guiBusFluidStorage; - - public PartFluidStorage part; - - public ContainerBusFluidStorage(PartFluidStorage part, EntityPlayer player) { - - addSlotToContainer(new SlotRespective(part.getUpgradeInventory(), 0, 187, 8)); - this.part = part; - bindPlayerInventory(player.inventory); - - for (int i = 0; i < player.inventory.getSizeInventory(); i++) { - ItemStack stack = player.inventory.getStackInSlot(i); - if (stack != null && AEApi.instance().definitions().items().networkTool().isSameAs(stack)) { - DimensionalCoord coord = part.getHost().getLocation(); - IGuiItem guiItem = (IGuiItem) stack.getItem(); - INetworkTool networkTool = (INetworkTool) guiItem.getGuiObject(stack, coord.getWorld(), coord.x, coord.y, coord.z); - for (int j = 0; j < 3; j++) { - for (int k = 0; k < 3; k++) { - addSlotToContainer(new SlotNetworkTool(networkTool, j + k * 3, 187 + k * 18, j * 18 + 102)); - } - } - return; - } - } - } - - protected void bindPlayerInventory(IInventory inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 140)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 198)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return part.isValid(); - } - - public void setGui(GuiBusFluidStorage _guiBusFluidStorage) { - this.guiBusFluidStorage = _guiBusFluidStorage; - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - if (this.guiBusFluidStorage != null) - this.guiBusFluidStorage.shiftClick(getSlot(slotnumber).getStack()); - - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (slotnumber < 36) { - if (!mergeItemStack(itemstack1, 36, this.inventorySlots.size(), true)) { - return null; - } - } else if (!mergeItemStack(itemstack1, 0, 36, false)) { - return null; - } - - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } - - return itemstack; - } + private GuiBusFluidStorage guiBusFluidStorage; + + public PartFluidStorage part; + + public ContainerBusFluidStorage(PartFluidStorage part, EntityPlayer player) { + + addSlotToContainer(new SlotRespective(part.getUpgradeInventory(), 0, 187, 8)); + this.part = part; + bindPlayerInventory(player.inventory); + + for (int i = 0; i < player.inventory.getSizeInventory(); i++) { + ItemStack stack = player.inventory.getStackInSlot(i); + if (stack != null && AEApi.instance().definitions().items().networkTool().isSameAs(stack)) { + DimensionalCoord coord = part.getHost().getLocation(); + IGuiItem guiItem = (IGuiItem) stack.getItem(); + INetworkTool networkTool = (INetworkTool) guiItem + .getGuiObject(stack, coord.getWorld(), coord.x, coord.y, coord.z); + for (int j = 0; j < 3; j++) { + for (int k = 0; k < 3; k++) { + addSlotToContainer(new SlotNetworkTool(networkTool, j + k * 3, 187 + k * 18, j * 18 + 102)); + } + } + return; + } + } + } + + protected void bindPlayerInventory(IInventory inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 153)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 211)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return part.isValid(); + } + + public void setGui(GuiBusFluidStorage _guiBusFluidStorage) { + this.guiBusFluidStorage = _guiBusFluidStorage; + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + if (this.guiBusFluidStorage != null) this.guiBusFluidStorage.shiftClick(getSlot(slotnumber).getStack()); + + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (slotnumber < 36) { + if (!mergeItemStack(itemstack1, 36, this.inventorySlots.size(), true)) { + return null; + } + } else if (!mergeItemStack(itemstack1, 0, 36, false)) { + return null; + } + + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } + + return itemstack; + } } diff --git a/src/main/scala/extracells/container/ContainerDrive.java b/src/main/scala/extracells/container/ContainerDrive.java index a295ad8cd..4bd32d988 100644 --- a/src/main/scala/extracells/container/ContainerDrive.java +++ b/src/main/scala/extracells/container/ContainerDrive.java @@ -1,69 +1,69 @@ package extracells.container; -import extracells.container.slot.SlotRespective; -import extracells.part.PartDrive; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import extracells.container.slot.SlotRespective; +import extracells.part.PartDrive; + public class ContainerDrive extends Container { - PartDrive part; - public ContainerDrive(PartDrive part, EntityPlayer player) { - this.part = part; - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 3; j++) { - addSlotToContainer(new SlotRespective(part.getInventory(), j - + i * 3, 18 + 71 - i * 18, j * 18 - 4)); - } - } - bindPlayerInventory(player.inventory); - } - protected void bindPlayerInventory(IInventory inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 63)); - } - } + PartDrive part; + + public ContainerDrive(PartDrive part, EntityPlayer player) { + this.part = part; + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 3; j++) { + addSlotToContainer(new SlotRespective(part.getInventory(), j + i * 3, 18 + 71 - i * 18, j * 18 - 4)); + } + } + bindPlayerInventory(player.inventory); + } + + protected void bindPlayerInventory(IInventory inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 63)); + } + } - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 121)); - } - } + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 121)); + } + } - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return part.isValid(); - } + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return part.isValid(); + } - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); - if (slotnumber < 36) { - if (!mergeItemStack(itemstack1, 36, this.inventorySlots.size(), - true)) { - return null; - } - } else if (!mergeItemStack(itemstack1, 0, 36, false)) { - return null; - } + if (slotnumber < 36) { + if (!mergeItemStack(itemstack1, 36, this.inventorySlots.size(), true)) { + return null; + } + } else if (!mergeItemStack(itemstack1, 0, 36, false)) { + return null; + } - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } - return itemstack; - } + return itemstack; + } } diff --git a/src/main/scala/extracells/container/ContainerFluidCrafter.java b/src/main/scala/extracells/container/ContainerFluidCrafter.java index 53e4caca9..13d17d85c 100644 --- a/src/main/scala/extracells/container/ContainerFluidCrafter.java +++ b/src/main/scala/extracells/container/ContainerFluidCrafter.java @@ -1,6 +1,5 @@ package extracells.container; -import extracells.container.slot.SlotRespective; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; @@ -8,73 +7,71 @@ import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; +import extracells.container.slot.SlotRespective; + public class ContainerFluidCrafter extends Container { - IInventory tileentity; - public ContainerFluidCrafter(InventoryPlayer player, IInventory tileentity) { - this.tileentity = tileentity; - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 3; j++) { - addSlotToContainer(new SlotRespective(tileentity, j + i * 3, - 62 + j * 18, 17 + i * 18)); - } - } - bindPlayerInventory(player); - } + IInventory tileentity; + + public ContainerFluidCrafter(InventoryPlayer player, IInventory tileentity) { + this.tileentity = tileentity; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + addSlotToContainer(new SlotRespective(tileentity, j + i * 3, 62 + j * 18, 17 + i * 18)); + } + } + bindPlayerInventory(player); + } - protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 84)); - } - } + protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 84)); + } + } - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); - } - } + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); + } + } - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.tileentity.isUseableByPlayer(entityplayer); + } - @Override - public void onContainerClosed(EntityPlayer entityplayer) { - super.onContainerClosed(entityplayer); - } + @Override + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + } - @Override - protected void retrySlotClick(int par1, int par2, boolean par3, - EntityPlayer par4EntityPlayer) { - // DON'T DO ANYTHING, YOU SHITTY METHOD! - } + @Override + protected void retrySlotClick(int par1, int par2, boolean par3, EntityPlayer par4EntityPlayer) { + // DON'T DO ANYTHING, YOU SHITTY METHOD! + } - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - if (this.tileentity.isItemValidForSlot(0, itemstack1)) { - if (slotnumber < 10) { - if (!mergeItemStack(itemstack1, 10, 36, false)) - return null; - } else if (slotnumber >= 10 && slotnumber <= 36) { - if (!mergeItemStack(itemstack1, 0, 1, false)) - return null; - } - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } else { - return null; - } - } - return itemstack; - } + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + if (this.tileentity.isItemValidForSlot(0, itemstack1)) { + if (slotnumber < 10) { + if (!mergeItemStack(itemstack1, 10, 36, false)) return null; + } else if (slotnumber >= 10 && slotnumber <= 36) { + if (!mergeItemStack(itemstack1, 0, 1, false)) return null; + } + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } else { + return null; + } + } + return itemstack; + } } diff --git a/src/main/scala/extracells/container/ContainerFluidEmitter.java b/src/main/scala/extracells/container/ContainerFluidEmitter.java index 7f9982b6d..64931be87 100644 --- a/src/main/scala/extracells/container/ContainerFluidEmitter.java +++ b/src/main/scala/extracells/container/ContainerFluidEmitter.java @@ -1,6 +1,5 @@ package extracells.container; -import extracells.part.PartFluidLevelEmitter; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; @@ -9,52 +8,51 @@ import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; +import extracells.part.PartFluidLevelEmitter; + public class ContainerFluidEmitter extends Container { - PartFluidLevelEmitter part; - EntityPlayer player; - - public ContainerFluidEmitter(PartFluidLevelEmitter _part, - EntityPlayer _player) { - super(); - this.part = _part; - this.player = _player; - bindPlayerInventory(this.player.inventory); - } - - protected void bindPlayerInventory(IInventory inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 84)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - if (slot != null && slot.getHasStack()) { - ItemStack fluidItem = slot.getStack().copy(); - fluidItem.stackSize = 1; - FluidStack fluidStack = FluidContainerRegistry - .getFluidForFilledItem(fluidItem); - if (fluidStack == null) { - return null; - } - this.part.setFluid(0, fluidStack.getFluid(), player); - return null; - } - return null; - } + PartFluidLevelEmitter part; + EntityPlayer player; + + public ContainerFluidEmitter(PartFluidLevelEmitter _part, EntityPlayer _player) { + super(); + this.part = _part; + this.player = _player; + bindPlayerInventory(this.player.inventory); + } + + protected void bindPlayerInventory(IInventory inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 84)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.part.isValid(); + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + if (slot != null && slot.getHasStack()) { + ItemStack fluidItem = slot.getStack().copy(); + fluidItem.stackSize = 1; + FluidStack fluidStack = FluidContainerRegistry.getFluidForFilledItem(fluidItem); + if (fluidStack == null) { + return null; + } + this.part.setFluid(0, fluidStack.getFluid(), player); + return null; + } + return null; + } } diff --git a/src/main/scala/extracells/container/ContainerFluidFiller.java b/src/main/scala/extracells/container/ContainerFluidFiller.java index 2d07134a2..6d8c9daf0 100644 --- a/src/main/scala/extracells/container/ContainerFluidFiller.java +++ b/src/main/scala/extracells/container/ContainerFluidFiller.java @@ -1,42 +1,41 @@ package extracells.container; -import extracells.tileentity.TileEntityFluidFiller; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; +import extracells.tileentity.TileEntityFluidFiller; + public class ContainerFluidFiller extends Container { - public TileEntityFluidFiller tileentity; - - public ContainerFluidFiller(InventoryPlayer player, - TileEntityFluidFiller tileentity) { - this.tileentity = tileentity; - - bindPlayerInventory(player); - } - - protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 84)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - @Override - protected void retrySlotClick(int par1, int par2, boolean par3, - EntityPlayer par4EntityPlayer) { - // DON'T DO ANYTHING, YOU SHITTY METHOD! - } + + public TileEntityFluidFiller tileentity; + + public ContainerFluidFiller(InventoryPlayer player, TileEntityFluidFiller tileentity) { + this.tileentity = tileentity; + + bindPlayerInventory(player); + } + + protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 84)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return true; + } + + @Override + protected void retrySlotClick(int par1, int par2, boolean par3, EntityPlayer par4EntityPlayer) { + // DON'T DO ANYTHING, YOU SHITTY METHOD! + } } diff --git a/src/main/scala/extracells/container/ContainerFluidInterface.java b/src/main/scala/extracells/container/ContainerFluidInterface.java index 1744a57e8..fdb3d6fcf 100644 --- a/src/main/scala/extracells/container/ContainerFluidInterface.java +++ b/src/main/scala/extracells/container/ContainerFluidInterface.java @@ -1,12 +1,5 @@ package extracells.container; -import appeng.api.implementations.ICraftingPatternItem; -import extracells.api.IFluidInterface; -import extracells.container.slot.SlotRespective; -import extracells.gui.GuiFluidInterface; -import extracells.network.packet.part.PacketFluidInterface; -import extracells.part.PartFluidInterface; -import extracells.tileentity.TileEntityFluidInterface; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; @@ -16,147 +9,140 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; -public class ContainerFluidInterface extends Container implements - IContainerListener { - public IFluidInterface fluidInterface; - public GuiFluidInterface gui; - EntityPlayer player; - - public ContainerFluidInterface(EntityPlayer player, - IFluidInterface fluidInterface) { - this.player = player; - this.fluidInterface = fluidInterface; - for (int j = 0; j < 9; j++) { - addSlotToContainer(new SlotRespective( - fluidInterface.getPatternInventory(), j, 8 + j * 18, 115)); - } - bindPlayerInventory(player.inventory); - if (fluidInterface instanceof TileEntityFluidInterface) { - ((TileEntityFluidInterface) fluidInterface).registerListener(this); - } else if (fluidInterface instanceof PartFluidInterface) { - ((PartFluidInterface) fluidInterface).registerListener(this); - } - if (fluidInterface instanceof TileEntityFluidInterface) { - ((TileEntityFluidInterface) fluidInterface).doNextUpdate = true; - } else if (fluidInterface instanceof PartFluidInterface) { - ((PartFluidInterface) fluidInterface).doNextUpdate = true; - } - } - - protected void bindPlayerInventory(IInventory inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 149)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 207));// 173 - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - private int getFluidID(ForgeDirection side) { - Fluid fluid = this.fluidInterface.getFilter(side); - if (fluid == null) - return -1; - return fluid.getID(); - } - - @Override - public void onContainerClosed(EntityPlayer player) { - super.onContainerClosed(player); - if (this.fluidInterface instanceof TileEntityFluidInterface) { - ((TileEntityFluidInterface) this.fluidInterface) - .removeListener(this); - } else if (this.fluidInterface instanceof PartFluidInterface) { - ((PartFluidInterface) this.fluidInterface).removeListener(this); - } - } - - @Override - protected void retrySlotClick(int p_75133_1_, int p_75133_2_, - boolean p_75133_3_, EntityPlayer p_75133_4_) { - - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (itemstack.getItem() instanceof ICraftingPatternItem) { - if (slotnumber < 9) { - if (!mergeItemStack(itemstack1, - this.inventorySlots.size() - 9, - this.inventorySlots.size(), false)) { - if (!mergeItemStack(itemstack1, 9, - this.inventorySlots.size() - 9, false)) - return null; - } - } else if (!mergeItemStack(itemstack1, 0, 9, false)) { - return null; - } - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - return itemstack; - } - - if (slotnumber < this.inventorySlots.size() - 9) { - if (!mergeItemStack(itemstack1, this.inventorySlots.size() - 9, - this.inventorySlots.size(), true)) { - return null; - } - } else if (!mergeItemStack(itemstack1, 9, - this.inventorySlots.size() - 9, false)) { - return null; - } - - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } - - return itemstack; - } - - @Override - public void updateContainer() { - new PacketFluidInterface(new FluidStack[] { - this.fluidInterface.getFluidTank( - ForgeDirection.getOrientation(0)).getFluid(), - this.fluidInterface.getFluidTank( - ForgeDirection.getOrientation(1)).getFluid(), - this.fluidInterface.getFluidTank( - ForgeDirection.getOrientation(2)).getFluid(), - this.fluidInterface.getFluidTank( - ForgeDirection.getOrientation(3)).getFluid(), - this.fluidInterface.getFluidTank( - ForgeDirection.getOrientation(4)).getFluid(), - this.fluidInterface.getFluidTank( - ForgeDirection.getOrientation(5)).getFluid() }, - new Integer[] { getFluidID(ForgeDirection.getOrientation(0)), - getFluidID(ForgeDirection.getOrientation(1)), - getFluidID(ForgeDirection.getOrientation(2)), - getFluidID(ForgeDirection.getOrientation(3)), - getFluidID(ForgeDirection.getOrientation(4)), - getFluidID(ForgeDirection.getOrientation(5)) }, - this.player).sendPacketToPlayer(this.player); - - } +import appeng.api.implementations.ICraftingPatternItem; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.api.IFluidInterface; +import extracells.container.slot.SlotRespective; +import extracells.gui.GuiFluidInterface; +import extracells.network.packet.part.PacketFluidInterface; +import extracells.part.PartFluidInterface; +import extracells.tileentity.TileEntityFluidInterface; +public class ContainerFluidInterface extends Container implements IContainerListener { + + public IFluidInterface fluidInterface; + + @SideOnly(Side.CLIENT) + public GuiFluidInterface gui; + + EntityPlayer player; + + public ContainerFluidInterface(EntityPlayer player, IFluidInterface fluidInterface) { + this.player = player; + this.fluidInterface = fluidInterface; + for (int j = 0; j < 9; j++) { + addSlotToContainer(new SlotRespective(fluidInterface.getPatternInventory(), j, 8 + j * 18, 115)); + } + bindPlayerInventory(player.inventory); + if (fluidInterface instanceof TileEntityFluidInterface) { + ((TileEntityFluidInterface) fluidInterface).registerListener(this); + } else if (fluidInterface instanceof PartFluidInterface) { + ((PartFluidInterface) fluidInterface).registerListener(this); + } + if (fluidInterface instanceof TileEntityFluidInterface) { + ((TileEntityFluidInterface) fluidInterface).doNextUpdate = true; + } else if (fluidInterface instanceof PartFluidInterface) { + ((PartFluidInterface) fluidInterface).doNextUpdate = true; + } + } + + protected void bindPlayerInventory(IInventory inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 149)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 207)); // 173 + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return true; + } + + private int getFluidID(ForgeDirection side) { + Fluid fluid = this.fluidInterface.getFilter(side); + if (fluid == null) return -1; + return fluid.getID(); + } + + @Override + public void onContainerClosed(EntityPlayer player) { + super.onContainerClosed(player); + if (this.fluidInterface instanceof TileEntityFluidInterface) { + ((TileEntityFluidInterface) this.fluidInterface).removeListener(this); + } else if (this.fluidInterface instanceof PartFluidInterface) { + ((PartFluidInterface) this.fluidInterface).removeListener(this); + } + } + + @Override + protected void retrySlotClick(int p_75133_1_, int p_75133_2_, boolean p_75133_3_, EntityPlayer p_75133_4_) {} + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (itemstack.getItem() instanceof ICraftingPatternItem) { + if (slotnumber < 9) { + if (!mergeItemStack( + itemstack1, + this.inventorySlots.size() - 9, + this.inventorySlots.size(), + false)) { + if (!mergeItemStack(itemstack1, 9, this.inventorySlots.size() - 9, false)) return null; + } + } else if (!mergeItemStack(itemstack1, 0, 9, false)) { + return null; + } + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + return itemstack; + } + + if (slotnumber < this.inventorySlots.size() - 9) { + if (!mergeItemStack(itemstack1, this.inventorySlots.size() - 9, this.inventorySlots.size(), true)) { + return null; + } + } else if (!mergeItemStack(itemstack1, 9, this.inventorySlots.size() - 9, false)) { + return null; + } + + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } + + return itemstack; + } + + @Override + public void updateContainer() { + new PacketFluidInterface( + new FluidStack[] { this.fluidInterface.getFluidTank(ForgeDirection.getOrientation(0)).getFluid(), + this.fluidInterface.getFluidTank(ForgeDirection.getOrientation(1)).getFluid(), + this.fluidInterface.getFluidTank(ForgeDirection.getOrientation(2)).getFluid(), + this.fluidInterface.getFluidTank(ForgeDirection.getOrientation(3)).getFluid(), + this.fluidInterface.getFluidTank(ForgeDirection.getOrientation(4)).getFluid(), + this.fluidInterface.getFluidTank(ForgeDirection.getOrientation(5)).getFluid() }, + new Integer[] { getFluidID(ForgeDirection.getOrientation(0)), + getFluidID(ForgeDirection.getOrientation(1)), getFluidID(ForgeDirection.getOrientation(2)), + getFluidID(ForgeDirection.getOrientation(3)), getFluidID(ForgeDirection.getOrientation(4)), + getFluidID(ForgeDirection.getOrientation(5)) }, + this.player).sendPacketToPlayer(this.player); + } } diff --git a/src/main/scala/extracells/container/ContainerFluidStorage.java b/src/main/scala/extracells/container/ContainerFluidStorage.java index 5db38cd45..ab19b173c 100644 --- a/src/main/scala/extracells/container/ContainerFluidStorage.java +++ b/src/main/scala/extracells/container/ContainerFluidStorage.java @@ -1,5 +1,18 @@ package extracells.container; +import static extracells.util.FluidUtil.filterEmptyFluid; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.inventory.SlotFurnace; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.apache.commons.lang3.tuple.MutablePair; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -9,6 +22,7 @@ import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import extracells.api.ECApi; import extracells.api.IPortableFluidStorageCell; import extracells.api.IWirelessFluidTermHandler; import extracells.container.slot.SlotPlayerInventory; @@ -20,384 +34,376 @@ import extracells.util.FluidUtil; import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.inventory.SlotFurnace; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import org.apache.commons.lang3.tuple.MutablePair; -public class ContainerFluidStorage extends Container implements - IMEMonitorHandlerReceiver, IFluidSelectorContainer, - IInventoryUpdateReceiver, IStorageContainer { - - private GuiFluidStorage guiFluidStorage; - private IItemList fluidStackList; - private Fluid selectedFluid; - private IAEFluidStack selectedFluidStack; - private EntityPlayer player; - private IMEMonitor monitor; - private HandlerItemStorageFluid storageFluid; - private IWirelessFluidTermHandler handler = null; - private IPortableFluidStorageCell storageCell = null; - public boolean hasWirelessTermHandler = false; - private ECPrivateInventory inventory = new ECPrivateInventory("extracells.item.fluid.storage", 2, 64, this) { - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return FluidUtil.isFluidContainer(itemStack); - } - }; - - public ContainerFluidStorage(EntityPlayer _player) { - this(null, _player); - } - - public ContainerFluidStorage(IMEMonitor _monitor, EntityPlayer _player) { - this.monitor = _monitor; - this.player = _player; - if (!this.player.worldObj.isRemote && this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } else { - this.fluidStackList = AEApi.instance().storage().createFluidList(); - } - - // Input Slot accepts all FluidContainers - addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, - 92)); - - bindPlayerInventory(this.player.inventory); - } - - public ContainerFluidStorage(IMEMonitor _monitor, EntityPlayer _player, IPortableFluidStorageCell _storageCell) { - this.hasWirelessTermHandler = _storageCell != null; - this.storageCell = _storageCell; - this.monitor = _monitor; - this.player = _player; - if (!this.player.worldObj.isRemote && this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } else { - this.fluidStackList = AEApi.instance().storage().createFluidList(); - } - - // Input Slot accepts all FluidContainers - addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, - 92)); - - bindPlayerInventory(this.player.inventory); - } - - public ContainerFluidStorage(IMEMonitor _monitor, - EntityPlayer _player, IWirelessFluidTermHandler _handler) { - this.hasWirelessTermHandler = _handler != null; - this.handler = _handler; - this.monitor = _monitor; - this.player = _player; - if (!this.player.worldObj.isRemote && this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } else { - this.fluidStackList = AEApi.instance().storage().createFluidList(); - } - - // Input Slot accepts all FluidContainers - addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, - 92)); - - bindPlayerInventory(this.player.inventory); - } - - protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new SlotPlayerInventory(inventoryPlayer, - this, j + i * 9 + 9, 8 + j * 18, i * 18 + 122)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new SlotPlayerInventory(inventoryPlayer, this, - i, 8 + i * 18, 180)); - } - - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - public void decreaseFirstSlot() { - ItemStack slot = this.inventory.getStackInSlot(0); - if (slot == null) - return; - slot.stackSize--; - if (slot.stackSize <= 0) - this.inventory.setInventorySlotContents(0, null); - } - - public void doWork() { - ItemStack secondSlot = this.inventory.getStackInSlot(1); - if (secondSlot != null && secondSlot.stackSize > secondSlot.getMaxStackSize()) - return; - ItemStack container = this.inventory.getStackInSlot(0); - if (!FluidUtil.isFluidContainer(container)) - return; - if (this.monitor == null) - return; - - container = container.copy(); - container.stackSize = 1; - - if (FluidUtil.isEmpty(container)) { - if (this.selectedFluid == null) - return; - int capacity = FluidUtil.getCapacity(container); - //Tries to simulate the extraction of fluid from storage. - IAEFluidStack result = this.monitor.extractItems(FluidUtil.createAEFluidStack(this.selectedFluid, capacity), Actionable.SIMULATE, new PlayerSource(this.player, null)); - - //Calculates the amount of fluid to fill container with. - int proposedAmount = result == null ? 0 : (int) Math.min(capacity, result.getStackSize()); - - if(proposedAmount == 0) - return; - - //Tries to fill the container with fluid. - MutablePair filledContainer = FluidUtil.fillStack(container, new FluidStack(this.selectedFluid, proposedAmount)); - - //Moves it to second slot and commits extraction to grid. - if (fillSecondSlot(filledContainer.getRight())) { - this.monitor.extractItems(FluidUtil.createAEFluidStack( - this.selectedFluid, filledContainer.getLeft()), - Actionable.MODULATE, - new PlayerSource(this.player, null)); - decreaseFirstSlot(); - } - - } else if (FluidUtil.isFilled(container)) { - FluidStack containerFluid = FluidUtil.getFluidFromContainer(container); - - //Tries to inject fluid to network. - IAEFluidStack notInjected = this.monitor.injectItems( - FluidUtil.createAEFluidStack(containerFluid), - Actionable.SIMULATE, new PlayerSource(this.player, null)); - if (notInjected != null) - return; - if (this.handler != null) { - if (!this.handler.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return; - } - this.handler.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } else if (this.storageCell != null) { - if (!this.storageCell.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return; - } - this.storageCell.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } - MutablePair drainedContainer = FluidUtil - .drainStack(container, containerFluid); - if (fillSecondSlot(drainedContainer.getRight())) { - this.monitor.injectItems( - FluidUtil.createAEFluidStack(containerFluid), - Actionable.MODULATE, - new PlayerSource(this.player, null)); - decreaseFirstSlot(); - } - } - } - - public boolean fillSecondSlot(ItemStack itemStack) { - if (itemStack == null) - return false; - ItemStack secondSlot = this.inventory.getStackInSlot(1); - if (secondSlot == null) { - if (this.handler != null) { - if (!this.handler.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.handler.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } else if (this.storageCell != null) { - if (!this.storageCell.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.storageCell.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } - this.inventory.setInventorySlotContents(1, itemStack); - return true; - } else { - if (!secondSlot.isItemEqual(itemStack) - || !ItemStack.areItemStackTagsEqual(itemStack, secondSlot)) - return false; - if (this.handler != null) { - if (!this.handler.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.handler.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } else if (this.storageCell != null) { - if (!this.storageCell.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.storageCell.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } - this.inventory.incrStackSize(1, itemStack.stackSize); - return true; - } - } - - public void forceFluidUpdate() { - if (this.monitor != null) - new PacketFluidStorage(this.player, this.monitor.getStorageList()) - .sendPacketToPlayer(this.player); - new PacketFluidStorage(this.player, this.hasWirelessTermHandler) - .sendPacketToPlayer(this.player); - } - - public IItemList getFluidStackList() { - return this.fluidStackList; - } - - public EntityPlayer getPlayer() { - return this.player; - } - - public Fluid getSelectedFluid() { - return this.selectedFluid; - } - - public IAEFluidStack getSelectedFluidStack() { - return this.selectedFluidStack; - } - - public boolean hasWirelessTermHandler() { - return this.hasWirelessTermHandler; - } - - @Override - public boolean isValid(Object verificationToken) { - return true; - } - - @Override - public void onContainerClosed(EntityPlayer entityPlayer) { - super.onContainerClosed(entityPlayer); - if (!entityPlayer.worldObj.isRemote) { - this.monitor.removeListener(this); - for (int i = 0; i < 2; i++) - this.player.dropPlayerItemWithRandomChoice( - ((Slot) this.inventorySlots.get(i)).getStack(), false); - } - } - - @Override - public void onInventoryChanged() { - - } - - @Override - public void onListUpdate() {} - - @Override - public void postChange(IBaseMonitor monitor, Iterable change, BaseActionSource actionSource) { - this.fluidStackList = ((IMEMonitor) monitor).getStorageList(); - new PacketFluidStorage(this.player, this.fluidStackList).sendPacketToPlayer(this.player); - new PacketFluidStorage(this.player, this.hasWirelessTermHandler).sendPacketToPlayer(this.player); - } - - public void receiveSelectedFluid(Fluid _selectedFluid) { - this.selectedFluid = _selectedFluid; - if (this.selectedFluid != null) { - for (IAEFluidStack stack : this.fluidStackList) { - if (stack != null && stack.getFluid() == this.selectedFluid) { - this.selectedFluidStack = stack; - break; - } - } - } else { - this.selectedFluidStack = null; - } - if (this.guiFluidStorage != null) - this.guiFluidStorage.updateSelectedFluid(); - } - - public void removeEnergyTick() { - if (this.handler != null) { - if (this.handler.hasPower(this.player, 1.0D, - this.player.getCurrentEquippedItem())) { - this.handler.usePower(this.player, 1.0D, - this.player.getCurrentEquippedItem()); - } - } else if (this.storageCell != null) { - if (this.storageCell.hasPower(this.player, 0.5D, - this.player.getCurrentEquippedItem())) { - this.storageCell.usePower(this.player, 0.5D, - this.player.getCurrentEquippedItem()); - } - } - } - - public void setGui(GuiFluidStorage _guiFluidStorage) { - this.guiFluidStorage = _guiFluidStorage; - } - - @Override - public void setSelectedFluid(Fluid _selectedFluid) { - new PacketFluidStorage(this.player, _selectedFluid) - .sendPacketToServer(); - receiveSelectedFluid(_selectedFluid); - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - if (this.inventory.isItemValidForSlot(0, itemstack1)) { - if (slotnumber == 0 || slotnumber == 1) { - if (!mergeItemStack(itemstack1, 2, 36, false)) - return null; - } else if (!mergeItemStack(itemstack1, 0, 1, false)) { - return null; - } - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } else { - return null; - } - } - return itemstack; - } - - public void updateFluidList(IItemList _fluidStackList) { - this.fluidStackList = _fluidStackList; - if (this.guiFluidStorage != null) - this.guiFluidStorage.updateFluids(); - } +public class ContainerFluidStorage extends Container implements IMEMonitorHandlerReceiver, + IFluidSelectorContainer, IInventoryUpdateReceiver, IStorageContainer { + + private GuiFluidStorage guiFluidStorage; + private IItemList fluidStackList; + private Fluid selectedFluid; + private IAEFluidStack selectedFluidStack; + private final EntityPlayer player; + private final IMEMonitor monitor; + private HandlerItemStorageFluid storageFluid; + private IWirelessFluidTermHandler handler = null; + private IPortableFluidStorageCell storageCell = null; + public boolean hasWirelessTermHandler = false; + + private final ECPrivateInventory inventory = new ECPrivateInventory("extracells.item.fluid.storage", 2, 64, this) { + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return FluidUtil.isFluidContainer(itemStack); + } + }; + + public ContainerFluidStorage(EntityPlayer _player) { + this(null, _player); + } + + public ContainerFluidStorage(IMEMonitor _monitor, EntityPlayer _player) { + this.monitor = _monitor; + this.player = _player; + if (!this.player.worldObj.isRemote && this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } else { + this.fluidStackList = AEApi.instance().storage().createFluidList(); + } + + // Input Slot accepts all FluidContainers + addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, 92)); + + bindPlayerInventory(this.player.inventory); + } + + public ContainerFluidStorage(IMEMonitor _monitor, EntityPlayer _player, + IPortableFluidStorageCell _storageCell) { + this.hasWirelessTermHandler = _storageCell != null; + this.storageCell = _storageCell; + this.monitor = _monitor; + this.player = _player; + if (!this.player.worldObj.isRemote && this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } else { + this.fluidStackList = AEApi.instance().storage().createFluidList(); + } + + // Input Slot accepts all FluidContainers + addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, 92)); + + bindPlayerInventory(this.player.inventory); + } + + public ContainerFluidStorage(IMEMonitor _monitor, EntityPlayer _player, + IWirelessFluidTermHandler _handler) { + this.hasWirelessTermHandler = _handler != null; + this.handler = _handler; + this.monitor = _monitor; + this.player = _player; + if (!this.player.worldObj.isRemote && this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } else { + this.fluidStackList = AEApi.instance().storage().createFluidList(); + } + + // Input Slot accepts all FluidContainers + addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, 92)); + + bindPlayerInventory(this.player.inventory); + } + + protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer( + new SlotPlayerInventory(inventoryPlayer, this, j + i * 9 + 9, 8 + j * 18, i * 18 + 122)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new SlotPlayerInventory(inventoryPlayer, this, i, 8 + i * 18, 180)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return true; + } + + public void decreaseFirstSlot() { + ItemStack slot = this.inventory.getStackInSlot(0); + if (slot == null) return; + slot.stackSize--; + if (slot.stackSize <= 0) this.inventory.setInventorySlotContents(0, null); + } + + public void doWork() { + ItemStack secondSlot = this.inventory.getStackInSlot(1); + if (secondSlot != null && secondSlot.stackSize >= secondSlot.getMaxStackSize()) return; + ItemStack container = this.inventory.getStackInSlot(0); + if (!FluidUtil.isFluidContainer(container)) return; + if (this.monitor == null) return; + + container = container.copy(); + container.stackSize = 1; + + if (FluidUtil.isEmpty(container)) { + if (this.selectedFluid == null) return; + int capacity = FluidUtil.getCapacity(container, this.selectedFluid); + // Tries to simulate the extraction of fluid from storage. + IAEFluidStack result = this.monitor.extractItems( + FluidUtil.createAEFluidStack(this.selectedFluid, capacity), + Actionable.SIMULATE, + new PlayerSource(this.player, null)); + + // Calculates the amount of fluid to fill container with. + int proposedAmount = result == null ? 0 : (int) Math.min(capacity, result.getStackSize()); + + if (proposedAmount == 0) return; + + // Tries to fill the container with fluid. + MutablePair filledContainer = FluidUtil + .fillStack(container, new FluidStack(this.selectedFluid, proposedAmount)); + + // Moves it to second slot and commits extraction to grid. + if (fillSecondSlot(filledContainer.getRight())) { + this.monitor.extractItems( + FluidUtil.createAEFluidStack(this.selectedFluid, filledContainer.getLeft()), + Actionable.MODULATE, + new PlayerSource(this.player, null)); + decreaseFirstSlot(); + } + + } else if (FluidUtil.isFilled(container)) { + FluidStack containerFluid = FluidUtil.getFluidFromContainer(container); + + // Tries to inject fluid to network. + IAEFluidStack notInjected = this.monitor.injectItems( + FluidUtil.createAEFluidStack(containerFluid), + Actionable.SIMULATE, + new PlayerSource(this.player, null)); + if (notInjected != null) return; + if (this.handler != null) { + if (!this.handler.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return; + } + this.handler.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } else if (this.storageCell != null) { + if (!this.storageCell.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return; + } + this.storageCell.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } + MutablePair drainedContainer = FluidUtil.drainStack(container, containerFluid); + if (fillSecondSlot(drainedContainer.getRight())) { + this.monitor.injectItems( + FluidUtil.createAEFluidStack(containerFluid), + Actionable.MODULATE, + new PlayerSource(this.player, null)); + decreaseFirstSlot(); + } + } + } + + public boolean fillSecondSlot(ItemStack itemStack) { + if (itemStack == null) return false; + ItemStack secondSlot = this.inventory.getStackInSlot(1); + if (secondSlot == null) { + if (this.handler != null) { + if (!this.handler.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.handler.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } else if (this.storageCell != null) { + if (!this.storageCell.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.storageCell.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } + this.inventory.setInventorySlotContents(1, itemStack); + return true; + } else { + if (!secondSlot.isItemEqual(itemStack) || !ItemStack.areItemStackTagsEqual(itemStack, secondSlot)) + return false; + if (this.handler != null) { + if (!this.handler.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.handler.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } else if (this.storageCell != null) { + if (!this.storageCell.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.storageCell.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } + this.inventory.incrStackSize(1, itemStack.stackSize); + return true; + } + } + + public void forceFluidUpdate() { + if (this.monitor != null) { + new PacketFluidStorage(this.player, this.monitor.getStorageList()).sendPacketToPlayer(this.player); + new PacketFluidStorage(this.player, this.hasWirelessTermHandler).sendPacketToPlayer(this.player); + } + } + + public void forceFluidUpdate(String searchText) { + if (this.monitor != null) { + IItemList fluidStackList = AEApi.instance().storage().createFluidList(); + for (IAEFluidStack fluidStack : this.monitor.getStorageList()) { + if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase().contains( + searchText.toLowerCase()) && ECApi.instance().canFluidSeeInTerminal(fluidStack.getFluid())) { + fluidStackList.add(fluidStack); + } + } + new PacketFluidStorage(this.player, fluidStackList).sendPacketToPlayer(this.player); + new PacketFluidStorage(this.player, this.hasWirelessTermHandler).sendPacketToPlayer(this.player); + } + } + + public IItemList getFluidStackList() { + return this.fluidStackList; + } + + public EntityPlayer getPlayer() { + return this.player; + } + + public Fluid getSelectedFluid() { + return this.selectedFluid; + } + + public IAEFluidStack getSelectedFluidStack() { + return this.selectedFluidStack; + } + + public boolean hasWirelessTermHandler() { + return this.hasWirelessTermHandler; + } + + @Override + public boolean isValid(Object verificationToken) { + return true; + } + + @Override + public void onContainerClosed(EntityPlayer entityPlayer) { + super.onContainerClosed(entityPlayer); + if (!entityPlayer.worldObj.isRemote) { + this.monitor.removeListener(this); + for (int i = 0; i < 2; i++) + this.player.dropPlayerItemWithRandomChoice(((Slot) this.inventorySlots.get(i)).getStack(), false); + } + } + + @Override + public void onInventoryChanged() {} + + @Override + public void onListUpdate() {} + + @Override + public void postChange(IBaseMonitor monitor, Iterable change, + BaseActionSource actionSource) { + this.fluidStackList = ((IMEMonitor) monitor).getStorageList(); + new PacketFluidStorage(this.player, change, this.fluidStackList).sendPacketToPlayer(this.player); + new PacketFluidStorage(this.player, this.hasWirelessTermHandler).sendPacketToPlayer(this.player); + } + + public void receiveSelectedFluid(Fluid _selectedFluid) { + this.selectedFluid = _selectedFluid; + if (this.selectedFluid != null) { + for (IAEFluidStack stack : this.fluidStackList) { + if (stack != null && stack.getFluid() == this.selectedFluid) { + this.selectedFluidStack = stack; + break; + } + } + } else { + this.selectedFluidStack = null; + } + if (this.guiFluidStorage != null) this.guiFluidStorage.updateSelectedFluid(); + } + + public void removeEnergyTick() { + if (this.handler != null) { + if (this.handler.hasPower(this.player, 1.0D, this.player.getCurrentEquippedItem())) { + this.handler.usePower(this.player, 1.0D, this.player.getCurrentEquippedItem()); + } + } else if (this.storageCell != null) { + if (this.storageCell.hasPower(this.player, 0.5D, this.player.getCurrentEquippedItem())) { + this.storageCell.usePower(this.player, 0.5D, this.player.getCurrentEquippedItem()); + } + } + } + + public void setGui(GuiFluidStorage _guiFluidStorage) { + this.guiFluidStorage = _guiFluidStorage; + } + + @Override + public void setSelectedFluid(Fluid _selectedFluid) { + new PacketFluidStorage(this.player, _selectedFluid).sendPacketToServer(); + receiveSelectedFluid(_selectedFluid); + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + if (this.inventory.isItemValidForSlot(0, itemstack1)) { + if (slotnumber == 0 || slotnumber == 1) { + if (!mergeItemStack(itemstack1, 2, 36, false)) return null; + } else if (!mergeItemStack(itemstack1, 0, 1, false)) { + return null; + } + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } else { + return null; + } + } + return itemstack; + } + + public void updateFluidList(IItemList _fluidStackList) { + this.fluidStackList = _fluidStackList; + if (this.guiFluidStorage != null) this.guiFluidStorage.updateFluids(); + } + + public void updateFluidList(IItemList _fluidStackList, boolean incremental) { + if (incremental) { + IItemList temp = this.getFluidStackList(); + for (IAEFluidStack f1 : _fluidStackList) { + boolean change = false; + for (IAEFluidStack f2 : temp) { + if (f1.getFluid().getID() == f2.getFluid().getID()) { + f2.setStackSize(f2.getStackSize() + f1.getStackSize()); + change = true; + } + } + if (!change) temp.add(f1); + } + this.fluidStackList = filterEmptyFluid(temp); + } else { + this.fluidStackList = _fluidStackList; + } + if (this.guiFluidStorage != null) this.guiFluidStorage.updateFluids(); + } } diff --git a/src/main/scala/extracells/container/ContainerFluidTerminal.java b/src/main/scala/extracells/container/ContainerFluidTerminal.java index 30559cf97..40f72012c 100644 --- a/src/main/scala/extracells/container/ContainerFluidTerminal.java +++ b/src/main/scala/extracells/container/ContainerFluidTerminal.java @@ -1,5 +1,16 @@ package extracells.container; +import static extracells.util.FluidUtil.filterEmptyFluid; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.inventory.SlotFurnace; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.networking.security.BaseActionSource; @@ -9,6 +20,7 @@ import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; +import extracells.api.ECApi; import extracells.container.slot.SlotRespective; import extracells.gui.GuiFluidTerminal; import extracells.gui.widget.fluid.IFluidSelectorContainer; @@ -16,203 +28,200 @@ import extracells.part.PartFluidTerminal; import extracells.util.FluidUtil; import extracells.util.PermissionUtil; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.inventory.SlotFurnace; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; -public class ContainerFluidTerminal extends Container implements - IMEMonitorHandlerReceiver, IFluidSelectorContainer { - - private PartFluidTerminal terminal; - private IMEMonitor monitor; - private IItemList fluidStackList = AEApi.instance() - .storage().createFluidList(); - private Fluid selectedFluid; - private EntityPlayer player; - private GuiFluidTerminal guiFluidTerminal; - - public ContainerFluidTerminal(PartFluidTerminal _terminal, - EntityPlayer _player) { - this.terminal = _terminal; - this.player = _player; - if (!this.player.worldObj.isRemote) { - this.monitor = this.terminal.getGridBlock().getFluidMonitor(); - if (this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } - this.terminal.addContainer(this); - } - - // Input Slot accepts all FluidContainers - addSlotToContainer(new SlotRespective(this.terminal.getInventory(), 0, - 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, - this.terminal.getInventory(), 1, 26, 92)); - bindPlayerInventory(this.player.inventory); - } - - protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 122)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 180)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - if (terminal == null) - return false; - return terminal.isValid(); - } - - public void forceFluidUpdate() { - if (this.monitor != null) { - new PacketFluidTerminal(this.player, this.monitor.getStorageList()) - .sendPacketToPlayer(this.player); - } - } - - public IItemList getFluidStackList() { - return this.fluidStackList; - } - - public EntityPlayer getPlayer() { - return this.player; - } - - public Fluid getSelectedFluid() { - return this.selectedFluid; - } - - public PartFluidTerminal getTerminal() { - return this.terminal; - } - - @Override - public boolean isValid(Object verificationToken) { - return true; - } - - @Override - public void onContainerClosed(EntityPlayer entityPlayer) { - super.onContainerClosed(entityPlayer); - if (!entityPlayer.worldObj.isRemote) { - if (this.monitor != null) - this.monitor.removeListener(this); - this.terminal.removeContainer(this); - } - } - - @Override - public void onListUpdate() { - - } - - @Override - public void postChange(IBaseMonitor monitor, - Iterable change, BaseActionSource actionSource) { - this.fluidStackList = ((IMEMonitor) monitor) - .getStorageList(); - new PacketFluidTerminal(this.player, this.fluidStackList) - .sendPacketToPlayer(this.player); - } - - public void receiveSelectedFluid(Fluid _selectedFluid) { - this.selectedFluid = _selectedFluid; - if (this.guiFluidTerminal != null) - this.guiFluidTerminal.updateSelectedFluid(); - } - - public void setGui(GuiFluidTerminal _guiFluidTerminal) { - if (_guiFluidTerminal != null) - this.guiFluidTerminal = _guiFluidTerminal; - } - - @Override - public void setSelectedFluid(Fluid _selectedFluid) { - new PacketFluidTerminal(this.player, _selectedFluid, this.terminal) - .sendPacketToServer(); - } - - @Override - public ItemStack slotClick(int slotNumber, int p_75144_2_, int p_75144_3_, - EntityPlayer player) { - ItemStack returnStack = null; - boolean hasPermission = true; - if (slotNumber == 0 || slotNumber == 1) { - ItemStack stack = player.inventory.getItemStack(); - if (stack == null) {} else { - if (FluidUtil.isEmpty(stack) - && PermissionUtil.hasPermission(player, - SecurityPermissions.INJECT, - (IPart) getTerminal())) {} else if (FluidUtil - .isFilled(stack) - && PermissionUtil.hasPermission(player, - SecurityPermissions.EXTRACT, - (IPart) getTerminal())) {} else { - ItemStack slotStack = ((Slot) this.inventorySlots - .get(slotNumber)).getStack(); - if (slotStack == null) - returnStack = null; - else - returnStack = slotStack.copy(); - hasPermission = false; - } - } - } - if (hasPermission) - returnStack = super.slotClick(slotNumber, p_75144_2_, p_75144_3_, - player); - if (player instanceof EntityPlayerMP) { - EntityPlayerMP p = (EntityPlayerMP) player; - p.sendContainerToPlayer(this); - } - return returnStack; - - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - if (this.terminal.getInventory().isItemValidForSlot(0, itemstack1)) { - if (slotnumber == 1 || slotnumber == 0) { - if (!mergeItemStack(itemstack1, 2, 36, false)) - return null; - } else if (!mergeItemStack(itemstack1, 0, 1, false)) { - return null; - } - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } else { - return null; - } - } - return itemstack; - } - - public void updateFluidList(IItemList _fluidStackList) { - this.fluidStackList = _fluidStackList; - if (this.guiFluidTerminal != null) - this.guiFluidTerminal.updateFluids(); - } +public class ContainerFluidTerminal extends Container + implements IMEMonitorHandlerReceiver, IFluidSelectorContainer { + + private final PartFluidTerminal terminal; + private IMEMonitor monitor; + private IItemList fluidStackList = AEApi.instance().storage().createFluidList(); + private Fluid selectedFluid; + private final EntityPlayer player; + private GuiFluidTerminal guiFluidTerminal; + + public ContainerFluidTerminal(PartFluidTerminal _terminal, EntityPlayer _player) { + this.terminal = _terminal; + this.player = _player; + if (!this.player.worldObj.isRemote) { + this.monitor = this.terminal.getGridBlock().getFluidMonitor(); + if (this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } + this.terminal.addContainer(this); + } + + // Input Slot accepts all FluidContainers + addSlotToContainer(new SlotRespective(this.terminal.getInventory(), 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.terminal.getInventory(), 1, 26, 92)); + bindPlayerInventory(this.player.inventory); + } + + protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 122)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 180)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + if (terminal == null) return false; + return terminal.isValid(); + } + + public void forceFluidUpdate(String searchText) { + if (this.monitor != null) { + IItemList fluidStackList = AEApi.instance().storage().createFluidList(); + for (IAEFluidStack fluidStack : this.monitor.getStorageList()) { + if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase().contains( + searchText.toLowerCase()) && ECApi.instance().canFluidSeeInTerminal(fluidStack.getFluid())) { + fluidStackList.add(fluidStack); + } + } + new PacketFluidTerminal(this.player, fluidStackList).sendPacketToPlayer(this.player); + } + } + + public void forceFluidUpdate() { + if (this.monitor != null) { + new PacketFluidTerminal(this.player, this.monitor.getStorageList()).sendPacketToPlayer(this.player); + } + } + + public IItemList getFluidStackList() { + return this.fluidStackList; + } + + public EntityPlayer getPlayer() { + return this.player; + } + + public Fluid getSelectedFluid() { + return this.selectedFluid; + } + + public PartFluidTerminal getTerminal() { + return this.terminal; + } + + @Override + public boolean isValid(Object verificationToken) { + return true; + } + + @Override + public void onContainerClosed(EntityPlayer entityPlayer) { + super.onContainerClosed(entityPlayer); + if (!entityPlayer.worldObj.isRemote) { + if (this.monitor != null) this.monitor.removeListener(this); + this.terminal.removeContainer(this); + } + } + + @Override + public void onListUpdate() {} + + @Override + public void postChange(IBaseMonitor monitor, Iterable change, + BaseActionSource actionSource) { + this.fluidStackList = ((IMEMonitor) monitor).getStorageList(); + new PacketFluidTerminal(this.player, change, this.fluidStackList).sendPacketToPlayer(this.player); + } + + public void receiveSelectedFluid(Fluid _selectedFluid) { + this.selectedFluid = _selectedFluid; + if (this.guiFluidTerminal != null) this.guiFluidTerminal.updateSelectedFluid(); + } + + public void setGui(GuiFluidTerminal _guiFluidTerminal) { + if (_guiFluidTerminal != null) this.guiFluidTerminal = _guiFluidTerminal; + } + + @Override + public void setSelectedFluid(Fluid _selectedFluid) { + new PacketFluidTerminal(this.player, _selectedFluid, this.terminal).sendPacketToServer(); + } + + @Override + public ItemStack slotClick(int slotNumber, int p_75144_2_, int p_75144_3_, EntityPlayer player) { + ItemStack returnStack = null; + boolean hasPermission = true; + if (slotNumber == 0 || slotNumber == 1) { + ItemStack stack = player.inventory.getItemStack(); + if (stack == null) {} else { + if (FluidUtil.isEmpty(stack) && PermissionUtil + .hasPermission(player, SecurityPermissions.INJECT, (IPart) getTerminal())) {} else + if (FluidUtil.isFilled(stack) && PermissionUtil + .hasPermission(player, SecurityPermissions.EXTRACT, (IPart) getTerminal())) {} else { + ItemStack slotStack = ((Slot) this.inventorySlots.get(slotNumber)).getStack(); + if (slotStack == null) returnStack = null; + else returnStack = slotStack.copy(); + hasPermission = false; + } + } + } + if (hasPermission) returnStack = super.slotClick(slotNumber, p_75144_2_, p_75144_3_, player); + if (player instanceof EntityPlayerMP) { + EntityPlayerMP p = (EntityPlayerMP) player; + p.sendContainerToPlayer(this); + } + return returnStack; + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + if (this.terminal.getInventory().isItemValidForSlot(0, itemstack1)) { + if (slotnumber == 1 || slotnumber == 0) { + if (!mergeItemStack(itemstack1, 2, 36, false)) return null; + } else if (!mergeItemStack(itemstack1, 0, 1, false)) { + return null; + } + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } else { + return null; + } + } + return itemstack; + } + + public void updateFluidList(IItemList _fluidStackList) { + this.fluidStackList = _fluidStackList; + if (this.guiFluidTerminal != null) this.guiFluidTerminal.updateFluids(); + } + + public void updateFluidList(IItemList _fluidStackList, boolean incremental) { + if (incremental) { + IItemList temp = this.getFluidStackList(); + for (IAEFluidStack f1 : _fluidStackList) { + boolean change = false; + for (IAEFluidStack f2 : temp) { + if (f1.getFluid().getID() == f2.getFluid().getID()) { + f2.setStackSize(f2.getStackSize() + f1.getStackSize()); + change = true; + } + } + if (!change) temp.add(f1); + } + this.fluidStackList = filterEmptyFluid(temp); + } else { + this.fluidStackList = _fluidStackList; + } + if (this.guiFluidTerminal != null) this.guiFluidTerminal.updateFluids(); + } } diff --git a/src/main/scala/extracells/container/ContainerGasStorage.java b/src/main/scala/extracells/container/ContainerGasStorage.java index 7aa93748f..ca2d76d30 100644 --- a/src/main/scala/extracells/container/ContainerGasStorage.java +++ b/src/main/scala/extracells/container/ContainerGasStorage.java @@ -1,5 +1,18 @@ package extracells.container; +import static extracells.util.FluidUtil.filterEmptyFluid; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.inventory.SlotFurnace; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.apache.commons.lang3.tuple.MutablePair; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.networking.security.BaseActionSource; @@ -24,400 +37,388 @@ import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; import mekanism.api.gas.GasStack; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.inventory.SlotFurnace; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import org.apache.commons.lang3.tuple.MutablePair; -public class ContainerGasStorage extends Container implements - IMEMonitorHandlerReceiver, IFluidSelectorContainer, - IInventoryUpdateReceiver, IStorageContainer { - - private boolean isMekanismEnabled = Integration.Mods.MEKANISMGAS.isEnabled(); - private GuiGasStorage guiGasStorage; - private IItemList fluidStackList; - private Fluid selectedFluid; - private IAEFluidStack selectedFluidStack; - private EntityPlayer player; - private IMEMonitor monitor; - private HandlerItemStorageFluid storageFluid; - private IWirelessGasTermHandler handler = null; - private IPortableGasStorageCell storageCell = null; - public boolean hasWirelessTermHandler = false; - private ECPrivateInventory inventory = new ECPrivateInventory( - "extracells.item.fluid.storage", 2, 64, this) { - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return GasUtil.isGasContainer(itemStack); - } - }; - - private boolean doNextFill = false; - - public ContainerGasStorage(EntityPlayer _player) { - this(null, _player); - } - - public ContainerGasStorage(IMEMonitor _monitor, - EntityPlayer _player) { - this.monitor = _monitor; - this.player = _player; - if (!this.player.worldObj.isRemote && this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } else { - this.fluidStackList = AEApi.instance().storage().createFluidList(); - } - - // Input Slot accepts all FluidContainers - addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, - 92)); - - bindPlayerInventory(this.player.inventory); - } - - - public ContainerGasStorage(IMEMonitor _monitor, EntityPlayer _player, IPortableGasStorageCell _storageCell) { - this.hasWirelessTermHandler = _storageCell != null; - this.storageCell = _storageCell; - this.monitor = _monitor; - this.player = _player; - if (!this.player.worldObj.isRemote && this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } else { - this.fluidStackList = AEApi.instance().storage().createFluidList(); - } - - // Input Slot accepts gas FluidContainers - addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, - 92)); - - bindPlayerInventory(this.player.inventory); - } - - public ContainerGasStorage(IMEMonitor _monitor, - EntityPlayer _player, IWirelessGasTermHandler _handler) { - this.hasWirelessTermHandler = _handler != null; - this.handler = _handler; - this.monitor = _monitor; - this.player = _player; - if (!this.player.worldObj.isRemote && this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } else { - this.fluidStackList = AEApi.instance().storage().createFluidList(); - } - - // Input Slot accepts all FluidContainers - addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, - 92)); - - bindPlayerInventory(this.player.inventory); - } - - protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new SlotPlayerInventory(inventoryPlayer, - this, j + i * 9 + 9, 8 + j * 18, i * 18 + 122)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new SlotPlayerInventory(inventoryPlayer, this, - i, 8 + i * 18, 180)); - } - - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - public void decreaseFirstSlot() { - ItemStack slot = this.inventory.getStackInSlot(0); - if (slot == null) - return; - slot.stackSize--; - if (slot.stackSize <= 0) - this.inventory.setInventorySlotContents(0, null); - } - - @Optional.Method(modid = "MekanismAPI|gas") - public void doWork() { - ItemStack secondSlot = this.inventory.getStackInSlot(1); - if (secondSlot != null && secondSlot.stackSize > secondSlot.getMaxStackSize()) - return; - ItemStack container = this.inventory.getStackInSlot(0); - if (container == null) - doNextFill = false; - if (!GasUtil.isGasContainer(container)) - return; - if (this.monitor == null) - return; - GasStack gasStack = GasUtil.getGasFromContainer(container); - container = container.copy(); - container.stackSize = 1; - if (GasUtil.isEmpty(container) || (gasStack.amount < GasUtil.getCapacity(container) && GasUtil.getFluidStack(gasStack).getFluid() == this.selectedFluid && doNextFill)) { - if (this.selectedFluid == null) - return; - int capacity = GasUtil.getCapacity(container); - //Tries to simulate the extraction of fluid from storage. - IAEFluidStack result = this.monitor.extractItems(FluidUtil.createAEFluidStack(this.selectedFluid, capacity), Actionable.SIMULATE, new PlayerSource(this.player, null)); - - //Calculates the amount of fluid to fill container with. - int proposedAmount = result == null ? 0 : gasStack == null ? (int) Math.min(capacity, result.getStackSize()) : (int) Math.min(capacity - gasStack.amount, result.getStackSize()); - - //Tries to fill the container with fluid. - MutablePair filledContainer = GasUtil.fillStack(container, GasUtil.getGasStack(new FluidStack(this.selectedFluid, proposedAmount))); - - GasStack gasStack2 = GasUtil.getGasFromContainer(filledContainer.getRight()); - - //Moves it to second slot and commits extraction to grid. - if (container.stackSize == 1 && gasStack2.amount < GasUtil.getCapacity(filledContainer.getRight())) { - this.inventory.setInventorySlotContents(0, filledContainer.getRight()); - monitor.extractItems(FluidUtil.createAEFluidStack(this.selectedFluid, filledContainer.getLeft()), Actionable.MODULATE, new PlayerSource(this.player, null)); - doNextFill = true; - - }else if (fillSecondSlot(filledContainer.getRight())){ - monitor.extractItems(FluidUtil.createAEFluidStack(this.selectedFluid, filledContainer.getLeft()), Actionable.MODULATE, new PlayerSource(this.player, null)); - decreaseFirstSlot(); - doNextFill = false; - } - - } else if (GasUtil.isFilled(container)) { - GasStack containerGas = GasUtil.getGasFromContainer(container); - - MutablePair drainedContainer = GasUtil.drainStack(container.copy(), containerGas); - GasStack gasStack1 = containerGas.copy(); - gasStack1.amount = drainedContainer.getLeft(); - - //Tries to inject fluid to network. - IAEFluidStack notInjected = this.monitor.injectItems(GasUtil.createAEFluidStack(gasStack1), Actionable.SIMULATE, new PlayerSource(this.player, null)); - if (notInjected != null) - return; - if (this.handler != null) { - if (!this.handler.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return; - } - this.handler.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } else if (this.storageCell != null) { - if (!this.storageCell.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return; - } - this.storageCell.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } - ItemStack emptyContainer = drainedContainer.getRight(); - if(emptyContainer != null && GasUtil.getGasFromContainer(emptyContainer) != null && emptyContainer.stackSize == 1){ - monitor.injectItems(GasUtil.createAEFluidStack(gasStack1), Actionable.MODULATE, new PlayerSource(this.player, null)); - this.inventory.setInventorySlotContents(0, emptyContainer); - } - else if (emptyContainer == null || fillSecondSlot(drainedContainer.getRight())) { - monitor.injectItems(GasUtil.createAEFluidStack(containerGas), Actionable.MODULATE, new PlayerSource(this.player, null)); - decreaseFirstSlot(); - } - } - } - - public boolean fillSecondSlot(ItemStack itemStack) { - if (itemStack == null) - return false; - ItemStack secondSlot = this.inventory.getStackInSlot(1); - if (secondSlot == null) { - if (this.handler != null) { - if (!this.handler.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.handler.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } else if (this.storageCell != null) { - if (!this.storageCell.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.storageCell.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } - this.inventory.setInventorySlotContents(1, itemStack); - return true; - } else { - if (!secondSlot.isItemEqual(itemStack) - || !ItemStack.areItemStackTagsEqual(itemStack, secondSlot)) - return false; - if (this.handler != null) { - if (!this.handler.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.handler.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - }else if (this.storageCell != null) { - if (!this.storageCell.hasPower(this.player, 20.0D, - this.player.getCurrentEquippedItem())) { - return false; - } - this.storageCell.usePower(this.player, 20.0D, - this.player.getCurrentEquippedItem()); - } - this.inventory.incrStackSize(1, itemStack.stackSize); - return true; - } - } - - public void forceFluidUpdate() { - if (this.monitor != null) - new PacketFluidStorage(this.player, this.monitor.getStorageList()) - .sendPacketToPlayer(this.player); - new PacketFluidStorage(this.player, this.hasWirelessTermHandler) - .sendPacketToPlayer(this.player); - } - - public IItemList getFluidStackList() { - return this.fluidStackList; - } - - public EntityPlayer getPlayer() { - return this.player; - } - - public Fluid getSelectedFluid() { - return this.selectedFluid; - } - - public IAEFluidStack getSelectedFluidStack() { - return this.selectedFluidStack; - } - - public boolean hasWirelessTermHandler() { - return this.hasWirelessTermHandler; - } - - @Override - public boolean isValid(Object verificationToken) { - return true; - } - - @Override - public void onContainerClosed(EntityPlayer entityPlayer) { - super.onContainerClosed(entityPlayer); - if (!entityPlayer.worldObj.isRemote) { - this.monitor.removeListener(this); - for (int i = 0; i < 2; i++) - this.player.dropPlayerItemWithRandomChoice( - ((Slot) this.inventorySlots.get(i)).getStack(), false); - } - } - - @Override - public void onInventoryChanged() { - - } - - @Override - public void onListUpdate() {} - - @Override - public void postChange(IBaseMonitor monitor, - Iterable change, BaseActionSource actionSource) { - this.fluidStackList = ((IMEMonitor) monitor) - .getStorageList(); - new PacketFluidStorage(this.player, this.fluidStackList) - .sendPacketToPlayer(this.player); - new PacketFluidStorage(this.player, this.hasWirelessTermHandler) - .sendPacketToPlayer(this.player); - } - - public void receiveSelectedFluid(Fluid _selectedFluid) { - this.selectedFluid = _selectedFluid; - if (this.selectedFluid != null) { - for (IAEFluidStack stack : this.fluidStackList) { - if (stack != null && stack.getFluid() == this.selectedFluid) { - this.selectedFluidStack = stack; - break; - } - } - } else { - this.selectedFluidStack = null; - } - if (this.guiGasStorage != null) - this.guiGasStorage.updateSelectedFluid(); - } - - public void removeEnergyTick() { - if (this.handler != null) { - if (this.handler.hasPower(this.player, 1.0D, - this.player.getCurrentEquippedItem())) { - this.handler.usePower(this.player, 1.0D, - this.player.getCurrentEquippedItem()); - } - } else if (this.storageCell != null) { - if (this.storageCell.hasPower(this.player, 0.5D, - this.player.getCurrentEquippedItem())) { - this.storageCell.usePower(this.player, 0.5D, - this.player.getCurrentEquippedItem()); - } - } - } - - public void setGui(GuiGasStorage _guiGasStorage) { - this.guiGasStorage = _guiGasStorage; - } - - @Override - public void setSelectedFluid(Fluid _selectedFluid) { - new PacketFluidStorage(this.player, _selectedFluid) - .sendPacketToServer(); - receiveSelectedFluid(_selectedFluid); - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - if (this.inventory.isItemValidForSlot(0, itemstack1)) { - if (slotnumber == 0 || slotnumber == 1) { - if (!mergeItemStack(itemstack1, 2, 36, false)) - return null; - } else if (!mergeItemStack(itemstack1, 0, 1, false)) { - return null; - } - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } else { - return null; - } - } - return itemstack; - } - - public void updateFluidList(IItemList _fluidStackList) { - this.fluidStackList = _fluidStackList; - if (this.guiGasStorage != null) - this.guiGasStorage.updateFluids(); - } +public class ContainerGasStorage extends Container implements IMEMonitorHandlerReceiver, + IFluidSelectorContainer, IInventoryUpdateReceiver, IStorageContainer { + + private final boolean isMekanismEnabled = Integration.Mods.MEKANISMGAS.isEnabled(); + private GuiGasStorage guiGasStorage; + private IItemList fluidStackList; + private Fluid selectedFluid; + private IAEFluidStack selectedFluidStack; + private final EntityPlayer player; + private final IMEMonitor monitor; + private HandlerItemStorageFluid storageFluid; + private IWirelessGasTermHandler handler = null; + private IPortableGasStorageCell storageCell = null; + public boolean hasWirelessTermHandler = false; + private final ECPrivateInventory inventory = new ECPrivateInventory("extracells.item.fluid.storage", 2, 64, this) { + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return GasUtil.isGasContainer(itemStack); + } + }; + + private boolean doNextFill = false; + + public ContainerGasStorage(EntityPlayer _player) { + this(null, _player); + } + + public ContainerGasStorage(IMEMonitor _monitor, EntityPlayer _player) { + this.monitor = _monitor; + this.player = _player; + if (!this.player.worldObj.isRemote && this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } else { + this.fluidStackList = AEApi.instance().storage().createFluidList(); + } + + // Input Slot accepts all FluidContainers + addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, 92)); + + bindPlayerInventory(this.player.inventory); + } + + public ContainerGasStorage(IMEMonitor _monitor, EntityPlayer _player, + IPortableGasStorageCell _storageCell) { + this.hasWirelessTermHandler = _storageCell != null; + this.storageCell = _storageCell; + this.monitor = _monitor; + this.player = _player; + if (!this.player.worldObj.isRemote && this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } else { + this.fluidStackList = AEApi.instance().storage().createFluidList(); + } + + // Input Slot accepts gas FluidContainers + addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, 92)); + + bindPlayerInventory(this.player.inventory); + } + + public ContainerGasStorage(IMEMonitor _monitor, EntityPlayer _player, + IWirelessGasTermHandler _handler) { + this.hasWirelessTermHandler = _handler != null; + this.handler = _handler; + this.monitor = _monitor; + this.player = _player; + if (!this.player.worldObj.isRemote && this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } else { + this.fluidStackList = AEApi.instance().storage().createFluidList(); + } + + // Input Slot accepts all FluidContainers + addSlotToContainer(new SlotRespective(this.inventory, 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.inventory, 1, 26, 92)); + + bindPlayerInventory(this.player.inventory); + } + + protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer( + new SlotPlayerInventory(inventoryPlayer, this, j + i * 9 + 9, 8 + j * 18, i * 18 + 122)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new SlotPlayerInventory(inventoryPlayer, this, i, 8 + i * 18, 180)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return true; + } + + public void decreaseFirstSlot() { + ItemStack slot = this.inventory.getStackInSlot(0); + if (slot == null) return; + slot.stackSize--; + if (slot.stackSize <= 0) this.inventory.setInventorySlotContents(0, null); + } + + @Optional.Method(modid = "MekanismAPI|gas") + public void doWork() { + ItemStack secondSlot = this.inventory.getStackInSlot(1); + if (secondSlot != null && secondSlot.stackSize > secondSlot.getMaxStackSize()) return; + ItemStack container = this.inventory.getStackInSlot(0); + if (container == null) doNextFill = false; + if (!GasUtil.isGasContainer(container)) return; + if (this.monitor == null) return; + GasStack gasStack = GasUtil.getGasFromContainer(container); + container = container.copy(); + container.stackSize = 1; + if (GasUtil.isEmpty(container) || (gasStack.amount < GasUtil.getCapacity(container) + && GasUtil.getFluidStack(gasStack).getFluid() == this.selectedFluid + && doNextFill)) { + if (this.selectedFluid == null) return; + int capacity = GasUtil.getCapacity(container); + // Tries to simulate the extraction of fluid from storage. + IAEFluidStack result = this.monitor.extractItems( + FluidUtil.createAEFluidStack(this.selectedFluid, capacity), + Actionable.SIMULATE, + new PlayerSource(this.player, null)); + + // Calculates the amount of fluid to fill container with. + int proposedAmount = result == null ? 0 + : gasStack == null ? (int) Math.min(capacity, result.getStackSize()) + : (int) Math.min(capacity - gasStack.amount, result.getStackSize()); + + // Tries to fill the container with fluid. + MutablePair filledContainer = GasUtil + .fillStack(container, GasUtil.getGasStack(new FluidStack(this.selectedFluid, proposedAmount))); + + GasStack gasStack2 = GasUtil.getGasFromContainer(filledContainer.getRight()); + + // Moves it to second slot and commits extraction to grid. + if (container.stackSize == 1 && gasStack2.amount < GasUtil.getCapacity(filledContainer.getRight())) { + this.inventory.setInventorySlotContents(0, filledContainer.getRight()); + monitor.extractItems( + FluidUtil.createAEFluidStack(this.selectedFluid, filledContainer.getLeft()), + Actionable.MODULATE, + new PlayerSource(this.player, null)); + doNextFill = true; + + } else if (fillSecondSlot(filledContainer.getRight())) { + monitor.extractItems( + FluidUtil.createAEFluidStack(this.selectedFluid, filledContainer.getLeft()), + Actionable.MODULATE, + new PlayerSource(this.player, null)); + decreaseFirstSlot(); + doNextFill = false; + } + + } else if (GasUtil.isFilled(container)) { + GasStack containerGas = GasUtil.getGasFromContainer(container); + + MutablePair drainedContainer = GasUtil.drainStack(container.copy(), containerGas); + GasStack gasStack1 = containerGas.copy(); + gasStack1.amount = drainedContainer.getLeft(); + + // Tries to inject fluid to network. + IAEFluidStack notInjected = this.monitor.injectItems( + GasUtil.createAEFluidStack(gasStack1), + Actionable.SIMULATE, + new PlayerSource(this.player, null)); + if (notInjected != null) return; + if (this.handler != null) { + if (!this.handler.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return; + } + this.handler.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } else if (this.storageCell != null) { + if (!this.storageCell.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return; + } + this.storageCell.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } + ItemStack emptyContainer = drainedContainer.getRight(); + if (emptyContainer != null && GasUtil.getGasFromContainer(emptyContainer) != null + && emptyContainer.stackSize == 1) { + monitor.injectItems( + GasUtil.createAEFluidStack(gasStack1), + Actionable.MODULATE, + new PlayerSource(this.player, null)); + this.inventory.setInventorySlotContents(0, emptyContainer); + } else if (emptyContainer == null || fillSecondSlot(drainedContainer.getRight())) { + monitor.injectItems( + GasUtil.createAEFluidStack(containerGas), + Actionable.MODULATE, + new PlayerSource(this.player, null)); + decreaseFirstSlot(); + } + } + } + + public boolean fillSecondSlot(ItemStack itemStack) { + if (itemStack == null) return false; + ItemStack secondSlot = this.inventory.getStackInSlot(1); + if (secondSlot == null) { + if (this.handler != null) { + if (!this.handler.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.handler.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } else if (this.storageCell != null) { + if (!this.storageCell.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.storageCell.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } + this.inventory.setInventorySlotContents(1, itemStack); + return true; + } else { + if (!secondSlot.isItemEqual(itemStack) || !ItemStack.areItemStackTagsEqual(itemStack, secondSlot)) + return false; + if (this.handler != null) { + if (!this.handler.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.handler.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } else if (this.storageCell != null) { + if (!this.storageCell.hasPower(this.player, 20.0D, this.player.getCurrentEquippedItem())) { + return false; + } + this.storageCell.usePower(this.player, 20.0D, this.player.getCurrentEquippedItem()); + } + this.inventory.incrStackSize(1, itemStack.stackSize); + return true; + } + } + + public void forceFluidUpdate() { + if (this.monitor != null) + new PacketFluidStorage(this.player, this.monitor.getStorageList()).sendPacketToPlayer(this.player); + new PacketFluidStorage(this.player, this.hasWirelessTermHandler).sendPacketToPlayer(this.player); + } + + public IItemList getFluidStackList() { + return this.fluidStackList; + } + + public EntityPlayer getPlayer() { + return this.player; + } + + public Fluid getSelectedFluid() { + return this.selectedFluid; + } + + public IAEFluidStack getSelectedFluidStack() { + return this.selectedFluidStack; + } + + public boolean hasWirelessTermHandler() { + return this.hasWirelessTermHandler; + } + + @Override + public boolean isValid(Object verificationToken) { + return true; + } + + @Override + public void onContainerClosed(EntityPlayer entityPlayer) { + super.onContainerClosed(entityPlayer); + if (!entityPlayer.worldObj.isRemote) { + this.monitor.removeListener(this); + for (int i = 0; i < 2; i++) + this.player.dropPlayerItemWithRandomChoice(((Slot) this.inventorySlots.get(i)).getStack(), false); + } + } + + @Override + public void onInventoryChanged() {} + + @Override + public void onListUpdate() {} + + @Override + public void postChange(IBaseMonitor monitor, Iterable change, + BaseActionSource actionSource) { + this.fluidStackList = ((IMEMonitor) monitor).getStorageList(); + new PacketFluidStorage(this.player, change, this.fluidStackList).sendPacketToPlayer(this.player); + new PacketFluidStorage(this.player, this.hasWirelessTermHandler).sendPacketToPlayer(this.player); + } + + public void receiveSelectedFluid(Fluid _selectedFluid) { + this.selectedFluid = _selectedFluid; + if (this.selectedFluid != null) { + for (IAEFluidStack stack : this.fluidStackList) { + if (stack != null && stack.getFluid() == this.selectedFluid) { + this.selectedFluidStack = stack; + break; + } + } + } else { + this.selectedFluidStack = null; + } + if (this.guiGasStorage != null) this.guiGasStorage.updateSelectedFluid(); + } + + public void removeEnergyTick() { + if (this.handler != null) { + if (this.handler.hasPower(this.player, 1.0D, this.player.getCurrentEquippedItem())) { + this.handler.usePower(this.player, 1.0D, this.player.getCurrentEquippedItem()); + } + } else if (this.storageCell != null) { + if (this.storageCell.hasPower(this.player, 0.5D, this.player.getCurrentEquippedItem())) { + this.storageCell.usePower(this.player, 0.5D, this.player.getCurrentEquippedItem()); + } + } + } + + public void setGui(GuiGasStorage _guiGasStorage) { + this.guiGasStorage = _guiGasStorage; + } + + @Override + public void setSelectedFluid(Fluid _selectedFluid) { + new PacketFluidStorage(this.player, _selectedFluid).sendPacketToServer(); + receiveSelectedFluid(_selectedFluid); + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + if (this.inventory.isItemValidForSlot(0, itemstack1)) { + if (slotnumber == 0 || slotnumber == 1) { + if (!mergeItemStack(itemstack1, 2, 36, false)) return null; + } else if (!mergeItemStack(itemstack1, 0, 1, false)) { + return null; + } + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } else { + return null; + } + } + return itemstack; + } + + public void updateFluidList(IItemList _fluidStackList) { + this.fluidStackList = _fluidStackList; + if (this.guiGasStorage != null) this.guiGasStorage.updateFluids(); + } + + public void updateFluidList(IItemList _fluidStackList, boolean incremental) { + if (incremental) { + IItemList temp = this.getFluidStackList(); + for (IAEFluidStack f1 : _fluidStackList) { + boolean change = false; + for (IAEFluidStack f2 : temp) { + if (f1.getFluid().getID() == f2.getFluid().getID()) { + f2.setStackSize(f2.getStackSize() + f1.getStackSize()); + change = true; + } + } + if (!change) temp.add(f1); + } + this.fluidStackList = filterEmptyFluid(temp); + } else { + this.fluidStackList = _fluidStackList; + } + if (this.guiGasStorage != null) this.guiGasStorage.updateFluids(); + } } diff --git a/src/main/scala/extracells/container/ContainerGasTerminal.java b/src/main/scala/extracells/container/ContainerGasTerminal.java index 360bc9988..0acc13f31 100644 --- a/src/main/scala/extracells/container/ContainerGasTerminal.java +++ b/src/main/scala/extracells/container/ContainerGasTerminal.java @@ -1,5 +1,16 @@ package extracells.container; +import static extracells.util.FluidUtil.filterEmptyFluid; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.Slot; +import net.minecraft.inventory.SlotFurnace; +import net.minecraft.item.ItemStack; +import net.minecraftforge.fluids.Fluid; + import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.networking.security.BaseActionSource; @@ -17,192 +28,186 @@ import extracells.part.PartGasTerminal; import extracells.util.GasUtil; import extracells.util.PermissionUtil; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.entity.player.InventoryPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.Slot; -import net.minecraft.inventory.SlotFurnace; -import net.minecraft.item.ItemStack; -import net.minecraftforge.fluids.Fluid; -public class ContainerGasTerminal extends Container implements - IMEMonitorHandlerReceiver, IFluidSelectorContainer { - - private PartGasTerminal terminal; - private IMEMonitor monitor; - private IItemList fluidStackList = AEApi.instance() - .storage().createFluidList(); - private Fluid selectedFluid; - private EntityPlayer player; - private GuiGasTerminal guiGasTerminal; - - public ContainerGasTerminal(PartGasTerminal _terminal, EntityPlayer _player) { - this.terminal = _terminal; - this.player = _player; - if (!this.player.worldObj.isRemote) { - this.monitor = this.terminal.getGridBlock().getFluidMonitor(); - if (this.monitor != null) { - this.monitor.addListener(this, null); - this.fluidStackList = this.monitor.getStorageList(); - } - this.terminal.addContainer(this); - } - - // Input Slot accepts all FluidContainers - addSlotToContainer(new SlotRespective(this.terminal.getInventory(), 0, - 8, 92)); - // Input Slot accepts nothing - addSlotToContainer(new SlotFurnace(this.player, - this.terminal.getInventory(), 1, 26, 92)); - bindPlayerInventory(this.player.inventory); - } - - protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 122)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 180)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - public void forceFluidUpdate() { - if (this.monitor != null) { - new PacketFluidTerminal(this.player, this.monitor.getStorageList()) - .sendPacketToPlayer(this.player); - } - } - - public IItemList getFluidStackList() { - return this.fluidStackList; - } - - public EntityPlayer getPlayer() { - return this.player; - } - - public Fluid getSelectedFluid() { - return this.selectedFluid; - } - - public PartFluidTerminal getTerminal() { - return this.terminal; - } - - @Override - public boolean isValid(Object verificationToken) { - return true; - } - - @Override - public void onContainerClosed(EntityPlayer entityPlayer) { - super.onContainerClosed(entityPlayer); - if (!entityPlayer.worldObj.isRemote) { - if (this.monitor != null) - this.monitor.removeListener(this); - this.terminal.removeContainer(this); - } - } - - @Override - public void onListUpdate() { - - } - - @Override - public void postChange(IBaseMonitor monitor, - Iterable change, BaseActionSource actionSource) { - this.fluidStackList = ((IMEMonitor) monitor) - .getStorageList(); - new PacketFluidTerminal(this.player, this.fluidStackList) - .sendPacketToPlayer(this.player); - } - - public void receiveSelectedFluid(Fluid _selectedFluid) { - this.selectedFluid = _selectedFluid; - if (this.guiGasTerminal != null) - this.guiGasTerminal.updateSelectedFluid(); - } - - public void setGui(GuiGasTerminal _guiGasTerminal) { - if (_guiGasTerminal != null) - this.guiGasTerminal = _guiGasTerminal; - } - - @Override - public void setSelectedFluid(Fluid _selectedFluid) { - new PacketFluidTerminal(this.player, _selectedFluid, this.terminal) - .sendPacketToServer(); - } - - @Override - public ItemStack slotClick(int slotNumber, int p_75144_2_, int p_75144_3_, EntityPlayer player) { - ItemStack returnStack = null; - boolean hasPermission = true; - if (slotNumber == 0 || slotNumber == 1) { - ItemStack stack = player.inventory.getItemStack(); - if (stack == null) {} else { - if (GasUtil.isEmpty(stack) && PermissionUtil.hasPermission(player, SecurityPermissions.INJECT, (IPart) getTerminal())) {} - else if (GasUtil.isFilled(stack) && PermissionUtil.hasPermission(player, SecurityPermissions.EXTRACT, (IPart) getTerminal())) {} - else { - ItemStack slotStack = ((Slot) this.inventorySlots.get(slotNumber)).getStack(); - if (slotStack == null) - returnStack = null; - else - returnStack = slotStack.copy(); - hasPermission = false; - } - } - } - if (hasPermission) - returnStack = super.slotClick(slotNumber, p_75144_2_, p_75144_3_, player); - if (player instanceof EntityPlayerMP) { - EntityPlayerMP p = (EntityPlayerMP) player; - p.sendContainerToPlayer(this); - } - return returnStack; - - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - if (this.terminal.getInventory().isItemValidForSlot(0, itemstack1)) { - if (slotnumber == 1 || slotnumber == 0) { - if (!mergeItemStack(itemstack1, 2, 36, false)) - return null; - } else if (!mergeItemStack(itemstack1, 0, 1, false)) { - return null; - } - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } else { - return null; - } - } - return itemstack; - } - - public void updateFluidList(IItemList _fluidStackList) { - this.fluidStackList = _fluidStackList; - if (this.guiGasTerminal != null) - this.guiGasTerminal.updateFluids(); - } +public class ContainerGasTerminal extends Container + implements IMEMonitorHandlerReceiver, IFluidSelectorContainer { + + private final PartGasTerminal terminal; + private IMEMonitor monitor; + private IItemList fluidStackList = AEApi.instance().storage().createFluidList(); + private Fluid selectedFluid; + private final EntityPlayer player; + private GuiGasTerminal guiGasTerminal; + + public ContainerGasTerminal(PartGasTerminal _terminal, EntityPlayer _player) { + this.terminal = _terminal; + this.player = _player; + if (!this.player.worldObj.isRemote) { + this.monitor = this.terminal.getGridBlock().getFluidMonitor(); + if (this.monitor != null) { + this.monitor.addListener(this, null); + this.fluidStackList = this.monitor.getStorageList(); + } + this.terminal.addContainer(this); + } + + // Input Slot accepts all FluidContainers + addSlotToContainer(new SlotRespective(this.terminal.getInventory(), 0, 8, 92)); + // Input Slot accepts nothing + addSlotToContainer(new SlotFurnace(this.player, this.terminal.getInventory(), 1, 26, 92)); + bindPlayerInventory(this.player.inventory); + } + + protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 122)); + } + } + + for (int i = 0; i < 9; i++) { + addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 180)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.terminal != null && this.terminal.isValid(); + } + + public void forceFluidUpdate() { + if (this.monitor != null) { + new PacketFluidTerminal(this.player, this.monitor.getStorageList()).sendPacketToPlayer(this.player); + } + } + + public IItemList getFluidStackList() { + return this.fluidStackList; + } + + public EntityPlayer getPlayer() { + return this.player; + } + + public Fluid getSelectedFluid() { + return this.selectedFluid; + } + + public PartFluidTerminal getTerminal() { + return this.terminal; + } + + @Override + public boolean isValid(Object verificationToken) { + return true; + } + + @Override + public void onContainerClosed(EntityPlayer entityPlayer) { + super.onContainerClosed(entityPlayer); + if (!entityPlayer.worldObj.isRemote) { + if (this.monitor != null) this.monitor.removeListener(this); + this.terminal.removeContainer(this); + } + } + + @Override + public void onListUpdate() {} + + @Override + public void postChange(IBaseMonitor monitor, Iterable change, + BaseActionSource actionSource) { + this.fluidStackList = ((IMEMonitor) monitor).getStorageList(); + new PacketFluidTerminal(this.player, this.fluidStackList).sendPacketToPlayer(this.player); + } + + public void receiveSelectedFluid(Fluid _selectedFluid) { + this.selectedFluid = _selectedFluid; + if (this.guiGasTerminal != null) this.guiGasTerminal.updateSelectedFluid(); + } + + public void setGui(GuiGasTerminal _guiGasTerminal) { + if (_guiGasTerminal != null) this.guiGasTerminal = _guiGasTerminal; + } + + @Override + public void setSelectedFluid(Fluid _selectedFluid) { + new PacketFluidTerminal(this.player, _selectedFluid, this.terminal).sendPacketToServer(); + } + + @Override + public ItemStack slotClick(int slotNumber, int p_75144_2_, int p_75144_3_, EntityPlayer player) { + ItemStack returnStack = null; + boolean hasPermission = true; + if (slotNumber == 0 || slotNumber == 1) { + ItemStack stack = player.inventory.getItemStack(); + if (stack == null) {} else { + if (GasUtil.isEmpty(stack) && PermissionUtil + .hasPermission(player, SecurityPermissions.INJECT, (IPart) getTerminal())) {} else + if (GasUtil.isFilled(stack) && PermissionUtil + .hasPermission(player, SecurityPermissions.EXTRACT, (IPart) getTerminal())) {} else { + ItemStack slotStack = ((Slot) this.inventorySlots.get(slotNumber)).getStack(); + if (slotStack == null) returnStack = null; + else returnStack = slotStack.copy(); + hasPermission = false; + } + } + } + if (hasPermission) returnStack = super.slotClick(slotNumber, p_75144_2_, p_75144_3_, player); + if (player instanceof EntityPlayerMP) { + EntityPlayerMP p = (EntityPlayerMP) player; + p.sendContainerToPlayer(this); + } + return returnStack; + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + if (this.terminal.getInventory().isItemValidForSlot(0, itemstack1)) { + if (slotnumber == 1 || slotnumber == 0) { + if (!mergeItemStack(itemstack1, 2, 36, false)) return null; + } else if (!mergeItemStack(itemstack1, 0, 1, false)) { + return null; + } + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } else { + return null; + } + } + return itemstack; + } + + public void updateFluidList(IItemList _fluidStackList) { + this.fluidStackList = _fluidStackList; + if (this.guiGasTerminal != null) this.guiGasTerminal.updateFluids(); + } + + public void updateFluidList(IItemList _fluidStackList, boolean incremental) { + if (incremental) { + IItemList temp = this.getFluidStackList(); + for (IAEFluidStack f1 : _fluidStackList) { + boolean change = false; + for (IAEFluidStack f2 : temp) { + if (f1.getFluid().getID() == f2.getFluid().getID()) { + f2.setStackSize(f2.getStackSize() + f1.getStackSize()); + change = true; + } + } + if (!change) temp.add(f1); + } + this.fluidStackList = filterEmptyFluid(temp); + } else { + this.fluidStackList = _fluidStackList; + } + if (this.guiGasTerminal != null) this.guiGasTerminal.updateFluids(); + } } diff --git a/src/main/scala/extracells/container/ContainerHardMEDrive.scala b/src/main/scala/extracells/container/ContainerHardMEDrive.scala index d8c5a9384..4b208dc55 100644 --- a/src/main/scala/extracells/container/ContainerHardMEDrive.scala +++ b/src/main/scala/extracells/container/ContainerHardMEDrive.scala @@ -7,61 +7,53 @@ import net.minecraft.entity.player.{EntityPlayer, InventoryPlayer} import net.minecraft.inventory.{Container, Slot} import net.minecraft.item.ItemStack +class ContainerHardMEDrive( + inventory: InventoryPlayer, + tile: TileEntityHardMeDrive +) extends Container { -class ContainerHardMEDrive(inventory: InventoryPlayer, tile: TileEntityHardMeDrive) extends Container{ - - - for (i <- 0 to 2) - { - addSlotToContainer(new SlotRespective(tile.getInventory, i, 80, 17 + i * 18) - { - override def isItemValid(item: ItemStack) = AEApi.instance.registries.cell().isCellHandled(item) - }); + for (i <- 0 to 2) { + addSlotToContainer( + new SlotRespective(tile.getInventory, i, 80, 17 + i * 18) { + override def isItemValid(item: ItemStack) = + AEApi.instance.registries.cell().isCellHandled(item) + } + ); } bindPlayerInventory() - protected def bindPlayerInventory(): Unit = - { - for (i <- 0 to 2) - { - for (j <- 0 to 8) - { - addSlotToContainer(new Slot(inventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + protected def bindPlayerInventory(): Unit = { + for (i <- 0 to 2) { + for (j <- 0 to 8) { + addSlotToContainer( + new Slot(inventory, j + i * 9 + 9, 8 + j * 18, 84 + i * 18) + ); } } - for (i <- 0 to 8) - { + for (i <- 0 to 8) { addSlotToContainer(new Slot(inventory, i, 8 + i * 18, 142)); } } - override def transferStackInSlot(p: EntityPlayer, i: Int): ItemStack = { var itemstack: ItemStack = null val slot = inventorySlots.get(i).asInstanceOf[Slot] - if (slot != null && slot.getHasStack()) - { + if (slot != null && slot.getHasStack()) { val itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); - if (AEApi.instance.registries.cell().isCellHandled(itemstack)) - { - if (i < 3) - { - if (!mergeItemStack(itemstack1, 3, 38, false)) - { + if (AEApi.instance.registries.cell().isCellHandled(itemstack)) { + if (i < 3) { + if (!mergeItemStack(itemstack1, 3, 38, false)) { return null } - } else if (!mergeItemStack(itemstack1, 0, 3, false)) - { + } else if (!mergeItemStack(itemstack1, 0, 3, false)) { return null } - if (itemstack1.stackSize == 0) - { + if (itemstack1.stackSize == 0) { slot.putStack(null) - } else - { + } else { slot.onSlotChanged() } } @@ -69,12 +61,13 @@ class ContainerHardMEDrive(inventory: InventoryPlayer, tile: TileEntityHardMeDri itemstack } - override protected def retrySlotClick(p_75133_1_ : Int, p_75133_2_ : Int, p_75133_3_ : Boolean, - p_75133_4_ : EntityPlayer) = null - override def canInteractWith(p_75145_1_ : EntityPlayer): Boolean = { if (tile.hasWorldObj) - tile.getWorldObj.getTileEntity(tile.xCoord, tile.yCoord, tile.zCoord) == this.tile + tile.getWorldObj.getTileEntity( + tile.xCoord, + tile.yCoord, + tile.zCoord + ) == this.tile else false } diff --git a/src/main/scala/extracells/container/ContainerOreDictExport.java b/src/main/scala/extracells/container/ContainerOreDictExport.java index 5d734a839..94fc06563 100644 --- a/src/main/scala/extracells/container/ContainerOreDictExport.java +++ b/src/main/scala/extracells/container/ContainerOreDictExport.java @@ -1,54 +1,53 @@ package extracells.container; -import cpw.mods.fml.relauncher.Side; -import extracells.gui.GuiFluidInterface; -import extracells.network.packet.part.PacketOreDictExport; -import extracells.part.PartOreDictExporter; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.tileentity.TileEntity; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.gui.GuiFluidInterface; +import extracells.network.packet.part.PacketOreDictExport; +import extracells.part.PartOreDictExporter; + public class ContainerOreDictExport extends Container { - public PartOreDictExporter part; - public GuiFluidInterface gui; - EntityPlayer player; - - public ContainerOreDictExport(EntityPlayer player, PartOreDictExporter _part) { - this.player = player; - this.part = _part; - bindPlayerInventory(player.inventory); - TileEntity tile = this.part.getHostTile(); - if (tile != null && tile.hasWorldObj() && !tile.getWorldObj().isRemote) { - new PacketOreDictExport(player, this.part.filter, Side.CLIENT) - .sendPacketToPlayer(player); - } - } - - protected void bindPlayerInventory(IInventory inventoryPlayer) { - for (int i = 0; i < 3; ++i) { - for (int j = 0; j < 9; ++j) { - this.addSlotToContainer(new Slot(inventoryPlayer, - j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); - } - } - - for (int i = 0; i < 9; ++i) { - this.addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, - 142)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - @Override - protected void retrySlotClick(int p_75133_1_, int p_75133_2_, - boolean p_75133_3_, EntityPlayer p_75133_4_) { - - } + public PartOreDictExporter part; + + @SideOnly(Side.CLIENT) + public GuiFluidInterface gui; + + EntityPlayer player; + + public ContainerOreDictExport(EntityPlayer player, PartOreDictExporter _part) { + this.player = player; + this.part = _part; + bindPlayerInventory(player.inventory); + TileEntity tile = this.part.getHostTile(); + if (tile != null && tile.hasWorldObj() && !tile.getWorldObj().isRemote) { + new PacketOreDictExport(player, this.part.getFilter(), Side.CLIENT).sendPacketToPlayer(player); + } + } + + protected void bindPlayerInventory(IInventory inventoryPlayer) { + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 9; ++j) { + this.addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (int i = 0; i < 9; ++i) { + this.addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 142)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.part.isValid(); + } + + @Override + protected void retrySlotClick(int p_75133_1_, int p_75133_2_, boolean p_75133_3_, EntityPlayer p_75133_4_) {} } diff --git a/src/main/scala/extracells/container/ContainerPlaneFormation.java b/src/main/scala/extracells/container/ContainerPlaneFormation.java index 7380bf14f..4cf744c93 100644 --- a/src/main/scala/extracells/container/ContainerPlaneFormation.java +++ b/src/main/scala/extracells/container/ContainerPlaneFormation.java @@ -1,98 +1,110 @@ package extracells.container; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; + import appeng.api.AEApi; import appeng.api.implementations.guiobjects.IGuiItem; import appeng.api.implementations.guiobjects.INetworkTool; import appeng.api.util.DimensionalCoord; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; import extracells.container.slot.SlotNetworkTool; import extracells.container.slot.SlotRespective; import extracells.gui.GuiFluidPlaneFormation; import extracells.part.PartFluidPlaneFormation; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; public class ContainerPlaneFormation extends Container { - private GuiFluidPlaneFormation gui; - - public ContainerPlaneFormation(PartFluidPlaneFormation part, - EntityPlayer player) { - addSlotToContainer(new SlotRespective(part.getUpgradeInventory(), 0, - 187, 8)); - bindPlayerInventory(player.inventory); - - for (int i = 0; i < player.inventory.getSizeInventory(); i++) { - ItemStack stack = player.inventory.getStackInSlot(i); - if (stack != null - && AEApi.instance().definitions().items().networkTool().isSameAs(stack)) { - DimensionalCoord coord = part.getHost().getLocation(); - IGuiItem guiItem = (IGuiItem) stack.getItem(); - INetworkTool networkTool = (INetworkTool) guiItem.getGuiObject( - stack, coord.getWorld(), coord.x, coord.y, coord.z); - for (int j = 0; j < 3; j++) { - for (int k = 0; k < 3; k++) { - addSlotToContainer(new SlotNetworkTool(networkTool, j - + k * 3, 187 + k * 18, j * 18 + 102)); - } - } - return; - } - } - } - - protected void bindPlayerInventory(IInventory inventoryPlayer) { - for (int i = 0; i < 3; i++) { - for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 102)); - } - } - - for (int i = 0; i < 9; i++) { - addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 160)); - } - } - - @Override - public boolean canInteractWith(EntityPlayer entityplayer) { - return true; - } - - public void setGui(GuiFluidPlaneFormation _gui) { - this.gui = _gui; - } - - @Override - public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { - if (this.gui != null) - this.gui.shiftClick(getSlot(slotnumber).getStack()); - - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(slotnumber); - - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (slotnumber < 36) { - if (!mergeItemStack(itemstack1, 36, this.inventorySlots.size(), - true)) { - return null; - } - } else if (!mergeItemStack(itemstack1, 0, 36, false)) { - return null; - } - - if (itemstack1.stackSize == 0) { - slot.putStack(null); - } else { - slot.onSlotChanged(); - } - } - - return itemstack; - } + @SideOnly(Side.CLIENT) + private GuiFluidPlaneFormation gui; + + private PartFluidPlaneFormation part; + + public ContainerPlaneFormation(PartFluidPlaneFormation part, EntityPlayer player) { + this.part = part; + + this.addSlotToContainer(new SlotRespective(part.getUpgradeInventory(), 0, 187, 8)); + this.bindPlayerInventory(player.inventory); + + for (int i = 0; i < player.inventory.getSizeInventory(); i++) { + ItemStack stack = player.inventory.getStackInSlot(i); + if (stack != null && AEApi.instance().definitions().items().networkTool().isSameAs(stack)) { + DimensionalCoord coord = part.getHost().getLocation(); + IGuiItem guiItem = (IGuiItem) stack.getItem(); + INetworkTool networkTool = (INetworkTool) guiItem + .getGuiObject(stack, coord.getWorld(), coord.x, coord.y, coord.z); + for (int j = 0; j < 3; j++) { + for (int k = 0; k < 3; k++) { + this.addSlotToContainer( + new SlotNetworkTool(networkTool, j + k * 3, 187 + k * 18, j * 18 + 102)); + } + } + return; + } + } + } + + protected void bindPlayerInventory(IInventory inventoryPlayer) { + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 9; j++) { + this.addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 102)); + } + } + + for (int i = 0; i < 9; i++) { + this.addSlotToContainer(new Slot(inventoryPlayer, i, 8 + i * 18, 160)); + } + } + + @Override + public boolean canInteractWith(EntityPlayer player) { + return this.part.isValid(); + } + + @SideOnly(Side.CLIENT) + private void transferStackInSlotClient(int slotnumber) { + if (this.gui != null) { + this.gui.shiftClick(this.getSlot(slotnumber).getStack()); + } + } + + @SideOnly(Side.CLIENT) + public void setGui(GuiFluidPlaneFormation _gui) { + this.gui = _gui; + } + + @Override + public ItemStack transferStackInSlot(EntityPlayer player, int slotnumber) { + if (FMLCommonHandler.instance().getSide().isClient()) { + this.transferStackInSlotClient(slotnumber); + } + + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(slotnumber); + + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (slotnumber < 36) { + if (!this.mergeItemStack(itemstack1, 36, this.inventorySlots.size(), true)) { + return null; + } + } else if (!this.mergeItemStack(itemstack1, 0, 36, false)) { + return null; + } + + if (itemstack1.stackSize == 0) { + slot.putStack(null); + } else { + slot.onSlotChanged(); + } + } + return itemstack; + } } diff --git a/src/main/scala/extracells/container/ContainerVibrationChamberFluid.java b/src/main/scala/extracells/container/ContainerVibrationChamberFluid.java index f5ea53726..154661c3d 100644 --- a/src/main/scala/extracells/container/ContainerVibrationChamberFluid.java +++ b/src/main/scala/extracells/container/ContainerVibrationChamberFluid.java @@ -1,17 +1,17 @@ package extracells.container; -import extracells.tileentity.TileEntityVibrationChamberFluid; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; +import extracells.tileentity.TileEntityVibrationChamberFluid; + public class ContainerVibrationChamberFluid extends Container { public TileEntityVibrationChamberFluid tileentity; - public ContainerVibrationChamberFluid(InventoryPlayer player, - TileEntityVibrationChamberFluid tileentity) { + public ContainerVibrationChamberFluid(InventoryPlayer player, TileEntityVibrationChamberFluid tileentity) { this.tileentity = tileentity; bindPlayerInventory(player); @@ -20,8 +20,7 @@ public ContainerVibrationChamberFluid(InventoryPlayer player, protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { - addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, - 8 + j * 18, i * 18 + 84)); + addSlotToContainer(new Slot(inventoryPlayer, j + i * 9 + 9, 8 + j * 18, i * 18 + 84)); } } @@ -32,14 +31,14 @@ protected void bindPlayerInventory(InventoryPlayer inventoryPlayer) { @Override public boolean canInteractWith(EntityPlayer entityplayer) { - return tileentity.hasWorldObj() ? - tileentity.getWorldObj().getTileEntity(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) == this.tileentity : - false; + return tileentity.hasWorldObj() + ? tileentity.getWorldObj().getTileEntity(tileentity.xCoord, tileentity.yCoord, tileentity.zCoord) + == this.tileentity + : false; } @Override - protected void retrySlotClick(int par1, int par2, boolean par3, - EntityPlayer par4EntityPlayer) { + protected void retrySlotClick(int par1, int par2, boolean par3, EntityPlayer par4EntityPlayer) { // DON'T DO ANYTHING, YOU SHITTY METHOD! } } diff --git a/src/main/scala/extracells/container/IContainerListener.java b/src/main/scala/extracells/container/IContainerListener.java index a2ec94aee..a49a99401 100644 --- a/src/main/scala/extracells/container/IContainerListener.java +++ b/src/main/scala/extracells/container/IContainerListener.java @@ -2,6 +2,5 @@ public interface IContainerListener { - public void updateContainer(); - + public void updateContainer(); } diff --git a/src/main/scala/extracells/container/IStorageContainer.java b/src/main/scala/extracells/container/IStorageContainer.java index b87109ffc..127cf9300 100644 --- a/src/main/scala/extracells/container/IStorageContainer.java +++ b/src/main/scala/extracells/container/IStorageContainer.java @@ -1,8 +1,6 @@ package extracells.container; - public interface IStorageContainer { public boolean hasWirelessTermHandler(); - } diff --git a/src/main/scala/extracells/container/slot/SlotNetworkTool.java b/src/main/scala/extracells/container/slot/SlotNetworkTool.java index f25a6e0a3..d50dc70f5 100644 --- a/src/main/scala/extracells/container/slot/SlotNetworkTool.java +++ b/src/main/scala/extracells/container/slot/SlotNetworkTool.java @@ -1,29 +1,28 @@ package extracells.container.slot; -import appeng.api.implementations.guiobjects.INetworkTool; -import appeng.api.implementations.items.IUpgradeModule; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; +import appeng.api.implementations.guiobjects.INetworkTool; +import appeng.api.implementations.items.IUpgradeModule; + public class SlotNetworkTool extends Slot { - IInventory inventory; + IInventory inventory; - public SlotNetworkTool(INetworkTool inventory, int index, int x, int y) { - super(inventory, index, x, y); - this.inventory = inventory; - } + public SlotNetworkTool(INetworkTool inventory, int index, int x, int y) { + super(inventory, index, x, y); + this.inventory = inventory; + } - @Override - public boolean isItemValid(ItemStack itemStack) { - if (itemStack == null) - return false; - Item item = itemStack.getItem(); - if (!(item instanceof IUpgradeModule)) - return false; - IUpgradeModule upgradeModule = (IUpgradeModule) item; - return upgradeModule.getType(itemStack) != null; - } + @Override + public boolean isItemValid(ItemStack itemStack) { + if (itemStack == null) return false; + Item item = itemStack.getItem(); + if (!(item instanceof IUpgradeModule)) return false; + IUpgradeModule upgradeModule = (IUpgradeModule) item; + return upgradeModule.getType(itemStack) != null; + } } diff --git a/src/main/scala/extracells/container/slot/SlotPlayerInventory.java b/src/main/scala/extracells/container/slot/SlotPlayerInventory.java index d79a4c0fb..63c7c0d2e 100644 --- a/src/main/scala/extracells/container/slot/SlotPlayerInventory.java +++ b/src/main/scala/extracells/container/slot/SlotPlayerInventory.java @@ -1,31 +1,27 @@ package extracells.container.slot; -import extracells.container.IStorageContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; -public class SlotPlayerInventory extends Slot { +import extracells.container.IStorageContainer; - public final IStorageContainer container; +public class SlotPlayerInventory extends Slot { - public SlotPlayerInventory(IInventory arg0, - IStorageContainer _container, int arg1, int arg2, int arg3) { - super(arg0, arg1, arg2, arg3); - this.container = _container; - } + public final IStorageContainer container; - @Override - public boolean canTakeStack(EntityPlayer player) { - if (player == null || this.container == null) - return true; - ItemStack s = player.getCurrentEquippedItem(); - if (s == null || !this.container.hasWirelessTermHandler()) - return true; - if (s == this.inventory.getStackInSlot(getSlotIndex())) - return false; - return true; - } + public SlotPlayerInventory(IInventory arg0, IStorageContainer _container, int arg1, int arg2, int arg3) { + super(arg0, arg1, arg2, arg3); + this.container = _container; + } + @Override + public boolean canTakeStack(EntityPlayer player) { + if (player == null || this.container == null) return true; + ItemStack s = player.getCurrentEquippedItem(); + if (s == null || !this.container.hasWirelessTermHandler()) return true; + if (s == this.inventory.getStackInSlot(getSlotIndex())) return false; + return true; + } } diff --git a/src/main/scala/extracells/container/slot/SlotRespective.java b/src/main/scala/extracells/container/slot/SlotRespective.java index 24d923bc5..4e01a7adc 100644 --- a/src/main/scala/extracells/container/slot/SlotRespective.java +++ b/src/main/scala/extracells/container/slot/SlotRespective.java @@ -6,15 +6,15 @@ public class SlotRespective extends Slot { - IInventory inventory; + IInventory inventory; - public SlotRespective(IInventory inventory, int index, int x, int y) { - super(inventory, index, x, y); - this.inventory = inventory; - } + public SlotRespective(IInventory inventory, int index, int x, int y) { + super(inventory, index, x, y); + this.inventory = inventory; + } - @Override - public boolean isItemValid(ItemStack itemstack) { - return this.inventory.isItemValidForSlot(this.slotNumber, itemstack); - } + @Override + public boolean isItemValid(ItemStack itemstack) { + return this.inventory.isItemValidForSlot(this.slotNumber, itemstack); + } } diff --git a/src/main/scala/extracells/crafting/CraftingPattern.java b/src/main/scala/extracells/crafting/CraftingPattern.java index 6314386ba..b74bccdf8 100644 --- a/src/main/scala/extracells/crafting/CraftingPattern.java +++ b/src/main/scala/extracells/crafting/CraftingPattern.java @@ -1,11 +1,5 @@ package extracells.crafting; -import appeng.api.AEApi; -import appeng.api.networking.crafting.ICraftingPatternDetails; -import appeng.api.storage.data.IAEFluidStack; -import appeng.api.storage.data.IAEItemStack; -import extracells.api.crafting.IFluidCraftingPatternDetails; -import extracells.registries.ItemEnum; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -14,220 +8,200 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidContainerItem; -public class CraftingPattern implements IFluidCraftingPatternDetails, - Comparable { - - protected final ICraftingPatternDetails pattern; - - private IAEFluidStack[] fluidsCondensed = null; - private IAEFluidStack[] fluids = null; - - public CraftingPattern(ICraftingPatternDetails _pattern) { - this.pattern = _pattern; - } - - @Override - public boolean canSubstitute() { - return this.pattern.canSubstitute(); - } - - public int compareInt(int int1, int int2) { - if (int1 == int2) - return 0; - if (int1 < int2) - return -1; - return 1; - } - - @Override - public int compareTo(CraftingPattern o) { - return compareInt(o.getPriority(), this.getPriority()); - } - - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (this.getClass() != obj.getClass()) - return false; - CraftingPattern other = (CraftingPattern) obj; - if (this.pattern != null && other.pattern != null) - return this.pattern.equals(other.pattern); - return false; - } - - @Override - public IAEFluidStack[] getCondensedFluidInputs() { - if (this.fluidsCondensed == null) { - getCondensedInputs(); - } - return this.fluidsCondensed; - } - - @Override - public IAEItemStack[] getCondensedInputs() { - return removeFluidContainers(this.pattern.getCondensedInputs(), true); - } - - @Override - public IAEItemStack[] getCondensedOutputs() { - return this.pattern.getCondensedOutputs(); - } - - @Override - public IAEFluidStack[] getFluidInputs() { - if (this.fluids == null) { - getInputs(); - } - return this.fluids; - } - - @Override - public IAEItemStack[] getInputs() { - return removeFluidContainers(this.pattern.getInputs(), false); - } - - @Override - public ItemStack getOutput(InventoryCrafting craftingInv, World world) { - IAEItemStack[] input = this.pattern.getInputs(); - for (int i = 0; i < input.length; i++) { - IAEItemStack stack = input[i]; - if (stack != null - && FluidContainerRegistry.isFilledContainer(stack - .getItemStack())) { - try { - craftingInv.setInventorySlotContents(i, - input[i].getItemStack()); - } catch (Throwable e) {} - } else if (stack != null - && stack.getItem() instanceof IFluidContainerItem) { - try { - craftingInv.setInventorySlotContents(i, - input[i].getItemStack()); - } catch (Throwable e) {} - } - } - ItemStack returnStack = this.pattern.getOutput(craftingInv, world); - for (int i = 0; i < input.length; i++) { - IAEItemStack stack = input[i]; - if (stack != null - && FluidContainerRegistry.isFilledContainer(stack - .getItemStack())) { - craftingInv.setInventorySlotContents(i, null); - } else if (stack != null - && stack.getItem() instanceof IFluidContainerItem) { - craftingInv.setInventorySlotContents(i, null); - } - } - return returnStack; - } - - @Override - public IAEItemStack[] getOutputs() { - return this.pattern.getOutputs(); - } - - @Override - public ItemStack getPattern() { - ItemStack p = this.pattern.getPattern(); - if (p == null) - return null; - ItemStack s = new ItemStack(ItemEnum.CRAFTINGPATTERN.getItem()); - NBTTagCompound tag = new NBTTagCompound(); - tag.setTag("item", p.writeToNBT(new NBTTagCompound())); - s.setTagCompound(tag); - return s; - } - - @Override - public int getPriority() { - return this.pattern.getPriority(); - } - - @Override - public boolean isCraftable() { - return this.pattern.isCraftable(); - } - - @Override - public boolean isValidItemForSlot(int slotIndex, ItemStack itemStack, - World world) { - return this.pattern.isValidItemForSlot(slotIndex, itemStack, world); - } - - public IAEItemStack[] removeFluidContainers(IAEItemStack[] requirements, - boolean isCondenced) { - - IAEItemStack[] returnStack = new IAEItemStack[requirements.length]; - - IAEFluidStack[] fluidStacks = new IAEFluidStack[requirements.length]; - - int removed = 0; - int i = 0; - for (IAEItemStack currentRequirement : requirements) { - - if (currentRequirement != null) { - ItemStack current = currentRequirement.getItemStack(); - current.stackSize = 1; - FluidStack fluid = null; - if (FluidContainerRegistry.isFilledContainer(current)) { - fluid = FluidContainerRegistry - .getFluidForFilledItem(current); - } else if (currentRequirement.getItem() instanceof IFluidContainerItem) { - fluid = ((IFluidContainerItem) currentRequirement.getItem()) - .getFluid(current); - } - if (fluid == null) { - returnStack[i] = currentRequirement; - } else { - removed++; - fluidStacks[i] = AEApi - .instance() - .storage() - .createFluidStack( - new FluidStack( - fluid.getFluid(), - (int) (fluid.amount * currentRequirement - .getStackSize()))); - } - } - i++; - } - - if (isCondenced) { - int i2 = 0; - IAEFluidStack[] fluids = new IAEFluidStack[removed]; - for (IAEFluidStack fluid : fluidStacks) { - if (fluid != null) { - fluids[i2] = fluid; - i2++; - } - } - int i3 = 0; - IAEItemStack[] items = new IAEItemStack[requirements.length - - removed]; - for (IAEItemStack item : returnStack) { - if (item != null) { - items[i3] = item; - i3++; - } - } - returnStack = items; - this.fluidsCondensed = fluids; - } else { - this.fluids = fluidStacks; - } - return returnStack; - } - - @Override - public void setPriority(int priority) { - this.pattern.setPriority(priority); - } - - @Override - public int hashCode(){ - return this.pattern.hashCode(); - } +import appeng.api.AEApi; +import appeng.api.networking.crafting.ICraftingPatternDetails; +import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IAEItemStack; +import extracells.api.crafting.IFluidCraftingPatternDetails; +import extracells.registries.ItemEnum; +public class CraftingPattern implements IFluidCraftingPatternDetails, Comparable { + + protected final ICraftingPatternDetails pattern; + + private IAEFluidStack[] fluidsCondensed = null; + private IAEFluidStack[] fluids = null; + + public CraftingPattern(ICraftingPatternDetails _pattern) { + this.pattern = _pattern; + } + + @Override + public boolean canSubstitute() { + return this.pattern.canSubstitute(); + } + + public int compareInt(int int1, int int2) { + if (int1 == int2) return 0; + if (int1 < int2) return -1; + return 1; + } + + @Override + public int compareTo(CraftingPattern o) { + return compareInt(o.getPriority(), this.getPriority()); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) return false; + if (this.getClass() != obj.getClass()) return false; + CraftingPattern other = (CraftingPattern) obj; + if (this.pattern != null && other.pattern != null) return this.pattern.equals(other.pattern); + return false; + } + + @Override + public IAEFluidStack[] getCondensedFluidInputs() { + if (this.fluidsCondensed == null) { + getCondensedInputs(); + } + return this.fluidsCondensed; + } + + @Override + public IAEItemStack[] getCondensedInputs() { + return removeFluidContainers(this.pattern.getCondensedInputs(), true); + } + + @Override + public IAEItemStack[] getCondensedOutputs() { + return this.pattern.getCondensedOutputs(); + } + + @Override + public IAEFluidStack[] getFluidInputs() { + if (this.fluids == null) { + getInputs(); + } + return this.fluids; + } + + @Override + public IAEItemStack[] getInputs() { + return removeFluidContainers(this.pattern.getInputs(), false); + } + + @Override + public ItemStack getOutput(InventoryCrafting craftingInv, World world) { + IAEItemStack[] input = this.pattern.getInputs(); + for (int i = 0; i < input.length; i++) { + IAEItemStack stack = input[i]; + if (stack != null && FluidContainerRegistry.isFilledContainer(stack.getItemStack())) { + try { + craftingInv.setInventorySlotContents(i, input[i].getItemStack()); + } catch (Throwable e) {} + } else if (stack != null && stack.getItem() instanceof IFluidContainerItem) { + try { + craftingInv.setInventorySlotContents(i, input[i].getItemStack()); + } catch (Throwable e) {} + } + } + ItemStack returnStack = this.pattern.getOutput(craftingInv, world); + for (int i = 0; i < input.length; i++) { + IAEItemStack stack = input[i]; + if (stack != null && FluidContainerRegistry.isFilledContainer(stack.getItemStack())) { + craftingInv.setInventorySlotContents(i, null); + } else if (stack != null && stack.getItem() instanceof IFluidContainerItem) { + craftingInv.setInventorySlotContents(i, null); + } + } + return returnStack; + } + + @Override + public IAEItemStack[] getOutputs() { + return this.pattern.getOutputs(); + } + + @Override + public ItemStack getPattern() { + ItemStack p = this.pattern.getPattern(); + if (p == null) return null; + ItemStack s = new ItemStack(ItemEnum.CRAFTINGPATTERN.getItem()); + NBTTagCompound tag = new NBTTagCompound(); + tag.setTag("item", p.writeToNBT(new NBTTagCompound())); + s.setTagCompound(tag); + return s; + } + + @Override + public int getPriority() { + return this.pattern.getPriority(); + } + + @Override + public boolean isCraftable() { + return this.pattern.isCraftable(); + } + + @Override + public boolean isValidItemForSlot(int slotIndex, ItemStack itemStack, World world) { + return this.pattern.isValidItemForSlot(slotIndex, itemStack, world); + } + + public IAEItemStack[] removeFluidContainers(IAEItemStack[] requirements, boolean isCondenced) { + + IAEItemStack[] returnStack = new IAEItemStack[requirements.length]; + + IAEFluidStack[] fluidStacks = new IAEFluidStack[requirements.length]; + + int removed = 0; + int i = 0; + for (IAEItemStack currentRequirement : requirements) { + + if (currentRequirement != null) { + ItemStack current = currentRequirement.getItemStack(); + current.stackSize = 1; + FluidStack fluid = null; + if (FluidContainerRegistry.isFilledContainer(current)) { + fluid = FluidContainerRegistry.getFluidForFilledItem(current); + } else if (currentRequirement.getItem() instanceof IFluidContainerItem) { + fluid = ((IFluidContainerItem) currentRequirement.getItem()).getFluid(current); + } + if (fluid == null) { + returnStack[i] = currentRequirement; + } else { + removed++; + fluidStacks[i] = AEApi.instance().storage().createFluidStack( + new FluidStack(fluid.getFluid(), (int) (fluid.amount * currentRequirement.getStackSize()))); + } + } + i++; + } + + if (isCondenced) { + int i2 = 0; + IAEFluidStack[] fluids = new IAEFluidStack[removed]; + for (IAEFluidStack fluid : fluidStacks) { + if (fluid != null) { + fluids[i2] = fluid; + i2++; + } + } + int i3 = 0; + IAEItemStack[] items = new IAEItemStack[requirements.length - removed]; + for (IAEItemStack item : returnStack) { + if (item != null) { + items[i3] = item; + i3++; + } + } + returnStack = items; + this.fluidsCondensed = fluids; + } else { + this.fluids = fluidStacks; + } + return returnStack; + } + + @Override + public void setPriority(int priority) { + this.pattern.setPriority(priority); + } + + @Override + public int hashCode() { + return this.pattern.hashCode(); + } } diff --git a/src/main/scala/extracells/crafting/CraftingPattern2.java b/src/main/scala/extracells/crafting/CraftingPattern2.java index 078b65423..6f2c04943 100644 --- a/src/main/scala/extracells/crafting/CraftingPattern2.java +++ b/src/main/scala/extracells/crafting/CraftingPattern2.java @@ -1,139 +1,104 @@ package extracells.crafting; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; + import appeng.api.AEApi; import appeng.api.networking.crafting.ICraftingPatternDetails; import appeng.api.storage.data.IAEItemStack; import extracells.registries.ItemEnum; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; public class CraftingPattern2 extends CraftingPattern { - private boolean needExtra = false; - - public CraftingPattern2(ICraftingPatternDetails _pattern) { - super(_pattern); - } + private boolean needExtra = false; - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (this.getClass() != obj.getClass()) - return false; - CraftingPattern other = (CraftingPattern) obj; - if (this.pattern != null && other.pattern != null) - return this.pattern.equals(other.pattern); - return false; - } + public CraftingPattern2(ICraftingPatternDetails _pattern) { + super(_pattern); + } - @Override - public IAEItemStack[] getCondensedInputs() { - IAEItemStack[] s = super.getCondensedInputs(); - if (s.length == 0) { - s = new IAEItemStack[1]; - s[0] = AEApi - .instance() - .storage() - .createItemStack( - new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); - this.needExtra = true; - } - return s; - } + @Override + public boolean equals(Object obj) { + if (obj == null) return false; + if (this.getClass() != obj.getClass()) return false; + CraftingPattern other = (CraftingPattern) obj; + if (this.pattern != null && other.pattern != null) return this.pattern.equals(other.pattern); + return false; + } - @Override - public IAEItemStack[] getCondensedOutputs() { - getCondensedInputs(); - IAEItemStack[] s = super.getCondensedOutputs(); - if (this.needExtra) { - IAEItemStack[] s2 = new IAEItemStack[s.length + 1]; - for (int i = 0; i < s.length; i++) { - s2[i] = s[i]; - } - s2[s.length] = AEApi - .instance() - .storage() - .createItemStack( - new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); - return s2; - } - return s; - } + @Override + public IAEItemStack[] getCondensedInputs() { + IAEItemStack[] s = super.getCondensedInputs(); + if (s.length == 0) { + s = new IAEItemStack[1]; + s[0] = AEApi.instance().storage().createItemStack(new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); + this.needExtra = true; + } + return s; + } - @Override - public IAEItemStack[] getInputs() { - IAEItemStack[] in = super.getInputs(); - if (in.length == 0) { - in = new IAEItemStack[1]; - in[0] = AEApi - .instance() - .storage() - .createItemStack( - new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); - } else { - for (IAEItemStack s : in) { - if (s != null) - return in; - } - in[0] = AEApi - .instance() - .storage() - .createItemStack( - new ItemStack(ItemEnum.FLUIDPATTERN.getItem()));; - } - return in; - } + @Override + public IAEItemStack[] getCondensedOutputs() { + getCondensedInputs(); + IAEItemStack[] s = super.getCondensedOutputs(); + if (this.needExtra) { + IAEItemStack[] s2 = new IAEItemStack[s.length + 1]; + for (int i = 0; i < s.length; i++) { + s2[i] = s[i]; + } + s2[s.length] = AEApi.instance().storage().createItemStack(new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); + return s2; + } + return s; + } - @Override - public IAEItemStack[] getOutputs() { - IAEItemStack[] out = super.getOutputs(); - getCondensedInputs(); - if (!this.needExtra) - return out; - if (out.length == 0) { - out = new IAEItemStack[1]; - out[0] = AEApi - .instance() - .storage() - .createItemStack( - new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); - } else { - for (int i = 0; i < out.length; i++) { - if (out[i] == null) { - out[i] = AEApi - .instance() - .storage() - .createItemStack( - new ItemStack(ItemEnum.FLUIDPATTERN - .getItem())); - return out; - } - } - IAEItemStack[] s2 = new IAEItemStack[out.length + 1]; - for (int i = 0; i < out.length; i++) { - s2[i] = out[i]; - } - s2[out.length] = AEApi - .instance() - .storage() - .createItemStack( - new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); - return s2; - } - return out; - } + @Override + public IAEItemStack[] getInputs() { + IAEItemStack[] in = super.getInputs(); + if (in.length == 0) { + in = new IAEItemStack[1]; + in[0] = AEApi.instance().storage().createItemStack(new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); + } else { + for (IAEItemStack s : in) { + if (s != null) return in; + } + in[0] = AEApi.instance().storage().createItemStack(new ItemStack(ItemEnum.FLUIDPATTERN.getItem()));; + } + return in; + } - @Override - public ItemStack getPattern() { - ItemStack p = this.pattern.getPattern(); - if (p == null) - return null; - ItemStack s = new ItemStack(ItemEnum.CRAFTINGPATTERN.getItem(), 1, 1); - NBTTagCompound tag = new NBTTagCompound(); - tag.setTag("item", p.writeToNBT(new NBTTagCompound())); - s.setTagCompound(tag); - return s; - } + @Override + public IAEItemStack[] getOutputs() { + IAEItemStack[] out = super.getOutputs(); + getCondensedInputs(); + if (!this.needExtra) return out; + if (out.length == 0) { + out = new IAEItemStack[1]; + out[0] = AEApi.instance().storage().createItemStack(new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); + } else { + for (int i = 0; i < out.length; i++) { + if (out[i] == null) { + out[i] = AEApi.instance().storage().createItemStack(new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); + return out; + } + } + IAEItemStack[] s2 = new IAEItemStack[out.length + 1]; + for (int i = 0; i < out.length; i++) { + s2[i] = out[i]; + } + s2[out.length] = AEApi.instance().storage().createItemStack(new ItemStack(ItemEnum.FLUIDPATTERN.getItem())); + return s2; + } + return out; + } + @Override + public ItemStack getPattern() { + ItemStack p = this.pattern.getPattern(); + if (p == null) return null; + ItemStack s = new ItemStack(ItemEnum.CRAFTINGPATTERN.getItem(), 1, 1); + NBTTagCompound tag = new NBTTagCompound(); + tag.setTag("item", p.writeToNBT(new NBTTagCompound())); + s.setTagCompound(tag); + return s; + } } diff --git a/src/main/scala/extracells/definitions/BlockDefinition.java b/src/main/scala/extracells/definitions/BlockDefinition.java index cfa060f6a..00fdab012 100644 --- a/src/main/scala/extracells/definitions/BlockDefinition.java +++ b/src/main/scala/extracells/definitions/BlockDefinition.java @@ -7,36 +7,50 @@ public class BlockDefinition implements IBlockDefinition { - public static final BlockDefinition instance = new BlockDefinition(); - - @Override - public ITileDefinition blockInterface() { - return new BlockItemDefinitions(BlockEnum.ECBASEBLOCK.getBlock(), - TileEntityFluidInterface.class); - } - - @Override - public ITileDefinition certusTank() { - return new BlockItemDefinitions(BlockEnum.CERTUSTANK.getBlock(), - TileEntityCertusTank.class); - } - - @Override - public ITileDefinition fluidCrafter() { - return new BlockItemDefinitions(BlockEnum.FLUIDCRAFTER.getBlock(), - TileEntityFluidCrafter.class); - } - - @Override - public ITileDefinition fluidFiller() { - return new BlockItemDefinitions(BlockEnum.FLUIDCRAFTER.getBlock(), 1, - TileEntityFluidFiller.class); - } - - @Override - public ITileDefinition walrus() { - return new BlockItemDefinitions(BlockEnum.WALRUS.getBlock(), - TileEntityWalrus.class); - } - + public static final BlockDefinition instance = new BlockDefinition(); + + @Override + public ITileDefinition blockInterface() { + return new BlockItemDefinitions(BlockEnum.ECBASEBLOCK.getBlock(), TileEntityFluidInterface.class); + } + + @Override + public ITileDefinition certusTank() { + return new BlockItemDefinitions(BlockEnum.CERTUSTANK.getBlock(), TileEntityCertusTank.class); + } + + @Override + public ITileDefinition fluidCrafter() { + return new BlockItemDefinitions(BlockEnum.FLUIDCRAFTER.getBlock(), TileEntityFluidCrafter.class); + } + + @Override + public ITileDefinition fluidFiller() { + return new BlockItemDefinitions(BlockEnum.FLUIDCRAFTER.getBlock(), 1, TileEntityFluidFiller.class); + } + + @Override + public ITileDefinition walrus() { + return new BlockItemDefinitions(BlockEnum.WALRUS.getBlock(), TileEntityWalrus.class); + } + + @Override + public ITileDefinition craftingStorage256k() { + return new BlockItemDefinitions(BlockEnum.CRAFTINGSTORAGE.getBlock(), 0, TileEntityCraftingStorage.class); + } + + @Override + public ITileDefinition craftingStorage1024k() { + return new BlockItemDefinitions(BlockEnum.CRAFTINGSTORAGE.getBlock(), 1, TileEntityCraftingStorage.class); + } + + @Override + public ITileDefinition craftingStorage4096k() { + return new BlockItemDefinitions(BlockEnum.CRAFTINGSTORAGE.getBlock(), 2, TileEntityCraftingStorage.class); + } + + @Override + public ITileDefinition craftingStorage16384k() { + return new BlockItemDefinitions(BlockEnum.CRAFTINGSTORAGE.getBlock(), 3, TileEntityCraftingStorage.class); + } } diff --git a/src/main/scala/extracells/definitions/BlockItemDefinitions.java b/src/main/scala/extracells/definitions/BlockItemDefinitions.java index 280d4f9f7..6cbcb0b15 100644 --- a/src/main/scala/extracells/definitions/BlockItemDefinitions.java +++ b/src/main/scala/extracells/definitions/BlockItemDefinitions.java @@ -1,7 +1,5 @@ package extracells.definitions; -import appeng.api.definitions.ITileDefinition; -import com.google.common.base.Optional; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; @@ -9,70 +7,72 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; +import com.google.common.base.Optional; + +import appeng.api.definitions.ITileDefinition; + public class BlockItemDefinitions implements ITileDefinition { - private final Block block; - private final int meta; - private final Class blockTileEntity; - - public BlockItemDefinitions(Block _block) { - this(_block, 0); - } - - public BlockItemDefinitions(Block _block, - Class _blockTileEntity) { - this(_block, 0, _blockTileEntity); - } - - public BlockItemDefinitions(Block _block, int _meta) { - this(_block, _meta, null); - } - - public BlockItemDefinitions(Block _block, int _meta, - Class _blockTileEntity) { - this.block = _block; - this.meta = _meta; - this.blockTileEntity = _blockTileEntity; - } - - @Override - public Optional maybeBlock() { - return Optional.fromNullable(block); - } - - @Override - public Optional maybeItemBlock() { - return Optional.absent(); - } - - @Override - public boolean isSameAs(ItemStack comparableStack) { - return comparableStack != null && ItemStack.areItemStacksEqual(maybeStack(1).orNull(), comparableStack); - } - - @Override - public boolean isSameAs(IBlockAccess world, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - return !maybeBlock().isPresent() && block == this.block; - } - - @Override - public Optional maybeItem() { - return Optional.fromNullable(Item.getItemFromBlock(block)); - } - - @Override - public Optional maybeStack(int stackSize) { - return Optional.of(new ItemStack(this.block, stackSize, this.meta)); - } - - @Override - public boolean isEnabled() { - return true; - } - - @Override - public Optional> maybeEntity() { - return Optional.fromNullable(this.blockTileEntity); - } + private final Block block; + private final int meta; + private final Class blockTileEntity; + + public BlockItemDefinitions(Block _block) { + this(_block, 0); + } + + public BlockItemDefinitions(Block _block, Class _blockTileEntity) { + this(_block, 0, _blockTileEntity); + } + + public BlockItemDefinitions(Block _block, int _meta) { + this(_block, _meta, null); + } + + public BlockItemDefinitions(Block _block, int _meta, Class _blockTileEntity) { + this.block = _block; + this.meta = _meta; + this.blockTileEntity = _blockTileEntity; + } + + @Override + public Optional maybeBlock() { + return Optional.fromNullable(block); + } + + @Override + public Optional maybeItemBlock() { + return Optional.absent(); + } + + @Override + public boolean isSameAs(ItemStack comparableStack) { + return comparableStack != null && ItemStack.areItemStacksEqual(maybeStack(1).orNull(), comparableStack); + } + + @Override + public boolean isSameAs(IBlockAccess world, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + return !maybeBlock().isPresent() && block == this.block; + } + + @Override + public Optional maybeItem() { + return Optional.fromNullable(Item.getItemFromBlock(block)); + } + + @Override + public Optional maybeStack(int stackSize) { + return Optional.of(new ItemStack(this.block, stackSize, this.meta)); + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public Optional> maybeEntity() { + return Optional.fromNullable(this.blockTileEntity); + } } diff --git a/src/main/scala/extracells/definitions/ItemDefinition.java b/src/main/scala/extracells/definitions/ItemDefinition.java index d71cd3e77..508dc1b37 100644 --- a/src/main/scala/extracells/definitions/ItemDefinition.java +++ b/src/main/scala/extracells/definitions/ItemDefinition.java @@ -5,146 +5,166 @@ public class ItemDefinition implements IItemDefinition { - public static final ItemDefinition instance = new ItemDefinition(); - - @Override - public appeng.api.definitions.IItemDefinition cell1024kPart() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 1); - } - - @Override - public appeng.api.definitions.IItemDefinition cell1024kPartFluid() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 9); - } - - @Override - public appeng.api.definitions.IItemDefinition cell16384kPart() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 3); - } - - @Override - public appeng.api.definitions.IItemDefinition cell16kPartFluid() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 6); - } - - // Fluid Storage Components - @Override - public appeng.api.definitions.IItemDefinition cell1kPartFluid() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 4); - } - - // Physical Storage Components - @Override - public appeng.api.definitions.IItemDefinition cell256kPart() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem()); - } - - @Override - public appeng.api.definitions.IItemDefinition cell256kPartFluid() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 8); - } - - @Override - public appeng.api.definitions.IItemDefinition cell4096kPart() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 2); - } - - @Override - public appeng.api.definitions.IItemDefinition cell4096kPartFluid() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 10); - } - - @Override - public appeng.api.definitions.IItemDefinition cell4kPartFluid() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 5); - } - - @Override - public appeng.api.definitions.IItemDefinition cell64kPartFluid() { - return new ItemItemDefinitions(ItemEnum.STORAGECOMPONET.getItem(), 7); - } - - // Fluid Storage - @Override - public appeng.api.definitions.IItemDefinition fluidCasing() { - return new ItemItemDefinitions(ItemEnum.STORAGECASING.getItem(), 1); - } - - @Override - public appeng.api.definitions.IItemDefinition fluidCell1024k() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 5); - } - - @Override - public appeng.api.definitions.IItemDefinition fluidCell16k() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 2); - } - - // Fluid Cells - @Override - public appeng.api.definitions.IItemDefinition fluidCell1k() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem()); - } - - @Override - public appeng.api.definitions.IItemDefinition fluidCell256k() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 4); - } - - @Override - public appeng.api.definitions.IItemDefinition fluidCell4096k() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 6); - } - - @Override - public appeng.api.definitions.IItemDefinition fluidCell4k() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 1); - } - - @Override - public appeng.api.definitions.IItemDefinition fluidCell64k() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 3); - } - - @Override - public appeng.api.definitions.IItemDefinition fluidCellPortable() { - return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGEPORTABLE.getItem()); - } - - // Physical Storage Casing - @Override - public appeng.api.definitions.IItemDefinition physCasing() { - return new ItemItemDefinitions(ItemEnum.STORAGECASING.getItem()); - } - - @Override - public appeng.api.definitions.IItemDefinition physCell1024k() { - return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 1); - } - - @Override - public appeng.api.definitions.IItemDefinition physCell16384k() { - return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 3); - } - - // Physical Cells - @Override - public appeng.api.definitions.IItemDefinition physCell256k() { - return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem()); - } - - @Override - public appeng.api.definitions.IItemDefinition physCell4096k() { - return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 2); - } - - @Override - public appeng.api.definitions.IItemDefinition physCellContainer() { - return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 4); - } - - @Override - public appeng.api.definitions.IItemDefinition wirelessFluidTerminal() { - return new ItemItemDefinitions(ItemEnum.FLUIDWIRELESSTERMINAL.getItem()); - } + public static final ItemDefinition instance = new ItemDefinition(); + + @Override + public appeng.api.definitions.IItemDefinition cell1024kPart() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 1); + } + + @Override + public appeng.api.definitions.IItemDefinition cell1024kPartFluid() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 9); + } + + @Override + public appeng.api.definitions.IItemDefinition cell16384kPart() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 3); + } + + @Override + public appeng.api.definitions.IItemDefinition cell16kPartFluid() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 6); + } + + // Fluid Storage Components + @Override + public appeng.api.definitions.IItemDefinition cell1kPartFluid() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 4); + } + + // Physical Storage Components + @Override + public appeng.api.definitions.IItemDefinition cell256kPart() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition cell256kPartFluid() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 8); + } + + @Override + public appeng.api.definitions.IItemDefinition cell4096kPart() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 2); + } + + @Override + public appeng.api.definitions.IItemDefinition cell4096kPartFluid() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 10); + } + + @Override + public appeng.api.definitions.IItemDefinition cell4kPartFluid() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 5); + } + + @Override + public appeng.api.definitions.IItemDefinition cell64kPartFluid() { + return new ItemItemDefinitions(ItemEnum.STORAGECOMPONENT.getItem(), 7); + } + + // Fluid Storage + @Override + public appeng.api.definitions.IItemDefinition fluidCasing() { + return new ItemItemDefinitions(ItemEnum.STORAGECASING.getItem(), 1); + } + + @Override + public appeng.api.definitions.IItemDefinition fluidCell1024k() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 5); + } + + @Override + public appeng.api.definitions.IItemDefinition fluidCell16k() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 2); + } + + // Fluid Cells + @Override + public appeng.api.definitions.IItemDefinition fluidCell1k() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition fluidCell256k() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 4); + } + + @Override + public appeng.api.definitions.IItemDefinition fluidCell4096k() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 6); + } + + @Override + public appeng.api.definitions.IItemDefinition fluidCell4k() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 1); + } + + @Override + public appeng.api.definitions.IItemDefinition fluidCell64k() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGE.getItem(), 3); + } + + @Override + public appeng.api.definitions.IItemDefinition fluidCellPortable() { + return new ItemItemDefinitions(ItemEnum.FLUIDSTORAGEPORTABLE.getItem()); + } + + // Physical Storage Casing + @Override + public appeng.api.definitions.IItemDefinition physCasing() { + return new ItemItemDefinitions(ItemEnum.STORAGECASING.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition physCell1024k() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 1); + } + + @Override + public appeng.api.definitions.IItemDefinition physCell16384k() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 3); + } + + // Physical Cells + @Override + public appeng.api.definitions.IItemDefinition physCell256k() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition physCell4096k() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 2); + } + + @Override + public appeng.api.definitions.IItemDefinition physCellContainer() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGE.getItem(), 4); + } + + @Override + public appeng.api.definitions.IItemDefinition physCellAdvancedSingularity() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGESINGULARITY.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition physCellAdvancedQuantum() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGEQUANTUM.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition physCellVoid() { + return new ItemItemDefinitions(ItemEnum.PHYSICALSTORAGEVOID.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition wirelessFluidTerminal() { + return new ItemItemDefinitions(ItemEnum.FLUIDWIRELESSTERMINAL.getItem()); + } + + @Override + public appeng.api.definitions.IItemDefinition itemFluidPattern() { + return new ItemItemDefinitions(ItemEnum.FLUIDPATTERN.getItem()); + } } diff --git a/src/main/scala/extracells/definitions/ItemItemDefinitions.java b/src/main/scala/extracells/definitions/ItemItemDefinitions.java index c22dffa36..70cb85438 100644 --- a/src/main/scala/extracells/definitions/ItemItemDefinitions.java +++ b/src/main/scala/extracells/definitions/ItemItemDefinitions.java @@ -1,41 +1,43 @@ package extracells.definitions; -import appeng.api.definitions.IItemDefinition; -import com.google.common.base.Optional; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.IBlockAccess; +import com.google.common.base.Optional; + +import appeng.api.definitions.IItemDefinition; + public class ItemItemDefinitions implements IItemDefinition { - public final Item item; - public final int meta; + public final Item item; + public final int meta; - public ItemItemDefinitions(Item _item) { - this(_item, 0); - } + public ItemItemDefinitions(Item _item) { + this(_item, 0); + } - public ItemItemDefinitions(Item _item, int _meta) { - this.item = _item; - this.meta = _meta; - } + public ItemItemDefinitions(Item _item, int _meta) { + this.item = _item; + this.meta = _meta; + } - @Override - public Optional maybeItem() { - return Optional.fromNullable(this.item); - } + @Override + public Optional maybeItem() { + return Optional.fromNullable(this.item); + } @Override public Optional maybeStack(int stackSize) { return Optional.of(new ItemStack(this.item, stackSize, this.meta)); } - @Override - public boolean isEnabled() { - return true; - } + @Override + public boolean isEnabled() { + return true; + } - @Override + @Override public boolean isSameAs(ItemStack comparableStack) { return comparableStack != null && comparableStack.isItemEqual(maybeStack(1).get()); } diff --git a/src/main/scala/extracells/definitions/PartDefinition.java b/src/main/scala/extracells/definitions/PartDefinition.java index 8c4cab4a5..f79e5241f 100644 --- a/src/main/scala/extracells/definitions/PartDefinition.java +++ b/src/main/scala/extracells/definitions/PartDefinition.java @@ -7,84 +7,70 @@ public class PartDefinition implements IPartDefinition { - public static final PartDefinition instance = new PartDefinition(); - - @Override - public IItemDefinition partBattery() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.BATTERY.ordinal()); - } - - @Override - public IItemDefinition partConversionMonitor() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDCONVERSIONMONITOR.ordinal()); - } - - @Override - public IItemDefinition partDrive() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.DRIVE.ordinal()); - } - - @Override - public IItemDefinition partFluidAnnihilationPlane() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDPANEANNIHILATION.ordinal()); - } - - @Override - public IItemDefinition partFluidExportBus() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDIMPORT.ordinal()); - } - - @Override - public IItemDefinition partFluidFormationPlane() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDPANEFORMATION.ordinal()); - } - - @Override - public IItemDefinition partFluidImportBus() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDEXPORT.ordinal()); - } - - @Override - public IItemDefinition partFluidLevelEmitter() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDLEVELEMITTER.ordinal()); - } - - @Override - public IItemDefinition partFluidStorageBus() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDSTORAGE.ordinal()); - } - - @Override - public IItemDefinition partFluidTerminal() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDTERMINAL.ordinal()); - } - - @Override - public IItemDefinition partInterface() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.INTERFACE.ordinal()); - } - - @Override - public IItemDefinition partOreDictExportBus() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.OREDICTEXPORTBUS.ordinal()); - } - - @Override - public IItemDefinition partStorageMonitor() { - return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), - PartEnum.FLUIDMONITOR.ordinal()); - } - + public static final PartDefinition instance = new PartDefinition(); + + @Override + public IItemDefinition partBattery() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.BATTERY.ordinal()); + } + + @Override + public IItemDefinition partConversionMonitor() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDCONVERSIONMONITOR.ordinal()); + } + + @Override + public IItemDefinition partDrive() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.DRIVE.ordinal()); + } + + @Override + public IItemDefinition partFluidAnnihilationPlane() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDPANEANNIHILATION.ordinal()); + } + + @Override + public IItemDefinition partFluidExportBus() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDIMPORT.ordinal()); + } + + @Override + public IItemDefinition partFluidFormationPlane() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDPANEFORMATION.ordinal()); + } + + @Override + public IItemDefinition partFluidImportBus() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDEXPORT.ordinal()); + } + + @Override + public IItemDefinition partFluidLevelEmitter() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDLEVELEMITTER.ordinal()); + } + + @Override + public IItemDefinition partFluidStorageBus() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDSTORAGE.ordinal()); + } + + @Override + public IItemDefinition partFluidTerminal() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDTERMINAL.ordinal()); + } + + @Override + public IItemDefinition partInterface() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.INTERFACE.ordinal()); + } + + @Override + public IItemDefinition partOreDictExportBus() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.OREDICTEXPORTBUS.ordinal()); + } + + @Override + public IItemDefinition partStorageMonitor() { + return new ItemItemDefinitions(ItemEnum.PARTITEM.getItem(), PartEnum.FLUIDMONITOR.ordinal()); + } } diff --git a/src/main/scala/extracells/gridblock/Constants.java b/src/main/scala/extracells/gridblock/Constants.java new file mode 100644 index 000000000..84950e06a --- /dev/null +++ b/src/main/scala/extracells/gridblock/Constants.java @@ -0,0 +1,10 @@ +package extracells.gridblock; + +import java.util.EnumSet; + +import appeng.api.networking.GridFlags; + +class Constants { + + static final EnumSet BASE_GRID_FLAGS = EnumSet.of(GridFlags.REQUIRE_CHANNEL); +} diff --git a/src/main/scala/extracells/gridblock/ECBaseGridBlock.java b/src/main/scala/extracells/gridblock/ECBaseGridBlock.java index d3ed75e58..bf0e41b64 100644 --- a/src/main/scala/extracells/gridblock/ECBaseGridBlock.java +++ b/src/main/scala/extracells/gridblock/ECBaseGridBlock.java @@ -1,5 +1,10 @@ package extracells.gridblock; +import java.util.EnumSet; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.networking.*; import appeng.api.networking.storage.IStorageGrid; import appeng.api.parts.PartItemStack; @@ -8,85 +13,77 @@ import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; import extracells.part.PartECBase; -import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.ForgeDirection; - -import java.util.EnumSet; public class ECBaseGridBlock implements IGridBlock { - protected AEColor color; - protected IGrid grid; - protected int usedChannels; - protected PartECBase host; - - public ECBaseGridBlock(PartECBase _host) { - this.host = _host; - } - - @Override - public final EnumSet getConnectableSides() { - return EnumSet.noneOf(ForgeDirection.class); - } - - @Override - public EnumSet getFlags() { - return EnumSet.of(GridFlags.REQUIRE_CHANNEL); - } - - public IMEMonitor getFluidMonitor() { - IGridNode node = this.host.getGridNode(); - if (node == null) - return null; - IGrid grid = node.getGrid(); - if (grid == null) - return null; - IStorageGrid storageGrid = grid.getCache(IStorageGrid.class); - if (storageGrid == null) - return null; - return storageGrid.getFluidInventory(); - - } - - @Override - public final AEColor getGridColor() { - return this.color == null ? AEColor.Transparent : this.color; - } - - @Override - public double getIdlePowerUsage() { - return this.host.getPowerUsage(); - } - - @Override - public final DimensionalCoord getLocation() { - return this.host.getLocation(); - } - - @Override - public IGridHost getMachine() { - return this.host; - } - - @Override - public ItemStack getMachineRepresentation() { - return this.host.getItemStack(PartItemStack.Network); - } - - @Override - public void gridChanged() {} - - @Override - public final boolean isWorldAccessible() { - return false; - } - - @Override - public void onGridNotification(GridNotification notification) {} - - @Override - public final void setNetworkStatus(IGrid _grid, int _usedChannels) { - this.grid = _grid; - this.usedChannels = _usedChannels; - } + protected AEColor color; + protected IGrid grid; + protected int usedChannels; + protected PartECBase host; + + public ECBaseGridBlock(PartECBase _host) { + this.host = _host; + } + + @Override + public final EnumSet getConnectableSides() { + return EnumSet.noneOf(ForgeDirection.class); + } + + @Override + public EnumSet getFlags() { + return Constants.BASE_GRID_FLAGS; + } + + public IMEMonitor getFluidMonitor() { + IGridNode node = this.host.getGridNode(); + if (node == null) return null; + IGrid grid = node.getGrid(); + if (grid == null) return null; + IStorageGrid storageGrid = grid.getCache(IStorageGrid.class); + if (storageGrid == null) return null; + return storageGrid.getFluidInventory(); + } + + @Override + public final AEColor getGridColor() { + return this.color == null ? AEColor.Transparent : this.color; + } + + @Override + public double getIdlePowerUsage() { + return this.host.getPowerUsage(); + } + + @Override + public final DimensionalCoord getLocation() { + return this.host.getLocation(); + } + + @Override + public IGridHost getMachine() { + return this.host; + } + + @Override + public ItemStack getMachineRepresentation() { + return this.host.getItemStack(PartItemStack.Network); + } + + @Override + public void gridChanged() {} + + @Override + public final boolean isWorldAccessible() { + return false; + } + + @Override + public void onGridNotification(GridNotification notification) {} + + @Override + public final void setNetworkStatus(IGrid _grid, int _usedChannels) { + this.grid = _grid; + this.usedChannels = _usedChannels; + } } diff --git a/src/main/scala/extracells/gridblock/ECFluidGridBlock.java b/src/main/scala/extracells/gridblock/ECFluidGridBlock.java index 6bc0a54aa..3920e0e59 100644 --- a/src/main/scala/extracells/gridblock/ECFluidGridBlock.java +++ b/src/main/scala/extracells/gridblock/ECFluidGridBlock.java @@ -1,5 +1,10 @@ package extracells.gridblock; +import java.util.EnumSet; + +import net.minecraft.item.ItemStack; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.networking.*; import appeng.api.networking.storage.IStorageGrid; import appeng.api.util.AEColor; @@ -7,88 +12,88 @@ import extracells.api.IECTileEntity; import extracells.tileentity.IListenerTile; import extracells.tileentity.TileEntityFluidFiller; -import net.minecraft.item.ItemStack; -import net.minecraftforge.common.util.ForgeDirection; - -import java.util.EnumSet; public class ECFluidGridBlock implements IGridBlock { - protected IGrid grid; - protected int usedChannels; - protected IECTileEntity host; - - public ECFluidGridBlock(IECTileEntity _host) { - this.host = _host; - } - - @Override - public final EnumSet getConnectableSides() { - return EnumSet.of(ForgeDirection.DOWN, ForgeDirection.UP, - ForgeDirection.NORTH, ForgeDirection.EAST, - ForgeDirection.SOUTH, ForgeDirection.WEST); - } - - @Override - public EnumSet getFlags() { - return EnumSet.of(GridFlags.REQUIRE_CHANNEL); - } - - @Override - public final AEColor getGridColor() { - return AEColor.Transparent; - } - - @Override - public double getIdlePowerUsage() { - return this.host.getPowerUsage(); - } - - @Override - public final DimensionalCoord getLocation() { - return this.host.getLocation(); - } - - @Override - public IGridHost getMachine() { - return this.host; - } - - @Override - public ItemStack getMachineRepresentation() { - DimensionalCoord loc = getLocation(); - if (loc == null) - return null; - return new ItemStack(loc.getWorld().getBlock(loc.x, loc.y, loc.z), 1, - loc.getWorld().getBlockMetadata(loc.x, loc.y, loc.z)); - } - - @Override - public void gridChanged() {} - - @Override - public final boolean isWorldAccessible() { - return true; - } - - @Override - public void onGridNotification(GridNotification notification) {} - - @Override - public final void setNetworkStatus(IGrid _grid, int _usedChannels) { - if (this.grid != null && this.host instanceof IListenerTile - && this.grid != _grid) { - ((IListenerTile) this.host).updateGrid(this.grid, _grid); - this.grid = _grid; - this.usedChannels = _usedChannels; - if (this.host instanceof TileEntityFluidFiller - && this.grid.getCache(IStorageGrid.class) != null) - ((TileEntityFluidFiller) this.host).postChange( - ((IStorageGrid) this.grid.getCache(IStorageGrid.class)) - .getFluidInventory(), null, null); - } else { - this.grid = _grid; - this.usedChannels = _usedChannels; - } - } + protected IGrid grid; + protected int usedChannels; + protected IECTileEntity host; + + public ECFluidGridBlock(IECTileEntity _host) { + this.host = _host; + } + + @Override + public final EnumSet getConnectableSides() { + return EnumSet.of( + ForgeDirection.DOWN, + ForgeDirection.UP, + ForgeDirection.NORTH, + ForgeDirection.EAST, + ForgeDirection.SOUTH, + ForgeDirection.WEST); + } + + @Override + public EnumSet getFlags() { + return Constants.BASE_GRID_FLAGS; + } + + @Override + public final AEColor getGridColor() { + return AEColor.Transparent; + } + + @Override + public double getIdlePowerUsage() { + return this.host.getPowerUsage(); + } + + @Override + public final DimensionalCoord getLocation() { + return this.host.getLocation(); + } + + @Override + public IGridHost getMachine() { + return this.host; + } + + @Override + public ItemStack getMachineRepresentation() { + DimensionalCoord loc = getLocation(); + if (loc == null) return null; + return new ItemStack( + loc.getWorld().getBlock(loc.x, loc.y, loc.z), + 1, + loc.getWorld().getBlockMetadata(loc.x, loc.y, loc.z)); + } + + @Override + public void gridChanged() {} + + @Override + public final boolean isWorldAccessible() { + return true; + } + + @Override + public void onGridNotification(GridNotification notification) {} + + @Override + public final void setNetworkStatus(IGrid _grid, int _usedChannels) { + if (this.grid != null && this.host instanceof IListenerTile && this.grid != _grid) { + ((IListenerTile) this.host).updateGrid(this.grid, _grid); + this.grid = _grid; + this.usedChannels = _usedChannels; + if (this.host instanceof TileEntityFluidFiller && this.grid.getCache(IStorageGrid.class) != null) + ((TileEntityFluidFiller) this.host).postChange( + ((IStorageGrid) this.grid.getCache(IStorageGrid.class)).getFluidInventory(), + null, + null); + } else { + this.grid = _grid; + this.usedChannels = _usedChannels; + } + } } diff --git a/src/main/scala/extracells/gridblock/ECGridBlockHardMEDrive.scala b/src/main/scala/extracells/gridblock/ECGridBlockHardMEDrive.scala index b1dd9bf7b..3d044e8d9 100644 --- a/src/main/scala/extracells/gridblock/ECGridBlockHardMEDrive.scala +++ b/src/main/scala/extracells/gridblock/ECGridBlockHardMEDrive.scala @@ -8,16 +8,22 @@ import extracells.tileentity.TileEntityHardMeDrive import net.minecraft.item.ItemStack import net.minecraftforge.common.util.ForgeDirection - -class ECGridBlockHardMEDrive(host: TileEntityHardMeDrive) extends IGridBlock{ +class ECGridBlockHardMEDrive(host: TileEntityHardMeDrive) extends IGridBlock { protected var grid: IGrid = null protected var usedChannels: Int = 0 override def getConnectableSides: EnumSet[ForgeDirection] = - EnumSet.of(ForgeDirection.DOWN, ForgeDirection.UP, ForgeDirection.NORTH, ForgeDirection.EAST, ForgeDirection.SOUTH, - ForgeDirection.WEST) - - override def getFlags: EnumSet[GridFlags] = EnumSet.of(GridFlags.REQUIRE_CHANNEL, GridFlags.DENSE_CAPACITY) + EnumSet.of( + ForgeDirection.DOWN, + ForgeDirection.UP, + ForgeDirection.NORTH, + ForgeDirection.EAST, + ForgeDirection.SOUTH, + ForgeDirection.WEST + ) + + override def getFlags: EnumSet[GridFlags] = + EnumSet.of(GridFlags.REQUIRE_CHANNEL, GridFlags.DENSE_CAPACITY) override def getGridColor = AEColor.Transparent @@ -30,7 +36,11 @@ class ECGridBlockHardMEDrive(host: TileEntityHardMeDrive) extends IGridBlock{ override def getMachineRepresentation: ItemStack = { val loc: DimensionalCoord = getLocation if (loc == null) return null - new ItemStack(loc.getWorld.getBlock(loc.x, loc.y, loc.z), 1, loc.getWorld.getBlockMetadata(loc.x, loc.y, loc.z)) + new ItemStack( + loc.getWorld.getBlock(loc.x, loc.y, loc.z), + 1, + loc.getWorld.getBlockMetadata(loc.x, loc.y, loc.z) + ) } override def gridChanged {} diff --git a/src/main/scala/extracells/gridblock/ECGridBlockVibrantChamber.scala b/src/main/scala/extracells/gridblock/ECGridBlockVibrantChamber.scala index 507bc0518..eed287c54 100644 --- a/src/main/scala/extracells/gridblock/ECGridBlockVibrantChamber.scala +++ b/src/main/scala/extracells/gridblock/ECGridBlockVibrantChamber.scala @@ -8,14 +8,20 @@ import extracells.tileentity.TileEntityVibrationChamberFluid import net.minecraft.item.ItemStack import net.minecraftforge.common.util.ForgeDirection - -class ECGridBlockVibrantChamber(host: TileEntityVibrationChamberFluid) extends IGridBlock{ +class ECGridBlockVibrantChamber(host: TileEntityVibrationChamberFluid) + extends IGridBlock { protected var grid: IGrid = null protected var usedChannels: Int = 0 override def getConnectableSides: EnumSet[ForgeDirection] = - EnumSet.of(ForgeDirection.DOWN, ForgeDirection.UP, ForgeDirection.NORTH, ForgeDirection.EAST, ForgeDirection.SOUTH, - ForgeDirection.WEST) + EnumSet.of( + ForgeDirection.DOWN, + ForgeDirection.UP, + ForgeDirection.NORTH, + ForgeDirection.EAST, + ForgeDirection.SOUTH, + ForgeDirection.WEST + ) override def getFlags: EnumSet[GridFlags] = EnumSet.noneOf(classOf[GridFlags]) @@ -30,7 +36,11 @@ class ECGridBlockVibrantChamber(host: TileEntityVibrationChamberFluid) extends I override def getMachineRepresentation: ItemStack = { val loc: DimensionalCoord = getLocation if (loc == null) return null - new ItemStack(loc.getWorld.getBlock(loc.x, loc.y, loc.z), 1, loc.getWorld.getBlockMetadata(loc.x, loc.y, loc.z)) + new ItemStack( + loc.getWorld.getBlock(loc.x, loc.y, loc.z), + 1, + loc.getWorld.getBlockMetadata(loc.x, loc.y, loc.z) + ) } override def gridChanged {} diff --git a/src/main/scala/extracells/gui/ECGuiContainer.java b/src/main/scala/extracells/gui/ECGuiContainer.java new file mode 100644 index 000000000..817ddbb47 --- /dev/null +++ b/src/main/scala/extracells/gui/ECGuiContainer.java @@ -0,0 +1,37 @@ +package extracells.gui; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.inventory.Container; + +import extracells.gui.widget.fluid.WidgetFluidSlot; + +abstract class ECGuiContainer extends GuiContainer { + + List fluidSlotList = new ArrayList(); + WidgetFluidSlot fluidSlot; + + ECGuiContainer(Container p_i1072_1_) { + super(p_i1072_1_); + } + + void showTooltip(int mouseX, int mouseY) { + if (fluidSlot != null) { + if (func_146978_c(fluidSlot.getPosX(), fluidSlot.getPosY(), 16, 16, mouseX, mouseY)) { + fluidSlot.drawTooltip(mouseX - this.guiLeft, mouseY - this.guiTop); + } + } + } + + void showTooltipList(int mouseX, int mouseY) { + for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { + if (fluidSlot == null) continue; + + if (func_146978_c(fluidSlot.getPosX(), fluidSlot.getPosY(), 16, 16, mouseX, mouseY)) { + fluidSlot.drawTooltip(mouseX - this.guiLeft, mouseY - this.guiTop); + } + } + } +} diff --git a/src/main/scala/extracells/gui/GuiBusFluidIO.java b/src/main/scala/extracells/gui/GuiBusFluidIO.java index 9eb1d2e2a..18b8f3c83 100644 --- a/src/main/scala/extracells/gui/GuiBusFluidIO.java +++ b/src/main/scala/extracells/gui/GuiBusFluidIO.java @@ -1,7 +1,26 @@ package extracells.gui; +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.lwjgl.opengl.GL11; + import appeng.api.AEApi; import appeng.api.config.RedstoneMode; +import codechicken.nei.VisiblityData; +import codechicken.nei.api.INEIGuiHandler; +import codechicken.nei.api.TaggedInventoryArea; +import cpw.mods.fml.common.Optional; import extracells.container.ContainerBusFluidIO; import extracells.gui.widget.WidgetRedstoneModes; import extracells.gui.widget.fluid.WidgetFluidSlot; @@ -12,200 +31,245 @@ import extracells.part.PartGasExport; import extracells.part.PartGasImport; import extracells.util.FluidUtil; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import org.lwjgl.opengl.GL11; +import extracells.util.GuiUtil; -import java.util.ArrayList; -import java.util.List; +@Optional.Interface(modid = "NotEnoughItems", iface = "codechicken.nei.api.INEIGuiHandler") +public class GuiBusFluidIO extends ECGuiContainer + implements WidgetFluidSlot.IConfigurable, IFluidSlotGui, INEIGuiHandler { + + private static final ResourceLocation guiTexture = new ResourceLocation( + "extracells", + "textures/gui/busiofluid.png"); + private final PartFluidIO part; + private final EntityPlayer player; + private byte filterSize; + private boolean redstoneControlled; + private final boolean hasNetworkTool; + + public GuiBusFluidIO(PartFluidIO _terminal, EntityPlayer _player) { + super(new ContainerBusFluidIO(_terminal, _player)); + ((ContainerBusFluidIO) this.inventorySlots).setGui(this); + this.part = _terminal; + this.player = _player; + + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 0, 61, 21, this, (byte) 2)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 1, 79, 21, this, (byte) 1)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 2, 97, 21, this, (byte) 2)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 3, 61, 39, this, (byte) 1)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 4, 79, 39, this, (byte) 0)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 5, 97, 39, this, (byte) 1)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 6, 61, 57, this, (byte) 2)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 7, 79, 57, this, (byte) 1)); + this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 8, 97, 57, this, (byte) 2)); + + new PacketBusFluidIO(this.player, this.part).sendPacketToServer(); + this.hasNetworkTool = this.inventorySlots.getInventory().size() > 40; + this.xSize = this.hasNetworkTool ? 246 : 211; + this.ySize = 184; + } + + @Override + public void actionPerformed(GuiButton button) { + super.actionPerformed(button); + new PacketBusFluidIO(this.player, (byte) button.id, this.part).sendPacketToServer(); + } + + public void changeConfig(byte _filterSize) { + this.filterSize = _filterSize; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int mouseX, int mouseY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 184); + drawTexturedModalRect(this.guiLeft + 179, this.guiTop, 179, 0, 32, 86); + if (this.hasNetworkTool) drawTexturedModalRect(this.guiLeft + 179, this.guiTop + 93, 178, 93, 68, 68); + for (Object s : this.inventorySlots.inventorySlots) { + renderBackground((Slot) s); + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + boolean overlayRendered = false; + for (byte i = 0; i < 9; i++) { + this.fluidSlotList.get(i).drawWidget(); + if (!overlayRendered && this.fluidSlotList.get(i).canRender()) + overlayRendered = renderOverlay(this.fluidSlotList.get(i), mouseX, mouseY); + } + + for (Object button : this.buttonList) { + if (button instanceof WidgetRedstoneModes) ((WidgetRedstoneModes) button) + .drawTooltip(mouseX, mouseY, (this.width - this.xSize) / 2, (this.height - this.ySize) / 2); + } + showTooltipList(mouseX, mouseY); + } + + @Override + public byte getConfigState() { + return this.filterSize; + } + + protected Slot getSlotAtPosition(int p_146975_1_, int p_146975_2_) { + for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { + Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); + + if (this.isMouseOverSlot(slot, p_146975_1_, p_146975_2_)) { + return slot; + } + } + + return null; + } + + private boolean isMouseOverSlot(Slot p_146981_1_, int p_146981_2_, int p_146981_3_) { + return this.func_146978_c( + p_146981_1_.xDisplayPosition, + p_146981_1_.yDisplayPosition, + 16, + 16, + p_146981_2_, + p_146981_3_); + } + + protected boolean isPointInRegion(int top, int left, int height, int width, int pointX, int pointY) { + int k1 = this.guiLeft; + int l1 = this.guiTop; + pointX -= k1; + pointY -= l1; + return pointX >= top - 1 && pointX < top + height + 1 && pointY >= left - 1 && pointY < left + width + 1; + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + Slot slot = getSlotAtPosition(mouseX, mouseY); + + if (slot != null && slot.getStack() != null + && slot.getStack() + .isItemEqual(AEApi.instance().definitions().items().networkTool().maybeStack(1).get())) + return; + super.mouseClicked(mouseX, mouseY, mouseBtn); + for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { + if (isPointInRegion(fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { + if ((part instanceof PartGasImport || part instanceof PartGasExport) + && Integration.Mods.MEKANISMGAS.isEnabled()) + fluidSlot.mouseClickedGas(this.player.inventory.getItemStack()); + else fluidSlot.mouseClicked(this.player.inventory.getItemStack()); + break; + } + } + } + + private void renderBackground(Slot slot) { + if (slot.getStack() == null && (slot.slotNumber < 4 || slot.slotNumber > 39)) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); + this.mc.getTextureManager() + .bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.drawTexturedModalRect( + this.guiLeft + slot.xDisplayPosition, + this.guiTop + slot.yDisplayPosition, + 240, + 208, + 16, + 16); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + } + } + + public boolean renderOverlay(WidgetFluidSlot fluidSlot, int mouseX, int mouseY) { + if (isPointInRegion(fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + drawGradientRect( + fluidSlot.getPosX() + 1, + fluidSlot.getPosY() + 1, + fluidSlot.getPosX() + 17, + fluidSlot.getPosY() + 17, + -0x7F000001, + -0x7F000001); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + return true; + } + return false; + } + + public void setRedstoneControlled(boolean _redstoneControlled) { + this.redstoneControlled = _redstoneControlled; + this.buttonList.clear(); + if (this.redstoneControlled) this.buttonList + .add(new WidgetRedstoneModes(0, this.guiLeft - 18, this.guiTop, 16, 16, this.part.getRedstoneMode())); + } + + public boolean shiftClick(ItemStack itemStack) { + FluidStack containerFluid = FluidUtil.getFluidFromContainer(itemStack); + Fluid fluid = containerFluid == null ? null : containerFluid.getFluid(); + for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { + if (fluidSlot.canRender() && fluid != null + && (fluidSlot.getFluid() == null || fluidSlot.getFluid() == fluid)) { + if ((part instanceof PartGasImport || part instanceof PartGasExport) + && Integration.Mods.MEKANISMGAS.isEnabled()) + fluidSlot.mouseClickedGas(itemStack); + else fluidSlot.mouseClicked(itemStack); + return true; + } + } + return false; + } + + @Override + public void updateFluids(List fluidList) { + for (int i = 0; i < this.fluidSlotList.size() && i < fluidList.size(); i++) { + this.fluidSlotList.get(i).setFluid(fluidList.get(i)); + } + } + + public void updateRedstoneMode(RedstoneMode mode) { + if (this.redstoneControlled && this.buttonList.size() > 0) + ((WidgetRedstoneModes) this.buttonList.get(0)).setRedstoneMode(mode); + } + + @Override + public boolean handleDragNDrop(GuiContainer gui, int mouseX, int mouseY, ItemStack draggedStack, int button) { + for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { + if (GuiUtil.isPointInRegion( + this.guiLeft, + this.guiTop, + fluidSlot.getPosX(), + fluidSlot.getPosY(), + 18, + 18, + mouseX, + mouseY)) { + fluidSlot.mouseNEIClicked(draggedStack); + return true; + } + } + return false; + } + + @Override + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { + return false; + } + + @Override + public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) { + return currentVisibility; + } + + @Override + public Iterable getItemSpawnSlots(GuiContainer gui, ItemStack item) { + return Collections.emptyList(); + } -public class GuiBusFluidIO extends GuiContainer implements - WidgetFluidSlot.IConfigurable, IFluidSlotGui { - - private static final ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/busiofluid.png"); - private PartFluidIO part; - private EntityPlayer player; - private byte filterSize; - private List fluidSlotList = new ArrayList(); - private boolean redstoneControlled; - private boolean hasNetworkTool; - - public GuiBusFluidIO(PartFluidIO _terminal, EntityPlayer _player) { - super(new ContainerBusFluidIO(_terminal, _player)); - ((ContainerBusFluidIO) this.inventorySlots).setGui(this); - this.part = _terminal; - this.player = _player; - - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 0, 61, 21, this, (byte) 2)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 1, 79, 21, this, (byte) 1)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 2, 97, 21, this, (byte) 2)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 3, 61, 39, this, (byte) 1)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 4, 79, 39, this, (byte) 0)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 5, 97, 39, this, (byte) 1)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 6, 61, 57, this, (byte) 2)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 7, 79, 57, this, (byte) 1)); - this.fluidSlotList.add(new WidgetFluidSlot(this.player, this.part, 8, 97, 57, this, (byte) 2)); - - new PacketBusFluidIO(this.player, this.part).sendPacketToServer(); - this.hasNetworkTool = this.inventorySlots.getInventory().size() > 40; - this.xSize = this.hasNetworkTool ? 246 : 211; - this.ySize = 184; - - } - - @Override - public void actionPerformed(GuiButton button) { - super.actionPerformed(button); - new PacketBusFluidIO(this.player, (byte) button.id, this.part) - .sendPacketToServer(); - } - - public void changeConfig(byte _filterSize) { - this.filterSize = _filterSize; - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int mouseX, - int mouseY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 184); - drawTexturedModalRect(this.guiLeft + 179, this.guiTop, 179, 0, 32, 86); - if (this.hasNetworkTool) - drawTexturedModalRect(this.guiLeft + 179, this.guiTop + 93, 178, - 93, 68, 68); - for (Object s : this.inventorySlots.inventorySlots) { - renderBackground((Slot) s); - } - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - boolean overlayRendered = false; - for (byte i = 0; i < 9; i++) { - this.fluidSlotList.get(i).drawWidget(); - if (!overlayRendered && this.fluidSlotList.get(i).canRender()) overlayRendered = renderOverlay(this.fluidSlotList.get(i), mouseX, mouseY); - } - - for (Object button : this.buttonList) { - if (button instanceof WidgetRedstoneModes) - ((WidgetRedstoneModes) button).drawTooltip(mouseX, mouseY, (this.width - this.xSize) / 2, (this.height - this.ySize) / 2); - } - } - - @Override - public byte getConfigState() { - return this.filterSize; - } - - protected Slot getSlotAtPosition(int p_146975_1_, int p_146975_2_) { - for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { - Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); - - if (this.isMouseOverSlot(slot, p_146975_1_, p_146975_2_)) { - return slot; - } - } - - return null; - } - - private boolean isMouseOverSlot(Slot p_146981_1_, int p_146981_2_, int p_146981_3_) { - return this.func_146978_c(p_146981_1_.xDisplayPosition, p_146981_1_.yDisplayPosition, 16, 16, p_146981_2_, p_146981_3_); - } - - protected boolean isPointInRegion(int top, int left, int height, int width, int pointX, int pointY) { - int k1 = this.guiLeft; - int l1 = this.guiTop; - pointX -= k1; - pointY -= l1; - return pointX >= top - 1 && pointX < top + height + 1 - && pointY >= left - 1 && pointY < left + width + 1; - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - Slot slot = getSlotAtPosition(mouseX, mouseY); - - if (slot != null && slot.getStack() != null && slot.getStack().isItemEqual(AEApi.instance().definitions().items().networkTool().maybeStack(1).get())) - return; - super.mouseClicked(mouseX, mouseY, mouseBtn); - for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { - if (isPointInRegion(fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { - if((part instanceof PartGasImport || part instanceof PartGasExport) && Integration.Mods.MEKANISMGAS.isEnabled()) - fluidSlot.mouseClickedGas(this.player.inventory.getItemStack()); - else - fluidSlot.mouseClicked(this.player.inventory.getItemStack()); - break; - } - } - } - - private void renderBackground(Slot slot) { - if (slot.getStack() == null && (slot.slotNumber < 4 || slot.slotNumber > 39)) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); - this.mc.getTextureManager().bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); - this.drawTexturedModalRect(this.guiLeft + slot.xDisplayPosition, this.guiTop + slot.yDisplayPosition, 240, 208, 16, 16); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_LIGHTING); - - } - } - - public boolean renderOverlay(WidgetFluidSlot fluidSlot, int mouseX, - int mouseY) { - if (isPointInRegion(fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - drawGradientRect(fluidSlot.getPosX() + 1, fluidSlot.getPosY() + 1, fluidSlot.getPosX() + 17, fluidSlot.getPosY() + 17, -0x7F000001, -0x7F000001); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - return true; - } - return false; - } - - public void setRedstoneControlled(boolean _redstoneControlled) { - this.redstoneControlled = _redstoneControlled; - this.buttonList.clear(); - if (this.redstoneControlled) - this.buttonList.add(new WidgetRedstoneModes(0, this.guiLeft - 18, this.guiTop, 16, 16, this.part.getRedstoneMode())); - } - - public boolean shiftClick(ItemStack itemStack) { - FluidStack containerFluid = FluidUtil.getFluidFromContainer(itemStack); - Fluid fluid = containerFluid == null ? null : containerFluid.getFluid(); - for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { - if (fluidSlot.canRender() && fluid != null && (fluidSlot.getFluid() == null || fluidSlot.getFluid() == fluid)) { - if((part instanceof PartGasImport || part instanceof PartGasExport) && Integration.Mods.MEKANISMGAS.isEnabled()) - fluidSlot.mouseClickedGas(itemStack); - else - fluidSlot.mouseClicked(itemStack); - return true; - } - } - return false; - } - - @Override - public void updateFluids(List fluidList) { - for (int i = 0; i < this.fluidSlotList.size() && i < fluidList.size(); i++) { - this.fluidSlotList.get(i).setFluid(fluidList.get(i)); - } - } - - public void updateRedstoneMode(RedstoneMode mode) { - if (this.redstoneControlled && this.buttonList.size() > 0) - ((WidgetRedstoneModes) this.buttonList.get(0)).setRedstoneMode(mode); - } + @Override + public List getInventoryAreas(GuiContainer gui) { + return null; + } } diff --git a/src/main/scala/extracells/gui/GuiBusFluidStorage.java b/src/main/scala/extracells/gui/GuiBusFluidStorage.java index caed31a8c..134f0faa0 100644 --- a/src/main/scala/extracells/gui/GuiBusFluidStorage.java +++ b/src/main/scala/extracells/gui/GuiBusFluidStorage.java @@ -1,197 +1,397 @@ package extracells.gui; +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.client.renderer.RenderHelper; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Slot; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + import appeng.api.AEApi; import appeng.api.config.AccessRestriction; +import appeng.client.gui.widgets.GuiTabButton; +import appeng.client.gui.widgets.ITooltip; +import appeng.core.localization.GuiText; +import codechicken.nei.VisiblityData; +import codechicken.nei.api.INEIGuiHandler; +import codechicken.nei.api.TaggedInventoryArea; +import cpw.mods.fml.common.Optional; import extracells.container.ContainerBusFluidStorage; import extracells.gui.widget.WidgetStorageDirection; import extracells.gui.widget.fluid.WidgetFluidSlot; import extracells.integration.Integration; import extracells.network.packet.other.IFluidSlotGui; +import extracells.network.packet.other.PacketGuiSwitch; import extracells.network.packet.part.PacketBusFluidStorage; import extracells.part.PartFluidStorage; import extracells.part.PartGasStorage; import extracells.util.FluidUtil; import extracells.util.GuiUtil; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Slot; -import net.minecraft.item.ItemStack; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import org.lwjgl.opengl.GL11; -import java.util.ArrayList; -import java.util.List; +@Optional.Interface(modid = "NotEnoughItems", iface = "codechicken.nei.api.INEIGuiHandler") +public class GuiBusFluidStorage extends ECGuiContainer + implements WidgetFluidSlot.IConfigurable, IFluidSlotGui, INEIGuiHandler { + + private static final ResourceLocation guiTexture = new ResourceLocation( + "extracells", + "textures/gui/storagebusfluid.png"); + private final EntityPlayer player; + private byte filterSize; + private final boolean hasNetworkTool; + private final PartFluidStorage part; + private GuiTabButton priority; + + public GuiBusFluidStorage(PartFluidStorage _part, EntityPlayer _player) { + super(new ContainerBusFluidStorage(_part, _player)); + part = _part; + ((ContainerBusFluidStorage) this.inventorySlots).setGui(this); + this.player = _player; + + for (int i = 0; i < 9; i++) { + for (int j = 0; j < 6; j++) { + this.fluidSlotList.add(new WidgetFluidSlot(this.player, part, i * 6 + j, 18 * i + 7, 18 * j + 30)); + } + } + + new PacketBusFluidStorage(this.player, part).sendPacketToServer(); + this.hasNetworkTool = this.inventorySlots.getInventory().size() > 40; + this.xSize = this.hasNetworkTool ? 246 : 211; + this.ySize = 235; + } + + @Override + public void actionPerformed(GuiButton button) { + super.actionPerformed(button); + if (button instanceof WidgetStorageDirection) { + switch (((WidgetStorageDirection) button).getAccessRestriction()) { + case NO_ACCESS: + new PacketBusFluidStorage(this.player, AccessRestriction.READ, false).sendPacketToServer(); + break; + case READ: + new PacketBusFluidStorage(this.player, AccessRestriction.READ_WRITE, false).sendPacketToServer(); + break; + case READ_WRITE: + new PacketBusFluidStorage(this.player, AccessRestriction.WRITE, false).sendPacketToServer(); + break; + case WRITE: + new PacketBusFluidStorage(this.player, AccessRestriction.NO_ACCESS, false).sendPacketToServer(); + break; + default: + break; + } + } else if (button == this.priority) { + new PacketGuiSwitch(100 + part.getSide().ordinal(), part.getHostTile()).sendPacketToServer(); + } + } + + public void changeConfig(byte _filterSize) { + this.filterSize = _filterSize; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int mouseX, int mouseY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 235); + drawTexturedModalRect(this.guiLeft + 179, this.guiTop, 179, 0, 32, 86); + fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.gui.fluid.storage"), + 8 + this.guiLeft, + 6 + this.guiTop, + 4210752); + if (this.hasNetworkTool) drawTexturedModalRect(this.guiLeft + 179, this.guiTop + 93, 178, 93, 68, 68); + for (Object s : this.inventorySlots.inventorySlots) { + renderBackground((Slot) s); + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + boolean overlayRendered = false; + for (byte i = 0; i < 54; i++) { + this.fluidSlotList.get(i).drawWidget(); + if (!overlayRendered && this.fluidSlotList.get(i).canRender()) overlayRendered = GuiUtil + .renderOverlay(this.zLevel, this.guiLeft, this.guiTop, this.fluidSlotList.get(i), mouseX, mouseY); + } + for (Object button : this.buttonList) { + if (button instanceof WidgetStorageDirection) { + ((WidgetStorageDirection) button) + .drawTooltip(mouseX, mouseY, (this.width - this.xSize) / 2, (this.height - this.ySize) / 2); + } + } + showTooltipList(mouseX, mouseY); + } + + @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) { + handleTooltip(mouseX, mouseY, (ITooltip) c); + } + } + } + + protected void handleTooltip(int mouseX, int mouseY, ITooltip c) { + final int x = c.xPos(); // ((GuiImgButton) c).xPosition; + int y = c.yPos(); // ((GuiImgButton) c).yPosition; + + if (x < mouseX && x + c.getWidth() > mouseX && c.isVisible()) { + if (y < mouseY && y + c.getHeight() > mouseY) { + if (y < 15) { + y = 15; + } + + final String msg = c.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 + public byte getConfigState() { + return this.filterSize; + } + + protected Slot getSlotAtPosition(int p_146975_1_, int p_146975_2_) { + for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { + Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); + + if (this.isMouseOverSlot(slot, p_146975_1_, p_146975_2_)) { + return slot; + } + } + + return null; + } + + @Override + @SuppressWarnings("unchecked") + public void initGui() { + super.initGui(); + this.buttonList.add( + new WidgetStorageDirection(0, this.guiLeft - 18, this.guiTop, 16, 16, AccessRestriction.READ_WRITE)); + this.priority = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + 2 + 4 * 16, + GuiText.Priority.getLocal(), + itemRender); + this.buttonList.add(priority); + } + + private boolean isMouseOverSlot(Slot p_146981_1_, int p_146981_2_, int p_146981_3_) { + return this.func_146978_c( + p_146981_1_.xDisplayPosition, + p_146981_1_.yDisplayPosition, + 16, + 16, + p_146981_2_, + p_146981_3_); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + Slot slot = getSlotAtPosition(mouseX, mouseY); + + if (slot != null && slot.getStack() != null + && AEApi.instance().definitions().items().networkTool().isSameAs(slot.getStack())) + return; + + for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { + if (GuiUtil.isPointInRegion( + this.guiLeft, + this.guiTop, + fluidSlot.getPosX(), + fluidSlot.getPosY(), + 18, + 18, + mouseX, + mouseY)) { + if (part instanceof PartGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) + fluidSlot.mouseClickedGas(this.player.inventory.getItemStack()); + else fluidSlot.mouseClicked(this.player.inventory.getItemStack()); + break; + } + } + } + + private void renderBackground(Slot slot) { + if (slot.getStack() == null && (slot.slotNumber == 0 || slot.slotNumber > 36)) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); + this.mc.getTextureManager() + .bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.drawTexturedModalRect( + this.guiLeft + slot.xDisplayPosition, + this.guiTop + slot.yDisplayPosition, + 240, + 208, + 16, + 16); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + } + } + + public void shiftClick(ItemStack itemStack) { + FluidStack containerFluid = FluidUtil.getFluidFromContainer(itemStack); + Fluid fluid = containerFluid == null ? null : containerFluid.getFluid(); + for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { + if (fluidSlot.getFluid() == null || fluid != null && fluidSlot.getFluid() == fluid) { + if (part instanceof PartGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) + fluidSlot.mouseClickedGas(itemStack); + else fluidSlot.mouseClicked(itemStack); + return; + } + } + } + + public void updateAccessRestriction(AccessRestriction mode) { + if (this.buttonList.size() > 0) ((WidgetStorageDirection) this.buttonList.get(0)).setAccessRestriction(mode); + } + + @Override + public void updateFluids(List fluidList) { + for (int i = 0; i < this.fluidSlotList.size() && i < fluidList.size(); i++) { + this.fluidSlotList.get(i).setFluid(fluidList.get(i)); + } + } + + @Override + public VisiblityData modifyVisiblity(GuiContainer guiContainer, VisiblityData visiblityData) { + return visiblityData; + } + + @Override + public Iterable getItemSpawnSlots(GuiContainer guiContainer, ItemStack itemStack) { + return Collections.emptyList(); + } + + @Override + public List getInventoryAreas(GuiContainer guiContainer) { + return null; + } + + @Override + public boolean handleDragNDrop(GuiContainer gui, int mouseX, int mouseY, ItemStack draggedStack, int button) { + if (!(gui instanceof GuiBusFluidStorage) || draggedStack == null) { + return false; + } + for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { + if (GuiUtil.isPointInRegion( + this.guiLeft, + this.guiTop, + fluidSlot.getPosX(), + fluidSlot.getPosY(), + 18, + 18, + mouseX, + mouseY)) { + if (part instanceof PartGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) + fluidSlot.mouseNEIClickedGas(draggedStack); + else fluidSlot.mouseNEIClicked(draggedStack); + draggedStack.stackSize = 0; + return true; + } + } + return false; + } -public class GuiBusFluidStorage extends GuiContainer implements - WidgetFluidSlot.IConfigurable, IFluidSlotGui { - - private static final ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/storagebusfluid.png"); - private EntityPlayer player; - private byte filterSize; - private List fluidSlotList = new ArrayList(); - private boolean hasNetworkTool; - private final PartFluidStorage part; - - public GuiBusFluidStorage(PartFluidStorage _part, EntityPlayer _player) { - super(new ContainerBusFluidStorage(_part, _player)); - part = _part; - ((ContainerBusFluidStorage) this.inventorySlots).setGui(this); - this.player = _player; - - for (int i = 0; i < 9; i++) { - for (int j = 0; j < 6; j++) { - this.fluidSlotList.add(new WidgetFluidSlot(this.player, part, i * 6 + j, 18 * i + 7, 18 * j + 17)); - } - } - - new PacketBusFluidStorage(this.player, part).sendPacketToServer(); - this.hasNetworkTool = this.inventorySlots.getInventory().size() > 40; - this.xSize = this.hasNetworkTool ? 246 : 211; - this.ySize = 222; - - } - - @Override - public void actionPerformed(GuiButton button) { - super.actionPerformed(button); - if (button instanceof WidgetStorageDirection) { - switch (((WidgetStorageDirection) button).getAccessRestriction()) { - case NO_ACCESS: - new PacketBusFluidStorage(this.player, AccessRestriction.READ, false).sendPacketToServer(); - break; - case READ: - new PacketBusFluidStorage(this.player, AccessRestriction.READ_WRITE, false).sendPacketToServer(); - break; - case READ_WRITE: - new PacketBusFluidStorage(this.player, AccessRestriction.WRITE, false).sendPacketToServer(); - break; - case WRITE: - new PacketBusFluidStorage(this.player, AccessRestriction.NO_ACCESS, false).sendPacketToServer(); - break; - default: - break; - } - } - } - - public void changeConfig(byte _filterSize) { - this.filterSize = _filterSize; - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int mouseX, int mouseY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 222); - drawTexturedModalRect(this.guiLeft + 179, this.guiTop, 179, 0, 32, 86); - if (this.hasNetworkTool) - drawTexturedModalRect(this.guiLeft + 179, this.guiTop + 93, 178, 93, 68, 68); - for (Object s : this.inventorySlots.inventorySlots) { - renderBackground((Slot) s); - } - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - boolean overlayRendered = false; - for (byte i = 0; i < 54; i++) { - this.fluidSlotList.get(i).drawWidget(); - if (!overlayRendered && this.fluidSlotList.get(i).canRender()) - overlayRendered = GuiUtil.renderOverlay(this.zLevel, this.guiLeft, this.guiTop, this.fluidSlotList.get(i), mouseX, mouseY); - } - - for (Object button : this.buttonList) { - if (button instanceof WidgetStorageDirection) - ((WidgetStorageDirection) button).drawTooltip(mouseX, mouseY, (this.width - this.xSize) / 2, (this.height - this.ySize) / 2); - } - } - - @Override - public byte getConfigState() { - return this.filterSize; - } - - protected Slot getSlotAtPosition(int p_146975_1_, int p_146975_2_) { - for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { - Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); - - if (this.isMouseOverSlot(slot, p_146975_1_, p_146975_2_)) { - return slot; - } - } - - return null; - } - - @Override - public void initGui() { - super.initGui(); - this.buttonList.add(new WidgetStorageDirection(0, this.guiLeft - 18, this.guiTop, 16, 16, AccessRestriction.READ_WRITE)); - } - - private boolean isMouseOverSlot(Slot p_146981_1_, int p_146981_2_, int p_146981_3_) { - return this.func_146978_c(p_146981_1_.xDisplayPosition, p_146981_1_.yDisplayPosition, 16, 16, p_146981_2_, p_146981_3_); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - Slot slot = getSlotAtPosition(mouseX, mouseY); - - if (slot != null && slot.getStack() != null && AEApi.instance().definitions().items().networkTool().isSameAs(slot.getStack())) - return; - super.mouseClicked(mouseX, mouseY, mouseBtn); - for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { - if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { - if(part instanceof PartGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) - fluidSlot.mouseClickedGas(this.player.inventory.getItemStack()); - else - fluidSlot.mouseClicked(this.player.inventory.getItemStack()); - break; - } - } - } - - private void renderBackground(Slot slot) { - if (slot.getStack() == null && (slot.slotNumber == 0 || slot.slotNumber > 36)) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); - this.mc.getTextureManager().bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); - this.drawTexturedModalRect(this.guiLeft + slot.xDisplayPosition, this.guiTop + slot.yDisplayPosition, 240, 208, 16, 16); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_LIGHTING); - - } - } - - public void shiftClick(ItemStack itemStack) { - FluidStack containerFluid = FluidUtil.getFluidFromContainer(itemStack); - Fluid fluid = containerFluid == null ? null : containerFluid.getFluid(); - for (WidgetFluidSlot fluidSlot : this.fluidSlotList) { - if (fluidSlot.getFluid() == null || fluid != null && fluidSlot.getFluid() == fluid) { - if(part instanceof PartGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) - fluidSlot.mouseClickedGas(itemStack); - else - fluidSlot.mouseClicked(itemStack); - return; - } - } - } - - public void updateAccessRestriction(AccessRestriction mode) { - if (this.buttonList.size() > 0) - ((WidgetStorageDirection) this.buttonList.get(0)).setAccessRestriction(mode); - } - - @Override - public void updateFluids(List fluidList) { - for (int i = 0; i < this.fluidSlotList.size() && i < fluidList.size(); i++) { - this.fluidSlotList.get(i).setFluid(fluidList.get(i)); - } - } + @Override + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { + return false; + } } diff --git a/src/main/scala/extracells/gui/GuiDrive.java b/src/main/scala/extracells/gui/GuiDrive.java index 7f37db360..237afcbec 100644 --- a/src/main/scala/extracells/gui/GuiDrive.java +++ b/src/main/scala/extracells/gui/GuiDrive.java @@ -1,54 +1,56 @@ package extracells.gui; -import extracells.container.ContainerDrive; -import extracells.network.packet.part.PacketFluidStorage; -import extracells.part.PartDrive; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.util.ResourceLocation; + import org.lwjgl.opengl.GL11; +import extracells.container.ContainerDrive; +import extracells.network.packet.part.PacketFluidStorage; +import extracells.part.PartDrive; + public class GuiDrive extends GuiContainer { - private EntityPlayer player; - private ResourceLocation guiTexture = new ResourceLocation("extracells", - "textures/gui/drive.png"); - - public GuiDrive(PartDrive _part, EntityPlayer _player) { - super(new ContainerDrive(_part, _player)); - this.player = _player; - this.xSize = 176; - this.ySize = 163; - new PacketFluidStorage(this.player).sendPacketToServer(); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, - int sizeY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop - 18, 0, 0, this.xSize, - this.ySize); - for (Object s : this.inventorySlots.inventorySlots) { - renderBackground((Slot) s); - } - } - - private void renderBackground(Slot slot) { - if (slot.getStack() == null && slot.slotNumber < 6) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); - this.mc.getTextureManager().bindTexture( - new ResourceLocation("appliedenergistics2", - "textures/guis/states.png")); - this.drawTexturedModalRect(this.guiLeft + slot.xDisplayPosition, - this.guiTop + slot.yDisplayPosition, 240, 0, 16, 16); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_LIGHTING); - - } - } + private EntityPlayer player; + private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/drive.png"); + + public GuiDrive(PartDrive _part, EntityPlayer _player) { + super(new ContainerDrive(_part, _player)); + this.player = _player; + this.xSize = 176; + this.ySize = 163; + new PacketFluidStorage(this.player).sendPacketToServer(); + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop - 18, 0, 0, this.xSize, this.ySize); + for (Object s : this.inventorySlots.inventorySlots) { + renderBackground((Slot) s); + } + } + + private void renderBackground(Slot slot) { + if (slot.getStack() == null && slot.slotNumber < 6) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); + this.mc.getTextureManager() + .bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.drawTexturedModalRect( + this.guiLeft + slot.xDisplayPosition, + this.guiTop + slot.yDisplayPosition, + 240, + 0, + 16, + 16); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + } + } } diff --git a/src/main/scala/extracells/gui/GuiECPriority.java b/src/main/scala/extracells/gui/GuiECPriority.java new file mode 100644 index 000000000..f77f68dcc --- /dev/null +++ b/src/main/scala/extracells/gui/GuiECPriority.java @@ -0,0 +1,202 @@ +package extracells.gui; + +import java.io.IOException; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; + +import appeng.client.gui.AEBaseGui; +import appeng.client.gui.widgets.GuiNumberBox; +import appeng.client.gui.widgets.GuiTabButton; +import appeng.container.AEBaseContainer; +import appeng.container.implementations.ContainerPriority; +import appeng.core.AEConfig; +import appeng.core.AELog; +import appeng.core.localization.GuiText; +import appeng.core.sync.network.NetworkHandler; +import appeng.core.sync.packets.PacketValueConfig; +import appeng.helpers.IPriorityHost; +import extracells.network.packet.other.PacketGuiSwitch; +import extracells.part.PartFluidStorage; +import extracells.registries.ItemEnum; +import extracells.registries.PartEnum; + +public class GuiECPriority 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; + + private int OriginalGui = -1; + private TileEntity te; + + public GuiECPriority(final InventoryPlayer inventoryPlayer, final IPriorityHost te) { + super(new ContainerPriority(inventoryPlayer, te)); + } + + @Override + @SuppressWarnings("unchecked") + public void initGui() { + super.initGui(); + + 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); + + 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)); + + 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)); + + ItemStack myIcon = null; + final Object target = ((AEBaseContainer) this.inventorySlots).getTarget(); + + if (target instanceof PartFluidStorage) { + te = ((PartFluidStorage) target).getHostTile(); + myIcon = ItemEnum.PARTITEM.getDamagedStack(PartEnum.FLUIDSTORAGE.ordinal()); + this.OriginalGui = ((PartFluidStorage) target).getSide().ordinal(); + } + + if (this.OriginalGui != -1 && myIcon != null) { + this.buttonList.add( + this.originalGuiBtn = new GuiTabButton( + this.guiLeft + 154, + this.guiTop, + myIcon, + myIcon.getDisplayName(), + itemRender)); + } + + this.priority = new GuiNumberBox( + this.fontRendererObj, + this.guiLeft + 62, + this.guiTop + 57, + 59, + this.fontRendererObj.FONT_HEIGHT, + Long.class); + 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); + } + + @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 + public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) { + this.bindTexture(getBackground()); + this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize); + + this.priority.drawTextBox(); + } + + @Override + protected void actionPerformed(final GuiButton btn) { + super.actionPerformed(btn); + + if (btn == this.originalGuiBtn) { + new PacketGuiSwitch(OriginalGui, te).sendPacketToServer(); + } + + 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 (isPlus || isMinus) { + this.addQty(this.getQty(btn)); + } + } + + private void addQty(final int i) { + try { + String out = this.priority.getText(); + + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } + + if (fixed) { + this.priority.setText(out); + } + + if (out.isEmpty()) { + out = "0"; + } + + long result = Long.parseLong(out); + result += i; + + this.priority.setText(out = Long.toString(result)); + + NetworkHandler.instance.sendToServer(new PacketValueConfig("PriorityHost.Priority", out)); + } catch (final NumberFormatException e) { + // nope.. + this.priority.setText("0"); + } catch (final IOException e) { + AELog.debug(e); + } + } + + @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(); + + boolean fixed = false; + while (out.startsWith("0") && out.length() > 1) { + out = out.substring(1); + fixed = true; + } + + 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"; + } +} diff --git a/src/main/scala/extracells/gui/GuiFluidCrafter.java b/src/main/scala/extracells/gui/GuiFluidCrafter.java index d77c32758..ed6be416f 100644 --- a/src/main/scala/extracells/gui/GuiFluidCrafter.java +++ b/src/main/scala/extracells/gui/GuiFluidCrafter.java @@ -1,61 +1,65 @@ package extracells.gui; -import extracells.container.ContainerFluidCrafter; -import extracells.registries.BlockEnum; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.util.ResourceLocation; + import org.lwjgl.opengl.GL11; +import extracells.container.ContainerFluidCrafter; +import extracells.registries.BlockEnum; + public class GuiFluidCrafter extends GuiContainer { - public static final int xSize = 176; - public static final int ySize = 166; - private ResourceLocation guiTexture = new ResourceLocation("extracells", - "textures/gui/fluidcrafter.png"); - - public GuiFluidCrafter(InventoryPlayer player, IInventory tileentity) { - super(new ContainerFluidCrafter(player, tileentity)); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { - drawDefaultBackground(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - int posX = (this.width - xSize) / 2; - int posY = (this.height - ySize) / 2; - drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); - for (Object s : this.inventorySlots.inventorySlots) { - renderBackground((Slot) s); - } - } - - @Override - protected void drawGuiContainerForegroundLayer(int i, int j) { - this.fontRendererObj.drawString(BlockEnum.FLUIDCRAFTER.getStatName(), - 5, 5, 0x000000); - } - - public int getRowLength() { - return 3; - } - - private void renderBackground(Slot slot) { - if (slot.getStack() == null && slot.slotNumber < 9) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); - this.mc.getTextureManager().bindTexture( - new ResourceLocation("appliedenergistics2", - "textures/guis/states.png")); - this.drawTexturedModalRect(this.guiLeft + slot.xDisplayPosition, - this.guiTop + slot.yDisplayPosition, 240, 128, 16, 16); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_LIGHTING); - } - } + public static final int xSize = 176; + public static final int ySize = 166; + private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/fluidcrafter.png"); + + public GuiFluidCrafter(InventoryPlayer player, IInventory tileentity) { + super(new ContainerFluidCrafter(player, tileentity)); + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + int posX = (this.width - xSize) / 2; + int posY = (this.height - ySize) / 2; + drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); + for (Object s : this.inventorySlots.inventorySlots) { + renderBackground((Slot) s); + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int i, int j) { + this.fontRendererObj.drawString(BlockEnum.FLUIDCRAFTER.getStatName(), 5, 5, 0x000000); + } + + public int getRowLength() { + return 3; + } + + private void renderBackground(Slot slot) { + if (slot.getStack() == null && slot.slotNumber < 9) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); + this.mc.getTextureManager() + .bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.drawTexturedModalRect( + this.guiLeft + slot.xDisplayPosition, + this.guiTop + slot.yDisplayPosition, + 240, + 128, + 16, + 16); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + } + } } diff --git a/src/main/scala/extracells/gui/GuiFluidEmitter.java b/src/main/scala/extracells/gui/GuiFluidEmitter.java index f21859ed6..610cf4401 100644 --- a/src/main/scala/extracells/gui/GuiFluidEmitter.java +++ b/src/main/scala/extracells/gui/GuiFluidEmitter.java @@ -1,6 +1,24 @@ package extracells.gui; +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.ResourceLocation; +import net.minecraftforge.fluids.Fluid; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.opengl.GL11; + import appeng.api.config.RedstoneMode; +import codechicken.nei.VisiblityData; +import codechicken.nei.api.INEIGuiHandler; +import codechicken.nei.api.TaggedInventoryArea; +import cpw.mods.fml.common.Optional; import extracells.container.ContainerFluidEmitter; import extracells.gui.widget.DigitTextField; import extracells.gui.widget.WidgetRedstoneModes; @@ -12,167 +30,200 @@ import extracells.part.PartGasLevelEmitter; import extracells.registries.PartEnum; import extracells.util.GuiUtil; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fluids.Fluid; -import org.lwjgl.input.Keyboard; -import org.lwjgl.opengl.GL11; - -import java.util.List; -public class GuiFluidEmitter extends GuiContainer implements IFluidSlotGui { - - public static final int xSize = 176; - public static final int ySize = 166; - private DigitTextField amountField; - private PartFluidLevelEmitter part; - private EntityPlayer player; - private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/levelemitterfluid.png"); - private WidgetFluidSlot fluidSlot; - - public GuiFluidEmitter(PartFluidLevelEmitter _part, EntityPlayer _player) { - super(new ContainerFluidEmitter(_part, _player)); - this.player = _player; - this.part = _part; - this.fluidSlot = new WidgetFluidSlot(this.player, this.part, 79, 36); - new PacketFluidEmitter(false, this.part, this.player).sendPacketToServer(); - } - - @Override - public void actionPerformed(GuiButton button) { - switch (button.id) { - case 0: - modifyAmount(-1); - break; - case 1: - modifyAmount(-10); - break; - case 2: - modifyAmount(-100); - break; - case 3: - modifyAmount(+1); - break; - case 4: - modifyAmount(+10); - break; - case 5: - modifyAmount(+100); - break; - case 6: - new PacketFluidEmitter(true, this.part, this.player).sendPacketToServer(); - break; - - } - } - - @Override - protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - int posX = (this.width - xSize) / 2; - int posY = (this.height - ySize) / 2; - drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - this.fontRendererObj.drawString(PartEnum.FLUIDLEVELEMITTER.getStatName(), 5, 5, 0x000000); - this.fluidSlot.drawWidget(); - ((WidgetRedstoneModes) this.buttonList.get(6)).drawTooltip(mouseX, mouseY, (this.width - xSize) / 2, (this.height - ySize) / 2); - GuiUtil.renderOverlay(this.zLevel, this.guiLeft, this.guiTop, this.fluidSlot, mouseX, mouseY); - } - - @Override - public void drawScreen(int x, int y, float f) { - - String[] buttonNames = { "-1", "-10", "-100", "+1", "+10", "+100" }; - String[] shiftNames = { "-100", "-1000", "-10000", "+100", "+1000", "+10000" }; - - for (int i = 0; i < this.buttonList.size(); i++) { - if (i == 6) - break; - GuiButton currentButton = (GuiButton) this.buttonList.get(i); - - if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { - currentButton.displayString = shiftNames[i] + "mB"; - } else { - currentButton.displayString = buttonNames[i] + "mB"; - } - } - - super.drawScreen(x, y, f); - this.amountField.drawTextBox(); - } - - @Override - @SuppressWarnings("unchecked") - public void initGui() { - int posX = (this.width - xSize) / 2; - int posY = (this.height - ySize) / 2; - - this.amountField = new DigitTextField(this.fontRendererObj, posX + 10, posY + 40, 59, 10); - this.amountField.setFocused(true); - this.amountField.setEnableBackgroundDrawing(false); - this.amountField.setTextColor(0xFFFFFF); - - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, posX + 65 - 46, posY + 8 + 6, 42, 20, "-1")); - this.buttonList.add(new GuiButton(1, posX + 115 - 46, posY + 8 + 6, 42, 20, "-10")); - this.buttonList.add(new GuiButton(2, posX + 165 - 46, posY + 8 + 6, 42, 20, "-100")); - this.buttonList.add(new GuiButton(3, posX + 65 - 46, posY + 58 - 2, 42, 20, "+1")); - this.buttonList.add(new GuiButton(4, posX + 115 - 46, posY + 58 - 2, 42, 20, "+10")); - this.buttonList.add(new GuiButton(5, posX + 165 - 46, posY + 58 - 2, 42, 20, "+100")); - this.buttonList.add(new WidgetRedstoneModes(6, posX + 120, posY + 36, 16, 16, RedstoneMode.LOW_SIGNAL, true)); - - super.initGui(); - } - - @Override - protected void keyTyped(char key, int keyID) { - super.keyTyped(key, keyID); - if ("0123456789".contains(String.valueOf(key)) || keyID == Keyboard.KEY_BACK) { - this.amountField.textboxKeyTyped(key, keyID); - new PacketFluidEmitter(this.amountField.getText(), this.part, this.player).sendPacketToServer(); - } - } - - private void modifyAmount(int amount) { - if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) - amount *= 100; - new PacketFluidEmitter(amount, this.part, this.player).sendPacketToServer(); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, this.fluidSlot.getPosX(), this.fluidSlot.getPosY(), 18, 18, mouseX, mouseY)){ - if(part instanceof PartGasLevelEmitter && Integration.Mods.MEKANISMGAS.isEnabled()) - this.fluidSlot.mouseClickedGas(this.player.inventory.getItemStack()); - else - this.fluidSlot.mouseClicked(this.player.inventory.getItemStack()); - } - - - } - - public void setAmountField(long amount) { - this.amountField.setText(Long.toString(amount)); - } - - public void setRedstoneMode(RedstoneMode mode) { - ((WidgetRedstoneModes) this.buttonList.get(6)).setRedstoneMode(mode); - } - - @Override - public void updateFluids(List _fluids) { - if (_fluids == null || _fluids.isEmpty()) { - this.fluidSlot.setFluid(null); - return; - } - this.fluidSlot.setFluid(_fluids.get(0)); - } +@Optional.Interface(modid = "NotEnoughItems", iface = "codechicken.nei.api.INEIGuiHandler") +public class GuiFluidEmitter extends ECGuiContainer implements IFluidSlotGui, INEIGuiHandler { + + public static final int xSize = 176; + public static final int ySize = 166; + private DigitTextField amountField; + private final PartFluidLevelEmitter part; + private final EntityPlayer player; + private final ResourceLocation guiTexture = new ResourceLocation( + "extracells", + "textures/gui/levelemitterfluid.png"); + + public GuiFluidEmitter(PartFluidLevelEmitter _part, EntityPlayer _player) { + super(new ContainerFluidEmitter(_part, _player)); + this.player = _player; + this.part = _part; + this.fluidSlot = new WidgetFluidSlot(this.player, this.part, 79, 36); + new PacketFluidEmitter(false, this.part, this.player).sendPacketToServer(); + } + + @Override + public void actionPerformed(GuiButton button) { + switch (button.id) { + case 0: + modifyAmount(-1); + break; + case 1: + modifyAmount(-10); + break; + case 2: + modifyAmount(-100); + break; + case 3: + modifyAmount(+1); + break; + case 4: + modifyAmount(+10); + break; + case 5: + modifyAmount(+100); + break; + case 6: + new PacketFluidEmitter(true, this.part, this.player).sendPacketToServer(); + break; + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + int posX = (this.width - xSize) / 2; + int posY = (this.height - ySize) / 2; + drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.fontRendererObj.drawString(PartEnum.FLUIDLEVELEMITTER.getStatName(), 5, 5, 0x000000); + this.fluidSlot.drawWidget(); + ((WidgetRedstoneModes) this.buttonList.get(6)) + .drawTooltip(mouseX, mouseY, (this.width - xSize) / 2, (this.height - ySize) / 2); + GuiUtil.renderOverlay(this.zLevel, this.guiLeft, this.guiTop, this.fluidSlot, mouseX, mouseY); + showTooltip(mouseX, mouseY); + } + + @Override + public void drawScreen(int x, int y, float f) { + + String[] buttonNames = { "-1", "-10", "-100", "+1", "+10", "+100" }; + String[] shiftNames = { "-100", "-1000", "-10000", "+100", "+1000", "+10000" }; + + for (int i = 0; i < this.buttonList.size(); i++) { + if (i == 6) break; + GuiButton currentButton = (GuiButton) this.buttonList.get(i); + + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { + currentButton.displayString = shiftNames[i] + "mB"; + } else { + currentButton.displayString = buttonNames[i] + "mB"; + } + } + + super.drawScreen(x, y, f); + this.amountField.drawTextBox(); + } + + @Override + @SuppressWarnings("unchecked") + public void initGui() { + int posX = (this.width - xSize) / 2; + int posY = (this.height - ySize) / 2; + + this.amountField = new DigitTextField(this.fontRendererObj, posX + 10, posY + 40, 59, 10); + this.amountField.setFocused(true); + this.amountField.setEnableBackgroundDrawing(false); + this.amountField.setTextColor(0xFFFFFF); + + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, posX + 65 - 46, posY + 8 + 6, 42, 20, "-1")); + this.buttonList.add(new GuiButton(1, posX + 115 - 46, posY + 8 + 6, 42, 20, "-10")); + this.buttonList.add(new GuiButton(2, posX + 165 - 46, posY + 8 + 6, 42, 20, "-100")); + this.buttonList.add(new GuiButton(3, posX + 65 - 46, posY + 58 - 2, 42, 20, "+1")); + this.buttonList.add(new GuiButton(4, posX + 115 - 46, posY + 58 - 2, 42, 20, "+10")); + this.buttonList.add(new GuiButton(5, posX + 165 - 46, posY + 58 - 2, 42, 20, "+100")); + this.buttonList.add(new WidgetRedstoneModes(6, posX + 120, posY + 36, 16, 16, RedstoneMode.LOW_SIGNAL, true)); + + super.initGui(); + } + + @Override + protected void keyTyped(char key, int keyID) { + super.keyTyped(key, keyID); + if ("0123456789".contains(String.valueOf(key)) || keyID == Keyboard.KEY_BACK) { + this.amountField.textboxKeyTyped(key, keyID); + new PacketFluidEmitter(this.amountField.getText(), this.part, this.player).sendPacketToServer(); + } + } + + private void modifyAmount(int amount) { + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) amount *= 100; + new PacketFluidEmitter(amount, this.part, this.player).sendPacketToServer(); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + if (GuiUtil.isPointInRegion( + this.guiLeft, + this.guiTop, + this.fluidSlot.getPosX(), + this.fluidSlot.getPosY(), + 18, + 18, + mouseX, + mouseY)) { + if (part instanceof PartGasLevelEmitter && Integration.Mods.MEKANISMGAS.isEnabled()) + this.fluidSlot.mouseClickedGas(this.player.inventory.getItemStack()); + else this.fluidSlot.mouseClicked(this.player.inventory.getItemStack()); + } + } + + public void setAmountField(long amount) { + this.amountField.setText(Long.toString(amount)); + } + + public void setRedstoneMode(RedstoneMode mode) { + ((WidgetRedstoneModes) this.buttonList.get(6)).setRedstoneMode(mode); + } + + @Override + public void updateFluids(List _fluids) { + if (_fluids == null || _fluids.isEmpty()) { + this.fluidSlot.setFluid(null); + return; + } + this.fluidSlot.setFluid(_fluids.get(0)); + } + + @Override + public boolean handleDragNDrop(GuiContainer gui, int mouseX, int mouseY, ItemStack draggedStack, int button) { + if (GuiUtil.isPointInRegion( + this.guiLeft, + this.guiTop, + this.fluidSlot.getPosX(), + this.fluidSlot.getPosY(), + 18, + 18, + mouseX, + mouseY)) { + this.fluidSlot.mouseNEIClicked(draggedStack); + return true; + } + return false; + } + + @Override + public boolean hideItemPanelSlot(GuiContainer gui, int x, int y, int w, int h) { + return false; + } + + @Override + public VisiblityData modifyVisiblity(GuiContainer gui, VisiblityData currentVisibility) { + return currentVisibility; + } + + @Override + public Iterable getItemSpawnSlots(GuiContainer gui, ItemStack item) { + return Collections.emptyList(); + } + + @Override + public List getInventoryAreas(GuiContainer gui) { + return null; + } } diff --git a/src/main/scala/extracells/gui/GuiFluidFiller.java b/src/main/scala/extracells/gui/GuiFluidFiller.java index 63645e3f9..90b56c18d 100644 --- a/src/main/scala/extracells/gui/GuiFluidFiller.java +++ b/src/main/scala/extracells/gui/GuiFluidFiller.java @@ -1,75 +1,76 @@ package extracells.gui; -import extracells.container.ContainerFluidFiller; -import extracells.gui.widget.WidgetSlotFluidContainer; -import extracells.tileentity.TileEntityFluidFiller; -import extracells.util.GuiUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; + import org.lwjgl.opengl.GL11; +import extracells.container.ContainerFluidFiller; +import extracells.gui.widget.WidgetSlotFluidContainer; +import extracells.tileentity.TileEntityFluidFiller; +import extracells.util.GuiUtil; + public class GuiFluidFiller extends GuiContainer { - public static final int xSize = 176; - public static final int ySize = 166; - private ResourceLocation guiTexture = new ResourceLocation("extracells", - "textures/gui/fluidfiller.png"); - private WidgetSlotFluidContainer fluidContainerSlot; - private EntityPlayer player; - public GuiFluidFiller(EntityPlayer player, TileEntityFluidFiller tileentity) { - super(new ContainerFluidFiller(player.inventory, tileentity)); - this.player = player; - this.fluidContainerSlot = new WidgetSlotFluidContainer(player, - tileentity, 80, 35); - } + public static final int xSize = 176; + public static final int ySize = 166; + private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/fluidfiller.png"); + private WidgetSlotFluidContainer fluidContainerSlot; + private EntityPlayer player; - @Override - protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { - drawDefaultBackground(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - int posX = (this.width - xSize) / 2; - int posY = (this.height - ySize) / 2; - drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); - } + public GuiFluidFiller(EntityPlayer player, TileEntityFluidFiller tileentity) { + super(new ContainerFluidFiller(player.inventory, tileentity)); + this.player = player; + this.fluidContainerSlot = new WidgetSlotFluidContainer(player, tileentity, 80, 35); + } - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - this.fontRendererObj - .drawString( - StatCollector.translateToLocal( - "extracells.block.fluidfiller.name").replace( - "ME ", ""), 5, 5, 0x000000); - int i = this.fluidContainerSlot.getPosX(); - int j = this.fluidContainerSlot.getPosY(); - if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, i, j, 16, 16, - mouseX, mouseY)) { - this.fluidContainerSlot.drawWidgetWithRect(i, j); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glColorMask(true, true, true, false); - this.drawGradientRect(i, j, i + 16, j + 16, -2130706433, - -2130706433); - GL11.glColorMask(true, true, true, true); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - } else - this.fluidContainerSlot.drawWidget(); - } + @Override + protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + int posX = (this.width - xSize) / 2; + int posY = (this.height - ySize) / 2; + drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); + } - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - if (this.fluidContainerSlot != null) - if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, - this.fluidContainerSlot.getPosX(), - this.fluidContainerSlot.getPosY(), 18, 18, mouseX, mouseY)) { - this.fluidContainerSlot.mouseClicked(this.player.inventory - .getItemStack()); + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.block.fluidfiller.name").replace("ME ", ""), + 5, + 5, + 0x000000); + int i = this.fluidContainerSlot.getPosX(); + int j = this.fluidContainerSlot.getPosY(); + if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, i, j, 16, 16, mouseX, mouseY)) { + this.fluidContainerSlot.drawWidgetWithRect(i, j); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glColorMask(true, true, true, false); + this.drawGradientRect(i, j, i + 16, j + 16, -2130706433, -2130706433); + GL11.glColorMask(true, true, true, true); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } else this.fluidContainerSlot.drawWidget(); + } - } - } + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + if (this.fluidContainerSlot != null) if (GuiUtil.isPointInRegion( + this.guiLeft, + this.guiTop, + this.fluidContainerSlot.getPosX(), + this.fluidContainerSlot.getPosY(), + 18, + 18, + mouseX, + mouseY)) { + this.fluidContainerSlot.mouseClicked(this.player.inventory.getItemStack()); + } + } } diff --git a/src/main/scala/extracells/gui/GuiFluidInterface.java b/src/main/scala/extracells/gui/GuiFluidInterface.java index 7ad03dad3..e8b1bc2a7 100644 --- a/src/main/scala/extracells/gui/GuiFluidInterface.java +++ b/src/main/scala/extracells/gui/GuiFluidInterface.java @@ -1,16 +1,7 @@ package extracells.gui; -import appeng.api.implementations.ICraftingPatternItem; -import extracells.api.IFluidInterface; -import extracells.container.ContainerFluidInterface; -import extracells.gui.widget.WidgetFluidTank; -import extracells.gui.widget.fluid.WidgetFluidSlot; -import extracells.network.packet.other.IFluidSlotPartOrBlock; -import extracells.registries.BlockEnum; -import extracells.util.GuiUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; @@ -19,202 +10,216 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import net.minecraftforge.common.util.ForgeDirection; + import org.lwjgl.opengl.GL11; -public class GuiFluidInterface extends GuiContainer { - IFluidInterface fluidInterface; - public WidgetFluidTank[] tanks = new WidgetFluidTank[6]; - public WidgetFluidSlot[] filter = new WidgetFluidSlot[6]; - private ResourceLocation guiTexture = new ResourceLocation("extracells", - "textures/gui/interfacefluid.png"); - private EntityPlayer player; - private ForgeDirection partSide = ForgeDirection.UNKNOWN; - - public GuiFluidInterface(EntityPlayer player, IFluidInterface fluidInterface) { - super(new ContainerFluidInterface(player, fluidInterface)); - this.ySize = 230; - this.fluidInterface = fluidInterface; - this.player = player; - ((ContainerFluidInterface) this.inventorySlots).gui = this; - } - - public GuiFluidInterface(EntityPlayer player, - IFluidInterface fluidInterface, ForgeDirection side) { - this(player, fluidInterface); - this.partSide = side; - } - - @Override - protected void drawGuiContainerBackgroundLayer(float f, int mouseX, - int mouseY) { - drawDefaultBackground(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, - this.ySize); - for (Object s : this.inventorySlots.inventorySlots) { - renderBackground((Slot) s); - } - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - this.fontRendererObj.drawString( - Item.getItemFromBlock(BlockEnum.ECBASEBLOCK.getBlock()) - .getItemStackDisplayName( - new ItemStack(BlockEnum.ECBASEBLOCK.getBlock(), - 1, 0)).replace("ME ", ""), 8, 5, - 0x000000); - this.fontRendererObj.drawString( - StatCollector.translateToLocal("container.inventory"), 8, 136, - 0x000000); - for (WidgetFluidTank tank : this.tanks) { - if (tank != null) - tank.draw(this.guiLeft, this.guiTop, mouseX, mouseY); - } - for (WidgetFluidSlot slot : this.filter) { - if (slot != null) - slot.drawWidget(); - } - for (WidgetFluidTank tank : this.tanks) { - if (tank != null) - if (func_146978_c(tank.posX, tank.posY, 18, 73, mouseX, mouseY)) { - tank.drawDirectionTooltip(mouseX - this.guiLeft, mouseY - - this.guiTop); - } - } - for (WidgetFluidSlot fluidSlot : this.filter) { - if (fluidSlot != null) { - int i = fluidSlot.getPosX() + 1; - int j = fluidSlot.getPosY() + 1; - if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, i, j, - 16, 16, mouseX, mouseY)) { - drawRect(i, j, i + 16, j + 16, -2130706433); - break; - } - } - } - for (Object s : this.inventorySlots.inventorySlots) { - try { - renderOutput((Slot) s, mouseX, mouseY); - } catch (Throwable e) { - e.printStackTrace(); - } - } - } - - @Override - public void initGui() { - super.initGui(); - this.guiLeft = (this.width - this.xSize) / 2; - this.guiTop = (this.height - this.ySize) / 2; - for (int i = 0; i < this.tanks.length; i++) { - if (this.partSide != null - && this.partSide != ForgeDirection.UNKNOWN - && this.partSide.ordinal() != i) - continue; - this.tanks[i] = new WidgetFluidTank( - this.fluidInterface.getFluidTank(ForgeDirection - .getOrientation(i)), i * 20 + 30, 16, - ForgeDirection.getOrientation(i)); - if (this.fluidInterface instanceof IFluidSlotPartOrBlock) { - this.filter[i] = new WidgetFluidSlot(this.player, - (IFluidSlotPartOrBlock) this.fluidInterface, i, - i * 20 + 30, 93); - } - } - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - for (WidgetFluidSlot fluidSlot : this.filter) { - if (fluidSlot != null) - if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, - fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, - mouseX, mouseY)) { - fluidSlot - .mouseClicked(this.player.inventory.getItemStack()); - break; - } - } - } - - private void renderBackground(Slot slot) { - if (slot.getStack() == null && slot.slotNumber < 9) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); - this.mc.getTextureManager().bindTexture( - new ResourceLocation("appliedenergistics2", - "textures/guis/states.png")); - this.drawTexturedModalRect(this.guiLeft + slot.xDisplayPosition, - this.guiTop + slot.yDisplayPosition, 240, 128, 16, 16); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_LIGHTING); - - } - } - - private void renderOutput(Slot slot, int mouseX, int mouseY) - throws Throwable { - if (slot.getStack() != null && slot.slotNumber < 9) { - ItemStack stack = slot.getStack(); - if (stack.getItem() instanceof ICraftingPatternItem) { - ICraftingPatternItem pattern = (ICraftingPatternItem) stack - .getItem(); - ItemStack output = pattern.getPatternForItem(stack, - Minecraft.getMinecraft().theWorld) - .getCondensedOutputs()[0].getItemStack().copy(); - - this.zLevel = 160.0F; - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor3f(1, 1, 1); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glColor3f(1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine - .bindTexture(this.guiTexture); - drawTexturedModalRect(slot.xDisplayPosition, - slot.yDisplayPosition, slot.xDisplayPosition, - slot.yDisplayPosition, 18, 18); - GL11.glEnable(GL11.GL_LIGHTING); - - GL11.glTranslatef(0.0F, 0.0F, 32.0F); - this.zLevel = 150.0F; - RenderItem itemRender = RenderItem.getInstance(); - itemRender.zLevel = 100.0F; - FontRenderer font = null; - if (output != null) - font = output.getItem().getFontRenderer(output); - if (font == null) - font = Minecraft.getMinecraft().fontRenderer; - GL11.glEnable(GL11.GL_DEPTH_TEST); - itemRender.renderItemAndEffectIntoGUI(font, Minecraft - .getMinecraft().getTextureManager(), output, - slot.xDisplayPosition, slot.yDisplayPosition); - itemRender.renderItemOverlayIntoGUI(font, Minecraft - .getMinecraft().getTextureManager(), output, - slot.xDisplayPosition, slot.yDisplayPosition, null); - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - - int i = slot.xDisplayPosition; - int j = slot.yDisplayPosition; - if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, i, j, - 16, 16, mouseX, mouseY)) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - GL11.glColorMask(true, true, true, false); - this.drawGradientRect(i, j, i + 16, j + 16, -2130706433, - -2130706433); - GL11.glColorMask(true, true, true, true); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - } - } - } - } +import appeng.api.implementations.ICraftingPatternItem; +import extracells.api.IFluidInterface; +import extracells.container.ContainerFluidInterface; +import extracells.gui.widget.WidgetFluidTank; +import extracells.gui.widget.fluid.WidgetFluidSlot; +import extracells.network.packet.other.IFluidSlotPartOrBlock; +import extracells.registries.BlockEnum; +import extracells.util.GuiUtil; + +public class GuiFluidInterface extends ECGuiContainer { + + IFluidInterface fluidInterface; + public WidgetFluidTank[] tanks = new WidgetFluidTank[6]; + public WidgetFluidSlot[] filter = new WidgetFluidSlot[6]; + private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/interfacefluid.png"); + private EntityPlayer player; + private ForgeDirection partSide = ForgeDirection.UNKNOWN; + + public GuiFluidInterface(EntityPlayer player, IFluidInterface fluidInterface) { + super(new ContainerFluidInterface(player, fluidInterface)); + this.ySize = 230; + this.fluidInterface = fluidInterface; + this.player = player; + ((ContainerFluidInterface) this.inventorySlots).gui = this; + } + + public GuiFluidInterface(EntityPlayer player, IFluidInterface fluidInterface, ForgeDirection side) { + this(player, fluidInterface); + this.partSide = side; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + for (Object s : this.inventorySlots.inventorySlots) { + renderBackground((Slot) s); + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + this.fontRendererObj.drawString( + Item.getItemFromBlock(BlockEnum.ECBASEBLOCK.getBlock()) + .getItemStackDisplayName(new ItemStack(BlockEnum.ECBASEBLOCK.getBlock(), 1, 0)) + .replace("ME ", ""), + 8, + 5, + 0x000000); + this.fontRendererObj.drawString(StatCollector.translateToLocal("container.inventory"), 8, 136, 0x000000); + for (WidgetFluidTank tank : this.tanks) { + if (tank != null) tank.draw(this.guiLeft, this.guiTop, mouseX, mouseY); + } + for (WidgetFluidSlot slot : this.filter) { + if (slot != null) slot.drawWidget(); + } + for (WidgetFluidTank tank : this.tanks) { + if (tank != null) if (func_146978_c(tank.posX, tank.posY, 18, 73, mouseX, mouseY)) { + tank.drawTooltip(mouseX - this.guiLeft, mouseY - this.guiTop); + } + } + for (WidgetFluidSlot fluidSlot : this.filter) { + if (fluidSlot != null) { + int i = fluidSlot.getPosX() + 1; + int j = fluidSlot.getPosY() + 1; + if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, i, j, 16, 16, mouseX, mouseY)) { + drawRect(i, j, i + 16, j + 16, -2130706433); + break; + } + } + } + showTooltipList(mouseX, mouseY); + for (Object s : this.inventorySlots.inventorySlots) { + try { + renderOutput((Slot) s, mouseX, mouseY); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + @Override + public void initGui() { + super.initGui(); + this.guiLeft = (this.width - this.xSize) / 2; + this.guiTop = (this.height - this.ySize) / 2; + for (int i = 0; i < this.tanks.length; i++) { + if (this.partSide != null && this.partSide != ForgeDirection.UNKNOWN && this.partSide.ordinal() != i) + continue; + this.tanks[i] = new WidgetFluidTank( + this.fluidInterface.getFluidTank(ForgeDirection.getOrientation(i)), + i * 20 + 30, + 16, + ForgeDirection.getOrientation(i)); + if (this.fluidInterface instanceof IFluidSlotPartOrBlock) { + this.filter[i] = new WidgetFluidSlot( + this.player, + (IFluidSlotPartOrBlock) this.fluidInterface, + i, + i * 20 + 30, + 93); + } + } + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + for (WidgetFluidSlot fluidSlot : this.filter) { + if (fluidSlot != null) if (GuiUtil.isPointInRegion( + this.guiLeft, + this.guiTop, + fluidSlot.getPosX(), + fluidSlot.getPosY(), + 18, + 18, + mouseX, + mouseY)) { + fluidSlot.mouseClicked(this.player.inventory.getItemStack()); + break; + } + } + } + + private void renderBackground(Slot slot) { + if (slot.getStack() == null && slot.slotNumber < 9) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F); + this.mc.getTextureManager() + .bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + this.drawTexturedModalRect( + this.guiLeft + slot.xDisplayPosition, + this.guiTop + slot.yDisplayPosition, + 240, + 128, + 16, + 16); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_LIGHTING); + } + } + + private void renderOutput(Slot slot, int mouseX, int mouseY) throws Throwable { + if (slot.getStack() != null && slot.slotNumber < 9) { + ItemStack stack = slot.getStack(); + if (stack.getItem() instanceof ICraftingPatternItem) { + ICraftingPatternItem pattern = (ICraftingPatternItem) stack.getItem(); + ItemStack output = pattern.getPatternForItem(stack, Minecraft.getMinecraft().theWorld) + .getCondensedOutputs()[0].getItemStack().copy(); + + this.zLevel = 160.0F; + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor3f(1, 1, 1); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glColor3f(1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect( + slot.xDisplayPosition, + slot.yDisplayPosition, + slot.xDisplayPosition, + slot.yDisplayPosition, + 18, + 18); + GL11.glEnable(GL11.GL_LIGHTING); + + GL11.glTranslatef(0.0F, 0.0F, 32.0F); + this.zLevel = 150.0F; + RenderItem itemRender = RenderItem.getInstance(); + itemRender.zLevel = 100.0F; + FontRenderer font = null; + if (output != null) font = output.getItem().getFontRenderer(output); + if (font == null) font = Minecraft.getMinecraft().fontRenderer; + GL11.glEnable(GL11.GL_DEPTH_TEST); + itemRender.renderItemAndEffectIntoGUI( + font, + Minecraft.getMinecraft().getTextureManager(), + output, + slot.xDisplayPosition, + slot.yDisplayPosition); + itemRender.renderItemOverlayIntoGUI( + font, + Minecraft.getMinecraft().getTextureManager(), + output, + slot.xDisplayPosition, + slot.yDisplayPosition, + null); + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + + int i = slot.xDisplayPosition; + int j = slot.yDisplayPosition; + if (GuiUtil.isPointInRegion(this.guiLeft, this.guiTop, i, j, 16, 16, mouseX, mouseY)) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glColorMask(true, true, true, false); + this.drawGradientRect(i, j, i + 16, j + 16, -2130706433, -2130706433); + GL11.glColorMask(true, true, true, true); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + } + } + } + } } diff --git a/src/main/scala/extracells/gui/GuiFluidPlaneFormation.java b/src/main/scala/extracells/gui/GuiFluidPlaneFormation.java index 606637b19..ab230f0f7 100644 --- a/src/main/scala/extracells/gui/GuiFluidPlaneFormation.java +++ b/src/main/scala/extracells/gui/GuiFluidPlaneFormation.java @@ -1,146 +1,142 @@ package extracells.gui; -import appeng.api.AEApi; -import extracells.container.ContainerPlaneFormation; -import extracells.gui.widget.WidgetRedstoneModes; -import extracells.gui.widget.fluid.WidgetFluidSlot; -import extracells.network.packet.other.IFluidSlotGui; -import extracells.network.packet.part.PacketFluidPlaneFormation; -import extracells.part.PartFluidPlaneFormation; -import extracells.util.FluidUtil; +import java.util.List; + import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; + import org.lwjgl.opengl.GL11; -import java.util.List; +import appeng.api.AEApi; +import extracells.container.ContainerPlaneFormation; +import extracells.gui.widget.WidgetRedstoneModes; +import extracells.gui.widget.fluid.WidgetFluidSlot; +import extracells.network.packet.other.IFluidSlotGui; +import extracells.network.packet.part.PacketFluidPlaneFormation; +import extracells.part.PartFluidPlaneFormation; +import extracells.util.FluidUtil; -public class GuiFluidPlaneFormation extends GuiContainer implements - IFluidSlotGui { - - private static final ResourceLocation guiTexture = new ResourceLocation( - "extracells", "textures/gui/paneformation.png"); - private PartFluidPlaneFormation part; - private EntityPlayer player; - private WidgetFluidSlot fluidSlot; - private boolean hasNetworkTool; - - public GuiFluidPlaneFormation(PartFluidPlaneFormation _part, - EntityPlayer _player) { - super(new ContainerPlaneFormation(_part, _player)); - ((ContainerPlaneFormation) this.inventorySlots).setGui(this); - this.part = _part; - this.player = _player; - this.fluidSlot = new WidgetFluidSlot(this.player, this.part, 0, 79, 39); - new PacketFluidPlaneFormation(this.player, this.part) - .sendPacketToServer(); - this.hasNetworkTool = this.inventorySlots.getInventory().size() > 40; - this.xSize = this.hasNetworkTool ? 246 : 211; - this.ySize = 184; - - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int mouseX, - int mouseY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 184); - drawTexturedModalRect(this.guiLeft + 179, this.guiTop, 179, 0, 32, 86); - if (this.hasNetworkTool) - drawTexturedModalRect(this.guiLeft + 179, this.guiTop + 93, 178, - 93, 68, 68); - - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - this.fluidSlot.drawWidget(); - renderOverlay(this.fluidSlot, mouseX, mouseY); - - for (Object button : this.buttonList) { - if (button instanceof WidgetRedstoneModes) - ((WidgetRedstoneModes) button).drawTooltip(this.guiLeft, - this.guiTop, (this.width - this.xSize) / 2, - (this.height - this.ySize) / 2); - } - } - - protected Slot getSlotAtPosition(int p_146975_1_, int p_146975_2_) { - for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { - Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); - - if (this.isMouseOverSlot(slot, p_146975_1_, p_146975_2_)) { - return slot; - } - } - - return null; - } - - private boolean isMouseOverSlot(Slot p_146981_1_, int p_146981_2_, - int p_146981_3_) { - return this.func_146978_c(p_146981_1_.xDisplayPosition, - p_146981_1_.yDisplayPosition, 16, 16, p_146981_2_, p_146981_3_); - } - - protected boolean isPointInRegion(int top, int left, int height, int width, - int pointX, int pointY) { - int k1 = this.guiLeft; - int l1 = this.guiTop; - pointX -= k1; - pointY -= l1; - return pointX >= top - 1 && pointX < top + height + 1 - && pointY >= left - 1 && pointY < left + width + 1; - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - Slot slot = getSlotAtPosition(mouseX, mouseY); - - if (slot != null - && slot.getStack() != null - && AEApi.instance().definitions().items().networkTool().isSameAs(slot.getStack())) - return; - super.mouseClicked(mouseX, mouseY, mouseBtn); - if (isPointInRegion(this.fluidSlot.getPosX(), this.fluidSlot.getPosY(), - 18, 18, mouseX, mouseY)) - this.fluidSlot.mouseClicked(this.player.inventory.getItemStack()); - } - - public boolean renderOverlay(WidgetFluidSlot fluidSlot, int mouseX, - int mouseY) { - if (isPointInRegion(fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, - mouseX, mouseY)) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - drawGradientRect(fluidSlot.getPosX() + 1, fluidSlot.getPosY() + 1, - fluidSlot.getPosX() + 17, fluidSlot.getPosY() + 17, - -0x7F000001, -0x7F000001); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - return true; - } - return false; - } - - public void shiftClick(ItemStack itemStack) { - FluidStack containerFluid = FluidUtil.getFluidFromContainer(itemStack); - Fluid fluid = containerFluid == null ? null : containerFluid.getFluid(); - - if (this.fluidSlot.getFluid() == null || fluid != null - && this.fluidSlot.getFluid() == fluid) - this.fluidSlot.mouseClicked(itemStack); - } - - @Override - public void updateFluids(List fluidList) { - this.fluidSlot.setFluid(fluidList.get(0)); - } +public class GuiFluidPlaneFormation extends ECGuiContainer implements IFluidSlotGui { + + private static final ResourceLocation guiTexture = new ResourceLocation( + "extracells", + "textures/gui/paneformation.png"); + private PartFluidPlaneFormation part; + private EntityPlayer player; + private boolean hasNetworkTool; + + public GuiFluidPlaneFormation(PartFluidPlaneFormation _part, EntityPlayer _player) { + super(new ContainerPlaneFormation(_part, _player)); + ((ContainerPlaneFormation) this.inventorySlots).setGui(this); + this.part = _part; + this.player = _player; + this.fluidSlot = new WidgetFluidSlot(this.player, this.part, 0, 79, 39); + new PacketFluidPlaneFormation(this.player, this.part).sendPacketToServer(); + this.hasNetworkTool = this.inventorySlots.getInventory().size() > 40; + this.xSize = this.hasNetworkTool ? 246 : 211; + this.ySize = 184; + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int mouseX, int mouseY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, 176, 184); + drawTexturedModalRect(this.guiLeft + 179, this.guiTop, 179, 0, 32, 86); + if (this.hasNetworkTool) drawTexturedModalRect(this.guiLeft + 179, this.guiTop + 93, 178, 93, 68, 68); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + this.fluidSlot.drawWidget(); + renderOverlay(this.fluidSlot, mouseX, mouseY); + + for (Object button : this.buttonList) { + if (button instanceof WidgetRedstoneModes) ((WidgetRedstoneModes) button).drawTooltip( + this.guiLeft, + this.guiTop, + (this.width - this.xSize) / 2, + (this.height - this.ySize) / 2); + } + showTooltip(mouseX, mouseY); + } + + protected Slot getSlotAtPosition(int p_146975_1_, int p_146975_2_) { + for (int k = 0; k < this.inventorySlots.inventorySlots.size(); ++k) { + Slot slot = (Slot) this.inventorySlots.inventorySlots.get(k); + + if (this.isMouseOverSlot(slot, p_146975_1_, p_146975_2_)) { + return slot; + } + } + + return null; + } + + private boolean isMouseOverSlot(Slot p_146981_1_, int p_146981_2_, int p_146981_3_) { + return this.func_146978_c( + p_146981_1_.xDisplayPosition, + p_146981_1_.yDisplayPosition, + 16, + 16, + p_146981_2_, + p_146981_3_); + } + + protected boolean isPointInRegion(int top, int left, int height, int width, int pointX, int pointY) { + int k1 = this.guiLeft; + int l1 = this.guiTop; + pointX -= k1; + pointY -= l1; + return pointX >= top - 1 && pointX < top + height + 1 && pointY >= left - 1 && pointY < left + width + 1; + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + Slot slot = getSlotAtPosition(mouseX, mouseY); + + if (slot != null && slot.getStack() != null + && AEApi.instance().definitions().items().networkTool().isSameAs(slot.getStack())) + return; + super.mouseClicked(mouseX, mouseY, mouseBtn); + if (isPointInRegion(this.fluidSlot.getPosX(), this.fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) + this.fluidSlot.mouseClicked(this.player.inventory.getItemStack()); + } + + public boolean renderOverlay(WidgetFluidSlot fluidSlot, int mouseX, int mouseY) { + if (isPointInRegion(fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + drawGradientRect( + fluidSlot.getPosX() + 1, + fluidSlot.getPosY() + 1, + fluidSlot.getPosX() + 17, + fluidSlot.getPosY() + 17, + -0x7F000001, + -0x7F000001); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + return true; + } + return false; + } + + public void shiftClick(ItemStack itemStack) { + FluidStack containerFluid = FluidUtil.getFluidFromContainer(itemStack); + Fluid fluid = containerFluid == null ? null : containerFluid.getFluid(); + + if (this.fluidSlot.getFluid() == null || fluid != null && this.fluidSlot.getFluid() == fluid) + this.fluidSlot.mouseClicked(itemStack); + } + + @Override + public void updateFluids(List fluidList) { + this.fluidSlot.setFluid(fluidList.get(0)); + } } diff --git a/src/main/scala/extracells/gui/GuiFluidStorage.java b/src/main/scala/extracells/gui/GuiFluidStorage.java index 792a8a0f1..38e5f2e05 100644 --- a/src/main/scala/extracells/gui/GuiFluidStorage.java +++ b/src/main/scala/extracells/gui/GuiFluidStorage.java @@ -1,235 +1,237 @@ package extracells.gui; -import appeng.api.storage.data.IAEFluidStack; -import extracells.Extracells; -import extracells.api.ECApi; -import extracells.container.ContainerFluidStorage; -import extracells.gui.widget.FluidWidgetComparator; -import extracells.gui.widget.fluid.AbstractFluidWidget; -import extracells.gui.widget.fluid.IFluidSelectorContainer; -import extracells.gui.widget.fluid.IFluidSelectorGui; -import extracells.gui.widget.fluid.WidgetFluidSelector; -import extracells.network.packet.part.PacketFluidStorage; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; + import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import appeng.api.storage.data.IAEFluidStack; +import extracells.Extracells; +import extracells.api.ECApi; +import extracells.container.ContainerFluidStorage; +import extracells.gui.widget.FluidWidgetComparator; +import extracells.gui.widget.fluid.AbstractFluidWidget; +import extracells.gui.widget.fluid.IFluidSelectorContainer; +import extracells.gui.widget.fluid.IFluidSelectorGui; +import extracells.gui.widget.fluid.WidgetFluidSelector; +import extracells.network.packet.part.PacketFluidStorage; +import extracells.util.FluidUtil; public class GuiFluidStorage extends GuiContainer implements IFluidSelectorGui { - private EntityPlayer player; - private int currentScroll = 0; - private GuiTextField searchbar; - private List fluidWidgets = new ArrayList(); - private ResourceLocation guiTexture = new ResourceLocation("extracells", - "textures/gui/terminalfluid.png"); - public IAEFluidStack currentFluid; - private ContainerFluidStorage containerFluidStorage; - private final String guiName; - - public GuiFluidStorage(EntityPlayer _player, String _guiName) { - super(new ContainerFluidStorage(_player)); - this.containerFluidStorage = (ContainerFluidStorage) this.inventorySlots; - this.containerFluidStorage.setGui(this); - this.player = _player; - this.xSize = 176; - this.ySize = 204; - this.guiName = _guiName; - new PacketFluidStorage(this.player).sendPacketToServer(); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, - int sizeY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, - this.ySize); - this.searchbar.drawTextBox(); - new PacketFluidStorage(this.player).sendPacketToServer(); - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - this.fontRendererObj - .drawString(StatCollector.translateToLocal(this.guiName) - .replace("ME ", ""), 5, 6, 0x000000); - drawWidgets(mouseX, mouseY); - if (this.currentFluid != null) { - long currentFluidAmount = this.currentFluid.getStackSize(); - String amountToText = Long.toString(currentFluidAmount) + "mB"; - if (Extracells.shortenedBuckets()) { - if (currentFluidAmount > 1000000000L) - amountToText = Long - .toString(currentFluidAmount / 1000000000L) - + "MegaB"; - else if (currentFluidAmount > 1000000L) - amountToText = Long.toString(currentFluidAmount / 1000000L) - + "KiloB"; - else if (currentFluidAmount > 9999L) { - amountToText = Long.toString(currentFluidAmount / 1000L) - + "B"; - } - } - - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.amount") - + ": " + amountToText, 45, 91, 0x000000); - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " - + this.currentFluid.getFluid().getLocalizedName( - this.currentFluid.getFluidStack()), 45, 101, - 0x000000); - } - } - - public void drawWidgets(int mouseX, int mouseY) { - int listSize = this.fluidWidgets.size(); - if (!this.containerFluidStorage.getFluidStackList().isEmpty()) { - outerLoop: for (int y = 0; y < 4; y++) { - for (int x = 0; x < 9; x++) { - int widgetIndex = y * 9 + x + this.currentScroll * 9; - if (0 <= widgetIndex && widgetIndex < listSize) { - AbstractFluidWidget widget = this.fluidWidgets - .get(widgetIndex); - widget.drawWidget(x * 18 + 7, y * 18 + 17); - } else { - break outerLoop; - } - } - } - - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int widgetIndex = y * 9 + x; - if (0 <= widgetIndex && widgetIndex < listSize) { - this.fluidWidgets.get(widgetIndex).drawTooltip( - x * 18 + 7, y * 18 - 1, mouseX, mouseY); - } else { - break; - } - } - } - - int deltaWheel = Mouse.getDWheel(); - if (deltaWheel > 0) { - this.currentScroll++; - } else if (deltaWheel < 0) { - this.currentScroll--; - } - - if (this.currentScroll < 0) - this.currentScroll = 0; - if (listSize / 9 < 4 && this.currentScroll < listSize / 9 + 4) - this.currentScroll = 0; - } - } - - @Override - public IFluidSelectorContainer getContainer() { - return this.containerFluidStorage; - } - - @Override - public IAEFluidStack getCurrentFluid() { - return this.containerFluidStorage.getSelectedFluidStack(); - } - - @Override - public int guiLeft() { - return this.guiLeft; - } - - @Override - public int guiTop() { - return this.guiTop; - } - - @Override - public void initGui() { - super.initGui(); - Mouse.getDWheel(); - - updateFluids(); - Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); - this.searchbar = new GuiTextField(this.fontRendererObj, - this.guiLeft + 81, this.guiTop + 6, 88, 10) { - - private int xPos = 0; - private int yPos = 0; - private int width = 0; - private int height = 0; - - @Override - public void mouseClicked(int x, int y, int mouseBtn) { - boolean flag = x >= this.xPos && x < this.xPos + this.width - && y >= this.yPos && y < this.yPos + this.height; - if (flag && mouseBtn == 3) - setText(""); - } - }; - this.searchbar.setEnableBackgroundDrawing(false); - this.searchbar.setFocused(true); - this.searchbar.setMaxStringLength(15); - } - - @Override - protected void keyTyped(char key, int keyID) { - if (keyID == Keyboard.KEY_ESCAPE) - this.mc.thePlayer.closeScreen(); - this.searchbar.textboxKeyTyped(key, keyID); - updateFluids(); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); - int listSize = this.fluidWidgets.size(); - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int index = y * 9 + x; - if (0 <= index && index < listSize) { - AbstractFluidWidget widget = this.fluidWidgets.get(index); - widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); - } - } - } - } - - public void updateFluids() { - this.fluidWidgets = new ArrayList(); - for (IAEFluidStack fluidStack : this.containerFluidStorage - .getFluidStackList()) { - if (fluidStack.getFluid() - .getLocalizedName(fluidStack.getFluidStack()).toLowerCase() - .contains(this.searchbar.getText().toLowerCase()) - && ECApi.instance().canFluidSeeInTerminal( - fluidStack.getFluid())) { - this.fluidWidgets - .add(new WidgetFluidSelector(this, fluidStack)); - } - } - updateSelectedFluid(); - } - - public void updateSelectedFluid() { - this.currentFluid = null; - for (IAEFluidStack stack : this.containerFluidStorage - .getFluidStackList()) { - if (stack.getFluid() == this.containerFluidStorage - .getSelectedFluid()) - this.currentFluid = stack; - } - } + private final EntityPlayer player; + private int currentScroll = 0; + private GuiTextField searchbar; + private List fluidWidgets = new ArrayList(); + private final ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); + public IAEFluidStack currentFluid; + private final ContainerFluidStorage containerFluidStorage; + private final String guiName; + private List cache = new ArrayList(); + private int tick = Extracells.terminalUpdateInterval(); + + public GuiFluidStorage(EntityPlayer _player, String _guiName) { + super(new ContainerFluidStorage(_player)); + this.containerFluidStorage = (ContainerFluidStorage) this.inventorySlots; + this.containerFluidStorage.setGui(this); + this.player = _player; + this.xSize = 176; + this.ySize = 204; + this.guiName = _guiName; + new PacketFluidStorage(this.player).sendPacketToServer(); + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + this.searchbar.drawTextBox(); + } + + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.fontRendererObj + .drawString(StatCollector.translateToLocal(this.guiName).replace("ME ", ""), 5, 6, 0x000000); + drawWidgets(mouseX, mouseY); + if (this.currentFluid != null) { + long currentFluidAmount = this.currentFluid.getStackSize(); + String amountToText = FluidUtil.formatFluidAmount(currentFluidAmount, true); + + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amountToText, + 45, + 91, + 0x000000); + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + this.currentFluid.getFluid().getLocalizedName(this.currentFluid.getFluidStack()), + 45, + 101, + 0x000000); + } + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + int deltaWheel = Mouse.getEventDWheel(); + if (deltaWheel < 0) { + currentScroll++; + } else if (deltaWheel > 0) { + currentScroll--; + } + } + + private List getCache() { + return this.cache; + } + + private void setCache(List _list) { + this.cache = _list; + } + + public void drawWidgets(int mouseX, int mouseY) { + if (tick < Extracells.terminalUpdateInterval() && this.getCache().size() > 0) { + tick++; + } else { + tick = 0; + this.setCache(this.fluidWidgets); + } + List tmp = this.getCache(); + int listSize = tmp.size(); + if (!this.containerFluidStorage.getFluidStackList().isEmpty()) { + outerLoop: for (int y = 0; y < 4; y++) { + for (int x = 0; x < 9; x++) { + int widgetIndex = y * 9 + x + this.currentScroll * 9; + if (0 <= widgetIndex && widgetIndex < listSize) { + AbstractFluidWidget widget = tmp.get(widgetIndex); + widget.drawWidget(x * 18 + 7, y * 18 + 17); + } else { + break outerLoop; + } + } + } + + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int widgetIndex = y * 9 + x + this.currentScroll * 9; + if (0 <= widgetIndex && widgetIndex < listSize) { + tmp.get(widgetIndex).drawTooltip(x * 18 + 7, y * 18 - 1, mouseX, mouseY); + } else { + break; + } + } + } + if (this.currentScroll < 0) this.currentScroll = 0; + int maxLine = listSize % 9 == 0 ? listSize / 9 : listSize / 9 + 1; + if (this.currentScroll > maxLine - 4) { + this.currentScroll = Math.max(maxLine - 4, 0); + } + } + } + + @Override + public IFluidSelectorContainer getContainer() { + return this.containerFluidStorage; + } + + @Override + public IAEFluidStack getCurrentFluid() { + return this.containerFluidStorage.getSelectedFluidStack(); + } + + @Override + public int guiLeft() { + return this.guiLeft; + } + + @Override + public int guiTop() { + return this.guiTop; + } + + @Override + public void initGui() { + super.initGui(); + + updateFluids(); + Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); + this.searchbar = new GuiTextField(this.fontRendererObj, this.guiLeft + 81, this.guiTop + 6, 88, 10) { + + private final int xPos = 0; + private final int yPos = 0; + private final int width = 0; + private final int height = 0; + + @Override + public void mouseClicked(int x, int y, int mouseBtn) { + boolean flag = x >= this.xPos && x < this.xPos + this.width + && y >= this.yPos + && y < this.yPos + this.height; + if (flag && mouseBtn == 3) setText(""); + } + }; + this.searchbar.setEnableBackgroundDrawing(false); + this.searchbar.setFocused(true); + this.searchbar.setMaxStringLength(15); + this.searchbar.setText(""); + } + + @Override + protected void keyTyped(char key, int keyID) { + if (keyID == Keyboard.KEY_ESCAPE) this.mc.thePlayer.closeScreen(); + this.searchbar.textboxKeyTyped(key, keyID); + updateFluids(); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); + int listSize = this.getCache().size(); + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int index = y * 9 + x + this.currentScroll * 9; + if (0 <= index && index < listSize) { + AbstractFluidWidget widget = this.getCache().get(index); + widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); + } + } + } + } + + public void updateFluids() { + if (this.searchbar != null && !this.searchbar.getText().isEmpty()) { + this.containerFluidStorage.forceFluidUpdate(this.searchbar.getText()); + } else { + this.containerFluidStorage.forceFluidUpdate(); + } + this.fluidWidgets = new ArrayList(); + for (IAEFluidStack fluidStack : this.containerFluidStorage.getFluidStackList()) { + if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase() + .contains(this.searchbar.getText().toLowerCase()) + && ECApi.instance().canFluidSeeInTerminal(fluidStack.getFluid())) { + this.fluidWidgets.add(new WidgetFluidSelector(this, fluidStack)); + } + } + Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); + updateSelectedFluid(); + } + + public void updateSelectedFluid() { + this.currentFluid = null; + for (IAEFluidStack stack : this.containerFluidStorage.getFluidStackList()) { + if (stack.getFluid() == this.containerFluidStorage.getSelectedFluid()) this.currentFluid = stack; + } + } } diff --git a/src/main/scala/extracells/gui/GuiFluidTerminal.java b/src/main/scala/extracells/gui/GuiFluidTerminal.java index a28df47a2..24b9eee18 100644 --- a/src/main/scala/extracells/gui/GuiFluidTerminal.java +++ b/src/main/scala/extracells/gui/GuiFluidTerminal.java @@ -1,5 +1,20 @@ package extracells.gui; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + import appeng.api.storage.data.IAEFluidStack; import extracells.Extracells; import extracells.api.ECApi; @@ -11,208 +26,222 @@ import extracells.gui.widget.fluid.WidgetFluidSelector; import extracells.network.packet.part.PacketFluidTerminal; import extracells.part.PartFluidTerminal; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import extracells.util.FluidUtil; public class GuiFluidTerminal extends GuiContainer implements IFluidSelectorGui { - private PartFluidTerminal terminal; - private EntityPlayer player; - private int currentScroll = 0; - private GuiTextField searchbar; - private List fluidWidgets = new ArrayList(); - private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); - public IAEFluidStack currentFluid; - private ContainerFluidTerminal containerTerminalFluid; - - public GuiFluidTerminal(PartFluidTerminal _terminal, EntityPlayer _player) { - super(new ContainerFluidTerminal(_terminal, _player)); - this.containerTerminalFluid = (ContainerFluidTerminal) this.inventorySlots; - this.containerTerminalFluid.setGui(this); - this.terminal = _terminal; - this.player = _player; - this.xSize = 176; - this.ySize = 204; - new PacketFluidTerminal(this.player, this.terminal).sendPacketToServer(); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); - this.searchbar.drawTextBox(); - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.part.fluid.terminal.name").replace("ME ", ""), 9, 6, 0x000000); - drawWidgets(mouseX, mouseY); - if (this.currentFluid != null) { - long currentFluidAmount = this.currentFluid.getStackSize(); - String amountToText = Long.toString(currentFluidAmount) + "mB"; - if (Extracells.shortenedBuckets()) { - if (currentFluidAmount > 1000000000L) - amountToText = Long - .toString(currentFluidAmount / 1000000000L) + "MegaB"; - else if (currentFluidAmount > 1000000L) - amountToText = Long.toString(currentFluidAmount / 1000000L) + "KiloB"; - else if (currentFluidAmount > 9999L) { - amountToText = Long.toString(currentFluidAmount / 1000L) + "B"; - } - } - - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amountToText, 45, 91, 0x000000); - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + this.currentFluid.getFluid().getLocalizedName(this.currentFluid.getFluidStack()), 45, 101, 0x000000); - } - } - - public void drawWidgets(int mouseX, int mouseY) { - int listSize = this.fluidWidgets.size(); - if (!this.containerTerminalFluid.getFluidStackList().isEmpty()) { - outerLoop: for (int y = 0; y < 4; y++) { - for (int x = 0; x < 9; x++) { - int widgetIndex = y * 9 + x + this.currentScroll * 9; - if (0 <= widgetIndex && widgetIndex < listSize) { - AbstractFluidWidget widget = this.fluidWidgets.get(widgetIndex); - widget.drawWidget(x * 18 + 7, y * 18 + 17); - } else { - break outerLoop; - } - } - } - - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int widgetIndex = y * 9 + x; - if (0 <= widgetIndex && widgetIndex < listSize) { - if (this.fluidWidgets.get(widgetIndex).drawTooltip(x * 18 + 7, y * 18 - 1, mouseX, mouseY)) - break; - } else { - break; - } - } - } - - int deltaWheel = Mouse.getDWheel(); - if (deltaWheel > 0) { - this.currentScroll++; - } else if (deltaWheel < 0) { - this.currentScroll--; - } - - if (this.currentScroll < 0) - this.currentScroll = 0; - if (listSize / 9 < 4 && this.currentScroll < listSize / 9 + 4) - this.currentScroll = 0; - } - } - - @Override - public IFluidSelectorContainer getContainer() { - return this.containerTerminalFluid; - } - - @Override - public IAEFluidStack getCurrentFluid() { - return this.currentFluid; - } - - public PartFluidTerminal getTerminal() { - return this.terminal; - } - - @Override - public int guiLeft() { - return this.guiLeft; - } - - @Override - public int guiTop() { - return this.guiTop; - } - - @Override - public void initGui() { - super.initGui(); - Mouse.getDWheel(); - - updateFluids(); - Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); - this.searchbar = new GuiTextField(this.fontRendererObj, - this.guiLeft + 81, this.guiTop + 6, 88, 10) { - - private int xPos = 0; - private int yPos = 0; - private int width = 0; - private int height = 0; - - @Override - public void mouseClicked(int x, int y, int mouseBtn) { - boolean flag = x >= this.xPos && x < this.xPos + this.width && y >= this.yPos && y < this.yPos + this.height; - if (flag && mouseBtn == 3) - setText(""); - } - }; - this.searchbar.setEnableBackgroundDrawing(false); - this.searchbar.setFocused(true); - this.searchbar.setMaxStringLength(15); - } - - @Override - protected void keyTyped(char key, int keyID) { - if (keyID == Keyboard.KEY_ESCAPE) - this.mc.thePlayer.closeScreen(); - this.searchbar.textboxKeyTyped(key, keyID); - updateFluids(); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); - int listSize = this.fluidWidgets.size(); - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int index = y * 9 + x; - if (0 <= index && index < listSize) { - AbstractFluidWidget widget = this.fluidWidgets.get(index); - widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); - } - } - } - } - - public void updateFluids() { - this.fluidWidgets = new ArrayList(); - for (IAEFluidStack fluidStack : this.containerTerminalFluid.getFluidStackList()) { - if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase().contains(this.searchbar.getText().toLowerCase()) && ECApi.instance().canFluidSeeInTerminal( - fluidStack.getFluid())) { - this.fluidWidgets.add(new WidgetFluidSelector(this, fluidStack)); - } - } - updateSelectedFluid(); - } - - public void updateSelectedFluid() { - this.currentFluid = null; - for (IAEFluidStack stack : this.containerTerminalFluid.getFluidStackList()) { - if (stack.getFluid() == this.containerTerminalFluid.getSelectedFluid()) - this.currentFluid = stack; - } - } + private final PartFluidTerminal terminal; + private final EntityPlayer player; + private int currentScroll = 0; + private GuiTextField searchbar; + private List fluidWidgets = new ArrayList(); + private final ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); + public IAEFluidStack currentFluid; + private final ContainerFluidTerminal containerTerminalFluid; + private List cache = new ArrayList(); + private int tick = Extracells.terminalUpdateInterval(); + + public GuiFluidTerminal(PartFluidTerminal _terminal, EntityPlayer _player) { + super(new ContainerFluidTerminal(_terminal, _player)); + this.containerTerminalFluid = (ContainerFluidTerminal) this.inventorySlots; + this.containerTerminalFluid.setGui(this); + this.terminal = _terminal; + this.player = _player; + this.xSize = 176; + this.ySize = 204; + new PacketFluidTerminal(this.player, this.terminal).sendPacketToServer(); + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + this.searchbar.drawTextBox(); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.part.fluid.terminal.name").replace("ME ", ""), + 9, + 6, + 0x000000); + drawWidgets(mouseX, mouseY); + if (this.currentFluid != null) { + long currentFluidAmount = this.currentFluid.getStackSize(); + String amountToText = FluidUtil.formatFluidAmount(currentFluidAmount, true); + + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amountToText, + 45, + 91, + 0x000000); + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + this.currentFluid.getFluid().getLocalizedName(this.currentFluid.getFluidStack()), + 45, + 101, + 0x000000); + } + } + + private List getCache() { + return this.cache; + } + + private void setCache(List _list) { + this.cache = _list; + } + + public void drawWidgets(int mouseX, int mouseY) { + if (tick < Extracells.terminalUpdateInterval() && this.getCache().size() > 0) { + tick++; + } else { + tick = 0; + this.setCache(this.fluidWidgets); + } + int listSize = this.getCache().size(); + if (!this.containerTerminalFluid.getFluidStackList().isEmpty()) { + outerLoop: for (int y = 0; y < 4; y++) { + for (int x = 0; x < 9; x++) { + int widgetIndex = y * 9 + x + this.currentScroll * 9; + if (0 <= widgetIndex && widgetIndex < listSize) { + AbstractFluidWidget widget = this.getCache().get(widgetIndex); + widget.drawWidget(x * 18 + 7, y * 18 + 17); + } else { + break outerLoop; + } + } + } + + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int widgetIndex = y * 9 + x + this.currentScroll * 9; + if (0 <= widgetIndex && widgetIndex < listSize) { + if (this.getCache().get(widgetIndex).drawTooltip(x * 18 + 7, y * 18 - 1, mouseX, mouseY)) break; + } else { + break; + } + } + } + + if (this.currentScroll < 0) this.currentScroll = 0; + int maxLine = listSize % 9 == 0 ? listSize / 9 : listSize / 9 + 1; + if (this.currentScroll > maxLine - 4) { + this.currentScroll = Math.max(maxLine - 4, 0); + } + } + } + + @Override + public IFluidSelectorContainer getContainer() { + return this.containerTerminalFluid; + } + + @Override + public IAEFluidStack getCurrentFluid() { + return this.currentFluid; + } + + public PartFluidTerminal getTerminal() { + return this.terminal; + } + + @Override + public int guiLeft() { + return this.guiLeft; + } + + @Override + public int guiTop() { + return this.guiTop; + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + int deltaWheel = Mouse.getEventDWheel(); + if (deltaWheel < 0) { + currentScroll++; + } else if (deltaWheel > 0) { + currentScroll--; + } + } + + @Override + public void initGui() { + super.initGui(); + + updateFluids(); + Collections.sort(this.getCache(), new FluidWidgetComparator()); + this.searchbar = new GuiTextField(this.fontRendererObj, this.guiLeft + 81, this.guiTop + 6, 88, 10) { + + private final int xPos = 0; + private final int yPos = 0; + private final int width = 0; + private final int height = 0; + + @Override + public void mouseClicked(int x, int y, int mouseBtn) { + boolean flag = x >= this.xPos && x < this.xPos + this.width + && y >= this.yPos + && y < this.yPos + this.height; + if (flag && mouseBtn == 3) setText(""); + } + }; + this.searchbar.setEnableBackgroundDrawing(false); + this.searchbar.setFocused(true); + this.searchbar.setMaxStringLength(15); + this.searchbar.setText(""); + } + + @Override + protected void keyTyped(char key, int keyID) { + if (keyID == Keyboard.KEY_ESCAPE) this.mc.thePlayer.closeScreen(); + this.searchbar.textboxKeyTyped(key, keyID); + updateFluids(); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); + int listSize = this.getCache().size(); + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int index = y * 9 + x + this.currentScroll * 9; + if (0 <= index && index < listSize) { + AbstractFluidWidget widget = this.getCache().get(index); + widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); + } + } + } + } + + public void updateFluids() { + if (this.searchbar != null && !this.searchbar.getText().isEmpty()) { + this.containerTerminalFluid.forceFluidUpdate(this.searchbar.getText()); + } else { + this.containerTerminalFluid.forceFluidUpdate(); + } + this.fluidWidgets = new ArrayList(); + for (IAEFluidStack fluidStack : this.containerTerminalFluid.getFluidStackList()) { + if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase() + .contains(this.searchbar.getText().toLowerCase()) + && ECApi.instance().canFluidSeeInTerminal(fluidStack.getFluid())) { + this.fluidWidgets.add(new WidgetFluidSelector(this, fluidStack)); + } + } + Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); + + updateSelectedFluid(); + } + + public void updateSelectedFluid() { + this.currentFluid = null; + for (IAEFluidStack stack : this.containerTerminalFluid.getFluidStackList()) { + if (stack.getFluid() == this.containerTerminalFluid.getSelectedFluid()) this.currentFluid = stack; + } + } } diff --git a/src/main/scala/extracells/gui/GuiGasStorage.java b/src/main/scala/extracells/gui/GuiGasStorage.java index 3c93d491f..4c67cf600 100644 --- a/src/main/scala/extracells/gui/GuiGasStorage.java +++ b/src/main/scala/extracells/gui/GuiGasStorage.java @@ -1,222 +1,217 @@ package extracells.gui; -import appeng.api.storage.data.IAEFluidStack; -import extracells.Extracells; -import extracells.api.ECApi; -import extracells.container.ContainerGasStorage; -import extracells.gui.widget.FluidWidgetComparator; -import extracells.gui.widget.fluid.AbstractFluidWidget; -import extracells.gui.widget.fluid.IFluidSelectorContainer; -import extracells.gui.widget.fluid.IFluidSelectorGui; -import extracells.gui.widget.fluid.WidgetFluidSelector; -import extracells.network.packet.part.PacketFluidStorage; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; + import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import appeng.api.storage.data.IAEFluidStack; +import extracells.Extracells; +import extracells.api.ECApi; +import extracells.container.ContainerGasStorage; +import extracells.gui.widget.FluidWidgetComparator; +import extracells.gui.widget.fluid.AbstractFluidWidget; +import extracells.gui.widget.fluid.IFluidSelectorContainer; +import extracells.gui.widget.fluid.IFluidSelectorGui; +import extracells.gui.widget.fluid.WidgetFluidSelector; +import extracells.network.packet.part.PacketFluidStorage; public class GuiGasStorage extends GuiContainer implements IFluidSelectorGui { - private EntityPlayer player; - private int currentScroll = 0; - private GuiTextField searchbar; - private List fluidWidgets = new ArrayList(); - private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); - public IAEFluidStack currentFluid; - private ContainerGasStorage containerGasStorage; - private final String guiName; - - public GuiGasStorage(EntityPlayer _player, String _guiName) { - super(new ContainerGasStorage(_player)); - this.containerGasStorage = (ContainerGasStorage) this.inventorySlots; - this.containerGasStorage.setGui(this); - this.player = _player; - this.xSize = 176; - this.ySize = 204; - this.guiName = _guiName; - new PacketFluidStorage(this.player).sendPacketToServer(); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, - this.ySize); - this.searchbar.drawTextBox(); - new PacketFluidStorage(this.player).sendPacketToServer(); - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - this.fontRendererObj.drawString(StatCollector.translateToLocal(this.guiName).replace("ME ", ""), 5, 6, 0x000000); - drawWidgets(mouseX, mouseY); - if (this.currentFluid != null) { - long currentFluidAmount = this.currentFluid.getStackSize(); - String amountToText = Long.toString(currentFluidAmount) + "mB"; - if (Extracells.shortenedBuckets()) { - if (currentFluidAmount > 1000000000L) - amountToText = Long - .toString(currentFluidAmount / 1000000000L) - + "Mega"; - else if (currentFluidAmount > 1000000L) - amountToText = Long.toString(currentFluidAmount / 1000000L) - + "Kilo"; - else if (currentFluidAmount > 9999L) { - amountToText = Long.toString(currentFluidAmount / 1000L); - } - } - - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.amount") - + ": " + amountToText, 45, 91, 0x000000); - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " - + this.currentFluid.getFluid().getLocalizedName( - this.currentFluid.getFluidStack()), 45, 101, - 0x000000); - } - } - - public void drawWidgets(int mouseX, int mouseY) { - int listSize = this.fluidWidgets.size(); - if (!this.containerGasStorage.getFluidStackList().isEmpty()) { - outerLoop: for (int y = 0; y < 4; y++) { - for (int x = 0; x < 9; x++) { - int widgetIndex = y * 9 + x + this.currentScroll * 9; - if (0 <= widgetIndex && widgetIndex < listSize) { - AbstractFluidWidget widget = this.fluidWidgets - .get(widgetIndex); - widget.drawWidget(x * 18 + 7, y * 18 + 17); - } else { - break outerLoop; - } - } - } - - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int widgetIndex = y * 9 + x; - if (0 <= widgetIndex && widgetIndex < listSize) { - this.fluidWidgets.get(widgetIndex).drawTooltip( - x * 18 + 7, y * 18 - 1, mouseX, mouseY); - } else { - break; - } - } - } - - int deltaWheel = Mouse.getDWheel(); - if (deltaWheel > 0) { - this.currentScroll++; - } else if (deltaWheel < 0) { - this.currentScroll--; - } - - if (this.currentScroll < 0) - this.currentScroll = 0; - if (listSize / 9 < 4 && this.currentScroll < listSize / 9 + 4) - this.currentScroll = 0; - } - } - - @Override - public IFluidSelectorContainer getContainer() { - return this.containerGasStorage; - } - - @Override - public IAEFluidStack getCurrentFluid() { - return this.containerGasStorage.getSelectedFluidStack(); - } - - @Override - public int guiLeft() { - return this.guiLeft; - } - - @Override - public int guiTop() { - return this.guiTop; - } - - @Override - public void initGui() { - super.initGui(); - Mouse.getDWheel(); - - updateFluids(); - Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); - this.searchbar = new GuiTextField(this.fontRendererObj, - this.guiLeft + 81, this.guiTop + 6, 88, 10) { - - private int xPos = 0; - private int yPos = 0; - private int width = 0; - private int height = 0; - - @Override - public void mouseClicked(int x, int y, int mouseBtn) { - boolean flag = x >= this.xPos && x < this.xPos + this.width - && y >= this.yPos && y < this.yPos + this.height; - if (flag && mouseBtn == 3) - setText(""); - } - }; - this.searchbar.setEnableBackgroundDrawing(false); - this.searchbar.setFocused(true); - this.searchbar.setMaxStringLength(15); - } - - @Override - protected void keyTyped(char key, int keyID) { - if (keyID == Keyboard.KEY_ESCAPE) - this.mc.thePlayer.closeScreen(); - this.searchbar.textboxKeyTyped(key, keyID); - updateFluids(); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); - int listSize = this.fluidWidgets.size(); - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int index = y * 9 + x; - if (0 <= index && index < listSize) { - AbstractFluidWidget widget = this.fluidWidgets.get(index); - widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); - } - } - } - } - - public void updateFluids() { - this.fluidWidgets = new ArrayList(); - for (IAEFluidStack fluidStack : this.containerGasStorage.getFluidStackList()) { - if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase().contains(this.searchbar.getText().toLowerCase()) && ECApi.instance().isGas(fluidStack.getFluid())) { - this.fluidWidgets.add(new WidgetFluidSelector(this, fluidStack)); - } - } - updateSelectedFluid(); - } - - public void updateSelectedFluid() { - this.currentFluid = null; - for (IAEFluidStack stack : this.containerGasStorage.getFluidStackList()) { - if (stack.getFluid() == this.containerGasStorage.getSelectedFluid()) - this.currentFluid = stack; - } - } + private final EntityPlayer player; + private int currentScroll = 0; + private GuiTextField searchbar; + private List fluidWidgets = new ArrayList(); + private final ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); + public IAEFluidStack currentFluid; + private final ContainerGasStorage containerGasStorage; + private final String guiName; + + public GuiGasStorage(EntityPlayer _player, String _guiName) { + super(new ContainerGasStorage(_player)); + this.containerGasStorage = (ContainerGasStorage) this.inventorySlots; + this.containerGasStorage.setGui(this); + this.player = _player; + this.xSize = 176; + this.ySize = 204; + this.guiName = _guiName; + new PacketFluidStorage(this.player).sendPacketToServer(); + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + int deltaWheel = Mouse.getEventDWheel(); + if (deltaWheel < 0) { + currentScroll++; + } else if (deltaWheel > 0) { + currentScroll--; + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + this.searchbar.drawTextBox(); + new PacketFluidStorage(this.player).sendPacketToServer(); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.fontRendererObj + .drawString(StatCollector.translateToLocal(this.guiName).replace("ME ", ""), 5, 6, 0x000000); + drawWidgets(mouseX, mouseY); + if (this.currentFluid != null) { + long currentFluidAmount = this.currentFluid.getStackSize(); + String amountToText = currentFluidAmount + "mB"; + if (Extracells.shortenedBuckets()) { + if (currentFluidAmount > 1000000000L) amountToText = currentFluidAmount / 1000000000L + "Mega"; + else if (currentFluidAmount > 1000000L) amountToText = currentFluidAmount / 1000000L + "Kilo"; + else if (currentFluidAmount > 9999L) { + amountToText = Long.toString(currentFluidAmount / 1000L); + } + } + + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amountToText, + 45, + 91, + 0x000000); + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + this.currentFluid.getFluid().getLocalizedName(this.currentFluid.getFluidStack()), + 45, + 101, + 0x000000); + } + } + + public void drawWidgets(int mouseX, int mouseY) { + int listSize = this.fluidWidgets.size(); + if (!this.containerGasStorage.getFluidStackList().isEmpty()) { + outerLoop: for (int y = 0; y < 4; y++) { + for (int x = 0; x < 9; x++) { + int widgetIndex = y * 9 + x + this.currentScroll * 9; + if (0 <= widgetIndex && widgetIndex < listSize) { + AbstractFluidWidget widget = this.fluidWidgets.get(widgetIndex); + widget.drawWidget(x * 18 + 7, y * 18 + 17); + } else { + break outerLoop; + } + } + } + + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int widgetIndex = y * 9 + x; + if (0 <= widgetIndex && widgetIndex < listSize) { + this.fluidWidgets.get(widgetIndex).drawTooltip(x * 18 + 7, y * 18 - 1, mouseX, mouseY); + } else { + break; + } + } + } + if (this.currentScroll < 0) this.currentScroll = 0; + if (listSize / 9 < 4 && this.currentScroll < listSize / 9 + 4) this.currentScroll = 0; + } + } + + @Override + public IFluidSelectorContainer getContainer() { + return this.containerGasStorage; + } + + @Override + public IAEFluidStack getCurrentFluid() { + return this.containerGasStorage.getSelectedFluidStack(); + } + + @Override + public int guiLeft() { + return this.guiLeft; + } + + @Override + public int guiTop() { + return this.guiTop; + } + + @Override + public void initGui() { + super.initGui(); + + updateFluids(); + Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); + this.searchbar = new GuiTextField(this.fontRendererObj, this.guiLeft + 81, this.guiTop + 6, 88, 10) { + + private final int xPos = 0; + private final int yPos = 0; + private final int width = 0; + private final int height = 0; + + @Override + public void mouseClicked(int x, int y, int mouseBtn) { + boolean flag = x >= this.xPos && x < this.xPos + this.width + && y >= this.yPos + && y < this.yPos + this.height; + if (flag && mouseBtn == 3) setText(""); + } + }; + this.searchbar.setEnableBackgroundDrawing(false); + this.searchbar.setFocused(true); + this.searchbar.setMaxStringLength(15); + } + + @Override + protected void keyTyped(char key, int keyID) { + if (keyID == Keyboard.KEY_ESCAPE) this.mc.thePlayer.closeScreen(); + this.searchbar.textboxKeyTyped(key, keyID); + updateFluids(); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); + int listSize = this.fluidWidgets.size(); + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int index = y * 9 + x; + if (0 <= index && index < listSize) { + AbstractFluidWidget widget = this.fluidWidgets.get(index); + widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); + } + } + } + } + + public void updateFluids() { + this.fluidWidgets = new ArrayList(); + for (IAEFluidStack fluidStack : this.containerGasStorage.getFluidStackList()) { + if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase().contains( + this.searchbar.getText().toLowerCase()) && ECApi.instance().isGas(fluidStack.getFluid())) { + this.fluidWidgets.add(new WidgetFluidSelector(this, fluidStack)); + } + } + updateSelectedFluid(); + } + + public void updateSelectedFluid() { + this.currentFluid = null; + for (IAEFluidStack stack : this.containerGasStorage.getFluidStackList()) { + if (stack.getFluid() == this.containerGasStorage.getSelectedFluid()) this.currentFluid = stack; + } + } } diff --git a/src/main/scala/extracells/gui/GuiGasTerminal.java b/src/main/scala/extracells/gui/GuiGasTerminal.java index f3c1578d9..e51ea46e9 100644 --- a/src/main/scala/extracells/gui/GuiGasTerminal.java +++ b/src/main/scala/extracells/gui/GuiGasTerminal.java @@ -1,5 +1,20 @@ package extracells.gui; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiTextField; +import net.minecraft.client.gui.inventory.GuiContainer; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.util.ResourceLocation; +import net.minecraft.util.StatCollector; + +import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; +import org.lwjgl.opengl.GL11; + import appeng.api.storage.data.IAEFluidStack; import extracells.Extracells; import extracells.api.ECApi; @@ -12,205 +27,200 @@ import extracells.network.packet.part.PacketFluidTerminal; import extracells.part.PartFluidTerminal; import extracells.part.PartGasTerminal; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiTextField; -import net.minecraft.client.gui.inventory.GuiContainer; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.StatCollector; -import org.lwjgl.input.Keyboard; -import org.lwjgl.input.Mouse; -import org.lwjgl.opengl.GL11; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; public class GuiGasTerminal extends GuiContainer implements IFluidSelectorGui { - private PartFluidTerminal terminal; - private EntityPlayer player; - private int currentScroll = 0; - private GuiTextField searchbar; - private List fluidWidgets = new ArrayList(); - private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); - public IAEFluidStack currentFluid; - private ContainerGasTerminal containerTerminalFluid; - - public GuiGasTerminal(PartGasTerminal _terminal, EntityPlayer _player) { - super(new ContainerGasTerminal(_terminal, _player)); - this.containerTerminalFluid = (ContainerGasTerminal) this.inventorySlots; - this.containerTerminalFluid.setGui(this); - this.terminal = _terminal; - this.player = _player; - this.xSize = 176; - this.ySize = 204; - new PacketFluidTerminal(this.player, this.terminal).sendPacketToServer(); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); - this.searchbar.drawTextBox(); - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - this.fontRendererObj.drawString(StatCollector.translateToLocal("extracells.part.gas.terminal.name").replace("ME ", ""), 9, 6, 0x000000); - drawWidgets(mouseX, mouseY); - if (this.currentFluid != null) { - long currentFluidAmount = this.currentFluid.getStackSize(); - String amountToText = Long.toString(currentFluidAmount) + "mB"; - if (Extracells.shortenedBuckets()) { - if (currentFluidAmount > 1000000000L) - amountToText = Long.toString(currentFluidAmount / 1000000000L) + "MegaB"; - else if (currentFluidAmount > 1000000L) - amountToText = Long.toString(currentFluidAmount / 1000000L) + "KiloB"; - else if (currentFluidAmount > 9999L) { - amountToText = Long.toString(currentFluidAmount / 1000L) + "B"; - } - } - - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amountToText, 45, 91, 0x000000); - this.fontRendererObj.drawString( - StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + this.currentFluid.getFluid().getLocalizedName(this.currentFluid.getFluidStack()), 45, 101, 0x000000); - } - } - - public void drawWidgets(int mouseX, int mouseY) { - int listSize = this.fluidWidgets.size(); - if (!this.containerTerminalFluid.getFluidStackList().isEmpty()) { - outerLoop: for (int y = 0; y < 4; y++) { - for (int x = 0; x < 9; x++) { - int widgetIndex = y * 9 + x + this.currentScroll * 9; - if (0 <= widgetIndex && widgetIndex < listSize) { - AbstractFluidWidget widget = this.fluidWidgets.get(widgetIndex); - widget.drawWidget(x * 18 + 7, y * 18 + 17); - } else { - break outerLoop; - } - } - } - - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int widgetIndex = y * 9 + x; - if (0 <= widgetIndex && widgetIndex < listSize) { - if (this.fluidWidgets.get(widgetIndex).drawTooltip(x * 18 + 7, y * 18 - 1, mouseX, mouseY)) - break; - } else { - break; - } - } - } - - int deltaWheel = Mouse.getDWheel(); - if (deltaWheel > 0) { - this.currentScroll++; - } else if (deltaWheel < 0) { - this.currentScroll--; - } - - if (this.currentScroll < 0) - this.currentScroll = 0; - if (listSize / 9 < 4 && this.currentScroll < listSize / 9 + 4) - this.currentScroll = 0; - } - } - - @Override - public IFluidSelectorContainer getContainer() { - return this.containerTerminalFluid; - } - - @Override - public IAEFluidStack getCurrentFluid() { - return this.currentFluid; - } - - public PartFluidTerminal getTerminal() { - return this.terminal; - } - - @Override - public int guiLeft() { - return this.guiLeft; - } - - @Override - public int guiTop() { - return this.guiTop; - } - - @Override - public void initGui() { - super.initGui(); - Mouse.getDWheel(); - - updateFluids(); - Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); - this.searchbar = new GuiTextField(this.fontRendererObj, - this.guiLeft + 81, this.guiTop + 6, 88, 10) { - - private int xPos = 0; - private int yPos = 0; - private int width = 0; - private int height = 0; - - @Override - public void mouseClicked(int x, int y, int mouseBtn) { - boolean flag = x >= this.xPos && x < this.xPos + this.width && y >= this.yPos && y < this.yPos + this.height; - if (flag && mouseBtn == 3) - setText(""); - } - }; - this.searchbar.setEnableBackgroundDrawing(false); - this.searchbar.setFocused(true); - this.searchbar.setMaxStringLength(15); - } - - @Override - protected void keyTyped(char key, int keyID) { - if (keyID == Keyboard.KEY_ESCAPE) - this.mc.thePlayer.closeScreen(); - this.searchbar.textboxKeyTyped(key, keyID); - updateFluids(); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); - int listSize = this.fluidWidgets.size(); - for (int x = 0; x < 9; x++) { - for (int y = 0; y < 4; y++) { - int index = y * 9 + x; - if (0 <= index && index < listSize) { - AbstractFluidWidget widget = this.fluidWidgets.get(index); - widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); - } - } - } - } - - public void updateFluids() { - this.fluidWidgets = new ArrayList(); - for (IAEFluidStack fluidStack : this.containerTerminalFluid.getFluidStackList()) { - if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase().contains(this.searchbar.getText().toLowerCase()) && ECApi.instance().isGasStack(fluidStack)) { - this.fluidWidgets.add(new WidgetFluidSelector(this, fluidStack)); - } - } - updateSelectedFluid(); - } - - public void updateSelectedFluid() { - this.currentFluid = null; - for (IAEFluidStack stack : this.containerTerminalFluid.getFluidStackList()) { - if (stack.getFluid() == this.containerTerminalFluid.getSelectedFluid()) - this.currentFluid = stack; - } - } + private final PartFluidTerminal terminal; + private final EntityPlayer player; + private int currentScroll = 0; + private GuiTextField searchbar; + private List fluidWidgets = new ArrayList(); + private final ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/terminalfluid.png"); + public IAEFluidStack currentFluid; + private final ContainerGasTerminal containerTerminalFluid; + + public GuiGasTerminal(PartGasTerminal _terminal, EntityPlayer _player) { + super(new ContainerGasTerminal(_terminal, _player)); + this.containerTerminalFluid = (ContainerGasTerminal) this.inventorySlots; + this.containerTerminalFluid.setGui(this); + this.terminal = _terminal; + this.player = _player; + this.xSize = 176; + this.ySize = 204; + new PacketFluidTerminal(this.player, this.terminal).sendPacketToServer(); + } + + @Override + protected void drawGuiContainerBackgroundLayer(float alpha, int sizeX, int sizeY) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + this.searchbar.drawTextBox(); + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.part.gas.terminal.name").replace("ME ", ""), + 9, + 6, + 0x000000); + drawWidgets(mouseX, mouseY); + if (this.currentFluid != null) { + long currentFluidAmount = this.currentFluid.getStackSize(); + String amountToText = currentFluidAmount + "mB"; + if (Extracells.shortenedBuckets()) { + if (currentFluidAmount > 1000000000L) amountToText = currentFluidAmount / 1000000000L + "MegaB"; + else if (currentFluidAmount > 1000000L) amountToText = currentFluidAmount / 1000000L + "KiloB"; + else if (currentFluidAmount > 9999L) { + amountToText = currentFluidAmount / 1000L + "B"; + } + } + + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amountToText, + 45, + 91, + 0x000000); + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + this.currentFluid.getFluid().getLocalizedName(this.currentFluid.getFluidStack()), + 45, + 101, + 0x000000); + } + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + int deltaWheel = Mouse.getEventDWheel(); + if (deltaWheel < 0) { + currentScroll++; + } else if (deltaWheel > 0) { + currentScroll--; + } + } + + public void drawWidgets(int mouseX, int mouseY) { + int listSize = this.fluidWidgets.size(); + if (!this.containerTerminalFluid.getFluidStackList().isEmpty()) { + outerLoop: for (int y = 0; y < 4; y++) { + for (int x = 0; x < 9; x++) { + int widgetIndex = y * 9 + x + this.currentScroll * 9; + if (0 <= widgetIndex && widgetIndex < listSize) { + AbstractFluidWidget widget = this.fluidWidgets.get(widgetIndex); + widget.drawWidget(x * 18 + 7, y * 18 + 17); + } else { + break outerLoop; + } + } + } + + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int widgetIndex = y * 9 + x; + if (0 <= widgetIndex && widgetIndex < listSize) { + if (this.fluidWidgets.get(widgetIndex).drawTooltip(x * 18 + 7, y * 18 - 1, mouseX, mouseY)) + break; + } else { + break; + } + } + } + if (this.currentScroll < 0) this.currentScroll = 0; + if (listSize / 9 < 4 && this.currentScroll < listSize / 9 + 4) this.currentScroll = 0; + } + } + + @Override + public IFluidSelectorContainer getContainer() { + return this.containerTerminalFluid; + } + + @Override + public IAEFluidStack getCurrentFluid() { + return this.currentFluid; + } + + public PartFluidTerminal getTerminal() { + return this.terminal; + } + + @Override + public int guiLeft() { + return this.guiLeft; + } + + @Override + public int guiTop() { + return this.guiTop; + } + + @Override + public void initGui() { + super.initGui(); + + updateFluids(); + Collections.sort(this.fluidWidgets, new FluidWidgetComparator()); + this.searchbar = new GuiTextField(this.fontRendererObj, this.guiLeft + 81, this.guiTop + 6, 88, 10) { + + private final int xPos = 0; + private final int yPos = 0; + private final int width = 0; + private final int height = 0; + + @Override + public void mouseClicked(int x, int y, int mouseBtn) { + boolean flag = x >= this.xPos && x < this.xPos + this.width + && y >= this.yPos + && y < this.yPos + this.height; + if (flag && mouseBtn == 3) setText(""); + } + }; + this.searchbar.setEnableBackgroundDrawing(false); + this.searchbar.setFocused(true); + this.searchbar.setMaxStringLength(15); + } + + @Override + protected void keyTyped(char key, int keyID) { + if (keyID == Keyboard.KEY_ESCAPE) this.mc.thePlayer.closeScreen(); + this.searchbar.textboxKeyTyped(key, keyID); + updateFluids(); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); + int listSize = this.fluidWidgets.size(); + for (int x = 0; x < 9; x++) { + for (int y = 0; y < 4; y++) { + int index = y * 9 + x; + if (0 <= index && index < listSize) { + AbstractFluidWidget widget = this.fluidWidgets.get(index); + widget.mouseClicked(x * 18 + 7, y * 18 - 1, mouseX, mouseY); + } + } + } + } + + public void updateFluids() { + this.fluidWidgets = new ArrayList(); + for (IAEFluidStack fluidStack : this.containerTerminalFluid.getFluidStackList()) { + if (fluidStack.getFluid().getLocalizedName(fluidStack.getFluidStack()).toLowerCase() + .contains(this.searchbar.getText().toLowerCase()) && ECApi.instance().isGasStack(fluidStack)) { + this.fluidWidgets.add(new WidgetFluidSelector(this, fluidStack)); + } + } + updateSelectedFluid(); + } + + public void updateSelectedFluid() { + this.currentFluid = null; + for (IAEFluidStack stack : this.containerTerminalFluid.getFluidStackList()) { + if (stack.getFluid() == this.containerTerminalFluid.getSelectedFluid()) this.currentFluid = stack; + } + } } diff --git a/src/main/scala/extracells/gui/GuiHardMEDrive.scala b/src/main/scala/extracells/gui/GuiHardMEDrive.scala index b074986d2..1ffb04bed 100644 --- a/src/main/scala/extracells/gui/GuiHardMEDrive.scala +++ b/src/main/scala/extracells/gui/GuiHardMEDrive.scala @@ -11,16 +11,16 @@ import net.minecraft.util.ResourceLocation import org.lwjgl.opengl.GL11 class GuiHardMEDrive(inventory: InventoryPlayer, tile: TileEntityHardMeDrive) - extends GuiContainer(new ContainerHardMEDrive(inventory, tile)){ - + extends GuiContainer(new ContainerHardMEDrive(inventory, tile)) { xSize = 176 ySize = 166 - private val guiTexture = new ResourceLocation("extracells", "textures/gui/hardmedrive.png") + private val guiTexture = + new ResourceLocation("extracells", "textures/gui/hardmedrive.png") - override def drawGuiContainerBackgroundLayer(f : Float, i : Int, j : Int) = { + override def drawGuiContainerBackgroundLayer(f: Float, i: Int, j: Int) = { drawDefaultBackground(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); val posX = (width - xSize) / 2; val posY = (height - ySize) / 2; @@ -31,16 +31,30 @@ class GuiHardMEDrive(inventory: InventoryPlayer, tile: TileEntityHardMeDrive) } } - override def drawGuiContainerForegroundLayer(i: Int, j: Int) = - fontRendererObj.drawString(BlockEnum.BLASTRESISTANTMEDRIVE.getStatName, 5, 5, 0x000000) + override def drawGuiContainerForegroundLayer(i: Int, j: Int) = + fontRendererObj.drawString( + BlockEnum.BLASTRESISTANTMEDRIVE.getStatName, + 5, + 5, + 0x000000 + ) private def renderBackground(slot: Slot) { if (slot.getStack == null && slot.slotNumber < 3) { GL11.glDisable(GL11.GL_LIGHTING) GL11.glEnable(GL11.GL_BLEND) - GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.5F) - this.mc.getTextureManager.bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")) - this.drawTexturedModalRect(this.guiLeft + slot.xDisplayPosition, this.guiTop + slot.yDisplayPosition, 240, 0, 16, 16) + GL11.glColor4f(1.0f, 1.0f, 1.0f, 0.5f) + this.mc.getTextureManager.bindTexture( + new ResourceLocation("appliedenergistics2", "textures/guis/states.png") + ) + this.drawTexturedModalRect( + this.guiLeft + slot.xDisplayPosition, + this.guiTop + slot.yDisplayPosition, + 240, + 0, + 16, + 16 + ) GL11.glDisable(GL11.GL_BLEND) GL11.glEnable(GL11.GL_LIGHTING) } diff --git a/src/main/scala/extracells/gui/GuiOreDictExport.java b/src/main/scala/extracells/gui/GuiOreDictExport.java index 608996f6d..9e2b2ba98 100644 --- a/src/main/scala/extracells/gui/GuiOreDictExport.java +++ b/src/main/scala/extracells/gui/GuiOreDictExport.java @@ -1,117 +1,207 @@ package extracells.gui; -import cpw.mods.fml.relauncher.Side; -import extracells.container.ContainerOreDictExport; -import extracells.network.packet.part.PacketOreDictExport; -import extracells.part.PartOreDictExporter; +import java.util.Iterator; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; + import org.lwjgl.input.Keyboard; +import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; +import appeng.util.item.AEItemStack; +import cpw.mods.fml.relauncher.Side; +import extracells.container.ContainerOreDictExport; +import extracells.network.packet.part.PacketOreDictExport; +import extracells.part.PartOreDictExporter; + public class GuiOreDictExport extends GuiContainer { - public static void updateFilter(String _filter) { - if (filter != null) { - filter = _filter; - Gui gui = Minecraft.getMinecraft().currentScreen; - if (gui != null && gui instanceof GuiOreDictExport) { - GuiOreDictExport g = (GuiOreDictExport) gui; - if (g.searchbar != null) - g.searchbar.setText(filter); - } - } - } - - private ResourceLocation guiTexture = new ResourceLocation("extracells", - "textures/gui/oredictexport.png"); - private EntityPlayer player; - private static String filter = ""; - - private GuiTextField searchbar; - - public GuiOreDictExport(EntityPlayer player, PartOreDictExporter _part) { - super(new ContainerOreDictExport(player, _part)); - this.player = player; - } - - @Override - protected void actionPerformed(GuiButton guibutton) { - new PacketOreDictExport(this.player, filter, Side.SERVER) - .sendPacketToServer(); - } - - @Override - protected void drawGuiContainerBackgroundLayer(float f, int mouseX, - int mouseY) { - drawDefaultBackground(); - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); - drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, - this.ySize); - this.searchbar.drawTextBox(); - } - - @Override - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - super.drawGuiContainerForegroundLayer(mouseX, mouseY); - this.fontRendererObj.drawString( - StatCollector.translateToLocal( - "extracells.part.oredict.export.name").replace("ME ", - ""), 8, 5, 0x000000); - this.fontRendererObj.drawString( - StatCollector.translateToLocal("container.inventory"), 8, - this.ySize - 94, 0x000000); - - } - - @Override - public void initGui() { - super.initGui(); - this.guiLeft = (this.width - this.xSize) / 2; - this.guiTop = (this.height - this.ySize) / 2; - this.buttonList.add(new GuiButton(1, - this.guiLeft + this.xSize / 2 - 44, this.guiTop + 35, 88, 20, - StatCollector.translateToLocal("extracells.tooltip.save"))); - this.searchbar = new GuiTextField(this.fontRendererObj, this.guiLeft - + this.xSize / 2 - 44, this.guiTop + 20, 88, 10) { - - private int xPos = 0; - private int yPos = 0; - private int width = 0; - private int height = 0; - - @Override - public void mouseClicked(int x, int y, int mouseBtn) { - boolean flag = x >= this.xPos && x < this.xPos + this.width - && y >= this.yPos && y < this.yPos + this.height; - if (flag && mouseBtn == 3) - setText(""); - } - }; - this.searchbar.setEnableBackgroundDrawing(true); - this.searchbar.setFocused(true); - this.searchbar.setMaxStringLength(15); - this.searchbar.setText(filter); - } - - @Override - protected void keyTyped(char key, int keyID) { - if (keyID == Keyboard.KEY_ESCAPE) - this.mc.thePlayer.closeScreen(); - this.searchbar.textboxKeyTyped(key, keyID); - filter = this.searchbar.getText(); - } - - @Override - protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { - super.mouseClicked(mouseX, mouseY, mouseBtn); - this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); - } + public ContainerOreDictExport _containerOreDictExport; + private int currentScroll = 0; + + public static void updateFilter(String _filter) { + if (filter != null) { + filter = _filter; + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui != null && gui instanceof GuiOreDictExport) { + GuiOreDictExport g = (GuiOreDictExport) gui; + if (g.searchbar != null) g.searchbar.setText(filter); + } + } + } + + private final ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/oredictexport.png"); + private final EntityPlayer player; + private static String filter = ""; + + private GuiTextField searchbar; + + public GuiOreDictExport(EntityPlayer player, PartOreDictExporter _part) { + super(new ContainerOreDictExport(player, _part)); + this._containerOreDictExport = new ContainerOreDictExport(player, _part); + this.player = player; + } + + @Override + protected void actionPerformed(GuiButton guibutton) { + new PacketOreDictExport(this.player, filter, Side.SERVER).sendPacketToServer(); + } + + @Override + public void handleMouseInput() { + super.handleMouseInput(); + int deltaWheel = Mouse.getEventDWheel(); + if (deltaWheel < 0) { + currentScroll++; + } else if (deltaWheel > 0) { + currentScroll--; + } + } + + @Override + protected void drawGuiContainerBackgroundLayer(float f, int mouseX, int mouseY) { + drawDefaultBackground(); + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(this.guiTexture); + drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + this.searchbar.drawTextBox(); + } + + public class RenderToolTip { + + private ItemStack item; + private int x; + private int y; + private boolean render = false; + + public RenderToolTip() {} + + public void setValue(ItemStack _item, int _x, int _y) { + this.item = _item; + this.x = _x; + this.y = _y; + this.render = true; + } + + public void renderToolTip() { + if (render) { + GuiOreDictExport.this.renderToolTip(this.item, this.x, this.y); + this.render = false; + } + } + } + + @Override + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + super.drawGuiContainerForegroundLayer(mouseX, mouseY); + this.fontRendererObj.drawString( + StatCollector.translateToLocal("extracells.part.oredict.export.name").replace("ME ", ""), + 8, + 5, + 0x000000); + this.fontRendererObj + .drawString(StatCollector.translateToLocal("container.inventory"), 8, this.ySize - 94, 0x000000); + if (!filter.isEmpty() && !filter.startsWith("*") && !filter.startsWith("^") && !filter.startsWith("$")) { + this._containerOreDictExport.part.setFilter(filter, false); + Iterator items = this._containerOreDictExport.part.getOres().iterator(); + int size = this._containerOreDictExport.part.getOres().size(); + if (this.currentScroll < 0) this.currentScroll = 0; + int maxPage = size / (4 * 10); + if (this.currentScroll > maxPage) { + this.currentScroll = maxPage; + } + for (int i = 0; i < 10 * 4 * currentScroll; i++) { + if (items.hasNext()) { + items.next(); + } else { + break; + } + } + RenderToolTip toolTip = new RenderToolTip(); + outerLoop: for (int y = 0; y < 10; y++) { + for (int x = 0; x < 4; x++) { + if (items.hasNext()) { + AEItemStack item = items.next(); + item.getItem().addInformation(item.getItemStack(), player, item.getToolTip(), true); + int posX = -70 + x * 16; + int posY = y * 16; + itemRender.renderItemAndEffectIntoGUI( + this.fontRendererObj, + Minecraft.getMinecraft().renderEngine, + item.getItemStack(), + posX, + posY); + if (mouseX - this.guiLeft > posX && mouseX - this.guiLeft < posX + 16 + && mouseY - this.guiTop > posY + && mouseY - this.guiTop < posY + 16) { + toolTip.setValue(item.getItemStack(), posX, posY); + } + } else { + break outerLoop; + } + } + } + toolTip.renderToolTip(); + } + } + + @Override + public void initGui() { + super.initGui(); + this.guiLeft = (this.width - this.xSize) / 2; + this.guiTop = (this.height - this.ySize) / 2; + this.buttonList.add( + new GuiButton( + 1, + this.guiLeft + this.xSize / 2 - 44, + this.guiTop + 35, + 88, + 20, + StatCollector.translateToLocal("extracells.tooltip.save"))); + this.searchbar = new GuiTextField( + this.fontRendererObj, + this.guiLeft + this.xSize / 2 - 75, + this.guiTop + 20, + 150, + 10) { + + private final int xPos = 0; + private final int yPos = 0; + private final int width = 0; + private final int height = 0; + + @Override + public void mouseClicked(int x, int y, int mouseBtn) { + boolean flag = x >= this.xPos && x < this.xPos + this.width + && y >= this.yPos + && y < this.yPos + this.height; + if (flag && mouseBtn == 3) setText(""); + } + }; + this.searchbar.setEnableBackgroundDrawing(true); + this.searchbar.setFocused(true); + this.searchbar.setMaxStringLength(128); + this.searchbar.setText(filter); + } + + @Override + protected void keyTyped(char key, int keyID) { + if (keyID == Keyboard.KEY_ESCAPE) this.mc.thePlayer.closeScreen(); + this.searchbar.textboxKeyTyped(key, keyID); + filter = this.searchbar.getText(); + } + + @Override + protected void mouseClicked(int mouseX, int mouseY, int mouseBtn) { + super.mouseClicked(mouseX, mouseY, mouseBtn); + this.searchbar.mouseClicked(mouseX, mouseY, mouseBtn); + } } diff --git a/src/main/scala/extracells/gui/GuiTypes.java b/src/main/scala/extracells/gui/GuiTypes.java index b48300742..b1ce40018 100644 --- a/src/main/scala/extracells/gui/GuiTypes.java +++ b/src/main/scala/extracells/gui/GuiTypes.java @@ -1,5 +1,9 @@ package extracells.gui; public enum GuiTypes { - PART, BLOCK, TILEENTITY, ITEM, STORAGE + PART, + BLOCK, + TILEENTITY, + ITEM, + STORAGE } diff --git a/src/main/scala/extracells/gui/GuiVibrationChamberFluid.java b/src/main/scala/extracells/gui/GuiVibrationChamberFluid.java index 286174165..3c148244e 100644 --- a/src/main/scala/extracells/gui/GuiVibrationChamberFluid.java +++ b/src/main/scala/extracells/gui/GuiVibrationChamberFluid.java @@ -1,19 +1,19 @@ package extracells.gui; -import extracells.container.ContainerVibrationChamberFluid; -import extracells.gui.widget.WidgetFluidTank; -import extracells.tileentity.TileEntityVibrationChamberFluid; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ResourceLocation; + import org.lwjgl.opengl.GL11; -public class GuiVibrationChamberFluid extends GuiContainer { +import extracells.container.ContainerVibrationChamberFluid; +import extracells.gui.widget.WidgetFluidTank; +import extracells.tileentity.TileEntityVibrationChamberFluid; +public class GuiVibrationChamberFluid extends GuiContainer { - private ResourceLocation guiTexture = new ResourceLocation("extracells", - "textures/gui/vibrationchamberfluid.png"); + private ResourceLocation guiTexture = new ResourceLocation("extracells", "textures/gui/vibrationchamberfluid.png"); private EntityPlayer player; public WidgetFluidTank widgetFluidTank; private TileEntityVibrationChamberFluid tileEntity; @@ -27,12 +27,10 @@ public GuiVibrationChamberFluid(EntityPlayer player, TileEntityVibrationChamberF @Override protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { super.drawGuiContainerForegroundLayer(mouseX, mouseY); - if(widgetFluidTank != null) - widgetFluidTank.draw(widgetFluidTank.posX, widgetFluidTank.posY, mouseX, mouseY); + if (widgetFluidTank != null) widgetFluidTank.draw(widgetFluidTank.posX, widgetFluidTank.posY, mouseX, mouseY); if (widgetFluidTank != null) if (func_146978_c(widgetFluidTank.posX, widgetFluidTank.posY, 18, 73, mouseX, mouseY)) { - widgetFluidTank.drawTooltip(mouseX - this.guiLeft, mouseY - - this.guiTop); + widgetFluidTank.drawTooltip(mouseX - this.guiLeft, mouseY - this.guiTop); } } @@ -45,12 +43,10 @@ protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { int posX = (this.width - xSize) / 2; int posY = (this.height - ySize) / 2; drawTexturedModalRect(posX, posY, 0, 0, xSize, ySize); - //int burnTime = tileEntity.getBurntTimeScaled(52); - //drawTexturedModalRect(posX + 105, posY + 17 + 54 - burnTime, 176, 0 + 54 - burnTime, 3, burnTime); + // int burnTime = tileEntity.getBurntTimeScaled(52); + // drawTexturedModalRect(posX + 105, posY + 17 + 54 - burnTime, 176, 0 + 54 - burnTime, 3, burnTime); } - - @Override public void initGui() { super.initGui(); diff --git a/src/main/scala/extracells/gui/widget/DigitTextField.java b/src/main/scala/extracells/gui/widget/DigitTextField.java index 745a9c315..20220b26d 100644 --- a/src/main/scala/extracells/gui/widget/DigitTextField.java +++ b/src/main/scala/extracells/gui/widget/DigitTextField.java @@ -3,118 +3,116 @@ import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiTextField; + import org.lwjgl.input.Keyboard; public class DigitTextField extends GuiTextField { - public DigitTextField(FontRenderer fontRenderer, int x, int y, int length, - int height) { - super(fontRenderer, x, y, length, height); - } + public DigitTextField(FontRenderer fontRenderer, int x, int y, int length, int height) { + super(fontRenderer, x, y, length, height); + } - private Boolean isWhiteListed(char key) { - return "0123456789".contains(String.valueOf(key)); - } + private Boolean isWhiteListed(char key) { + return "0123456789".contains(String.valueOf(key)); + } - @Override - public boolean textboxKeyTyped(char keyChar, int keyID) { - if (isFocused()) { - switch (keyChar) { - case 1: - this.setCursorPositionEnd(); - this.setSelectionPos(0); - return true; - case 3: - GuiScreen.setClipboardString(getSelectedText()); - return true; - case 22: - this.writeText(GuiScreen.getClipboardString()); - return true; - case 24: - GuiScreen.setClipboardString(getSelectedText()); - this.writeText(""); - return true; - default: - switch (keyID) { - case Keyboard.KEY_ESCAPE: - this.setFocused(false); - return true; - case 14: - if (GuiScreen.isCtrlKeyDown()) { - this.deleteWords(-1); - } else { - this.deleteFromCursor(-1); - } + @Override + public boolean textboxKeyTyped(char keyChar, int keyID) { + if (isFocused()) { + switch (keyChar) { + case 1: + this.setCursorPositionEnd(); + this.setSelectionPos(0); + return true; + case 3: + GuiScreen.setClipboardString(getSelectedText()); + return true; + case 22: + this.writeText(GuiScreen.getClipboardString()); + return true; + case 24: + GuiScreen.setClipboardString(getSelectedText()); + this.writeText(""); + return true; + default: + switch (keyID) { + case Keyboard.KEY_ESCAPE: + this.setFocused(false); + return true; + case 14: + if (GuiScreen.isCtrlKeyDown()) { + this.deleteWords(-1); + } else { + this.deleteFromCursor(-1); + } - return true; - case 199: - if (GuiScreen.isShiftKeyDown()) { - this.setSelectionPos(0); - } else { - this.setCursorPositionZero(); - } + return true; + case 199: + if (GuiScreen.isShiftKeyDown()) { + this.setSelectionPos(0); + } else { + this.setCursorPositionZero(); + } - return true; - case 203: - if (GuiScreen.isShiftKeyDown()) { - if (GuiScreen.isCtrlKeyDown()) { - this.setSelectionPos(this.getNthWordFromPos(-1, - this.getSelectionEnd())); - } else { - this.setSelectionPos(this.getSelectionEnd() - 1); - } - } else if (GuiScreen.isCtrlKeyDown()) { - this.setCursorPosition(this.getNthWordFromCursor(-1)); - } else { - this.moveCursorBy(-1); - } + return true; + case 203: + if (GuiScreen.isShiftKeyDown()) { + if (GuiScreen.isCtrlKeyDown()) { + this.setSelectionPos(this.getNthWordFromPos(-1, this.getSelectionEnd())); + } else { + this.setSelectionPos(this.getSelectionEnd() - 1); + } + } else if (GuiScreen.isCtrlKeyDown()) { + this.setCursorPosition(this.getNthWordFromCursor(-1)); + } else { + this.moveCursorBy(-1); + } - return true; - case 205: - if (GuiScreen.isShiftKeyDown()) { - if (GuiScreen.isCtrlKeyDown()) { - this.setSelectionPos(this.getNthWordFromPos(1, - this.getSelectionEnd())); - } else { - this.setSelectionPos(this.getSelectionEnd() + 1); - } - } else if (GuiScreen.isCtrlKeyDown()) { - this.setCursorPosition(this.getNthWordFromCursor(1)); - } else { - this.moveCursorBy(1); - } + return true; + case 205: + if (GuiScreen.isShiftKeyDown()) { + if (GuiScreen.isCtrlKeyDown()) { + this.setSelectionPos(this.getNthWordFromPos(1, this.getSelectionEnd())); + } else { + this.setSelectionPos(this.getSelectionEnd() + 1); + } + } else if (GuiScreen.isCtrlKeyDown()) { + this.setCursorPosition(this.getNthWordFromCursor(1)); + } else { + this.moveCursorBy(1); + } - return true; - case 207: - if (GuiScreen.isShiftKeyDown()) { - this.setSelectionPos(getText().length()); - } else { - this.setCursorPositionEnd(); - } + return true; + case 207: + if (GuiScreen.isShiftKeyDown()) { + this.setSelectionPos(getText().length()); + } else { + this.setCursorPositionEnd(); + } - return true; - case 211: - if (GuiScreen.isCtrlKeyDown()) { - this.deleteWords(1); - } else { - this.deleteFromCursor(1); - } + return true; + case 211: + if (GuiScreen.isCtrlKeyDown()) { + this.deleteWords(1); + } else { + this.deleteFromCursor(1); + } - return true; - default: - if (isWhiteListed(keyChar)) { - this.writeText(Character.toString(keyChar)); - return true; - } else if (keyChar == '-' && getText().isEmpty()) { - writeText(Character.toString(keyChar)); - return true; - } else { - return false; - } - } - } - } else { - return false; - } - } + return true; + default: + if (isWhiteListed(keyChar)) { + this.writeText(Character.toString(keyChar)); + return true; + } else if (keyChar == '-' && getText().isEmpty()) { + writeText(Character.toString(keyChar)); + return true; + } else { + return false; + } + } + } + } else { + return false; + } + } } diff --git a/src/main/scala/extracells/gui/widget/FluidWidgetComparator.java b/src/main/scala/extracells/gui/widget/FluidWidgetComparator.java index 93f562b35..a7866b6e7 100644 --- a/src/main/scala/extracells/gui/widget/FluidWidgetComparator.java +++ b/src/main/scala/extracells/gui/widget/FluidWidgetComparator.java @@ -1,15 +1,16 @@ package extracells.gui.widget; -import extracells.gui.widget.fluid.AbstractFluidWidget; +import java.util.Comparator; + import net.minecraftforge.fluids.FluidStack; -import java.util.Comparator; +import extracells.gui.widget.fluid.AbstractFluidWidget; public class FluidWidgetComparator implements Comparator { - @Override - public int compare(AbstractFluidWidget o1, AbstractFluidWidget o2) { - return o1.getFluid().getLocalizedName(new FluidStack(o1.getFluid(), 0)) - .compareTo(o2.getFluid().getLocalizedName(new FluidStack(o1.getFluid(), 0))); - } + @Override + public int compare(AbstractFluidWidget o1, AbstractFluidWidget o2) { + return o1.getFluid().getLocalizedName(new FluidStack(o1.getFluid(), 0)) + .compareTo(o2.getFluid().getLocalizedName(new FluidStack(o1.getFluid(), 0))); + } } diff --git a/src/main/scala/extracells/gui/widget/WidgetFluidTank.java b/src/main/scala/extracells/gui/widget/WidgetFluidTank.java index 93dcf653b..d6c42c4e1 100644 --- a/src/main/scala/extracells/gui/widget/WidgetFluidTank.java +++ b/src/main/scala/extracells/gui/widget/WidgetFluidTank.java @@ -1,5 +1,9 @@ package extracells.gui.widget; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; @@ -11,185 +15,170 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidTank; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - public class WidgetFluidTank extends Gui { - IFluidTank tank; - public int posX, posY; - ForgeDirection direction; - - public WidgetFluidTank(IFluidTank tank, int posX, int posY) { - this(tank, posX, posY, ForgeDirection.UNKNOWN); - } - - public WidgetFluidTank(IFluidTank tank, int posX, int posY, - ForgeDirection direction) { - this.tank = tank; - this.posX = posX; - this.posY = posY; - this.direction = direction; - } - - public void draw(int guiX, int guiY, int mouseX, int mouseY) { - if (this.tank == null || 73 < 31) - return; - - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glColor3f(1.0F, 1.0F, 1.0F); - - Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation( - "extracells", "textures/gui/fluidtank.png")); - drawTexturedModalRect(this.posX, this.posY, 0, 0, 18, 73); - - int iconHeightRemainder = (73 - 4) % 16; - - FluidStack fluid = this.tank.getFluid(); - if (fluid != null && fluid.amount > 0) { - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - - IIcon fluidIcon = fluid.getFluid().getStillIcon(); - - if (iconHeightRemainder > 0) { - drawTexturedModelRectFromIcon(this.posX + 1, this.posY + 2, - fluidIcon, 16, iconHeightRemainder); - } - for (int i = 0; i < (73 - 6) / 16; i++) { - drawTexturedModelRectFromIcon(this.posX + 1, this.posY + 2 + i - * 16 + iconHeightRemainder, fluidIcon, 16, 16); - } - - Minecraft.getMinecraft().renderEngine - .bindTexture(new ResourceLocation("extracells", - "textures/gui/fluidtank.png")); - drawTexturedModalRect(this.posX + 2, this.posY + 1, 1, 1, 15, - 72 - (int) (73 * ((float) fluid.amount / this.tank - .getCapacity()))); - } - - Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation( - "extracells", "textures/gui/fluidtank.png")); - drawTexturedModalRect(this.posX + 1, this.posY + 1, 19, 1, 16, 73); - - GL11.glEnable(GL11.GL_LIGHTING); - } - - @SuppressWarnings("rawtypes") - protected void drawHoveringText(List list, int x, int y, - FontRenderer fontrenderer) { - if (!list.isEmpty()) { - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - int k = 0; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - int l = fontrenderer.getStringWidth(s); - - if (l > k) { - k = l; - } - } - - int i1 = x + 12; - int j1 = y - 12; - int k1 = 8; - - if (list.size() > 1) { - k1 += 2 + (list.size() - 1) * 10; - } - - this.zLevel = 300.0F; - int l1 = -267386864; - this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); - this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, - l1, l1); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, - l1); - this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, - l1, l1); - int i2 = 1347420415; - int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; - this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - - 1, i2, j2); - this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 - + 3 - 1, i2, j2); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, - i2); - this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, - j2, j2); - - for (int k2 = 0; k2 < list.size(); ++k2) { - String s1 = (String) list.get(k2); - fontrenderer.drawStringWithShadow(s1, i1, j1, -1); - - if (k2 == 0) { - j1 += 2; - } - - j1 += 10; - } - - this.zLevel = 0.0F; - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - } - } - - public void drawDirectionTooltip(int x, int y) { - - List description = new ArrayList(); - description.add(StatCollector - .translateToLocal("extracells.tooltip.direction." - + this.direction.ordinal())); - - if (this.tank == null || this.tank.getFluid() == null) { - description.add(StatCollector - .translateToLocal("extracells.tooltip.empty1")); - } else { - if (this.tank.getFluid().amount > 0 - && this.tank.getFluid().getFluid() != null) { - String amountToText = this.tank.getFluid().amount + "mB"; - - description.add(this.tank.getFluid().getFluid() - .getLocalizedName(this.tank.getFluid())); - description.add(amountToText); - } - } - drawHoveringText(description, x, y, - Minecraft.getMinecraft().fontRenderer); - } - - public void drawTooltip(int x, int y) { - - List description = new ArrayList(); - - if (this.tank == null || this.tank.getFluid() == null) { - description.add(StatCollector - .translateToLocal("extracells.tooltip.empty1")); - } else { - if (this.tank.getFluid().amount > 0 - && this.tank.getFluid().getFluid() != null) { - String amountToText = this.tank.getFluid().amount + "mB"; - - description.add(this.tank.getFluid().getFluid() - .getLocalizedName(this.tank.getFluid())); - description.add(amountToText); - } - } - drawHoveringText(description, x, y, - Minecraft.getMinecraft().fontRenderer); - } + IFluidTank tank; + public int posX, posY; + ForgeDirection direction; + + public WidgetFluidTank(IFluidTank tank, int posX, int posY) { + this(tank, posX, posY, ForgeDirection.UNKNOWN); + } + + public WidgetFluidTank(IFluidTank tank, int posX, int posY, ForgeDirection direction) { + this.tank = tank; + this.posX = posX; + this.posY = posY; + this.direction = direction; + } + + public void draw(int guiX, int guiY, int mouseX, int mouseY) { + if (this.tank == null || 73 < 31) return; + + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glColor3f(1.0F, 1.0F, 1.0F); + + Minecraft.getMinecraft().renderEngine + .bindTexture(new ResourceLocation("extracells", "textures/gui/fluidtank.png")); + drawTexturedModalRect(this.posX, this.posY, 0, 0, 18, 73); + + int iconHeightRemainder = (73 - 4) % 16; + + FluidStack fluid = this.tank.getFluid(); + if (fluid != null && fluid.amount > 0) { + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + + IIcon fluidIcon = fluid.getFluid().getStillIcon(); + GL11.glColor3f( + (fluid.getFluid().getColor() >> 16 & 0xFF) / 255.0F, + (fluid.getFluid().getColor() >> 8 & 0xFF) / 255.0F, + (fluid.getFluid().getColor() & 0xFF) / 255.0F); + if (iconHeightRemainder > 0) { + drawTexturedModelRectFromIcon(this.posX + 1, this.posY + 2, fluidIcon, 16, iconHeightRemainder); + } + for (int i = 0; i < (73 - 6) / 16; i++) { + drawTexturedModelRectFromIcon( + this.posX + 1, + this.posY + 2 + i * 16 + iconHeightRemainder, + fluidIcon, + 16, + 16); + } + GL11.glColor3f(1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine + .bindTexture(new ResourceLocation("extracells", "textures/gui/fluidtank.png")); + drawTexturedModalRect( + this.posX + 2, + this.posY + 1, + 1, + 1, + 15, + 72 - (int) (73 * ((float) fluid.amount / this.tank.getCapacity()))); + } + + Minecraft.getMinecraft().renderEngine + .bindTexture(new ResourceLocation("extracells", "textures/gui/fluidtank.png")); + drawTexturedModalRect(this.posX + 1, this.posY + 1, 19, 1, 16, 73); + + GL11.glEnable(GL11.GL_LIGHTING); + } + + @SuppressWarnings("rawtypes") + protected void drawHoveringText(List list, int x, int y, FontRenderer fontrenderer) { + if (!list.isEmpty()) { + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + int k = 0; + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int l = fontrenderer.getStringWidth(s); + + if (l > k) { + k = l; + } + } + + int i1 = x + 12; + int j1 = y - 12; + int k1 = 8; + + if (list.size() > 1) { + k1 += 2 + (list.size() - 1) * 10; + } + + this.zLevel = 300.0F; + int l1 = -267386864; + this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); + this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); + int i2 = 1347420415; + int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; + this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2); + this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2); + + for (int k2 = 0; k2 < list.size(); ++k2) { + String s1 = (String) list.get(k2); + fontrenderer.drawStringWithShadow(s1, i1, j1, -1); + + if (k2 == 0) { + j1 += 2; + } + + j1 += 10; + } + + this.zLevel = 0.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + } + + public void drawDirectionTooltip(int x, int y) { + + List description = new ArrayList(); + description.add(StatCollector.translateToLocal("extracells.tooltip.direction." + this.direction.ordinal())); + + if (this.tank == null || this.tank.getFluid() == null) { + description.add(StatCollector.translateToLocal("extracells.tooltip.empty1")); + } else { + if (this.tank.getFluid().amount > 0 && this.tank.getFluid().getFluid() != null) { + String amountToText = this.tank.getFluid().amount + "mB"; + + description.add(this.tank.getFluid().getFluid().getLocalizedName(this.tank.getFluid())); + description.add(amountToText); + } + } + drawHoveringText(description, x, y, Minecraft.getMinecraft().fontRenderer); + } + + public void drawTooltip(int x, int y) { + + List description = new ArrayList(); + + if (this.tank == null || this.tank.getFluid() == null) { + description.add(StatCollector.translateToLocal("extracells.tooltip.empty1")); + } else { + if (this.tank.getFluid().amount > 0 && this.tank.getFluid().getFluid() != null) { + String amountToText = this.tank.getFluid().amount + "mB"; + + description.add(this.tank.getFluid().getFluid().getLocalizedName(this.tank.getFluid())); + description.add(amountToText); + } + } + drawHoveringText(description, x, y, Minecraft.getMinecraft().fontRenderer); + } } diff --git a/src/main/scala/extracells/gui/widget/WidgetRedstoneModes.java b/src/main/scala/extracells/gui/widget/WidgetRedstoneModes.java index 7faccdd7e..100d42e63 100644 --- a/src/main/scala/extracells/gui/widget/WidgetRedstoneModes.java +++ b/src/main/scala/extracells/gui/widget/WidgetRedstoneModes.java @@ -1,7 +1,9 @@ package extracells.gui.widget; -import appeng.api.config.RedstoneMode; -import com.google.common.base.Splitter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; @@ -9,172 +11,157 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import com.google.common.base.Splitter; + +import appeng.api.config.RedstoneMode; public class WidgetRedstoneModes extends GuiButton { - private RedstoneMode redstoneMode; - private boolean emitter = false; - - public WidgetRedstoneModes(int ID, int xPos, int yPos, int width, - int height, RedstoneMode mode) { - super(ID, xPos, yPos, width, height, "ScrewStrings :D"); - this.emitter = false; - this.redstoneMode = mode; - } - - public WidgetRedstoneModes(int ID, int xPos, int yPos, int width, - int height, RedstoneMode mode, boolean emitter) { - super(ID, xPos, yPos, width, height, "ScrewStrings :D"); - this.emitter = emitter; - this.redstoneMode = mode; - } - - @Override - public void drawButton(Minecraft minecraftInstance, int x, int y) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - mouseDragged(minecraftInstance, x, y); - - minecraftInstance.getTextureManager().bindTexture( - new ResourceLocation("extracells", - "textures/gui/redstonemodes.png")); - drawTexturedModalRect(this.xPosition, this.yPosition, 0, 16, 16, 16); - - switch (this.redstoneMode) { - case HIGH_SIGNAL: - drawTexturedModalRect(this.xPosition, this.yPosition, 16, 0, 16, 16); - break; - case LOW_SIGNAL: - drawTexturedModalRect(this.xPosition, this.yPosition, 0, 0, 16, 16); - break; - case SIGNAL_PULSE: - drawTexturedModalRect(this.xPosition, this.yPosition, 32, 0, 16, 16); - break; - case IGNORE: - drawTexturedModalRect(this.xPosition, this.yPosition, 48, 0, 16, 16); - break; - default: - break; - } - } - - @SuppressWarnings("rawtypes") - protected void drawHoveringText(List list, int x, int y, - FontRenderer fontrenderer) { - if (!list.isEmpty()) { - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - int k = 0; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - int l = fontrenderer.getStringWidth(s); - - if (l > k) { - k = l; - } - } - - int i1 = x + 12; - int j1 = y - 12; - int k1 = 8; - - if (list.size() > 1) { - k1 += 2 + (list.size() - 1) * 10; - } - - this.zLevel = 300.0F; - int l1 = -267386864; - this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); - this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, - l1, l1); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, - l1); - this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, - l1, l1); - int i2 = 1347420415; - int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; - this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - - 1, i2, j2); - this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 - + 3 - 1, i2, j2); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, - i2); - this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, - j2, j2); - - for (int k2 = 0; k2 < list.size(); ++k2) { - String s1 = (String) list.get(k2); - fontrenderer.drawStringWithShadow(s1, i1, j1, -1); - - if (k2 == 0) { - j1 += 2; - } - - j1 += 10; - } - - this.zLevel = 0.0F; - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - } - } - - public void drawTooltip(int mouseX, int mouseY, int guiXPos, int guiYPos) { - List description = new ArrayList(); - description - .add(StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.RedstoneMode")); - String explanation = ""; - switch (this.redstoneMode) { - case HIGH_SIGNAL: - explanation = StatCollector - .translateToLocal(this.emitter ? "gui.tooltips.appliedenergistics2.EmitLevelAbove" - : "gui.tooltips.appliedenergistics2.ActiveWithSignal"); - break; - case LOW_SIGNAL: - explanation = StatCollector - .translateToLocal(this.emitter ? "gui.tooltips.appliedenergistics2.EmitLevelsBelow" - : "gui.tooltips.appliedenergistics2.ActiveWithoutSignal"); - break; - case SIGNAL_PULSE: - explanation = StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.ActiveOnPulse"); - break; - case IGNORE: - explanation = StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.AlwaysActive"); - break; - default: - break; - } - - for (String current : Splitter.fixedLength(30).split(explanation)) { - description.add(EnumChatFormatting.GRAY + current); - } - - Minecraft mc = Minecraft.getMinecraft(); - - if (mouseX >= this.xPosition && mouseX <= this.xPosition + this.width - && mouseY >= this.yPosition - && mouseY <= this.yPosition + this.height) { - drawHoveringText(description, mouseX - guiXPos, mouseY - guiYPos, - mc.fontRenderer); - } - } - - public void setRedstoneMode(RedstoneMode mode) { - this.redstoneMode = mode; - } + private RedstoneMode redstoneMode; + private boolean emitter = false; + + public WidgetRedstoneModes(int ID, int xPos, int yPos, int width, int height, RedstoneMode mode) { + super(ID, xPos, yPos, width, height, "ScrewStrings :D"); + this.emitter = false; + this.redstoneMode = mode; + } + + public WidgetRedstoneModes(int ID, int xPos, int yPos, int width, int height, RedstoneMode mode, boolean emitter) { + super(ID, xPos, yPos, width, height, "ScrewStrings :D"); + this.emitter = emitter; + this.redstoneMode = mode; + } + + @Override + public void drawButton(Minecraft minecraftInstance, int x, int y) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mouseDragged(minecraftInstance, x, y); + + minecraftInstance.getTextureManager() + .bindTexture(new ResourceLocation("extracells", "textures/gui/redstonemodes.png")); + drawTexturedModalRect(this.xPosition, this.yPosition, 0, 16, 16, 16); + + switch (this.redstoneMode) { + case HIGH_SIGNAL: + drawTexturedModalRect(this.xPosition, this.yPosition, 16, 0, 16, 16); + break; + case LOW_SIGNAL: + drawTexturedModalRect(this.xPosition, this.yPosition, 0, 0, 16, 16); + break; + case SIGNAL_PULSE: + drawTexturedModalRect(this.xPosition, this.yPosition, 32, 0, 16, 16); + break; + case IGNORE: + drawTexturedModalRect(this.xPosition, this.yPosition, 48, 0, 16, 16); + break; + default: + break; + } + } + + @SuppressWarnings("rawtypes") + protected void drawHoveringText(List list, int x, int y, FontRenderer fontrenderer) { + if (!list.isEmpty()) { + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + int k = 0; + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int l = fontrenderer.getStringWidth(s); + + if (l > k) { + k = l; + } + } + + int i1 = x + 12; + int j1 = y - 12; + int k1 = 8; + + if (list.size() > 1) { + k1 += 2 + (list.size() - 1) * 10; + } + + this.zLevel = 300.0F; + int l1 = -267386864; + this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); + this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); + int i2 = 1347420415; + int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; + this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2); + this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2); + + for (int k2 = 0; k2 < list.size(); ++k2) { + String s1 = (String) list.get(k2); + fontrenderer.drawStringWithShadow(s1, i1, j1, -1); + + if (k2 == 0) { + j1 += 2; + } + + j1 += 10; + } + + this.zLevel = 0.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + } + + public void drawTooltip(int mouseX, int mouseY, int guiXPos, int guiYPos) { + List description = new ArrayList(); + description.add(StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.RedstoneMode")); + String explanation = ""; + switch (this.redstoneMode) { + case HIGH_SIGNAL: + explanation = StatCollector.translateToLocal( + this.emitter ? "gui.tooltips.appliedenergistics2.EmitLevelAbove" + : "gui.tooltips.appliedenergistics2.ActiveWithSignal"); + break; + case LOW_SIGNAL: + explanation = StatCollector.translateToLocal( + this.emitter ? "gui.tooltips.appliedenergistics2.EmitLevelsBelow" + : "gui.tooltips.appliedenergistics2.ActiveWithoutSignal"); + break; + case SIGNAL_PULSE: + explanation = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.ActiveOnPulse"); + break; + case IGNORE: + explanation = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.AlwaysActive"); + break; + default: + break; + } + + for (String current : Splitter.fixedLength(30).split(explanation)) { + description.add(EnumChatFormatting.GRAY + current); + } + + Minecraft mc = Minecraft.getMinecraft(); + + if (mouseX >= this.xPosition && mouseX <= this.xPosition + this.width + && mouseY >= this.yPosition + && mouseY <= this.yPosition + this.height) { + drawHoveringText(description, mouseX - guiXPos, mouseY - guiYPos, mc.fontRenderer); + } + } + + public void setRedstoneMode(RedstoneMode mode) { + this.redstoneMode = mode; + } } diff --git a/src/main/scala/extracells/gui/widget/WidgetSlotFluidContainer.java b/src/main/scala/extracells/gui/widget/WidgetSlotFluidContainer.java index d8741489c..2e57abc4b 100644 --- a/src/main/scala/extracells/gui/widget/WidgetSlotFluidContainer.java +++ b/src/main/scala/extracells/gui/widget/WidgetSlotFluidContainer.java @@ -1,9 +1,5 @@ package extracells.gui.widget; -import extracells.gui.widget.fluid.WidgetFluidSlot.IConfigurable; -import extracells.network.packet.other.PacketFluidContainerSlot; -import extracells.tileentity.TileEntityFluidFiller; -import extracells.util.FluidUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; @@ -11,92 +7,97 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; + import org.lwjgl.opengl.GL11; -public class WidgetSlotFluidContainer extends Gui { +import extracells.gui.widget.fluid.WidgetFluidSlot.IConfigurable; +import extracells.network.packet.other.PacketFluidContainerSlot; +import extracells.tileentity.TileEntityFluidFiller; +import extracells.util.FluidUtil; - private int posX, posY; - private static final ResourceLocation guiTexture = new ResourceLocation( - "extracells", "textures/gui/busiofluid.png"); - private TileEntityFluidFiller fluidFiller; - private EntityPlayer player; - private IConfigurable configurable; - private byte configOption; +public class WidgetSlotFluidContainer extends Gui { - public WidgetSlotFluidContainer(EntityPlayer _player, - TileEntityFluidFiller _fluidFiller, int _posX, int _posY) { - this.player = _player; - this.fluidFiller = _fluidFiller; - this.posX = _posX; - this.posY = _posY; - } + private int posX, posY; + private static final ResourceLocation guiTexture = new ResourceLocation( + "extracells", + "textures/gui/busiofluid.png"); + private TileEntityFluidFiller fluidFiller; + private EntityPlayer player; + private IConfigurable configurable; + private byte configOption; - public boolean canRender() { - return this.configurable == null - || this.configurable.getConfigState() >= this.configOption; - } + public WidgetSlotFluidContainer(EntityPlayer _player, TileEntityFluidFiller _fluidFiller, int _posX, int _posY) { + this.player = _player; + this.fluidFiller = _fluidFiller; + this.posX = _posX; + this.posY = _posY; + } - public void drawTooltip() { - if (canRender()) { + public boolean canRender() { + return this.configurable == null || this.configurable.getConfigState() >= this.configOption; + } - } - } + public void drawTooltip() { + if (canRender()) {} + } - public void drawWidget() { - ItemStack container = this.fluidFiller.containerItem; - GL11.glTranslatef(0.0F, 0.0F, 32.0F); - this.zLevel = 100.0F; - RenderItem itemRender = RenderItem.getInstance(); - itemRender.zLevel = 100.0F; - FontRenderer font = null; - if (container != null) - font = container.getItem().getFontRenderer(container); - if (font == null) - font = Minecraft.getMinecraft().fontRenderer; - GL11.glEnable(GL11.GL_DEPTH_TEST); - itemRender.renderItemAndEffectIntoGUI(font, Minecraft.getMinecraft() - .getTextureManager(), container, this.posX, this.posY); - // itemRender.renderItemOverlayIntoGUI(font, - // Minecraft.getMinecraft().getTextureManager(), container, posX + 1, - // posY - 7, null); - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - } + public void drawWidget() { + ItemStack container = this.fluidFiller.containerItem; + GL11.glTranslatef(0.0F, 0.0F, 32.0F); + this.zLevel = 100.0F; + RenderItem itemRender = RenderItem.getInstance(); + itemRender.zLevel = 100.0F; + FontRenderer font = null; + if (container != null) font = container.getItem().getFontRenderer(container); + if (font == null) font = Minecraft.getMinecraft().fontRenderer; + GL11.glEnable(GL11.GL_DEPTH_TEST); + itemRender.renderItemAndEffectIntoGUI( + font, + Minecraft.getMinecraft().getTextureManager(), + container, + this.posX, + this.posY); + // itemRender.renderItemOverlayIntoGUI(font, + // Minecraft.getMinecraft().getTextureManager(), container, posX + 1, + // posY - 7, null); + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } - public void drawWidgetWithRect(int i, int j) { - ItemStack container = this.fluidFiller.containerItem; - GL11.glTranslatef(0.0F, 0.0F, 32.0F); - this.zLevel = 100.0F; - RenderItem itemRender = RenderItem.getInstance(); - itemRender.zLevel = 100.0F; - FontRenderer font = null; - if (container != null) - font = container.getItem().getFontRenderer(container); - if (font == null) - font = Minecraft.getMinecraft().fontRenderer; - drawRect(i, j, i + 16, j + 16, -2130706433); - GL11.glEnable(GL11.GL_DEPTH_TEST); - itemRender.renderItemAndEffectIntoGUI(font, Minecraft.getMinecraft() - .getTextureManager(), container, this.posX, this.posY); - // itemRender.renderItemOverlayIntoGUI(font, - // Minecraft.getMinecraft().getTextureManager(), container, posX + 1, - // posY - 7, null); - this.zLevel = 0.0F; - itemRender.zLevel = 0.0F; - } + public void drawWidgetWithRect(int i, int j) { + ItemStack container = this.fluidFiller.containerItem; + GL11.glTranslatef(0.0F, 0.0F, 32.0F); + this.zLevel = 100.0F; + RenderItem itemRender = RenderItem.getInstance(); + itemRender.zLevel = 100.0F; + FontRenderer font = null; + if (container != null) font = container.getItem().getFontRenderer(container); + if (font == null) font = Minecraft.getMinecraft().fontRenderer; + drawRect(i, j, i + 16, j + 16, -2130706433); + GL11.glEnable(GL11.GL_DEPTH_TEST); + itemRender.renderItemAndEffectIntoGUI( + font, + Minecraft.getMinecraft().getTextureManager(), + container, + this.posX, + this.posY); + // itemRender.renderItemOverlayIntoGUI(font, + // Minecraft.getMinecraft().getTextureManager(), container, posX + 1, + // posY - 7, null); + this.zLevel = 0.0F; + itemRender.zLevel = 0.0F; + } - public int getPosX() { - return this.posX; - } + public int getPosX() { + return this.posX; + } - public int getPosY() { - return this.posY; - } + public int getPosY() { + return this.posY; + } - public void mouseClicked(ItemStack stack) { - if (stack != null && stack.getItem() != null - && FluidUtil.isEmpty(stack)) - new PacketFluidContainerSlot(this.fluidFiller, stack, this.player) - .sendPacketToServer(); - } + public void mouseClicked(ItemStack stack) { + if (stack != null && stack.getItem() != null && FluidUtil.isEmpty(stack)) + new PacketFluidContainerSlot(this.fluidFiller, stack, this.player).sendPacketToServer(); + } } diff --git a/src/main/scala/extracells/gui/widget/WidgetStorageDirection.java b/src/main/scala/extracells/gui/widget/WidgetStorageDirection.java index 7dab8cc50..c10db1ad3 100644 --- a/src/main/scala/extracells/gui/widget/WidgetStorageDirection.java +++ b/src/main/scala/extracells/gui/widget/WidgetStorageDirection.java @@ -1,7 +1,9 @@ package extracells.gui.widget; -import appeng.api.config.AccessRestriction; -import com.google.common.base.Splitter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; @@ -9,167 +11,149 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; +import com.google.common.base.Splitter; + +import appeng.api.config.AccessRestriction; public class WidgetStorageDirection extends GuiButton { - private AccessRestriction access; - - public WidgetStorageDirection(int ID, int xPos, int yPos, int width, - int height, AccessRestriction mode) { - super(ID, xPos, yPos, width, height, ""); - this.access = mode; - } - - @Override - public void drawButton(Minecraft minecraftInstance, int x, int y) { - GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - mouseDragged(minecraftInstance, x, y); - - minecraftInstance.getTextureManager().bindTexture( - new ResourceLocation("appliedenergistics2", - "textures/guis/states.png")); - drawTexturedModalRect(this.xPosition, this.yPosition, 240, 240, 16, 16); - - switch (this.access) { - case NO_ACCESS: - drawTexturedModalRect(this.xPosition, this.yPosition, 96, 0, 16, 16); - break; - case READ: - drawTexturedModalRect(this.xPosition, this.yPosition, 16, 144, 16, - 16); - break; - case READ_WRITE: - drawTexturedModalRect(this.xPosition, this.yPosition, 32, 144, 16, - 16); - break; - case WRITE: - drawTexturedModalRect(this.xPosition, this.yPosition, 0, 144, 16, - 16); - break; - default: - break; - } - } - - @SuppressWarnings("rawtypes") - protected void drawHoveringText(List list, int x, int y, - FontRenderer fontrenderer) { - if (!list.isEmpty()) { - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - int k = 0; - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - String s = (String) iterator.next(); - int l = fontrenderer.getStringWidth(s); - - if (l > k) { - k = l; - } - } - - int i1 = x + 12; - int j1 = y - 12; - int k1 = 8; - - if (list.size() > 1) { - k1 += 2 + (list.size() - 1) * 10; - } - - this.zLevel = 300.0F; - int l1 = -267386864; - this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); - this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, - l1, l1); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, - l1); - this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, - l1, l1); - int i2 = 1347420415; - int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; - this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - - 1, i2, j2); - this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 - + 3 - 1, i2, j2); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, - i2); - this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, - j2, j2); - - for (int k2 = 0; k2 < list.size(); ++k2) { - String s1 = (String) list.get(k2); - fontrenderer.drawStringWithShadow(s1, i1, j1, -1); - - if (k2 == 0) { - j1 += 2; - } - - j1 += 10; - } - - this.zLevel = 0.0F; - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - } - } - - public void drawTooltip(int mouseX, int mouseY, int guiXPos, int guiYPos) { - List description = new ArrayList(); - description.add(StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.IOMode")); - String explanation = ""; - switch (this.access) { - case NO_ACCESS: - explanation = StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.Disabled"); - break; - case READ: - explanation = StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.Read"); - break; - case READ_WRITE: - explanation = StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.ReadWrite"); - break; - case WRITE: - explanation = StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.Write"); - break; - default: - break; - } - - for (String current : Splitter.fixedLength(30).split(explanation)) { - description.add(EnumChatFormatting.GRAY + current); - } - - Minecraft mc = Minecraft.getMinecraft(); - - if (mouseX >= this.xPosition && mouseX <= this.xPosition + this.width - && mouseY >= this.yPosition - && mouseY <= this.yPosition + this.height) { - drawHoveringText(description, mouseX - guiXPos, mouseY - guiYPos, - mc.fontRenderer); - } - } - - public AccessRestriction getAccessRestriction() { - return this.access; - } - - public void setAccessRestriction(AccessRestriction mode) { - this.access = mode; - } + private AccessRestriction access; + + public WidgetStorageDirection(int ID, int xPos, int yPos, int width, int height, AccessRestriction mode) { + super(ID, xPos, yPos, width, height, ""); + this.access = mode; + } + + @Override + public void drawButton(Minecraft minecraftInstance, int x, int y) { + GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); + mouseDragged(minecraftInstance, x, y); + + minecraftInstance.getTextureManager() + .bindTexture(new ResourceLocation("appliedenergistics2", "textures/guis/states.png")); + drawTexturedModalRect(this.xPosition, this.yPosition, 240, 240, 16, 16); + + switch (this.access) { + case NO_ACCESS: + drawTexturedModalRect(this.xPosition, this.yPosition, 96, 0, 16, 16); + break; + case READ: + drawTexturedModalRect(this.xPosition, this.yPosition, 16, 144, 16, 16); + break; + case READ_WRITE: + drawTexturedModalRect(this.xPosition, this.yPosition, 32, 144, 16, 16); + break; + case WRITE: + drawTexturedModalRect(this.xPosition, this.yPosition, 0, 144, 16, 16); + break; + default: + break; + } + } + + @SuppressWarnings("rawtypes") + protected void drawHoveringText(List list, int x, int y, FontRenderer fontrenderer) { + if (!list.isEmpty()) { + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + int k = 0; + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + String s = (String) iterator.next(); + int l = fontrenderer.getStringWidth(s); + + if (l > k) { + k = l; + } + } + + int i1 = x + 12; + int j1 = y - 12; + int k1 = 8; + + if (list.size() > 1) { + k1 += 2 + (list.size() - 1) * 10; + } + + this.zLevel = 300.0F; + int l1 = -267386864; + this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); + this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); + int i2 = 1347420415; + int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; + this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2); + this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2); + + for (int k2 = 0; k2 < list.size(); ++k2) { + String s1 = (String) list.get(k2); + fontrenderer.drawStringWithShadow(s1, i1, j1, -1); + + if (k2 == 0) { + j1 += 2; + } + + j1 += 10; + } + + this.zLevel = 0.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + } + + public void drawTooltip(int mouseX, int mouseY, int guiXPos, int guiYPos) { + List description = new ArrayList(); + description.add(StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.IOMode")); + String explanation = ""; + switch (this.access) { + case NO_ACCESS: + explanation = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.Disabled"); + break; + case READ: + explanation = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.Read"); + break; + case READ_WRITE: + explanation = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.ReadWrite"); + break; + case WRITE: + explanation = StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.Write"); + break; + default: + break; + } + + for (String current : Splitter.fixedLength(30).split(explanation)) { + description.add(EnumChatFormatting.GRAY + current); + } + + Minecraft mc = Minecraft.getMinecraft(); + + if (mouseX >= this.xPosition && mouseX <= this.xPosition + this.width + && mouseY >= this.yPosition + && mouseY <= this.yPosition + this.height) { + drawHoveringText(description, mouseX - guiXPos, mouseY - guiYPos, mc.fontRenderer); + } + } + + public AccessRestriction getAccessRestriction() { + return this.access; + } + + public void setAccessRestriction(AccessRestriction mode) { + this.access = mode; + } } diff --git a/src/main/scala/extracells/gui/widget/fluid/AbstractFluidWidget.java b/src/main/scala/extracells/gui/widget/fluid/AbstractFluidWidget.java index 19c27feeb..9c4e5b21d 100644 --- a/src/main/scala/extracells/gui/widget/fluid/AbstractFluidWidget.java +++ b/src/main/scala/extracells/gui/widget/fluid/AbstractFluidWidget.java @@ -1,122 +1,111 @@ package extracells.gui.widget.fluid; +import java.util.List; + import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; import net.minecraft.client.renderer.RenderHelper; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.List; - public abstract class AbstractFluidWidget extends Gui { - protected int height = 0, width = 0; - protected Fluid fluid; - protected IFluidWidgetGui guiFluidTerminal; - - public AbstractFluidWidget(IFluidWidgetGui guiFluidTerminal, int height, - int width, Fluid fluid) { - this.guiFluidTerminal = guiFluidTerminal; - this.height = height; - this.width = width; - this.fluid = fluid; - } - - @SuppressWarnings("rawtypes") - protected void drawHoveringText(List list, int x, int y, - FontRenderer fontrenderer) { - if (!list.isEmpty()) { - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - int k = 0; - - for (Object string : list) { - String s = (String) string; - int l = fontrenderer.getStringWidth(s); - - if (l > k) { - k = l; - } - } - - int i1 = x + 12; - int j1 = y - 12; - int k1 = 8; - - if (list.size() > 1) { - k1 += 2 + (list.size() - 1) * 10; - } - - this.zLevel = 300.0F; - int l1 = -267386864; - this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); - this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, - l1, l1); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, - l1); - this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, - l1, l1); - int i2 = 1347420415; - int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; - this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - - 1, i2, j2); - this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 - + 3 - 1, i2, j2); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, - i2); - this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, - j2, j2); - - for (int k2 = 0; k2 < list.size(); ++k2) { - String s1 = (String) list.get(k2); - fontrenderer.drawStringWithShadow(s1, i1, j1, -1); - - if (k2 == 0) { - j1 += 2; - } - - j1 += 10; - } - - this.zLevel = 0.0F; - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - } - } - - public abstract boolean drawTooltip(int posX, int posY, int mouseX, - int mouseY); - - public abstract void drawWidget(int posX, int posY); - - public Fluid getFluid() { - return this.fluid; - } - - protected boolean isPointInRegion(int top, int left, int height, int width, - int pointX, int pointY) { - int k1 = this.guiFluidTerminal.guiLeft(); - int l1 = this.guiFluidTerminal.guiTop() + 18; - pointX -= k1; - pointY -= l1; - return pointX >= top - 1 && pointX < top + height + 1 - && pointY >= left - 1 && pointY < left + width + 1; - } - - public abstract void mouseClicked(int posX, int posY, int mouseX, int mouseY); - - public void setFluid(Fluid fluid) { - this.fluid = fluid; - } - - public void setFluid(int fluidID) { - this.fluid = FluidRegistry.getFluid(fluidID); - } + protected int height = 0, width = 0; + protected Fluid fluid; + protected IFluidWidgetGui guiFluidTerminal; + + public AbstractFluidWidget(IFluidWidgetGui guiFluidTerminal, int height, int width, Fluid fluid) { + this.guiFluidTerminal = guiFluidTerminal; + this.height = height; + this.width = width; + this.fluid = fluid; + } + + @SuppressWarnings("rawtypes") + protected void drawHoveringText(List list, int x, int y, FontRenderer fontrenderer) { + if (!list.isEmpty()) { + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + int k = 0; + + for (Object string : list) { + String s = (String) string; + int l = fontrenderer.getStringWidth(s); + + if (l > k) { + k = l; + } + } + + int i1 = x + 12; + int j1 = y - 12; + int k1 = 8; + + if (list.size() > 1) { + k1 += 2 + (list.size() - 1) * 10; + } + + this.zLevel = 300.0F; + int l1 = -267386864; + this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); + this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); + int i2 = 1347420415; + int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; + this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2); + this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2); + + for (int k2 = 0; k2 < list.size(); ++k2) { + String s1 = (String) list.get(k2); + fontrenderer.drawStringWithShadow(s1, i1, j1, -1); + + if (k2 == 0) { + j1 += 2; + } + + j1 += 10; + } + + this.zLevel = 0.0F; + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + } + + public abstract boolean drawTooltip(int posX, int posY, int mouseX, int mouseY); + + public abstract void drawWidget(int posX, int posY); + + public Fluid getFluid() { + return this.fluid; + } + + protected boolean isPointInRegion(int top, int left, int height, int width, int pointX, int pointY) { + int k1 = this.guiFluidTerminal.guiLeft(); + int l1 = this.guiFluidTerminal.guiTop() + 18; + pointX -= k1; + pointY -= l1; + return pointX >= top - 1 && pointX < top + height + 1 && pointY >= left - 1 && pointY < left + width + 1; + } + + public abstract void mouseClicked(int posX, int posY, int mouseX, int mouseY); + + public void setFluid(Fluid fluid) { + this.fluid = fluid; + } + + public void setFluid(int fluidID) { + this.fluid = FluidRegistry.getFluid(fluidID); + } } diff --git a/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorContainer.java b/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorContainer.java index 0ae9d1289..506aac0c5 100644 --- a/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorContainer.java +++ b/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorContainer.java @@ -4,5 +4,5 @@ public interface IFluidSelectorContainer { - public void setSelectedFluid(Fluid _fluid); + public void setSelectedFluid(Fluid _fluid); } diff --git a/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorGui.java b/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorGui.java index 77d15a63e..33ab12219 100644 --- a/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorGui.java +++ b/src/main/scala/extracells/gui/widget/fluid/IFluidSelectorGui.java @@ -4,7 +4,7 @@ public interface IFluidSelectorGui extends IFluidWidgetGui { - public IFluidSelectorContainer getContainer(); + public IFluidSelectorContainer getContainer(); - public IAEFluidStack getCurrentFluid(); + public IAEFluidStack getCurrentFluid(); } diff --git a/src/main/scala/extracells/gui/widget/fluid/IFluidWidgetGui.java b/src/main/scala/extracells/gui/widget/fluid/IFluidWidgetGui.java index 59009e6d2..ae8565342 100644 --- a/src/main/scala/extracells/gui/widget/fluid/IFluidWidgetGui.java +++ b/src/main/scala/extracells/gui/widget/fluid/IFluidWidgetGui.java @@ -2,7 +2,7 @@ public interface IFluidWidgetGui { - public int guiLeft(); + public int guiLeft(); - public int guiTop(); + public int guiTop(); } diff --git a/src/main/scala/extracells/gui/widget/fluid/WidgetFluidRequest.java b/src/main/scala/extracells/gui/widget/fluid/WidgetFluidRequest.java index 9b0e4b2be..24137790d 100644 --- a/src/main/scala/extracells/gui/widget/fluid/WidgetFluidRequest.java +++ b/src/main/scala/extracells/gui/widget/fluid/WidgetFluidRequest.java @@ -1,67 +1,67 @@ package extracells.gui.widget.fluid; -import extracells.gui.GuiFluidTerminal; +import java.util.ArrayList; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; + import org.apache.commons.lang3.text.WordUtils; import org.lwjgl.opengl.GL11; -import java.util.ArrayList; -import java.util.List; +import extracells.gui.GuiFluidTerminal; public class WidgetFluidRequest extends AbstractFluidWidget { - public WidgetFluidRequest(GuiFluidTerminal guiFluidTerminal, Fluid fluid) { - super(guiFluidTerminal, 18, 18, fluid); - } + public WidgetFluidRequest(GuiFluidTerminal guiFluidTerminal, Fluid fluid) { + super(guiFluidTerminal, 18, 18, fluid); + } - @Override - public boolean drawTooltip(int posX, int posY, int mouseX, int mouseY) { - if (this.fluid == null - || !isPointInRegion(posX, posY, this.height, this.width, - mouseX, mouseY)) - return false; + @Override + public boolean drawTooltip(int posX, int posY, int mouseX, int mouseY) { + if (this.fluid == null || !isPointInRegion(posX, posY, this.height, this.width, mouseX, mouseY)) return false; - List description = new ArrayList(); - description - .add(StatCollector - .translateToLocal("gui.tooltips.appliedenergistics2.Craftable")); - description.add(this.fluid.getLocalizedName(new FluidStack(this.fluid, - 1))); - drawHoveringText(description, mouseX - this.guiFluidTerminal.guiLeft(), - mouseY - this.guiFluidTerminal.guiTop() + 18, - Minecraft.getMinecraft().fontRenderer); - return true; - } + List description = new ArrayList(); + description.add(StatCollector.translateToLocal("gui.tooltips.appliedenergistics2.Craftable")); + description.add(this.fluid.getLocalizedName(new FluidStack(this.fluid, 1))); + drawHoveringText( + description, + mouseX - this.guiFluidTerminal.guiLeft(), + mouseY - this.guiFluidTerminal.guiTop() + 18, + Minecraft.getMinecraft().fontRenderer); + return true; + } - @Override - public void drawWidget(int posX, int posY) { - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor3f(1, 1, 1); - if (this.fluid != null && this.fluid.getIcon() != null) { - drawTexturedModelRectFromIcon(posX + 1, posY + 1, - this.fluid.getIcon(), this.height - 2, this.width - 2); - GL11.glScalef(0.5F, 0.5F, 0.5F); - String str = StatCollector.translateToLocal("extracells.gui.craft"); - str = WordUtils.capitalize(str.toLowerCase()); - Minecraft.getMinecraft().fontRenderer.drawString( - EnumChatFormatting.WHITE + str, 52 + posX - str.length(), - posY + 24, 0); - } - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_BLEND); - } + @Override + public void drawWidget(int posX, int posY) { + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor3f(1, 1, 1); + if (this.fluid != null && this.fluid.getIcon() != null) { + GL11.glColor3f( + (this.fluid.getColor() >> 16 & 0xFF) / 255.0F, + (this.fluid.getColor() >> 8 & 0xFF) / 255.0F, + (this.fluid.getColor() & 0xFF) / 255.0F); + drawTexturedModelRectFromIcon(posX + 1, posY + 1, this.fluid.getIcon(), this.height - 2, this.width - 2); + GL11.glColor3f(1.0F, 1.0F, 1.0F); + GL11.glScalef(0.5F, 0.5F, 0.5F); + String str = StatCollector.translateToLocal("extracells.gui.craft"); + str = WordUtils.capitalize(str.toLowerCase()); + Minecraft.getMinecraft().fontRenderer + .drawString(EnumChatFormatting.WHITE + str, 52 + posX - str.length(), posY + 24, 0); + } + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + } - @Override - public void mouseClicked(int posX, int posY, int mouseX, int mouseY) { - // TODO - } + @Override + public void mouseClicked(int posX, int posY, int mouseX, int mouseY) { + // TODO + } } diff --git a/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSelector.java b/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSelector.java index 978831ff3..bc8599960 100644 --- a/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSelector.java +++ b/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSelector.java @@ -1,114 +1,121 @@ package extracells.gui.widget.fluid; -import appeng.api.storage.data.IAEFluidStack; -import extracells.Extracells; +import java.util.ArrayList; +import java.util.List; + import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; + import org.lwjgl.opengl.GL11; -import java.util.ArrayList; -import java.util.List; +import appeng.api.storage.data.IAEFluidStack; +import extracells.util.FluidUtil; public class WidgetFluidSelector extends AbstractFluidWidget { - private long amount = 0; - private int color; - private int borderThickness; - - public WidgetFluidSelector(IFluidSelectorGui guiFluidTerminal, - IAEFluidStack stack) { - super(guiFluidTerminal, 18, 18, stack.getFluidStack().getFluid()); - this.amount = stack.getStackSize(); - this.color = 0xFF00FFFF; - this.borderThickness = 1; - } - - private void drawHollowRectWithCorners(int posX, int posY, int height, - int width, int color, int thickness) { - drawRect(posX, posY, posX + height, posY + thickness, color); - drawRect(posX, posY + width - thickness, posX + height, posY + width, - color); - drawRect(posX, posY, posX + thickness, posY + width, color); - drawRect(posX + height - thickness, posY, posX + height, posY + width, - color); - - drawRect(posX, posY, posX + thickness + 1, posY + thickness + 1, color); - drawRect(posX + height, posY + width, posX + height - thickness - 1, - posY + width - thickness - 1, color); - drawRect(posX + height, posY, posX + height - thickness - 1, posY - + thickness + 1, color); - drawRect(posX, posY + width, posX + thickness + 1, posY + width - - thickness - 1, color); - } - - @Override - public boolean drawTooltip(int posX, int posY, int mouseX, int mouseY) { - if (this.fluid == null - || this.amount <= 0 - || !isPointInRegion(posX, posY, this.height, this.width, - mouseX, mouseY)) - return false; - - String amountToText = Long.toString(this.amount) + "mB"; - if (Extracells.shortenedBuckets()) { - if (this.amount > 1000000000L) - amountToText = Long.toString(this.amount / 1000000000L) - + "MegaB"; - else if (this.amount > 1000000L) - amountToText = Long.toString(this.amount / 1000000L) + "KiloB"; - else if (this.amount > 9999L) { - amountToText = Long.toString(this.amount / 1000L) + "B"; - } - } - - List description = new ArrayList(); - description.add(this.fluid.getLocalizedName(new FluidStack(this.fluid, 0))); - description.add(amountToText); - drawHoveringText(description, mouseX - this.guiFluidTerminal.guiLeft(), - mouseY - this.guiFluidTerminal.guiTop() + 18, - Minecraft.getMinecraft().fontRenderer); - return true; - } - - @Override - public void drawWidget(int posX, int posY) { - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor3f(1, 1, 1); - IAEFluidStack terminalFluid = ((IFluidSelectorGui) this.guiFluidTerminal) - .getCurrentFluid(); - Fluid currentFluid = terminalFluid != null ? terminalFluid.getFluid() - : null; - if (this.fluid != null && this.fluid.getIcon() != null) - drawTexturedModelRectFromIcon(posX + 1, posY + 1, - this.fluid.getIcon(), this.height - 2, this.width - 2); - if (this.fluid == currentFluid) - drawHollowRectWithCorners(posX, posY, this.height, this.width, - this.color, this.borderThickness); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_BLEND); - } - - public long getAmount() { - return this.amount; - } - - @Override - public void mouseClicked(int posX, int posY, int mouseX, int mouseY) { - if (this.fluid != null - && isPointInRegion(posX, posY, this.height, this.width, mouseX, - mouseY)) { - ((IFluidSelectorGui) this.guiFluidTerminal).getContainer() - .setSelectedFluid(this.fluid); - } - } - - public void setAmount(long amount) { - this.amount = amount; - } + private long amount = 0; + private int color; + private int borderThickness; + + public WidgetFluidSelector(IFluidSelectorGui guiFluidTerminal, IAEFluidStack stack) { + super(guiFluidTerminal, 18, 18, stack.getFluidStack().getFluid()); + this.amount = stack.getStackSize(); + this.color = 0xFF00FFFF; + this.borderThickness = 1; + } + + private void drawHollowRectWithCorners(int posX, int posY, int height, int width, int color, int thickness) { + drawRect(posX, posY, posX + height, posY + thickness, color); + drawRect(posX, posY + width - thickness, posX + height, posY + width, color); + drawRect(posX, posY, posX + thickness, posY + width, color); + drawRect(posX + height - thickness, posY, posX + height, posY + width, color); + + drawRect(posX, posY, posX + thickness + 1, posY + thickness + 1, color); + drawRect(posX + height, posY + width, posX + height - thickness - 1, posY + width - thickness - 1, color); + drawRect(posX + height, posY, posX + height - thickness - 1, posY + thickness + 1, color); + drawRect(posX, posY + width, posX + thickness + 1, posY + width - thickness - 1, color); + } + + @Override + public boolean drawTooltip(int posX, int posY, int mouseX, int mouseY) { + if (this.fluid == null || this.amount <= 0 + || !isPointInRegion(posX, posY, this.height, this.width, mouseX, mouseY)) + return false; + + String amountToText = FluidUtil.formatFluidAmount(this.amount, true); + + List description = new ArrayList(); + description.add(this.fluid.getLocalizedName(new FluidStack(this.fluid, 0))); + description.add(amountToText); + drawHoveringText( + description, + mouseX - this.guiFluidTerminal.guiLeft(), + mouseY - this.guiFluidTerminal.guiTop() + 18, + Minecraft.getMinecraft().fontRenderer); + return true; + } + + @Override + public void drawWidget(int posX, int posY) { + FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer; + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor3f(1F, 1F, 1F); + + IAEFluidStack terminalFluid = ((IFluidSelectorGui) this.guiFluidTerminal).getCurrentFluid(); + Fluid currentFluid = terminalFluid != null ? terminalFluid.getFluid() : null; + + if (this.fluid != null && this.fluid.getIcon() != null) { + GL11.glColor3f( + (this.fluid.getColor() >> 16 & 0xFF) / 255.0F, + (this.fluid.getColor() >> 8 & 0xFF) / 255.0F, + (this.fluid.getColor() & 0xFF) / 255.0F); + drawTexturedModelRectFromIcon(posX + 1, posY + 1, this.fluid.getIcon(), this.height - 2, this.width - 2); + } + GL11.glColor3f(1F, 1F, 1F); + + final float scaleFactor = 0.5f; + final float inverseScaleFactor = 1.0f / scaleFactor; + final float offset = -1.0f; + final String stackSize = FluidUtil.formatFluidAmount(this.amount); + + GL11.glDisable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_DEPTH_TEST); + GL11.glPushMatrix(); + GL11.glScaled(scaleFactor, scaleFactor, scaleFactor); + + final int X = (int) (((float) posX + offset + 16.0f - fontRenderer.getStringWidth(stackSize) * scaleFactor) + * inverseScaleFactor); + final int Y = (int) (((float) posY + offset + 16.0f - 7.0f * scaleFactor) * inverseScaleFactor); + fontRenderer.drawStringWithShadow(stackSize, X, Y, 16777215); + + GL11.glPopMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_DEPTH_TEST); + + if (this.fluid == currentFluid) + drawHollowRectWithCorners(posX, posY, this.height, this.width, this.color, this.borderThickness); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + } + + public long getAmount() { + return this.amount; + } + + @Override + public void mouseClicked(int posX, int posY, int mouseX, int mouseY) { + if (this.fluid != null && isPointInRegion(posX, posY, this.height, this.width, mouseX, mouseY)) { + ((IFluidSelectorGui) this.guiFluidTerminal).getContainer().setSelectedFluid(this.fluid); + } + } + + public void setAmount(long amount) { + this.amount = amount; + } } diff --git a/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSlot.java b/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSlot.java index cc9d1f92e..3b505504f 100644 --- a/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSlot.java +++ b/src/main/scala/extracells/gui/widget/fluid/WidgetFluidSlot.java @@ -1,11 +1,8 @@ package extracells.gui.widget.fluid; -import cpw.mods.fml.common.Optional; -import extracells.network.packet.other.IFluidSlotPartOrBlock; -import extracells.network.packet.other.PacketFluidSlot; -import extracells.util.FluidUtil; -import extracells.util.GasUtil; -import mekanism.api.gas.GasStack; +import java.util.ArrayList; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.Gui; @@ -16,184 +13,206 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import java.util.List; +import cpw.mods.fml.common.Optional; +import extracells.network.packet.other.IFluidSlotPartOrBlock; +import extracells.network.packet.other.PacketFluidSlot; +import extracells.util.FluidUtil; +import extracells.util.GasUtil; +import mekanism.api.gas.GasStack; public class WidgetFluidSlot extends Gui { - public interface IConfigurable { - - public byte getConfigState(); - } - - private int id; - private int posX, posY; - private Fluid fluid; - private static final ResourceLocation guiTexture = new ResourceLocation( - "extracells", "textures/gui/busiofluid.png"); - private IFluidSlotPartOrBlock part; - private EntityPlayer player; - private IConfigurable configurable; - - private byte configOption; - - public WidgetFluidSlot(EntityPlayer _player, IFluidSlotPartOrBlock _part, - int _posX, int _posY) { - this(_player, _part, 0, _posX, _posY, null, (byte) 0); - } - - public WidgetFluidSlot(EntityPlayer _player, IFluidSlotPartOrBlock _part, - int _id, int _posX, int _posY) { - this(_player, _part, _id, _posX, _posY, null, (byte) 0); - } - - public WidgetFluidSlot(EntityPlayer _player, IFluidSlotPartOrBlock _part, - int _id, int _posX, int _posY, IConfigurable _configurable, - byte _configOption) { - this.player = _player; - this.part = _part; - this.id = _id; - this.posX = _posX; - this.posY = _posY; - this.configurable = _configurable; - this.configOption = _configOption; - } - - public boolean canRender() { - return this.configurable == null - || this.configurable.getConfigState() >= this.configOption; - } - - @SuppressWarnings("rawtypes") - protected void drawHoveringText(List list, int x, int y, - FontRenderer fontrenderer) { - boolean lighting_enabled = GL11.glIsEnabled(GL11.GL_LIGHTING); - if (!list.isEmpty()) { - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - RenderHelper.disableStandardItemLighting(); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - int k = 0; - - for (Object string : list) { - String s = (String) string; - int l = fontrenderer.getStringWidth(s); - - if (l > k) { - k = l; - } - } - - int i1 = x + 12; - int j1 = y - 12; - int k1 = 8; - - if (list.size() > 1) { - k1 += 2 + (list.size() - 1) * 10; - } - - this.zLevel = 300.0F; - int l1 = -267386864; - this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); - this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, - l1, l1); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, - l1); - this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); - this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, - l1, l1); - int i2 = 1347420415; - int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; - this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - - 1, i2, j2); - this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 - + 3 - 1, i2, j2); - this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, - i2); - this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, - j2, j2); - - for (int k2 = 0; k2 < list.size(); ++k2) { - String s1 = (String) list.get(k2); - fontrenderer.drawStringWithShadow(s1, i1, j1, -1); - - if (k2 == 0) { - j1 += 2; - } - - j1 += 10; - } - - this.zLevel = 0.0F; - if (lighting_enabled) - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - RenderHelper.enableStandardItemLighting(); - GL11.glEnable(GL12.GL_RESCALE_NORMAL); - } - } - - public void drawTooltip() { - if (canRender()) { - - } - } - - public void drawWidget() { - if (!canRender()) - return; - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor3f(1, 1, 1); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glColor3f(1.0F, 1.0F, 1.0F); - Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); - drawTexturedModalRect(this.posX, this.posY, 79, 39, 18, 18); - GL11.glEnable(GL11.GL_LIGHTING); - - if (this.fluid == null || this.fluid.getIcon() == null) - return; - - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glColor3f(1.0F, 1.0F, 1.0F); - drawTexturedModelRectFromIcon(this.posX + 1, this.posY + 1, - this.fluid.getIcon(), 16, 16); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_BLEND); - } - - public Fluid getFluid() { - return this.fluid; - } - - public int getPosX() { - return this.posX; - } - - public int getPosY() { - return this.posY; - } - - public void mouseClicked(ItemStack stack) { - FluidStack fluidStack = FluidUtil.getFluidFromContainer(stack); - this.fluid = fluidStack == null ? null : fluidStack.getFluid(); - new PacketFluidSlot(this.part, this.id, this.fluid, this.player).sendPacketToServer(); - } - - @Optional.Method(modid = "MekanismAPI|gas") - public void mouseClickedGas(ItemStack stack) { - GasStack gasStack = GasUtil.getGasFromContainer(stack); - FluidStack fluidStack = GasUtil.getFluidStack(gasStack); - this.fluid = fluidStack == null ? null : fluidStack.getFluid(); - new PacketFluidSlot(this.part, this.id, this.fluid, this.player).sendPacketToServer(); - } - - public void setFluid(Fluid _fluid) { - this.fluid = _fluid; - } + public interface IConfigurable { + + public byte getConfigState(); + } + + private int id; + private int posX, posY; + private Fluid fluid; + private static final ResourceLocation guiTexture = new ResourceLocation( + "extracells", + "textures/gui/busiofluid.png"); + private IFluidSlotPartOrBlock part; + private EntityPlayer player; + private IConfigurable configurable; + + private byte configOption; + + private boolean dragItem = false; + + public WidgetFluidSlot(EntityPlayer _player, IFluidSlotPartOrBlock _part, int _posX, int _posY) { + this(_player, _part, 0, _posX, _posY, null, (byte) 0); + } + + public WidgetFluidSlot(EntityPlayer _player, IFluidSlotPartOrBlock _part, int _id, int _posX, int _posY) { + this(_player, _part, _id, _posX, _posY, null, (byte) 0); + } + + public WidgetFluidSlot(EntityPlayer _player, IFluidSlotPartOrBlock _part, int _id, int _posX, int _posY, + IConfigurable _configurable, byte _configOption) { + this.player = _player; + this.part = _part; + this.id = _id; + this.posX = _posX; + this.posY = _posY; + this.configurable = _configurable; + this.configOption = _configOption; + } + + public boolean canRender() { + return this.configurable == null || this.configurable.getConfigState() >= this.configOption; + } + + @SuppressWarnings("rawtypes") + protected void drawHoveringText(List list, int x, int y, FontRenderer fontrenderer) { + boolean lighting_enabled = GL11.glIsEnabled(GL11.GL_LIGHTING); + if (!list.isEmpty()) { + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + RenderHelper.disableStandardItemLighting(); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + int k = 0; + + for (Object string : list) { + String s = (String) string; + int l = fontrenderer.getStringWidth(s); + + if (l > k) { + k = l; + } + } + + int i1 = x + 12; + int j1 = y - 12; + int k1 = 8; + + if (list.size() > 1) { + k1 += 2 + (list.size() - 1) * 10; + } + + this.zLevel = 300.0F; + int l1 = -267386864; + this.drawGradientRect(i1 - 3, j1 - 4, i1 + k + 3, j1 - 3, l1, l1); + this.drawGradientRect(i1 - 3, j1 + k1 + 3, i1 + k + 3, j1 + k1 + 4, l1, l1); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 - 4, j1 - 3, i1 - 3, j1 + k1 + 3, l1, l1); + this.drawGradientRect(i1 + k + 3, j1 - 3, i1 + k + 4, j1 + k1 + 3, l1, l1); + int i2 = 1347420415; + int j2 = (i2 & 16711422) >> 1 | i2 & -16777216; + this.drawGradientRect(i1 - 3, j1 - 3 + 1, i1 - 3 + 1, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 + k + 2, j1 - 3 + 1, i1 + k + 3, j1 + k1 + 3 - 1, i2, j2); + this.drawGradientRect(i1 - 3, j1 - 3, i1 + k + 3, j1 - 3 + 1, i2, i2); + this.drawGradientRect(i1 - 3, j1 + k1 + 2, i1 + k + 3, j1 + k1 + 3, j2, j2); + + for (int k2 = 0; k2 < list.size(); ++k2) { + String s1 = (String) list.get(k2); + fontrenderer.drawStringWithShadow(s1, i1, j1, -1); + + if (k2 == 0) { + j1 += 2; + } + + j1 += 10; + } + + this.zLevel = 0.0F; + if (lighting_enabled) GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + RenderHelper.enableStandardItemLighting(); + GL11.glEnable(GL12.GL_RESCALE_NORMAL); + } + } + + public void drawTooltip(int x, int y) { + if (canRender()) { + if (this.fluid != null) { + List description = new ArrayList(); + description.add(this.fluid.getLocalizedName(new FluidStack(this.fluid, 0))); + drawHoveringText(description, x, y, Minecraft.getMinecraft().fontRenderer); + } + } + } + + public void drawWidget() { + if (!canRender()) return; + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor3f(1, 1, 1); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glColor3f(1.0F, 1.0F, 1.0F); + Minecraft.getMinecraft().renderEngine.bindTexture(guiTexture); + drawTexturedModalRect(this.posX, this.posY, 79, 39, 18, 18); + GL11.glEnable(GL11.GL_LIGHTING); + + if (this.fluid == null || this.fluid.getIcon() == null) return; + + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glColor3f(1.0F, 1.0F, 1.0F); + GL11.glColor3f( + (this.fluid.getColor() >> 16 & 0xFF) / 255.0F, + (this.fluid.getColor() >> 8 & 0xFF) / 255.0F, + (this.fluid.getColor() & 0xFF) / 255.0F); + drawTexturedModelRectFromIcon(this.posX + 1, this.posY + 1, this.fluid.getIcon(), 16, 16); + GL11.glColor3f(1.0F, 1.0F, 1.0F); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_BLEND); + } + + public Fluid getFluid() { + return this.fluid; + } + + public int getPosX() { + return this.posX; + } + + public int getPosY() { + return this.posY; + } + + public void mouseClicked(ItemStack stack) { + if (dragItem) { + dragItem = false; + return; + } + FluidStack fluidStack = FluidUtil.getFluidFromContainer(stack); + this.fluid = fluidStack == null ? null : fluidStack.getFluid(); + new PacketFluidSlot(this.part, this.id, this.fluid, this.player).sendPacketToServer(); + } + + public void mouseNEIClicked(ItemStack stack) { + if (stack == null) return; + dragItem = true; + FluidStack fluidStack = FluidUtil.getFluidFromContainer(stack); + this.fluid = fluidStack == null ? null : fluidStack.getFluid(); + new PacketFluidSlot(this.part, this.id, this.fluid, this.player).sendPacketToServer(); + } + + @Optional.Method(modid = "MekanismAPI|gas") + public void mouseClickedGas(ItemStack stack) { + GasStack gasStack = GasUtil.getGasFromContainer(stack); + FluidStack fluidStack = GasUtil.getFluidStack(gasStack); + this.fluid = fluidStack == null ? null : fluidStack.getFluid(); + new PacketFluidSlot(this.part, this.id, this.fluid, this.player).sendPacketToServer(); + } + + @Optional.Method(modid = "MekanismAPI|gas") + public void mouseNEIClickedGas(ItemStack stack) { + if (stack == null) return; + GasStack gasStack = GasUtil.getGasFromContainer(stack); + FluidStack fluidStack = GasUtil.getFluidStack(gasStack); + this.fluid = fluidStack == null ? null : fluidStack.getFluid(); + new PacketFluidSlot(this.part, this.id, this.fluid, this.player).sendPacketToServer(); + } + + public void setFluid(Fluid _fluid) { + this.fluid = _fluid; + } } diff --git a/src/main/scala/extracells/integration/Integration.java b/src/main/scala/extracells/integration/Integration.java index 462e720be..5c022c7a0 100644 --- a/src/main/scala/extracells/integration/Integration.java +++ b/src/main/scala/extracells/integration/Integration.java @@ -1,5 +1,7 @@ package extracells.integration; +import net.minecraftforge.common.config.Configuration; + import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ModAPIManager; import cpw.mods.fml.relauncher.Side; @@ -10,109 +12,103 @@ import extracells.integration.nei.Nei; import extracells.integration.opencomputers.OpenComputers; import extracells.integration.waila.Waila; -import net.minecraftforge.common.config.Configuration; public class Integration { - - public enum Mods{ - WAILA("Waila"), - OPENCOMPUTERS("OpenComputers"), - BCFUEL("BuildCraftAPI|fuels", "BuildCraftFuel"), - NEI("NotEnoughItems", Side.CLIENT), - MEKANISMGAS("MekanismAPI|gas", "MekanismGas"), - IGW("IGWMod", "IngameWikiMod", Side.CLIENT), - THAUMATICENERGISTICS("thaumicenergistics", "Thaumatic Energistics"), - MEKANISM("Mekanism"), - WIRELESSCRAFTING("ae2wct", "AE2 Wireless Crafting Terminal"); - - private final String modID; - - private boolean shouldLoad = true; - - private final String name; - - private final Side side; - - private Mods(String modid){ - this(modid, modid); - } - - private Mods(String modid, String modName, Side side) { - this.modID = modid; - this.name = modName; - this.side = side; - } - - private Mods(String modid, String modName){ - this(modid, modName, null); - } - - private Mods(String modid, Side side){ - this(modid, modid, side); - } - - public String getModID(){ - return modID; - } - - public String getModName() { - return name; - } - - public boolean isOnClient(){ - return side != Side.SERVER; - } - - public boolean isOnServer(){ - return side != Side.CLIENT; - } - - public void loadConfig(Configuration config){ - shouldLoad = config.get("Integration", "enable" + getModName(), true, "Enable " + getModName() + " Integration.").getBoolean(true); - } - - public boolean isEnabled(){ - return (Loader.isModLoaded(getModID()) && shouldLoad && correctSide()) || (ModAPIManager.INSTANCE.hasAPI(getModID()) && shouldLoad && correctSide()); - } - - private boolean correctSide(){ - return Extracells.proxy().isClient() ? isOnClient() : isOnServer(); - } - - - } - - - public void loadConfig(Configuration config){ - for (Mods mod : Mods.values()){ - mod.loadConfig(config); - } - } - - - public void preInit(){ - if (Mods.IGW.correctSide() && Mods.IGW.shouldLoad) - IGW.initNotifier(); - } - - public void init(){ - if (Mods.WAILA.isEnabled()) - Waila.init(); - if (Mods.OPENCOMPUTERS.isEnabled()) - OpenComputers.init(); - if (Mods.NEI.isEnabled()) - Nei.init(); - if (Mods.MEKANISMGAS.isEnabled()) - MekanismGas.init(); - if (Mods.IGW.isEnabled()) - IGW.init(); - if(Mods.MEKANISM.isEnabled()) - Mekanism.init(); - } - - public void postInit(){ - if (Mods.MEKANISMGAS.isEnabled()) - MekanismGas.postInit(); - } + public enum Mods { + + WAILA("Waila"), + OPENCOMPUTERS("OpenComputers"), + BCFUEL("BuildCraftAPI|fuels", "BuildCraftFuel"), + NEI("NotEnoughItems", Side.CLIENT), + MEKANISMGAS("MekanismAPI|gas", "MekanismGas"), + IGW("IGWMod", "IngameWikiMod", Side.CLIENT), + THAUMATICENERGISTICS("thaumicenergistics", "Thaumatic Energistics"), + MEKANISM("Mekanism"), + WIRELESSCRAFTING("ae2wct", "AE2 Wireless Crafting Terminal"), + FLUIDCRAFT("ae2fc", "Fluid Craft For AE2"); + + private final String modID; + + private boolean shouldLoad = true; + + private final String name; + + private final Side side; + + private Mods(String modid) { + this(modid, modid); + } + + private Mods(String modid, String modName, Side side) { + this.modID = modid; + this.name = modName; + this.side = side; + this.enabled = (Loader.isModLoaded(getModID()) && shouldLoad && correctSide()) + || (ModAPIManager.INSTANCE.hasAPI(getModID()) && shouldLoad && correctSide()); + } + + private Mods(String modid, String modName) { + this(modid, modName, null); + } + + private Mods(String modid, Side side) { + this(modid, modid, side); + } + + public String getModID() { + return modID; + } + + public String getModName() { + return name; + } + + public boolean isOnClient() { + return side != Side.SERVER; + } + + public boolean isOnServer() { + return side != Side.CLIENT; + } + + private final boolean enabled; + + public void loadConfig(Configuration config) { + shouldLoad = config + .get("Integration", "enable" + getModName(), true, "Enable " + getModName() + " Integration.") + .getBoolean(true); + } + + public boolean isEnabled() { + return enabled; + } + + private boolean correctSide() { + return Extracells.proxy().isClient() ? isOnClient() : isOnServer(); + } + } + + public void loadConfig(Configuration config) { + for (Mods mod : Mods.values()) { + mod.loadConfig(config); + } + } + + public void preInit() { + if (Mods.IGW.correctSide() && Mods.IGW.shouldLoad) IGW.initNotifier(); + } + + public void init() { + if (Mods.WAILA.isEnabled()) Waila.init(); + if (Mods.OPENCOMPUTERS.isEnabled()) OpenComputers.init(); + if (Mods.NEI.isEnabled()) Nei.init(); + if (Mods.MEKANISMGAS.isEnabled()) MekanismGas.init(); + if (Mods.IGW.isEnabled()) IGW.init(); + if (Mods.MEKANISM.isEnabled()) Mekanism.init(); + } + + public void postInit() { + if (Mods.MEKANISMGAS.isEnabled()) MekanismGas.postInit(); + } } diff --git a/src/main/scala/extracells/integration/WirelessCrafting/WirelessCrafting.scala b/src/main/scala/extracells/integration/WirelessCrafting/WirelessCrafting.scala index 929230d25..b67f166ae 100644 --- a/src/main/scala/extracells/integration/WirelessCrafting/WirelessCrafting.scala +++ b/src/main/scala/extracells/integration/WirelessCrafting/WirelessCrafting.scala @@ -4,9 +4,8 @@ import net.minecraft.entity.player.EntityPlayer import net.p455w0rd.wirelesscraftingterminal.api.WCTApi import net.p455w0rd.wirelesscraftingterminal.reference.Reference; - object WirelessCrafting { - def openCraftingTerminal(player :EntityPlayer) :Unit = + def openCraftingTerminal(player: EntityPlayer): Unit = WCTApi.instance.interact.openWirelessCraftingTerminalGui(player) def getBoosterItem = diff --git a/src/main/scala/extracells/integration/ae2fc/FluidCraft.java b/src/main/scala/extracells/integration/ae2fc/FluidCraft.java new file mode 100644 index 000000000..0850a9661 --- /dev/null +++ b/src/main/scala/extracells/integration/ae2fc/FluidCraft.java @@ -0,0 +1,87 @@ +package extracells.integration.ae2fc; + +import java.util.HashMap; +import java.util.Map; + +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +import com.glodblock.github.util.NameConst; + +import appeng.api.storage.data.IAEItemStack; +import appeng.util.item.AEItemStack; +import cpw.mods.fml.common.Optional; +import cpw.mods.fml.common.event.FMLModIdMappingEvent; +import cpw.mods.fml.common.registry.GameRegistry; +import extracells.registries.PartEnum; + +public final class FluidCraft { + + private final static Map REPLACER = new HashMap<>(16); + + @Optional.Method(modid = "ae2fc") + public static void onRemapEvent(FMLModIdMappingEvent event) { + REPLACER.put( + PartEnum.FLUIDEXPORT, + (short) Item.getIdFromItem(GameRegistry.findItem("ae2fc", NameConst.ITEM_PART_FLUID_EXPORT))); + REPLACER.put( + PartEnum.FLUIDIMPORT, + (short) Item.getIdFromItem(GameRegistry.findItem("ae2fc", NameConst.ITEM_PART_FLUID_IMPORT))); + REPLACER.put( + PartEnum.FLUIDSTORAGE, + (short) Item.getIdFromItem(GameRegistry.findItem("ae2fc", NameConst.ITEM_PART_FLUID_STORAGE_BUS))); + REPLACER.put( + PartEnum.FLUIDLEVELEMITTER, + (short) Item.getIdFromItem(GameRegistry.findItem("ae2fc", NameConst.ITEM_PART_FLUID_LEVEL_EMITTER))); + REPLACER.put( + PartEnum.FLUIDMONITOR, + (short) Item.getIdFromItem(GameRegistry.findItem("ae2fc", NameConst.ITEM_PART_FLUID_STORAGE_MONITOR))); + REPLACER.put( + PartEnum.FLUIDCONVERSIONMONITOR, + (short) Item + .getIdFromItem(GameRegistry.findItem("ae2fc", NameConst.ITEM_PART_FLUID_CONVERSION_MONITOR))); + REPLACER.put( + PartEnum.INTERFACE, + (short) Item.getIdFromItem(GameRegistry.findItem("ae2fc", NameConst.ITEM_PART_FLUID_INTERFACE))); + } + + public static void replace(NBTTagCompound def, PartEnum part) { + def.setShort("id", REPLACER.getOrDefault(part, (short) 0)); + def.setShort("Damage", (short) 0); + } + + @Optional.Method(modid = "ae2fc") + public static NBTTagCompound createFluidDisplay(String fluidName) { + NBTTagCompound fluidDisplay = new NBTTagCompound(); + Fluid fluid = FluidRegistry.getFluid(fluidName); + if (fluid != null) { + ItemStack fluidPacket = new ItemStack(GameRegistry.findItem("ae2fc", "fluid_packet"), 1, 0); + NBTTagCompound fluidPacketTag = new NBTTagCompound(); + // FluidStack + FluidStack fluidStack = new FluidStack(fluid, 1000); + NBTTagCompound fluidStackNbt = new NBTTagCompound(); + fluidStack.writeToNBT(fluidStackNbt); + fluidPacketTag.setTag("FluidStack", fluidStackNbt); + // FluidPacket + fluidPacketTag.setBoolean("DisplayOnly", true); + fluidPacket.setTagCompound(fluidPacketTag); + // Final Item + IAEItemStack aeStack = AEItemStack.create(fluidPacket); + aeStack.writeToNBT(fluidDisplay); + } + return fluidDisplay; + } + + public static NBTTagCompound createFluidNBT(String fluidName, long amount) { + NBTTagCompound fluid = new NBTTagCompound(); + fluid.setString("FluidName", fluidName); + fluid.setBoolean("Craft", false); + fluid.setLong("Req", 0); + fluid.setLong("Cnt", amount); + return fluid; + } +} diff --git a/src/main/scala/extracells/integration/igw/IGW.scala b/src/main/scala/extracells/integration/igw/IGW.scala index 593f746a4..942fc6a83 100644 --- a/src/main/scala/extracells/integration/igw/IGW.scala +++ b/src/main/scala/extracells/integration/igw/IGW.scala @@ -19,41 +19,64 @@ object IGW { } @Optional.Method(modid = "IGWMod") - def init{ - for(item <- ItemEnum.values()){ - if(item != ItemEnum.CRAFTINGPATTERN && item != ItemEnum.FLUIDITEM) { - if(item == ItemEnum.FLUIDPATTERN){ - WikiRegistry.registerBlockAndItemPageEntry(item.getSizedStack(1), item.getSizedStack(1).getUnlocalizedName.replace(".", "/")) - }else if (item == ItemEnum.STORAGECOMPONET || item == ItemEnum.STORAGECASING){ + def init { + for (item <- ItemEnum.values()) { + if (item != ItemEnum.CRAFTINGPATTERN && item != ItemEnum.FLUIDITEM) { + if (item == ItemEnum.FLUIDPATTERN) { + WikiRegistry.registerBlockAndItemPageEntry( + item.getSizedStack(1), + item.getSizedStack(1).getUnlocalizedName.replace(".", "/") + ) + } else if ( + item == ItemEnum.STORAGECOMPONENT || item == ItemEnum.STORAGECASING + ) { val list = new util.ArrayList[java.lang.Object] item.getItem.getSubItems(item.getItem, Extracells.ModTab, list) for (sub <- list) { val stack = sub.asInstanceOf[ItemStack] - WikiRegistry.registerBlockAndItemPageEntry(stack, "extracells/item/crafting") + WikiRegistry.registerBlockAndItemPageEntry( + stack, + "extracells/item/crafting" + ) } - }else{ + } else { val list = new util.ArrayList[java.lang.Object] item.getItem.getSubItems(item.getItem, Extracells.ModTab, list) for (sub <- list) { val stack = sub.asInstanceOf[ItemStack] - WikiRegistry.registerBlockAndItemPageEntry(stack, stack.getUnlocalizedName.replace(".", "/")) + WikiRegistry.registerBlockAndItemPageEntry( + stack, + stack.getUnlocalizedName.replace(".", "/") + ) } } } } - if(Integration.Mods.OPENCOMPUTERS.isEnabled){ + if (Integration.Mods.OPENCOMPUTERS.isEnabled) { val stack = GameRegistry.findItemStack("extracells", "oc.upgrade", 1) - WikiRegistry.registerBlockAndItemPageEntry(stack.getItem, stack.getUnlocalizedName.replace(".", "/")) + WikiRegistry.registerBlockAndItemPageEntry( + stack.getItem, + stack.getUnlocalizedName.replace(".", "/") + ) } - for(block <- BlockEnum.values()){ + for (block <- BlockEnum.values()) { val list = new util.ArrayList[java.lang.Object] - Item.getItemFromBlock(block.getBlock).getSubItems(Item.getItemFromBlock(block.getBlock), Extracells.ModTab, list) - for(sub <- list){ + Item + .getItemFromBlock(block.getBlock) + .getSubItems( + Item.getItemFromBlock(block.getBlock), + Extracells.ModTab, + list + ) + for (sub <- list) { val stack = sub.asInstanceOf[ItemStack] - WikiRegistry.registerBlockAndItemPageEntry(stack, stack.getUnlocalizedName.replace(".", "/").replace("tile/", "")) + WikiRegistry.registerBlockAndItemPageEntry( + stack, + stack.getUnlocalizedName.replace(".", "/").replace("tile/", "") + ) } } } diff --git a/src/main/scala/extracells/integration/igw/IGWSupportNotifier.scala b/src/main/scala/extracells/integration/igw/IGWSupportNotifier.scala index 9e14e43f7..233118e3f 100644 --- a/src/main/scala/extracells/integration/igw/IGWSupportNotifier.scala +++ b/src/main/scala/extracells/integration/igw/IGWSupportNotifier.scala @@ -12,31 +12,50 @@ import cpw.mods.fml.common.{FMLCommonHandler, Loader, ModContainer} import cpw.mods.fml.relauncher.Side import net.minecraft.client.Minecraft import net.minecraft.command.{CommandBase, ICommandSender} -import net.minecraft.util.{ChatComponentText, EnumChatFormatting, IChatComponent} +import net.minecraft.util.{ + ChatComponentText, + EnumChatFormatting, + IChatComponent +} import net.minecraftforge.client.ClientCommandHandler import net.minecraftforge.common.config.Configuration import org.apache.commons.io.FileUtils -/** - * This class is meant to be copied to your own mod which implements IGW-Mod. When properly implemented by instantiating a new instance somewhere in your mod - * loading stage, this will notify the player when it doesn't have IGW in the instance. It also needs to have the config option enabled to - * notify the player. This config option will be generated in its own config file. - * @author MineMaarten https://github.com/MineMaarten/IGW-mod - */ +/** This class is meant to be copied to your own mod which implements IGW-Mod. + * When properly implemented by instantiating a new instance somewhere in your + * mod loading stage, this will notify the player when it doesn't have IGW in + * the instance. It also needs to have the config option enabled to notify the + * player. This config option will be generated in its own config file. + * @author + * MineMaarten https://github.com/MineMaarten/IGW-mod + */ object IGWSupportNotifier { - private val LATEST_DL_URL: String = "http://minecraft.curseforge.com/mc-mods/223815-in-game-wiki-mod/files/latest" + private val LATEST_DL_URL: String = + "http://minecraft.curseforge.com/mc-mods/223815-in-game-wiki-mod/files/latest" private var supportingMod: String = null - /** - * Needs to be instantiated somewhere in your mod's loading stage. - */ + /** Needs to be instantiated somewhere in your mod's loading stage. + */ - if (FMLCommonHandler.instance.getSide == Side.CLIENT && !Loader.isModLoaded("IGWMod")) { + if ( + FMLCommonHandler.instance.getSide == Side.CLIENT && !Loader.isModLoaded( + "IGWMod" + ) + ) { val dir: File = new File(".", "config") val config: Configuration = new Configuration(new File(dir, "IGWMod.cfg")) config.load - if (config.get(Configuration.CATEGORY_GENERAL, "enable_missing_notification", true, "When enabled, this will notify players when IGW-Mod is not installed even though mods add support.").getBoolean) { + if ( + config + .get( + Configuration.CATEGORY_GENERAL, + "enable_missing_notification", + true, + "When enabled, this will notify players when IGW-Mod is not installed even though mods add support." + ) + .getBoolean + ) { val mc: ModContainer = Loader.instance.activeModContainer val modid: String = mc.getModId val loadedMods: List[ModContainer] = Loader.instance.getActiveModList @@ -52,11 +71,16 @@ object IGWSupportNotifier { config.save } - @SubscribeEvent def onPlayerJoin(event: TickEvent.PlayerTickEvent) { - if (event.player.worldObj.isRemote && event.player == FMLClientHandler.instance.getClientPlayerEntity) { - event.player.addChatComponentMessage(IChatComponent.Serializer.func_150699_a("[\"" + EnumChatFormatting.GOLD + "The mod " + supportingMod + " is supporting In-Game Wiki mod. " + EnumChatFormatting.GOLD + "However, In-Game Wiki isn't installed! " + "[\"," + "{\"text\":\"Download Latest\",\"color\":\"green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/igwmod_download\"}}," + "\"]\"]")) + if ( + event.player.worldObj.isRemote && event.player == FMLClientHandler.instance.getClientPlayerEntity + ) { + event.player.addChatComponentMessage( + IChatComponent.Serializer.func_150699_a( + "[\"" + EnumChatFormatting.GOLD + "The mod " + supportingMod + " is supporting In-Game Wiki mod. " + EnumChatFormatting.GOLD + "However, In-Game Wiki isn't installed! " + "[\"," + "{\"text\":\"Download Latest\",\"color\":\"green\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/igwmod_download\"}}," + "\"]\"]" + ) + ) FMLCommonHandler.instance.bus.unregister(this) } } @@ -74,7 +98,10 @@ object IGWSupportNotifier { return getCommandName } - def processCommand(p_71515_1_ : ICommandSender, p_71515_2_ : Array[String]) { + def processCommand( + p_71515_1_ : ICommandSender, + p_71515_2_ : Array[String] + ) { new ThreadDownloadIGW } @@ -82,13 +109,15 @@ object IGWSupportNotifier { private class ThreadDownloadIGW extends Thread { - setName("IGW-Mod Download Thread") - start - + setName("IGW-Mod Download Thread") + start override def run { try { - if (Minecraft.getMinecraft.thePlayer != null) Minecraft.getMinecraft.thePlayer.addChatMessage(new ChatComponentText("Downloading IGW-Mod...")) + if (Minecraft.getMinecraft.thePlayer != null) + Minecraft.getMinecraft.thePlayer.addChatMessage( + new ChatComponentText("Downloading IGW-Mod...") + ) val url: URL = new URL(IGWSupportNotifier.LATEST_DL_URL) val connection: URLConnection = url.openConnection connection.connect @@ -96,18 +125,26 @@ object IGWSupportNotifier { val dir: File = new File(".", "mods") val f: File = new File(dir, fileName) FileUtils.copyURLToFile(url, f) - if (Minecraft.getMinecraft.thePlayer != null) Minecraft.getMinecraft.thePlayer.addChatMessage(new ChatComponentText(EnumChatFormatting.GREEN + "Successfully downloaded. Restart Minecraft to apply.")) + if (Minecraft.getMinecraft.thePlayer != null) + Minecraft.getMinecraft.thePlayer.addChatMessage( + new ChatComponentText( + EnumChatFormatting.GREEN + "Successfully downloaded. Restart Minecraft to apply." + ) + ) Desktop.getDesktop.open(dir) finalize - } - catch { + } catch { case e: Throwable => { e.printStackTrace - if (Minecraft.getMinecraft.thePlayer != null) Minecraft.getMinecraft.thePlayer.addChatComponentMessage(new ChatComponentText(EnumChatFormatting.RED + "Failed to download")) + if (Minecraft.getMinecraft.thePlayer != null) + Minecraft.getMinecraft.thePlayer.addChatComponentMessage( + new ChatComponentText( + EnumChatFormatting.RED + "Failed to download" + ) + ) try { finalize - } - catch { + } catch { case e1: Throwable => { e1.printStackTrace } diff --git a/src/main/scala/extracells/integration/mekanism/HandlerMekanismGasTank.scala b/src/main/scala/extracells/integration/mekanism/HandlerMekanismGasTank.scala index 05041b126..ae6fbeab8 100644 --- a/src/main/scala/extracells/integration/mekanism/HandlerMekanismGasTank.scala +++ b/src/main/scala/extracells/integration/mekanism/HandlerMekanismGasTank.scala @@ -10,27 +10,34 @@ import mekanism.api.gas.GasTank import net.minecraft.tileentity.TileEntity import net.minecraftforge.common.util.ForgeDirection - -object HandlerMekanismGasTank extends IExternalGasStorageHandler{ +object HandlerMekanismGasTank extends IExternalGasStorageHandler { val clazz = Class.forName("mekanism.common.tile.TileEntityGasTank") - override def canHandle(tile: TileEntity, d: ForgeDirection, mySrc: BaseActionSource): Boolean = { + override def canHandle( + tile: TileEntity, + d: ForgeDirection, + mySrc: BaseActionSource + ): Boolean = { tile != null && tile.getClass == clazz } - override def getInventory(tile: TileEntity, d: ForgeDirection, src: BaseActionSource): IMEInventory[IAEFluidStack] = { + override def getInventory( + tile: TileEntity, + d: ForgeDirection, + src: BaseActionSource + ): IMEInventory[IAEFluidStack] = { val tank = getGasTank(tile) - if(tank == null) + if (tank == null) null else new Inventory(tank) } def getGasTank(tile: TileEntity): GasTank = { - try{ + try { val tank = clazz.getField("gasTank") - if(tank != null) + if (tank != null) tank.get(tile).asInstanceOf[GasTank] else null @@ -39,14 +46,18 @@ object HandlerMekanismGasTank extends IExternalGasStorageHandler{ } } - class Inventory(tank: GasTank) extends IMEInventory[IAEFluidStack]{ - override def injectItems(stackType: IAEFluidStack, actionable: Actionable, baseActionSource: BaseActionSource): IAEFluidStack = { + class Inventory(tank: GasTank) extends IMEInventory[IAEFluidStack] { + override def injectItems( + stackType: IAEFluidStack, + actionable: Actionable, + baseActionSource: BaseActionSource + ): IAEFluidStack = { val gasStack = GasUtil.getGasStack(stackType) - if(gasStack == null) + if (gasStack == null) return stackType - if(tank.canReceive(gasStack.getGas)){ + if (tank.canReceive(gasStack.getGas)) { val accepted = tank.receive(gasStack, actionable == Actionable.MODULATE) - if(accepted == stackType.getStackSize) + if (accepted == stackType.getStackSize) return null val returnStack = stackType.copy() returnStack.setStackSize(stackType.getStackSize - accepted) @@ -56,18 +67,26 @@ object HandlerMekanismGasTank extends IExternalGasStorageHandler{ override def getChannel: StorageChannel = StorageChannel.FLUIDS - override def extractItems(stackType: IAEFluidStack, actionable: Actionable, baseActionSource: BaseActionSource): IAEFluidStack = { + override def extractItems( + stackType: IAEFluidStack, + actionable: Actionable, + baseActionSource: BaseActionSource + ): IAEFluidStack = { val gasStack = GasUtil.getGasStack(stackType) - if(gasStack == null) + if (gasStack == null) return null - if(tank.canDraw(gasStack.getGas)){ - val drawed = tank.draw(gasStack.amount, actionable == Actionable.MODULATE) + if (tank.canDraw(gasStack.getGas)) { + val drawed = + tank.draw(gasStack.amount, actionable == Actionable.MODULATE) return GasUtil.createAEFluidStack(drawed) } null } - override def getAvailableItems(itemList: IItemList[IAEFluidStack]): IItemList[IAEFluidStack] = { + override def getAvailableItems( + itemList: IItemList[IAEFluidStack], + iteration: Int + ): IItemList[IAEFluidStack] = { val gas = tank.getGas if (gas != null) itemList.add(GasUtil.createAEFluidStack(tank.getGas)) diff --git a/src/main/scala/extracells/integration/mekanism/Mekanism.scala b/src/main/scala/extracells/integration/mekanism/Mekanism.scala index 386d5c5fc..648e25982 100644 --- a/src/main/scala/extracells/integration/mekanism/Mekanism.scala +++ b/src/main/scala/extracells/integration/mekanism/Mekanism.scala @@ -3,11 +3,10 @@ package extracells.integration.mekanism import extracells.api.ECApi import extracells.integration.Integration.Mods - object Mekanism { - def init: Unit ={ - if(Mods.MEKANISMGAS.isEnabled){ + def init: Unit = { + if (Mods.MEKANISMGAS.isEnabled) { ECApi.instance().addExternalStorageInterface(HandlerMekanismGasTank) } } diff --git a/src/main/scala/extracells/integration/mekanism/gas/GasCellHandler.java b/src/main/scala/extracells/integration/mekanism/gas/GasCellHandler.java index eadb5197e..4305389e1 100644 --- a/src/main/scala/extracells/integration/mekanism/gas/GasCellHandler.java +++ b/src/main/scala/extracells/integration/mekanism/gas/GasCellHandler.java @@ -1,5 +1,10 @@ package extracells.integration.mekanism.gas; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.implementations.tiles.IMEChest; import appeng.api.networking.security.PlayerSource; @@ -9,79 +14,83 @@ import extracells.inventory.HandlerItemStorageGas; import extracells.network.GuiHandler; import extracells.render.TextureManager; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraftforge.common.util.ForgeDirection; public class GasCellHandler implements ICellHandler { - @Override - public double cellIdleDrain(ItemStack is, IMEInventory handler) { - return 0; - } - - @Override - public IMEInventoryHandler getCellInventory(ItemStack itemStack, ISaveProvider saveProvider, StorageChannel channel) { - if (channel == StorageChannel.ITEMS || !(itemStack.getItem() instanceof IGasStorageCell)) { - return null; - } - return new HandlerItemStorageGas(itemStack, saveProvider, ((IGasStorageCell) itemStack.getItem()).getFilter(itemStack)); - } + @Override + public double cellIdleDrain(ItemStack is, IMEInventory handler) { + return 0; + } - public IMEInventoryHandler getCellInventoryPlayer(ItemStack itemStack, EntityPlayer player) { - return new HandlerItemPlayerStorageGas(itemStack, null, ((IGasStorageCell) itemStack.getItem()).getFilter(itemStack), player); - } + @Override + public IMEInventoryHandler getCellInventory(ItemStack itemStack, ISaveProvider saveProvider, + StorageChannel channel) { + if (channel == StorageChannel.ITEMS || !(itemStack.getItem() instanceof IGasStorageCell)) { + return null; + } + return new HandlerItemStorageGas( + itemStack, + saveProvider, + ((IGasStorageCell) itemStack.getItem()).getFilter(itemStack)); + } - @Override - public int getStatusForCell(ItemStack is, IMEInventory handler) { - if (handler == null) { - return 0; - } + public IMEInventoryHandler getCellInventoryPlayer(ItemStack itemStack, EntityPlayer player) { + return new HandlerItemPlayerStorageGas( + itemStack, + null, + ((IGasStorageCell) itemStack.getItem()).getFilter(itemStack), + player); + } - HandlerItemStorageGas inventory = (HandlerItemStorageGas) handler; - if (inventory.freeBytes() == 0) { - return 3; - } - if (inventory.isFormatted() || inventory.usedTypes() == inventory.totalTypes()) { - return 2; - } + @Override + public int getStatusForCell(ItemStack is, IMEInventory handler) { + if (handler == null) { + return 0; + } - return 1; - } + HandlerItemStorageGas inventory = (HandlerItemStorageGas) handler; + if (inventory.freeBytes() == 0) { + return 3; + } + if (inventory.isFormatted() || inventory.usedTypes() == inventory.totalTypes()) { + return 2; + } - @Override - public IIcon getTopTexture_Dark() { - return TextureManager.TERMINAL_FRONT.getTextures()[0]; - } + return 1; + } - @Override - public IIcon getTopTexture_Light() { - return TextureManager.TERMINAL_FRONT.getTextures()[2]; - } + @Override + public IIcon getTopTexture_Dark() { + return TextureManager.TERMINAL_FRONT.getTextures()[0]; + } - @Override - public IIcon getTopTexture_Medium() { - return TextureManager.TERMINAL_FRONT.getTextures()[1]; - } + @Override + public IIcon getTopTexture_Light() { + return TextureManager.TERMINAL_FRONT.getTextures()[2]; + } - @Override - public boolean isCell(ItemStack is) { - return is != null && is.getItem() != null && is.getItem() instanceof IGasStorageCell; - } + @Override + public IIcon getTopTexture_Medium() { + return TextureManager.TERMINAL_FRONT.getTextures()[1]; + } - @Override - public void openChestGui(EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan) { - if (chan != StorageChannel.FLUIDS) { - return; - } - IStorageMonitorable monitorable = null; - if (chest != null) { - monitorable = ((IMEChest) chest).getMonitorable(ForgeDirection.UNKNOWN, new PlayerSource(player, chest)); - } - if (monitorable != null) { - GuiHandler.launchGui(GuiHandler.getGuiId(4), player, new Object[]{monitorable.getFluidInventory()}); - } - } + @Override + public boolean isCell(ItemStack is) { + return is != null && is.getItem() != null && is.getItem() instanceof IGasStorageCell; + } + @Override + public void openChestGui(EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, + IMEInventoryHandler inv, ItemStack is, StorageChannel chan) { + if (chan != StorageChannel.FLUIDS) { + return; + } + IStorageMonitorable monitorable = null; + if (chest != null) { + monitorable = ((IMEChest) chest).getMonitorable(ForgeDirection.UNKNOWN, new PlayerSource(player, chest)); + } + if (monitorable != null) { + GuiHandler.launchGui(GuiHandler.getGuiId(4), player, new Object[] { monitorable.getFluidInventory() }); + } + } } diff --git a/src/main/scala/extracells/integration/mekanism/gas/GasInterfaceBase.scala b/src/main/scala/extracells/integration/mekanism/gas/GasInterfaceBase.scala index cc2338048..efe123951 100644 --- a/src/main/scala/extracells/integration/mekanism/gas/GasInterfaceBase.scala +++ b/src/main/scala/extracells/integration/mekanism/gas/GasInterfaceBase.scala @@ -11,11 +11,26 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraftforge.common.util.ForgeDirection import net.minecraftforge.fluids.Fluid -@InterfaceList(Array( - new Interface(iface = "mekanism.api.gas.IGasHandler", modid = "MekanismAPI|gas", striprefs = true), - new Interface(iface = "mekanism.api.gas.ITubeConnection", modid = "MekanismAPI|gas", striprefs = true) -)) -trait GasInterfaceBase extends IGasHandler with ITubeConnection with IPowerChannelState with IActionHost with IFluidSlotPartOrBlock{ +@InterfaceList( + Array( + new Interface( + iface = "mekanism.api.gas.IGasHandler", + modid = "MekanismAPI|gas", + striprefs = true + ), + new Interface( + iface = "mekanism.api.gas.ITubeConnection", + modid = "MekanismAPI|gas", + striprefs = true + ) + ) +) +trait GasInterfaceBase + extends IGasHandler + with ITubeConnection + with IPowerChannelState + with IActionHost + with IFluidSlotPartOrBlock { val isMekanismLoaded = MEKANISM.isEnabled @@ -23,30 +38,42 @@ trait GasInterfaceBase extends IGasHandler with ITubeConnection with IPowerChann def getGasTank(side: ForgeDirection): GasTank @Method(modid = "MekanismAPI|gas") - override def receiveGas(side: ForgeDirection, stack: GasStack, doTransfer: Boolean): Int = getGasTank(side).receive(stack, doTransfer) + override def receiveGas( + side: ForgeDirection, + stack: GasStack, + doTransfer: Boolean + ): Int = getGasTank(side).receive(stack, doTransfer) @Method(modid = "MekanismAPI|gas") - override def drawGas(side: ForgeDirection, amount: Int, doTransfer: Boolean): GasStack = getGasTank(side).draw(amount, doTransfer) + override def drawGas( + side: ForgeDirection, + amount: Int, + doTransfer: Boolean + ): GasStack = getGasTank(side).draw(amount, doTransfer) @Method(modid = "MekanismAPI|gas") - override def drawGas(side: ForgeDirection, amount: Int): GasStack = drawGas(side, amount, true) + override def drawGas(side: ForgeDirection, amount: Int): GasStack = + drawGas(side, amount, true) @Method(modid = "MekanismAPI|gas") - override def canDrawGas(side: ForgeDirection, gas: Gas): Boolean = getGasTank(side).canDraw(gas) + override def canDrawGas(side: ForgeDirection, gas: Gas): Boolean = + getGasTank(side).canDraw(gas) @Method(modid = "MekanismAPI|gas") - override def receiveGas(side: ForgeDirection, stack: GasStack): Int = receiveGas(side, stack, true) + override def receiveGas(side: ForgeDirection, stack: GasStack): Int = + receiveGas(side, stack, true) @Method(modid = "MekanismAPI|gas") - override def canReceiveGas(side: ForgeDirection, gas: Gas): Boolean = (!hasFilter(side)) && getGasTank(side).canReceive(gas) + override def canReceiveGas(side: ForgeDirection, gas: Gas): Boolean = + (!hasFilter(side)) && getGasTank(side).canReceive(gas) @Method(modid = "MekanismAPI|gas") override def canTubeConnect(side: ForgeDirection): Boolean = isMekanismLoaded def getFilter(side: ForgeDirection): Int - def setFilter(side: ForgeDirection, fluid: Fluid): Unit ={ - if(fluid == null) + def setFilter(side: ForgeDirection, fluid: Fluid): Unit = { + if (fluid == null) setFilter(side, -1) else setFilter(side, fluid.getID) @@ -57,21 +84,25 @@ trait GasInterfaceBase extends IGasHandler with ITubeConnection with IPowerChann def hasFilter(side: ForgeDirection) = getFilter(side) != -1 @Method(modid = "MekanismAPI|gas") - def exportGas(side: ForgeDirection, gas: GasStack, pos: DimensionalCoord): Int = { + def exportGas( + side: ForgeDirection, + gas: GasStack, + pos: DimensionalCoord + ): Int = { val tank = getGasTank(side) val x = pos.x + side.offsetX val y = pos.y + side.offsetY val z = pos.z + side.offsetZ val world = pos.getWorld - if(world == null) + if (world == null) return 0 val tile = world.getTileEntity(x, y, z) - if(tile == null) + if (tile == null) return 0 - if(!tile.isInstanceOf[IGasHandler]) + if (!tile.isInstanceOf[IGasHandler]) return 0 val gasHandler = tile.asInstanceOf[IGasHandler] - if(gasHandler.canReceiveGas(side.getOpposite, gas.getGas)) + if (gasHandler.canReceiveGas(side.getOpposite, gas.getGas)) gasHandler.receiveGas(side.getOpposite, gas, true) else 0 diff --git a/src/main/scala/extracells/integration/mekanism/gas/LayerGasHandler.java b/src/main/scala/extracells/integration/mekanism/gas/LayerGasHandler.java index ee2f82fca..72201c94e 100644 --- a/src/main/scala/extracells/integration/mekanism/gas/LayerGasHandler.java +++ b/src/main/scala/extracells/integration/mekanism/gas/LayerGasHandler.java @@ -1,18 +1,19 @@ package extracells.integration.mekanism.gas; +import net.minecraftforge.common.util.ForgeDirection; import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import mekanism.api.gas.Gas; import mekanism.api.gas.GasStack; import mekanism.api.gas.IGasHandler; -import net.minecraftforge.common.util.ForgeDirection; -public class LayerGasHandler extends LayerBase implements IGasHandler{ +public class LayerGasHandler extends LayerBase implements IGasHandler { + @Override public int receiveGas(ForgeDirection side, GasStack stack, boolean doTransfer) { IPart part = this.getPart(side); - if(part instanceof IGasHandler){ + if (part instanceof IGasHandler) { return ((IGasHandler) part).receiveGas(side, stack, doTransfer); } return 0; @@ -21,7 +22,7 @@ public int receiveGas(ForgeDirection side, GasStack stack, boolean doTransfer) { @Override public int receiveGas(ForgeDirection side, GasStack stack) { IPart part = this.getPart(side); - if(part instanceof IGasHandler){ + if (part instanceof IGasHandler) { return ((IGasHandler) part).receiveGas(side, stack, true); } return 0; @@ -30,7 +31,7 @@ public int receiveGas(ForgeDirection side, GasStack stack) { @Override public GasStack drawGas(ForgeDirection side, int amount, boolean doTransfer) { IPart part = this.getPart(side); - if(part instanceof IGasHandler){ + if (part instanceof IGasHandler) { return ((IGasHandler) part).drawGas(side, amount, doTransfer); } return null; @@ -39,7 +40,7 @@ public GasStack drawGas(ForgeDirection side, int amount, boolean doTransfer) { @Override public GasStack drawGas(ForgeDirection side, int amount) { IPart part = this.getPart(side); - if(part instanceof IGasHandler){ + if (part instanceof IGasHandler) { return ((IGasHandler) part).drawGas(side, amount, true); } return null; @@ -48,7 +49,7 @@ public GasStack drawGas(ForgeDirection side, int amount) { @Override public boolean canReceiveGas(ForgeDirection side, Gas type) { IPart part = this.getPart(side); - if(part instanceof IGasHandler){ + if (part instanceof IGasHandler) { return ((IGasHandler) part).canReceiveGas(side, type); } return false; @@ -57,7 +58,7 @@ public boolean canReceiveGas(ForgeDirection side, Gas type) { @Override public boolean canDrawGas(ForgeDirection side, Gas type) { IPart part = this.getPart(side); - if(part instanceof IGasHandler){ + if (part instanceof IGasHandler) { return ((IGasHandler) part).canDrawGas(side, type); } return false; diff --git a/src/main/scala/extracells/integration/mekanism/gas/LayerTubeConnection.java b/src/main/scala/extracells/integration/mekanism/gas/LayerTubeConnection.java index 9d2371df9..8ed868ad2 100644 --- a/src/main/scala/extracells/integration/mekanism/gas/LayerTubeConnection.java +++ b/src/main/scala/extracells/integration/mekanism/gas/LayerTubeConnection.java @@ -1,17 +1,18 @@ package extracells.integration.mekanism.gas; +import net.minecraftforge.common.util.ForgeDirection; import appeng.api.parts.IPart; import appeng.api.parts.LayerBase; import mekanism.api.gas.IGasHandler; import mekanism.api.gas.ITubeConnection; -import net.minecraftforge.common.util.ForgeDirection; -public class LayerTubeConnection extends LayerBase implements ITubeConnection{ +public class LayerTubeConnection extends LayerBase implements ITubeConnection { + @Override public boolean canTubeConnect(ForgeDirection side) { IPart part = this.getPart(side); - if(part instanceof ITubeConnection) { + if (part instanceof ITubeConnection) { return ((ITubeConnection) part).canTubeConnect(side); } return part instanceof IGasHandler; diff --git a/src/main/scala/extracells/integration/mekanism/gas/MekanismGas.scala b/src/main/scala/extracells/integration/mekanism/gas/MekanismGas.scala index 7a9f51595..81ee48303 100644 --- a/src/main/scala/extracells/integration/mekanism/gas/MekanismGas.scala +++ b/src/main/scala/extracells/integration/mekanism/gas/MekanismGas.scala @@ -7,35 +7,43 @@ import net.minecraftforge.fluids.{Fluid, FluidRegistry, FluidStack} import scala.collection.JavaConversions._ - object MekanismGas { - private var fluidGas:Map[Gas, Fluid] = Map() + private var fluidGas: Map[Gas, Fluid] = Map() def init { val api = AEApi.instance.partHelper - api.registerNewLayer(classOf[LayerGasHandler].getName, classOf[IGasHandler].getName) - api.registerNewLayer(classOf[LayerTubeConnection].getName, classOf[ITubeConnection].getName) + api.registerNewLayer( + classOf[LayerGasHandler].getName, + classOf[IGasHandler].getName + ) + api.registerNewLayer( + classOf[LayerTubeConnection].getName, + classOf[ITubeConnection].getName + ) AEApi.instance().registries().cell().addCellHandler(new GasCellHandler()) } - def getFluidGasMap = mapAsJavaMap(fluidGas) + def getFluidGasMap = mapAsJavaMap(fluidGas) - def postInit{ + def postInit { val it = GasRegistry.getRegisteredGasses.iterator - while(it.hasNext){ + while (it.hasNext) { val g = it.next val fluid = new GasFluid(g) - if((!FluidRegistry.isFluidRegistered(fluid)) && FluidRegistry.registerFluid(fluid)) + if ( + (!FluidRegistry.isFluidRegistered(fluid)) && FluidRegistry + .registerFluid(fluid) + ) fluidGas += (g -> fluid) } ECApi.instance.addFluidToShowBlacklist(classOf[GasFluid]) ECApi.instance.addFluidToStorageBlacklist(classOf[GasFluid]) } - class GasFluid(gas: Gas) extends Fluid("ec.internal." + gas.getName){ + class GasFluid(gas: Gas) extends Fluid("ec.internal." + gas.getName) { - override def getLocalizedName (stack: FluidStack) = gas.getLocalizedName + override def getLocalizedName(stack: FluidStack) = gas.getLocalizedName override def getIcon = gas.getIcon diff --git a/src/main/scala/extracells/integration/nei/Nei.scala b/src/main/scala/extracells/integration/nei/Nei.scala index 28af005f0..c44ab42a5 100644 --- a/src/main/scala/extracells/integration/nei/Nei.scala +++ b/src/main/scala/extracells/integration/nei/Nei.scala @@ -7,7 +7,6 @@ import extracells.Extracells import extracells.registries.{BlockEnum, ItemEnum} import net.minecraft.item.{Item, ItemStack} - object Nei { def hideItems = { @@ -19,7 +18,7 @@ object Nei { val list = new util.ArrayList[ItemStack] i.getSubItems(i, Extracells.ModTab, list) val it = list.iterator - while(it.hasNext){ + while (it.hasNext) { API.hideItem(it.next) } } @@ -31,7 +30,7 @@ object Nei { val list = new util.ArrayList[ItemStack] b.getSubBlocks(Item.getItemFromBlock(b), Extracells.ModTab, list) val it = list.iterator - while(it.hasNext){ + while (it.hasNext) { API.hideItem(it.next) } } @@ -40,7 +39,7 @@ object Nei { def init = { hideItems - if(Extracells.proxy.isClient){ + if (Extracells.proxy.isClient) { val handler = new UniversalTerminalRecipe API.registerUsageHandler(handler) API.registerRecipeHandler(handler) diff --git a/src/main/scala/extracells/integration/nei/UniversalTerminalRecipe.scala b/src/main/scala/extracells/integration/nei/UniversalTerminalRecipe.scala index 3db283ab4..5c85468ff 100644 --- a/src/main/scala/extracells/integration/nei/UniversalTerminalRecipe.scala +++ b/src/main/scala/extracells/integration/nei/UniversalTerminalRecipe.scala @@ -3,7 +3,12 @@ package extracells.integration.nei import java.awt.Rectangle import java.util -import codechicken.nei.api.{DefaultOverlayRenderer, IOverlayHandler, IRecipeOverlayRenderer, IStackPositioner} +import codechicken.nei.api.{ + DefaultOverlayRenderer, + IOverlayHandler, + IRecipeOverlayRenderer, + IStackPositioner +} import codechicken.nei.recipe.{RecipeInfo, TemplateRecipeHandler} import codechicken.nei.{NEIClientUtils, PositionedStack} import extracells.registries.ItemEnum @@ -14,7 +19,12 @@ import net.minecraft.item.ItemStack class UniversalTerminalRecipe extends TemplateRecipeHandler { override def loadTransferRects { - this.transferRects.add(new TemplateRecipeHandler.RecipeTransferRect(new Rectangle(84, 23, 24, 18), "crafting")) + this.transferRects.add( + new TemplateRecipeHandler.RecipeTransferRect( + new Rectangle(84, 23, 24, 18), + "crafting" + ) + ) } override def loadCraftingRecipes(outputId: String, results: AnyRef*) { @@ -25,13 +35,15 @@ class UniversalTerminalRecipe extends TemplateRecipeHandler { val cachedRecipe2 = new CachedShapelessRecipe(false) cachedRecipe2.computeVisuals arecipes.add(cachedRecipe2) - }else{ - super.loadCraftingRecipes(outputId, results:_*) + } else { + super.loadCraftingRecipes(outputId, results: _*) } } override def loadCraftingRecipes(result: ItemStack) { - if(result != null && result.getItem == ItemEnum.UNIVERSALTERMINAL.getItem){ + if ( + result != null && result.getItem == ItemEnum.UNIVERSALTERMINAL.getItem + ) { val cachedRecipe = new CachedShapelessRecipe(true) cachedRecipe.computeVisuals arecipes.add(cachedRecipe) @@ -42,54 +54,62 @@ class UniversalTerminalRecipe extends TemplateRecipeHandler { } override def loadUsageRecipes(ingredient: ItemStack) { - if(ingredient == null || ingredient.getItem == null) + if (ingredient == null || ingredient.getItem == null) return - if(UniversalTerminal.isTerminal(ingredient)){ + if (UniversalTerminal.isTerminal(ingredient)) { val cachedRecipe = new CachedShapelessRecipe(true) cachedRecipe.computeVisuals arecipes.add(cachedRecipe) val cachedRecipe2 = new CachedShapelessRecipe(false) cachedRecipe2.computeVisuals arecipes.add(cachedRecipe2) - }else if(UniversalTerminal.isWirelessTerminal(ingredient)){ + } else if (UniversalTerminal.isWirelessTerminal(ingredient)) { val cachedRecipe = new CachedShapelessRecipe(false) cachedRecipe.computeVisuals arecipes.add(cachedRecipe) - }else if(ingredient.getItem == ItemEnum.UNIVERSALTERMINAL.getItem){ + } else if (ingredient.getItem == ItemEnum.UNIVERSALTERMINAL.getItem) { val cachedRecipe = new CachedShapelessRecipe(true) cachedRecipe.computeVisuals arecipes.add(cachedRecipe) } - } def getGuiTexture: String = "textures/gui/container/crafting_table.png" - override def getOverlayIdentifier: String = "crafting" - override def getGuiClass: Class[_ <: GuiContainer] = classOf[GuiCrafting] - - override def hasOverlay(gui: GuiContainer, container: Container, recipe: Int): Boolean = - (super.hasOverlay(gui, container, recipe)) || ((this.isRecipe2x2(recipe)) && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))) - - - override def getOverlayRenderer(gui: GuiContainer, recipe: Int): IRecipeOverlayRenderer = { + override def hasOverlay( + gui: GuiContainer, + container: Container, + recipe: Int + ): Boolean = + (super.hasOverlay(gui, container, recipe)) || ((this.isRecipe2x2( + recipe + )) && (RecipeInfo.hasDefaultOverlay(gui, "crafting2x2"))) + + override def getOverlayRenderer( + gui: GuiContainer, + recipe: Int + ): IRecipeOverlayRenderer = { val renderer: IRecipeOverlayRenderer = super.getOverlayRenderer(gui, recipe) if (renderer != null) { return renderer } - val positioner: IStackPositioner = RecipeInfo.getStackPositioner(gui, "crafting2x2") + val positioner: IStackPositioner = + RecipeInfo.getStackPositioner(gui, "crafting2x2") if (positioner == null) { return null } new DefaultOverlayRenderer(this.getIngredientStacks(recipe), positioner) } - override def getOverlayHandler(gui: GuiContainer, recipe: Int): IOverlayHandler = { + override def getOverlayHandler( + gui: GuiContainer, + recipe: Int + ): IOverlayHandler = { val handler: IOverlayHandler = super.getOverlayHandler(gui, recipe) if (handler != null) { return handler @@ -109,31 +129,43 @@ class UniversalTerminalRecipe extends TemplateRecipeHandler { def getRecipeName: String = NEIClientUtils.translate("recipe.shapeless") - - private class CachedShapelessRecipe (isUniversal: Boolean) extends CachedRecipe { + private class CachedShapelessRecipe(isUniversal: Boolean) + extends CachedRecipe { private val ingredients = new util.ArrayList[PositionedStack] - private val result: PositionedStack = new PositionedStack(ItemEnum.UNIVERSALTERMINAL.getDamagedStack(0), 119, 24) + private val result: PositionedStack = new PositionedStack( + ItemEnum.UNIVERSALTERMINAL.getDamagedStack(0), + 119, + 24 + ) setIngredients - def getResult: PositionedStack = this.result override def getIngredients: util.List[PositionedStack] = { - this.getCycledIngredients(UniversalTerminalRecipe.this.cycleticks / 20, this.ingredients) + this.getCycledIngredients( + UniversalTerminalRecipe.this.cycleticks / 20, + this.ingredients + ) } def setIngredients() { val stack: PositionedStack = { - if(isUniversal) - new PositionedStack(ItemEnum.UNIVERSALTERMINAL.getDamagedStack(0), 25, 6, false) + if (isUniversal) + new PositionedStack( + ItemEnum.UNIVERSALTERMINAL.getDamagedStack(0), + 25, + 6, + false + ) else new PositionedStack(UniversalTerminal.wirelessTerminals, 25, 6, false) } stack.setMaxSize(1) this.ingredients.add(stack) - val stack2: PositionedStack = new PositionedStack(UniversalTerminal.terminals, 43, 6, false) + val stack2: PositionedStack = + new PositionedStack(UniversalTerminal.terminals, 43, 6, false) stack2.setMaxSize(1) this.ingredients.add(stack2) @@ -148,4 +180,4 @@ class UniversalTerminalRecipe extends TemplateRecipeHandler { } } -} \ No newline at end of file +} diff --git a/src/main/scala/extracells/integration/opencomputers/DriverFluidExportBus.java b/src/main/scala/extracells/integration/opencomputers/DriverFluidExportBus.java index 40f390eb3..c8ad1a650 100644 --- a/src/main/scala/extracells/integration/opencomputers/DriverFluidExportBus.java +++ b/src/main/scala/extracells/integration/opencomputers/DriverFluidExportBus.java @@ -1,191 +1,183 @@ package extracells.integration.opencomputers; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import appeng.api.networking.ticking.TickRateModulation; import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; +import extracells.Extracells; import extracells.part.PartFluidExport; import extracells.part.PartGasExport; import extracells.registries.ItemEnum; import extracells.registries.PartEnum; import extracells.util.FluidUtil; import li.cil.oc.api.Network; -import li.cil.oc.api.driver.EnvironmentAware; +import li.cil.oc.api.driver.EnvironmentProvider; import li.cil.oc.api.driver.NamedBlock; +import li.cil.oc.api.driver.SidedBlock; import li.cil.oc.api.internal.Database; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; import li.cil.oc.api.machine.Context; -import li.cil.oc.api.network.Environment; import li.cil.oc.api.network.Node; import li.cil.oc.api.network.Visibility; import li.cil.oc.api.prefab.ManagedEnvironment; import li.cil.oc.server.network.Component; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -public class DriverFluidExportBus implements li.cil.oc.api.driver.Block, EnvironmentAware{ - - @Override - public boolean worksWith(World world, int x, int y, int z) { - return getExportBus(world, x, y, z, ForgeDirection.UNKNOWN) != null; - } - - @Override - public ManagedEnvironment createEnvironment(World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - return new Enviroment((IPartHost) tile); - } - - private static PartFluidExport getExportBus(World world, int x, int y, int z, ForgeDirection dir){ - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - IPartHost host = (IPartHost) tile; - if(dir == null || dir == ForgeDirection.UNKNOWN){ - for (ForgeDirection side: ForgeDirection.VALID_DIRECTIONS){ - IPart part = host.getPart(side); - if (part != null && part instanceof PartFluidExport && !(part instanceof PartGasExport)) - return (PartFluidExport) part; - } - return null; - }else{ - IPart part = host.getPart(dir); - return part == null ? null : part instanceof PartGasExport ? null :(PartFluidExport) part; - } - } - - public class Enviroment extends ManagedEnvironment implements NamedBlock{ - - protected final TileEntity tile; - protected final IPartHost host; - - public Enviroment(IPartHost host){ - tile = (TileEntity) host; - this.host = host; - setNode(Network.newNode(this, Visibility.Network). - withComponent("me_exportbus"). - create()); - } - - @Callback(doc = "function(side:number, [ slot:number]):table -- Get the configuration of the fluid export bus pointing in the specified direction.") - public Object[] getFluidExportConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; - PartFluidExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; - int slot = args.optInteger(1, 4); - try{ - Fluid fluid = part.filterFluids[slot]; - if (fluid == null) - return new Object[]{null}; - return new Object[]{new FluidStack(fluid, 1000)}; - }catch(Throwable e){ - return new Object[]{null, "Invalid slot"}; - } - - } - - @Callback(doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the fluid export bus pointing in the specified direction to export fluid stacks matching the specified descriptor.") - public Object[] setFluidExportConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; - PartFluidExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; - int slot; - String address; - int entry; - if (args.count() == 3){ - address = args.checkString(1); - entry = args.checkInteger(2); - slot = 4; - }else if (args.count() < 3){ - slot = args.optInteger(1, 4); - try{ - part.filterFluids[slot] = null; - part.onInventoryChanged(); - context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; - } - }else{ - slot = args.optInteger(1, 4); - address = args.checkString(2); - entry = args.checkInteger(3); - } - Node node = node().network().node(address); - if (node == null) - throw new IllegalArgumentException("no such component"); - if (!(node instanceof Component)) - throw new IllegalArgumentException("no such component"); - Component component = (Component) node; - Environment env = node.host(); - if (!(env instanceof Database)) - throw new IllegalArgumentException("not a database"); - Database database = (Database) env; - try{ - ItemStack data = database.getStackInSlot(entry - 1); - if (data == null) - part.filterFluids[slot] = null; - else{ - FluidStack fluid = FluidUtil.getFluidFromContainer(data); - if(fluid == null || fluid.getFluid() == null) - return new Object[]{false, "not a fluid container"}; - part.filterFluids[slot] = fluid.getFluid(); - } - part.onInventoryChanged(); - context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; - } - } - - @Callback(doc = "function(side:number, amount:number):boolean -- Make the fluid export bus facing the specified direction perform a single export operation.") - public Object[] exportFluid(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{false, "unknown side"}; - PartFluidExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{false, "no export bus"}; - if (part.getFacingTank() == null) - return new Object[]{false, "no tank"}; - int amount = Math.min(args.optInteger(1, 625), 125 + part.getSpeedState() * 125); - boolean didSomething = part.doWork(amount, 1); - if (didSomething) - context.pause(0.25); - return new Object[]{didSomething}; - } - - @Override - public String preferredName() { - return "me_exportbus"; - } - - @Override - public int priority() { - return 2; - } - - } - - @Override - public Class providedEnvironment(ItemStack stack) { - if(stack == null) - return null; - if(stack.getItem() == ItemEnum.PARTITEM.getItem() && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) - return Enviroment.class; - return null; - } +public class DriverFluidExportBus implements SidedBlock { + + @Override + public boolean worksWith(World world, int x, int y, int z, ForgeDirection side) { + return getExportBus(world, x, y, z, side) != null; + } + + @Override + public ManagedEnvironment createEnvironment(World world, int x, int y, int z, ForgeDirection side) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile == null || (!(tile instanceof IPartHost))) return null; + return new Environment((IPartHost) tile); + } + + private static PartFluidExport getExportBus(World world, int x, int y, int z, ForgeDirection dir) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile == null || (!(tile instanceof IPartHost))) return null; + IPartHost host = (IPartHost) tile; + if (dir == null || dir == ForgeDirection.UNKNOWN) { + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + IPart part = host.getPart(side); + if (part != null && part instanceof PartFluidExport && !(part instanceof PartGasExport)) + return (PartFluidExport) part; + } + return null; + } else { + IPart part = host.getPart(dir); + if (part != null && part instanceof PartFluidExport && !(part instanceof PartGasExport)) + return (PartFluidExport) part; + return null; + } + } + + public class Environment extends ManagedEnvironment implements NamedBlock { + + protected final TileEntity tile; + protected final IPartHost host; + + Environment(IPartHost host) { + tile = (TileEntity) host; + this.host = host; + setNode(Network.newNode(this, Visibility.Network).withComponent("me_exportbus").create()); + } + + @Callback( + doc = "function(side:number, [ slot:number]):table -- Get the configuration of the fluid export bus pointing in the specified direction.") + public Object[] getFluidExportConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; + PartFluidExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { null, "no export bus" }; + int slot = args.optInteger(1, 4); + try { + Fluid fluid = part.filterFluids[slot]; + if (fluid == null) return new Object[] { null }; + return new Object[] { new FluidStack(fluid, 1000) }; + } catch (Throwable e) { + return new Object[] { null, "Invalid slot" }; + } + } + + @Callback( + doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the fluid export bus pointing in the specified direction to export fluid stacks matching the specified descriptor.") + public Object[] setFluidExportConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; + PartFluidExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { null, "no export bus" }; + int slot; + String address; + int entry; + if (args.count() == 3) { + address = args.checkString(1); + entry = args.checkInteger(2); + slot = 4; + } else if (args.count() < 3) { + slot = args.optInteger(1, 4); + try { + part.filterFluids[slot] = null; + part.onInventoryChanged(); + context.pause(0.5); + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; + } + } else { + slot = args.optInteger(1, 4); + address = args.checkString(2); + entry = args.checkInteger(3); + } + Node node = node().network().node(address); + if (node == null) throw new IllegalArgumentException("no such component"); + if (!(node instanceof Component)) throw new IllegalArgumentException("no such component"); + li.cil.oc.api.network.Environment env = node.host(); + if (!(env instanceof Database)) throw new IllegalArgumentException("not a database"); + Database database = (Database) env; + try { + ItemStack data = database.getStackInSlot(entry - 1); + if (data == null) part.filterFluids[slot] = null; + else { + FluidStack fluid = FluidUtil.getFluidFromContainer(data); + if (fluid == null || fluid.getFluid() == null) + return new Object[] { false, "not a fluid container" }; + part.filterFluids[slot] = fluid.getFluid(); + } + part.onInventoryChanged(); + context.pause(0.5); + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; + } + } + + @Callback( + doc = "function(side:number, amount:number):boolean -- Make the fluid export bus facing the specified direction perform a single export operation.") + public Object[] exportFluid(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { false, "unknown side" }; + PartFluidExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { false, "no export bus" }; + if (part.getFacingTank() == null) return new Object[] { false, "no tank" }; + int amount = Math.min( + args.optInteger(1, Extracells.basePartSpeed() * 5), + Extracells.basePartSpeed() + part.getSpeedState() * Extracells.basePartSpeed()); + boolean didSomething = part.doWork(amount, 1) == TickRateModulation.FASTER; + if (didSomething) context.pause(0.25); + return new Object[] { didSomething }; + } + + @Override + public String preferredName() { + return "me_exportbus"; + } + + @Override + public int priority() { + return 2; + } + } + + static class Provider implements EnvironmentProvider { + @Override + public Class getEnvironment(ItemStack stack) { + if (stack == null) return null; + if (stack.getItem() == ItemEnum.PARTITEM.getItem() + && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) + return Environment.class; + return null; + } + } } diff --git a/src/main/scala/extracells/integration/opencomputers/DriverFluidImportBus.java b/src/main/scala/extracells/integration/opencomputers/DriverFluidImportBus.java index ca2fcd92e..45acbb50e 100644 --- a/src/main/scala/extracells/integration/opencomputers/DriverFluidImportBus.java +++ b/src/main/scala/extracells/integration/opencomputers/DriverFluidImportBus.java @@ -1,5 +1,12 @@ package extracells.integration.opencomputers; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import extracells.part.PartFluidImport; @@ -8,8 +15,9 @@ import extracells.registries.PartEnum; import extracells.util.FluidUtil; import li.cil.oc.api.Network; -import li.cil.oc.api.driver.EnvironmentAware; +import li.cil.oc.api.driver.EnvironmentProvider; import li.cil.oc.api.driver.NamedBlock; +import li.cil.oc.api.driver.SidedBlock; import li.cil.oc.api.internal.Database; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; @@ -19,173 +27,152 @@ import li.cil.oc.api.network.Visibility; import li.cil.oc.api.prefab.ManagedEnvironment; import li.cil.oc.server.network.Component; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -public class DriverFluidImportBus implements li.cil.oc.api.driver.Block, EnvironmentAware{ - - @Override - public boolean worksWith(World world, int x, int y, int z) { - return getImportBus(world, x, y, z, ForgeDirection.UNKNOWN) != null; - } - - @Override - public ManagedEnvironment createEnvironment(World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - return new Enviroment((IPartHost) tile); - } - - private static PartFluidImport getImportBus(World world, int x, int y, int z, ForgeDirection dir){ - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - IPartHost host = (IPartHost) tile; - if(dir == null || dir == ForgeDirection.UNKNOWN){ - for (ForgeDirection side: ForgeDirection.VALID_DIRECTIONS){ - IPart part = host.getPart(side); - if (part != null && part instanceof PartFluidImport &&!(part instanceof PartGasImport)) - return (PartFluidImport) part; - } - return null; - }else{ - IPart part = host.getPart(dir); - return part == null ? null : part instanceof PartGasImport ? null : (PartFluidImport) part; - } - } - - public class Enviroment extends ManagedEnvironment implements NamedBlock{ - - protected final TileEntity tile; - protected final IPartHost host; - - public Enviroment(IPartHost host){ - tile = (TileEntity) host; - this.host = host; - setNode(Network.newNode(this, Visibility.Network). - withComponent("me_importbus"). - create()); - } - - @Callback(doc = "function(side:number, [ slot:number]):table -- Get the configuration of the fluid import bus pointing in the specified direction.") - public Object[] getFluidImportConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; - PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; - int slot = args.optInteger(1, 4); - try{ - Fluid fluid = part.filterFluids[slot]; - if (fluid == null) - return new Object[]{null}; - return new Object[]{new FluidStack(fluid, 1000)}; - }catch(Throwable e){ - return new Object[]{null, "Invalid slot"}; - } - - } - - @Callback(doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the fluid import bus pointing in the specified direction to export fluid stacks matching the specified descriptor.") - public Object[] setFluidImportConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; - PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; - int slot; - String address; - int entry; - if (args.count() == 3){ - address = args.checkString(1); - entry = args.checkInteger(2); - slot = 4; - }else if (args.count() < 3){ - slot = args.optInteger(1, 4); - try{ - part.filterFluids[slot] = null; - part.onInventoryChanged(); - context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; - } - }else{ - slot = args.optInteger(1, 4); - address = args.checkString(2); - entry = args.checkInteger(3); - } - Node node = node().network().node(address); - if (node == null) - throw new IllegalArgumentException("no such component"); - if (!(node instanceof Component)) - throw new IllegalArgumentException("no such component"); - Component component = (Component) node; - Environment env = node.host(); - if (!(env instanceof Database)) - throw new IllegalArgumentException("not a database"); - Database database = (Database) env; - try{ - ItemStack data = database.getStackInSlot(entry - 1); - if (data == null) - part.filterFluids[slot] = null; - else{ - FluidStack fluid = FluidUtil.getFluidFromContainer(data); - if(fluid == null || fluid.getFluid() == null) - return new Object[]{false, "not a fluid container"}; - part.filterFluids[slot] = fluid.getFluid(); - } - part.onInventoryChanged(); - context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; - } - } - - /*@Callback(doc = "function(side:number, amount:number):boolean -- Make the fluid export bus facing the specified direction perform a single export operation.") - public Object[] exportFluid(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{false, "unknown side"}; - PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{false, "no export bus"}; - if (part.getFacingTank() == null) - return new Object[]{false, "no tank"}; - int amount = Math.min(args.optInteger(1, 625), 125 + part.getSpeedState() * 125); - boolean didSomething = part.doWork(amount, 1); - if (didSomething) - context.pause(0.25); - return new Object[]{didSomething}; - }*/ - - @Override - public String preferredName() { - return "me_importbus"; - } - - @Override - public int priority() { - return 1; - } - - } - - @Override - public Class providedEnvironment(ItemStack stack) { - if(stack == null) - return null; - if(stack.getItem() == ItemEnum.PARTITEM.getItem() && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) - return Enviroment.class; - return null; - } +public class DriverFluidImportBus implements SidedBlock { + + @Override + public boolean worksWith(World world, int x, int y, int z, ForgeDirection side) { + return getImportBus(world, x, y, z, side) != null; + } + + @Override + public ManagedEnvironment createEnvironment(World world, int x, int y, int z, ForgeDirection side) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile == null || (!(tile instanceof IPartHost))) return null; + return new Enviroment((IPartHost) tile); + } + + private static PartFluidImport getImportBus(World world, int x, int y, int z, ForgeDirection dir) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile == null || (!(tile instanceof IPartHost))) return null; + IPartHost host = (IPartHost) tile; + if (dir == null || dir == ForgeDirection.UNKNOWN) { + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + IPart part = host.getPart(side); + if (part != null && part instanceof PartFluidImport && !(part instanceof PartGasImport)) + return (PartFluidImport) part; + } + return null; + } else { + IPart part = host.getPart(dir); + if (part != null && part instanceof PartFluidImport && !(part instanceof PartGasImport)) + return (PartFluidImport) part; + return null; + } + } + + public class Enviroment extends ManagedEnvironment implements NamedBlock { + + protected final TileEntity tile; + protected final IPartHost host; + + Enviroment(IPartHost host) { + tile = (TileEntity) host; + this.host = host; + setNode(Network.newNode(this, Visibility.Network).withComponent("me_importbus").create()); + } + + @Callback( + doc = "function(side:number, [ slot:number]):table -- Get the configuration of the fluid import bus pointing in the specified direction.") + public Object[] getFluidImportConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; + PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { null, "no export bus" }; + int slot = args.optInteger(1, 4); + try { + Fluid fluid = part.filterFluids[slot]; + if (fluid == null) return new Object[] { null }; + return new Object[] { new FluidStack(fluid, 1000) }; + } catch (Throwable e) { + return new Object[] { null, "Invalid slot" }; + } + } + + @Callback( + doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the fluid import bus pointing in the specified direction to export fluid stacks matching the specified descriptor.") + public Object[] setFluidImportConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; + PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { null, "no export bus" }; + int slot; + String address; + int entry; + if (args.count() == 3) { + address = args.checkString(1); + entry = args.checkInteger(2); + slot = 4; + } else if (args.count() < 3) { + slot = args.optInteger(1, 4); + try { + part.filterFluids[slot] = null; + part.onInventoryChanged(); + context.pause(0.5); + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; + } + } else { + slot = args.optInteger(1, 4); + address = args.checkString(2); + entry = args.checkInteger(3); + } + Node node = node().network().node(address); + if (node == null) throw new IllegalArgumentException("no such component"); + if (!(node instanceof Component)) throw new IllegalArgumentException("no such component"); + Environment env = node.host(); + if (!(env instanceof Database)) throw new IllegalArgumentException("not a database"); + Database database = (Database) env; + try { + ItemStack data = database.getStackInSlot(entry - 1); + if (data == null) part.filterFluids[slot] = null; + else { + FluidStack fluid = FluidUtil.getFluidFromContainer(data); + if (fluid == null || fluid.getFluid() == null) + return new Object[] { false, "not a fluid container" }; + part.filterFluids[slot] = fluid.getFluid(); + } + part.onInventoryChanged(); + context.pause(0.5); + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; + } + } + + /* + * @Callback(doc = + * "function(side:number, amount:number):boolean -- Make the fluid export bus facing the specified direction perform a single export operation." + * ) public Object[] exportFluid(Context context, Arguments args){ ForgeDirection dir = + * ForgeDirection.getOrientation(args.checkInteger(0)); if (dir == null || dir == ForgeDirection.UNKNOWN) return + * new Object[]{false, "unknown side"}; PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, + * tile.yCoord, tile.zCoord, dir); if (part == null) return new Object[]{false, "no export bus"}; if + * (part.getFacingTank() == null) return new Object[]{false, "no tank"}; int amount = + * Math.min(args.optInteger(1, 625), 125 + part.getSpeedState() * 125); boolean didSomething = + * part.doWork(amount, 1); if (didSomething) context.pause(0.25); return new Object[]{didSomething}; } + */ + + @Override + public String preferredName() { + return "me_importbus"; + } + + @Override + public int priority() { + return 1; + } + } + + static class Provider implements EnvironmentProvider { + @Override + public Class getEnvironment(ItemStack stack) { + if (stack == null) return null; + if (stack.getItem() == ItemEnum.PARTITEM.getItem() + && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) + return Enviroment.class; + return null; + } + } } diff --git a/src/main/scala/extracells/integration/opencomputers/DriverFluidInterface.java b/src/main/scala/extracells/integration/opencomputers/DriverFluidInterface.java index 3f1919bf3..889a16681 100644 --- a/src/main/scala/extracells/integration/opencomputers/DriverFluidInterface.java +++ b/src/main/scala/extracells/integration/opencomputers/DriverFluidInterface.java @@ -1,5 +1,13 @@ package extracells.integration.opencomputers; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import extracells.api.IFluidInterface; @@ -10,162 +18,141 @@ import extracells.tileentity.TileEntityFluidInterface; import extracells.util.FluidUtil; import li.cil.oc.api.Network; -import li.cil.oc.api.driver.EnvironmentAware; +import li.cil.oc.api.driver.EnvironmentProvider; import li.cil.oc.api.driver.NamedBlock; +import li.cil.oc.api.driver.SidedBlock; import li.cil.oc.api.internal.Database; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; import li.cil.oc.api.machine.Context; -import li.cil.oc.api.network.Environment; import li.cil.oc.api.network.Node; import li.cil.oc.api.network.Visibility; import li.cil.oc.api.prefab.ManagedEnvironment; import li.cil.oc.server.network.Component; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -public class DriverFluidInterface implements li.cil.oc.api.driver.Block, EnvironmentAware{ +public class DriverFluidInterface implements SidedBlock { + + @Override + public boolean worksWith(World world, int x, int y, int z, ForgeDirection side) { + TileEntity tile = world.getTileEntity(x, y, z); + return tile != null && (getFluidInterface(world, x, y, z, side) != null || tile instanceof IFluidInterface); + } + + @Override + public ManagedEnvironment createEnvironment(World world, int x, int y, int z, ForgeDirection side) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile == null || (!(tile instanceof IPartHost || tile instanceof IFluidInterface))) return null; + return new Environment(tile); + } + + private static PartFluidInterface getFluidInterface(World world, int x, int y, int z, ForgeDirection dir) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile == null || (!(tile instanceof IPartHost))) return null; + IPartHost host = (IPartHost) tile; + if (dir == null || dir == ForgeDirection.UNKNOWN) { + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + IPart part = host.getPart(side); + if (part != null && part instanceof PartFluidInterface) return (PartFluidInterface) part; + } + return null; + } else { + IPart part = host.getPart(dir); + return part instanceof PartFluidInterface ? (PartFluidInterface) part : null; + } + } + + public class Environment extends ManagedEnvironment implements NamedBlock { + + protected final TileEntity tile; + protected final IPartHost host; - @Override - public boolean worksWith(World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null) - return false; - return getFluidInterface(world, x, y, z, ForgeDirection.UNKNOWN) != null || tile instanceof IFluidInterface; - } + Environment(TileEntity tile) { + this.tile = tile; + this.host = tile instanceof IPartHost ? (IPartHost) tile : null; + setNode(Network.newNode(this, Visibility.Network).withComponent("me_interface").create()); + } - @Override - public ManagedEnvironment createEnvironment(World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost || tile instanceof IFluidInterface))) - return null; - return new Enviroment(tile); - } - - private static PartFluidInterface getFluidInterface(World world, int x, int y, int z, ForgeDirection dir){ - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - IPartHost host = (IPartHost) tile; - if(dir == null || dir == ForgeDirection.UNKNOWN){ - for (ForgeDirection side: ForgeDirection.VALID_DIRECTIONS){ - IPart part = host.getPart(side); - if (part != null && part instanceof PartFluidInterface) - return (PartFluidInterface) part; - } - return null; - }else{ - IPart part = host.getPart(dir); - return part == null ? null : (PartFluidInterface) part; - } - } - - public class Enviroment extends ManagedEnvironment implements NamedBlock{ - - protected final TileEntity tile; - protected final IPartHost host; - - public Enviroment(TileEntity tile){ - this.tile = tile; - this.host = tile instanceof IPartHost ? (IPartHost) tile : null; - setNode(Network.newNode(this, Visibility.Network). - withComponent("me_interface"). - create()); - } + @Callback( + doc = "function(side:number):table -- Get the configuration of the fluid interface on the specified direction.") + public Object[] getFluidInterfaceConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; + if (tile instanceof TileEntityFluidInterface) { + TileEntityFluidInterface fluidInterface = (TileEntityFluidInterface) tile; + Fluid fluid = fluidInterface.getFilter(dir); + if (fluid == null) return new Object[] { null }; + return new Object[] { new FluidStack(fluid, 1000) }; + } + PartFluidInterface part = getFluidInterface(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { null, "no interface" }; + Fluid fluid = part.getFilter(dir); + if (fluid == null) return new Object[] { null }; + return new Object[] { new FluidStack(fluid, 1000) }; + } - @Callback(doc = "function(side:number):table -- Get the configuration of the fluid interface on the specified direction.") - public Object[] getFluidInterfaceConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; - if (tile instanceof TileEntityFluidInterface){ - TileEntityFluidInterface fluidInterface = (TileEntityFluidInterface) tile; - Fluid fluid = fluidInterface.getFilter(dir); - if (fluid == null) - return new Object[]{null}; - return new Object[]{new FluidStack(fluid, 1000)}; - } - PartFluidInterface part = getFluidInterface(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no interface"}; - Fluid fluid = part.getFilter(dir); - if (fluid == null) - return new Object[]{null}; - return new Object[]{new FluidStack(fluid, 1000)}; - - } - - @Callback(doc = "function(side:number[, database:address, entry:number]):boolean -- Configure the filter in fluid interface on the specified direction.") - public Object[] setFluidInterfaceConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; - IFluidInterface part = tile instanceof IFluidInterface ? (IFluidInterface) tile : getFluidInterface(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; - String address; - int entry; - if (args.count() == 3){ - address = args.checkString(1); - entry = args.checkInteger(2); - }else{ - part.setFilter(dir, null); - context.pause(0.5); - return new Object[]{true}; - } - Node node = node().network().node(address); - if (node == null) - throw new IllegalArgumentException("no such component"); - if (!(node instanceof Component)) - throw new IllegalArgumentException("no such component"); - Component component = (Component) node; - Environment env = node.host(); - if (!(env instanceof Database)) - throw new IllegalArgumentException("not a database"); - Database database = (Database) env; - try{ - ItemStack data = database.getStackInSlot(entry - 1); - if (data == null) - part.setFilter(dir, null); - else{ - FluidStack fluid = FluidUtil.getFluidFromContainer(data); - if(fluid == null || fluid.getFluid() == null) - return new Object[]{false, "not a fluid container"}; - part.setFilter(dir, fluid.getFluid()); - } - context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; - } - } + @Callback( + doc = "function(side:number[, database:address, entry:number]):boolean -- Configure the filter in fluid interface on the specified direction.") + public Object[] setFluidInterfaceConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; + IFluidInterface part = tile instanceof IFluidInterface ? (IFluidInterface) tile + : getFluidInterface(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { null, "no export bus" }; + String address; + int entry; + if (args.count() == 3) { + address = args.checkString(1); + entry = args.checkInteger(2); + } else { + part.setFilter(dir, null); + context.pause(0.5); + return new Object[] { true }; + } + Node node = node().network().node(address); + if (node == null) throw new IllegalArgumentException("no such component"); + if (!(node instanceof Component)) throw new IllegalArgumentException("no such component"); + Component component = (Component) node; + li.cil.oc.api.network.Environment env = node.host(); + if (!(env instanceof Database)) throw new IllegalArgumentException("not a database"); + Database database = (Database) env; + try { + ItemStack data = database.getStackInSlot(entry - 1); + if (data == null) part.setFilter(dir, null); + else { + FluidStack fluid = FluidUtil.getFluidFromContainer(data); + if (fluid == null || fluid.getFluid() == null) + return new Object[] { false, "not a fluid container" }; + part.setFilter(dir, fluid.getFluid()); + } + context.pause(0.5); + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; + } + } - @Override - public String preferredName() { - return "me_interface"; - } + @Override + public String preferredName() { + return "me_interface"; + } - @Override - public int priority() { - return 0; - } - - } + @Override + public int priority() { + return 0; + } + } - @Override - public Class providedEnvironment(ItemStack stack) { - if(stack == null) - return null; - if(stack.getItem() == ItemEnum.PARTITEM.getItem() && stack.getItemDamage() == PartEnum.INTERFACE.ordinal()) - return Enviroment.class; - if(stack.getItem() == Item.getItemFromBlock(BlockEnum.ECBASEBLOCK.getBlock()) && stack.getItemDamage() == 0) - return Enviroment.class; - return null; - } + static class Provider implements EnvironmentProvider { + @Override + public Class getEnvironment(ItemStack stack) { + if (stack == null) return null; + if (stack.getItem() == ItemEnum.PARTITEM.getItem() && stack.getItemDamage() == PartEnum.INTERFACE.ordinal()) + return Environment.class; + if (stack.getItem() == Item.getItemFromBlock(BlockEnum.ECBASEBLOCK.getBlock()) + && stack.getItemDamage() == 0) + return Environment.class; + return null; + } + } } diff --git a/src/main/scala/extracells/integration/opencomputers/DriverGasExportBus.java b/src/main/scala/extracells/integration/opencomputers/DriverGasExportBus.java index 570962820..feaf87287 100644 --- a/src/main/scala/extracells/integration/opencomputers/DriverGasExportBus.java +++ b/src/main/scala/extracells/integration/opencomputers/DriverGasExportBus.java @@ -1,170 +1,157 @@ package extracells.integration.opencomputers; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import appeng.api.networking.ticking.TickRateModulation; import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; +import extracells.Extracells; import extracells.part.PartGasExport; import extracells.registries.ItemEnum; import extracells.registries.PartEnum; import extracells.util.GasUtil; import li.cil.oc.api.Network; -import li.cil.oc.api.driver.EnvironmentAware; +import li.cil.oc.api.driver.EnvironmentProvider; import li.cil.oc.api.driver.NamedBlock; +import li.cil.oc.api.driver.SidedBlock; import li.cil.oc.api.internal.Database; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; import li.cil.oc.api.machine.Context; -import li.cil.oc.api.network.Environment; import li.cil.oc.api.network.Node; import li.cil.oc.api.network.Visibility; import li.cil.oc.api.prefab.ManagedEnvironment; import li.cil.oc.server.network.Component; import mekanism.api.gas.GasStack; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -public class DriverGasExportBus implements li.cil.oc.api.driver.Block, EnvironmentAware{ +public class DriverGasExportBus implements SidedBlock { @Override - public boolean worksWith(World world, int x, int y, int z) { - return getExportBus(world, x, y, z, ForgeDirection.UNKNOWN) != null; + public boolean worksWith(World world, int x, int y, int z, ForgeDirection side) { + return getExportBus(world, x, y, z, side) != null; } @Override - public ManagedEnvironment createEnvironment(World world, int x, int y, int z) { + public ManagedEnvironment createEnvironment(World world, int x, int y, int z, ForgeDirection side) { TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - return new Enviroment((IPartHost) tile); + if (tile == null || (!(tile instanceof IPartHost))) return null; + return new Environment((IPartHost) tile); } - private static PartGasExport getExportBus(World world, int x, int y, int z, ForgeDirection dir){ + private static PartGasExport getExportBus(World world, int x, int y, int z, ForgeDirection dir) { TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; + if (tile == null || (!(tile instanceof IPartHost))) return null; IPartHost host = (IPartHost) tile; - if(dir == null || dir == ForgeDirection.UNKNOWN){ - for (ForgeDirection side: ForgeDirection.VALID_DIRECTIONS){ + if (dir == null || dir == ForgeDirection.UNKNOWN) { + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { IPart part = host.getPart(side); - if (part != null && part instanceof PartGasExport && !(part instanceof PartGasExport)) - return (PartGasExport) part; + if (part != null && part instanceof PartGasExport) return (PartGasExport) part; } return null; - }else{ + } else { IPart part = host.getPart(dir); - return part == null ? null : part instanceof PartGasExport ? null :(PartGasExport) part; + return part == null ? null : part instanceof PartGasExport ? (PartGasExport) part : null; } } - public class Enviroment extends ManagedEnvironment implements NamedBlock{ + public class Environment extends ManagedEnvironment implements NamedBlock { protected final TileEntity tile; protected final IPartHost host; - public Enviroment(IPartHost host){ + Environment(IPartHost host) { tile = (TileEntity) host; this.host = host; - setNode(Network.newNode(this, Visibility.Network). - withComponent("me_exportbus"). - create()); + setNode(Network.newNode(this, Visibility.Network).withComponent("me_exportbus").create()); } - @Callback(doc = "function(side:number, [ slot:number]):table -- Get the configuration of the gas export bus pointing in the specified direction.") - public Object[] getGasExportConfiguration(Context context, Arguments args){ + @Callback( + doc = "function(side:number, [ slot:number]):table -- Get the configuration of the gas export bus pointing in the specified direction.") + public Object[] getGasExportConfiguration(Context context, Arguments args) { ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; PartGasExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; + if (part == null) return new Object[] { null, "no export bus" }; int slot = args.optInteger(1, 4); - try{ + try { Fluid fluid = part.filterFluids[slot]; - if (fluid == null) - return new Object[]{null}; - return new Object[]{GasUtil.getGasStack(new FluidStack(fluid, 1000))}; - }catch(Throwable e){ - return new Object[]{null, "Invalid slot"}; + if (fluid == null) return new Object[] { null }; + return new Object[] { GasUtil.getGasStack(new FluidStack(fluid, 1000)) }; + } catch (Throwable e) { + return new Object[] { null, "Invalid slot" }; } - } - @Callback(doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the gas export bus pointing in the specified direction to export gas stacks matching the specified descriptor.") - public Object[] setGasExportConfiguration(Context context, Arguments args){ + @Callback( + doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the gas export bus pointing in the specified direction to export gas stacks matching the specified descriptor.") + public Object[] setGasExportConfiguration(Context context, Arguments args) { ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; PartGasExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; + if (part == null) return new Object[] { null, "no export bus" }; int slot; String address; int entry; - if (args.count() == 3){ + if (args.count() == 3) { address = args.checkString(1); entry = args.checkInteger(2); slot = 4; - }else if (args.count() < 3){ + } else if (args.count() < 3) { slot = args.optInteger(1, 4); - try{ + try { part.filterFluids[slot] = null; part.onInventoryChanged(); context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; } - }else{ + } else { slot = args.optInteger(1, 4); address = args.checkString(2); entry = args.checkInteger(3); } Node node = node().network().node(address); - if (node == null) - throw new IllegalArgumentException("no such component"); - if (!(node instanceof Component)) - throw new IllegalArgumentException("no such component"); - Component component = (Component) node; - Environment env = node.host(); - if (!(env instanceof Database)) - throw new IllegalArgumentException("not a database"); + if (node == null) throw new IllegalArgumentException("no such component"); + if (!(node instanceof Component)) throw new IllegalArgumentException("no such component"); + li.cil.oc.api.network.Environment env = node.host(); + if (!(env instanceof Database)) throw new IllegalArgumentException("not a database"); Database database = (Database) env; - try{ + try { ItemStack data = database.getStackInSlot(entry - 1); - if (data == null) - part.filterFluids[slot] = null; - else{ + if (data == null) part.filterFluids[slot] = null; + else { GasStack fluid = GasUtil.getGasFromContainer(data); - if(fluid == null || fluid.getGas() == null) - return new Object[]{false, "not a fluid container"}; + if (fluid == null || fluid.getGas() == null) return new Object[] { false, "not a fluid container" }; part.filterFluids[slot] = GasUtil.getFluidStack(fluid).getFluid(); } part.onInventoryChanged(); context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; } } - @Callback(doc = "function(side:number, amount:number):boolean -- Make the gas export bus facing the specified direction perform a single export operation.") - public Object[] exportGas(Context context, Arguments args){ + @Callback( + doc = "function(side:number, amount:number):boolean -- Make the gas export bus facing the specified direction perform a single export operation.") + public Object[] exportGas(Context context, Arguments args) { ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{false, "unknown side"}; + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { false, "unknown side" }; PartGasExport part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{false, "no export bus"}; - if (part.getFacingGasTank() == null) - return new Object[]{false, "no tank"}; - int amount = Math.min(args.optInteger(1, 625), 125 + part.getSpeedState() * 125); - boolean didSomething = part.doWork(amount, 1); - if (didSomething) - context.pause(0.25); - return new Object[]{didSomething}; + if (part == null) return new Object[] { false, "no export bus" }; + if (part.getFacingGasTank() == null) return new Object[] { false, "no tank" }; + int amount = Math.min( + args.optInteger(1, Extracells.basePartSpeed() * 5), + Extracells.basePartSpeed() + part.getSpeedState() * Extracells.basePartSpeed()); + boolean didSomething = part.doWork(amount, 1) == TickRateModulation.FASTER; + if (didSomething) context.pause(0.25); + return new Object[] { didSomething }; } @Override @@ -176,16 +163,17 @@ public String preferredName() { public int priority() { return 2; } - } - @Override - public Class providedEnvironment(ItemStack stack) { - if(stack == null) + static class Provider implements EnvironmentProvider { + + @Override + public Class getEnvironment(ItemStack stack) { + if (stack == null) return null; + if (stack.getItem() == ItemEnum.PARTITEM.getItem() + && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) + return Environment.class; return null; - if(stack.getItem() == ItemEnum.PARTITEM.getItem() && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) - return Enviroment.class; - return null; + } } - } diff --git a/src/main/scala/extracells/integration/opencomputers/DriverGasImportBus.java b/src/main/scala/extracells/integration/opencomputers/DriverGasImportBus.java index 977a2c166..7cb714f3d 100644 --- a/src/main/scala/extracells/integration/opencomputers/DriverGasImportBus.java +++ b/src/main/scala/extracells/integration/opencomputers/DriverGasImportBus.java @@ -1,5 +1,12 @@ package extracells.integration.opencomputers; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import extracells.part.PartFluidImport; @@ -8,165 +15,140 @@ import extracells.registries.PartEnum; import extracells.util.GasUtil; import li.cil.oc.api.Network; -import li.cil.oc.api.driver.EnvironmentAware; +import li.cil.oc.api.driver.EnvironmentProvider; import li.cil.oc.api.driver.NamedBlock; +import li.cil.oc.api.driver.SidedBlock; import li.cil.oc.api.internal.Database; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; import li.cil.oc.api.machine.Context; -import li.cil.oc.api.network.Environment; import li.cil.oc.api.network.Node; import li.cil.oc.api.network.Visibility; import li.cil.oc.api.prefab.ManagedEnvironment; import li.cil.oc.server.network.Component; import mekanism.api.gas.GasStack; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -public class DriverGasImportBus implements li.cil.oc.api.driver.Block, EnvironmentAware{ +public class DriverGasImportBus implements SidedBlock { @Override - public boolean worksWith(World world, int x, int y, int z) { - return getImportBus(world, x, y, z, ForgeDirection.UNKNOWN) != null; + public boolean worksWith(World world, int x, int y, int z, ForgeDirection side) { + return getImportBus(world, x, y, z, side) != null; } @Override - public ManagedEnvironment createEnvironment(World world, int x, int y, int z) { + public ManagedEnvironment createEnvironment(World world, int x, int y, int z, ForgeDirection side) { TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - return new Enviroment((IPartHost) tile); + if (tile == null || (!(tile instanceof IPartHost))) return null; + return new Environment((IPartHost) tile); } - private static PartGasImport getImportBus(World world, int x, int y, int z, ForgeDirection dir){ + private static PartGasImport getImportBus(World world, int x, int y, int z, ForgeDirection dir) { TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; + if (tile == null || (!(tile instanceof IPartHost))) return null; IPartHost host = (IPartHost) tile; - if(dir == null || dir == ForgeDirection.UNKNOWN){ - for (ForgeDirection side: ForgeDirection.VALID_DIRECTIONS){ + if (dir == null || dir == ForgeDirection.UNKNOWN) { + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { IPart part = host.getPart(side); - if (part != null && part instanceof PartGasImport) - return (PartGasImport) part; + if (part != null && part instanceof PartGasImport) return (PartGasImport) part; } return null; - }else{ + } else { IPart part = host.getPart(dir); - return part == null ? null : (PartGasImport) part; + return part instanceof PartGasImport ? (PartGasImport) part : null; } } - public class Enviroment extends ManagedEnvironment implements NamedBlock{ + public class Environment extends ManagedEnvironment implements NamedBlock { protected final TileEntity tile; protected final IPartHost host; - public Enviroment(IPartHost host){ + Environment(IPartHost host) { tile = (TileEntity) host; this.host = host; - setNode(Network.newNode(this, Visibility.Network). - withComponent("me_importbus"). - create()); + setNode(Network.newNode(this, Visibility.Network).withComponent("me_importbus").create()); } - @Callback(doc = "function(side:number, [ slot:number]):table -- Get the configuration of the gas import bus pointing in the specified direction.") - public Object[] getGasImportConfiguration(Context context, Arguments args){ + @Callback( + doc = "function(side:number, [ slot:number]):table -- Get the configuration of the gas import bus pointing in the specified direction.") + public Object[] getGasImportConfiguration(Context context, Arguments args) { ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; + if (part == null) return new Object[] { null, "no export bus" }; int slot = args.optInteger(1, 4); - try{ + try { Fluid fluid = part.filterFluids[slot]; - if (fluid == null) - return new Object[]{null}; - return new Object[]{GasUtil.getGasStack(new FluidStack(fluid, 1000))}; - }catch(Throwable e){ - return new Object[]{null, "Invalid slot"}; + if (fluid == null) return new Object[] { null }; + return new Object[] { GasUtil.getGasStack(new FluidStack(fluid, 1000)) }; + } catch (Throwable e) { + return new Object[] { null, "Invalid slot" }; } - } - @Callback(doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the gas import bus pointing in the specified direction to export gas stacks matching the specified descriptor.") - public Object[] setFluidImportConfiguration(Context context, Arguments args){ + @Callback( + doc = "function(side:number[, slot:number][, database:address, entry:number]):boolean -- Configure the gas import bus pointing in the specified direction to export gas stacks matching the specified descriptor.") + public Object[] setFluidImportConfiguration(Context context, Arguments args) { ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; PartGasImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; + if (part == null) return new Object[] { null, "no export bus" }; int slot; String address; int entry; - if (args.count() == 3){ + if (args.count() == 3) { address = args.checkString(1); entry = args.checkInteger(2); slot = 4; - }else if (args.count() < 3){ + } else if (args.count() < 3) { slot = args.optInteger(1, 4); - try{ + try { part.filterFluids[slot] = null; part.onInventoryChanged(); context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; } - }else{ + } else { slot = args.optInteger(1, 4); address = args.checkString(2); entry = args.checkInteger(3); } Node node = node().network().node(address); - if (node == null) - throw new IllegalArgumentException("no such component"); - if (!(node instanceof Component)) - throw new IllegalArgumentException("no such component"); + if (node == null) throw new IllegalArgumentException("no such component"); + if (!(node instanceof Component)) throw new IllegalArgumentException("no such component"); Component component = (Component) node; - Environment env = node.host(); - if (!(env instanceof Database)) - throw new IllegalArgumentException("not a database"); + li.cil.oc.api.network.Environment env = node.host(); + if (!(env instanceof Database)) throw new IllegalArgumentException("not a database"); Database database = (Database) env; - try{ + try { ItemStack data = database.getStackInSlot(entry - 1); - if (data == null) - part.filterFluids[slot] = null; - else{ + if (data == null) part.filterFluids[slot] = null; + else { GasStack fluid = GasUtil.getGasFromContainer(data); - if(fluid == null || fluid.getGas() == null) - return new Object[]{false, "not a fluid container"}; + if (fluid == null || fluid.getGas() == null) return new Object[] { false, "not a fluid container" }; part.filterFluids[slot] = GasUtil.getFluidStack(fluid).getFluid(); } part.onInventoryChanged(); context.pause(0.5); - return new Object[]{true}; - }catch(Throwable e){ - return new Object[]{false, "invalid slot"}; + return new Object[] { true }; + } catch (Throwable e) { + return new Object[] { false, "invalid slot" }; } } - /*@Callback(doc = "function(side:number, amount:number):boolean -- Make the fluid export bus facing the specified direction perform a single export operation.") - public Object[] exportFluid(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{false, "unknown side"}; - PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{false, "no export bus"}; - if (part.getFacingTank() == null) - return new Object[]{false, "no tank"}; - int amount = Math.min(args.optInteger(1, 625), 125 + part.getSpeedState() * 125); - boolean didSomething = part.doWork(amount, 1); - if (didSomething) - context.pause(0.25); - return new Object[]{didSomething}; - }*/ + /* + * @Callback(doc = + * "function(side:number, amount:number):boolean -- Make the fluid export bus facing the specified direction perform a single export operation." + * ) public Object[] exportFluid(Context context, Arguments args){ ForgeDirection dir = + * ForgeDirection.getOrientation(args.checkInteger(0)); if (dir == null || dir == ForgeDirection.UNKNOWN) return + * new Object[]{false, "unknown side"}; PartFluidImport part = getImportBus(tile.getWorldObj(), tile.xCoord, + * tile.yCoord, tile.zCoord, dir); if (part == null) return new Object[]{false, "no export bus"}; if + * (part.getFacingTank() == null) return new Object[]{false, "no tank"}; int amount = + * Math.min(args.optInteger(1, 625), 125 + part.getSpeedState() * 125); boolean didSomething = + * part.doWork(amount, 1); if (didSomething) context.pause(0.25); return new Object[]{didSomething}; } + */ @Override public String preferredName() { @@ -177,16 +159,17 @@ public String preferredName() { public int priority() { return 1; } - } - @Override - public Class providedEnvironment(ItemStack stack) { - if(stack == null) + static class Provider implements EnvironmentProvider { + + @Override + public Class getEnvironment(ItemStack stack) { + if (stack == null) return null; + if (stack.getItem() == ItemEnum.PARTITEM.getItem() + && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) + return Environment.class; return null; - if(stack.getItem() == ItemEnum.PARTITEM.getItem() && stack.getItemDamage() == PartEnum.FLUIDEXPORT.ordinal()) - return Enviroment.class; - return null; + } } - } diff --git a/src/main/scala/extracells/integration/opencomputers/DriverOreDictExportBus.java b/src/main/scala/extracells/integration/opencomputers/DriverOreDictExportBus.java index 99d484112..1cb979c83 100644 --- a/src/main/scala/extracells/integration/opencomputers/DriverOreDictExportBus.java +++ b/src/main/scala/extracells/integration/opencomputers/DriverOreDictExportBus.java @@ -1,114 +1,108 @@ package extracells.integration.opencomputers; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.parts.IPart; import appeng.api.parts.IPartHost; import extracells.part.PartOreDictExporter; import extracells.registries.ItemEnum; import extracells.registries.PartEnum; import li.cil.oc.api.Network; -import li.cil.oc.api.driver.EnvironmentAware; +import li.cil.oc.api.driver.EnvironmentProvider; import li.cil.oc.api.driver.NamedBlock; +import li.cil.oc.api.driver.SidedBlock; import li.cil.oc.api.machine.Arguments; import li.cil.oc.api.machine.Callback; import li.cil.oc.api.machine.Context; -import li.cil.oc.api.network.Environment; import li.cil.oc.api.network.Visibility; import li.cil.oc.api.prefab.ManagedEnvironment; -import net.minecraft.item.ItemStack; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -public class DriverOreDictExportBus implements li.cil.oc.api.driver.Block, EnvironmentAware{ - - @Override - public boolean worksWith(World world, int x, int y, int z) { - return getExportBus(world, x, y, z, ForgeDirection.UNKNOWN) != null; - } - - @Override - public ManagedEnvironment createEnvironment(World world, int x, int y, int z) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - return new Enviroment((IPartHost) tile); - } - - private static PartOreDictExporter getExportBus(World world, int x, int y, int z, ForgeDirection dir){ - TileEntity tile = world.getTileEntity(x, y, z); - if (tile == null || (!(tile instanceof IPartHost))) - return null; - IPartHost host = (IPartHost) tile; - if(dir == null || dir == ForgeDirection.UNKNOWN){ - for (ForgeDirection side: ForgeDirection.VALID_DIRECTIONS){ - IPart part = host.getPart(side); - if (part != null && part instanceof PartOreDictExporter) - return (PartOreDictExporter) part; - } - return null; - }else{ - IPart part = host.getPart(dir); - return part == null ? null : (PartOreDictExporter) part; - } - } - - public class Enviroment extends ManagedEnvironment implements NamedBlock{ - - protected final TileEntity tile; - protected final IPartHost host; - - public Enviroment(IPartHost host){ - tile = (TileEntity) host; - this.host = host; - setNode(Network.newNode(this, Visibility.Network). - withComponent("me_exportbus"). - create()); - } - - @Callback(doc = "function(side:number):string -- Get the configuration of the ore dict export bus pointing in the specified direction.") - public Object[] getOreConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{null, "unknown side"}; - PartOreDictExporter part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{null, "no export bus"}; - return new Object[]{part.filter}; - } - - @Callback(doc = "function(side:number[, filter:string]):boolean -- Set the configuration of the ore dict export bus pointing in the specified direction.") - public Object[] setOreConfiguration(Context context, Arguments args){ - ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); - if (dir == null || dir == ForgeDirection.UNKNOWN) - return new Object[]{false, "unknown side"}; - PartOreDictExporter part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); - if (part == null) - return new Object[]{false, "no export bus"}; - part.filter = args.optString(1, ""); - context.pause(0.5); - return new Object[]{true}; - } - - - @Override - public String preferredName() { - return "me_exportbus"; - } - - @Override - public int priority() { - return 0; - } - - } - - @Override - public Class providedEnvironment(ItemStack stack) { - if(stack == null) - return null; - if(stack.getItem() == ItemEnum.PARTITEM.getItem() && stack.getItemDamage() == PartEnum.OREDICTEXPORTBUS.ordinal()) - return Enviroment.class; - return null; - } +public class DriverOreDictExportBus implements SidedBlock { + + @Override + public boolean worksWith(World world, int x, int y, int z, ForgeDirection side) { + return getExportBus(world, x, y, z, side) != null; + } + + @Override + public ManagedEnvironment createEnvironment(World world, int x, int y, int z, ForgeDirection side) { + TileEntity tile = world.getTileEntity(x, y, z); + if (!(tile instanceof IPartHost)) return null; + return new Environment((IPartHost) tile); + } + + private static PartOreDictExporter getExportBus(World world, int x, int y, int z, ForgeDirection dir) { + TileEntity tile = world.getTileEntity(x, y, z); + if ((!(tile instanceof IPartHost))) return null; + IPartHost host = (IPartHost) tile; + if (dir == null || dir == ForgeDirection.UNKNOWN) { + for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS) { + IPart part = host.getPart(side); + if (part instanceof PartOreDictExporter) return (PartOreDictExporter) part; + } + return null; + } else { + IPart part = host.getPart(dir); + return part instanceof PartOreDictExporter ? (PartOreDictExporter) part : null; + } + } + + public static class Environment extends ManagedEnvironment implements NamedBlock { + + protected final TileEntity tile; + protected final IPartHost host; + + Environment(IPartHost host) { + tile = (TileEntity) host; + this.host = host; + setNode(Network.newNode(this, Visibility.Network).withComponent("me_exportbus").create()); + } + + @Callback( + doc = "function(side:number):string -- Get the configuration of the ore dict export bus pointing in the specified direction.") + public Object[] getOreConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { null, "unknown side" }; + PartOreDictExporter part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { null, "no export bus" }; + return new Object[] { part.getFilter() }; + } + + @Callback( + doc = "function(side:number[, filter:string]):boolean -- Set the configuration of the ore dict export bus pointing in the specified direction.") + public Object[] setOreConfiguration(Context context, Arguments args) { + ForgeDirection dir = ForgeDirection.getOrientation(args.checkInteger(0)); + if (dir == null || dir == ForgeDirection.UNKNOWN) return new Object[] { false, "unknown side" }; + PartOreDictExporter part = getExportBus(tile.getWorldObj(), tile.xCoord, tile.yCoord, tile.zCoord, dir); + if (part == null) return new Object[] { false, "no export bus" }; + part.setFilter(args.optString(1, "")); + + context.pause(0.5); + return new Object[] { true }; + } + + @Override + public String preferredName() { + return "me_exportbus"; + } + + @Override + public int priority() { + return 0; + } + } + + static class Provider implements EnvironmentProvider { + @Override + public Class getEnvironment(ItemStack stack) { + if (stack.getItem() == ItemEnum.PARTITEM.getItem() + && stack.getItemDamage() == PartEnum.OREDICTEXPORTBUS.ordinal()) + return Environment.class; + return null; + } + } } diff --git a/src/main/scala/extracells/integration/opencomputers/ExtraCellsPathProvider.scala b/src/main/scala/extracells/integration/opencomputers/ExtraCellsPathProvider.scala index 733c5b3a1..6831a809b 100644 --- a/src/main/scala/extracells/integration/opencomputers/ExtraCellsPathProvider.scala +++ b/src/main/scala/extracells/integration/opencomputers/ExtraCellsPathProvider.scala @@ -8,13 +8,19 @@ import li.cil.oc.api.prefab.{ItemStackTabIconRenderer, ResourceContentProvider} import net.minecraft.item.ItemStack import net.minecraft.world.World - -object ExtraCellsPathProvider extends PathProvider{ +object ExtraCellsPathProvider extends PathProvider { Manual.addProvider(this) Manual.addProvider(new ResourceContentProvider("extracells", "doc/")) - Manual.addTab(new ItemStackTabIconRenderer(new ItemStack(ItemEnum.FLUIDSTORAGE.getItem)),"itemGroup.Extra_Cells", "extracells/%LANGUAGE%/index.md") + Manual.addTab( + new ItemStackTabIconRenderer(new ItemStack(ItemEnum.FLUIDSTORAGE.getItem)), + "itemGroup.Extra_Cells", + "extracells/%LANGUAGE%/index.md" + ) - override def pathFor(stack: ItemStack): String = if(stack != null && stack.getItem == ItemOCUpgrade) "extracells/%LANGUAGE%/me_upgrade.md" else null + override def pathFor(stack: ItemStack): String = if ( + stack != null && stack.getItem == ItemOCUpgrade + ) "extracells/%LANGUAGE%/me_upgrade.md" + else null override def pathFor(world: World, x: Int, y: Int, z: Int): String = null } diff --git a/src/main/scala/extracells/integration/opencomputers/OCRecipes.java b/src/main/scala/extracells/integration/opencomputers/OCRecipes.java index 1d04660f6..06eb89b82 100644 --- a/src/main/scala/extracells/integration/opencomputers/OCRecipes.java +++ b/src/main/scala/extracells/integration/opencomputers/OCRecipes.java @@ -1,33 +1,59 @@ package extracells.integration.opencomputers; +import net.minecraft.init.Items; +import net.minecraft.item.ItemStack; import appeng.api.AEApi; import cpw.mods.fml.common.registry.GameRegistry; import li.cil.oc.api.API; -import net.minecraft.init.Items; -import net.minecraft.item.ItemStack; public class OCRecipes { - public static void loadRecipes(){ - GameRegistry.addShapedRecipe(new ItemStack(GameRegistry.findItem("extracells", "oc.upgrade")), "DAD", "MBM", "DCD", - 'A', AEApi.instance().definitions().materials().wireless().maybeStack(1).get(), - 'C', API.items.get("printedCircuitBoard").createItemStack(1), - 'B', API.items.get("wlanCard").createItemStack(1), - 'D', Items.diamond, - 'M', API.items.get("chip3").createItemStack(1)); - GameRegistry.addShapedRecipe(new ItemStack(GameRegistry.findItem("extracells", "oc.upgrade"), 1, 1), "DAD", "MBM", "DCD", - 'A', AEApi.instance().definitions().materials().wireless().maybeStack(1).get(), - 'C', API.items.get("printedCircuitBoard").createItemStack(1), - 'B', API.items.get("wlanCard").createItemStack(1), - 'D', Items.gold_ingot, - 'M', API.items.get("chip2").createItemStack(1)); - GameRegistry.addShapedRecipe(new ItemStack(GameRegistry.findItem("extracells", "oc.upgrade"), 1, 2), "DAD", "MBM", "DCD", - 'A', AEApi.instance().definitions().materials().wireless().maybeStack(1).get(), - 'C', API.items.get("printedCircuitBoard").createItemStack(1), - 'B', API.items.get("wlanCard").createItemStack(1), - 'D', Items.iron_ingot, - 'M', API.items.get("chip1").createItemStack(1)); + public static void loadRecipes() { + GameRegistry.addShapedRecipe( + new ItemStack(GameRegistry.findItem("extracells", "oc.upgrade")), + "DAD", + "MBM", + "DCD", + 'A', + AEApi.instance().definitions().materials().wireless().maybeStack(1).get(), + 'C', + API.items.get("printedCircuitBoard").createItemStack(1), + 'B', + API.items.get("wlanCard").createItemStack(1), + 'D', + Items.diamond, + 'M', + API.items.get("chip3").createItemStack(1)); + GameRegistry.addShapedRecipe( + new ItemStack(GameRegistry.findItem("extracells", "oc.upgrade"), 1, 1), + "DAD", + "MBM", + "DCD", + 'A', + AEApi.instance().definitions().materials().wireless().maybeStack(1).get(), + 'C', + API.items.get("printedCircuitBoard").createItemStack(1), + 'B', + API.items.get("wlanCard").createItemStack(1), + 'D', + Items.gold_ingot, + 'M', + API.items.get("chip2").createItemStack(1)); + GameRegistry.addShapedRecipe( + new ItemStack(GameRegistry.findItem("extracells", "oc.upgrade"), 1, 2), + "DAD", + "MBM", + "DCD", + 'A', + AEApi.instance().definitions().materials().wireless().maybeStack(1).get(), + 'C', + API.items.get("printedCircuitBoard").createItemStack(1), + 'B', + API.items.get("wlanCard").createItemStack(1), + 'D', + Items.iron_ingot, + 'M', + API.items.get("chip1").createItemStack(1)); } - } diff --git a/src/main/scala/extracells/integration/opencomputers/OCUtils.scala b/src/main/scala/extracells/integration/opencomputers/OCUtils.scala index c834d2ab9..18817f932 100644 --- a/src/main/scala/extracells/integration/opencomputers/OCUtils.scala +++ b/src/main/scala/extracells/integration/opencomputers/OCUtils.scala @@ -4,7 +4,6 @@ import li.cil.oc.api.API import li.cil.oc.common.item.data.{DroneData, RobotData} import net.minecraft.item.{Item, ItemStack} - object OCUtils { def isRobot(stack: ItemStack): Boolean = { @@ -20,22 +19,23 @@ object OCUtils { } def getComponent(robot: RobotData, item: Item, meta: Int): ItemStack = { - for(component <- robot.components){ - if(component != null && component.getItem == item) return component + for (component <- robot.components) { + if (component != null && component.getItem == item) return component } null } - def getComponent(robot: RobotData, item: Item): ItemStack = getComponent(robot, item, 0) + def getComponent(robot: RobotData, item: Item): ItemStack = + getComponent(robot, item, 0) def getComponent(drone: DroneData, item: Item, meta: Int): ItemStack = { - for(component <- drone.components){ - if(component != null && component.getItem == item) return component + for (component <- drone.components) { + if (component != null && component.getItem == item) return component } null } - def getComponent(drone: DroneData, item: Item): ItemStack = getComponent(drone, item, 0) - + def getComponent(drone: DroneData, item: Item): ItemStack = + getComponent(drone, item, 0) } diff --git a/src/main/scala/extracells/integration/opencomputers/OpenComputers.scala b/src/main/scala/extracells/integration/opencomputers/OpenComputers.scala index 50ebb0300..423cfa25f 100644 --- a/src/main/scala/extracells/integration/opencomputers/OpenComputers.scala +++ b/src/main/scala/extracells/integration/opencomputers/OpenComputers.scala @@ -5,19 +5,28 @@ import extracells.integration.Integration import extracells.item.ItemOCUpgrade import li.cil.oc.api.Driver object OpenComputers { - - def init{ - Driver.add(new DriverFluidExportBus) - Driver.add(new DriverOreDictExportBus) - Driver.add(new DriverFluidInterface) - if(Integration.Mods.MEKANISMGAS.isEnabled){ - Driver.add(new DriverGasExportBus) - Driver.add(new DriverGasImportBus) - } - Driver.add(ItemOCUpgrade) - AEApi.instance.registries.wireless.registerWirelessHandler(WirelessHandlerUpgradeAE) - OCRecipes.loadRecipes - ExtraCellsPathProvider - } + + def init() { + Driver.add(new DriverFluidExportBus) + Driver.add(new DriverFluidExportBus.Provider) + Driver.add(new DriverFluidImportBus) + Driver.add(new DriverFluidImportBus.Provider) + Driver.add(new DriverOreDictExportBus) + Driver.add(new DriverOreDictExportBus.Provider) + Driver.add(new DriverFluidInterface) + Driver.add(new DriverFluidInterface.Provider) + if (Integration.Mods.MEKANISMGAS.isEnabled) { + Driver.add(new DriverGasExportBus) + Driver.add(new DriverGasExportBus.Provider) + Driver.add(new DriverGasImportBus) + Driver.add(new DriverGasImportBus.Provider) + } + Driver.add(ItemOCUpgrade) + Driver.add(ItemOCUpgrade.Provider) + AEApi.instance.registries.wireless + .registerWirelessHandler(WirelessHandlerUpgradeAE) + OCRecipes.loadRecipes() + ExtraCellsPathProvider + } } diff --git a/src/main/scala/extracells/integration/opencomputers/UpgradeAE.scala b/src/main/scala/extracells/integration/opencomputers/UpgradeAE.scala index c7d758986..e64d1fe20 100644 --- a/src/main/scala/extracells/integration/opencomputers/UpgradeAE.scala +++ b/src/main/scala/extracells/integration/opencomputers/UpgradeAE.scala @@ -12,7 +12,7 @@ import appeng.api.util.WorldCoord import appeng.tile.misc.TileSecurity import extracells.item.ItemOCUpgrade import li.cil.oc.api.Network -import li.cil.oc.api.driver.EnvironmentHost +import li.cil.oc.api.network.EnvironmentHost import li.cil.oc.api.internal.{Agent, Database, Drone, Robot} import li.cil.oc.api.machine.{Arguments, Callback, Context} import li.cil.oc.api.network._ @@ -25,32 +25,39 @@ import net.minecraftforge.fluids.FluidContainerRegistry import scala.collection.JavaConversions._ +class UpgradeAE(host: EnvironmentHost) + extends ManagedEnvironment + with appeng.NetworkControl[TileSecurity] + with ec.NetworkControl[TileSecurity] { + val robot: Robot = host match { + case r: Robot => r + case _ => null + } -class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.NetworkControl[TileSecurity] with ec.NetworkControl[TileSecurity]{ - val robot: Robot = - if (host.isInstanceOf[Robot]) - host.asInstanceOf[Robot] - else - null - - val drone: Drone = - if (host.isInstanceOf[Drone]) - host.asInstanceOf[Drone] - else - null + val drone: Drone = host match { + case d: Drone => d + case _ => null + } var isActive = false val agent: Agent = host.asInstanceOf[Agent] - setNode(Network.newNode(this, Visibility.Network).withConnector().withComponent("upgrade_me", Visibility.Neighbors).create()); + + setNode( + Network + .newNode(this, Visibility.Network) + .withConnector() + .withComponent("upgrade_me", Visibility.Neighbors) + .create() + ) def getComponent: ItemStack = { if (robot != null) return robot.getStackInSlot(robot.componentSlot(node.address)) - else if(drone != null){ + else if (drone != null) { val i = drone.internalComponents.iterator - while (i.hasNext){ + while (i.hasNext) { val item = i.next - if(item != null && item.getItem == ItemOCUpgrade) + if (item != null && item.getItem == ItemOCUpgrade) return item } } @@ -60,8 +67,10 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne def getSecurity: IGridHost = { if (host.world.isRemote) return null val component = getComponent - val sec = AEApi.instance.registries.locatable.getLocatableBy(getAEKey(component)).asInstanceOf[IGridHost] - if(checkRange(component, sec)) + val sec = AEApi.instance.registries.locatable + .getLocatableBy(getAEKey(component)) + .asInstanceOf[IGridHost] + if (checkRange(component, sec)) sec else null @@ -71,19 +80,36 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne val gridNode: IGridNode = sec.getGridNode(ForgeDirection.UNKNOWN) if (gridNode == null) return false val grid = gridNode.getGrid - if(grid == null) return false - stack.getItemDamage match{ + if (grid == null) return false + stack.getItemDamage match { case 0 => - grid.getMachines(AEApi.instance.definitions.blocks.wireless.maybeEntity.get.asInstanceOf[Class[_ <: IGridHost]]).iterator.hasNext + grid + .getMachines( + AEApi.instance.definitions.blocks.wireless.maybeEntity.get + .asInstanceOf[Class[_ <: IGridHost]] + ) + .iterator + .hasNext case 1 => val gridBlock = gridNode.getGridBlock if (gridBlock == null) return false val loc = gridBlock.getLocation if (loc == null) return false - for (node <- grid.getMachines(AEApi.instance.definitions.blocks.wireless.maybeEntity.get.asInstanceOf[Class[_ <: IGridHost]])) { - val accessPoint: IWirelessAccessPoint = node.getMachine.asInstanceOf[IWirelessAccessPoint] - val distance: WorldCoord = accessPoint.getLocation.subtract(agent.xPosition.toInt, agent.yPosition.toInt, agent.zPosition.toInt) - val squaredDistance: Int = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z + for ( + node <- grid.getMachines( + AEApi.instance.definitions.blocks.wireless.maybeEntity.get + .asInstanceOf[Class[_ <: IGridHost]] + ) + ) { + val accessPoint: IWirelessAccessPoint = + node.getMachine.asInstanceOf[IWirelessAccessPoint] + val distance: WorldCoord = accessPoint.getLocation.subtract( + agent.xPosition.toInt, + agent.yPosition.toInt, + agent.zPosition.toInt + ) + val squaredDistance: Int = + distance.x * distance.x + distance.y * distance.y + distance.z * distance.z val range = accessPoint.getRange if (squaredDistance <= range * range) return true } @@ -93,10 +119,21 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne if (gridBlock == null) return false val loc = gridBlock.getLocation if (loc == null) return false - for (node <- grid.getMachines(AEApi.instance.definitions.blocks.wireless.maybeEntity.get.asInstanceOf[Class[_ <: IGridHost]])) { - val accessPoint: IWirelessAccessPoint = node.getMachine.asInstanceOf[IWirelessAccessPoint] - val distance: WorldCoord = accessPoint.getLocation.subtract(agent.xPosition.toInt, agent.yPosition.toInt, agent.zPosition.toInt) - val squaredDistance: Int = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z + for ( + node <- grid.getMachines( + AEApi.instance.definitions.blocks.wireless.maybeEntity.get + .asInstanceOf[Class[_ <: IGridHost]] + ) + ) { + val accessPoint: IWirelessAccessPoint = + node.getMachine.asInstanceOf[IWirelessAccessPoint] + val distance: WorldCoord = accessPoint.getLocation.subtract( + agent.xPosition.toInt, + agent.yPosition.toInt, + agent.zPosition.toInt + ) + val squaredDistance: Int = + distance.x * distance.x + distance.y * distance.y + distance.z * distance.z val range = accessPoint.getRange / 2 if (squaredDistance <= range * range) return true } @@ -108,7 +145,8 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne if (host.world.isRemote) return null val securityTerminal = getSecurity if (securityTerminal == null) return null - val gridNode: IGridNode = securityTerminal.getGridNode(ForgeDirection.UNKNOWN) + val gridNode: IGridNode = + securityTerminal.getGridNode(ForgeDirection.UNKNOWN) if (gridNode == null) return null gridNode.getGrid } @@ -116,15 +154,12 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne def getAEKey(stack: ItemStack): Long = { try { return WirelessHandlerUpgradeAE.getEncryptionKey(stack).toLong - } - catch { - case ignored: Throwable => { - } + } catch { + case _: Throwable => } 0L } - override def tile: TileSecurity = { val sec = getSecurity if (sec == null) @@ -135,7 +170,9 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne if (gridBlock == null) throw new SecurityException("No Security Station") val coord = gridBlock.getLocation if (coord == null) throw new SecurityException("No Security Station") - val tileSecurity = coord.getWorld.getTileEntity(coord.x, coord.y, coord.z).asInstanceOf[TileSecurity] + val tileSecurity = coord.getWorld + .getTileEntity(coord.x, coord.y, coord.z) + .asInstanceOf[TileSecurity] if (tileSecurity == null) throw new SecurityException("No Security Station") tileSecurity } @@ -156,36 +193,45 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne storage.getItemInventory } - @Callback(doc = "function([number:amount]):number -- Transfer selected items to your ae system.") + @Callback(doc = + "function([number:amount]):number -- Transfer selected items to your ae system." + ) def sendItems(context: Context, args: Arguments): Array[AnyRef] = { val selected = agent.selectedSlot val invRobot = agent.mainInventory - if (invRobot.getSizeInventory <= 0) return Array(0.underlying.asInstanceOf[AnyRef]) + if (invRobot.getSizeInventory <= 0) return Array(0.underlying) val stack = invRobot.getStackInSlot(selected) val inv = getItemInventory - if (stack == null || inv == null) return Array(0.underlying.asInstanceOf[AnyRef]) + if (stack == null || inv == null) return Array(0.underlying) val amount = Math.min(args.optInteger(0, 64), stack.stackSize) val stack2 = stack.copy stack2.stackSize = amount - val notInjectet = inv.injectItems(AEApi.instance.storage.createItemStack(stack2), Actionable.MODULATE, new MachineSource(tile)) - if (notInjectet == null){ + val notInjected = inv.injectItems( + AEApi.instance.storage.createItemStack(stack2), + Actionable.MODULATE, + new MachineSource(tile) + ) + if (notInjected == null) { stack.stackSize -= amount if (stack.stackSize <= 0) invRobot.setInventorySlotContents(selected, null) else invRobot.setInventorySlotContents(selected, stack) - return Array(amount.underlying.asInstanceOf[AnyRef]) - }else{ - stack.stackSize = stack.stackSize - amount + notInjectet.getStackSize.toInt + Array(amount.underlying) + } else { + stack.stackSize = + stack.stackSize - amount + notInjected.getStackSize.toInt if (stack.stackSize <= 0) invRobot.setInventorySlotContents(selected, null) else invRobot.setInventorySlotContents(selected, stack) - return Array((stack2.stackSize - notInjectet.getStackSize).underlying.asInstanceOf[AnyRef]) + Array((stack2.stackSize - notInjected.getStackSize).underlying) } } - @Callback(doc = "function(database:address, entry:number[, number:amount]):number -- Get items from your ae system.") + @Callback(doc = + "function(database:address, entry:number[, number:amount]):number -- Get items from your ae system." + ) def requestItems(context: Context, args: Arguments): Array[AnyRef] = { val address = args.checkString(0) @@ -193,29 +239,30 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne val amount = args.optInteger(2, 64) val selected = agent.selectedSlot val invRobot = agent.mainInventory - if (invRobot.getSizeInventory <= 0) return Array(0.underlying.asInstanceOf[AnyRef]) + if (invRobot.getSizeInventory <= 0) return Array(0.underlying) val inv = getItemInventory - if (inv == null) return Array(0.underlying.asInstanceOf[AnyRef]) + if (inv == null) return Array(0.underlying) val n: Node = node.network.node(address) if (n == null) throw new IllegalArgumentException("no such component") - if (!(n.isInstanceOf[Component])) throw new IllegalArgumentException("no such component") - val component: Component = n.asInstanceOf[Component] + if (!n.isInstanceOf[Component]) + throw new IllegalArgumentException("no such component") val env: Environment = n.host - if (!(env.isInstanceOf[Database])) throw new IllegalArgumentException("not a database") + if (!env.isInstanceOf[Database]) + throw new IllegalArgumentException("not a database") val database: Database = env.asInstanceOf[Database] val sel = invRobot.getStackInSlot(selected) val inSlot = - if (sel == null) - 0 - else - sel.stackSize + if (sel == null) + 0 + else + sel.stackSize val maxSize = - if (sel == null) - 64 - else - sel.getMaxStackSize + if (sel == null) + 64 + else + sel.getMaxStackSize val stack = database.getStackInSlot(entry - 1) - if(stack == null) return Array(0.underlying.asInstanceOf[AnyRef]) + if (stack == null) return Array(0.underlying) stack.stackSize = Math.min(amount, maxSize - inSlot) val stack2 = stack.copy stack2.stackSize = 1 @@ -224,69 +271,92 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne val sel3 = sel.copy sel3.stackSize = 1 sel3 - }else + } else null - if(sel != null && !ItemStack.areItemStacksEqual(sel2, stack2)) return Array(0.underlying.asInstanceOf[AnyRef]) - val extracted = inv.extractItems(AEApi.instance.storage.createItemStack(stack), Actionable.MODULATE, new MachineSource(tile)) - if(extracted == null) return Array(0.underlying.asInstanceOf[AnyRef]) + if (sel != null && !ItemStack.areItemStacksEqual(sel2, stack2)) + return Array(0.underlying) + val extracted = inv.extractItems( + AEApi.instance.storage.createItemStack(stack), + Actionable.MODULATE, + new MachineSource(tile) + ) + if (extracted == null) return Array(0.underlying) val ext = extracted.getStackSize.toInt stack.stackSize = inSlot + ext invRobot.setInventorySlotContents(selected, stack) - Array(ext.underlying.asInstanceOf[AnyRef]) + Array(ext.underlying) } - @Callback(doc = "function([number:amount]):number -- Transfer selecte fluid to your ae system.") + @Callback(doc = + "function([number:amount]):number -- Transfer selecte fluid to your ae system." + ) def sendFluids(context: Context, args: Arguments): Array[AnyRef] = { val selected = agent.selectedTank val tanks = agent.tank - if (tanks.tankCount <= 0) return Array(0.underlying.asInstanceOf[AnyRef]) + if (tanks.tankCount <= 0) return Array(0.underlying) val tank = tanks.getFluidTank(selected) val inv = getFluidInventory - if (tank == null || inv == null || tank.getFluid == null) return Array(0.underlying.asInstanceOf[AnyRef]) - val amount = Math.min(args.optInteger(0, tank.getCapacity), tank.getFluidAmount) + if (tank == null || inv == null || tank.getFluid == null) + return Array(0.underlying) + val amount = + Math.min(args.optInteger(0, tank.getCapacity), tank.getFluidAmount) val fluid = tank.getFluid val fluid2 = fluid.copy fluid2.amount = amount - val notInjectet = inv.injectItems(AEApi.instance.storage.createFluidStack(fluid2), Actionable.MODULATE, new MachineSource(tile)) - if (notInjectet == null){ + val notInjectet = inv.injectItems( + AEApi.instance.storage.createFluidStack(fluid2), + Actionable.MODULATE, + new MachineSource(tile) + ) + if (notInjectet == null) { tank.drain(amount, true) - Array(amount.underlying.asInstanceOf[AnyRef]) - }else{ + Array(amount.underlying) + } else { tank.drain(amount - notInjectet.getStackSize.toInt, true) - Array((amount - notInjectet.getStackSize).underlying.asInstanceOf[AnyRef]) + Array((amount - notInjectet.getStackSize).underlying) } } - @Callback(doc = "function(database:address, entry:number[, number:amount]):number -- Get fluid from your ae system.") + @Callback(doc = + "function(database:address, entry:number[, number:amount]):number -- Get fluid from your ae system." + ) def requestFluids(context: Context, args: Arguments): Array[AnyRef] = { val address = args.checkString(0) val entry = args.checkInteger(1) val amount = args.optInteger(2, FluidContainerRegistry.BUCKET_VOLUME) val tanks = agent.tank val selected = agent.selectedTank - if (tanks.tankCount <= 0) return Array(0.underlying.asInstanceOf[AnyRef]) + if (tanks.tankCount <= 0) return Array(0.underlying) val tank = tanks.getFluidTank(selected) val inv = getFluidInventory - if (tank == null || inv == null) return Array(0.underlying.asInstanceOf[AnyRef]) + if (tank == null || inv == null) return Array(0.underlying) val n: Node = node.network.node(address) if (n == null) throw new IllegalArgumentException("no such component") - if (!(n.isInstanceOf[Component])) throw new IllegalArgumentException("no such component") - val component: Component = n.asInstanceOf[Component] + if (!n.isInstanceOf[Component]) + throw new IllegalArgumentException("no such component") val env: Environment = n.host - if (!(env.isInstanceOf[Database])) throw new IllegalArgumentException("not a database") + if (!env.isInstanceOf[Database]) + throw new IllegalArgumentException("not a database") val database: Database = env.asInstanceOf[Database] - val fluid = FluidContainerRegistry.getFluidForFilledItem(database.getStackInSlot(entry - 1)) + val fluid = FluidContainerRegistry.getFluidForFilledItem( + database.getStackInSlot(entry - 1) + ) fluid.amount = amount val fluid2 = fluid.copy() fluid2.amount = tank.fill(fluid, false) - if (fluid2.amount == 0) return Array(0.underlying.asInstanceOf[AnyRef]) - val extracted = inv.extractItems(AEApi.instance.storage.createFluidStack(fluid2), Actionable.MODULATE, new MachineSource(tile)) - if (extracted == 0) return Array(0.underlying.asInstanceOf[AnyRef]) - Array(tank.fill(extracted.getFluidStack, true).underlying.asInstanceOf[AnyRef]) + if (fluid2.amount == 0) return Array(0.underlying) + val extracted = inv.extractItems( + AEApi.instance.storage.createFluidStack(fluid2), + Actionable.MODULATE, + new MachineSource(tile) + ) + if (extracted == null) return Array(0.underlying) + Array(tank.fill(extracted.getFluidStack, true).underlying) } - - @Callback(doc = "function():boolean -- Return true if the card is linket to your ae network.") + @Callback(doc = + "function():boolean -- Return true if the card is linket to your ae network." + ) def isLinked(context: Context, args: Arguments): Array[AnyRef] = { val isLinked = getGrid != null Array(boolean2Boolean(isLinked)) @@ -301,12 +371,12 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne } } - def getEnergy = { + private def getEnergy = { val c = getComponent if (c == null) .0 else - c.getItemDamage match{ + c.getItemDamage match { case 0 => .6 case 1 => .3 case _ => .05 @@ -317,8 +387,7 @@ class UpgradeAE(host: EnvironmentHost) extends ManagedEnvironment with appeng.Ne super.onMessage(message) if (message.name == "computer.stopped") { isActive = false - } - else if (message.name == "computer.started") { + } else if (message.name == "computer.started") { isActive = true } } diff --git a/src/main/scala/extracells/integration/opencomputers/UpgradeItemAEBase.scala b/src/main/scala/extracells/integration/opencomputers/UpgradeItemAEBase.scala index dc43bc2d9..821b35bed 100644 --- a/src/main/scala/extracells/integration/opencomputers/UpgradeItemAEBase.scala +++ b/src/main/scala/extracells/integration/opencomputers/UpgradeItemAEBase.scala @@ -3,21 +3,27 @@ package extracells.integration.opencomputers import cpw.mods.fml.common.Optional.{Interface, InterfaceList, Method} import li.cil.oc.api.CreativeTab import li.cil.oc.api.driver.item.{HostAware, Slot} -import li.cil.oc.api.driver.{EnvironmentAware, EnvironmentHost} +import li.cil.oc.api.driver.EnvironmentProvider +import li.cil.oc.api.network.EnvironmentHost import li.cil.oc.api.internal.{Drone, Robot} import li.cil.oc.api.network.{Environment, ManagedEnvironment} import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.{EnumRarity, Item, ItemStack} import net.minecraft.nbt.NBTTagCompound -@InterfaceList(Array( - new Interface(iface = "li.cil.oc.api.driver.item.HostAware", modid = "OpenComputers", striprefs = true), - new Interface(iface = "li.cil.oc.api.driver.EnvironmentAware", modid = "OpenComputers", striprefs = true) -)) -trait UpgradeItemAEBase extends Item with HostAware with EnvironmentAware{ +@InterfaceList( + Array( + new Interface( + iface = "li.cil.oc.api.driver.item.HostAware", + modid = "OpenComputers", + striprefs = true + ) + ) +) +trait UpgradeItemAEBase extends Item with HostAware { @Method(modid = "OpenComputers") - override def setCreativeTab(creativeTabs: CreativeTabs): Item ={ + override def setCreativeTab(creativeTabs: CreativeTabs): Item = { super.setCreativeTab(CreativeTab.instance) } @@ -27,31 +33,37 @@ trait UpgradeItemAEBase extends Item with HostAware with EnvironmentAware{ case 0 => 2 case 1 => 1 case _ => 0 - } + } @Method(modid = "OpenComputers") override def slot(stack: ItemStack): String = Slot.Upgrade @Method(modid = "OpenComputers") - override def worksWith(stack: ItemStack): Boolean = stack != null && stack.getItem == this + override def worksWith(stack: ItemStack): Boolean = + stack != null && stack.getItem == this @Method(modid = "OpenComputers") - override def createEnvironment(stack: ItemStack, host: EnvironmentHost): ManagedEnvironment = { - if (stack != null && stack.getItem == this && worksWith(stack, host.getClass)) + override def createEnvironment( + stack: ItemStack, + host: EnvironmentHost + ): ManagedEnvironment = { + if ( + stack != null && stack.getItem == this && worksWith(stack, host.getClass) + ) new UpgradeAE(host) else null } - override def getRarity (stack: ItemStack) = + override def getRarity(stack: ItemStack): EnumRarity = stack.getItemDamage match { case 0 => EnumRarity.rare case 1 => EnumRarity.uncommon case _ => super.getRarity(stack) - } + } @Method(modid = "OpenComputers") - override def dataTag(stack: ItemStack) = { + override def dataTag(stack: ItemStack): NBTTagCompound = { if (!stack.hasTagCompound) { stack.setTagCompound(new NBTTagCompound) } @@ -63,15 +75,28 @@ trait UpgradeItemAEBase extends Item with HostAware with EnvironmentAware{ } @Method(modid = "OpenComputers") - override def worksWith(stack: ItemStack, host: Class[_ <: EnvironmentHost]): Boolean = - worksWith(stack) && host != null && (classOf[Robot].isAssignableFrom(host) || classOf[Drone].isAssignableFrom(host)) + override def worksWith( + stack: ItemStack, + host: Class[_ <: EnvironmentHost] + ): Boolean = + worksWith(stack) && host != null && (classOf[Robot].isAssignableFrom( + host + ) || classOf[Drone].isAssignableFrom(host)) - @Method(modid = "OpenComputers") - override def providedEnvironment(stack: ItemStack): Class[_ <: Environment] = { - if (stack != null && stack.getItem == this) - classOf[UpgradeAE] - else - null + @InterfaceList( + Array( + new Interface( + iface = "li.cil.oc.api.driver.EnvironmentProvider", + modid = "OpenComputers", + striprefs = true + ) + ) + ) + object Provider extends EnvironmentProvider { + @Method(modid = "OpenComputers") + override def getEnvironment(stack: ItemStack): Class[_] = + if (worksWith(stack)) + classOf[UpgradeAE] + else null } - } diff --git a/src/main/scala/extracells/integration/opencomputers/WirelessHandlerUpgradeAE.scala b/src/main/scala/extracells/integration/opencomputers/WirelessHandlerUpgradeAE.scala index aac610eed..860ef6b9b 100644 --- a/src/main/scala/extracells/integration/opencomputers/WirelessHandlerUpgradeAE.scala +++ b/src/main/scala/extracells/integration/opencomputers/WirelessHandlerUpgradeAE.scala @@ -8,29 +8,46 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound - -object WirelessHandlerUpgradeAE extends IWirelessTermHandler{ +object WirelessHandlerUpgradeAE extends IWirelessTermHandler { override def canHandle(itemStack: ItemStack): Boolean = { if (itemStack == null) return false val item = itemStack.getItem if (item == ItemOCUpgrade) return true - (OCUtils.isRobot(itemStack) && OCUtils.getComponent(new RobotData(itemStack), ItemOCUpgrade) != null)|| - (OCUtils.isDrone(itemStack) && OCUtils.getComponent(new DroneData(itemStack), ItemOCUpgrade) != null) + (OCUtils.isRobot(itemStack) && OCUtils.getComponent( + new RobotData(itemStack), + ItemOCUpgrade + ) != null) || + (OCUtils.isDrone(itemStack) && OCUtils.getComponent( + new DroneData(itemStack), + ItemOCUpgrade + ) != null) } - override def usePower(entityPlayer: EntityPlayer, v: Double, itemStack: ItemStack): Boolean = false + override def usePower( + entityPlayer: EntityPlayer, + v: Double, + itemStack: ItemStack + ): Boolean = false override def getConfigManager(itemStack: ItemStack): IConfigManager = null - override def hasPower(entityPlayer: EntityPlayer, v: Double, itemStack: ItemStack): Boolean = true + override def hasPower( + entityPlayer: EntityPlayer, + v: Double, + itemStack: ItemStack + ): Boolean = true - override def setEncryptionKey(itemStack: ItemStack, encKey: String, name: String) { - if(OCUtils.isRobot(itemStack)){ + override def setEncryptionKey( + itemStack: ItemStack, + encKey: String, + name: String + ) { + if (OCUtils.isRobot(itemStack)) { setEncryptionKeyRobot(itemStack, encKey, name) return } - if(OCUtils.isDrone(itemStack)){ + if (OCUtils.isDrone(itemStack)) { setEncryptionKeyDrone(itemStack, encKey, name) return } @@ -40,15 +57,19 @@ object WirelessHandlerUpgradeAE extends IWirelessTermHandler{ } override def getEncryptionKey(itemStack: ItemStack): String = { - if(OCUtils.isRobot(itemStack)) + if (OCUtils.isRobot(itemStack)) return getEncryptionKeyRobot(itemStack) - if(OCUtils.isDrone(itemStack)) + if (OCUtils.isDrone(itemStack)) return getEncryptionKeyDrone(itemStack) if (!itemStack.hasTagCompound) itemStack.setTagCompound(new NBTTagCompound) itemStack.getTagCompound.getString("key") } - def setEncryptionKeyRobot(itemStack: ItemStack, encKey: String, name: String){ + def setEncryptionKeyRobot( + itemStack: ItemStack, + encKey: String, + name: String + ) { val robot = new RobotData(itemStack) val component = OCUtils.getComponent(robot, ItemOCUpgrade) if (component != null) setEncryptionKey(component, encKey, name); @@ -62,7 +83,11 @@ object WirelessHandlerUpgradeAE extends IWirelessTermHandler{ getEncryptionKey(component) } - def setEncryptionKeyDrone(itemStack: ItemStack, encKey: String, name: String){ + def setEncryptionKeyDrone( + itemStack: ItemStack, + encKey: String, + name: String + ) { val robot = new RobotData(itemStack) val component = OCUtils.getComponent(robot, ItemOCUpgrade) if (component != null) setEncryptionKey(component, encKey, name); diff --git a/src/main/scala/extracells/integration/thaumaticenergistics/ThaumaticEnergistics.scala b/src/main/scala/extracells/integration/thaumaticenergistics/ThaumaticEnergistics.scala index d03790780..31115c6d6 100644 --- a/src/main/scala/extracells/integration/thaumaticenergistics/ThaumaticEnergistics.scala +++ b/src/main/scala/extracells/integration/thaumaticenergistics/ThaumaticEnergistics.scala @@ -1,16 +1,17 @@ package extracells.integration.thaumaticenergistics import net.minecraft.entity.player.EntityPlayer -import thaumicenergistics.api.{IThEWirelessEssentiaTerminal, ThEApi} - +import net.minecraft.item.ItemStack +import thaumicenergistics.api.ThEApi object ThaumaticEnergistics { - def openEssentiaTerminal(player :EntityPlayer, terminal :Any) :Unit = - ThEApi.instance.interact.openWirelessTerminalGui(player, terminal.asInstanceOf[IThEWirelessEssentiaTerminal]) + def openEssentiaTerminal(player: EntityPlayer, terminal: Any): Unit = + ThEApi.instance.interact.openWirelessTerminalGui(player) - def getTerminal = ThEApi.instance.parts.Essentia_Terminal.getStack + def getTerminal: ItemStack = ThEApi.instance.parts.Essentia_Terminal.getStack - def getWirelessTerminal = ThEApi.instance.items.WirelessEssentiaTerminal.getStack + def getWirelessTerminal: ItemStack = + ThEApi.instance.items.WirelessEssentiaTerminal.getStack } diff --git a/src/main/scala/extracells/integration/waila/BlockWailaDataProvider.java b/src/main/scala/extracells/integration/waila/BlockWailaDataProvider.java index 91982f7b9..e64108214 100644 --- a/src/main/scala/extracells/integration/waila/BlockWailaDataProvider.java +++ b/src/main/scala/extracells/integration/waila/BlockWailaDataProvider.java @@ -1,61 +1,54 @@ package extracells.integration.waila; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; +import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.util.List; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; public class BlockWailaDataProvider implements IWailaDataProvider { - @Override - public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, - NBTTagCompound tag, World world, int x, int y, int z) { - if (te != null && te instanceof IWailaTile) { - tag.setTag("WailaTile", - ((IWailaTile) te).getWailaTag(new NBTTagCompound())); - } - return tag; - } - - @Override - public List getWailaBody(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - TileEntity tile = accessor.getTileEntity(); - NBTTagCompound tag = accessor.getNBTData(); - if (tile != null && tile instanceof IWailaTile && tag != null - && tag.hasKey("WailaTile")) { - IWailaTile t = (IWailaTile) tile; - return t.getWailaBody(currenttip, tag.getCompoundTag("WailaTile"), - accessor.getSide()); - } - return currenttip; - } - - @Override - public List getWailaHead(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return currenttip; - } - - @Override - public ItemStack getWailaStack(IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return accessor.getStack(); - } - - @Override - public List getWailaTail(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return currenttip; - } - + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, + int y, int z) { + if (te != null && te instanceof IWailaTile) { + tag.setTag("WailaTile", ((IWailaTile) te).getWailaTag(new NBTTagCompound())); + } + return tag; + } + + @Override + public List getWailaBody(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + TileEntity tile = accessor.getTileEntity(); + NBTTagCompound tag = accessor.getNBTData(); + if (tile != null && tile instanceof IWailaTile && tag != null && tag.hasKey("WailaTile")) { + IWailaTile t = (IWailaTile) tile; + return t.getWailaBody(currenttip, tag.getCompoundTag("WailaTile"), accessor.getSide()); + } + return currenttip; + } + + @Override + public List getWailaHead(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + return currenttip; + } + + @Override + public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) { + return accessor.getStack(); + } + + @Override + public List getWailaTail(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + return currenttip; + } } diff --git a/src/main/scala/extracells/integration/waila/IWailaTile.java b/src/main/scala/extracells/integration/waila/IWailaTile.java index e5ad70b9f..cdcd9a6df 100644 --- a/src/main/scala/extracells/integration/waila/IWailaTile.java +++ b/src/main/scala/extracells/integration/waila/IWailaTile.java @@ -1,15 +1,13 @@ package extracells.integration.waila; +import java.util.List; + import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.common.util.ForgeDirection; -import java.util.List; - public interface IWailaTile { - public List getWailaBody(List list, NBTTagCompound tag, - ForgeDirection side); - - public NBTTagCompound getWailaTag(NBTTagCompound tag); + public List getWailaBody(List list, NBTTagCompound tag, ForgeDirection side); + public NBTTagCompound getWailaTag(NBTTagCompound tag); } diff --git a/src/main/scala/extracells/integration/waila/PartWailaDataProvider.java b/src/main/scala/extracells/integration/waila/PartWailaDataProvider.java index f8ec7aa5a..c121e8f9f 100644 --- a/src/main/scala/extracells/integration/waila/PartWailaDataProvider.java +++ b/src/main/scala/extracells/integration/waila/PartWailaDataProvider.java @@ -1,12 +1,7 @@ package extracells.integration.waila; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartHost; -import appeng.api.parts.SelectedPart; -import extracells.part.PartECBase; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; +import java.util.List; + import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; @@ -16,92 +11,86 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; -import java.util.List; +import appeng.api.parts.IPart; +import appeng.api.parts.IPartHost; +import appeng.api.parts.SelectedPart; +import extracells.part.PartECBase; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; public class PartWailaDataProvider implements IWailaDataProvider { - @Override - public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, - NBTTagCompound tag, World world, int x, int y, int z) { - final MovingObjectPosition mop = retraceBlock(world, player, x, y, z); - - if (mop != null) { - final IPart part = getPart(te, mop); - - if (part != null && part instanceof PartECBase) { - tag.setTag("partEC", - ((PartECBase) part).getWailaTag(new NBTTagCompound())); - } - } - return tag; - } - - private IPart getPart(TileEntity tile, MovingObjectPosition pos) { - if (tile instanceof IPartHost) { - final Vec3 position = pos.hitVec.addVector(-pos.blockX, - -pos.blockY, -pos.blockZ); - final IPartHost host = (IPartHost) tile; - final SelectedPart sp = host.selectPart(position); - if (sp.part != null) { - return sp.part; - } - } - return null; - } - - @Override - public List getWailaBody(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - TileEntity tile = accessor.getTileEntity(); - - IPart part = getPart(tile, accessor.getPosition()); - if (part != null && part instanceof PartECBase) { - NBTTagCompound tag; - if (accessor.getNBTData() != null - && accessor.getNBTData().hasKey("partEC")) - tag = accessor.getNBTData().getCompoundTag("partEC"); - else - tag = new NBTTagCompound(); - return ((PartECBase) part).getWailaBodey(tag, currenttip); - } - - return currenttip; - } - - @Override - public List getWailaHead(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return currenttip; - } - - @Override - public ItemStack getWailaStack(IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return accessor.getStack(); - } - - @Override - public List getWailaTail(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return currenttip; - } - - private MovingObjectPosition retraceBlock(World world, - EntityPlayerMP player, int x, int y, int z) { - Block block = world.getBlock(x, y, z); - - Vec3 head = Vec3.createVectorHelper(player.posX, player.posY, - player.posZ); - head.yCoord += player.getEyeHeight(); - if (player.isSneaking()) - head.yCoord -= 0.08; - Vec3 look = player.getLook(1.0F); - double reach = player.theItemInWorldManager.getBlockReachDistance(); - Vec3 endVec = head.addVector(look.xCoord * reach, look.yCoord * reach, - look.zCoord * reach); - return block.collisionRayTrace(world, x, y, z, head, endVec); - } + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, + int y, int z) { + final MovingObjectPosition mop = retraceBlock(world, player, x, y, z); + + if (mop != null) { + final IPart part = getPart(te, mop); + + if (part != null && part instanceof PartECBase) { + tag.setTag("partEC", ((PartECBase) part).getWailaTag(new NBTTagCompound())); + } + } + return tag; + } + + private IPart getPart(TileEntity tile, MovingObjectPosition pos) { + if (tile instanceof IPartHost) { + final Vec3 position = pos.hitVec.addVector(-pos.blockX, -pos.blockY, -pos.blockZ); + final IPartHost host = (IPartHost) tile; + final SelectedPart sp = host.selectPart(position); + if (sp.part != null) { + return sp.part; + } + } + return null; + } + + @Override + public List getWailaBody(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + TileEntity tile = accessor.getTileEntity(); + + IPart part = getPart(tile, accessor.getPosition()); + if (part != null && part instanceof PartECBase) { + NBTTagCompound tag; + if (accessor.getNBTData() != null && accessor.getNBTData().hasKey("partEC")) + tag = accessor.getNBTData().getCompoundTag("partEC"); + else tag = new NBTTagCompound(); + return ((PartECBase) part).getWailaBodey(tag, currenttip); + } + + return currenttip; + } + + @Override + public List getWailaHead(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + return currenttip; + } + + @Override + public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) { + return accessor.getStack(); + } + + @Override + public List getWailaTail(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + return currenttip; + } + + private MovingObjectPosition retraceBlock(World world, EntityPlayerMP player, int x, int y, int z) { + Block block = world.getBlock(x, y, z); + + Vec3 head = Vec3.createVectorHelper(player.posX, player.posY, player.posZ); + head.yCoord += player.getEyeHeight(); + if (player.isSneaking()) head.yCoord -= 0.08; + Vec3 look = player.getLook(1.0F); + double reach = player.theItemInWorldManager.getBlockReachDistance(); + Vec3 endVec = head.addVector(look.xCoord * reach, look.yCoord * reach, look.zCoord * reach); + return block.collisionRayTrace(world, x, y, z, head, endVec); + } } diff --git a/src/main/scala/extracells/integration/waila/TileCertusTankWailaDataProvider.java b/src/main/scala/extracells/integration/waila/TileCertusTankWailaDataProvider.java index 2c955020a..9e44711d4 100644 --- a/src/main/scala/extracells/integration/waila/TileCertusTankWailaDataProvider.java +++ b/src/main/scala/extracells/integration/waila/TileCertusTankWailaDataProvider.java @@ -1,9 +1,7 @@ package extracells.integration.waila; -import extracells.tileentity.TileEntityCertusTank; -import mcp.mobius.waila.api.IWailaConfigHandler; -import mcp.mobius.waila.api.IWailaDataAccessor; -import mcp.mobius.waila.api.IWailaDataProvider; +import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -15,84 +13,73 @@ import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import java.util.List; +import extracells.tileentity.TileEntityCertusTank; +import mcp.mobius.waila.api.IWailaConfigHandler; +import mcp.mobius.waila.api.IWailaDataAccessor; +import mcp.mobius.waila.api.IWailaDataProvider; public class TileCertusTankWailaDataProvider implements IWailaDataProvider { - @Override - public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity tile, - NBTTagCompound tag, World world, int x, int y, int z) { - if (tile instanceof TileEntityCertusTank) { - if (((TileEntityCertusTank) tile).tank.getFluid() == null) - tag.setInteger("fluidID", -1); - else { - tag.setInteger("fluidID", - ((TileEntityCertusTank) tile).tank.getFluid().getFluidID()); - tag.setInteger("currentFluid", - ((TileEntityCertusTank) tile).tank.getFluidAmount()); - } - tag.setInteger("maxFluid", - ((TileEntityCertusTank) tile).tank.getCapacity()); - } - return tag; - } - - @Override - public List getWailaBody(ItemStack itemStack, List list, - IWailaDataAccessor accessor, IWailaConfigHandler config) { - NBTTagCompound tag = accessor.getNBTData(); - if (tag == null) - return list; - if (tag.hasKey("fluidID")) { - int fluidID = tag.getInteger("fluidID"); - if (fluidID == -1) { - list.add(StatCollector - .translateToLocal("extracells.tooltip.fluid") - + ": " - + StatCollector - .translateToLocal("extracells.tooltip.empty1")); - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": 0mB / " + tag.getInteger("maxFluid") + "mB"); - return list; - } else { - Fluid fluid = FluidRegistry.getFluid(tag.getInteger("fluidID")); - list.add(StatCollector - .translateToLocal("extracells.tooltip.fluid") - + ": " - + fluid.getLocalizedName(new FluidStack(fluid, - FluidContainerRegistry.BUCKET_VOLUME))); - } - } else - return list; - if (tag.hasKey("maxFluid") && tag.hasKey("currentFluid")) - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": " - + tag.getInteger("currentFluid") - + "mB / " - + tag.getInteger("maxFluid") + "mB"); - return list; - } + @Override + public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity tile, NBTTagCompound tag, World world, int x, + int y, int z) { + if (tile instanceof TileEntityCertusTank) { + if (((TileEntityCertusTank) tile).tank.getFluid() == null) tag.setInteger("fluidID", -1); + else { + tag.setInteger("fluidID", ((TileEntityCertusTank) tile).tank.getFluid().getFluidID()); + tag.setInteger("currentFluid", ((TileEntityCertusTank) tile).tank.getFluidAmount()); + } + tag.setInteger("maxFluid", ((TileEntityCertusTank) tile).tank.getCapacity()); + } + return tag; + } - @Override - public List getWailaHead(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return currenttip; - } + @Override + public List getWailaBody(ItemStack itemStack, List list, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + NBTTagCompound tag = accessor.getNBTData(); + if (tag == null) return list; + if (tag.hasKey("fluidID")) { + int fluidID = tag.getInteger("fluidID"); + if (fluidID == -1) { + list.add( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + StatCollector.translateToLocal("extracells.tooltip.empty1")); + list.add( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": 0mB / " + + tag.getInteger("maxFluid") + + "mB"); + return list; + } else { + Fluid fluid = FluidRegistry.getFluid(tag.getInteger("fluidID")); + list.add( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + fluid.getLocalizedName(new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME))); + } + } else return list; + if (tag.hasKey("maxFluid") && tag.hasKey("currentFluid")) list.add( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + + tag.getInteger("currentFluid") + + "mB / " + + tag.getInteger("maxFluid") + + "mB"); + return list; + } - @Override - public ItemStack getWailaStack(IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return accessor.getStack(); - } + @Override + public List getWailaHead(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + return currenttip; + } - @Override - public List getWailaTail(ItemStack itemStack, - List currenttip, IWailaDataAccessor accessor, - IWailaConfigHandler config) { - return currenttip; - } + @Override + public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler config) { + return accessor.getStack(); + } + @Override + public List getWailaTail(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, + IWailaConfigHandler config) { + return currenttip; + } } diff --git a/src/main/scala/extracells/integration/waila/Waila.java b/src/main/scala/extracells/integration/waila/Waila.java index f70cb4e09..bdab9a0af 100644 --- a/src/main/scala/extracells/integration/waila/Waila.java +++ b/src/main/scala/extracells/integration/waila/Waila.java @@ -9,28 +9,25 @@ public class Waila { - public static void init() { - FMLInterModComms.sendMessage("Waila", "register", Waila.class.getName() + ".register"); - } + public static void init() { + FMLInterModComms.sendMessage("Waila", "register", Waila.class.getName() + ".register"); + } - @Optional.Method(modid = "Waila") - public static void register(IWailaRegistrar registrar) { - final IWailaDataProvider partHost = new PartWailaDataProvider(); + @Optional.Method(modid = "Waila") + public static void register(IWailaRegistrar registrar) { + final IWailaDataProvider partHost = new PartWailaDataProvider(); - registrar.registerBodyProvider(partHost, IPartHost.class); - registrar.registerNBTProvider(partHost, IPartHost.class); + registrar.registerBodyProvider(partHost, IPartHost.class); + registrar.registerNBTProvider(partHost, IPartHost.class); - final IWailaDataProvider tileCertusTank = new TileCertusTankWailaDataProvider(); + final IWailaDataProvider tileCertusTank = new TileCertusTankWailaDataProvider(); - registrar.registerBodyProvider(tileCertusTank, - TileEntityCertusTank.class); - registrar.registerNBTProvider(tileCertusTank, - TileEntityCertusTank.class); + registrar.registerBodyProvider(tileCertusTank, TileEntityCertusTank.class); + registrar.registerNBTProvider(tileCertusTank, TileEntityCertusTank.class); - final IWailaDataProvider blocks = new BlockWailaDataProvider(); - - registrar.registerBodyProvider(blocks, IWailaTile.class); - registrar.registerNBTProvider(blocks, IWailaTile.class); - } + final IWailaDataProvider blocks = new BlockWailaDataProvider(); + registrar.registerBodyProvider(blocks, IWailaTile.class); + registrar.registerNBTProvider(blocks, IWailaTile.class); + } } diff --git a/src/main/scala/extracells/inventory/AdvancedCellInventory.java b/src/main/scala/extracells/inventory/AdvancedCellInventory.java new file mode 100644 index 000000000..f6aa16fbc --- /dev/null +++ b/src/main/scala/extracells/inventory/AdvancedCellInventory.java @@ -0,0 +1,496 @@ +package extracells.inventory; + +import java.util.HashSet; +import java.util.Set; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.oredict.OreDictionary; + +import appeng.api.AEApi; +import appeng.api.config.Actionable; +import appeng.api.config.FuzzyMode; +import appeng.api.exceptions.AppEngException; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.*; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.util.IterationCounter; +import appeng.util.Platform; +import appeng.util.item.AEItemStack; +import extracells.api.IStorageCellAdvanced; + +public class AdvancedCellInventory implements ICellInventory { + + 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 = 63; + private short storedItems = 0; + private long storedItemCount = 0; + private IItemList cellItems; + private final ItemStack cellItem; + private IStorageCellAdvanced cellType; + + private AdvancedCellInventory(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 IStorageCellAdvanced) { + this.cellType = (IStorageCellAdvanced) 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!"); + } + + this.container = container; + this.tagCompound = Platform.openNbtData(o); + this.storedItems = this.tagCompound.getShort(ITEM_TYPE_TAG); + this.storedItemCount = this.tagCompound.getLong(ITEM_COUNT_TAG); + this.cellItems = null; + } + + public static IMEInventoryHandler getCell(final ItemStack o, final ISaveProvider container2) { + try { + return new AdvancedCellInventoryHandler(new AdvancedCellInventory(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 IStorageCellAdvanced) { + return !((IStorageCellAdvanced) 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 IStorageCellAdvanced) { + return ((IStorageCellAdvanced) 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(), IterationCounter.fetchNewId()) + .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 (AdvancedCellInventory.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 * Integer.MAX_VALUE); + this.saveChanges(); + } + + return r; + } else { + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() + input.getStackSize()); + this.updateItemCount(input.getStackSize() * Integer.MAX_VALUE); + this.saveChanges(); + } + + return null; + } + } + + if (this.canHoldNewItem()) // room for new type, and for at least one item! + { + final long remainingItemCount = this.getRemainingItemCount() - this.getBytesPerType() * 8; + + if (remainingItemCount > 0) { + if (input.getStackSize() > remainingItemCount) { + final AEItemStack toReturn = AEItemStack.create(sharedItemStack); + toReturn.setStackSize(sharedItemStack.stackSize - remainingItemCount);; + + if (mode == Actionable.MODULATE) { + final AEItemStack toWrite = AEItemStack.create(sharedItemStack); + toWrite.setStackSize(remainingItemCount); + + this.cellItems.add(toWrite); + this.updateItemCount(toWrite.getStackSize() * Integer.MAX_VALUE); + + this.saveChanges(); + } + + return 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.setLong(ITEM_COUNT_TAG, this.storedItemCount); + } + + private void saveChanges() { + // cellItems.clean(); + long 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.setLong(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.setLong(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().createPrimitiveItemList(); + } + + this.cellItems.resetStatus(); // clears totals and stuff. + + final int types = (int) this.getStoredItemTypes(); + + for (int x = 0; x < types; x++) { + final IAEItemStack t = AEItemStack.loadItemStackFromNBT(this.tagCompound.getCompoundTag(itemSlots[x])); + + if (t != null) { + this.cellItems.add(t); + } + } + + // cellItems.clean(); + } + + @Override + public IItemList getAvailableItems(final IItemList out, int iteration) { + 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(this.cellItem); + } + + @Override + public FuzzyMode getFuzzyMode() { + return this.cellType.getFuzzyMode(this.cellItem); + } + + @Override + public String getOreFilter() { + return this.cellType.getOreFilter(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()) / 8; + + return this.getStoredItemTypes() * this.getBytesPerType() + 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; + + 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/scala/extracells/inventory/AdvancedCellInventoryHandler.java b/src/main/scala/extracells/inventory/AdvancedCellInventoryHandler.java new file mode 100644 index 000000000..3506c9534 --- /dev/null +++ b/src/main/scala/extracells/inventory/AdvancedCellInventoryHandler.java @@ -0,0 +1,122 @@ +package extracells.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +import appeng.api.AEApi; +import appeng.api.config.FuzzyMode; +import appeng.api.config.IncludeExclude; +import appeng.api.config.Upgrades; +import appeng.api.implementations.items.IUpgradeModule; +import appeng.api.storage.ICellInventory; +import appeng.api.storage.ICellInventoryHandler; +import appeng.api.storage.IMEInventory; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.util.item.AEItemStack; +import appeng.util.prioitylist.FuzzyPriorityList; +import appeng.util.prioitylist.OreFilteredList; +import appeng.util.prioitylist.PrecisePriorityList; + +public class AdvancedCellInventoryHandler extends MEAdvancedInventoryHandler + implements ICellInventoryHandler { + + AdvancedCellInventoryHandler(final IMEInventory c) { + super(c, StorageChannel.ITEMS); + + final ICellInventory ci = this.getCellInv(); + + if (ci != null) { + final IInventory upgrades = ci.getUpgradesInventory(); + final IInventory config = ci.getConfigInventory(); + final FuzzyMode fzMode = ci.getFuzzyMode(); + final String filter = ci.getOreFilter(); + // final String filter = ""; + boolean hasInverter = false; + boolean hasFuzzy = false; + boolean hasOreFilter = false; + + 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; + case ORE_FILTER: + hasOreFilter = true; + break; + default: + } + } + } + } + this.setWhitelist(hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + if (hasOreFilter && !filter.isEmpty()) { + this.setPartitionList(new OreFilteredList(filter)); + } else { + final IItemList priorityList = AEApi.instance().storage().createItemList(); + 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)); + } + } + } + } + } + + @Override + public ICellInventory getCellInv() { + Object o = this.getInternal(); + + if (o instanceof MEPassThrough) { + o = ((MEPassThrough) o).getInternal(); + } + + return (AdvancedCellInventory) (o instanceof AdvancedCellInventory ? o : null); + } + + @Override + public boolean isPreformatted() { + return !this.getPartitionList().isEmpty(); + } + + @Override + public boolean isFuzzy() { + return this.getPartitionList() instanceof FuzzyPriorityList; + } + + @Override + public IncludeExclude getIncludeExcludeMode() { + return this.getWhitelist(); + } + + public int getStatusForCell() { + ICellInventory c = this.getCellInv(); + int val = 0; + if (c != null) { + val = this.getCellInv().getStatusForCell(); + } + + if (val == 1 && this.isPreformatted()) { + val = 2; + } + + return val; + } +} diff --git a/src/main/scala/extracells/inventory/HandlerItemPlayerStorageFluid.java b/src/main/scala/extracells/inventory/HandlerItemPlayerStorageFluid.java index 5c80baedd..54aa5aea7 100644 --- a/src/main/scala/extracells/inventory/HandlerItemPlayerStorageFluid.java +++ b/src/main/scala/extracells/inventory/HandlerItemPlayerStorageFluid.java @@ -1,47 +1,42 @@ package extracells.inventory; -import appeng.api.storage.ISaveProvider; +import java.util.ArrayList; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; -import java.util.ArrayList; +import appeng.api.storage.ISaveProvider; public class HandlerItemPlayerStorageFluid extends HandlerItemStorageFluid { - private final EntityPlayer player; - - public HandlerItemPlayerStorageFluid(ItemStack _storageStack, - ISaveProvider _saveProvider, ArrayList _filter, - EntityPlayer _player) { - super(_storageStack, _saveProvider, _filter); - this.player = _player; - } - - public HandlerItemPlayerStorageFluid(ItemStack _storageStack, - ISaveProvider _saveProvider, EntityPlayer _player) { - super(_storageStack, _saveProvider); - this.player = _player; - } - - @Override - protected void writeFluidToSlot(int i, FluidStack fluidStack) { - if (this.player.getCurrentEquippedItem() == null) - return; - ItemStack item = this.player.getCurrentEquippedItem(); - if (!item.hasTagCompound()) - item.setTagCompound(new NBTTagCompound()); - NBTTagCompound fluidTag = new NBTTagCompound(); - if (fluidStack != null && fluidStack.getFluidID() > 0 - && fluidStack.amount > 0) { - fluidStack.writeToNBT(fluidTag); - item.getTagCompound().setTag("Fluid#" + i, fluidTag); - } else { - item.getTagCompound().removeTag("Fluid#" + i); - } - this.fluidStacks.set(i, fluidStack); - } - + private final EntityPlayer player; + + public HandlerItemPlayerStorageFluid(ItemStack _storageStack, ISaveProvider _saveProvider, ArrayList _filter, + EntityPlayer _player) { + super(_storageStack, _saveProvider, _filter); + this.player = _player; + } + + public HandlerItemPlayerStorageFluid(ItemStack _storageStack, ISaveProvider _saveProvider, EntityPlayer _player) { + super(_storageStack, _saveProvider); + this.player = _player; + } + + @Override + protected void writeFluidToSlot(int i, FluidStack fluidStack) { + if (this.player.getCurrentEquippedItem() == null) return; + ItemStack item = this.player.getCurrentEquippedItem(); + if (!item.hasTagCompound()) item.setTagCompound(new NBTTagCompound()); + NBTTagCompound fluidTag = new NBTTagCompound(); + if (fluidStack != null && fluidStack.getFluidID() > 0 && fluidStack.amount > 0) { + fluidStack.writeToNBT(fluidTag); + item.getTagCompound().setTag("Fluid#" + i, fluidTag); + } else { + item.getTagCompound().removeTag("Fluid#" + i); + } + this.fluidStacks.set(i, fluidStack); + } } diff --git a/src/main/scala/extracells/inventory/HandlerItemPlayerStorageGas.java b/src/main/scala/extracells/inventory/HandlerItemPlayerStorageGas.java index 474b0de60..dbd1fd4f8 100644 --- a/src/main/scala/extracells/inventory/HandlerItemPlayerStorageGas.java +++ b/src/main/scala/extracells/inventory/HandlerItemPlayerStorageGas.java @@ -1,40 +1,37 @@ package extracells.inventory; +import java.util.ArrayList; -import appeng.api.storage.ISaveProvider; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; -import java.util.ArrayList; +import appeng.api.storage.ISaveProvider; -public class HandlerItemPlayerStorageGas extends HandlerItemStorageGas{ +public class HandlerItemPlayerStorageGas extends HandlerItemStorageGas { private final EntityPlayer player; - public HandlerItemPlayerStorageGas(ItemStack _storageStack, ISaveProvider _saveProvider, ArrayList _filter, EntityPlayer _player) { + public HandlerItemPlayerStorageGas(ItemStack _storageStack, ISaveProvider _saveProvider, ArrayList _filter, + EntityPlayer _player) { super(_storageStack, _saveProvider, _filter); this.player = _player; } - public HandlerItemPlayerStorageGas(ItemStack _storageStack, - ISaveProvider _saveProvider, EntityPlayer _player) { + public HandlerItemPlayerStorageGas(ItemStack _storageStack, ISaveProvider _saveProvider, EntityPlayer _player) { super(_storageStack, _saveProvider); this.player = _player; } @Override protected void writeFluidToSlot(int i, FluidStack fluidStack) { - if (this.player.getCurrentEquippedItem() == null) - return; + if (this.player.getCurrentEquippedItem() == null) return; ItemStack item = this.player.getCurrentEquippedItem(); - if (!item.hasTagCompound()) - item.setTagCompound(new NBTTagCompound()); + if (!item.hasTagCompound()) item.setTagCompound(new NBTTagCompound()); NBTTagCompound fluidTag = new NBTTagCompound(); - if (fluidStack != null && fluidStack.getFluidID() > 0 - && fluidStack.amount > 0) { + if (fluidStack != null && fluidStack.getFluidID() > 0 && fluidStack.amount > 0) { fluidStack.writeToNBT(fluidTag); item.getTagCompound().setTag("Fluid#" + i, fluidTag); } else { diff --git a/src/main/scala/extracells/inventory/HandlerItemStorageFluid.java b/src/main/scala/extracells/inventory/HandlerItemStorageFluid.java index d244dae44..e4d64fb0c 100644 --- a/src/main/scala/extracells/inventory/HandlerItemStorageFluid.java +++ b/src/main/scala/extracells/inventory/HandlerItemStorageFluid.java @@ -1,5 +1,13 @@ package extracells.inventory; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -9,254 +17,223 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; -import com.google.common.collect.Lists; import extracells.api.ECApi; import extracells.api.IFluidStorageCell; import extracells.api.IHandlerFluidStorage; import extracells.container.ContainerFluidStorage; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import java.util.ArrayList; -import java.util.List; +/** + * Handler for fluid storage disks + */ public class HandlerItemStorageFluid implements IMEInventoryHandler, IHandlerFluidStorage { - private NBTTagCompound stackTag; - protected ArrayList fluidStacks = new ArrayList(); - private ArrayList prioritizedFluids = new ArrayList(); - private int totalTypes; - private int totalBytes; - private List containers = new ArrayList(); - private ISaveProvider saveProvider; - - public HandlerItemStorageFluid(ItemStack _storageStack, - ISaveProvider _saveProvider) { - if (!_storageStack.hasTagCompound()) _storageStack.setTagCompound(new NBTTagCompound()); - this.stackTag = _storageStack.getTagCompound(); - this.totalTypes = ((IFluidStorageCell) _storageStack.getItem()).getMaxTypes(_storageStack); - this.totalBytes = ((IFluidStorageCell) _storageStack.getItem()).getMaxBytes(_storageStack) * 250; - - for (int i = 0; i < this.totalTypes; i++) - this.fluidStacks.add(FluidStack.loadFluidStackFromNBT(this.stackTag.getCompoundTag("Fluid#" + i))); - - this.saveProvider = _saveProvider; - } - - public HandlerItemStorageFluid(ItemStack _storageStack, ISaveProvider _saveProvider, ArrayList _filter) { - this(_storageStack, _saveProvider); - if (_filter != null) - this.prioritizedFluids = _filter; - } - - private boolean allowedByFormat(Fluid fluid) { - return !isFormatted() || this.prioritizedFluids.contains(fluid); - } - - @Override - public boolean canAccept(IAEFluidStack input) { - if (input == null) - return false; - if (!ECApi.instance().canStoreFluid(input.getFluid())) - return false; - for (FluidStack fluidStack : this.fluidStacks) { - if (fluidStack == null || fluidStack.getFluid() == input.getFluid()) - return allowedByFormat(input.getFluid()); - } - return false; - } - - @Override - public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, - BaseActionSource src) { - if (request == null || !allowedByFormat(request.getFluid())) - return null; - - IAEFluidStack removedStack; - List currentFluids = Lists.newArrayList(this.fluidStacks); - for (int i = 0; i < this.fluidStacks.size(); i++) { - FluidStack currentStack = this.fluidStacks.get(i); - if (currentStack != null && currentStack.getFluidID() == request.getFluid().getID()) { - long endAmount = currentStack.amount - request.getStackSize(); - if (endAmount >= 0) { - removedStack = request.copy(); - FluidStack toWrite = new FluidStack(currentStack.getFluid(), (int) endAmount); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - } else { - removedStack = AEApi.instance().storage().createFluidStack(currentStack.copy()); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, null); - } - } - if (removedStack != null && removedStack.getStackSize() > 0) - requestSave(); - return removedStack; - } - } - - return null; - } - - public int freeBytes() { - int i = 0; - for (FluidStack stack : this.fluidStacks) - if (stack != null) - i += stack.amount; - return this.totalBytes - i; - } - - @Override - public AccessRestriction getAccess() { - return AccessRestriction.READ_WRITE; - } - - @Override - public IItemList getAvailableItems( - IItemList out) { - for (FluidStack fluidStack : this.fluidStacks) - if (fluidStack != null) - out.add(AEApi.instance().storage().createFluidStack(fluidStack)); - return out; - } - - @Override - public StorageChannel getChannel() { - return StorageChannel.FLUIDS; - } - - @Override - public int getPriority() { - return 0; - } - - @Override - public int getSlot() { - return 0; - } - - @Override - public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, - BaseActionSource src) { - if (input == null || !allowedByFormat(input.getFluid())) - return input; - IAEFluidStack notAdded = input.copy(); - List currentFluids = Lists.newArrayList(this.fluidStacks); - for (int i = 0; i < currentFluids.size(); i++) { - FluidStack currentStack = currentFluids.get(i); - if (notAdded != null && currentStack != null - && input.getFluid() == currentStack.getFluid()) { - if (notAdded.getStackSize() <= freeBytes()) { - FluidStack toWrite = new FluidStack(currentStack.getFluid(), - currentStack.amount + (int) notAdded.getStackSize()); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded = null; - } else { - FluidStack toWrite = new FluidStack(currentStack.getFluid(), currentStack.amount + freeBytes()); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded.setStackSize(notAdded.getStackSize() - freeBytes()); - } - } - } - for (int i = 0; i < currentFluids.size(); i++) { - FluidStack currentStack = currentFluids.get(i); - if (notAdded != null && currentStack == null) { - if (input.getStackSize() <= freeBytes()) { - FluidStack toWrite = notAdded.getFluidStack(); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded = null; - } else { - FluidStack toWrite = new FluidStack(notAdded.getFluid(), freeBytes()); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded.setStackSize(notAdded.getStackSize() - freeBytes()); - } - } - } - if (notAdded == null || !notAdded.equals(input)) - requestSave(); - return notAdded; - } - - @Override - public boolean isFormatted() { - // Common case - if (this.prioritizedFluids.isEmpty()) { - return false; - } - - for (Fluid currentFluid : this.prioritizedFluids) { - if (currentFluid != null) - return true; - } - - return false; - } - - @Override - public boolean isPrioritized(IAEFluidStack input) { - return input != null - && this.prioritizedFluids.contains(input.getFluid()); - } - - private void requestSave() { - if (this.saveProvider != null) - this.saveProvider.saveChanges(this); - } - - @Override - public int totalBytes() { - return this.totalBytes; - } - - @Override - public int totalTypes() { - return this.totalTypes; - } - - @Override - public int usedBytes() { - return this.totalBytes - freeBytes(); - } - - @Override - public int usedTypes() { - int i = 0; - for (FluidStack stack : this.fluidStacks) - if (stack != null) - i++; - return i; - } - - @Override - public boolean validForPass(int i) { - return true; // TODO - } - - protected void writeFluidToSlot(int i, FluidStack fluidStack) { - NBTTagCompound fluidTag = new NBTTagCompound(); - if (fluidStack != null && fluidStack.getFluidID() > 0 - && fluidStack.amount > 0) { - fluidStack.writeToNBT(fluidTag); - this.stackTag.setTag("Fluid#" + i, fluidTag); - } else { - this.stackTag.removeTag("Fluid#" + i); - } - this.fluidStacks.set(i, fluidStack); - } + private NBTTagCompound stackTag; + protected ArrayList fluidStacks = new ArrayList(); + private ArrayList prioritizedFluids = new ArrayList(); + private int totalTypes; + private int totalBytes; + private List containers = new ArrayList(); + private ISaveProvider saveProvider; + + public HandlerItemStorageFluid(ItemStack _storageStack, ISaveProvider _saveProvider) { + if (!_storageStack.hasTagCompound()) _storageStack.setTagCompound(new NBTTagCompound()); + this.stackTag = _storageStack.getTagCompound(); + this.totalTypes = ((IFluidStorageCell) _storageStack.getItem()).getMaxTypes(_storageStack); + this.totalBytes = ((IFluidStorageCell) _storageStack.getItem()).getMaxBytes(_storageStack) * 250; + + for (int i = 0; i < this.totalTypes; i++) + this.fluidStacks.add(FluidStack.loadFluidStackFromNBT(this.stackTag.getCompoundTag("Fluid#" + i))); + + this.saveProvider = _saveProvider; + } + + public HandlerItemStorageFluid(ItemStack _storageStack, ISaveProvider _saveProvider, ArrayList _filter) { + this(_storageStack, _saveProvider); + if (_filter != null) this.prioritizedFluids = _filter; + } + + private boolean allowedByFormat(Fluid fluid) { + return !isFormatted() || this.prioritizedFluids.contains(fluid); + } + + @Override + public boolean canAccept(IAEFluidStack input) { + if (input == null) return false; + if (!ECApi.instance().canStoreFluid(input.getFluid())) return false; + for (FluidStack fluidStack : this.fluidStacks) { + if (fluidStack == null || fluidStack.getFluid() == input.getFluid()) + return allowedByFormat(input.getFluid()); + } + return false; + } + + @Override + public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, BaseActionSource src) { + if (request == null || !allowedByFormat(request.getFluid())) return null; + + IAEFluidStack removedStack; + for (int i = 0; i < this.fluidStacks.size(); i++) { + FluidStack currentStack = this.fluidStacks.get(i); + if (currentStack != null && currentStack.getFluidID() == request.getFluid().getID()) { + long endAmount = currentStack.amount - request.getStackSize(); + if (endAmount >= 0) { + removedStack = request.copy(); + FluidStack toWrite = new FluidStack(currentStack.getFluid(), (int) endAmount); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, toWrite); + } + } else { + removedStack = AEApi.instance().storage().createFluidStack(currentStack); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, null); + } + } + if (removedStack != null && removedStack.getStackSize() > 0) requestSave(); + return removedStack; + } + } + + return null; + } + + public int freeBytes() { + int i = 0; + for (FluidStack stack : this.fluidStacks) if (stack != null) i += stack.amount; + return this.totalBytes - i; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + @Override + public IItemList getAvailableItems(IItemList out, int iteration) { + for (FluidStack fluidStack : this.fluidStacks) + if (fluidStack != null) out.add(AEApi.instance().storage().createFluidStack(fluidStack)); + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, BaseActionSource src) { + if (input == null || !allowedByFormat(input.getFluid())) return input; + + // Find a matching slot, or empty slot to insert to + int targetSlot = -1; + int emptySlot = -1; + for (int i = 0; i < this.fluidStacks.size(); i++) { + FluidStack stack = this.fluidStacks.get(i); + if (stack != null && stack.getFluid().getID() == input.getFluid().getID()) { + targetSlot = i; + break; + } + if (stack == null && emptySlot < 0) { + emptySlot = i; + } + } + if (targetSlot < 0) { + targetSlot = emptySlot; + } + if (targetSlot < 0) { + // Failed to find a good slot + return input; + } + + final FluidStack originalTargetContents = this.fluidStacks.get(targetSlot); + final long originalTargetAmount = (originalTargetContents != null) ? originalTargetContents.amount : 0; + final long requestedAmount = input.getStackSize(); + final long freeSpace = freeBytes(); + final long drainedAmount = Long.min(requestedAmount, freeSpace); + + if (mode == Actionable.MODULATE) { + final Fluid fluidInserted = (originalTargetContents != null) ? originalTargetContents.getFluid() + : input.getFluid(); + writeFluidToSlot(targetSlot, new FluidStack(fluidInserted, (int) (originalTargetAmount + drainedAmount))); + requestSave(); + } + + if (drainedAmount == requestedAmount) { + return null; + } else { + IAEFluidStack notAdded = input.copy(); + notAdded.setStackSize(requestedAmount - drainedAmount); + return notAdded; + } + } + + @Override + public boolean isFormatted() { + // Common case + if (this.prioritizedFluids.isEmpty()) { + return false; + } + + for (Fluid currentFluid : this.prioritizedFluids) { + if (currentFluid != null) return true; + } + + return false; + } + + @Override + public boolean isPrioritized(IAEFluidStack input) { + return input != null && this.prioritizedFluids.contains(input.getFluid()); + } + + private void requestSave() { + if (this.saveProvider != null) this.saveProvider.saveChanges(this); + } + + @Override + public int totalBytes() { + return this.totalBytes; + } + + @Override + public int totalTypes() { + return this.totalTypes; + } + + @Override + public int usedBytes() { + return this.totalBytes - freeBytes(); + } + + @Override + public int usedTypes() { + int i = 0; + for (FluidStack stack : this.fluidStacks) if (stack != null) i++; + return i; + } + + @Override + public boolean validForPass(int i) { + return true; // TODO + } + + protected void writeFluidToSlot(int i, FluidStack fluidStack) { + NBTTagCompound fluidTag = new NBTTagCompound(); + if (fluidStack != null && fluidStack.getFluidID() > 0 && fluidStack.amount > 0) { + fluidStack.writeToNBT(fluidTag); + this.stackTag.setTag("Fluid#" + i, fluidTag); + } else { + this.stackTag.removeTag("Fluid#" + i); + } + this.fluidStacks.set(i, fluidStack); + } } diff --git a/src/main/scala/extracells/inventory/HandlerItemStorageGas.java b/src/main/scala/extracells/inventory/HandlerItemStorageGas.java index 410dc3e53..c5f59a17f 100644 --- a/src/main/scala/extracells/inventory/HandlerItemStorageGas.java +++ b/src/main/scala/extracells/inventory/HandlerItemStorageGas.java @@ -1,5 +1,15 @@ package extracells.inventory; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import com.google.common.collect.Lists; + import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -9,254 +19,226 @@ import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; -import com.google.common.collect.Lists; import extracells.api.ECApi; import extracells.api.IGasStorageCell; import extracells.api.IHandlerFluidStorage; import extracells.container.ContainerFluidStorage; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import java.util.ArrayList; -import java.util.List; public class HandlerItemStorageGas implements IMEInventoryHandler, IHandlerFluidStorage { - private NBTTagCompound stackTag; - protected ArrayList fluidStacks = new ArrayList(); - private ArrayList prioritizedFluids = new ArrayList(); - private int totalTypes; - private int totalBytes; - private List containers = new ArrayList(); - private ISaveProvider saveProvider; - - public HandlerItemStorageGas(ItemStack _storageStack, - ISaveProvider _saveProvider) { - if (!_storageStack.hasTagCompound()) _storageStack.setTagCompound(new NBTTagCompound()); - this.stackTag = _storageStack.getTagCompound(); - this.totalTypes = ((IGasStorageCell) _storageStack.getItem()).getMaxTypes(_storageStack); - this.totalBytes = ((IGasStorageCell) _storageStack.getItem()).getMaxBytes(_storageStack) * 250; - - for (int i = 0; i < this.totalTypes; i++) - this.fluidStacks.add(FluidStack.loadFluidStackFromNBT(this.stackTag.getCompoundTag("Fluid#" + i))); - - this.saveProvider = _saveProvider; - } - - public HandlerItemStorageGas(ItemStack _storageStack, ISaveProvider _saveProvider, ArrayList _filter) { - this(_storageStack, _saveProvider); - if (_filter != null) - this.prioritizedFluids = _filter; - } - - private boolean allowedByFormat(Fluid fluid) { - return !isFormatted() || this.prioritizedFluids.contains(fluid); - } - - @Override - public boolean canAccept(IAEFluidStack input) { - if (input == null) - return false; - if (!ECApi.instance().isGasStack(input)) - return false; - for (FluidStack fluidStack : this.fluidStacks) { - if (fluidStack == null || fluidStack.getFluid() == input.getFluid()) - return allowedByFormat(input.getFluid()); - } - return false; - } - - @Override - public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, - BaseActionSource src) { - if (request == null || !allowedByFormat(request.getFluid())) - return null; - - IAEFluidStack removedStack; - List currentFluids = Lists.newArrayList(this.fluidStacks); - for (int i = 0; i < this.fluidStacks.size(); i++) { - FluidStack currentStack = this.fluidStacks.get(i); - if (currentStack != null && currentStack.getFluidID() == request.getFluid().getID()) { - long endAmount = currentStack.amount - request.getStackSize(); - if (endAmount >= 0) { - removedStack = request.copy(); - FluidStack toWrite = new FluidStack(currentStack.getFluid(), (int) endAmount); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - } else { - removedStack = AEApi.instance().storage().createFluidStack(currentStack.copy()); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, null); - } - } - if (removedStack != null && removedStack.getStackSize() > 0) - requestSave(); - return removedStack; - } - } - - return null; - } - - public int freeBytes() { - int i = 0; - for (FluidStack stack : this.fluidStacks) - if (stack != null) - i += stack.amount; - return this.totalBytes - i; - } - - @Override - public AccessRestriction getAccess() { - return AccessRestriction.READ_WRITE; - } - - @Override - public IItemList getAvailableItems( - IItemList out) { - for (FluidStack fluidStack : this.fluidStacks) - if (fluidStack != null) - out.add(AEApi.instance().storage().createFluidStack(fluidStack)); - return out; - } - - @Override - public StorageChannel getChannel() { - return StorageChannel.FLUIDS; - } - - @Override - public int getPriority() { - return 0; - } - - @Override - public int getSlot() { - return 0; - } - - @Override - public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, - BaseActionSource src) { - if (input == null || !allowedByFormat(input.getFluid())) - return input; - IAEFluidStack notAdded = input.copy(); - List currentFluids = Lists.newArrayList(this.fluidStacks); - for (int i = 0; i < currentFluids.size(); i++) { - FluidStack currentStack = currentFluids.get(i); - if (notAdded != null && currentStack != null - && input.getFluid() == currentStack.getFluid()) { - if (notAdded.getStackSize() <= freeBytes()) { - FluidStack toWrite = new FluidStack(currentStack.getFluid(), - currentStack.amount + (int) notAdded.getStackSize()); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded = null; - } else { - FluidStack toWrite = new FluidStack(currentStack.getFluid(), currentStack.amount + freeBytes()); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded.setStackSize(notAdded.getStackSize() - freeBytes()); - } - } - } - for (int i = 0; i < currentFluids.size(); i++) { - FluidStack currentStack = currentFluids.get(i); - if (notAdded != null && currentStack == null) { - if (input.getStackSize() <= freeBytes()) { - FluidStack toWrite = notAdded.getFluidStack(); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded = null; - } else { - FluidStack toWrite = new FluidStack(notAdded.getFluid(), freeBytes()); - currentFluids.set(i, toWrite); - if (mode == Actionable.MODULATE) { - writeFluidToSlot(i, toWrite); - } - notAdded.setStackSize(notAdded.getStackSize() - freeBytes()); - } - } - } - if (notAdded == null || !notAdded.equals(input)) - requestSave(); - return notAdded; - } - - @Override - public boolean isFormatted() { - // Common case - if (this.prioritizedFluids.isEmpty()) { - return false; - } - - for (Fluid currentFluid : this.prioritizedFluids) { - if (currentFluid != null) - return true; - } - - return false; - } - - @Override - public boolean isPrioritized(IAEFluidStack input) { - return input != null - && this.prioritizedFluids.contains(input.getFluid()); - } - - private void requestSave() { - if (this.saveProvider != null) - this.saveProvider.saveChanges(this); - } - - @Override - public int totalBytes() { - return this.totalBytes; - } - - @Override - public int totalTypes() { - return this.totalTypes; - } - - @Override - public int usedBytes() { - return this.totalBytes - freeBytes(); - } - - @Override - public int usedTypes() { - int i = 0; - for (FluidStack stack : this.fluidStacks) - if (stack != null) - i++; - return i; - } - - @Override - public boolean validForPass(int i) { - return true; // TODO - } - - protected void writeFluidToSlot(int i, FluidStack fluidStack) { - NBTTagCompound fluidTag = new NBTTagCompound(); - if (fluidStack != null && fluidStack.getFluidID() > 0 - && fluidStack.amount > 0) { - fluidStack.writeToNBT(fluidTag); - this.stackTag.setTag("Fluid#" + i, fluidTag); - } else { - this.stackTag.removeTag("Fluid#" + i); - } - this.fluidStacks.set(i, fluidStack); - } + private NBTTagCompound stackTag; + protected ArrayList fluidStacks = new ArrayList(); + private ArrayList prioritizedFluids = new ArrayList(); + private int totalTypes; + private int totalBytes; + private List containers = new ArrayList(); + private ISaveProvider saveProvider; + + public HandlerItemStorageGas(ItemStack _storageStack, ISaveProvider _saveProvider) { + if (!_storageStack.hasTagCompound()) _storageStack.setTagCompound(new NBTTagCompound()); + this.stackTag = _storageStack.getTagCompound(); + this.totalTypes = ((IGasStorageCell) _storageStack.getItem()).getMaxTypes(_storageStack); + this.totalBytes = ((IGasStorageCell) _storageStack.getItem()).getMaxBytes(_storageStack) * 250; + + for (int i = 0; i < this.totalTypes; i++) + this.fluidStacks.add(FluidStack.loadFluidStackFromNBT(this.stackTag.getCompoundTag("Fluid#" + i))); + + this.saveProvider = _saveProvider; + } + + public HandlerItemStorageGas(ItemStack _storageStack, ISaveProvider _saveProvider, ArrayList _filter) { + this(_storageStack, _saveProvider); + if (_filter != null) this.prioritizedFluids = _filter; + } + + private boolean allowedByFormat(Fluid fluid) { + return !isFormatted() || this.prioritizedFluids.contains(fluid); + } + + @Override + public boolean canAccept(IAEFluidStack input) { + if (input == null) return false; + if (!ECApi.instance().isGasStack(input)) return false; + for (FluidStack fluidStack : this.fluidStacks) { + if (fluidStack == null || fluidStack.getFluid() == input.getFluid()) + return allowedByFormat(input.getFluid()); + } + return false; + } + + @Override + public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, BaseActionSource src) { + if (request == null || !allowedByFormat(request.getFluid())) return null; + + IAEFluidStack removedStack; + List currentFluids = Lists.newArrayList(this.fluidStacks); + for (int i = 0; i < this.fluidStacks.size(); i++) { + FluidStack currentStack = this.fluidStacks.get(i); + if (currentStack != null && currentStack.getFluidID() == request.getFluid().getID()) { + long endAmount = currentStack.amount - request.getStackSize(); + if (endAmount >= 0) { + removedStack = request.copy(); + FluidStack toWrite = new FluidStack(currentStack.getFluid(), (int) endAmount); + currentFluids.set(i, toWrite); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, toWrite); + } + } else { + removedStack = AEApi.instance().storage().createFluidStack(currentStack.copy()); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, null); + } + } + if (removedStack != null && removedStack.getStackSize() > 0) requestSave(); + return removedStack; + } + } + + return null; + } + + public int freeBytes() { + int i = 0; + for (FluidStack stack : this.fluidStacks) if (stack != null) i += stack.amount; + return this.totalBytes - i; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.READ_WRITE; + } + + @Override + public IItemList getAvailableItems(IItemList out, int iteration) { + for (FluidStack fluidStack : this.fluidStacks) + if (fluidStack != null) out.add(AEApi.instance().storage().createFluidStack(fluidStack)); + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, BaseActionSource src) { + if (input == null || !allowedByFormat(input.getFluid())) return input; + IAEFluidStack notAdded = input.copy(); + List currentFluids = Lists.newArrayList(this.fluidStacks); + for (int i = 0; i < currentFluids.size(); i++) { + FluidStack currentStack = currentFluids.get(i); + if (notAdded != null && currentStack != null && input.getFluid() == currentStack.getFluid()) { + if (notAdded.getStackSize() <= freeBytes()) { + FluidStack toWrite = new FluidStack( + currentStack.getFluid(), + currentStack.amount + (int) notAdded.getStackSize()); + currentFluids.set(i, toWrite); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, toWrite); + } + notAdded = null; + } else { + FluidStack toWrite = new FluidStack(currentStack.getFluid(), currentStack.amount + freeBytes()); + currentFluids.set(i, toWrite); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, toWrite); + } + notAdded.setStackSize(notAdded.getStackSize() - freeBytes()); + } + } + } + for (int i = 0; i < currentFluids.size(); i++) { + FluidStack currentStack = currentFluids.get(i); + if (notAdded != null && currentStack == null) { + if (input.getStackSize() <= freeBytes()) { + FluidStack toWrite = notAdded.getFluidStack(); + currentFluids.set(i, toWrite); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, toWrite); + } + notAdded = null; + } else { + FluidStack toWrite = new FluidStack(notAdded.getFluid(), freeBytes()); + currentFluids.set(i, toWrite); + if (mode == Actionable.MODULATE) { + writeFluidToSlot(i, toWrite); + } + notAdded.setStackSize(notAdded.getStackSize() - freeBytes()); + } + } + } + if (notAdded == null || !notAdded.equals(input)) requestSave(); + return notAdded; + } + + @Override + public boolean isFormatted() { + // Common case + if (this.prioritizedFluids.isEmpty()) { + return false; + } + + for (Fluid currentFluid : this.prioritizedFluids) { + if (currentFluid != null) return true; + } + + return false; + } + + @Override + public boolean isPrioritized(IAEFluidStack input) { + return input != null && this.prioritizedFluids.contains(input.getFluid()); + } + + private void requestSave() { + if (this.saveProvider != null) this.saveProvider.saveChanges(this); + } + + @Override + public int totalBytes() { + return this.totalBytes; + } + + @Override + public int totalTypes() { + return this.totalTypes; + } + + @Override + public int usedBytes() { + return this.totalBytes - freeBytes(); + } + + @Override + public int usedTypes() { + int i = 0; + for (FluidStack stack : this.fluidStacks) if (stack != null) i++; + return i; + } + + @Override + public boolean validForPass(int i) { + return true; // TODO + } + + protected void writeFluidToSlot(int i, FluidStack fluidStack) { + NBTTagCompound fluidTag = new NBTTagCompound(); + if (fluidStack != null && fluidStack.getFluidID() > 0 && fluidStack.amount > 0) { + fluidStack.writeToNBT(fluidTag); + this.stackTag.setTag("Fluid#" + i, fluidTag); + } else { + this.stackTag.removeTag("Fluid#" + i); + } + this.fluidStacks.set(i, fluidStack); + } } diff --git a/src/main/scala/extracells/inventory/HandlerPartStorageFluid.java b/src/main/scala/extracells/inventory/HandlerPartStorageFluid.java index 580cd9ef9..c59b3f0d3 100644 --- a/src/main/scala/extracells/inventory/HandlerPartStorageFluid.java +++ b/src/main/scala/extracells/inventory/HandlerPartStorageFluid.java @@ -1,5 +1,15 @@ package extracells.inventory; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; + import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -16,308 +26,281 @@ import appeng.api.storage.data.IItemList; import extracells.part.PartFluidStorage; import extracells.util.FluidUtil; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; -import java.util.ArrayList; -import java.util.List; +/** + * Handler for fluid storage buses + */ +public class HandlerPartStorageFluid + implements IMEInventoryHandler, IMEMonitorHandlerReceiver { -public class HandlerPartStorageFluid implements IMEInventoryHandler, IMEMonitorHandlerReceiver { + protected PartFluidStorage node; + protected IFluidHandler tank; + protected AccessRestriction access = AccessRestriction.READ_WRITE; + protected List prioritizedFluids = new ArrayList(); + protected boolean inverted; + private IExternalStorageHandler externalHandler = null; + protected TileEntity tile = null; + public ITileStorageMonitorable externalSystem; - protected PartFluidStorage node; - protected IFluidHandler tank; - protected AccessRestriction access = AccessRestriction.READ_WRITE; - protected List prioritizedFluids = new ArrayList(); - protected boolean inverted; - private IExternalStorageHandler externalHandler = null; - protected TileEntity tile = null; - public ITileStorageMonitorable externalSystem; + public HandlerPartStorageFluid(PartFluidStorage _node) { + this.node = _node; + } - public HandlerPartStorageFluid(PartFluidStorage _node) { - this.node = _node; - } + @Override + public boolean canAccept(IAEFluidStack input) { + if (!this.node.isActive()) return false; + else if (this.tank == null && this.externalSystem == null && this.externalHandler == null + || !this.access.hasPermission(AccessRestriction.WRITE) + || input == null) + return false; + else if (this.externalSystem != null) { + IStorageMonitorable monitor = this.externalSystem + .getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (monitor == null) return false; + IMEMonitor fluidInventory = monitor.getFluidInventory(); + return fluidInventory != null && fluidInventory.canAccept(input); + } else if (externalHandler != null) { + IMEInventory inventory = this.externalHandler.getInventory( + this.tile, + this.node.getSide().getOpposite(), + StorageChannel.FLUIDS, + new MachineSource(this.node)); + return inventory != null; + } + FluidTankInfo[] infoArray = this.tank.getTankInfo(this.node.getSide().getOpposite()); + if (infoArray != null && infoArray.length > 0) { + for (FluidTankInfo tank : infoArray) { + if (tank.fluid == null) return isPrioritized(input); + else if (tank.fluid.getFluidID() == input.getFluidStack().getFluidID()) { + if (!isPrioritized(input)) return false; + if (tank.fluid.amount < tank.capacity) return true; + } + } + } + return false; + } - @Override - public boolean canAccept(IAEFluidStack input) { - if (!this.node.isActive()) - return false; - if (this.tank == null && this.externalSystem == null && this.externalHandler == null || !(this.access == AccessRestriction.WRITE || this.access == AccessRestriction.READ_WRITE) || input == null) - return false; - if (this.externalSystem != null) { - IStorageMonitorable monitor = this.externalSystem.getMonitorable( - this.node.getSide().getOpposite(), new MachineSource( - this.node)); - if (monitor == null) - return false; - IMEMonitor fluidInventory = monitor - .getFluidInventory(); - return fluidInventory != null && fluidInventory.canAccept(input); - }else if(externalHandler != null){ - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), StorageChannel.FLUIDS, new MachineSource(this.node)); - return inventory != null; - } - FluidTankInfo[] infoArray = this.tank.getTankInfo(this.node.getSide().getOpposite()); - if (infoArray != null && infoArray.length > 0) { - FluidTankInfo info = infoArray[0]; - if (info.fluid == null || info.fluid.amount == 0 - || info.fluid.getFluidID() == input.getFluidStack().getFluidID()) - if (this.inverted) - return !this.prioritizedFluids.isEmpty() || !isPrioritized(input); - else - return this.prioritizedFluids.isEmpty() || isPrioritized(input); - } - return false; - } + @Override + public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, BaseActionSource src) { + if (!this.node.isActive() || !this.access.hasPermission(AccessRestriction.READ)) return null; + if (this.externalSystem != null && request != null) { + IStorageMonitorable monitor = this.externalSystem.getMonitorable(this.node.getSide().getOpposite(), src); + if (monitor == null) return null; + IMEMonitor fluidInventory = monitor.getFluidInventory(); + if (fluidInventory == null) return null; + return fluidInventory.extractItems(request, mode, src); - @Override - public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, BaseActionSource src) { - if (!this.node.isActive() - || !(this.access == AccessRestriction.READ || this.access == AccessRestriction.READ_WRITE)) - return null; - if (this.externalSystem != null && request != null) { - IStorageMonitorable monitor = this.externalSystem.getMonitorable( - this.node.getSide().getOpposite(), src); - if (monitor == null) - return null; - IMEMonitor fluidInventory = monitor - .getFluidInventory(); - if (fluidInventory == null) - return null; - return fluidInventory.extractItems(request, mode, src); + } else if (externalHandler != null && request != null) { + IMEInventory inventory = externalHandler.getInventory( + this.tile, + this.node.getSide().getOpposite(), + StorageChannel.FLUIDS, + new MachineSource(this.node)); + if (inventory == null) return null; + return inventory.extractItems(request, mode, new MachineSource(this.node)); + } + if (this.tank == null || request == null) return null; + FluidStack toDrain = request.getFluidStack(); + if (!this.tank.canDrain(this.node.getSide().getOpposite(), toDrain.getFluid())) return null; - }else if(externalHandler != null && request != null){ - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), StorageChannel.FLUIDS, new MachineSource(this.node)); - if(inventory == null) - return null; - return inventory.extractItems(request, mode, new MachineSource(this.node)); - } - if (this.tank == null || request == null || this.access == AccessRestriction.WRITE || this.access == AccessRestriction.NO_ACCESS) - return null; - FluidStack toDrain = request.getFluidStack(); - int drained = 0; - int drained2 = 0; - do { - FluidStack drain = this.tank.drain(this.node.getSide().getOpposite(), new FluidStack(toDrain.getFluid(), toDrain.amount - drained), mode == Actionable.MODULATE); - if (drain == null) - drained2 = 0; - else - drained2 = drain.amount; - drained = drained + drained2; - } while (toDrain.amount != drained && drained2 != 0); - if (drained == 0) - return null; - IItemList fluids = getAvailableItems(AEApi.instance().storage().createFluidList()); - for(IAEFluidStack fluid : fluids){ - if(fluid.getFluid() == request.getFluid()){ - drained = (int) Math.min(drained, fluid.getStackSize()); - } - } + FluidStack drain = this.tank.drain( + this.node.getSide().getOpposite(), + new FluidStack(toDrain.getFluid(), toDrain.amount), + mode == Actionable.MODULATE); - if (drained == toDrain.amount) - return request; - return FluidUtil.createAEFluidStack(toDrain.getFluidID(), drained); - } + if (drain == null || !drain.getFluid().equals(request.getFluid())) { + return null; + } else if (drain.amount == 0) { + return null; + } else if (drain.amount == toDrain.amount) { + return request; + } else { + return FluidUtil.createAEFluidStack(toDrain.getFluidID(), drain.amount); + } + } - @Override - public AccessRestriction getAccess() { - return this.access; - } + @Override + public AccessRestriction getAccess() { + return this.access; + } - @Override - public IItemList getAvailableItems( - IItemList out) { - if (!this.node.isActive() || !(this.access == AccessRestriction.READ || this.access == AccessRestriction.READ_WRITE)) - return out; - if (this.externalSystem != null) { - IStorageMonitorable monitor = this.externalSystem.getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)); - if (monitor == null) - return out; - IMEMonitor fluidInventory = monitor.getFluidInventory(); - if (fluidInventory == null) - return out; - IItemList list = this.externalSystem.getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)).getFluidInventory().getStorageList(); - for (IAEFluidStack stack : list) { - out.add(stack); - } - }else if(externalHandler != null){ - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), StorageChannel.FLUIDS, new MachineSource(this.node)); - if(inventory == null) - return out; - IItemList list = inventory.getAvailableItems(AEApi.instance().storage().createFluidList()); - for(IAEFluidStack stack : list){ - out.add(stack); - } - } else if (this.tank != null) { - FluidTankInfo[] infoArray = this.tank.getTankInfo(this.node.getSide().getOpposite()); - if (infoArray != null && infoArray.length > 0){ - for(FluidTankInfo info : infoArray){ - if(info.fluid != null) - out.add(AEApi.instance().storage().createFluidStack(info.fluid)); - } - } - } - return out; - } + @Override + public IItemList getAvailableItems(IItemList out, int iteration) { + if (!this.node.isActive() + || !(this.access == AccessRestriction.READ || this.access == AccessRestriction.READ_WRITE)) + return out; + if (this.externalSystem != null) { + IStorageMonitorable monitor = this.externalSystem + .getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (monitor == null) return out; + IMEMonitor fluidInventory = monitor.getFluidInventory(); + if (fluidInventory == null) return out; + IItemList list = this.externalSystem + .getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)).getFluidInventory() + .getStorageList(); + for (IAEFluidStack stack : list) { + out.add(stack); + } + } else if (externalHandler != null) { + IMEInventory inventory = externalHandler.getInventory( + this.tile, + this.node.getSide().getOpposite(), + StorageChannel.FLUIDS, + new MachineSource(this.node)); + if (inventory == null) return out; + IItemList list = inventory + .getAvailableItems(AEApi.instance().storage().createFluidList(), iteration); + for (IAEFluidStack stack : list) { + out.add(stack); + } + } else if (this.tank != null) { + FluidTankInfo[] infoArray = this.tank.getTankInfo(this.node.getSide().getOpposite()); + if (infoArray != null && infoArray.length > 0) { + for (FluidTankInfo info : infoArray) { + if (info.fluid != null) out.add(AEApi.instance().storage().createFluidStack(info.fluid)); + } + } + } + return out; + } - @Override - public StorageChannel getChannel() { - return StorageChannel.FLUIDS; - } + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } - @Override - public int getPriority() { - return this.node.getPriority(); - } + @Override + public int getPriority() { + return this.node.getPriority(); + } - @Override - public int getSlot() { - return 0; - } + @Override + public int getSlot() { + return 0; + } - @Override - public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, - BaseActionSource src) { - if (!(this.access == AccessRestriction.WRITE || this.access == AccessRestriction.READ_WRITE)) - return null; - if (this.externalSystem != null && input != null) { - IStorageMonitorable monitor = this.externalSystem.getMonitorable(this.node.getSide().getOpposite(), src); - if (monitor == null) - return input; - IMEMonitor fluidInventory = monitor.getFluidInventory(); - if (fluidInventory == null) - return input; - return fluidInventory.injectItems(input, mode, src); - }else if(externalHandler != null && input != null){ - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), StorageChannel.FLUIDS, new MachineSource(this.node)); - if(inventory == null) - return input; - return inventory.injectItems(input, mode, new MachineSource(this.node)); - } - if (this.tank == null || input == null || !canAccept(input)) - return input; - FluidStack toFill = input.getFluidStack(); - int filled = 0; - int filled2 = 0; - do { - filled2 = this.tank.fill(this.node.getSide().getOpposite(), new FluidStack(toFill.getFluid(), toFill.amount - filled), mode == Actionable.MODULATE); - filled = filled + filled2; - } while (filled2 != 0 && filled != toFill.amount); - FluidTankInfo[] infos = this.tank.getTankInfo(this.node.getSide().getOpposite()); - int maxFill = 0; - for(FluidTankInfo info : infos){ - if(info.fluid == null) - maxFill += info.capacity; - else if(info.fluid.getFluid() == toFill.getFluid()) - maxFill += info.capacity - info.fluid.amount; - } - filled = Math.min(filled, maxFill); - if (filled == toFill.amount) - return null; - return FluidUtil.createAEFluidStack(toFill.getFluidID(), toFill.amount - filled); - } + @Override + public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, BaseActionSource src) { + if (!(this.access == AccessRestriction.WRITE || this.access == AccessRestriction.READ_WRITE)) return null; + if (this.externalSystem != null && input != null) { + IStorageMonitorable monitor = this.externalSystem.getMonitorable(this.node.getSide().getOpposite(), src); + if (monitor == null) return input; + IMEMonitor fluidInventory = monitor.getFluidInventory(); + if (fluidInventory == null) return input; + return fluidInventory.injectItems(input, mode, src); + } else if (externalHandler != null && input != null) { + IMEInventory inventory = externalHandler.getInventory( + this.tile, + this.node.getSide().getOpposite(), + StorageChannel.FLUIDS, + new MachineSource(this.node)); + if (inventory == null) return input; + return inventory.injectItems(input, mode, new MachineSource(this.node)); + } + if (this.tank == null || input == null || !canAccept(input)) return input; + FluidStack toFill = input.getFluidStack(); + int filled = this.tank.fill( + this.node.getSide().getOpposite(), + new FluidStack(toFill.getFluid(), toFill.amount), + mode == Actionable.MODULATE); + if (filled == toFill.amount) return null; + return FluidUtil.createAEFluidStack(toFill.getFluidID(), toFill.amount - filled); + } - @Override - public boolean isPrioritized(IAEFluidStack input) { - if (input == null) - return false; - for (Fluid fluid : this.prioritizedFluids) - if (fluid == input.getFluid()) - return true; - return false; - } + @Override + public boolean isPrioritized(IAEFluidStack input) { + if (input == null) return false; + else if (this.prioritizedFluids.isEmpty()) return true; - @Override - public boolean isValid(Object verificationToken) { - return true; - } + for (Fluid fluid : this.prioritizedFluids) if (fluid == input.getFluid()) return !this.inverted; + return this.inverted; + } - @Override - public void onListUpdate() { + @Override + public boolean isValid(Object verificationToken) { + return true; + } - } + @Override + public void onListUpdate() {} - public void onNeighborChange() { - if (this.externalSystem != null) { - IStorageMonitorable monitor = this.externalSystem.getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)); - if (monitor != null) { - IMEMonitor fluidInventory = monitor.getFluidInventory(); - if (fluidInventory != null) { - fluidInventory.removeListener(this); - } - } - } - this.tank = null; - ForgeDirection orientation = this.node.getSide(); - TileEntity hostTile = this.node.getHostTile(); - if (hostTile == null) - return; - if (hostTile.getWorldObj() == null) - return; - TileEntity tileEntity = hostTile.getWorldObj().getTileEntity( - hostTile.xCoord + orientation.offsetX, - hostTile.yCoord + orientation.offsetY, - hostTile.zCoord + orientation.offsetZ); - this.tile = tileEntity; - this.tank = null; - this.externalSystem = null; - if(tileEntity == null){ - this.externalHandler = null; - return; - } - this.externalHandler = AEApi.instance().registries().externalStorage().getHandler(tileEntity, this.node.getSide().getOpposite(), StorageChannel.FLUIDS, new MachineSource(this.node)); - if (tileEntity instanceof ITileStorageMonitorable) { - this.externalSystem = (ITileStorageMonitorable) tileEntity; - IStorageMonitorable monitor = this.externalSystem.getMonitorable( - this.node.getSide().getOpposite(), new MachineSource( - this.node)); - if (monitor == null) - return; - IMEMonitor fluidInventory = monitor - .getFluidInventory(); - if (fluidInventory == null) - return; - fluidInventory.addListener(this, null); + public void onNeighborChange() { + if (this.externalSystem != null) { + IStorageMonitorable monitor = this.externalSystem + .getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (monitor != null) { + IMEMonitor fluidInventory = monitor.getFluidInventory(); + if (fluidInventory != null) { + fluidInventory.removeListener(this); + } + } + } + this.tank = null; + ForgeDirection orientation = this.node.getSide(); + TileEntity hostTile = this.node.getHostTile(); + if (hostTile == null) return; + if (hostTile.getWorldObj() == null) return; + TileEntity tileEntity = hostTile.getWorldObj().getTileEntity( + hostTile.xCoord + orientation.offsetX, + hostTile.yCoord + orientation.offsetY, + hostTile.zCoord + orientation.offsetZ); + this.tile = tileEntity; + this.tank = null; + this.externalSystem = null; + if (tileEntity == null) { + this.externalHandler = null; + return; + } + this.externalHandler = AEApi.instance().registries().externalStorage().getHandler( + tileEntity, + this.node.getSide().getOpposite(), + StorageChannel.FLUIDS, + new MachineSource(this.node)); + if (tileEntity instanceof ITileStorageMonitorable) { + this.externalSystem = (ITileStorageMonitorable) tileEntity; + IStorageMonitorable monitor = this.externalSystem + .getMonitorable(this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (monitor == null) return; + IMEMonitor fluidInventory = monitor.getFluidInventory(); + if (fluidInventory == null) return; + fluidInventory.addListener(this, null); - }else if (externalHandler == null && tileEntity instanceof IFluidHandler) - this.tank = (IFluidHandler) tileEntity; - } + } else + if (externalHandler == null && tileEntity instanceof IFluidHandler) this.tank = (IFluidHandler) tileEntity; + } - @Override - public void postChange(IBaseMonitor monitor, - Iterable change, BaseActionSource actionSource) { - IGridNode gridNode = this.node.getGridNode(); - if (gridNode != null) { - IGrid grid = gridNode.getGrid(); - if (grid != null) { - grid.postEvent(new MENetworkCellArrayUpdate()); - gridNode.getGrid().postEvent(new MENetworkStorageEvent(this.node.getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); - } - this.node.getHost().markForUpdate(); - } - } + @Override + public void postChange(IBaseMonitor monitor, Iterable change, + BaseActionSource actionSource) { + IGridNode gridNode = this.node.getGridNode(); + if (gridNode != null) { + IGrid grid = gridNode.getGrid(); + if (grid != null) { + grid.postEvent(new MENetworkCellArrayUpdate()); + gridNode.getGrid().postEvent( + new MENetworkStorageEvent(this.node.getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); + } + this.node.getHost().markForUpdate(); + } + } - public void setAccessRestriction(AccessRestriction access) { - this.access = access; - } + public void setAccessRestriction(AccessRestriction access) { + this.access = access; + } - public void setInverted(boolean _inverted) { - this.inverted = _inverted; - } + public void setInverted(boolean _inverted) { + this.inverted = _inverted; + } - public void setPrioritizedFluids(Fluid[] _fluids) { - this.prioritizedFluids.clear(); - for (Fluid fluid : _fluids) { - if (fluid != null) - this.prioritizedFluids.add(fluid); - } - } + public void setPrioritizedFluids(Fluid[] _fluids) { + this.prioritizedFluids.clear(); + for (Fluid fluid : _fluids) { + if (fluid != null) this.prioritizedFluids.add(fluid); + } + } - @Override - public boolean validForPass(int i) { - return true; // TODO - } + @Override + public boolean validForPass(int i) { + return true; // TODO + } } diff --git a/src/main/scala/extracells/inventory/HandlerPartStorageGas.java b/src/main/scala/extracells/inventory/HandlerPartStorageGas.java index a6acd9975..6ec9f89f5 100644 --- a/src/main/scala/extracells/inventory/HandlerPartStorageGas.java +++ b/src/main/scala/extracells/inventory/HandlerPartStorageGas.java @@ -1,5 +1,9 @@ package extracells.inventory; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; + import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -17,174 +21,163 @@ import extracells.api.ECApi; import extracells.api.IExternalGasStorageHandler; import extracells.part.PartFluidStorage; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; public class HandlerPartStorageGas extends HandlerPartStorageFluid { - private IExternalGasStorageHandler externalHandler = null; - - public HandlerPartStorageGas(PartFluidStorage _node) { - super(_node); - } - - @Override - public boolean canAccept(IAEFluidStack input) { - if (!this.node.isActive()) - return false; - if (this.tank == null && this.externalSystem == null && this.externalHandler == null || !(this.access == AccessRestriction.WRITE || this.access == AccessRestriction.READ_WRITE) || input == null) - return false; - if(externalHandler != null){ - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); - if (inventory == null) - return false; - }else - return false; - if (this.inverted) - return !this.prioritizedFluids.isEmpty() || !isPrioritized(input); - else - return this.prioritizedFluids.isEmpty() || isPrioritized(input); - } - - @Override - public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, BaseActionSource src) { - if (!this.node.isActive() || !(this.access == AccessRestriction.READ || this.access == AccessRestriction.READ_WRITE)) - return null; - if(externalHandler != null && request != null){ - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); - if(inventory == null) - return null; - return inventory.extractItems(request, mode, new MachineSource(this.node)); - } - return null; - } - - @Override - public AccessRestriction getAccess() { - return this.access; - } - - @Override - public IItemList getAvailableItems(IItemList out) { - if (!this.node.isActive() || !(this.access == AccessRestriction.READ || this.access == AccessRestriction.READ_WRITE)) - return out; - if(externalHandler != null) { - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); - if (inventory == null) - return out; - IItemList list = inventory.getAvailableItems(AEApi.instance().storage().createFluidList()); - for (IAEFluidStack stack : list) { - out.add(stack); - } - } - return out; - } - - @Override - public StorageChannel getChannel() { - return StorageChannel.FLUIDS; - } - - @Override - public int getPriority() { - return this.node.getPriority(); - } - - @Override - public int getSlot() { - return 0; - } - - @Override - public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, BaseActionSource src) { - if (!(this.access == AccessRestriction.WRITE || this.access == AccessRestriction.READ_WRITE)) - return input; - if(externalHandler != null && input != null){ - IMEInventory inventory = externalHandler.getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); - if(inventory == null) - return null; - return inventory.injectItems(input, mode, new MachineSource(this.node)); - } - return input; - } - - @Override - public boolean isPrioritized(IAEFluidStack input) { - if (input == null) - return false; - for (Fluid fluid : this.prioritizedFluids) - if (fluid == input.getFluid()) - return true; - return false; - } - - @Override - public boolean isValid(Object verificationToken) { - return true; - } - - @Override - public void onListUpdate() { - - } - - public void onNeighborChange() { - this.tank = null; - ForgeDirection orientation = this.node.getSide(); - TileEntity hostTile = this.node.getHostTile(); - if (hostTile == null) - return; - if (hostTile.getWorldObj() == null) - return; - TileEntity tileEntity = hostTile.getWorldObj().getTileEntity( - hostTile.xCoord + orientation.offsetX, - hostTile.yCoord + orientation.offsetY, - hostTile.zCoord + orientation.offsetZ); - this.tile = tileEntity; - this.tank = null; - this.externalSystem = null; - if(tileEntity == null){ - this.externalHandler = null; - return; - } - this.externalHandler = ECApi.instance().getHandler(tileEntity, this.node.getSide().getOpposite(), new MachineSource(this.node)); - } - - @Override - public void postChange(IBaseMonitor monitor, - Iterable change, BaseActionSource actionSource) { - IGridNode gridNode = this.node.getGridNode(); - if (gridNode != null) { - IGrid grid = gridNode.getGrid(); - if (grid != null) { - grid.postEvent(new MENetworkCellArrayUpdate()); - gridNode.getGrid().postEvent( - new MENetworkStorageEvent(this.node.getGridBlock() - .getFluidMonitor(), StorageChannel.FLUIDS)); - } - this.node.getHost().markForUpdate(); - } - } - - public void setAccessRestriction(AccessRestriction access) { - this.access = access; - } - - public void setInverted(boolean _inverted) { - this.inverted = _inverted; - } - - public void setPrioritizedFluids(Fluid[] _fluids) { - this.prioritizedFluids.clear(); - for (Fluid fluid : _fluids) { - if (fluid != null) - this.prioritizedFluids.add(fluid); - } - } - - @Override - public boolean validForPass(int i) { - return true; // TODO - } + private IExternalGasStorageHandler externalHandler = null; + + public HandlerPartStorageGas(PartFluidStorage _node) { + super(_node); + } + + @Override + public boolean canAccept(IAEFluidStack input) { + if (!this.node.isActive()) return false; + if (this.tank == null && this.externalSystem == null && this.externalHandler == null + || !(this.access == AccessRestriction.WRITE || this.access == AccessRestriction.READ_WRITE) + || input == null) + return false; + if (externalHandler != null) { + IMEInventory inventory = externalHandler + .getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (inventory == null) return false; + } else return false; + if (this.inverted) return !this.prioritizedFluids.isEmpty() || !isPrioritized(input); + else return this.prioritizedFluids.isEmpty() || isPrioritized(input); + } + + @Override + public IAEFluidStack extractItems(IAEFluidStack request, Actionable mode, BaseActionSource src) { + if (!this.node.isActive() + || !(this.access == AccessRestriction.READ || this.access == AccessRestriction.READ_WRITE)) + return null; + if (externalHandler != null && request != null) { + IMEInventory inventory = externalHandler + .getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (inventory == null) return null; + return inventory.extractItems(request, mode, new MachineSource(this.node)); + } + return null; + } + + @Override + public AccessRestriction getAccess() { + return this.access; + } + + @Override + public IItemList getAvailableItems(IItemList out, int iteration) { + if (!this.node.isActive() + || !(this.access == AccessRestriction.READ || this.access == AccessRestriction.READ_WRITE)) + return out; + if (externalHandler != null) { + IMEInventory inventory = externalHandler + .getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (inventory == null) return out; + IItemList list = inventory + .getAvailableItems(AEApi.instance().storage().createFluidList(), iteration); + for (IAEFluidStack stack : list) { + out.add(stack); + } + } + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.FLUIDS; + } + + @Override + public int getPriority() { + return this.node.getPriority(); + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public IAEFluidStack injectItems(IAEFluidStack input, Actionable mode, BaseActionSource src) { + if (!(this.access == AccessRestriction.WRITE || this.access == AccessRestriction.READ_WRITE)) return input; + if (externalHandler != null && input != null) { + IMEInventory inventory = externalHandler + .getInventory(this.tile, this.node.getSide().getOpposite(), new MachineSource(this.node)); + if (inventory == null) return null; + return inventory.injectItems(input, mode, new MachineSource(this.node)); + } + return input; + } + + @Override + public boolean isPrioritized(IAEFluidStack input) { + if (input == null) return false; + for (Fluid fluid : this.prioritizedFluids) if (fluid == input.getFluid()) return true; + return false; + } + + @Override + public boolean isValid(Object verificationToken) { + return true; + } + + @Override + public void onListUpdate() {} + + public void onNeighborChange() { + this.tank = null; + ForgeDirection orientation = this.node.getSide(); + TileEntity hostTile = this.node.getHostTile(); + if (hostTile == null) return; + if (hostTile.getWorldObj() == null) return; + TileEntity tileEntity = hostTile.getWorldObj().getTileEntity( + hostTile.xCoord + orientation.offsetX, + hostTile.yCoord + orientation.offsetY, + hostTile.zCoord + orientation.offsetZ); + this.tile = tileEntity; + this.tank = null; + this.externalSystem = null; + if (tileEntity == null) { + this.externalHandler = null; + return; + } + this.externalHandler = ECApi.instance() + .getHandler(tileEntity, this.node.getSide().getOpposite(), new MachineSource(this.node)); + } + + @Override + public void postChange(IBaseMonitor monitor, Iterable change, + BaseActionSource actionSource) { + IGridNode gridNode = this.node.getGridNode(); + if (gridNode != null) { + IGrid grid = gridNode.getGrid(); + if (grid != null) { + grid.postEvent(new MENetworkCellArrayUpdate()); + gridNode.getGrid().postEvent( + new MENetworkStorageEvent(this.node.getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); + } + this.node.getHost().markForUpdate(); + } + } + + public void setAccessRestriction(AccessRestriction access) { + this.access = access; + } + + public void setInverted(boolean _inverted) { + this.inverted = _inverted; + } + + public void setPrioritizedFluids(Fluid[] _fluids) { + this.prioritizedFluids.clear(); + for (Fluid fluid : _fluids) { + if (fluid != null) this.prioritizedFluids.add(fluid); + } + } + + @Override + public boolean validForPass(int i) { + return true; // TODO + } } diff --git a/src/main/scala/extracells/inventory/MEAdvancedInventoryHandler.java b/src/main/scala/extracells/inventory/MEAdvancedInventoryHandler.java new file mode 100644 index 000000000..e9721bc87 --- /dev/null +++ b/src/main/scala/extracells/inventory/MEAdvancedInventoryHandler.java @@ -0,0 +1,149 @@ +package extracells.inventory; + +import appeng.api.config.AccessRestriction; +import appeng.api.config.Actionable; +import appeng.api.config.IncludeExclude; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.IMEInventory; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEStack; +import appeng.api.storage.data.IItemList; +import appeng.util.prioitylist.DefaultPriorityList; +import appeng.util.prioitylist.IPartitionList; + +public class MEAdvancedInventoryHandler> implements IMEInventoryHandler { + + private final IMEInventoryHandler internal; + private int myPriority; + private IncludeExclude myWhitelist; + private AccessRestriction myAccess; + private IPartitionList myPartitionList; + + private AccessRestriction cachedAccessRestriction; + private boolean hasReadAccess; + private boolean hasWriteAccess; + + public MEAdvancedInventoryHandler(final IMEInventory i, final StorageChannel channel) { + if (i instanceof MEAdvancedInventoryHandler) { + this.internal = (MEAdvancedInventoryHandler) i; + } else { + this.internal = new MEPassThrough(i, channel); + } + + this.myPriority = 0; + this.myWhitelist = IncludeExclude.WHITELIST; + this.setBaseAccess(AccessRestriction.READ_WRITE); + this.myPartitionList = new DefaultPriorityList(); + } + + IncludeExclude getWhitelist() { + return this.myWhitelist; + } + + public void setWhitelist(final IncludeExclude myWhitelist) { + this.myWhitelist = myWhitelist; + } + + public AccessRestriction getBaseAccess() { + return this.myAccess; + } + + 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); + } + + IPartitionList getPartitionList() { + return this.myPartitionList; + } + + public void setPartitionList(final IPartitionList myPartitionList) { + this.myPartitionList = myPartitionList; + } + + @Override + public T injectItems(final T input, final Actionable type, final BaseActionSource src) { + if (!this.canAccept(input)) { + return input; + } + + return this.internal.injectItems(input, type, src); + } + + @Override + public T extractItems(final T request, final Actionable type, final BaseActionSource src) { + if (!this.hasReadAccess) { + return null; + } + + return this.internal.extractItems(request, type, src); + } + + @Override + public IItemList getAvailableItems(final IItemList out, int iteration) { + if (!this.hasReadAccess) { + return out; + } + + return this.internal.getAvailableItems(out, iteration); + } + + @Override + public StorageChannel getChannel() { + return this.internal.getChannel(); + } + + @Override + public AccessRestriction getAccess() { + return this.cachedAccessRestriction; + } + + @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 boolean canAccept(final T input) { + if (!this.hasWriteAccess) { + 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 int getPriority() { + return this.myPriority; + } + + public void setPriority(final int myPriority) { + this.myPriority = myPriority; + } + + @Override + public int getSlot() { + return this.internal.getSlot(); + } + + @Override + public boolean validForPass(final int i) { + return true; + } + + public IMEInventory getInternal() { + return this.internal; + } +} diff --git a/src/main/scala/extracells/inventory/MEPassThrough.java b/src/main/scala/extracells/inventory/MEPassThrough.java new file mode 100644 index 000000000..ff476e894 --- /dev/null +++ b/src/main/scala/extracells/inventory/MEPassThrough.java @@ -0,0 +1,93 @@ +/* + * 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 extracells.inventory; + +import appeng.api.config.AccessRestriction; +import appeng.api.config.Actionable; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.IMEInventory; +import appeng.api.storage.IMEInventoryHandler; +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 MEPassThrough(final IMEInventory i, final StorageChannel channel) { + this.wrappedChannel = channel; + this.setInternal(i); + } + + protected IMEInventory getInternal() { + return this.internal; + } + + public void setInternal(final IMEInventory i) { + this.internal = i; + } + + @Override + public T injectItems(final T input, final Actionable type, final BaseActionSource src) { + return this.internal.injectItems(input, type, src); + } + + @Override + public T extractItems(final T request, final Actionable type, final BaseActionSource src) { + return this.internal.extractItems(request, type, src); + } + + @Override + public IItemList getAvailableItems(final IItemList out, int iteration) { + return this.internal.getAvailableItems(out, iteration); + } + + @Override + public StorageChannel getChannel() { + return this.internal.getChannel(); + } + + @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; + } + + StorageChannel getWrappedChannel() { + return this.wrappedChannel; + } +} diff --git a/src/main/scala/extracells/inventory/MEVoidInventoryHandler.java b/src/main/scala/extracells/inventory/MEVoidInventoryHandler.java new file mode 100644 index 000000000..b8513e02c --- /dev/null +++ b/src/main/scala/extracells/inventory/MEVoidInventoryHandler.java @@ -0,0 +1,149 @@ +package extracells.inventory; + +import appeng.api.config.AccessRestriction; +import appeng.api.config.Actionable; +import appeng.api.config.IncludeExclude; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.IMEInventory; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEStack; +import appeng.api.storage.data.IItemList; +import appeng.util.prioitylist.DefaultPriorityList; +import appeng.util.prioitylist.IPartitionList; + +public class MEVoidInventoryHandler> implements IMEInventoryHandler { + + private final IMEInventoryHandler internal; + private int myPriority; + private IncludeExclude myWhitelist; + private AccessRestriction myAccess; + private IPartitionList myPartitionList; + + private AccessRestriction cachedAccessRestriction; + private boolean hasReadAccess; + private boolean hasWriteAccess; + + public MEVoidInventoryHandler(final IMEInventory i, final StorageChannel channel) { + if (i instanceof MEVoidInventoryHandler) { + this.internal = (MEVoidInventoryHandler) i; + } else { + this.internal = new MEPassThrough(i, channel); + } + + this.myPriority = 0; + this.myWhitelist = IncludeExclude.WHITELIST; + this.setBaseAccess(AccessRestriction.READ_WRITE); + this.myPartitionList = new DefaultPriorityList(); + } + + IncludeExclude getWhitelist() { + return this.myWhitelist; + } + + public void setWhitelist(final IncludeExclude myWhitelist) { + this.myWhitelist = myWhitelist; + } + + public AccessRestriction getBaseAccess() { + return this.myAccess; + } + + 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); + } + + IPartitionList getPartitionList() { + return this.myPartitionList; + } + + public void setPartitionList(final IPartitionList myPartitionList) { + this.myPartitionList = myPartitionList; + } + + @Override + public T injectItems(final T input, final Actionable type, final BaseActionSource src) { + if (!this.canAccept(input)) { + return input; + } + + return this.internal.injectItems(input, type, src); + } + + @Override + public T extractItems(final T request, final Actionable type, final BaseActionSource src) { + if (!this.hasReadAccess) { + return null; + } + + return this.internal.extractItems(request, type, src); + } + + @Override + public IItemList getAvailableItems(final IItemList out, int iteration) { + if (!this.hasReadAccess) { + return out; + } + + return this.internal.getAvailableItems(out, iteration); + } + + @Override + public StorageChannel getChannel() { + return this.internal.getChannel(); + } + + @Override + public AccessRestriction getAccess() { + return this.cachedAccessRestriction; + } + + @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 boolean canAccept(final T input) { + if (!this.hasWriteAccess) { + 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 int getPriority() { + return this.myPriority; + } + + public void setPriority(final int myPriority) { + this.myPriority = myPriority; + } + + @Override + public int getSlot() { + return this.internal.getSlot(); + } + + @Override + public boolean validForPass(final int i) { + return true; + } + + public IMEInventory getInternal() { + return this.internal; + } +} diff --git a/src/main/scala/extracells/inventory/VoidCellInventory.java b/src/main/scala/extracells/inventory/VoidCellInventory.java new file mode 100644 index 000000000..a7b8b9ec0 --- /dev/null +++ b/src/main/scala/extracells/inventory/VoidCellInventory.java @@ -0,0 +1,499 @@ +package extracells.inventory; + +import java.util.HashSet; +import java.util.Set; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTBase; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.oredict.OreDictionary; + +import appeng.api.AEApi; +import appeng.api.config.Actionable; +import appeng.api.config.FuzzyMode; +import appeng.api.exceptions.AppEngException; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.*; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.util.IterationCounter; +import appeng.util.Platform; +import appeng.util.item.AEItemStack; +import extracells.api.IStorageCellVoid; + +public class VoidCellInventory implements ICellInventory { + + 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 = 63; + private short storedItems = 0; + private long storedItemCount = 0; + private IItemList cellItems; + private final ItemStack cellItem; + private IStorageCellVoid cellType; + + private VoidCellInventory(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 IStorageCellVoid) { + this.cellType = (IStorageCellVoid) 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!"); + } + + this.container = container; + this.tagCompound = Platform.openNbtData(o); + this.storedItems = this.tagCompound.getShort(ITEM_TYPE_TAG); + this.storedItemCount = this.tagCompound.getLong(ITEM_COUNT_TAG); + this.cellItems = null; + } + + public static IMEInventoryHandler getCell(final ItemStack o, final ISaveProvider container2) { + try { + return new VoidCellInventoryHandler(new VoidCellInventory(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 IStorageCellVoid) { + return !((IStorageCellVoid) 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 IStorageCellVoid) { + return ((IStorageCellVoid) 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(), IterationCounter.fetchNewId()) + .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 (VoidCellInventory.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); + // Void the item + // this.updateItemCount( remainingItemSlots * Integer.MAX_VALUE); + this.saveChanges(); + } + + return r; + } else { + if (mode == Actionable.MODULATE) { + l.setStackSize(l.getStackSize() + input.getStackSize()); + // Void the item + // this.updateItemCount( input.getStackSize() * Integer.MAX_VALUE); + this.saveChanges(); + } + + return null; + } + } + + if (this.canHoldNewItem()) // room for new type, and for at least one item! + { + final long remainingItemCount = this.getRemainingItemCount() - this.getBytesPerType() * 8; + + if (remainingItemCount > 0) { + if (input.getStackSize() > remainingItemCount) { + final AEItemStack toReturn = AEItemStack.create(sharedItemStack); + toReturn.setStackSize(sharedItemStack.stackSize - remainingItemCount);; + + if (mode == Actionable.MODULATE) { + final AEItemStack toWrite = AEItemStack.create(sharedItemStack); + toWrite.setStackSize(remainingItemCount); + // Void the item + // this.cellItems.add( toWrite ); + // this.updateItemCount( toWrite.getStackSize() * Integer.MAX_VALUE); + + this.saveChanges(); + } + + return input; + } + + if (mode == Actionable.MODULATE) { + // Void the item + // 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.setLong(ITEM_COUNT_TAG, this.storedItemCount); + } + + private void saveChanges() { + // cellItems.clean(); + long 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.setLong(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.setLong(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().createPrimitiveItemList(); + } + + this.cellItems.resetStatus(); // clears totals and stuff. + + final int types = (int) this.getStoredItemTypes(); + + for (int x = 0; x < types; x++) { + final IAEItemStack t = AEItemStack.loadItemStackFromNBT(this.tagCompound.getCompoundTag(itemSlots[x])); + + if (t != null) { + this.cellItems.add(t); + } + } + + // cellItems.clean(); + } + + @Override + public IItemList getAvailableItems(final IItemList out, int iteration) { + 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(this.cellItem); + } + + @Override + public FuzzyMode getFuzzyMode() { + return this.cellType.getFuzzyMode(this.cellItem); + } + + @Override + public String getOreFilter() { + return this.cellType.getOreFilter(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()) / 8; + + return this.getStoredItemTypes() * this.getBytesPerType() + 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; + + 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/scala/extracells/inventory/VoidCellInventoryHandler.java b/src/main/scala/extracells/inventory/VoidCellInventoryHandler.java new file mode 100644 index 000000000..0cf43d4e1 --- /dev/null +++ b/src/main/scala/extracells/inventory/VoidCellInventoryHandler.java @@ -0,0 +1,121 @@ +package extracells.inventory; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; + +import appeng.api.AEApi; +import appeng.api.config.FuzzyMode; +import appeng.api.config.IncludeExclude; +import appeng.api.config.Upgrades; +import appeng.api.implementations.items.IUpgradeModule; +import appeng.api.storage.ICellInventory; +import appeng.api.storage.ICellInventoryHandler; +import appeng.api.storage.IMEInventory; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; +import appeng.util.item.AEItemStack; +import appeng.util.prioitylist.FuzzyPriorityList; +import appeng.util.prioitylist.OreFilteredList; +import appeng.util.prioitylist.PrecisePriorityList; + +public class VoidCellInventoryHandler extends MEVoidInventoryHandler implements ICellInventoryHandler { + + VoidCellInventoryHandler(final IMEInventory c) { + super(c, StorageChannel.ITEMS); + + final ICellInventory ci = this.getCellInv(); + + if (ci != null) { + final IInventory upgrades = ci.getUpgradesInventory(); + final IInventory config = ci.getConfigInventory(); + final FuzzyMode fzMode = ci.getFuzzyMode(); + final String filter = ci.getOreFilter(); + // final String filter = ""; + boolean hasInverter = false; + boolean hasFuzzy = false; + boolean hasOreFilter = false; + + 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; + case ORE_FILTER: + hasOreFilter = true; + break; + default: + } + } + } + } + this.setWhitelist(hasInverter ? IncludeExclude.BLACKLIST : IncludeExclude.WHITELIST); + if (hasOreFilter && !filter.isEmpty()) { + this.setPartitionList(new OreFilteredList(filter)); + } else { + final IItemList priorityList = AEApi.instance().storage().createItemList(); + 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)); + } + } + } + } + } + + @Override + public ICellInventory getCellInv() { + Object o = this.getInternal(); + + if (o instanceof MEPassThrough) { + o = ((MEPassThrough) o).getInternal(); + } + + return (VoidCellInventory) (o instanceof VoidCellInventory ? o : null); + } + + @Override + public boolean isPreformatted() { + return !this.getPartitionList().isEmpty(); + } + + @Override + public boolean isFuzzy() { + return this.getPartitionList() instanceof FuzzyPriorityList; + } + + @Override + public IncludeExclude getIncludeExcludeMode() { + return this.getWhitelist(); + } + + public int getStatusForCell() { + ICellInventory c = this.getCellInv(); + int val = 0; + if (c != null) { + val = this.getCellInv().getStatusForCell(); + } + + if (val == 1 && this.isPreformatted()) { + val = 2; + } + + return val; + } +} diff --git a/src/main/scala/extracells/item/CraftingTerminal.scala b/src/main/scala/extracells/item/CraftingTerminal.scala index af9a2063a..63e9ac907 100644 --- a/src/main/scala/extracells/item/CraftingTerminal.scala +++ b/src/main/scala/extracells/item/CraftingTerminal.scala @@ -6,19 +6,26 @@ import extracells.integration.WirelessCrafting.WirelessCrafting import net.minecraft.item.{Item, ItemStack} import net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTerminalItem -@Optional.Interface(iface = "net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTerminalItem", modid = "ae2wct", striprefs = true) -trait CraftingTerminal extends Item with IWirelessCraftingTerminalItem{ +@Optional.Interface( + iface = + "net.p455w0rd.wirelesscraftingterminal.api.IWirelessCraftingTerminalItem", + modid = "ae2wct", + striprefs = true +) +trait CraftingTerminal extends Item with IWirelessCraftingTerminalItem { @Optional.Method(modid = "ae2wct") - def checkForBooster (wirelessTerminal: ItemStack):Boolean = { - if(wirelessTerminal.hasTagCompound()) { - val boosterNBTList = wirelessTerminal.getTagCompound().getTagList("BoosterSlot", 10) - if(boosterNBTList != null) { + def checkForBooster(wirelessTerminal: ItemStack): Boolean = { + if (wirelessTerminal.hasTagCompound()) { + val boosterNBTList = + wirelessTerminal.getTagCompound().getTagList("BoosterSlot", 10) + if (boosterNBTList != null) { val boosterTagCompound = boosterNBTList.getCompoundTagAt(0) - if(boosterTagCompound != null) { + if (boosterTagCompound != null) { val boosterCard = ItemStack.loadItemStackFromNBT(boosterTagCompound) - if(boosterCard != null) { - return boosterCard.getItem() == WirelessCrafting.getBoosterItem && WirelessCrafting.isBoosterEnabled + if (boosterCard != null) { + return boosterCard + .getItem() == WirelessCrafting.getBoosterItem && WirelessCrafting.isBoosterEnabled } } } @@ -31,12 +38,15 @@ trait CraftingTerminal extends Item with IWirelessCraftingTerminalItem{ override def handler(): IFeatureHandler = null @Optional.Method(modid = "ae2wct") - override def postInit() :Unit = {} + override def postInit(): Unit = {} @Optional.Method(modid = "ae2wct") override def isWirelessCraftingEnabled(itemStack: ItemStack): Boolean = { if (this == ItemWirelessTerminalUniversal) - ItemWirelessTerminalUniversal.isInstalled(itemStack, TerminalType.CRAFTING) + ItemWirelessTerminalUniversal.isInstalled( + itemStack, + TerminalType.CRAFTING + ) else true } diff --git a/src/main/scala/extracells/item/EssensiaTerminal.scala b/src/main/scala/extracells/item/EssensiaTerminal.scala index bee8a9c04..57d370564 100644 --- a/src/main/scala/extracells/item/EssensiaTerminal.scala +++ b/src/main/scala/extracells/item/EssensiaTerminal.scala @@ -5,11 +5,16 @@ import net.minecraft.item.{Item, ItemStack} import net.minecraft.nbt.NBTTagCompound import thaumicenergistics.api.IThEWirelessEssentiaTerminal -@Optional.Interface(iface = "thaumicenergistics.api.IThEWirelessEssentiaTerminal", modid = "thaumicenergistics", striprefs = true) -trait EssensiaTerminal extends Item with IThEWirelessEssentiaTerminal{ +@Optional.Interface( + iface = "thaumicenergistics.api.IThEWirelessEssentiaTerminal", + modid = "thaumicenergistics", + striprefs = true +) +trait EssensiaTerminal extends Item with IThEWirelessEssentiaTerminal { - - override def getWETerminalTag(terminalItemstack: ItemStack): NBTTagCompound = { + override def getWETerminalTag( + terminalItemstack: ItemStack + ): NBTTagCompound = { val tag = ensureTagCompound(terminalItemstack) if (!tag.hasKey("essentia")) tag.setTag("essentia", new NBTTagCompound) diff --git a/src/main/scala/extracells/item/ItemAdvancedStorageCell.java b/src/main/scala/extracells/item/ItemAdvancedStorageCell.java new file mode 100644 index 000000000..f3f1e3c25 --- /dev/null +++ b/src/main/scala/extracells/item/ItemAdvancedStorageCell.java @@ -0,0 +1,224 @@ +package extracells.item; + +import java.text.NumberFormat; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; +import java.util.Set; + +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; + +import appeng.api.AEApi; +import appeng.api.config.FuzzyMode; +import appeng.api.config.IncludeExclude; +import appeng.api.exceptions.MissingDefinition; +import appeng.api.implementations.items.IItemGroup; +import appeng.api.storage.ICellInventory; +import appeng.api.storage.ICellInventoryHandler; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEItemStack; +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; +import appeng.core.localization.GuiText; +import appeng.items.AEBaseItem; +import appeng.items.contents.CellConfig; +import appeng.items.contents.CellUpgrades; +import appeng.util.Platform; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.api.IStorageCellAdvanced; +import extracells.inventory.AdvancedCellInventoryHandler; +import extracells.util.DeprecationWarning; + +public final class ItemAdvancedStorageCell extends AEBaseItem implements IStorageCellAdvanced, IItemGroup { + + private final long totalBytes; + private final int totalTypes; + private final int perType; + private final double idleDrain; + private final String suffix; + private IIcon icon; + Random r = new Random(); + + public ItemAdvancedStorageCell(long bytes, int types, int bytesPerType, double drain, String suffix) { + + this.setFeature(EnumSet.of(AEFeature.StorageCells)); + this.setMaxStackSize(1); + this.totalBytes = bytes; + this.totalTypes = types; + this.perType = bytesPerType; + this.idleDrain = drain; + this.suffix = suffix; + } + + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final EntityPlayer player, final List lines, + final boolean displayMoreInfo) { + DeprecationWarning.addGeneralDeprecationWarning(lines); + DeprecationWarning.addContentTransferInfo(lines); + + final IMEInventoryHandler inventory = AEApi.instance().registries().cell() + .getCellInventory(stack, null, StorageChannel.ITEMS); + + if (inventory instanceof AdvancedCellInventoryHandler) { + final ICellInventoryHandler handler = (ICellInventoryHandler) inventory; + + final ICellInventory cellInventory = handler.getCellInv(); + + if (cellInventory != null) { + lines.add( + NumberFormat.getInstance().format(cellInventory.getUsedBytes()) + " " + + GuiText.Of.getLocal() + + ' ' + + NumberFormat.getInstance().format(cellInventory.getTotalBytes()) + + ' ' + + GuiText.BytesUsed.getLocal()); + + format(lines, handler, cellInventory); + } + } + } + + static void format(List lines, ICellInventoryHandler handler, ICellInventory cellInventory) { + lines.add( + NumberFormat.getInstance().format(cellInventory.getStoredItemTypes()) + " " + + GuiText.Of.getLocal() + + ' ' + + NumberFormat.getInstance().format(cellInventory.getTotalItemTypes()) + + ' ' + + GuiText.Types.getLocal()); + + if (handler.isPreformatted()) { + String filter = cellInventory.getOreFilter(); + + if (filter.isEmpty()) { + final String list = (handler.getIncludeExcludeMode() == IncludeExclude.WHITELIST ? GuiText.Included + : GuiText.Excluded).getLocal(); + + if (handler.isFuzzy()) { + lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Fuzzy.getLocal()); + } else { + lines.add(GuiText.Partitioned.getLocal() + " - " + list + ' ' + GuiText.Precise.getLocal()); + } + } else { + lines.add(GuiText.PartitionedOre.getLocal() + " : " + filter); + } + } + } + + @Override + public long getBytes(final ItemStack cellItem) { + return this.totalBytes; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return this.perType; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return this.totalTypes; + } + + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + return false; + } + + @Override + public boolean storableInStorageCell() { + return false; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain(ItemStack i) { + return this.idleDrain; + } + + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return "extracells.item.storage.physical.advanced." + this.suffix; + } + + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icon = iconRegister.registerIcon("extracells:storage.physical.advanced." + this.suffix); + } + + @Override + public IIcon getIconFromDamage(int dmg) { + return this.icon; + } + + @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 String getOreFilter(ItemStack is) { + return Platform.openNbtData(is).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack is, String filter) { + Platform.openNbtData(is).setString("OreFilter", filter); + } + + @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); + } +} diff --git a/src/main/scala/extracells/item/ItemBlockCertusTank.java b/src/main/scala/extracells/item/ItemBlockCertusTank.java index a2aefe51a..9a19d2e1b 100644 --- a/src/main/scala/extracells/item/ItemBlockCertusTank.java +++ b/src/main/scala/extracells/item/ItemBlockCertusTank.java @@ -1,8 +1,7 @@ package extracells.item; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import extracells.tileentity.TileEntityCertusTank; +import java.util.List; + import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; @@ -13,191 +12,175 @@ import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.IFluidContainerItem; -import java.util.List; - -public class ItemBlockCertusTank extends ItemBlock implements - IFluidContainerItem { - - private final int capacity = 32000; - - public ItemBlockCertusTank(Block block) { - super(block); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - @SideOnly(Side.CLIENT) - public void addInformation(ItemStack stack, EntityPlayer player, List list, - boolean par4) { - if (stack != null && stack.hasTagCompound()) { - if (FluidStack.loadFluidStackFromNBT(stack.getTagCompound() - .getCompoundTag("tileEntity")) != null) - list.add(FluidStack.loadFluidStackFromNBT(stack - .getTagCompound().getCompoundTag("tileEntity")).amount - + "mB"); - } - } - - @Override - public FluidStack drain(ItemStack container, int maxDrain, boolean doDrain) { - if (container.stackTagCompound == null - || !container.stackTagCompound.hasKey("tileEntity") - || container.stackTagCompound.getCompoundTag("tileEntity") - .hasKey("Empty")) { - return null; - } - - FluidStack stack = FluidStack - .loadFluidStackFromNBT(container.stackTagCompound - .getCompoundTag("tileEntity")); - if (stack == null) { - return null; - } - - int currentAmount = stack.amount; - stack.amount = Math.min(stack.amount, maxDrain); - if (doDrain) { - if (currentAmount == stack.amount) { - container.stackTagCompound.removeTag("tileEntity"); - - if (container.stackTagCompound.hasNoTags()) { - container.stackTagCompound = null; - } - return stack; - } - - NBTTagCompound fluidTag = container.stackTagCompound - .getCompoundTag("tileEntity"); - fluidTag.setInteger("Amount", currentAmount - stack.amount); - container.stackTagCompound.setTag("tileEntity", fluidTag); - } - return stack; - } - - @Override - public int fill(ItemStack container, FluidStack resource, boolean doFill) { - if (resource == null) { - return 0; - } - - if (!doFill) { - if (container.stackTagCompound == null - || !container.stackTagCompound.hasKey("tileEntity")) { - return Math.min(this.capacity, resource.amount); - } - - FluidStack stack = FluidStack - .loadFluidStackFromNBT(container.stackTagCompound - .getCompoundTag("tileEntity")); - - if (stack == null) { - return Math.min(this.capacity, resource.amount); - } - - if (!stack.isFluidEqual(resource)) { - return 0; - } - - return Math.min(this.capacity - stack.amount, resource.amount); - } - - if (container.stackTagCompound == null) { - container.stackTagCompound = new NBTTagCompound(); - } - - if (!container.stackTagCompound.hasKey("tileEntity") - || container.stackTagCompound.getCompoundTag("tileEntity") - .hasKey("Empty")) { - NBTTagCompound fluidTag = resource.writeToNBT(new NBTTagCompound()); - - if (this.capacity < resource.amount) { - fluidTag.setInteger("Amount", this.capacity); - container.stackTagCompound.setTag("tileEntity", fluidTag); - return this.capacity; - } - - container.stackTagCompound.setTag("tileEntity", fluidTag); - return resource.amount; - } - - NBTTagCompound fluidTag = container.stackTagCompound - .getCompoundTag("tileEntity"); - FluidStack stack = FluidStack.loadFluidStackFromNBT(fluidTag); - - if (!stack.isFluidEqual(resource)) { - return 0; - } - - int filled = this.capacity - stack.amount; - if (resource.amount < filled) { - stack.amount += resource.amount; - filled = resource.amount; - } else { - stack.amount = this.capacity; - } - - container.stackTagCompound.setTag("tileEntity", - stack.writeToNBT(fluidTag)); - return filled; - } - - @Override - public int getCapacity(ItemStack container) { - return this.capacity; - } - - @Override - public FluidStack getFluid(ItemStack container) { - if (container.stackTagCompound == null - || !container.stackTagCompound.hasKey("tileEntity")) { - return null; - } - return FluidStack.loadFluidStackFromNBT(container.stackTagCompound - .getCompoundTag("tileEntity")); - } - - @Override - public String getItemStackDisplayName(ItemStack itemstack) { - if (itemstack != null) { - if (itemstack.hasTagCompound()) { - try { - FluidStack fluidInTank = FluidStack - .loadFluidStackFromNBT(itemstack.getTagCompound() - .getCompoundTag("tileEntity")); - - if (fluidInTank != null && fluidInTank.getFluid() != null) { - return StatCollector - .translateToLocal(getUnlocalizedName(itemstack)) - + " - " - + fluidInTank.getFluid().getLocalizedName( - fluidInTank); - } - } catch (Throwable ignored) {} - } - return StatCollector - .translateToLocal(getUnlocalizedName(itemstack)); - } - return ""; - } - - @Override - public boolean placeBlockAt(ItemStack stack, EntityPlayer player, - World world, int x, int y, int z, int side, float hitX, float hitY, - float hitZ, int metadata) { - if (!world.setBlock(x, y, z, this.field_150939_a, metadata, 3)) { - return false; - } - - if (world.getBlock(x, y, z) == this.field_150939_a) { - this.field_150939_a.onBlockPlacedBy(world, x, y, z, player, stack); - this.field_150939_a.onPostBlockPlaced(world, x, y, z, metadata); - } - - if (stack != null && stack.hasTagCompound()) { - ((TileEntityCertusTank) world.getTileEntity(x, y, z)) - .readFromNBTWithoutCoords(stack.getTagCompound() - .getCompoundTag("tileEntity")); - } - return true; - } -} \ No newline at end of file +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.tileentity.TileEntityCertusTank; +import extracells.util.DeprecationWarning; + +public class ItemBlockCertusTank extends ItemBlock implements IFluidContainerItem { + + private final int capacity = 32000; + + public ItemBlockCertusTank(Block block) { + super(block); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + @SideOnly(Side.CLIENT) + public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) { + DeprecationWarning.addGeneralDeprecationWarning(list); + DeprecationWarning.addContentTransferInfo(list); + + if (stack != null && stack.hasTagCompound()) { + if (FluidStack.loadFluidStackFromNBT(stack.getTagCompound().getCompoundTag("tileEntity")) != null) list.add( + FluidStack.loadFluidStackFromNBT(stack.getTagCompound().getCompoundTag("tileEntity")).amount + + "mB"); + } + } + + @Override + public FluidStack drain(ItemStack container, int maxDrain, boolean doDrain) { + if (container.stackSize != 1 || container.stackTagCompound == null + || !container.stackTagCompound.hasKey("tileEntity") + || container.stackTagCompound.getCompoundTag("tileEntity").hasKey("Empty")) { + return null; + } + + FluidStack stack = FluidStack.loadFluidStackFromNBT(container.stackTagCompound.getCompoundTag("tileEntity")); + if (stack == null) { + return null; + } + + int currentAmount = stack.amount; + stack.amount = Math.min(stack.amount, maxDrain); + if (doDrain) { + if (currentAmount == stack.amount) { + container.stackTagCompound.removeTag("tileEntity"); + + if (container.stackTagCompound.hasNoTags()) { + container.stackTagCompound = null; + } + return stack; + } + + NBTTagCompound fluidTag = container.stackTagCompound.getCompoundTag("tileEntity"); + fluidTag.setInteger("Amount", currentAmount - stack.amount); + container.stackTagCompound.setTag("tileEntity", fluidTag); + } + return stack; + } + + @Override + public int fill(ItemStack container, FluidStack resource, boolean doFill) { + if (resource == null || container.stackSize != 1) { + return 0; + } + + if (!doFill) { + if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("tileEntity")) { + return Math.min(this.capacity, resource.amount); + } + + FluidStack stack = FluidStack + .loadFluidStackFromNBT(container.stackTagCompound.getCompoundTag("tileEntity")); + + if (stack == null) { + return Math.min(this.capacity, resource.amount); + } + + if (!stack.isFluidEqual(resource)) { + return 0; + } + + return Math.min(this.capacity - stack.amount, resource.amount); + } + + if (container.stackTagCompound == null) { + container.stackTagCompound = new NBTTagCompound(); + } + + if (!container.stackTagCompound.hasKey("tileEntity") + || container.stackTagCompound.getCompoundTag("tileEntity").hasKey("Empty")) { + NBTTagCompound fluidTag = resource.writeToNBT(new NBTTagCompound()); + + if (this.capacity < resource.amount) { + fluidTag.setInteger("Amount", this.capacity); + container.stackTagCompound.setTag("tileEntity", fluidTag); + return this.capacity; + } + + container.stackTagCompound.setTag("tileEntity", fluidTag); + return resource.amount; + } + + NBTTagCompound fluidTag = container.stackTagCompound.getCompoundTag("tileEntity"); + FluidStack stack = FluidStack.loadFluidStackFromNBT(fluidTag); + + if (!stack.isFluidEqual(resource)) { + return 0; + } + + int filled = this.capacity - stack.amount; + if (resource.amount < filled) { + stack.amount += resource.amount; + filled = resource.amount; + } else { + stack.amount = this.capacity; + } + + container.stackTagCompound.setTag("tileEntity", stack.writeToNBT(fluidTag)); + return filled; + } + + @Override + public int getCapacity(ItemStack container) { + return this.capacity; + } + + @Override + public FluidStack getFluid(ItemStack container) { + if (container.stackTagCompound == null || !container.stackTagCompound.hasKey("tileEntity")) { + return null; + } + return FluidStack.loadFluidStackFromNBT(container.stackTagCompound.getCompoundTag("tileEntity")); + } + + @Override + public String getItemStackDisplayName(ItemStack itemstack) { + if (itemstack != null) { + if (itemstack.hasTagCompound()) { + try { + FluidStack fluidInTank = FluidStack + .loadFluidStackFromNBT(itemstack.getTagCompound().getCompoundTag("tileEntity")); + + if (fluidInTank != null && fluidInTank.getFluid() != null) { + return StatCollector.translateToLocal(getUnlocalizedName(itemstack)) + " - " + + fluidInTank.getFluid().getLocalizedName(fluidInTank); + } + } catch (Throwable ignored) {} + } + return StatCollector.translateToLocal(getUnlocalizedName(itemstack)); + } + return ""; + } + + @Override + public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, + float hitX, float hitY, float hitZ, int metadata) { + if (!world.setBlock(x, y, z, this.field_150939_a, metadata, 3)) { + return false; + } + + if (world.getBlock(x, y, z) == this.field_150939_a) { + this.field_150939_a.onBlockPlacedBy(world, x, y, z, player, stack); + this.field_150939_a.onPostBlockPlaced(world, x, y, z, metadata); + } + + if (stack != null && stack.hasTagCompound()) { + ((TileEntityCertusTank) world.getTileEntity(x, y, z)) + .readFromNBTWithoutCoords(stack.getTagCompound().getCompoundTag("tileEntity")); + } + return true; + } +} diff --git a/src/main/scala/extracells/item/ItemBlockECBase.java b/src/main/scala/extracells/item/ItemBlockECBase.java index f742e557f..9350bdc9c 100644 --- a/src/main/scala/extracells/item/ItemBlockECBase.java +++ b/src/main/scala/extracells/item/ItemBlockECBase.java @@ -1,8 +1,7 @@ package extracells.item; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import extracells.tileentity.TileEntityFluidInterface; +import java.util.List; + import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; @@ -14,82 +13,88 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.World; -import java.util.List; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.tileentity.TileEntityFluidInterface; +import extracells.util.DeprecationWarning; public class ItemBlockECBase extends ItemBlock { - public ItemBlockECBase(Block block) { - super(block); - setMaxDamage(0); - setHasSubtypes(true); - } - - @Override - @SideOnly(Side.CLIENT) - public IIcon getIconFromDamage(int damage) { - return Block.getBlockFromItem(this).getIcon(0, damage); - } - - @Override - public String getItemStackDisplayName(ItemStack stack) { - return StatCollector.translateToLocal(getUnlocalizedName(stack) + ".name"); - } - - @Override - public int getMetadata(int damage) { - return damage; - } - - @Override - @SideOnly(Side.CLIENT) - public int getSpriteNumber() { - return 0; - } - - @Override - @SideOnly(Side.CLIENT) - public void getSubItems(Item item, CreativeTabs tab, List list) { - list.add(new ItemStack(item)); - list.add(new ItemStack(item, 1, 1)); - } - - @Override - public String getUnlocalizedName(ItemStack stack) { - if (stack == null) - return "null"; - switch (stack.getItemDamage()) { - case 0: - return "extracells.block.fluidinterface"; - case 1: - return "extracells.block.fluidfiller"; - default: - return super.getUnlocalizedName(stack); - } - } - - @Override - public boolean placeBlockAt(ItemStack stack, EntityPlayer player, - World world, int x, int y, int z, int side, float hitX, float hitY, - float hitZ, int metadata) { - - if (!world.setBlock(x, y, z, this.field_150939_a, metadata, 3)) { - return false; - } - - if (world.getBlock(x, y, z) == this.field_150939_a) { - this.field_150939_a.onBlockPlacedBy(world, x, y, z, player, stack); - this.field_150939_a.onPostBlockPlaced(world, x, y, z, metadata); - } - - if (getMetadata(stack.getItemDamage()) == 0 && stack.hasTagCompound()) { - TileEntity tile = world.getTileEntity(x, y, z); - if (tile != null && tile instanceof TileEntityFluidInterface) { - ((TileEntityFluidInterface) tile).readFilter(stack - .getTagCompound()); - } - } - - return true; - } - + public ItemBlockECBase(Block block) { + super(block); + setMaxDamage(0); + setHasSubtypes(true); + } + + @Override + @SideOnly(Side.CLIENT) + public IIcon getIconFromDamage(int damage) { + return Block.getBlockFromItem(this).getIcon(0, damage); + } + + @Override + @SideOnly(Side.CLIENT) + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List tooltip, boolean p_77624_4_) { + DeprecationWarning.addGeneralDeprecationWarning(tooltip); + } + + @Override + public String getItemStackDisplayName(ItemStack stack) { + return StatCollector.translateToLocal(getUnlocalizedName(stack) + ".name"); + } + + @Override + public int getMetadata(int damage) { + return damage; + } + + @Override + @SideOnly(Side.CLIENT) + public int getSpriteNumber() { + return 0; + } + + @Override + @SideOnly(Side.CLIENT) + public void getSubItems(Item item, CreativeTabs tab, List list) { + list.add(new ItemStack(item)); + list.add(new ItemStack(item, 1, 1)); + } + + @Override + public String getUnlocalizedName(ItemStack stack) { + if (stack == null) return "null"; + switch (stack.getItemDamage()) { + case 0: + return "extracells.block.fluidinterface"; + case 1: + return "extracells.block.fluidfiller"; + default: + return super.getUnlocalizedName(stack); + } + } + + @Override + public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, + float hitX, float hitY, float hitZ, int metadata) { + + if (!world.setBlock(x, y, z, this.field_150939_a, metadata, 3)) { + return false; + } + + if (world.getBlock(x, y, z) == this.field_150939_a) { + this.field_150939_a.onBlockPlacedBy(world, x, y, z, player, stack); + this.field_150939_a.onPostBlockPlaced(world, x, y, z, metadata); + } + + if (getMetadata(stack.getItemDamage()) == 0 && stack.hasTagCompound()) { + TileEntity tile = world.getTileEntity(x, y, z); + if (tile != null && tile instanceof TileEntityFluidInterface) { + ((TileEntityFluidInterface) tile).readFilter(stack.getTagCompound()); + } + } + + return true; + } } diff --git a/src/main/scala/extracells/item/ItemCraftingStorage.java b/src/main/scala/extracells/item/ItemCraftingStorage.java new file mode 100644 index 000000000..52ac59b45 --- /dev/null +++ b/src/main/scala/extracells/item/ItemCraftingStorage.java @@ -0,0 +1,39 @@ +package extracells.item; + +import static extracells.item.ItemStoragePhysical.suffixes; + +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + +import appeng.block.AEBaseItemBlock; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.util.DeprecationWarning; + +public class ItemCraftingStorage extends AEBaseItemBlock { + + public ItemCraftingStorage(Block b) { + super(b); + } + + @Override + public String getUnlocalizedName(ItemStack stack) { + return String.format("%s.%s", super.getUnlocalizedName(), suffixes[stack.getItemDamage()]); + } + + @Override + public int getMetadata(int meta) { + return meta; + } + + @SuppressWarnings("unchecked") + @Override + @SideOnly(Side.CLIENT) + public void addCheckedInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) { + DeprecationWarning.addGeneralDeprecationWarning(list); + super.addCheckedInformation(stack, player, list, par4); + } +} diff --git a/src/main/scala/extracells/item/ItemECBase.java b/src/main/scala/extracells/item/ItemECBase.java new file mode 100644 index 000000000..1364acfd5 --- /dev/null +++ b/src/main/scala/extracells/item/ItemECBase.java @@ -0,0 +1,22 @@ +package extracells.item; + +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; + +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.util.DeprecationWarning; + +class ItemECBase extends Item { + + @Override + @SideOnly(Side.CLIENT) + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List tooltip, boolean p_77624_4_) { + DeprecationWarning.addGeneralDeprecationWarning(tooltip); + } + +} diff --git a/src/main/scala/extracells/item/ItemECBase.scala b/src/main/scala/extracells/item/ItemECBase.scala deleted file mode 100644 index 5294540cf..000000000 --- a/src/main/scala/extracells/item/ItemECBase.scala +++ /dev/null @@ -1,8 +0,0 @@ -package extracells.item - -import net.minecraft.item.Item - - -class ItemECBase extends Item{ - -} diff --git a/src/main/scala/extracells/item/ItemFluid.java b/src/main/scala/extracells/item/ItemFluid.java index 306a974a4..370ce57ca 100644 --- a/src/main/scala/extracells/item/ItemFluid.java +++ b/src/main/scala/extracells/item/ItemFluid.java @@ -8,12 +8,11 @@ public class ItemFluid extends ItemECBase { - @Override - public String getItemStackDisplayName(ItemStack stack) { - Fluid fluid = FluidRegistry.getFluid(stack.getItemDamage()); + @Override + public String getItemStackDisplayName(ItemStack stack) { + Fluid fluid = FluidRegistry.getFluid(stack.getItemDamage()); - if (fluid != null) - return fluid.getLocalizedName(new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME)); - return "null"; - } + if (fluid != null) return fluid.getLocalizedName(new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME)); + return "null"; + } } diff --git a/src/main/scala/extracells/item/ItemFluidPattern.java b/src/main/scala/extracells/item/ItemFluidPattern.java index ed3907a9c..bee62d136 100644 --- a/src/main/scala/extracells/item/ItemFluidPattern.java +++ b/src/main/scala/extracells/item/ItemFluidPattern.java @@ -1,11 +1,7 @@ package extracells.item; -import extracells.registries.ItemEnum; import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.EnumRarity; -import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; @@ -15,96 +11,69 @@ import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import java.util.List; +import extracells.registries.ItemEnum; public class ItemFluidPattern extends ItemECBase { - public static Fluid getFluid(ItemStack itemStack) { - if (!itemStack.hasTagCompound()) - itemStack.setTagCompound(new NBTTagCompound()); - - return FluidRegistry.getFluid(itemStack.getTagCompound().getString( - "fluidID")); - } - - public static ItemStack getPatternForFluid(Fluid fluid) { - ItemStack itemStack = new ItemStack(ItemEnum.FLUIDPATTERN.getItem(), 1); - itemStack.setTagCompound(new NBTTagCompound()); - if (fluid != null) - itemStack.getTagCompound().setString("fluidID", fluid.getName()); - return itemStack; - } - - IIcon icon; - - public ItemFluidPattern() { - setMaxStackSize(1); - } - - @Override - public IIcon getIcon(ItemStack itemStack, int pass) { - switch (pass) { - case 0: - Fluid fluid = getFluid(itemStack); - if (fluid == null) - return null; - return fluid.getIcon(); - default: - return this.icon; - } - } - - @Override - public String getItemStackDisplayName(ItemStack itemStack) { - Fluid fluid = getFluid(itemStack); - if (fluid == null) - return StatCollector.translateToLocal(getUnlocalizedName(itemStack)); - return StatCollector.translateToLocal(getUnlocalizedName(itemStack)) - + ": " + fluid.getLocalizedName(new FluidStack(fluid, 1)); - } - - @Override - public EnumRarity getRarity(ItemStack itemStack) { - return EnumRarity.uncommon; - } - - @Override - public int getSpriteNumber() { - return 1; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { - for (Fluid fluid : FluidRegistry.getRegisteredFluidIDsByFluid().keySet()) { - String name = ""; - ItemStack itemStack = new ItemStack(this, 1); - itemStack.setTagCompound(new NBTTagCompound()); - itemStack.getTagCompound().setString("fluidID", fluid.getName()); - itemList.add(itemStack); - } - } - - @Override - public String getUnlocalizedName(ItemStack itemStack) { - return "extracells.item.fluid.pattern"; - } - - @Override - public ItemStack onItemRightClick(ItemStack itemStack, World world, - EntityPlayer entityPlayer) { - if (entityPlayer.isSneaking()) - return ItemEnum.FLUIDPATTERN.getSizedStack(itemStack.stackSize); - return itemStack; - } - - @Override - public void registerIcons(IIconRegister iconRegister) { - this.icon = iconRegister.registerIcon("extracells:fluid.pattern"); - } - - @Override - public boolean requiresMultipleRenderPasses() { - return true; - } + public static Fluid getFluid(ItemStack itemStack) { + if (!itemStack.hasTagCompound()) itemStack.setTagCompound(new NBTTagCompound()); + + return FluidRegistry.getFluid(itemStack.getTagCompound().getString("fluidID")); + } + + public static ItemStack getPatternForFluid(Fluid fluid) { + ItemStack itemStack = new ItemStack(ItemEnum.FLUIDPATTERN.getItem(), 1); + itemStack.setTagCompound(new NBTTagCompound()); + if (fluid != null) itemStack.getTagCompound().setString("fluidID", fluid.getName()); + return itemStack; + } + + IIcon icon; + + public ItemFluidPattern() { + setMaxStackSize(1); + } + + @Override + public IIcon getIcon(ItemStack itemStack, int pass) { + if (pass == 0) { + Fluid fluid = getFluid(itemStack); + if (fluid != null) return fluid.getIcon(); + } + return this.icon; + } + + @Override + public String getItemStackDisplayName(ItemStack itemStack) { + Fluid fluid = getFluid(itemStack); + if (fluid == null) return StatCollector.translateToLocal(getUnlocalizedName(itemStack)); + return StatCollector.translateToLocal(getUnlocalizedName(itemStack)) + ": " + + fluid.getLocalizedName(new FluidStack(fluid, 1)); + } + + @Override + public int getSpriteNumber() { + return 1; + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return "extracells.item.fluid.pattern"; + } + + @Override + public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) { + if (entityPlayer.isSneaking()) return ItemEnum.FLUIDPATTERN.getSizedStack(itemStack.stackSize); + return itemStack; + } + + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icon = iconRegister.registerIcon("extracells:fluid.pattern"); + } + + @Override + public boolean requiresMultipleRenderPasses() { + return true; + } } diff --git a/src/main/scala/extracells/item/ItemInternalCraftingPattern.java b/src/main/scala/extracells/item/ItemInternalCraftingPattern.java index 0796e054f..c981eff54 100644 --- a/src/main/scala/extracells/item/ItemInternalCraftingPattern.java +++ b/src/main/scala/extracells/item/ItemInternalCraftingPattern.java @@ -1,35 +1,34 @@ package extracells.item; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + import appeng.api.implementations.ICraftingPatternItem; import appeng.api.networking.crafting.ICraftingPatternDetails; import extracells.crafting.CraftingPattern; import extracells.crafting.CraftingPattern2; -import net.minecraft.item.ItemStack; -import net.minecraft.world.World; public class ItemInternalCraftingPattern extends ItemECBase implements ICraftingPatternItem { - @Override - public ICraftingPatternDetails getPatternForItem(ItemStack is, World w) { - if (is == null || w == null) - return null; - switch (is.getItemDamage()) { - case 0: - if (is.hasTagCompound() && is.getTagCompound().hasKey("item")) { - ItemStack s = ItemStack.loadItemStackFromNBT(is.getTagCompound().getCompoundTag("item")); - if (s != null && s.getItem() instanceof ICraftingPatternItem) - return new CraftingPattern(((ICraftingPatternItem) s.getItem()).getPatternForItem(s, w)); - } - return null; - case 1: - if (is.hasTagCompound() && is.getTagCompound().hasKey("item")) { - ItemStack s = ItemStack.loadItemStackFromNBT(is.getTagCompound().getCompoundTag("item")); - if (s != null && s.getItem() instanceof ICraftingPatternItem) - return new CraftingPattern2(((ICraftingPatternItem) s.getItem()).getPatternForItem(s, w)); - } - default: - return null; - } - } - + @Override + public ICraftingPatternDetails getPatternForItem(ItemStack is, World w) { + if (is == null || w == null) return null; + switch (is.getItemDamage()) { + case 0: + if (is.hasTagCompound() && is.getTagCompound().hasKey("item")) { + ItemStack s = ItemStack.loadItemStackFromNBT(is.getTagCompound().getCompoundTag("item")); + if (s != null && s.getItem() instanceof ICraftingPatternItem) + return new CraftingPattern(((ICraftingPatternItem) s.getItem()).getPatternForItem(s, w)); + } + return null; + case 1: + if (is.hasTagCompound() && is.getTagCompound().hasKey("item")) { + ItemStack s = ItemStack.loadItemStackFromNBT(is.getTagCompound().getCompoundTag("item")); + if (s != null && s.getItem() instanceof ICraftingPatternItem) + return new CraftingPattern2(((ICraftingPatternItem) s.getItem()).getPatternForItem(s, w)); + } + default: + return null; + } + } } diff --git a/src/main/scala/extracells/item/ItemOCUpgrade.scala b/src/main/scala/extracells/item/ItemOCUpgrade.scala index edd9b2f8b..99e9e4e6d 100644 --- a/src/main/scala/extracells/item/ItemOCUpgrade.scala +++ b/src/main/scala/extracells/item/ItemOCUpgrade.scala @@ -5,25 +5,31 @@ import extracells.integration.opencomputers.UpgradeItemAEBase import net.minecraft.creativetab.CreativeTabs import net.minecraft.item.{Item, ItemStack} -object ItemOCUpgrade extends ItemECBase with UpgradeItemAEBase{ +object ItemOCUpgrade extends ItemECBase with UpgradeItemAEBase { setTextureName("extracells:upgrade.oc") def THIS = this - override def getUnlocalizedName = super.getUnlocalizedName.replace("item.extracells", "extracells.item") + override def getUnlocalizedName = + super.getUnlocalizedName.replace("item.extracells", "extracells.item") override def getUnlocalizedName(stack: ItemStack) = getUnlocalizedName @SideOnly(Side.CLIENT) - override def getSubItems(item : Item, tab : CreativeTabs, list : java.util.List[_]) { - def add[T](list: java.util.List[T], value: Any) = list.add(value.asInstanceOf[T]) + override def getSubItems( + item: Item, + tab: CreativeTabs, + list: java.util.List[_] + ) { + def add[T](list: java.util.List[T], value: Any) = + list.add(value.asInstanceOf[T]) add(list, new ItemStack(item, 1, 2)) add(list, new ItemStack(item, 1, 1)) add(list, new ItemStack(item, 1, 0)) } - override def getItemStackDisplayName(stack : ItemStack): String = { + override def getItemStackDisplayName(stack: ItemStack): String = { val tier = stack.getItemDamage match { case 0 => 3 case 1 => 2 diff --git a/src/main/scala/extracells/item/ItemPartECBase.java b/src/main/scala/extracells/item/ItemPartECBase.java index e370dd2f3..adfbf6dad 100644 --- a/src/main/scala/extracells/item/ItemPartECBase.java +++ b/src/main/scala/extracells/item/ItemPartECBase.java @@ -1,5 +1,19 @@ package extracells.item; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.MathHelper; +import net.minecraft.world.World; + +import org.apache.logging.log4j.Level; + import appeng.api.AEApi; import appeng.api.config.Upgrades; import appeng.api.implementations.items.IItemGroup; @@ -10,111 +24,89 @@ import cpw.mods.fml.relauncher.SideOnly; import extracells.api.ECApi; import extracells.registries.PartEnum; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.EnumRarity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.util.MathHelper; -import net.minecraft.world.World; -import org.apache.logging.log4j.Level; - -import java.util.List; -import java.util.Map; -import java.util.Set; +import extracells.util.DeprecationWarning; public class ItemPartECBase extends Item implements IPartItem, IItemGroup { - public ItemPartECBase() { - setMaxDamage(0); - setHasSubtypes(true); - AEApi.instance().partHelper().setItemBusRenderer(this); - - for (PartEnum part : PartEnum.values()) { - Map possibleUpgradesList = part.getUpgrades(); - for (Upgrades upgrade : possibleUpgradesList.keySet()) { - upgrade.registerItem(new ItemStack(this, 1, part.ordinal()), - possibleUpgradesList.get(upgrade)); - } - } - } - - @Override - public IPart createPartFromItemStack(ItemStack itemStack) { - try { - return PartEnum.values()[MathHelper.clamp_int( - itemStack.getItemDamage(), 0, PartEnum.values().length - 1)] - .newInstance(itemStack); - } catch (Throwable ex) { - FMLLog.log( - Level.ERROR, - ex, - "ExtraCells2 severe error - could not create AE2 Part from ItemStack! This should not happen!\n" - + "[ExtraCells2 SEVERE] Contact Leonelf/M3gaFr3ak with the following stack trace.\n" - + "[ExtraCells2 SEVERE] Offending item: '%s'", - itemStack.toString()); - return null; - } - } - - @Override - public String getItemStackDisplayName(ItemStack stack) { - if (stack == null) - return super.getItemStackDisplayName(null); - if (stack.getItemDamage() == PartEnum.INTERFACE.ordinal()) - return ECApi.instance().blocks().blockInterface().maybeItem().get().getItemStackDisplayName( - ECApi.instance().blocks().blockInterface().maybeStack(1).get()); - return super.getItemStackDisplayName(stack); - } - - @Override - public EnumRarity getRarity(ItemStack itemStack) { - if (itemStack != null - && itemStack.getItemDamage() == PartEnum.OREDICTEXPORTBUS - .ordinal()) - return super.getRarity(itemStack); - return EnumRarity.rare; - } - - @Override - @SideOnly(Side.CLIENT) - public int getSpriteNumber() { - return 0; - } - - @Override - @SuppressWarnings("unchecked") - public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { - for (int i = 0; i < PartEnum.values().length; i++) { - PartEnum part = PartEnum.values()[i]; - if(part.getMod() == null || part.getMod().isEnabled()) - itemList.add(new ItemStack(item, 1, i)); - } - } - - @Override - public String getUnlocalizedGroupName(Set otherItems, - ItemStack itemStack) { - return PartEnum.values()[MathHelper.clamp_int( - itemStack.getItemDamage(), 0, PartEnum.values().length - 1)] - .getGroupName(); - } - - @Override - public String getUnlocalizedName(ItemStack itemStack) { - return PartEnum.values()[MathHelper.clamp_int( - itemStack.getItemDamage(), 0, PartEnum.values().length - 1)] - .getUnlocalizedName(); - } - - @Override - 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); - } - - @Override - public void registerIcons(IIconRegister _iconRegister) {} + public ItemPartECBase() { + setMaxDamage(0); + setHasSubtypes(true); + AEApi.instance().partHelper().setItemBusRenderer(this); + + for (PartEnum part : PartEnum.values()) { + Map possibleUpgradesList = part.getUpgrades(); + for (Upgrades upgrade : possibleUpgradesList.keySet()) { + upgrade.registerItem(new ItemStack(this, 1, part.ordinal()), possibleUpgradesList.get(upgrade)); + } + } + } + + @Override + @SideOnly(Side.CLIENT) + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List tooltip, boolean p_77624_4_) { + DeprecationWarning.addGeneralDeprecationWarning(tooltip); + } + + @Override + public IPart createPartFromItemStack(ItemStack itemStack) { + try { + return PartEnum.values()[MathHelper.clamp_int(itemStack.getItemDamage(), 0, PartEnum.values().length - 1)] + .newInstance(itemStack); + } catch (Throwable ex) { + FMLLog.log( + Level.ERROR, + ex, + "ExtraCells2 severe error - could not create AE2 Part from ItemStack! This should not happen!\n" + + "[ExtraCells2 SEVERE] Contact Leonelf/M3gaFr3ak with the following stack trace.\n" + + "[ExtraCells2 SEVERE] Offending item: '%s'", + itemStack.toString()); + return null; + } + } + + @Override + public String getItemStackDisplayName(ItemStack stack) { + if (stack == null) return super.getItemStackDisplayName(null); + if (stack.getItemDamage() == PartEnum.INTERFACE.ordinal()) + return ECApi.instance().blocks().blockInterface().maybeItem().get() + .getItemStackDisplayName(ECApi.instance().blocks().blockInterface().maybeStack(1).get()); + return super.getItemStackDisplayName(stack); + } + + @Override + @SideOnly(Side.CLIENT) + public int getSpriteNumber() { + return 0; + } + + @Override + @SuppressWarnings("unchecked") + public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { + for (int i = 0; i < PartEnum.values().length; i++) { + PartEnum part = PartEnum.values()[i]; + if (part.getMod() == null || part.getMod().isEnabled()) itemList.add(new ItemStack(item, 1, i)); + } + } + + @Override + public String getUnlocalizedGroupName(Set otherItems, ItemStack itemStack) { + return PartEnum.values()[MathHelper.clamp_int(itemStack.getItemDamage(), 0, PartEnum.values().length - 1)] + .getGroupName(); + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return PartEnum.values()[MathHelper.clamp_int(itemStack.getItemDamage(), 0, PartEnum.values().length - 1)] + .getUnlocalizedName(); + } + + @Override + 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); + } + + @Override + public void registerIcons(IIconRegister _iconRegister) {} } diff --git a/src/main/scala/extracells/item/ItemStorageCasing.java b/src/main/scala/extracells/item/ItemStorageCasing.java index 55debba94..85afad760 100644 --- a/src/main/scala/extracells/item/ItemStorageCasing.java +++ b/src/main/scala/extracells/item/ItemStorageCasing.java @@ -1,7 +1,7 @@ package extracells.item; -import extracells.Extracells; -import extracells.integration.Integration; +import java.util.List; + import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; @@ -9,47 +9,46 @@ import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; -import java.util.List; +import extracells.Extracells; +import extracells.integration.Integration; public class ItemStorageCasing extends ItemECBase { - private IIcon[] icons; - public final String[] suffixes = { "physical", "fluid", "gas" }; - - public ItemStorageCasing() { - setMaxDamage(0); - setHasSubtypes(true); - setCreativeTab(Extracells.ModTab()); - } - - @Override - public IIcon getIconFromDamage(int dmg) { - int j = MathHelper.clamp_int(dmg, 0, this.icons.length - 1); - return this.icons[j]; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { - for (int j = 0; j < this.suffixes.length; ++j) { - if(!(suffixes[j].contains("gas") && !Integration.Mods.MEKANISMGAS.isEnabled())) - itemList.add(new ItemStack(item, 1, j)); - } - } - - @Override - public String getUnlocalizedName(ItemStack itemStack) { - return "extracells.item.storage.casing." - + this.suffixes[itemStack.getItemDamage()]; - } - - @Override - public void registerIcons(IIconRegister iconRegister) { - this.icons = new IIcon[this.suffixes.length]; - - for (int i = 0; i < this.suffixes.length; ++i) { - this.icons[i] = iconRegister.registerIcon("extracells:" - + "storage.casing." + this.suffixes[i]); - } - } + private IIcon[] icons; + public final String[] suffixes = { "physical", "fluid", "gas" }; + + public ItemStorageCasing() { + setMaxDamage(0); + setHasSubtypes(true); + setCreativeTab(Extracells.ModTab()); + } + + @Override + public IIcon getIconFromDamage(int dmg) { + int j = MathHelper.clamp_int(dmg, 0, this.icons.length - 1); + return this.icons[j]; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { + for (int j = 0; j < this.suffixes.length; ++j) { + if (!(suffixes[j].contains("gas") && !Integration.Mods.MEKANISMGAS.isEnabled())) + itemList.add(new ItemStack(item, 1, j)); + } + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return "extracells.item.storage.casing." + this.suffixes[itemStack.getItemDamage()]; + } + + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icons = new IIcon[this.suffixes.length]; + + for (int i = 0; i < this.suffixes.length; ++i) { + this.icons[i] = iconRegister.registerIcon("extracells:" + "storage.casing." + this.suffixes[i]); + } + } } diff --git a/src/main/scala/extracells/item/ItemStorageComponent.java b/src/main/scala/extracells/item/ItemStorageComponent.java index 15bccfe76..e96fc0554 100644 --- a/src/main/scala/extracells/item/ItemStorageComponent.java +++ b/src/main/scala/extracells/item/ItemStorageComponent.java @@ -1,74 +1,68 @@ package extracells.item; -import appeng.api.implementations.items.IStorageComponent; -import extracells.integration.Integration; +import java.util.List; + import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; -import java.util.List; +import appeng.api.implementations.items.IStorageComponent; +import extracells.integration.Integration; public class ItemStorageComponent extends ItemECBase implements IStorageComponent { - private IIcon[] icons; - public final String[] suffixes = { "physical.256k", "physical.1024k", "physical.4096k", "physical.16384k", "fluid.1k", "fluid.4k", "fluid.16k", "fluid.64k", "fluid.256k", "fluid.1024k", "fluid.4096k", "gas.1k", "gas.4k", "gas.16k", "gas.64k", "gas.256k", "gas.1024k", "gas.4096k" }; - public final int[] size = new int[] { 262144, 1048576, 4194304, 16777216, - 1024, 4096, 16384, 65536, 262144, 1048576, 4194304 }; - - public ItemStorageComponent() { - setMaxDamage(0); - setHasSubtypes(true); - } + private IIcon[] icons; + public final String[] suffixes = { "physical.256k", "physical.1024k", "physical.4096k", "physical.16384k", + "fluid.1k", "fluid.4k", "fluid.16k", "fluid.64k", "fluid.256k", "fluid.1024k", "fluid.4096k", "gas.1k", + "gas.4k", "gas.16k", "gas.64k", "gas.256k", "gas.1024k", "gas.4096k" }; + public final int[] size = new int[] { 262144, 1048576, 4194304, 16777216, 1024, 4096, 16384, 65536, 262144, 1048576, + 4194304 }; - @Override - public int getBytes(ItemStack is) { - return this.size[is.getItemDamage()]; - } + public ItemStorageComponent() { + setMaxDamage(0); + setHasSubtypes(true); + } - @Override - public IIcon getIconFromDamage(int dmg) { - int j = MathHelper.clamp_int(dmg, 0, this.suffixes.length); - return this.icons[j]; - } + @Override + public int getBytes(ItemStack is) { + return this.size[MathHelper.clamp_int(is.getItemDamage(), 0, this.size.length)]; + } - @Override - public EnumRarity getRarity(ItemStack itemStack) { - if (itemStack.getItemDamage() >= 4) - return EnumRarity.rare; - return EnumRarity.epic; - } + @Override + public IIcon getIconFromDamage(int dmg) { + int j = MathHelper.clamp_int(dmg, 0, this.suffixes.length); + return this.icons[j]; + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { - for (int j = 0; j < this.suffixes.length; ++j) { - if(!(suffixes[j].contains("gas") && !Integration.Mods.MEKANISMGAS.isEnabled())) - itemList.add(new ItemStack(item, 1, j)); - } - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { + for (int j = 0; j < this.suffixes.length; ++j) { + if (!(suffixes[j].contains("gas") && !Integration.Mods.MEKANISMGAS.isEnabled())) + itemList.add(new ItemStack(item, 1, j)); + } + } - @Override - public String getUnlocalizedName(ItemStack itemStack) { - return "extracells.item.storage.component." - + this.suffixes[itemStack.getItemDamage()]; - } + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return String.format("extracells.item.storage.component.%s", this.suffixes[itemStack.getItemDamage()]); + } - @Override - public boolean isStorageComponent(ItemStack is) { - return is.getItem() == this; - } + @Override + public boolean isStorageComponent(ItemStack is) { + return is.getItem() == this; + } - @Override - public void registerIcons(IIconRegister iconRegister) { - this.icons = new IIcon[this.suffixes.length]; + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icons = new IIcon[this.suffixes.length]; - for (int i = 0; i < this.suffixes.length; ++i) { - this.icons[i] = iconRegister.registerIcon("extracells:" - + "storage.component." + this.suffixes[i]); - } - } + for (int i = 0; i < this.suffixes.length; ++i) { + this.icons[i] = iconRegister + .registerIcon(String.format("extracells:storage.component.%s", this.suffixes[i])); + } + } } diff --git a/src/main/scala/extracells/item/ItemStorageFluid.java b/src/main/scala/extracells/item/ItemStorageFluid.java index ab2664bba..ba5ffa9e4 100644 --- a/src/main/scala/extracells/item/ItemStorageFluid.java +++ b/src/main/scala/extracells/item/ItemStorageFluid.java @@ -1,20 +1,12 @@ package extracells.item; -import appeng.api.AEApi; -import appeng.api.config.FuzzyMode; -import appeng.api.storage.IMEInventoryHandler; -import appeng.api.storage.StorageChannel; -import appeng.api.storage.data.IAEFluidStack; -import extracells.api.IFluidStorageCell; -import extracells.api.IHandlerFluidStorage; -import extracells.registries.ItemEnum; -import extracells.util.inventory.ECFluidFilterInventory; -import extracells.util.inventory.ECPrivateInventory; +import java.util.ArrayList; +import java.util.List; + import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; -import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -25,165 +17,188 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; -import java.util.ArrayList; -import java.util.List; +import appeng.api.AEApi; +import appeng.api.config.FuzzyMode; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEFluidStack; +import extracells.api.IFluidStorageCell; +import extracells.api.IHandlerFluidStorage; +import extracells.registries.ItemEnum; +import extracells.util.inventory.ECFluidFilterInventory; +import extracells.util.inventory.ECPrivateInventory; public class ItemStorageFluid extends ItemECBase implements IFluidStorageCell { - public static final String[] suffixes = { "1k", "4k", "16k", "64k", "256k", "1024k", "4096k" }; - - public static final int[] spaces = { 1024, 4096, 16348, 65536, 262144, 1048576, 4194304 }; - - private IIcon[] icons; - - public ItemStorageFluid() { - setMaxStackSize(1); - setMaxDamage(0); - setHasSubtypes(true); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void addInformation(ItemStack itemStack, EntityPlayer player, - List list, boolean par4) { - IMEInventoryHandler handler = AEApi.instance().registries().cell().getCellInventory(itemStack, null, StorageChannel.FLUIDS); - if (!(handler instanceof IHandlerFluidStorage)) { - return; - } - IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; - boolean partitioned = cellHandler.isFormatted(); - long usedBytes = cellHandler.usedBytes(); - - list.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.fluid.bytes"), usedBytes / 250, cellHandler.totalBytes() / 250)); - list.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.fluid.types"), cellHandler.usedTypes(), cellHandler.totalTypes())); - if (usedBytes != 0) { - list.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.fluid.content"), usedBytes)); - } - - if (partitioned) { - list.add(StatCollector.translateToLocal("gui.appliedenergistics2.Partitioned") + " - " + StatCollector.translateToLocal("gui.appliedenergistics2.Precise")); - } - } - - @Override - public IInventory getConfigInventory(ItemStack is) { - return new ECFluidFilterInventory("configFluidCell", 63, is); - } - - @Override - public ArrayList getFilter(ItemStack stack) { - ECFluidFilterInventory inventory = new ECFluidFilterInventory("", 63, stack); - ItemStack[] stacks = inventory.slots; - ArrayList filter = new ArrayList(); - if (stacks.length == 0) - return null; - for (ItemStack s : stacks) { - if (s == null) - continue; - Fluid f = FluidRegistry.getFluid(s.getItemDamage()); - if (f != null) - filter.add(f); - } - return filter; - } - - @Override - public FuzzyMode getFuzzyMode(ItemStack is) { - if (is == null) - return null; - if (!is.hasTagCompound()) - is.setTagCompound(new NBTTagCompound()); - if (is.getTagCompound().hasKey("fuzzyMode")) - return FuzzyMode.valueOf(is.getTagCompound().getString("fuzzyMode")); - is.getTagCompound().setString("fuzzyMode", FuzzyMode.IGNORE_ALL.name()); - return FuzzyMode.IGNORE_ALL; - } - - @Override - public IIcon getIconFromDamage(int dmg) { - int j = MathHelper.clamp_int(dmg, 0, suffixes.length); - return this.icons[j]; - } - - @Override - public int getMaxBytes(ItemStack is) { - return spaces[Math.max(0, is.getItemDamage())]; - } - - @Override - public int getMaxTypes(ItemStack unused) { - return 5; - } - - @Override - public EnumRarity getRarity(ItemStack itemStack) { - return EnumRarity.rare; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void getSubItems(Item item, CreativeTabs creativeTab, - List listSubItems) { - for (int i = 0; i < suffixes.length; ++i) { - listSubItems.add(new ItemStack(item, 1, i)); - } - } - - @Override - public String getUnlocalizedName(ItemStack itemStack) { - return "extracells.item.storage.fluid." + suffixes[itemStack.getItemDamage()]; - } - - @Override - public IInventory getUpgradesInventory(ItemStack is) { - return new ECPrivateInventory("configInventory", 0, 64); - } - - @Override - public boolean isEditable(ItemStack is) { - if (is == null) - return false; - return is.getItem() == this; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public ItemStack onItemRightClick(ItemStack itemStack, World world, - EntityPlayer entityPlayer) { - if (!entityPlayer.isSneaking()) { - return itemStack; - } - IMEInventoryHandler handler = AEApi.instance().registries().cell().getCellInventory(itemStack, null, StorageChannel.FLUIDS); - if (!(handler instanceof IHandlerFluidStorage)) { - return itemStack; - } - IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; - if (cellHandler.usedBytes() == 0 && entityPlayer.inventory.addItemStackToInventory(ItemEnum.STORAGECASING.getDamagedStack(1))) { - return ItemEnum.STORAGECOMPONET.getDamagedStack(itemStack.getItemDamage() + 4); - } - return itemStack; - } - - @Override - public void registerIcons(IIconRegister iconRegister) { - this.icons = new IIcon[suffixes.length]; - - for (int i = 0; i < suffixes.length; ++i) { - this.icons[i] = iconRegister.registerIcon("extracells:" + "storage.fluid." + suffixes[i]); - } - } - - @Override - public void setFuzzyMode(ItemStack is, FuzzyMode fzMode) { - if (is == null) - return; - NBTTagCompound tag; - if (is.hasTagCompound()) - tag = is.getTagCompound(); - else - tag = new NBTTagCompound(); - tag.setString("fuzzyMode", fzMode.name()); - is.setTagCompound(tag); - - } + public static final String[] suffixes = { "1k", "4k", "16k", "64k", "256k", "1024k", "4096k" }; + + public static final int[] spaces = { 1024, 4096, 16348, 65536, 262144, 1048576, 4194304 }; + + public static final double[] idle_drains = { 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 }; + + private IIcon[] icons; + + public ItemStorageFluid() { + setMaxStackSize(1); + setMaxDamage(0); + setHasSubtypes(true); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean par4) { + super.addInformation(itemStack, player, list, par4); + IMEInventoryHandler handler = AEApi.instance().registries().cell() + .getCellInventory(itemStack, null, StorageChannel.FLUIDS); + if (!(handler instanceof IHandlerFluidStorage)) { + return; + } + IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; + boolean partitioned = cellHandler.isFormatted(); + long usedBytes = cellHandler.usedBytes(); + + list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.fluid.bytes"), + usedBytes / 250, + cellHandler.totalBytes() / 250)); + list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.fluid.types"), + cellHandler.usedTypes(), + cellHandler.totalTypes())); + if (usedBytes != 0) { + list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.fluid.content"), + usedBytes)); + } + + if (partitioned) { + list.add( + StatCollector.translateToLocal("gui.appliedenergistics2.Partitioned") + " - " + + StatCollector.translateToLocal("gui.appliedenergistics2.Precise")); + } + } + + @Override + public IInventory getConfigInventory(ItemStack is) { + return new ECFluidFilterInventory("configFluidCell", 63, is); + } + + @Override + public ArrayList getFilter(ItemStack stack) { + ECFluidFilterInventory inventory = new ECFluidFilterInventory("", 63, stack); + ItemStack[] stacks = inventory.slots; + ArrayList filter = new ArrayList(); + if (stacks.length == 0) return null; + for (ItemStack s : stacks) { + if (s == null) continue; + Fluid f = FluidRegistry.getFluid(s.getItemDamage()); + if (f != null) filter.add(f); + } + return filter; + } + + @Override + public FuzzyMode getFuzzyMode(ItemStack is) { + if (is == null) return null; + if (!is.hasTagCompound()) is.setTagCompound(new NBTTagCompound()); + if (is.getTagCompound().hasKey("fuzzyMode")) + return FuzzyMode.valueOf(is.getTagCompound().getString("fuzzyMode")); + is.getTagCompound().setString("fuzzyMode", FuzzyMode.IGNORE_ALL.name()); + return FuzzyMode.IGNORE_ALL; + } + + @Override + public IIcon getIconFromDamage(int dmg) { + int j = MathHelper.clamp_int(dmg, 0, suffixes.length); + return this.icons[j]; + } + + @Override + public int getMaxBytes(ItemStack is) { + return spaces[Math.max(0, is.getItemDamage())]; + } + + @Override + public int getMaxTypes(ItemStack unused) { + return 5; + } + + @Override + public double idleDrain(ItemStack is) { + int variant = MathHelper.clamp_int(is.getItemDamage(), 0, idle_drains.length); + return idle_drains[variant]; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void getSubItems(Item item, CreativeTabs creativeTab, List listSubItems) { + for (int i = 0; i < suffixes.length; ++i) { + listSubItems.add(new ItemStack(item, 1, i)); + } + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return "extracells.item.storage.fluid." + suffixes[itemStack.getItemDamage()]; + } + + @Override + public IInventory getUpgradesInventory(ItemStack is) { + return new ECPrivateInventory("configInventory", 0, 64); + } + + @Override + public boolean isEditable(ItemStack is) { + if (is == null) return false; + return is.getItem() == this; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) { + if (!entityPlayer.isSneaking()) { + return itemStack; + } + IMEInventoryHandler handler = AEApi.instance().registries().cell() + .getCellInventory(itemStack, null, StorageChannel.FLUIDS); + if (!(handler instanceof IHandlerFluidStorage)) { + return itemStack; + } + IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; + if (cellHandler.usedBytes() == 0 + && entityPlayer.inventory.addItemStackToInventory(ItemEnum.STORAGECASING.getDamagedStack(1))) { + return ItemEnum.STORAGECOMPONENT.getDamagedStack(itemStack.getItemDamage() + 4); + } + return itemStack; + } + + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icons = new IIcon[suffixes.length]; + + for (int i = 0; i < suffixes.length; ++i) { + this.icons[i] = iconRegister.registerIcon("extracells:" + "storage.fluid." + suffixes[i]); + } + } + + @Override + public void setFuzzyMode(ItemStack is, FuzzyMode fzMode) { + if (is == null) return; + NBTTagCompound tag; + if (is.hasTagCompound()) tag = is.getTagCompound(); + else tag = new NBTTagCompound(); + tag.setString("fuzzyMode", fzMode.name()); + is.setTagCompound(tag); + } + + @Override + public String getOreFilter(ItemStack itemStack) { + return ""; + } + + @Override + public void setOreFilter(ItemStack itemStack, String s) {} } diff --git a/src/main/scala/extracells/item/ItemStorageGas.java b/src/main/scala/extracells/item/ItemStorageGas.java index 8063d3cc3..30b588fc8 100644 --- a/src/main/scala/extracells/item/ItemStorageGas.java +++ b/src/main/scala/extracells/item/ItemStorageGas.java @@ -1,20 +1,12 @@ package extracells.item; -import appeng.api.AEApi; -import appeng.api.config.FuzzyMode; -import appeng.api.storage.IMEInventoryHandler; -import appeng.api.storage.StorageChannel; -import appeng.api.storage.data.IAEFluidStack; -import extracells.api.IGasStorageCell; -import extracells.api.IHandlerFluidStorage; -import extracells.registries.ItemEnum; -import extracells.util.inventory.ECFluidFilterInventory; -import extracells.util.inventory.ECPrivateInventory; +import java.util.ArrayList; +import java.util.List; + import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; -import net.minecraft.item.EnumRarity; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; @@ -25,165 +17,177 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; -import java.util.ArrayList; -import java.util.List; +import appeng.api.AEApi; +import appeng.api.config.FuzzyMode; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEFluidStack; +import extracells.api.IGasStorageCell; +import extracells.api.IHandlerFluidStorage; +import extracells.registries.ItemEnum; +import extracells.util.inventory.ECFluidFilterInventory; +import extracells.util.inventory.ECPrivateInventory; public class ItemStorageGas extends ItemECBase implements IGasStorageCell { - public static final String[] suffixes = { "1k", "4k", "16k", "64k", "256k", "1024k", "4096k" }; - - public static final int[] spaces = { 1024, 4096, 16348, 65536, 262144, 1048576, 4194304 }; - - private IIcon[] icons; - - public ItemStorageGas() { - setMaxStackSize(1); - setMaxDamage(0); - setHasSubtypes(true); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void addInformation(ItemStack itemStack, EntityPlayer player, - List list, boolean par4) { - IMEInventoryHandler handler = AEApi.instance().registries().cell().getCellInventory(itemStack, null, StorageChannel.FLUIDS); - if (!(handler instanceof IHandlerFluidStorage)) { - return; - } - IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; - boolean partitioned = cellHandler.isFormatted(); - long usedBytes = cellHandler.usedBytes(); - - list.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.gas.bytes"), usedBytes / 250, cellHandler.totalBytes() / 250)); - list.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.gas.types"), cellHandler.usedTypes(), cellHandler.totalTypes())); - if (usedBytes != 0) { - list.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.gas.content"), usedBytes)); - } - - if (partitioned) { - list.add(StatCollector.translateToLocal("gui.appliedenergistics2.Partitioned") + " - " + StatCollector.translateToLocal("gui.appliedenergistics2.Precise")); - } - } - - @Override - public IInventory getConfigInventory(ItemStack is) { - return new ECFluidFilterInventory("configFluidCell", 63, is); - } - - @Override - public ArrayList getFilter(ItemStack stack) { - ECFluidFilterInventory inventory = new ECFluidFilterInventory("", 63, stack); - ItemStack[] stacks = inventory.slots; - ArrayList filter = new ArrayList(); - if (stacks.length == 0) - return null; - for (ItemStack s : stacks) { - if (s == null) - continue; - Fluid f = FluidRegistry.getFluid(s.getItemDamage()); - if (f != null) - filter.add(f); - } - return filter; - } - - @Override - public FuzzyMode getFuzzyMode(ItemStack is) { - if (is == null) - return null; - if (!is.hasTagCompound()) - is.setTagCompound(new NBTTagCompound()); - if (is.getTagCompound().hasKey("fuzzyMode")) - return FuzzyMode.valueOf(is.getTagCompound().getString("fuzzyMode")); - is.getTagCompound().setString("fuzzyMode", FuzzyMode.IGNORE_ALL.name()); - return FuzzyMode.IGNORE_ALL; - } - - @Override - public IIcon getIconFromDamage(int dmg) { - int j = MathHelper.clamp_int(dmg, 0, suffixes.length); - return this.icons[j]; - } - - @Override - public int getMaxBytes(ItemStack is) { - return spaces[Math.max(0, is.getItemDamage())]; - } - - @Override - public int getMaxTypes(ItemStack unused) { - return 5; - } - - @Override - public EnumRarity getRarity(ItemStack itemStack) { - return EnumRarity.rare; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void getSubItems(Item item, CreativeTabs creativeTab, - List listSubItems) { - for (int i = 0; i < suffixes.length; ++i) { - listSubItems.add(new ItemStack(item, 1, i)); - } - } - - @Override - public String getUnlocalizedName(ItemStack itemStack) { - return "extracells.item.storage.gas." + suffixes[itemStack.getItemDamage()]; - } - - @Override - public IInventory getUpgradesInventory(ItemStack is) { - return new ECPrivateInventory("configInventory", 0, 64); - } - - @Override - public boolean isEditable(ItemStack is) { - if (is == null) - return false; - return is.getItem() == this; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public ItemStack onItemRightClick(ItemStack itemStack, World world, - EntityPlayer entityPlayer) { - if (!entityPlayer.isSneaking()) { - return itemStack; - } - IMEInventoryHandler handler = AEApi.instance().registries().cell().getCellInventory(itemStack, null, StorageChannel.FLUIDS); - if (!(handler instanceof IHandlerFluidStorage)) { - return itemStack; - } - IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; - if (cellHandler.usedBytes() == 0 && entityPlayer.inventory.addItemStackToInventory(ItemEnum.STORAGECASING.getDamagedStack(2))) { - return ItemEnum.STORAGECOMPONET.getDamagedStack(itemStack.getItemDamage() + 11); - } - return itemStack; - } - - @Override - public void registerIcons(IIconRegister iconRegister) { - this.icons = new IIcon[suffixes.length]; - - for (int i = 0; i < suffixes.length; ++i) { - this.icons[i] = iconRegister.registerIcon("extracells:" + "storage.gas." + suffixes[i]); - } - } - - @Override - public void setFuzzyMode(ItemStack is, FuzzyMode fzMode) { - if (is == null) - return; - NBTTagCompound tag; - if (is.hasTagCompound()) - tag = is.getTagCompound(); - else - tag = new NBTTagCompound(); - tag.setString("fuzzyMode", fzMode.name()); - is.setTagCompound(tag); - - } + public static final String[] suffixes = { "1k", "4k", "16k", "64k", "256k", "1024k", "4096k" }; + + public static final int[] spaces = { 1024, 4096, 16348, 65536, 262144, 1048576, 4194304 }; + + private IIcon[] icons; + + public ItemStorageGas() { + setMaxStackSize(1); + setMaxDamage(0); + setHasSubtypes(true); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean par4) { + IMEInventoryHandler handler = AEApi.instance().registries().cell() + .getCellInventory(itemStack, null, StorageChannel.FLUIDS); + if (!(handler instanceof IHandlerFluidStorage)) { + return; + } + IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; + boolean partitioned = cellHandler.isFormatted(); + long usedBytes = cellHandler.usedBytes(); + + list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.gas.bytes"), + usedBytes / 250, + cellHandler.totalBytes() / 250)); + list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.gas.types"), + cellHandler.usedTypes(), + cellHandler.totalTypes())); + if (usedBytes != 0) { + list.add( + String.format(StatCollector.translateToLocal("extracells.tooltip.storage.gas.content"), usedBytes)); + } + + if (partitioned) { + list.add( + StatCollector.translateToLocal("gui.appliedenergistics2.Partitioned") + " - " + + StatCollector.translateToLocal("gui.appliedenergistics2.Precise")); + } + } + + @Override + public IInventory getConfigInventory(ItemStack is) { + return new ECFluidFilterInventory("configFluidCell", 63, is); + } + + @Override + public ArrayList getFilter(ItemStack stack) { + ECFluidFilterInventory inventory = new ECFluidFilterInventory("", 63, stack); + ItemStack[] stacks = inventory.slots; + ArrayList filter = new ArrayList(); + if (stacks.length == 0) return null; + for (ItemStack s : stacks) { + if (s == null) continue; + Fluid f = FluidRegistry.getFluid(s.getItemDamage()); + if (f != null) filter.add(f); + } + return filter; + } + + @Override + public FuzzyMode getFuzzyMode(ItemStack is) { + if (is == null) return null; + if (!is.hasTagCompound()) is.setTagCompound(new NBTTagCompound()); + if (is.getTagCompound().hasKey("fuzzyMode")) + return FuzzyMode.valueOf(is.getTagCompound().getString("fuzzyMode")); + is.getTagCompound().setString("fuzzyMode", FuzzyMode.IGNORE_ALL.name()); + return FuzzyMode.IGNORE_ALL; + } + + @Override + public IIcon getIconFromDamage(int dmg) { + int j = MathHelper.clamp_int(dmg, 0, suffixes.length); + return this.icons[j]; + } + + @Override + public int getMaxBytes(ItemStack is) { + return spaces[Math.max(0, is.getItemDamage())]; + } + + @Override + public int getMaxTypes(ItemStack unused) { + return 5; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void getSubItems(Item item, CreativeTabs creativeTab, List listSubItems) { + for (int i = 0; i < suffixes.length; ++i) { + listSubItems.add(new ItemStack(item, 1, i)); + } + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return "extracells.item.storage.gas." + suffixes[itemStack.getItemDamage()]; + } + + @Override + public IInventory getUpgradesInventory(ItemStack is) { + return new ECPrivateInventory("configInventory", 0, 64); + } + + @Override + public boolean isEditable(ItemStack is) { + if (is == null) return false; + return is.getItem() == this; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) { + if (!entityPlayer.isSneaking()) { + return itemStack; + } + IMEInventoryHandler handler = AEApi.instance().registries().cell() + .getCellInventory(itemStack, null, StorageChannel.FLUIDS); + if (!(handler instanceof IHandlerFluidStorage)) { + return itemStack; + } + IHandlerFluidStorage cellHandler = (IHandlerFluidStorage) handler; + if (cellHandler.usedBytes() == 0 + && entityPlayer.inventory.addItemStackToInventory(ItemEnum.STORAGECASING.getDamagedStack(2))) { + return ItemEnum.STORAGECOMPONENT.getDamagedStack(itemStack.getItemDamage() + 11); + } + return itemStack; + } + + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icons = new IIcon[suffixes.length]; + + for (int i = 0; i < suffixes.length; ++i) { + this.icons[i] = iconRegister.registerIcon("extracells:" + "storage.gas." + suffixes[i]); + } + } + + @Override + public void setFuzzyMode(ItemStack is, FuzzyMode fzMode) { + if (is == null) return; + NBTTagCompound tag; + if (is.hasTagCompound()) tag = is.getTagCompound(); + else tag = new NBTTagCompound(); + tag.setString("fuzzyMode", fzMode.name()); + is.setTagCompound(tag); + } + + @Override + public String getOreFilter(ItemStack itemStack) { + return ""; + } + + @Override + public void setOreFilter(ItemStack itemStack, String s) {} } diff --git a/src/main/scala/extracells/item/ItemStoragePhysical.java b/src/main/scala/extracells/item/ItemStoragePhysical.java index f9366ab83..fc149dc10 100644 --- a/src/main/scala/extracells/item/ItemStoragePhysical.java +++ b/src/main/scala/extracells/item/ItemStoragePhysical.java @@ -1,5 +1,22 @@ package extracells.item; +import java.util.List; + +import javax.annotation.Nullable; + +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.Item; +import net.minecraft.item.ItemBlock; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.*; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; @@ -11,613 +28,647 @@ import appeng.api.storage.*; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IItemList; +import appeng.util.IterationCounter; +import appeng.util.Platform; import cofh.api.energy.IEnergyContainerItem; import cpw.mods.fml.common.Optional; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import extracells.Extracells; import extracells.registries.ItemEnum; +import extracells.util.DeprecationWarning; import extracells.util.inventory.ECCellInventory; -import net.minecraft.client.renderer.texture.IIconRegister; -import net.minecraft.creativetab.CreativeTabs; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.EnumRarity; -import net.minecraft.item.Item; -import net.minecraft.item.ItemBlock; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChatComponentTranslation; -import net.minecraft.util.IIcon; -import net.minecraft.util.MathHelper; -import net.minecraft.util.StatCollector; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; - -import java.util.List; @Optional.Interface(iface = "cofh.api.energy.IEnergyContainerItem", modid = "CoFHAPI|energy") -public class ItemStoragePhysical extends ItemECBase implements IStorageCell, - IAEItemPowerStorage, IEnergyContainerItem { - - public static final String[] suffixes = { "256k", "1024k", "4096k", "16384k", "container" }; - - public static final int[] bytes_cell = { 262144, 1048576, 4194304, 16777216, 65536 }; - public static final int[] types_cell = { 63, 63, 63, 63, 1 }; - private IIcon[] icons; - private final int MAX_POWER = 32000; - - public ItemStoragePhysical() { - setMaxStackSize(1); - setMaxDamage(0); - setHasSubtypes(true); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void addInformation(ItemStack itemStack, EntityPlayer player, - List list, boolean par4) { - ICellRegistry cellRegistry = AEApi.instance().registries().cell(); - IMEInventoryHandler invHandler = cellRegistry - .getCellInventory(itemStack, null, StorageChannel.ITEMS); - ICellInventoryHandler inventoryHandler = (ICellInventoryHandler) invHandler; - ICellInventory cellInv = inventoryHandler.getCellInv(); - long usedBytes = cellInv.getUsedBytes(); - - list.add(String.format(StatCollector - .translateToLocal("extracells.tooltip.storage.physical.bytes"), - usedBytes, cellInv.getTotalBytes())); - list.add(String.format(StatCollector - .translateToLocal("extracells.tooltip.storage.physical.types"), - cellInv.getStoredItemTypes(), cellInv.getTotalItemTypes())); - if (usedBytes > 0) - list.add(String.format( - StatCollector - .translateToLocal("extracells.tooltip.storage.physical.content"), - cellInv.getStoredItemCount())); - } - - @Override - public int getBytesPerType(ItemStack cellItem) { - return Extracells.dynamicTypes() ? bytes_cell[MathHelper.clamp_int( - cellItem.getItemDamage(), 0, suffixes.length - 1)] / 128 : 8; - } - - @Override - @Deprecated - public int BytePerType(ItemStack cellItem) { - return getBytesPerType(cellItem); - } - - private NBTTagCompound ensureTagCompound(ItemStack itemStack) { - if (!itemStack.hasTagCompound()) - itemStack.setTagCompound(new NBTTagCompound()); - return itemStack.getTagCompound(); - } - - @Override - public double extractAEPower(ItemStack itemStack, double amt) { - if (itemStack == null || itemStack.getItemDamage() != 4) - return 0.0D; - NBTTagCompound tagCompound = ensureTagCompound(itemStack); - double currentPower = tagCompound.getDouble("power"); - double toExtract = Math.min(amt, currentPower); - tagCompound.setDouble("power", currentPower - toExtract); - return toExtract; - } - - @Override - @Optional.Method(modid = "CoFHAPI|energy") - public int extractEnergy(ItemStack container, int maxExtract, - boolean simulate) { - if (container == null || container.getItemDamage() != 4) - return 0; - if (simulate) { - return getEnergyStored(container) >= maxExtract ? maxExtract - : getEnergyStored(container); - } else { - return (int) PowerUnits.AE - .convertTo( - PowerUnits.RF, - extractAEPower(container, PowerUnits.RF.convertTo( - PowerUnits.AE, maxExtract))); - } - } - - @Override - public double getAECurrentPower(ItemStack itemStack) { - if (itemStack == null || itemStack.getItemDamage() != 4) - return 0.0D; - NBTTagCompound tagCompound = ensureTagCompound(itemStack); - return tagCompound.getDouble("power"); - } - - @Override - public double getAEMaxPower(ItemStack itemStack) { - if (itemStack == null || itemStack.getItemDamage() != 4) - return 0.0D; - return this.MAX_POWER; - } - - @Override - public int getBytes(ItemStack cellItem) { - return bytes_cell[MathHelper.clamp_int(cellItem.getItemDamage(), 0, - suffixes.length - 1)]; - } - - @Override - public IInventory getConfigInventory(ItemStack is) { - return new ECCellInventory(is, "config", 63, 1); - } - - @Override - public double getDurabilityForDisplay(ItemStack itemStack) { - if (itemStack == null || itemStack.getItemDamage() != 4) - return super.getDurabilityForDisplay(itemStack); - return 1 - getAECurrentPower(itemStack) / this.MAX_POWER; - } - - @Override - @Optional.Method(modid = "CoFHAPI|energy") - public int getEnergyStored(ItemStack arg0) { - return (int) PowerUnits.AE.convertTo(PowerUnits.RF, - getAECurrentPower(arg0)); - } - - @Override - public FuzzyMode getFuzzyMode(ItemStack is) { - if (!is.hasTagCompound()) - is.setTagCompound(new NBTTagCompound()); - return FuzzyMode.values()[is.getTagCompound().getInteger("fuzzyMode")]; - } - - @Override - public IIcon getIconFromDamage(int dmg) { - return this.icons[MathHelper.clamp_int(dmg, 0, suffixes.length - 1)]; - } - - @Override - public double getIdleDrain() { - return 0; - } - - @SideOnly(Side.CLIENT) - @Override - public String getItemStackDisplayName(ItemStack stack) { - if (stack == null) - return super.getItemStackDisplayName(stack); - if (stack.getItemDamage() == 4) { - try { - IItemList list = AEApi - .instance() - .registries() - .cell() - .getCellInventory(stack, null, StorageChannel.ITEMS) - .getAvailableItems( - AEApi.instance().storage().createItemList()); - if (list.isEmpty()) - return super.getItemStackDisplayName(stack) - + " - " - + StatCollector - .translateToLocal("extracells.tooltip.empty1"); - IAEItemStack s = (IAEItemStack) list.getFirstItem(); - return super.getItemStackDisplayName(stack) + " - " - + s.getItemStack().getDisplayName(); - } catch (Throwable e) {} - return super.getItemStackDisplayName(stack) - + " - " - + StatCollector - .translateToLocal("extracells.tooltip.empty1"); - } - return super.getItemStackDisplayName(stack); - } - - @Override - @Optional.Method(modid = "CoFHAPI|energy") - public int getMaxEnergyStored(ItemStack arg0) { - return (int) PowerUnits.AE - .convertTo(PowerUnits.RF, getAEMaxPower(arg0)); - } - - @Override - public AccessRestriction getPowerFlow(ItemStack itemStack) { - if (itemStack == null) - return null; - return itemStack.getItemDamage() == 4 ? AccessRestriction.READ_WRITE - : AccessRestriction.NO_ACCESS; - } - - @Override - public EnumRarity getRarity(ItemStack itemStack) { - return EnumRarity.epic; - } - - @Override - @SuppressWarnings("unchecked") - public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { - for (int i = 0; i < suffixes.length; i++) { - itemList.add(new ItemStack(item, 1, i)); - if (i == 4) { - ItemStack s = new ItemStack(item, 1, i); - s.setTagCompound(new NBTTagCompound()); - s.getTagCompound().setDouble("power", this.MAX_POWER); - itemList.add(s); - } - } - } - - @Override - public int getTotalTypes(ItemStack cellItem) { - return types_cell[MathHelper.clamp_int(cellItem.getItemDamage(), 0, - suffixes.length - 1)]; - } - - @Override - public String getUnlocalizedName(ItemStack itemStack) { - return "extracells.item.storage.physical." - + suffixes[itemStack.getItemDamage()]; - } - - @Override - public IInventory getUpgradesInventory(ItemStack is) { - return new ECCellInventory(is, "upgrades", 2, 1); - } - - @Override - public double injectAEPower(ItemStack itemStack, double amt) { - if (itemStack == null || itemStack.getItemDamage() != 4) - return 0.0D; - NBTTagCompound tagCompound = ensureTagCompound(itemStack); - double currentPower = tagCompound.getDouble("power"); - double toInject = Math.min(amt, this.MAX_POWER - currentPower); - tagCompound.setDouble("power", currentPower + toInject); - return toInject; - } - - @Override - public boolean isBlackListed(ItemStack cellItem, - IAEItemStack requestedAddition) { - return false; - } - - @Override - public boolean isEditable(ItemStack is) { - return true; - } - - @Override - public boolean isStorageCell(ItemStack i) { - return true; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public ItemStack onItemRightClick(ItemStack itemStack, World world, - EntityPlayer entityPlayer) { - if (itemStack == null) - return itemStack; - if (itemStack.getItemDamage() == 4 && !world.isRemote && entityPlayer.isSneaking()) { - switch (itemStack.getTagCompound().getInteger("mode")) { - case 0: - itemStack.getTagCompound().setInteger("mode", 1); - entityPlayer.addChatMessage(new ChatComponentTranslation("extracells.tooltip.storage.container.1")); - break; - case 1: - itemStack.getTagCompound().setInteger("mode", 2); - entityPlayer.addChatMessage(new ChatComponentTranslation("extracells.tooltip.storage.container.2")); - break; - case 2: - itemStack.getTagCompound().setInteger("mode", 0); - entityPlayer.addChatMessage(new ChatComponentTranslation("extracells.tooltip.storage.container.0")); - break; - } - return itemStack; - } - if (!entityPlayer.isSneaking()) - return itemStack; - IMEInventoryHandler invHandler = AEApi.instance().registries().cell().getCellInventory(itemStack, null, StorageChannel.ITEMS); - ICellInventoryHandler inventoryHandler = (ICellInventoryHandler) invHandler; - ICellInventory cellInv = inventoryHandler.getCellInv(); - if (cellInv.getUsedBytes() == 0 && entityPlayer.inventory.addItemStackToInventory(ItemEnum.STORAGECASING.getDamagedStack(0))) - return ItemEnum.STORAGECOMPONET.getDamagedStack(itemStack.getItemDamage()); - return itemStack; - } - - @Override - public boolean onItemUse(ItemStack itemstack, EntityPlayer player, - World world, int x, int y, int z, int side, float xOffset, - float yOffset, float zOffset) { - if (itemstack == null || player == null) - return false; - if (itemstack.getItemDamage() == 4 && !player.isSneaking()) { - double power = getAECurrentPower(itemstack); - ForgeDirection face = ForgeDirection.getOrientation(side); - IItemList list = AEApi.instance().registries().cell().getCellInventory(itemstack, null, StorageChannel.ITEMS).getAvailableItems( - AEApi.instance().storage().createItemList()); - if (list.isEmpty()) - return false; - IAEItemStack storageStack = (IAEItemStack) list.getFirstItem(); - if (world.getBlock(x + face.offsetX, y + face.offsetY, z + face.offsetZ) == Blocks.air && storageStack.getStackSize() != 0 && power >= 20.0D) { - if (!world.isRemote) { - IAEItemStack request = storageStack.copy(); - request.setStackSize(1); - ItemStack block = request.getItemStack(); - if (block.getItem() instanceof ItemBlock) { - ItemBlock itemblock = (ItemBlock) request.getItem(); - if (world.getBlock(x, y, z) != Blocks.bedrock && world.getBlock(x, y, z).getBlockHardness(world, x, y, z) >= 0.0F) { - switch (itemstack.getTagCompound().getInteger("mode")) { - case 0: - request.setStackSize(1); - itemblock.onItemUseFirst(request.getItemStack(), player, world, x, y, z, side, xOffset, yOffset, zOffset); - itemblock.onItemUse(request.getItemStack(), player, world, x, y, z, side, xOffset, yOffset, zOffset); - AEApi.instance().registries().cell().getCellInventory(itemstack, null, StorageChannel.ITEMS).extractItems(request, Actionable.MODULATE, new PlayerSource(player, null));extractAEPower(player.getCurrentEquippedItem(), 20.0D); - break; - case 1: - request.setStackSize(1); - world.func_147480_a(x, y, z, true); - placeBlock(request.getItemStack(), world, player, x, y, z, side, xOffset, yOffset, zOffset); - AEApi.instance().registries().cell().getCellInventory(itemstack, null, StorageChannel.ITEMS).extractItems(request, Actionable.MODULATE, new PlayerSource(player, null)); - break; - case 2: - - request.setStackSize(9); - if (storageStack.getStackSize() > 9 - && power >= 180.0D) { - switch (ForgeDirection.getOrientation(side)) { - case DOWN: - for (int posX = x - 1; posX < x + 2; posX++) { - for (int posZ = z - 1; posZ < z + 2; posZ++) { - if (world.getBlock(posX, y, posZ) != Blocks.bedrock && world.getBlock(posX, y, posZ).getBlockHardness(world, posX, y, posZ) >= 0.0F) { - world.func_147480_a(posX, y, posZ, true); - placeBlock(request.getItemStack(), world, player, x, y, z, side, xOffset, yOffset, zOffset); - } - } - } - AEApi.instance().registries().cell().getCellInventory(itemstack, null, StorageChannel.ITEMS).extractItems(request, Actionable.MODULATE, new PlayerSource(player, null)); - break; - case EAST: - for (int posZ = z - 1; posZ < z + 2; posZ++) { - for (int posY = y - 1; posY < y + 2; posY++) { - if (world.getBlock(x, posY, posZ) != Blocks.bedrock && world.getBlock(x, posY, posZ).getBlockHardness(world, x, posY, posZ) >= 0.0F) { - world.func_147480_a(x, posY, posZ, true); - placeBlock(request.getItemStack(), world, player, x, posY, posZ, side, xOffset, yOffset, zOffset); - } - } - } - AEApi.instance().registries().cell().getCellInventory(itemstack, null, StorageChannel.ITEMS).extractItems(request, Actionable.MODULATE, new PlayerSource(player, null)); - break; - case NORTH: - for (int posX = x - 1; posX < x + 2; posX++) { - for (int posY = y - 1; posY < y + 2; posY++) { - if (world.getBlock(posX, posY, z) != Blocks.bedrock && world.getBlock(posX, posY, z).getBlockHardness(world, posX, posY, z) >= 0.0F) { - world.func_147480_a(posX, posY, - z, true); - placeBlock( - request.getItemStack(), - world, player, posX, - posY, z, side, xOffset, - yOffset, zOffset); - } - } - } - AEApi.instance() - .registries() - .cell() - .getCellInventory(itemstack, - null, - StorageChannel.ITEMS) - .extractItems( - request, - Actionable.MODULATE, - new PlayerSource( - player, null)); - break; - case SOUTH: - for (int posX = x - 1; posX < x + 2; posX++) { - for (int posY = y - 1; posY < y + 2; posY++) { - if (world.getBlock(posX, posY, z) != Blocks.bedrock && world.getBlock(posX, posY, z).getBlockHardness(world, posX, posY, z) >= 0.0F) { - world.func_147480_a(posX, posY, - z, true); - placeBlock( - request.getItemStack(), - world, player, posX, - posY, z, side, xOffset, - yOffset, zOffset); - } - } - } - AEApi.instance() - .registries() - .cell() - .getCellInventory(itemstack, - null, - StorageChannel.ITEMS) - .extractItems( - request, - Actionable.MODULATE, - new PlayerSource( - player, null)); - break; - case UNKNOWN: - break; - case UP: - for (int posX = x - 1; posX < x + 2; posX++) { - for (int posZ = z - 1; posZ < z + 2; posZ++) { - if (world.getBlock(posX, y, posZ) != Blocks.bedrock && world.getBlock(posX, y, posZ).getBlockHardness(world, posX, y, posZ) >= 0.0F) { - world.func_147480_a(posX, y, - posZ, true); - placeBlock( - request.getItemStack(), - world, player, posX, y, - posZ, side, xOffset, - yOffset, zOffset); - } - } - } - AEApi.instance() - .registries() - .cell() - .getCellInventory(itemstack, - null, - StorageChannel.ITEMS) - .extractItems( - request, - Actionable.MODULATE, - new PlayerSource( - player, null)); - break; - case WEST: - for (int posZ = z - 1; posZ < z + 2; posZ++) { - for (int posY = y - 1; posY < y + 2; posY++) { - if (world.getBlock(x, posY, posZ) != Blocks.bedrock && world.getBlock(x, posY, posZ).getBlockHardness(world, x, posY, posZ) >= 0.0F) { - world.func_147480_a(x, posY, - posZ, true); - placeBlock( - request.getItemStack(), - world, player, x, posY, - posZ, side, xOffset, - yOffset, zOffset); - } - } - } - AEApi.instance() - .registries() - .cell() - .getCellInventory(itemstack, - null, - StorageChannel.ITEMS) - .extractItems( - request, - Actionable.MODULATE, - new PlayerSource( - player, null)); - break; - default: - break; - } - } - } - return true; - } else { - return false; - } - } else { - player.addChatMessage(new ChatComponentTranslation( - "extracells.tooltip.onlyblocks")); - return false; - } - } else { - return false; - } - } else { - return false; - } - } else { - return false; - } - } - - public void placeBlock(ItemStack itemstack, World world, - EntityPlayer player, int x, int y, int z, int side, float xOffset, - float yOffset, float zOffset) { - extractAEPower(player.getCurrentEquippedItem(), 20.0D); - ItemBlock itemblock = (ItemBlock) itemstack.getItem(); - switch (ForgeDirection.getOrientation(side)) { - case DOWN: - itemblock.onItemUseFirst(itemstack, player, world, x, y++, z, side, - xOffset, yOffset, zOffset); - itemblock.onItemUse(itemstack, player, world, x, y++, z, side, - xOffset, yOffset, zOffset); - break; - case EAST: - itemblock.onItemUseFirst(itemstack, player, world, x--, y, z, side, - xOffset, yOffset, zOffset); - itemblock.onItemUse(itemstack, player, world, x--, y, z, side, - xOffset, yOffset, zOffset); - break; - case NORTH: - itemblock.onItemUseFirst(itemstack, player, world, x, y, z++, side, - xOffset, yOffset, zOffset); - itemblock.onItemUse(itemstack, player, world, x, y, z++, side, - xOffset, yOffset, zOffset); - break; - case SOUTH: - itemblock.onItemUseFirst(itemstack, player, world, x, y, z--, side, - xOffset, yOffset, zOffset); - itemblock.onItemUse(itemstack, player, world, x, y, z--, side, - xOffset, yOffset, zOffset); - break; - case UNKNOWN: - break; - case UP: - itemblock.onItemUseFirst(itemstack, player, world, x, y--, z, side, - xOffset, yOffset, zOffset); - itemblock.onItemUse(itemstack, player, world, x, y--, z, side, - xOffset, yOffset, zOffset); - break; - case WEST: - itemblock.onItemUseFirst(itemstack, player, world, x++, y, z, side, - xOffset, yOffset, zOffset); - itemblock.onItemUse(itemstack, player, world, x++, y, z, side, - xOffset, yOffset, zOffset); - break; - default: - break; - } - } - - @Override - @Optional.Method(modid = "CoFHAPI|energy") - public int receiveEnergy(ItemStack container, int maxReceive, - boolean simulate) { - if (container == null || container.getItemDamage() != 4) - return 0; - if (simulate) { - double current = PowerUnits.AE.convertTo(PowerUnits.RF, - getAECurrentPower(container)); - double max = PowerUnits.AE.convertTo(PowerUnits.RF, - getAEMaxPower(container)); - if (max - current >= maxReceive) - return maxReceive; - else - return (int) (max - current); - } else { - int notStored = (int) PowerUnits.AE - .convertTo( - PowerUnits.RF, - injectAEPower(container, PowerUnits.RF.convertTo( - PowerUnits.AE, maxReceive))); - return maxReceive - notStored; - } - } - - @Override - public void registerIcons(IIconRegister iconRegister) { - this.icons = new IIcon[suffixes.length]; - - for (int i = 0; i < suffixes.length; ++i) { - this.icons[i] = iconRegister.registerIcon("extracells:" - + "storage.physical." + suffixes[i]); - } - } - - @Override - public void setFuzzyMode(ItemStack is, FuzzyMode fzMode) { - if (!is.hasTagCompound()) - is.setTagCompound(new NBTTagCompound()); - is.getTagCompound().setInteger("fuzzyMode", fzMode.ordinal()); - } - - @Override - public boolean showDurabilityBar(ItemStack itemStack) { - if (itemStack == null) - return false; - return itemStack.getItemDamage() == 4 ? true : false; - } - - @Override - public boolean storableInStorageCell() { - return false; - } +public class ItemStoragePhysical extends ItemECBase implements IStorageCell, IAEItemPowerStorage, IEnergyContainerItem { + + public static final String[] suffixes = { "256k", "1024k", "4096k", "16384k", "container" }; + + public static final int[] bytes_cell = { 262144, 1048576, 4194304, 16777216, 65536 }; + public static final double[] idle_drain_cell = { 2.5, 3.0, 3.5, 4.0, 2.0 }; + public static final int[] types_cell = { 63, 63, 63, 63, 1 }; + private IIcon[] icons; + private final int MAX_POWER = 32000; + + public ItemStoragePhysical() { + setMaxStackSize(1); + setMaxDamage(0); + setHasSubtypes(true); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean par4) { + super.addInformation(itemStack, player, list, par4); + DeprecationWarning.addContentTransferInfo(list); + + ICellRegistry cellRegistry = AEApi.instance().registries().cell(); + IMEInventoryHandler invHandler = cellRegistry + .getCellInventory(itemStack, null, StorageChannel.ITEMS); + ICellInventoryHandler inventoryHandler = (ICellInventoryHandler) invHandler; + ICellInventory cellInv = inventoryHandler.getCellInv(); + long usedBytes = cellInv.getUsedBytes(); + + list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.physical.bytes"), + usedBytes, + cellInv.getTotalBytes())); + list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.physical.types"), + cellInv.getStoredItemTypes(), + cellInv.getTotalItemTypes())); + if (usedBytes > 0) list.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.physical.content"), + cellInv.getStoredItemCount())); + } + + @Override + public int getBytesPerType(ItemStack cellItem) { + return Extracells.dynamicTypes() + ? bytes_cell[MathHelper.clamp_int(cellItem.getItemDamage(), 0, suffixes.length - 1)] / 128 + : 8; + } + + @Override + @Deprecated + public int BytePerType(ItemStack cellItem) { + return getBytesPerType(cellItem); + } + + private NBTTagCompound ensureTagCompound(ItemStack itemStack) { + if (!itemStack.hasTagCompound()) itemStack.setTagCompound(new NBTTagCompound()); + return itemStack.getTagCompound(); + } + + @Override + public double extractAEPower(ItemStack itemStack, double amt) { + if (itemStack == null || itemStack.getItemDamage() != 4) return 0.0D; + NBTTagCompound tagCompound = ensureTagCompound(itemStack); + double currentPower = tagCompound.getDouble("power"); + double toExtract = Math.min(amt, currentPower); + tagCompound.setDouble("power", currentPower - toExtract); + return toExtract; + } + + @Override + @Optional.Method(modid = "CoFHAPI|energy") + public int extractEnergy(ItemStack container, int maxExtract, boolean simulate) { + if (container == null || container.getItemDamage() != 4) return 0; + if (simulate) { + return getEnergyStored(container) >= maxExtract ? maxExtract : getEnergyStored(container); + } else { + return (int) PowerUnits.AE.convertTo( + PowerUnits.RF, + extractAEPower(container, PowerUnits.RF.convertTo(PowerUnits.AE, maxExtract))); + } + } + + @Override + public double getAECurrentPower(ItemStack itemStack) { + if (itemStack == null || itemStack.getItemDamage() != 4) return 0.0D; + NBTTagCompound tagCompound = ensureTagCompound(itemStack); + return tagCompound.getDouble("power"); + } + + @Override + public double getAEMaxPower(ItemStack itemStack) { + if (itemStack == null || itemStack.getItemDamage() != 4) return 0.0D; + return this.MAX_POWER; + } + + @Override + public int getBytes(ItemStack cellItem) { + return bytes_cell[MathHelper.clamp_int(cellItem.getItemDamage(), 0, suffixes.length - 1)]; + } + + @Override + public IInventory getConfigInventory(ItemStack is) { + return new ECCellInventory(is, "config", 63, 1); + } + + @Override + public double getDurabilityForDisplay(ItemStack itemStack) { + if (itemStack == null || itemStack.getItemDamage() != 4) return super.getDurabilityForDisplay(itemStack); + return 1 - getAECurrentPower(itemStack) / this.MAX_POWER; + } + + @Override + @Optional.Method(modid = "CoFHAPI|energy") + public int getEnergyStored(ItemStack arg0) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, getAECurrentPower(arg0)); + } + + @Override + public FuzzyMode getFuzzyMode(ItemStack is) { + if (!is.hasTagCompound()) is.setTagCompound(new NBTTagCompound()); + return FuzzyMode.values()[is.getTagCompound().getInteger("fuzzyMode")]; + } + + @Override + public IIcon getIconFromDamage(int dmg) { + return this.icons[MathHelper.clamp_int(dmg, 0, suffixes.length - 1)]; + } + + @Override + @Deprecated + public double getIdleDrain() { + return 2.5; + } + + @Override + public double getIdleDrain(@Nullable ItemStack cellItem) { + return cellItem != null + ? idle_drain_cell[MathHelper.clamp_int(cellItem.getItemDamage(), 0, idle_drain_cell.length - 1)] + : 2.5; + } + + @SideOnly(Side.CLIENT) + @Override + public String getItemStackDisplayName(ItemStack stack) { + if (stack == null) return super.getItemStackDisplayName(stack); + if (stack.getItemDamage() == 4) { + try { + IItemList list = AEApi.instance().registries().cell() + .getCellInventory(stack, null, StorageChannel.ITEMS) + .getAvailableItems(AEApi.instance().storage().createItemList(), IterationCounter.fetchNewId()); + if (list.isEmpty()) return super.getItemStackDisplayName(stack) + " - " + + StatCollector.translateToLocal("extracells.tooltip.empty1"); + IAEItemStack s = (IAEItemStack) list.getFirstItem(); + return super.getItemStackDisplayName(stack) + " - " + s.getItemStack().getDisplayName(); + } catch (Throwable e) {} + return super.getItemStackDisplayName(stack) + " - " + + StatCollector.translateToLocal("extracells.tooltip.empty1"); + } + return super.getItemStackDisplayName(stack); + } + + @Override + @Optional.Method(modid = "CoFHAPI|energy") + public int getMaxEnergyStored(ItemStack arg0) { + return (int) PowerUnits.AE.convertTo(PowerUnits.RF, getAEMaxPower(arg0)); + } + + @Override + public AccessRestriction getPowerFlow(ItemStack itemStack) { + if (itemStack == null) return null; + return itemStack.getItemDamage() == 4 ? AccessRestriction.READ_WRITE : AccessRestriction.NO_ACCESS; + } + + @Override + @SuppressWarnings("unchecked") + public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) { + for (int i = 0; i < suffixes.length; i++) { + itemList.add(new ItemStack(item, 1, i)); + if (i == 4) { + ItemStack s = new ItemStack(item, 1, i); + s.setTagCompound(new NBTTagCompound()); + s.getTagCompound().setDouble("power", this.MAX_POWER); + itemList.add(s); + } + } + } + + @Override + public int getTotalTypes(ItemStack cellItem) { + return types_cell[MathHelper.clamp_int(cellItem.getItemDamage(), 0, suffixes.length - 1)]; + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return "extracells.item.storage.physical." + suffixes[itemStack.getItemDamage()]; + } + + @Override + public IInventory getUpgradesInventory(ItemStack is) { + return new ECCellInventory(is, "upgrades", 2, 1); + } + + @Override + public double injectAEPower(ItemStack itemStack, double amt) { + if (itemStack == null || itemStack.getItemDamage() != 4) return 0.0D; + NBTTagCompound tagCompound = ensureTagCompound(itemStack); + double currentPower = tagCompound.getDouble("power"); + double toInject = Math.min(amt, this.MAX_POWER - currentPower); + tagCompound.setDouble("power", currentPower + toInject); + return toInject; + } + + @Override + public boolean isBlackListed(ItemStack cellItem, IAEItemStack requestedAddition) { + return false; + } + + @Override + public boolean isEditable(ItemStack is) { + return true; + } + + @Override + public boolean isStorageCell(ItemStack i) { + return true; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) { + if (itemStack == null) return itemStack; + if (itemStack.getItemDamage() == 4 && entityPlayer.isSneaking()) { + if (!world.isRemote) { + switch (itemStack.getTagCompound().getInteger("mode")) { + case 0: + itemStack.getTagCompound().setInteger("mode", 1); + entityPlayer + .addChatMessage(new ChatComponentTranslation("extracells.tooltip.storage.container.1")); + break; + case 1: + itemStack.getTagCompound().setInteger("mode", 2); + entityPlayer + .addChatMessage(new ChatComponentTranslation("extracells.tooltip.storage.container.2")); + break; + case 2: + itemStack.getTagCompound().setInteger("mode", 0); + entityPlayer + .addChatMessage(new ChatComponentTranslation("extracells.tooltip.storage.container.0")); + break; + } + } + return itemStack; + } + if (!entityPlayer.isSneaking()) return itemStack; + IMEInventoryHandler invHandler = AEApi.instance().registries().cell() + .getCellInventory(itemStack, null, StorageChannel.ITEMS); + ICellInventoryHandler inventoryHandler = (ICellInventoryHandler) invHandler; + ICellInventory cellInv = inventoryHandler.getCellInv(); + if (cellInv.getUsedBytes() == 0 + && entityPlayer.inventory.addItemStackToInventory(ItemEnum.STORAGECASING.getDamagedStack(0))) + return ItemEnum.STORAGECOMPONENT.getDamagedStack(itemStack.getItemDamage()); + return itemStack; + } + + @Override + public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int side, + float xOffset, float yOffset, float zOffset) { + if (itemstack == null || player == null) return false; + if (itemstack.getItemDamage() == 4 && !player.isSneaking()) { + double power = getAECurrentPower(itemstack); + ForgeDirection face = ForgeDirection.getOrientation(side); + IItemList list = AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .getAvailableItems(AEApi.instance().storage().createItemList(), IterationCounter.fetchNewId()); + if (list.isEmpty()) return false; + IAEItemStack storageStack = (IAEItemStack) list.getFirstItem(); + if (world.getBlock(x + face.offsetX, y + face.offsetY, z + face.offsetZ) == Blocks.air + && storageStack.getStackSize() != 0 + && power >= 20.0D) { + if (!world.isRemote) { + IAEItemStack request = storageStack.copy(); + request.setStackSize(1); + ItemStack block = request.getItemStack(); + if (block.getItem() instanceof ItemBlock) { + ItemBlock itemblock = (ItemBlock) request.getItem(); + if (world.getBlock(x, y, z) != Blocks.bedrock + && world.getBlock(x, y, z).getBlockHardness(world, x, y, z) >= 0.0F) { + switch (itemstack.getTagCompound().getInteger("mode")) { + case 0: + request.setStackSize(1); + itemblock.onItemUseFirst( + request.getItemStack(), + player, + world, + x, + y, + z, + side, + xOffset, + yOffset, + zOffset); + itemblock.onItemUse( + request.getItemStack(), + player, + world, + x, + y, + z, + side, + xOffset, + yOffset, + zOffset); + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems(request, Actionable.MODULATE, new PlayerSource(player, null)); + extractAEPower(player.getCurrentEquippedItem(), 20.0D); + break; + case 1: + request.setStackSize(1); + world.func_147480_a(x, y, z, true); + placeBlock( + request.getItemStack(), + world, + player, + x, + y, + z, + side, + xOffset, + yOffset, + zOffset); + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems(request, Actionable.MODULATE, new PlayerSource(player, null)); + break; + case 2: + request.setStackSize(9); + if (storageStack.getStackSize() > 9 && power >= 180.0D) { + switch (ForgeDirection.getOrientation(side)) { + case DOWN: + for (int posX = x - 1; posX < x + 2; posX++) { + for (int posZ = z - 1; posZ < z + 2; posZ++) { + if (world.getBlock(posX, y, posZ) != Blocks.bedrock + && world.getBlock(posX, y, posZ) + .getBlockHardness(world, posX, y, posZ) + >= 0.0F) { + world.func_147480_a(posX, y, posZ, true); + placeBlock( + request.getItemStack(), + world, + player, + x, + y, + z, + side, + xOffset, + yOffset, + zOffset); + } + } + } + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems( + request, + Actionable.MODULATE, + new PlayerSource(player, null)); + break; + case EAST: + for (int posZ = z - 1; posZ < z + 2; posZ++) { + for (int posY = y - 1; posY < y + 2; posY++) { + if (world.getBlock(x, posY, posZ) != Blocks.bedrock + && world.getBlock(x, posY, posZ) + .getBlockHardness(world, x, posY, posZ) + >= 0.0F) { + world.func_147480_a(x, posY, posZ, true); + placeBlock( + request.getItemStack(), + world, + player, + x, + posY, + posZ, + side, + xOffset, + yOffset, + zOffset); + } + } + } + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems( + request, + Actionable.MODULATE, + new PlayerSource(player, null)); + break; + case NORTH: + for (int posX = x - 1; posX < x + 2; posX++) { + for (int posY = y - 1; posY < y + 2; posY++) { + if (world.getBlock(posX, posY, z) != Blocks.bedrock + && world.getBlock(posX, posY, z) + .getBlockHardness(world, posX, posY, z) + >= 0.0F) { + world.func_147480_a(posX, posY, z, true); + placeBlock( + request.getItemStack(), + world, + player, + posX, + posY, + z, + side, + xOffset, + yOffset, + zOffset); + } + } + } + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems( + request, + Actionable.MODULATE, + new PlayerSource(player, null)); + break; + case SOUTH: + for (int posX = x - 1; posX < x + 2; posX++) { + for (int posY = y - 1; posY < y + 2; posY++) { + if (world.getBlock(posX, posY, z) != Blocks.bedrock + && world.getBlock(posX, posY, z) + .getBlockHardness(world, posX, posY, z) + >= 0.0F) { + world.func_147480_a(posX, posY, z, true); + placeBlock( + request.getItemStack(), + world, + player, + posX, + posY, + z, + side, + xOffset, + yOffset, + zOffset); + } + } + } + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems( + request, + Actionable.MODULATE, + new PlayerSource(player, null)); + break; + case UNKNOWN: + break; + case UP: + for (int posX = x - 1; posX < x + 2; posX++) { + for (int posZ = z - 1; posZ < z + 2; posZ++) { + if (world.getBlock(posX, y, posZ) != Blocks.bedrock + && world.getBlock(posX, y, posZ) + .getBlockHardness(world, posX, y, posZ) + >= 0.0F) { + world.func_147480_a(posX, y, posZ, true); + placeBlock( + request.getItemStack(), + world, + player, + posX, + y, + posZ, + side, + xOffset, + yOffset, + zOffset); + } + } + } + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems( + request, + Actionable.MODULATE, + new PlayerSource(player, null)); + break; + case WEST: + for (int posZ = z - 1; posZ < z + 2; posZ++) { + for (int posY = y - 1; posY < y + 2; posY++) { + if (world.getBlock(x, posY, posZ) != Blocks.bedrock + && world.getBlock(x, posY, posZ) + .getBlockHardness(world, x, posY, posZ) + >= 0.0F) { + world.func_147480_a(x, posY, posZ, true); + placeBlock( + request.getItemStack(), + world, + player, + x, + posY, + posZ, + side, + xOffset, + yOffset, + zOffset); + } + } + } + AEApi.instance().registries().cell() + .getCellInventory(itemstack, null, StorageChannel.ITEMS) + .extractItems( + request, + Actionable.MODULATE, + new PlayerSource(player, null)); + break; + default: + break; + } + } + } + return true; + } else { + return false; + } + } else { + player.addChatMessage(new ChatComponentTranslation("extracells.tooltip.onlyblocks")); + return false; + } + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + + public void placeBlock(ItemStack itemstack, World world, EntityPlayer player, int x, int y, int z, int side, + float xOffset, float yOffset, float zOffset) { + extractAEPower(player.getCurrentEquippedItem(), 20.0D); + ItemBlock itemblock = (ItemBlock) itemstack.getItem(); + switch (ForgeDirection.getOrientation(side)) { + case DOWN: + itemblock.onItemUseFirst(itemstack, player, world, x, y++, z, side, xOffset, yOffset, zOffset); + itemblock.onItemUse(itemstack, player, world, x, y++, z, side, xOffset, yOffset, zOffset); + break; + case EAST: + itemblock.onItemUseFirst(itemstack, player, world, x--, y, z, side, xOffset, yOffset, zOffset); + itemblock.onItemUse(itemstack, player, world, x--, y, z, side, xOffset, yOffset, zOffset); + break; + case NORTH: + itemblock.onItemUseFirst(itemstack, player, world, x, y, z++, side, xOffset, yOffset, zOffset); + itemblock.onItemUse(itemstack, player, world, x, y, z++, side, xOffset, yOffset, zOffset); + break; + case SOUTH: + itemblock.onItemUseFirst(itemstack, player, world, x, y, z--, side, xOffset, yOffset, zOffset); + itemblock.onItemUse(itemstack, player, world, x, y, z--, side, xOffset, yOffset, zOffset); + break; + case UNKNOWN: + break; + case UP: + itemblock.onItemUseFirst(itemstack, player, world, x, y--, z, side, xOffset, yOffset, zOffset); + itemblock.onItemUse(itemstack, player, world, x, y--, z, side, xOffset, yOffset, zOffset); + break; + case WEST: + itemblock.onItemUseFirst(itemstack, player, world, x++, y, z, side, xOffset, yOffset, zOffset); + itemblock.onItemUse(itemstack, player, world, x++, y, z, side, xOffset, yOffset, zOffset); + break; + default: + break; + } + } + + @Override + @Optional.Method(modid = "CoFHAPI|energy") + public int receiveEnergy(ItemStack container, int maxReceive, boolean simulate) { + if (container == null || container.getItemDamage() != 4) return 0; + if (simulate) { + double current = PowerUnits.AE.convertTo(PowerUnits.RF, getAECurrentPower(container)); + double max = PowerUnits.AE.convertTo(PowerUnits.RF, getAEMaxPower(container)); + if (max - current >= maxReceive) return maxReceive; + else return (int) (max - current); + } else { + int notStored = (int) PowerUnits.AE.convertTo( + PowerUnits.RF, + injectAEPower(container, PowerUnits.RF.convertTo(PowerUnits.AE, maxReceive))); + return maxReceive - notStored; + } + } + + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icons = new IIcon[suffixes.length]; + + for (int i = 0; i < suffixes.length; ++i) { + this.icons[i] = iconRegister.registerIcon("extracells:" + "storage.physical." + suffixes[i]); + } + } + + @Override + public void setFuzzyMode(ItemStack is, FuzzyMode fzMode) { + if (!is.hasTagCompound()) is.setTagCompound(new NBTTagCompound()); + is.getTagCompound().setInteger("fuzzyMode", fzMode.ordinal()); + } + + @Override + public String getOreFilter(ItemStack itemStack) { + return Platform.openNbtData(itemStack).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack itemStack, String s) { + Platform.openNbtData(itemStack).setString("OreFilter", s); + } + + @Override + public boolean showDurabilityBar(ItemStack itemStack) { + if (itemStack == null) return false; + return itemStack.getItemDamage() == 4 ? true : false; + } + + @Override + public boolean storableInStorageCell() { + return false; + } } diff --git a/src/main/scala/extracells/item/ItemStoragePortableFluidCell.scala b/src/main/scala/extracells/item/ItemStoragePortableFluidCell.scala index 38aa88305..c9c290a61 100644 --- a/src/main/scala/extracells/item/ItemStoragePortableFluidCell.scala +++ b/src/main/scala/extracells/item/ItemStoragePortableFluidCell.scala @@ -13,41 +13,89 @@ import net.minecraft.client.renderer.texture.IIconRegister import net.minecraft.creativetab.CreativeTabs import net.minecraft.entity.player.EntityPlayer import net.minecraft.inventory.IInventory -import net.minecraft.item.{EnumRarity, Item, ItemStack} +import net.minecraft.item.{Item, ItemStack} import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.{IIcon, StatCollector} import net.minecraft.world.World import net.minecraftforge.fluids.{Fluid, FluidRegistry} -object ItemStoragePortableFluidCell extends ItemECBase with IPortableFluidStorageCell with PowerItem { +object ItemStoragePortableFluidCell + extends ItemECBase + with IPortableFluidStorageCell + with PowerItem { - override val MAX_POWER: Double = 20000 + override val MAX_POWER: Double = 100000 private[item] var icon: IIcon = null def THIS = this setMaxStackSize(1) setMaxDamage(0) - - @SuppressWarnings(Array("rawtypes", "unchecked")) override def addInformation(itemStack: ItemStack, player: EntityPlayer, list: util.List[_], par4: Boolean) { + @SuppressWarnings(Array("rawtypes", "unchecked")) + override def addInformation( + itemStack: ItemStack, + player: EntityPlayer, + list: util.List[_], + par4: Boolean + ) { + super.addInformation(itemStack, player, list, par4) val list2 = list.asInstanceOf[util.List[String]] - val handler: IMEInventoryHandler[IAEFluidStack] = AEApi.instance.registries.cell.getCellInventory(itemStack, null, StorageChannel.FLUIDS).asInstanceOf[IMEInventoryHandler[IAEFluidStack]] + val handler: IMEInventoryHandler[IAEFluidStack] = + AEApi.instance.registries.cell + .getCellInventory(itemStack, null, StorageChannel.FLUIDS) + .asInstanceOf[IMEInventoryHandler[IAEFluidStack]] if (!(handler.isInstanceOf[IHandlerFluidStorage])) { return } - val cellHandler: IHandlerFluidStorage = handler.asInstanceOf[IHandlerFluidStorage] + val cellHandler: IHandlerFluidStorage = + handler.asInstanceOf[IHandlerFluidStorage] val partitioned: Boolean = cellHandler.isFormatted val usedBytes: Long = cellHandler.usedBytes val aeCurrentPower: Double = getAECurrentPower(itemStack) - list2.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.fluid.bytes"), (usedBytes / 250).asInstanceOf[AnyRef], (cellHandler.totalBytes / 250).asInstanceOf[AnyRef])) - list2.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.fluid.types"), cellHandler.usedTypes.asInstanceOf[AnyRef], cellHandler.totalTypes.asInstanceOf[AnyRef])) + list2.add( + String.format( + StatCollector.translateToLocal( + "extracells.tooltip.storage.fluid.bytes" + ), + (usedBytes / 250).asInstanceOf[AnyRef], + (cellHandler.totalBytes / 250).asInstanceOf[AnyRef] + ) + ) + list2.add( + String.format( + StatCollector.translateToLocal( + "extracells.tooltip.storage.fluid.types" + ), + cellHandler.usedTypes.asInstanceOf[AnyRef], + cellHandler.totalTypes.asInstanceOf[AnyRef] + ) + ) if (usedBytes != 0) { - list2.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.fluid.content"), usedBytes.asInstanceOf[AnyRef])) + list2.add( + String.format( + StatCollector.translateToLocal( + "extracells.tooltip.storage.fluid.content" + ), + usedBytes.asInstanceOf[AnyRef] + ) + ) } if (partitioned) { - list2.add(StatCollector.translateToLocal("gui.appliedenergistics2.Partitioned") + " - " + StatCollector.translateToLocal("gui.appliedenergistics2.Precise")) + list2.add( + StatCollector.translateToLocal( + "gui.appliedenergistics2.Partitioned" + ) + " - " + StatCollector.translateToLocal( + "gui.appliedenergistics2.Precise" + ) + ) } - list2.add(StatCollector.translateToLocal("gui.appliedenergistics2.StoredEnergy") + ": " + aeCurrentPower + " AE - " + Math.floor(aeCurrentPower / ItemStoragePortableFluidCell.MAX_POWER * 1e4) / 1e2 + "%") + list2.add( + StatCollector.translateToLocal( + "gui.appliedenergistics2.StoredEnergy" + ) + ": " + aeCurrentPower + " AE - " + Math.floor( + aeCurrentPower / ItemStoragePortableFluidCell.MAX_POWER * 1e4 + ) / 1e2 + "%" + ) } def getConfigInventory(is: ItemStack): IInventory = { @@ -55,12 +103,14 @@ object ItemStoragePortableFluidCell extends ItemECBase with IPortableFluidStorag } override def getDurabilityForDisplay(itemStack: ItemStack): Double = { - return 1 - getAECurrentPower(itemStack) / ItemStoragePortableFluidCell.MAX_POWER + return 1 - getAECurrentPower( + itemStack + ) / ItemStoragePortableFluidCell.MAX_POWER } - def getFilter(stack: ItemStack): util.ArrayList[Fluid] = { - val inventory: ECFluidFilterInventory = new ECFluidFilterInventory("", 63, stack) + val inventory: ECFluidFilterInventory = + new ECFluidFilterInventory("", 63, stack) val stacks: Array[ItemStack] = inventory.slots val filter: util.ArrayList[Fluid] = new util.ArrayList[Fluid] if (stacks.length == 0) return null @@ -76,7 +126,8 @@ object ItemStoragePortableFluidCell extends ItemECBase with IPortableFluidStorag def getFuzzyMode(is: ItemStack): FuzzyMode = { if (is == null) return null if (!is.hasTagCompound) is.setTagCompound(new NBTTagCompound) - if (is.getTagCompound.hasKey("fuzzyMode")) return FuzzyMode.valueOf(is.getTagCompound.getString("fuzzyMode")) + if (is.getTagCompound.hasKey("fuzzyMode")) + return FuzzyMode.valueOf(is.getTagCompound.getString("fuzzyMode")) is.getTagCompound.setString("fuzzyMode", FuzzyMode.IGNORE_ALL.name) return FuzzyMode.IGNORE_ALL } @@ -86,10 +137,10 @@ object ItemStoragePortableFluidCell extends ItemECBase with IPortableFluidStorag } def getMaxBytes(is: ItemStack): Int = { - return 512 + // 8192 buckets when using only one fluid type + return 32768 } - def getMaxTypes(unused: ItemStack): Int = { return 3 } @@ -98,11 +149,11 @@ object ItemStoragePortableFluidCell extends ItemECBase with IPortableFluidStorag return AccessRestriction.READ_WRITE } - override def getRarity(itemStack: ItemStack): EnumRarity = { - return EnumRarity.rare - } - - override def getSubItems(item: Item, creativeTab: CreativeTabs, itemList: util.List[_]) { + override def getSubItems( + item: Item, + creativeTab: CreativeTabs, + itemList: util.List[_] + ) { val itemList2 = itemList.asInstanceOf[util.List[ItemStack]] itemList2.add(new ItemStack(item)) val itemStack: ItemStack = new ItemStack(item) @@ -128,11 +179,14 @@ object ItemStoragePortableFluidCell extends ItemECBase with IPortableFluidStorag } @SuppressWarnings(Array("rawtypes", "unchecked")) - override def onItemRightClick(itemStack: ItemStack, world: World, player: EntityPlayer): ItemStack = { + override def onItemRightClick( + itemStack: ItemStack, + world: World, + player: EntityPlayer + ): ItemStack = { return ECApi.instance.openPortableFluidCellGui(player, itemStack, world) } - @SideOnly(Side.CLIENT) override def registerIcons(iconRegister: IIconRegister) { this.icon = iconRegister.registerIcon("extracells:storage.fluid.portable") @@ -153,4 +207,8 @@ object ItemStoragePortableFluidCell extends ItemECBase with IPortableFluidStorag extractAEPower(is, amount) return true } + + override def getOreFilter(itemStack: ItemStack): String = "" + + override def setOreFilter(itemStack: ItemStack, s: String): Unit = Unit } diff --git a/src/main/scala/extracells/item/ItemStoragePortableGasCell.scala b/src/main/scala/extracells/item/ItemStoragePortableGasCell.scala index 3474ecdfb..87c06e5e6 100644 --- a/src/main/scala/extracells/item/ItemStoragePortableGasCell.scala +++ b/src/main/scala/extracells/item/ItemStoragePortableGasCell.scala @@ -13,13 +13,16 @@ import net.minecraft.client.renderer.texture.IIconRegister import net.minecraft.creativetab.CreativeTabs import net.minecraft.entity.player.EntityPlayer import net.minecraft.inventory.IInventory -import net.minecraft.item.{EnumRarity, Item, ItemStack} +import net.minecraft.item.{Item, ItemStack} import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.{IIcon, StatCollector} import net.minecraft.world.World import net.minecraftforge.fluids.{Fluid, FluidRegistry} -object ItemStoragePortableGasCell extends ItemECBase with IPortableGasStorageCell with PowerItem { +object ItemStoragePortableGasCell + extends ItemECBase + with IPortableGasStorageCell + with PowerItem { override val MAX_POWER: Double = 20000 private[item] var icon: IIcon = null @@ -27,39 +30,78 @@ object ItemStoragePortableGasCell extends ItemECBase with IPortableGasStorageCel setMaxStackSize(1) setMaxDamage(0) - @SuppressWarnings(Array("rawtypes", "unchecked")) - override def addInformation(itemStack: ItemStack, player: EntityPlayer, list: util.List[_], par4: Boolean) { + override def addInformation( + itemStack: ItemStack, + player: EntityPlayer, + list: util.List[_], + par4: Boolean + ) { val list2 = list.asInstanceOf[util.List[String]] - val handler: IMEInventoryHandler[IAEFluidStack] = AEApi.instance.registries.cell.getCellInventory(itemStack, null, StorageChannel.FLUIDS).asInstanceOf[IMEInventoryHandler[IAEFluidStack]] + val handler: IMEInventoryHandler[IAEFluidStack] = + AEApi.instance.registries.cell + .getCellInventory(itemStack, null, StorageChannel.FLUIDS) + .asInstanceOf[IMEInventoryHandler[IAEFluidStack]] if (!(handler.isInstanceOf[IHandlerFluidStorage])) { return } - val cellHandler: IHandlerFluidStorage = handler.asInstanceOf[IHandlerFluidStorage] + val cellHandler: IHandlerFluidStorage = + handler.asInstanceOf[IHandlerFluidStorage] val partitioned: Boolean = cellHandler.isFormatted val usedBytes: Long = cellHandler.usedBytes val aeCurrentPower: Double = getAECurrentPower(itemStack) - list2.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.gas.bytes"), (usedBytes / 250).asInstanceOf[AnyRef], (cellHandler.totalBytes / 250).asInstanceOf[AnyRef])) - list2.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.gas.types"), cellHandler.usedTypes.asInstanceOf[AnyRef], cellHandler.totalTypes.asInstanceOf[AnyRef])) + list2.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.gas.bytes"), + (usedBytes / 250).asInstanceOf[AnyRef], + (cellHandler.totalBytes / 250).asInstanceOf[AnyRef] + ) + ) + list2.add( + String.format( + StatCollector.translateToLocal("extracells.tooltip.storage.gas.types"), + cellHandler.usedTypes.asInstanceOf[AnyRef], + cellHandler.totalTypes.asInstanceOf[AnyRef] + ) + ) if (usedBytes != 0) { - list2.add(String.format(StatCollector.translateToLocal("extracells.tooltip.storage.gas.content"), usedBytes.asInstanceOf[AnyRef])) + list2.add( + String.format( + StatCollector.translateToLocal( + "extracells.tooltip.storage.gas.content" + ), + usedBytes.asInstanceOf[AnyRef] + ) + ) } if (partitioned) { - list2.add(StatCollector.translateToLocal("gui.appliedenergistics2.Partitioned") + " - " + StatCollector.translateToLocal("gui.appliedenergistics2.Precise")) + list2.add( + StatCollector.translateToLocal( + "gui.appliedenergistics2.Partitioned" + ) + " - " + StatCollector.translateToLocal( + "gui.appliedenergistics2.Precise" + ) + ) } - list2.add(StatCollector.translateToLocal("gui.appliedenergistics2.StoredEnergy") + ": " + aeCurrentPower + " AE - " + Math.floor(aeCurrentPower / ItemStoragePortableFluidCell.MAX_POWER * 1e4) / 1e2 + "%") + list2.add( + StatCollector.translateToLocal( + "gui.appliedenergistics2.StoredEnergy" + ) + ": " + aeCurrentPower + " AE - " + Math.floor( + aeCurrentPower / ItemStoragePortableFluidCell.MAX_POWER * 1e4 + ) / 1e2 + "%" + ) } - def getConfigInventory(is: ItemStack): IInventory = new ECFluidFilterInventory("configFluidCell", 63, is) - - - override def getDurabilityForDisplay(itemStack: ItemStack): Double = 1 - getAECurrentPower(itemStack) / ItemStoragePortableFluidCell.MAX_POWER - + def getConfigInventory(is: ItemStack): IInventory = + new ECFluidFilterInventory("configFluidCell", 63, is) + override def getDurabilityForDisplay(itemStack: ItemStack): Double = + 1 - getAECurrentPower(itemStack) / ItemStoragePortableFluidCell.MAX_POWER def getFilter(stack: ItemStack): util.ArrayList[Fluid] = { - val inventory: ECFluidFilterInventory = new ECFluidFilterInventory("", 63, stack) + val inventory: ECFluidFilterInventory = + new ECFluidFilterInventory("", 63, stack) val stacks: Array[ItemStack] = inventory.slots val filter: util.ArrayList[Fluid] = new util.ArrayList[Fluid] if (stacks.length == 0) return null @@ -75,28 +117,26 @@ object ItemStoragePortableGasCell extends ItemECBase with IPortableGasStorageCel def getFuzzyMode(is: ItemStack): FuzzyMode = { if (is == null) return null if (!is.hasTagCompound) is.setTagCompound(new NBTTagCompound) - if (is.getTagCompound.hasKey("fuzzyMode")) return FuzzyMode.valueOf(is.getTagCompound.getString("fuzzyMode")) + if (is.getTagCompound.hasKey("fuzzyMode")) + return FuzzyMode.valueOf(is.getTagCompound.getString("fuzzyMode")) is.getTagCompound.setString("fuzzyMode", FuzzyMode.IGNORE_ALL.name) FuzzyMode.IGNORE_ALL } override def getIconFromDamage(dmg: Int): IIcon = this.icon - def getMaxBytes(is: ItemStack): Int = 512 - - def getMaxTypes(unused: ItemStack): Int = 3 + override def getPowerFlow(itemStack: ItemStack): AccessRestriction = + AccessRestriction.READ_WRITE - override def getPowerFlow(itemStack: ItemStack): AccessRestriction = AccessRestriction.READ_WRITE - - - override def getRarity(itemStack: ItemStack): EnumRarity = EnumRarity.rare - - - override def getSubItems(item: Item, creativeTab: CreativeTabs, itemList: util.List[_]) { + override def getSubItems( + item: Item, + creativeTab: CreativeTabs, + itemList: util.List[_] + ) { val itemList2 = itemList.asInstanceOf[util.List[ItemStack]] itemList2.add(new ItemStack(item)) val itemStack: ItemStack = new ItemStack(item) @@ -104,14 +144,14 @@ object ItemStoragePortableGasCell extends ItemECBase with IPortableGasStorageCel itemList2.add(itemStack) } - override def getUnlocalizedName(itemStack: ItemStack): String = "extracells.item.storage.gas.portable" - - - def getUpgradesInventory(is: ItemStack): IInventory = new ECPrivateInventory("configInventory", 0, 64) + override def getUnlocalizedName(itemStack: ItemStack): String = + "extracells.item.storage.gas.portable" + def getUpgradesInventory(is: ItemStack): IInventory = + new ECPrivateInventory("configInventory", 0, 64) - def hasPower(player: EntityPlayer, amount: Double, is: ItemStack): Boolean = getAECurrentPower(is) >= amount - + def hasPower(player: EntityPlayer, amount: Double, is: ItemStack): Boolean = + getAECurrentPower(is) >= amount def isEditable(is: ItemStack): Boolean = { if (is == null) return false @@ -119,11 +159,13 @@ object ItemStoragePortableGasCell extends ItemECBase with IPortableGasStorageCel } @SuppressWarnings(Array("rawtypes", "unchecked")) - override def onItemRightClick(itemStack: ItemStack, world: World, player: EntityPlayer): ItemStack = + override def onItemRightClick( + itemStack: ItemStack, + world: World, + player: EntityPlayer + ): ItemStack = ECApi.instance.openPortableGasCellGui(player, itemStack, world) - - @SideOnly(Side.CLIENT) override def registerIcons(iconRegister: IIconRegister) { this.icon = iconRegister.registerIcon("extracells:storage.gas.portable") @@ -138,9 +180,12 @@ object ItemStoragePortableGasCell extends ItemECBase with IPortableGasStorageCel override def showDurabilityBar(itemStack: ItemStack): Boolean = true - def usePower(player: EntityPlayer, amount: Double, is: ItemStack): Boolean = { extractAEPower(is, amount) true } + + override def getOreFilter(itemStack: ItemStack): String = "" + + override def setOreFilter(itemStack: ItemStack, s: String): Unit = Unit } diff --git a/src/main/scala/extracells/item/ItemVoidStorageCell.java b/src/main/scala/extracells/item/ItemVoidStorageCell.java new file mode 100644 index 000000000..65b2aae63 --- /dev/null +++ b/src/main/scala/extracells/item/ItemVoidStorageCell.java @@ -0,0 +1,192 @@ +package extracells.item; + +import java.util.EnumSet; +import java.util.List; +import java.util.Set; + +import net.minecraft.client.renderer.texture.IIconRegister; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; + +import appeng.api.AEApi; +import appeng.api.config.FuzzyMode; +import appeng.api.exceptions.MissingDefinition; +import appeng.api.implementations.items.IItemGroup; +import appeng.api.storage.ICellInventory; +import appeng.api.storage.ICellInventoryHandler; +import appeng.api.storage.IMEInventoryHandler; +import appeng.api.storage.StorageChannel; +import appeng.api.storage.data.IAEItemStack; +import appeng.core.AEConfig; +import appeng.core.features.AEFeature; +import appeng.core.localization.GuiText; +import appeng.items.AEBaseItem; +import appeng.items.contents.CellConfig; +import appeng.items.contents.CellUpgrades; +import appeng.util.Platform; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.api.IStorageCellVoid; +import extracells.inventory.VoidCellInventoryHandler; +import extracells.util.DeprecationWarning; + +public final class ItemVoidStorageCell extends AEBaseItem implements IStorageCellVoid, IItemGroup { + + private final int totalBytes; + private final int totalTypes; + private final int perType; + private final double idleDrain; + private final String suffix; + private IIcon icon; + + public ItemVoidStorageCell() { + + this.setFeature(EnumSet.of(AEFeature.StorageCells)); + this.setMaxStackSize(1); + this.totalBytes = 1024; + this.totalTypes = 63; + this.perType = 8; + this.idleDrain = 0.0; + this.suffix = "void"; + } + + @SideOnly(Side.CLIENT) + @Override + public void addCheckedInformation(final ItemStack stack, final EntityPlayer player, final List lines, + final boolean displayMoreInfo) { + DeprecationWarning.addGeneralDeprecationWarning(lines); + + final IMEInventoryHandler inventory = AEApi.instance().registries().cell() + .getCellInventory(stack, null, StorageChannel.ITEMS); + + if (inventory instanceof VoidCellInventoryHandler) { + final ICellInventoryHandler handler = (ICellInventoryHandler) inventory; + + final ICellInventory cellInventory = handler.getCellInv(); + + if (cellInventory != null) { + lines.add("Deletes \u00A74everything\u00A77 stored on it "); + + lines.add( + cellInventory.getUsedBytes() + " " + + GuiText.Of.getLocal() + + " \u00A7k9999\u00A77 " + + GuiText.BytesUsed.getLocal()); + + ItemAdvancedStorageCell.format(lines, handler, cellInventory); + } + } + } + + @Override + public int getBytes(final ItemStack cellItem) { + return this.totalBytes; + } + + @Override + public int getBytesPerType(final ItemStack cellItem) { + return this.perType; + } + + @Override + public int getTotalTypes(final ItemStack cellItem) { + return this.totalTypes; + } + + @Override + public boolean isBlackListed(final ItemStack cellItem, final IAEItemStack requestedAddition) { + return false; + } + + @Override + public boolean storableInStorageCell() { + return false; + } + + @Override + public boolean isStorageCell(final ItemStack i) { + return true; + } + + @Override + public double getIdleDrain() { + return this.idleDrain; + } + + @Override + public String getUnlocalizedGroupName(final Set others, final ItemStack is) { + return GuiText.StorageCells.getUnlocalized(); + } + + @Override + public String getUnlocalizedName(ItemStack itemStack) { + return "extracells.item.storage.physical.void"; + } + + @Override + public void registerIcons(IIconRegister iconRegister) { + this.icon = iconRegister.registerIcon("extracells:storage.physical.void"); + } + + @Override + public IIcon getIconFromDamage(int dmg) { + return this.icon; + } + + @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 String getOreFilter(ItemStack is) { + return Platform.openNbtData(is).getString("OreFilter"); + } + + @Override + public void setOreFilter(ItemStack is, String filter) { + Platform.openNbtData(is).setString("OreFilter", filter); + } + + @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); + } +} diff --git a/src/main/scala/extracells/item/ItemWirelessTerminalFluid.scala b/src/main/scala/extracells/item/ItemWirelessTerminalFluid.scala index e46ceb06a..057e58675 100644 --- a/src/main/scala/extracells/item/ItemWirelessTerminalFluid.scala +++ b/src/main/scala/extracells/item/ItemWirelessTerminalFluid.scala @@ -8,27 +8,33 @@ import net.minecraft.item.{Item, ItemStack} import net.minecraft.util.IIcon import net.minecraft.world.World -object ItemWirelessTerminalFluid extends Item with IWirelessFluidTermHandler with WirelessTermBase { +object ItemWirelessTerminalFluid + extends Item + with IWirelessFluidTermHandler + with WirelessTermBase { private[item] var icon: IIcon = null def THIS = this ECApi.instance.registerWirelessTermHandler(this) override def getIconFromDamage(dmg: Int): IIcon = this.icon - - override def getUnlocalizedName(itemStack: ItemStack): String = super.getUnlocalizedName(itemStack).replace("item.extracells", "extracells.item") - + override def getUnlocalizedName(itemStack: ItemStack): String = super + .getUnlocalizedName(itemStack) + .replace("item.extracells", "extracells.item") def isItemNormalWirelessTermToo(is: ItemStack): Boolean = false - - override def onItemRightClick(itemStack: ItemStack, world: World, entityPlayer: EntityPlayer): ItemStack = + override def onItemRightClick( + itemStack: ItemStack, + world: World, + entityPlayer: EntityPlayer + ): ItemStack = ECApi.instance.openWirelessFluidTerminal(entityPlayer, itemStack, world) - @SideOnly(Side.CLIENT) override def registerIcons(iconRegister: IIconRegister) { - this.icon = iconRegister.registerIcon("extracells:" + "terminal.fluid.wireless") + this.icon = + iconRegister.registerIcon("extracells:" + "terminal.fluid.wireless") } } diff --git a/src/main/scala/extracells/item/ItemWirelessTerminalGas.scala b/src/main/scala/extracells/item/ItemWirelessTerminalGas.scala index a181eadae..8b8d174e3 100644 --- a/src/main/scala/extracells/item/ItemWirelessTerminalGas.scala +++ b/src/main/scala/extracells/item/ItemWirelessTerminalGas.scala @@ -8,28 +8,34 @@ import net.minecraft.item.{Item, ItemStack} import net.minecraft.util.IIcon import net.minecraft.world.World -object ItemWirelessTerminalGas extends Item with IWirelessGasTermHandler with WirelessTermBase { +object ItemWirelessTerminalGas + extends Item + with IWirelessGasTermHandler + with WirelessTermBase { private[item] var icon: IIcon = null def THIS = this ECApi.instance.registerWirelessTermHandler(this) override def getIconFromDamage(dmg: Int): IIcon = this.icon - override def getUnlocalizedName(itemStack: ItemStack): String = - super.getUnlocalizedName(itemStack).replace("item.extracells", "extracells.item") - + super + .getUnlocalizedName(itemStack) + .replace("item.extracells", "extracells.item") def isItemNormalWirelessTermToo(is: ItemStack): Boolean = false - - override def onItemRightClick(itemStack: ItemStack, world: World, entityPlayer: EntityPlayer): ItemStack = + override def onItemRightClick( + itemStack: ItemStack, + world: World, + entityPlayer: EntityPlayer + ): ItemStack = ECApi.instance.openWirelessGasTerminal(entityPlayer, itemStack, world) - @SideOnly(Side.CLIENT) override def registerIcons(iconRegister: IIconRegister) { - this.icon = iconRegister.registerIcon("extracells:" + "terminal.fluid.wireless") + this.icon = + iconRegister.registerIcon("extracells:" + "terminal.fluid.wireless") } } diff --git a/src/main/scala/extracells/item/ItemWirelessTerminalUniversal.scala b/src/main/scala/extracells/item/ItemWirelessTerminalUniversal.scala index a1184fe18..80463d4fb 100644 --- a/src/main/scala/extracells/item/ItemWirelessTerminalUniversal.scala +++ b/src/main/scala/extracells/item/ItemWirelessTerminalUniversal.scala @@ -1,13 +1,14 @@ package extracells.item - -import java.util - import appeng.api.AEApi import appeng.api.features.IWirelessTermHandler import appeng.api.util.IConfigManager import cpw.mods.fml.relauncher.{Side, SideOnly} -import extracells.api.{ECApi, IWirelessFluidTermHandler, IWirelessGasTermHandler} +import extracells.api.{ + ECApi, + IWirelessFluidTermHandler, + IWirelessGasTermHandler +} import extracells.integration.Integration import extracells.integration.WirelessCrafting.WirelessCrafting import extracells.integration.thaumaticenergistics.ThaumaticEnergistics @@ -18,31 +19,38 @@ import net.minecraft.creativetab.CreativeTabs import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.{Item, ItemStack} import net.minecraft.nbt.NBTTagCompound -import net.minecraft.util.{IIcon, StatCollector} +import net.minecraft.util.{ChatComponentText, IIcon, StatCollector} import net.minecraft.world.World -object ItemWirelessTerminalUniversal extends ItemECBase with WirelessTermBase with IWirelessFluidTermHandler with IWirelessGasTermHandler with IWirelessTermHandler with EssensiaTerminal with CraftingTerminal{ +import java.util + +object ItemWirelessTerminalUniversal + extends ItemECBase + with WirelessTermBase + with IWirelessFluidTermHandler + with IWirelessGasTermHandler + with IWirelessTermHandler + with EssensiaTerminal + with CraftingTerminal { val isTeEnabled = Integration.Mods.THAUMATICENERGISTICS.isEnabled val isMekEnabled = Integration.Mods.MEKANISMGAS.isEnabled val isWcEnabled = Integration.Mods.WIRELESSCRAFTING.isEnabled - var icon :IIcon = null + var icon: IIcon = null def THIS = this - if(isWcEnabled){ + if (isWcEnabled) { ECApi.instance.registerWirelessTermHandler(this) AEApi.instance.registries.wireless.registerWirelessHandler(this) - }else{ + } else { ECApi.instance.registerWirelessTermHandler(HandlerUniversalWirelessTerminal) - AEApi.instance.registries.wireless.registerWirelessHandler(HandlerUniversalWirelessTerminal) + AEApi.instance.registries.wireless + .registerWirelessHandler(HandlerUniversalWirelessTerminal) } - - - override def isItemNormalWirelessTermToo(is: ItemStack): Boolean = true override def getConfigManager(itemStack: ItemStack): IConfigManager = { val nbt = ensureTagCompound(itemStack) - if(!nbt.hasKey("settings")) + if (!nbt.hasKey("settings")) nbt.setTag("settings", new NBTTagCompound) val tag = nbt.getCompoundTag("settings") new ConfigManager(tag) @@ -54,166 +62,216 @@ object ItemWirelessTerminalUniversal extends ItemECBase with WirelessTermBase wi } override def getUnlocalizedName(itemStack: ItemStack): String = - super.getUnlocalizedName(itemStack).replace("item.extracells", "extracells.item") - + super + .getUnlocalizedName(itemStack) + .replace("item.extracells", "extracells.item") - override def onItemRightClick(itemStack: ItemStack, world: World, entityPlayer: EntityPlayer): ItemStack = { - if(world.isRemote){ - if(entityPlayer.isSneaking) + override def onItemRightClick( + itemStack: ItemStack, + world: World, + entityPlayer: EntityPlayer + ): ItemStack = { + if (world.isRemote) { + if (entityPlayer.isSneaking) return itemStack val tag = ensureTagCompound(itemStack) - if(!tag.hasKey("type")) + if (!tag.hasKey("type")) tag.setByte("type", 0) - if(tag.getByte("type") == 4 && isWcEnabled) + if (tag.getByte("type") == 4 && isWcEnabled) WirelessCrafting.openCraftingTerminal(entityPlayer) return itemStack } val tag = ensureTagCompound(itemStack) - if(!tag.hasKey("type")) + if (!tag.hasKey("type")) tag.setByte("type", 0) - if(entityPlayer.isSneaking) + if (entityPlayer.isSneaking) return changeMode(itemStack, entityPlayer, tag) val matchted = tag.getByte("type") match { - case 0 => AEApi.instance.registries.wireless.openWirelessTerminalGui(itemStack, world, entityPlayer) - case 1 => ECApi.instance.openWirelessFluidTerminal(entityPlayer, itemStack, world) - case 2 => ECApi.instance.openWirelessGasTerminal(entityPlayer, itemStack, world) - case 3 => if(isTeEnabled) ThaumaticEnergistics.openEssentiaTerminal(entityPlayer, this) + case 0 => + AEApi.instance.registries.wireless + .openWirelessTerminalGui(itemStack, world, entityPlayer) + case 1 => + ECApi.instance.openWirelessFluidTerminal(entityPlayer, itemStack, world) + case 2 => + ECApi.instance.openWirelessGasTerminal(entityPlayer, itemStack, world) + case 3 => + if (isTeEnabled) + ThaumaticEnergistics.openEssentiaTerminal(entityPlayer, this) case _ => } itemStack } - def changeMode(itemStack: ItemStack, player: EntityPlayer, tag :NBTTagCompound): ItemStack = { + def changeMode( + itemStack: ItemStack, + player: EntityPlayer, + tag: NBTTagCompound + ): ItemStack = { val installed = getInstalledModules(itemStack) val matchted = tag.getByte("type") match { case 0 => - if(installed.contains(TerminalType.FLUID)) + if (installed.contains(TerminalType.FLUID)) tag.setByte("type", 1) - else if(isMekEnabled && installed.contains(TerminalType.GAS)) + else if (isMekEnabled && installed.contains(TerminalType.GAS)) tag.setByte("type", 2) - else if(isTeEnabled && installed.contains(TerminalType.ESSENTIA)) + else if (isTeEnabled && installed.contains(TerminalType.ESSENTIA)) tag.setByte("type", 3) - else if(isWcEnabled && installed.contains(TerminalType.CRAFTING)) + else if (isWcEnabled && installed.contains(TerminalType.CRAFTING)) tag.setByte("type", 4) case 1 => - if(isMekEnabled && installed.contains(TerminalType.GAS)) + if (isMekEnabled && installed.contains(TerminalType.GAS)) tag.setByte("type", 2) - else if(isTeEnabled && installed.contains(TerminalType.ESSENTIA)) + else if (isTeEnabled && installed.contains(TerminalType.ESSENTIA)) tag.setByte("type", 3) - else if(isWcEnabled && installed.contains(TerminalType.CRAFTING)) + else if (isWcEnabled && installed.contains(TerminalType.CRAFTING)) tag.setByte("type", 4) - else if(installed.contains(TerminalType.ITEM)) + else if (installed.contains(TerminalType.ITEM)) tag.setByte("type", 0) case 2 => - if(isTeEnabled && installed.contains(TerminalType.ESSENTIA)) + if (isTeEnabled && installed.contains(TerminalType.ESSENTIA)) tag.setByte("type", 3) - else if(isWcEnabled && installed.contains(TerminalType.CRAFTING)) + else if (isWcEnabled && installed.contains(TerminalType.CRAFTING)) tag.setByte("type", 4) - else if(installed.contains(TerminalType.ITEM)) + else if (installed.contains(TerminalType.ITEM)) tag.setByte("type", 0) - else if(installed.contains(TerminalType.FLUID)) + else if (installed.contains(TerminalType.FLUID)) tag.setByte("type", 1) case 3 => - if(isWcEnabled && installed.contains(TerminalType.CRAFTING)) + if (isWcEnabled && installed.contains(TerminalType.CRAFTING)) tag.setByte("type", 4) - else if(installed.contains(TerminalType.ITEM)) + else if (installed.contains(TerminalType.ITEM)) tag.setByte("type", 0) - else if(installed.contains(TerminalType.FLUID)) + else if (installed.contains(TerminalType.FLUID)) tag.setByte("type", 1) - else if(isMekEnabled && installed.contains(TerminalType.GAS)) + else if (isMekEnabled && installed.contains(TerminalType.GAS)) tag.setByte("type", 2) case _ => - if(installed.contains(TerminalType.ITEM)) + if (installed.contains(TerminalType.ITEM)) tag.setByte("type", 0) - else if(installed.contains(TerminalType.FLUID)) + else if (installed.contains(TerminalType.FLUID)) tag.setByte("type", 1) - else if(isMekEnabled && installed.contains(TerminalType.GAS)) + else if (isMekEnabled && installed.contains(TerminalType.GAS)) tag.setByte("type", 2) - else if(isTeEnabled && installed.contains(TerminalType.ESSENTIA)) + else if (isTeEnabled && installed.contains(TerminalType.ESSENTIA)) tag.setByte("type", 3) - else if(isWcEnabled && installed.contains(TerminalType.CRAFTING)) + else if (isWcEnabled && installed.contains(TerminalType.CRAFTING)) tag.setByte("type", 4) else tag.setByte("type", 0) } + player.addChatMessage( + new ChatComponentText( + StatCollector.translateToLocal( + "extracells.tooltip.mode" + ) + ": " + StatCollector.translateToLocal( + "extracells.tooltip." + TerminalType + .values() + .apply(tag.getByte("type")) + .toString + .toLowerCase + ) + ) + ) itemStack } @SideOnly(Side.CLIENT) override def registerIcons(iconRegister: IIconRegister) { - this.icon = iconRegister.registerIcon("extracells:" + "terminal.universal.wireless") + this.icon = + iconRegister.registerIcon("extracells:" + "terminal.universal.wireless") } override def getIconFromDamage(dmg: Int): IIcon = this.icon - @SideOnly(Side.CLIENT) - override def addInformation(itemStack: ItemStack, player: EntityPlayer, list: util.List[_], par4: Boolean) { + override def addInformation( + itemStack: ItemStack, + player: EntityPlayer, + list: util.List[_], + par4: Boolean + ) { val tag = ensureTagCompound(itemStack) - if(!tag.hasKey("type")) + if (!tag.hasKey("type")) tag.setByte("type", 0) val list2 = list.asInstanceOf[util.List[String]]; - list2.add(StatCollector.translateToLocal("extracells.tooltip.mode") + ": " + StatCollector.translateToLocal("extracells.tooltip." + TerminalType.values().apply(tag.getByte("type")).toString.toLowerCase)) + list2.add( + StatCollector.translateToLocal( + "extracells.tooltip.mode" + ) + ": " + StatCollector.translateToLocal( + "extracells.tooltip." + TerminalType + .values() + .apply(tag.getByte("type")) + .toString + .toLowerCase + ) + ) list2.add(StatCollector.translateToLocal("extracells.tooltip.installed")) val it = getInstalledModules(itemStack).iterator while (it.hasNext) - list2.add("- " + StatCollector.translateToLocal("extracells.tooltip." + it.next.name.toLowerCase)) + list2.add( + "- " + StatCollector.translateToLocal( + "extracells.tooltip." + it.next.name.toLowerCase + ) + ) super.addInformation(itemStack, player, list, par4); } - def installModule(itemStack: ItemStack, module: TerminalType): Unit ={ - if(isInstalled(itemStack, module)) + def installModule(itemStack: ItemStack, module: TerminalType): Unit = { + if (isInstalled(itemStack, module)) return val install = (1 << module.ordinal).toByte val tag = ensureTagCompound(itemStack) val installed: Byte = { - if(tag.hasKey("modules")) + if (tag.hasKey("modules")) (tag.getByte("modules") + install).toByte else - install + install } tag.setByte("modules", installed) } - def getInstalledModules(itemStack: ItemStack) :util.EnumSet[TerminalType] = { - if(itemStack == null || itemStack.getItem == null) + def getInstalledModules(itemStack: ItemStack): util.EnumSet[TerminalType] = { + if (itemStack == null || itemStack.getItem == null) return util.EnumSet.noneOf(classOf[TerminalType]) val tag = ensureTagCompound(itemStack) val installed: Byte = { - if(tag.hasKey("modules")) + if (tag.hasKey("modules")) tag.getByte("modules") else 0 } val set = util.EnumSet.noneOf(classOf[TerminalType]) - for(x <- TerminalType.values){ - if(1 == (installed >> x.ordinal) % 2) + for (x <- TerminalType.values) { + if (1 == (installed >> x.ordinal) % 2) set.add(x) } set } - def isInstalled(itemStack: ItemStack, module: TerminalType): Boolean ={ - if(itemStack == null || itemStack.getItem == null) + def isInstalled(itemStack: ItemStack, module: TerminalType): Boolean = { + if (itemStack == null || itemStack.getItem == null) return false val tag = ensureTagCompound(itemStack) val installed: Byte = { - if(tag.hasKey("modules")) + if (tag.hasKey("modules")) tag.getByte("modules") else 0 } - if(1 == (installed >> module.ordinal) % 2) + if (1 == (installed >> module.ordinal) % 2) true else false } - @SuppressWarnings(Array("unchecked", "rawtypes")) - override def getSubItems(item: Item, creativeTab: CreativeTabs, itemList: util.List[_]) { + override def getSubItems( + item: Item, + creativeTab: CreativeTabs, + itemList: util.List[_] + ) { val itemList2 = itemList.asInstanceOf[util.List[ItemStack]] val tag = new NBTTagCompound tag.setByte("modules", 31) diff --git a/src/main/scala/extracells/item/PowerItem.scala b/src/main/scala/extracells/item/PowerItem.scala index b8e739bec..f5a66336c 100644 --- a/src/main/scala/extracells/item/PowerItem.scala +++ b/src/main/scala/extracells/item/PowerItem.scala @@ -7,19 +7,38 @@ import cpw.mods.fml.common.Optional import net.minecraft.item.{Item, ItemStack} import net.minecraft.nbt.NBTTagCompound -@Optional.Interface(iface = "cofh.api.energy.IEnergyContainerItem", modid = "CoFHAPI|energy", striprefs = true) -trait PowerItem extends Item with IAEItemPowerStorage with IEnergyContainerItem{ +@Optional.Interface( + iface = "cofh.api.energy.IEnergyContainerItem", + modid = "CoFHAPI|energy", + striprefs = true +) +trait PowerItem + extends Item + with IAEItemPowerStorage + with IEnergyContainerItem { - val MAX_POWER :Double + val MAX_POWER: Double @Optional.Method(modid = "CoFHAPI|energy") - override def extractEnergy(container: ItemStack, maxExtract: Int, simulate: Boolean): Int = { + override def extractEnergy( + container: ItemStack, + maxExtract: Int, + simulate: Boolean + ): Int = { if (container == null) return 0 if (simulate) { - return if (getEnergyStored(container) >= maxExtract) maxExtract else getEnergyStored(container) - } - else { - return PowerUnits.AE.convertTo(PowerUnits.RF, extractAEPower(container, PowerUnits.RF.convertTo(PowerUnits.AE, maxExtract))).toInt + return if (getEnergyStored(container) >= maxExtract) maxExtract + else getEnergyStored(container) + } else { + return PowerUnits.AE + .convertTo( + PowerUnits.RF, + extractAEPower( + container, + PowerUnits.RF.convertTo(PowerUnits.AE, maxExtract) + ) + ) + .toInt } } @@ -34,20 +53,32 @@ trait PowerItem extends Item with IAEItemPowerStorage with IEnergyContainerItem{ } @Optional.Method(modid = "CoFHAPI|energy") - override def receiveEnergy(container: ItemStack, maxReceive: Int, simulate: Boolean): Int = { + override def receiveEnergy( + container: ItemStack, + maxReceive: Int, + simulate: Boolean + ): Int = { if (container == null) return 0 if (simulate) { - val current: Double = PowerUnits.AE.convertTo(PowerUnits.RF, getAECurrentPower(container)) - val max: Double = PowerUnits.AE.convertTo(PowerUnits.RF, getAEMaxPower(container)) + val current: Double = + PowerUnits.AE.convertTo(PowerUnits.RF, getAECurrentPower(container)) + val max: Double = + PowerUnits.AE.convertTo(PowerUnits.RF, getAEMaxPower(container)) if (max - current >= maxReceive) maxReceive else (max - current).toInt - } - else { + } else { val currentAEPower = getAECurrentPower(container) - if ( currentAEPower < getAEMaxPower(container)){ - val leftOver = PowerUnits.AE.convertTo(PowerUnits.RF, injectAEPower(container, PowerUnits.RF.convertTo(PowerUnits.AE, maxReceive))) - (maxReceive - leftOver).toInt - }else + if (currentAEPower < getAEMaxPower(container)) { + PowerUnits.AE + .convertTo( + PowerUnits.RF, + injectAEPower( + container, + PowerUnits.RF.convertTo(PowerUnits.AE, maxReceive) + ) + ) + .toInt + } else 0 } } diff --git a/src/main/scala/extracells/item/WirelessTermBase.scala b/src/main/scala/extracells/item/WirelessTermBase.scala index c62570693..ccc5bc8b5 100644 --- a/src/main/scala/extracells/item/WirelessTermBase.scala +++ b/src/main/scala/extracells/item/WirelessTermBase.scala @@ -10,8 +10,7 @@ import net.minecraft.item.{Item, ItemStack} import net.minecraft.nbt.NBTTagCompound import net.minecraft.util.StatCollector - -trait WirelessTermBase extends PowerItem{ +trait WirelessTermBase extends PowerItem { setMaxStackSize(1) override val MAX_POWER: Double = 1600000 @@ -20,7 +19,6 @@ trait WirelessTermBase extends PowerItem{ return AccessRestriction.READ_WRITE } - override def getDurabilityForDisplay(itemStack: ItemStack): Double = { return 1 - getAECurrentPower(itemStack) / MAX_POWER } @@ -51,7 +49,11 @@ trait WirelessTermBase extends PowerItem{ } @SuppressWarnings(Array("unchecked", "rawtypes")) - override def getSubItems(item: Item, creativeTab: CreativeTabs, itemList: util.List[_]) { + override def getSubItems( + item: Item, + creativeTab: CreativeTabs, + itemList: util.List[_] + ) { val itemList2 = itemList.asInstanceOf[util.List[ItemStack]] itemList2.add(new ItemStack(item)) val itemStack: ItemStack = new ItemStack(item) @@ -65,12 +67,29 @@ trait WirelessTermBase extends PowerItem{ @SuppressWarnings(Array("rawtypes", "unchecked")) @SideOnly(Side.CLIENT) - override def addInformation(itemStack: ItemStack, player: EntityPlayer, list: util.List[_], par4: Boolean) { + override def addInformation( + itemStack: ItemStack, + player: EntityPlayer, + list: util.List[_], + par4: Boolean + ) { val list2 = list.asInstanceOf[util.List[String]]; if (!itemStack.hasTagCompound) itemStack.setTagCompound(new NBTTagCompound) val encryptionKey: String = itemStack.getTagCompound.getString("key") val aeCurrentPower: Double = getAECurrentPower(itemStack) - list2.add(StatCollector.translateToLocal("gui.appliedenergistics2.StoredEnergy") + ": " + aeCurrentPower + " AE - " + Math.floor(aeCurrentPower / this.MAX_POWER * 1e4) / 1e2 + "%") - list2.add(StatCollector.translateToLocal(if (encryptionKey != null && !encryptionKey.isEmpty) "gui.appliedenergistics2.Linked" else "gui.appliedenergistics2.Unlinked")) + list2.add( + StatCollector.translateToLocal( + "gui.appliedenergistics2.StoredEnergy" + ) + ": " + aeCurrentPower + " AE - " + Math.floor( + aeCurrentPower / this.MAX_POWER * 1e4 + ) / 1e2 + "%" + ) + list2.add( + StatCollector.translateToLocal( + if (encryptionKey != null && !encryptionKey.isEmpty) + "gui.appliedenergistics2.Linked" + else "gui.appliedenergistics2.Unlinked" + ) + ) } } diff --git a/src/main/scala/extracells/network/AbstractPacket.java b/src/main/scala/extracells/network/AbstractPacket.java index de16ea786..76ae3ef34 100644 --- a/src/main/scala/extracells/network/AbstractPacket.java +++ b/src/main/scala/extracells/network/AbstractPacket.java @@ -1,14 +1,5 @@ package extracells.network; -import appeng.api.parts.IPartHost; -import com.google.common.base.Charsets; -import cpw.mods.fml.common.FMLCommonHandler; -import cpw.mods.fml.common.network.NetworkRegistry; -import cpw.mods.fml.common.network.simpleimpl.IMessage; -import cpw.mods.fml.relauncher.Side; -import cpw.mods.fml.relauncher.SideOnly; -import extracells.part.PartECBase; -import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; @@ -18,136 +9,145 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; +import com.google.common.base.Charsets; + +import appeng.api.parts.IPartHost; +import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.network.NetworkRegistry; +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.relauncher.Side; +import cpw.mods.fml.relauncher.SideOnly; +import extracells.part.PartECBase; +import io.netty.buffer.ByteBuf; + public abstract class AbstractPacket implements IMessage { - @SideOnly(Side.CLIENT) - public static World getClientWorld() { - return net.minecraft.client.Minecraft.getMinecraft().theWorld; - } - - public static Fluid readFluid(ByteBuf in) { - return FluidRegistry.getFluid(readString(in)); - } - - public static PartECBase readPart(ByteBuf in) { - return (PartECBase) ((IPartHost) readTileEntity(in)) - .getPart(ForgeDirection.getOrientation(in.readByte())); - } - - public static EntityPlayer readPlayer(ByteBuf in) { - if (!in.readBoolean()) { - return null; - } - World playerWorld = readWorld(in); - return playerWorld.getPlayerEntityByName(readString(in)); - } - - public static String readString(ByteBuf in) { - byte[] stringBytes = new byte[in.readInt()]; - in.readBytes(stringBytes); - return new String(stringBytes, Charsets.UTF_8); - } - - public static TileEntity readTileEntity(ByteBuf in) { - return readWorld(in).getTileEntity(in.readInt(), in.readInt(), - in.readInt()); - } - - public static World readWorld(ByteBuf in) { - WorldServer world = DimensionManager.getWorld(in.readInt()); - if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { - return world != null ? world : getClientWorld(); - } - return world; - } - - public static void writeFluid(Fluid fluid, ByteBuf out) { - if (fluid == null) { - writeString("", out); - return; - } - writeString(fluid.getName(), out); - } - - public static void writePart(PartECBase part, ByteBuf out) { - writeTileEntity(part.getHost().getTile(), out); - out.writeByte(part.getSide().ordinal()); - } - - public static void writePlayer(EntityPlayer player, ByteBuf out) { - if (player == null) { - out.writeBoolean(false); - return; - } - out.writeBoolean(true); - writeWorld(player.worldObj, out); - writeString(player.getCommandSenderName(), out); - } - - public static void writeString(String string, ByteBuf out) { - byte[] stringBytes; - stringBytes = string.getBytes(Charsets.UTF_8); - out.writeInt(stringBytes.length); - out.writeBytes(stringBytes); - } - - public static void writeTileEntity(TileEntity tileEntity, ByteBuf out) { - writeWorld(tileEntity.getWorldObj(), out); - out.writeInt(tileEntity.xCoord); - out.writeInt(tileEntity.yCoord); - out.writeInt(tileEntity.zCoord); - } - - public static void writeWorld(World world, ByteBuf out) { - out.writeInt(world.provider.dimensionId); - } - - protected EntityPlayer player; - - protected byte mode; - - @SuppressWarnings("unused") - public AbstractPacket() { - this.player = null; - } - - public AbstractPacket(EntityPlayer _player) { - this.player = _player; - } - - public abstract void execute(); - - @Override - public void fromBytes(ByteBuf in) { - this.mode = in.readByte(); - this.player = readPlayer(in); - readData(in); - } - - public abstract void readData(ByteBuf in); - - public void sendPacketToAllPlayers() { - ChannelHandler.sendPacketToAllPlayers(this); - } - - public void sendPacketToPlayer(EntityPlayer player) { - ChannelHandler.sendPacketToPlayer(this, player); - } - - public void sendPacketToPlayersAround(NetworkRegistry.TargetPoint point) { - ChannelHandler.sendPacketToPlayersAround(this, point); - } - - public void sendPacketToServer() { - ChannelHandler.sendPacketToServer(this); - } - - @Override - public void toBytes(ByteBuf out) { - out.writeByte(this.mode); - writePlayer(this.player, out); - writeData(out); - } - - public abstract void writeData(ByteBuf out); + @SideOnly(Side.CLIENT) + public static World getClientWorld() { + return net.minecraft.client.Minecraft.getMinecraft().theWorld; + } + + public static Fluid readFluid(ByteBuf in) { + return FluidRegistry.getFluid(readString(in)); + } + + public static PartECBase readPart(ByteBuf in) { + return (PartECBase) ((IPartHost) readTileEntity(in)).getPart(ForgeDirection.getOrientation(in.readByte())); + } + + public static EntityPlayer readPlayer(ByteBuf in) { + if (!in.readBoolean()) { + return null; + } + World playerWorld = readWorld(in); + return playerWorld.getPlayerEntityByName(readString(in)); + } + + public static String readString(ByteBuf in) { + byte[] stringBytes = new byte[in.readInt()]; + in.readBytes(stringBytes); + return new String(stringBytes, Charsets.UTF_8); + } + + public static TileEntity readTileEntity(ByteBuf in) { + return readWorld(in).getTileEntity(in.readInt(), in.readInt(), in.readInt()); + } + + public static World readWorld(ByteBuf in) { + WorldServer world = DimensionManager.getWorld(in.readInt()); + if (FMLCommonHandler.instance().getSide() == Side.CLIENT) { + return world != null ? world : getClientWorld(); + } + return world; + } + + public static void writeFluid(Fluid fluid, ByteBuf out) { + if (fluid == null) { + writeString("", out); + return; + } + writeString(fluid.getName(), out); + } + + public static void writePart(PartECBase part, ByteBuf out) { + writeTileEntity(part.getHost().getTile(), out); + out.writeByte(part.getSide().ordinal()); + } + + public static void writePlayer(EntityPlayer player, ByteBuf out) { + if (player == null) { + out.writeBoolean(false); + return; + } + out.writeBoolean(true); + writeWorld(player.worldObj, out); + writeString(player.getCommandSenderName(), out); + } + + public static void writeString(String string, ByteBuf out) { + byte[] stringBytes; + stringBytes = string.getBytes(Charsets.UTF_8); + out.writeInt(stringBytes.length); + out.writeBytes(stringBytes); + } + + public static void writeTileEntity(TileEntity tileEntity, ByteBuf out) { + writeWorld(tileEntity.getWorldObj(), out); + out.writeInt(tileEntity.xCoord); + out.writeInt(tileEntity.yCoord); + out.writeInt(tileEntity.zCoord); + } + + public static void writeWorld(World world, ByteBuf out) { + out.writeInt(world.provider.dimensionId); + } + + protected EntityPlayer player; + + protected byte mode; + + @SuppressWarnings("unused") + public AbstractPacket() { + this.player = null; + } + + public AbstractPacket(EntityPlayer _player) { + this.player = _player; + } + + public abstract void execute(); + + @Override + public void fromBytes(ByteBuf in) { + this.mode = in.readByte(); + this.player = readPlayer(in); + readData(in); + } + + public abstract void readData(ByteBuf in); + + public void sendPacketToAllPlayers() { + ChannelHandler.sendPacketToAllPlayers(this); + } + + public void sendPacketToPlayer(EntityPlayer player) { + ChannelHandler.sendPacketToPlayer(this, player); + } + + public void sendPacketToPlayersAround(NetworkRegistry.TargetPoint point) { + ChannelHandler.sendPacketToPlayersAround(this, point); + } + + public void sendPacketToServer() { + ChannelHandler.sendPacketToServer(this); + } + + @Override + public void toBytes(ByteBuf out) { + out.writeByte(this.mode); + writePlayer(this.player, out); + writeData(out); + } + + public abstract void writeData(ByteBuf out); } diff --git a/src/main/scala/extracells/network/ChannelHandler.java b/src/main/scala/extracells/network/ChannelHandler.java index 533f601aa..d7a3a7484 100644 --- a/src/main/scala/extracells/network/ChannelHandler.java +++ b/src/main/scala/extracells/network/ChannelHandler.java @@ -1,106 +1,87 @@ package extracells.network; +import java.util.EnumMap; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.network.Packet; +import net.minecraft.world.World; + import cpw.mods.fml.common.network.FMLEmbeddedChannel; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; import extracells.network.handler.other.HandlerFluidContainerSlot; import extracells.network.handler.other.HandlerFluidSlot; +import extracells.network.handler.other.HandlerGuiSwitch; import extracells.network.handler.part.*; import extracells.network.packet.other.PacketFluidContainerSlot; import extracells.network.packet.other.PacketFluidSlot; +import extracells.network.packet.other.PacketGuiSwitch; import extracells.network.packet.part.*; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.entity.player.EntityPlayerMP; -import net.minecraft.network.Packet; -import net.minecraft.world.World; - -import java.util.EnumMap; public class ChannelHandler { - public static void registerMessages() { - wrapper.registerMessage(HandlerFluidSlot.class, PacketFluidSlot.class, - 0, Side.CLIENT); - wrapper.registerMessage(HandlerFluidSlot.class, PacketFluidSlot.class, - 0, Side.SERVER); - - wrapper.registerMessage(HandlerBusFluidIO.class, - PacketBusFluidIO.class, 1, Side.CLIENT); - wrapper.registerMessage(HandlerBusFluidIO.class, - PacketBusFluidIO.class, 1, Side.SERVER); - - wrapper.registerMessage(HandlerBusFluidStorage.class, - PacketBusFluidStorage.class, 2, Side.CLIENT); - wrapper.registerMessage(HandlerBusFluidStorage.class, - PacketBusFluidStorage.class, 2, Side.SERVER); - - wrapper.registerMessage(HandlerFluidEmitter.class, - PacketFluidEmitter.class, 3, Side.CLIENT); - wrapper.registerMessage(HandlerFluidEmitter.class, - PacketFluidEmitter.class, 3, Side.SERVER); - - wrapper.registerMessage(HandlerFluidPlaneFormation.class, - PacketFluidPlaneFormation.class, 4, Side.CLIENT); - wrapper.registerMessage(HandlerFluidPlaneFormation.class, - PacketFluidPlaneFormation.class, 4, Side.SERVER); - - wrapper.registerMessage(HandlerFluidStorage.class, - PacketFluidStorage.class, 5, Side.CLIENT); - wrapper.registerMessage(HandlerFluidStorage.class, - PacketFluidStorage.class, 5, Side.SERVER); - - wrapper.registerMessage(HandlerFluidTerminal.class, - PacketFluidTerminal.class, 6, Side.CLIENT); - wrapper.registerMessage(HandlerFluidTerminal.class, - PacketFluidTerminal.class, 6, Side.SERVER); - - wrapper.registerMessage(HandlerFluidInterface.class, - PacketFluidInterface.class, 7, Side.CLIENT); - wrapper.registerMessage(HandlerFluidInterface.class, - PacketFluidInterface.class, 7, Side.SERVER); - - wrapper.registerMessage(HandlerFluidContainerSlot.class, - PacketFluidContainerSlot.class, 8, Side.CLIENT); - wrapper.registerMessage(HandlerFluidContainerSlot.class, - PacketFluidContainerSlot.class, 8, Side.SERVER); - - wrapper.registerMessage(HandlerOreDictExport.class, - PacketOreDictExport.class, 9, Side.CLIENT); - wrapper.registerMessage(HandlerOreDictExport.class, - PacketOreDictExport.class, 9, Side.SERVER); - - } - - public static void sendPacketToAllPlayers(AbstractPacket packet) { - wrapper.sendToAll(packet); - } - - public static void sendPacketToAllPlayers(Packet packet, World world) { - for (Object player : world.playerEntities) { - if (player instanceof EntityPlayerMP) { - ((EntityPlayerMP) player).playerNetServerHandler - .sendPacket(packet); - } - } - } - - public static void sendPacketToPlayer(AbstractPacket packet, - EntityPlayer player) { - wrapper.sendTo(packet, (EntityPlayerMP) player); - } - - public static void sendPacketToPlayersAround(AbstractPacket abstractPacket, - NetworkRegistry.TargetPoint point) { - wrapper.sendToAllAround(abstractPacket, point); - } - - public static void sendPacketToServer(AbstractPacket packet) { - wrapper.sendToServer(packet); - } - - private static EnumMap channels; - - public static SimpleNetworkWrapper wrapper = NetworkRegistry.INSTANCE - .newSimpleChannel("extracells"); + public static void registerMessages() { + wrapper.registerMessage(HandlerFluidSlot.class, PacketFluidSlot.class, 0, Side.CLIENT); + wrapper.registerMessage(HandlerFluidSlot.class, PacketFluidSlot.class, 0, Side.SERVER); + + wrapper.registerMessage(HandlerBusFluidIO.class, PacketBusFluidIO.class, 1, Side.CLIENT); + wrapper.registerMessage(HandlerBusFluidIO.class, PacketBusFluidIO.class, 1, Side.SERVER); + + wrapper.registerMessage(HandlerBusFluidStorage.class, PacketBusFluidStorage.class, 2, Side.CLIENT); + wrapper.registerMessage(HandlerBusFluidStorage.class, PacketBusFluidStorage.class, 2, Side.SERVER); + + wrapper.registerMessage(HandlerFluidEmitter.class, PacketFluidEmitter.class, 3, Side.CLIENT); + wrapper.registerMessage(HandlerFluidEmitter.class, PacketFluidEmitter.class, 3, Side.SERVER); + + wrapper.registerMessage(HandlerFluidPlaneFormation.class, PacketFluidPlaneFormation.class, 4, Side.CLIENT); + wrapper.registerMessage(HandlerFluidPlaneFormation.class, PacketFluidPlaneFormation.class, 4, Side.SERVER); + + wrapper.registerMessage(HandlerFluidStorage.class, PacketFluidStorage.class, 5, Side.CLIENT); + wrapper.registerMessage(HandlerFluidStorage.class, PacketFluidStorage.class, 5, Side.SERVER); + + wrapper.registerMessage(HandlerFluidTerminal.class, PacketFluidTerminal.class, 6, Side.CLIENT); + wrapper.registerMessage(HandlerFluidTerminal.class, PacketFluidTerminal.class, 6, Side.SERVER); + + wrapper.registerMessage(HandlerFluidInterface.class, PacketFluidInterface.class, 7, Side.CLIENT); + wrapper.registerMessage(HandlerFluidInterface.class, PacketFluidInterface.class, 7, Side.SERVER); + + wrapper.registerMessage(HandlerFluidContainerSlot.class, PacketFluidContainerSlot.class, 8, Side.CLIENT); + wrapper.registerMessage(HandlerFluidContainerSlot.class, PacketFluidContainerSlot.class, 8, Side.SERVER); + + wrapper.registerMessage(HandlerOreDictExport.class, PacketOreDictExport.class, 9, Side.CLIENT); + wrapper.registerMessage(HandlerOreDictExport.class, PacketOreDictExport.class, 9, Side.SERVER); + + wrapper.registerMessage(HandlerGuiSwitch.class, PacketGuiSwitch.class, 10, Side.CLIENT); + wrapper.registerMessage(HandlerGuiSwitch.class, PacketGuiSwitch.class, 10, Side.SERVER); + } + + public static void sendPacketToAllPlayers(AbstractPacket packet) { + wrapper.sendToAll(packet); + } + + public static void sendPacketToAllPlayers(Packet packet, World world) { + for (Object player : world.playerEntities) { + if (player instanceof EntityPlayerMP) { + ((EntityPlayerMP) player).playerNetServerHandler.sendPacket(packet); + } + } + } + + public static void sendPacketToPlayer(AbstractPacket packet, EntityPlayer player) { + wrapper.sendTo(packet, (EntityPlayerMP) player); + } + + public static void sendPacketToPlayersAround(AbstractPacket abstractPacket, NetworkRegistry.TargetPoint point) { + wrapper.sendToAllAround(abstractPacket, point); + } + + public static void sendPacketToServer(AbstractPacket packet) { + wrapper.sendToServer(packet); + } + + private static EnumMap channels; + + public static SimpleNetworkWrapper wrapper = NetworkRegistry.INSTANCE.newSimpleChannel("extracells"); } diff --git a/src/main/scala/extracells/network/GuiHandler.scala b/src/main/scala/extracells/network/GuiHandler.scala index 62b0caedd..e4cfd0060 100644 --- a/src/main/scala/extracells/network/GuiHandler.scala +++ b/src/main/scala/extracells/network/GuiHandler.scala @@ -3,6 +3,8 @@ package extracells.network import appeng.api.parts.IPartHost import appeng.api.storage.IMEMonitor import appeng.api.storage.data.IAEFluidStack +import appeng.container.implementations.ContainerPriority +import appeng.helpers.IPriorityHost import cpw.mods.fml.common.network.IGuiHandler import cpw.mods.fml.relauncher.{Side, SideOnly} import extracells.Extracells @@ -11,162 +13,277 @@ import extracells.block.TGuiBlock import extracells.container._ import extracells.gui._ import extracells.part.PartECBase -import extracells.registries.BlockEnum -import extracells.tileentity.{TileEntityFluidCrafter, TileEntityFluidFiller, TileEntityFluidInterface} +import extracells.registries.{BlockEnum, PartEnum} +import extracells.tileentity.{ + TileEntityFluidCrafter, + TileEntityFluidFiller, + TileEntityFluidInterface +} import net.minecraft.entity.player.EntityPlayer import net.minecraft.world.World import net.minecraftforge.common.util.ForgeDirection; object GuiHandler extends IGuiHandler { - def getContainer(ID: Int, player: EntityPlayer, args: Array[Any]) : Any = { - ID match { - case 0 => - val fluidInventory = args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] - new ContainerFluidStorage(fluidInventory, player) - case 1 => - val fluidInventory2 = args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] - val handler = args.apply(1).asInstanceOf[IWirelessFluidTermHandler] - new ContainerFluidStorage(fluidInventory2, player, handler) - case 3 => - val fluidInventory3 = args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] - val storageCell = args.apply(1).asInstanceOf[IPortableFluidStorageCell] - new ContainerFluidStorage(fluidInventory3, player, storageCell) - case 4 => - val fluidInventory = args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] - new ContainerGasStorage(fluidInventory, player) - case 5 => - val fluidInventory2 = args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] - val handler = args.apply(1).asInstanceOf[IWirelessGasTermHandler] - new ContainerGasStorage(fluidInventory2, player, handler) - case 6 => - val fluidInventory3 = args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] - val storageCell = args.apply(1).asInstanceOf[IPortableGasStorageCell] - new ContainerGasStorage(fluidInventory3, player, storageCell) - case _ => - null - } - } - - @SideOnly(Side.CLIENT) - def getGui(ID: Int, player: EntityPlayer) : Any = { - ID match { - case 0 => - new GuiFluidStorage(player, "extracells.part.fluid.terminal.name"); - case 1 => - new GuiFluidStorage(player, "extracells.part.fluid.terminal.name"); - case 3 => - new GuiFluidStorage(player, "extracells.item.storage.fluid.portable.name"); - case 4 => - new GuiGasStorage(player, "extracells.part.gas.terminal.name"); - case 5 => - new GuiGasStorage(player, "extracells.part.gas.terminal.name"); - case 6 => - new GuiGasStorage(player, "extracells.item.storage.gas.portable.name"); - case _ => - null; - } - } - - def getGuiId(guiId: Int) = guiId + 6 + def getContainer(ID: Int, player: EntityPlayer, args: Array[Any]): Any = { + ID match { + case 0 => + val fluidInventory = + args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] + new ContainerFluidStorage(fluidInventory, player) + case 1 => + val fluidInventory2 = + args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] + val handler = args.apply(1).asInstanceOf[IWirelessFluidTermHandler] + new ContainerFluidStorage(fluidInventory2, player, handler) + case 3 => + val fluidInventory3 = + args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] + val storageCell = args.apply(1).asInstanceOf[IPortableFluidStorageCell] + new ContainerFluidStorage(fluidInventory3, player, storageCell) + case 4 => + val fluidInventory = + args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] + new ContainerGasStorage(fluidInventory, player) + case 5 => + val fluidInventory2 = + args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] + val handler = args.apply(1).asInstanceOf[IWirelessGasTermHandler] + new ContainerGasStorage(fluidInventory2, player, handler) + case 6 => + val fluidInventory3 = + args.apply(0).asInstanceOf[IMEMonitor[IAEFluidStack]] + val storageCell = args.apply(1).asInstanceOf[IPortableGasStorageCell] + new ContainerGasStorage(fluidInventory3, player, storageCell) + case _ => + null + } + } - def getGuiId(part: PartECBase) = part.getSide().ordinal() + @SideOnly(Side.CLIENT) + def getGui(ID: Int, player: EntityPlayer): Any = { + ID match { + case 0 => + new GuiFluidStorage(player, "extracells.part.fluid.terminal.name"); + case 1 => + new GuiFluidStorage(player, "extracells.part.fluid.terminal.name"); + case 3 => + new GuiFluidStorage( + player, + "extracells.item.storage.fluid.portable.name" + ); + case 4 => + new GuiGasStorage(player, "extracells.part.gas.terminal.name"); + case 5 => + new GuiGasStorage(player, "extracells.part.gas.terminal.name"); + case 6 => + new GuiGasStorage(player, "extracells.item.storage.gas.portable.name"); + case _ => + null; + } + } - def getPartContainer(side: ForgeDirection, player: EntityPlayer, world: World, x: Int, y: Int, z: Int) : Any = - world.getTileEntity(x, y, z).asInstanceOf[IPartHost].getPart(side).asInstanceOf[PartECBase] - .getServerGuiElement(player) + def getGuiId(guiId: Int) = guiId + 6 + def getGuiId(part: PartECBase) = part.getSide().ordinal() - def getPartGui(side: ForgeDirection, player: EntityPlayer, world: World, x: Int, y: Int, z: Int) : Any = - world.getTileEntity(x, y, z).asInstanceOf[IPartHost].getPart(side).asInstanceOf[PartECBase] - .getClientGuiElement(player) + def getPartContainer( + side: ForgeDirection, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = + world + .getTileEntity(x, y, z) + .asInstanceOf[IPartHost] + .getPart(side) + .asInstanceOf[PartECBase] + .getServerGuiElement(player) - def launchGui(ID: Int, player: EntityPlayer, args: Array[Any]) { - temp = args - player.openGui(Extracells, ID, null, 0, 0, 0); - } + def getPartGui( + side: ForgeDirection, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = + world + .getTileEntity(x, y, z) + .asInstanceOf[IPartHost] + .getPart(side) + .asInstanceOf[PartECBase] + .getClientGuiElement(player) - def launchGui(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z:Int) : Any = - player.openGui(Extracells, ID, world, x, y, z); + def launchGui(ID: Int, player: EntityPlayer, args: Array[Any]) { + temp = args + player.openGui(Extracells, ID, null, 0, 0, 0); + } + def launchGui( + ID: Int, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = + player.openGui(Extracells, ID, world, x, y, z); - var temp: Array[Any] = Array[Any]() + var temp: Array[Any] = Array[Any]() - override def getClientGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int) : AnyRef = { - val gui: Any = getGuiBlockElement(player, world, x, y, z) - if (gui != null) - return gui.asInstanceOf[AnyRef] - val side = ForgeDirection.getOrientation(ID); - if (world.getBlock(x, y, z) == BlockEnum.FLUIDCRAFTER.getBlock()) { - val tileEntity = world.getTileEntity(x, y, z); - if (tileEntity == null || !(tileEntity.isInstanceOf[TileEntityFluidCrafter])) - return null - return new GuiFluidCrafter(player.inventory, tileEntity.asInstanceOf[TileEntityFluidCrafter].getInventory()) - } - if (world != null - && world.getBlock(x, y, z) == BlockEnum.ECBASEBLOCK.getBlock()) { - val tileEntity = world.getTileEntity(x, y, z) - if (tileEntity == null) - return null - if (tileEntity.isInstanceOf[TileEntityFluidInterface]) - return new GuiFluidInterface(player,tileEntity.asInstanceOf[IFluidInterface]) - else if (tileEntity.isInstanceOf[TileEntityFluidFiller]) - return new GuiFluidFiller(player, tileEntity.asInstanceOf[TileEntityFluidFiller]) - return null; - } - if (world != null && side != ForgeDirection.UNKNOWN) - return getPartGui(side, player, world, x, y, z).asInstanceOf[AnyRef] - getGui(ID - 6, player).asInstanceOf[AnyRef] - } + override def getClientGuiElement( + ID: Int, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): AnyRef = { + val gui: Any = getGuiBlockElement(player, world, x, y, z) + if (gui != null) + return gui.asInstanceOf[AnyRef] + var side = ForgeDirection.getOrientation(ID) + if (world.getBlock(x, y, z) == BlockEnum.FLUIDCRAFTER.getBlock()) { + val tileEntity = world.getTileEntity(x, y, z); + if ( + tileEntity == null || !(tileEntity.isInstanceOf[TileEntityFluidCrafter]) + ) + return null + return new GuiFluidCrafter( + player.inventory, + tileEntity.asInstanceOf[TileEntityFluidCrafter].getInventory() + ) + } + if ( + world != null + && world.getBlock(x, y, z) == BlockEnum.ECBASEBLOCK.getBlock() + ) { + val tileEntity = world.getTileEntity(x, y, z) + if (tileEntity == null) + return null + if (tileEntity.isInstanceOf[TileEntityFluidInterface]) + return new GuiFluidInterface( + player, + tileEntity.asInstanceOf[IFluidInterface] + ) + else if (tileEntity.isInstanceOf[TileEntityFluidFiller]) + return new GuiFluidFiller( + player, + tileEntity.asInstanceOf[TileEntityFluidFiller] + ) + return null; + } + if (ID >= 100) { + side = ForgeDirection.getOrientation(ID % 100) + val part = world + .getTileEntity(x, y, z) + .asInstanceOf[IPartHost] + .getPart(side) + .asInstanceOf[IPriorityHost] + return new GuiECPriority(player.inventory, part) + } + if (world != null && side != ForgeDirection.UNKNOWN) + return getPartGui(side, player, world, x, y, z).asInstanceOf[AnyRef] + getGui(ID - 6, player).asInstanceOf[AnyRef] + } - override def getServerGuiElement(ID: Int, player: EntityPlayer, world: World, x: Int, y: Int, z: Int) : AnyRef = { - val con: Any = getContainerBlockElement(player, world, x, y, z) - if (con != null) - return con.asInstanceOf[AnyRef] - val side = ForgeDirection.getOrientation(ID) - if (world != null && world.getBlock(x, y, z) == BlockEnum.FLUIDCRAFTER.getBlock()) { - val tileEntity = world.getTileEntity(x, y, z) - if (tileEntity == null || !(tileEntity.isInstanceOf[TileEntityFluidCrafter])) - return null - return new ContainerFluidCrafter(player.inventory, - tileEntity.asInstanceOf[TileEntityFluidCrafter].getInventory()) - } - if (world != null && world.getBlock(x, y, z) == BlockEnum.ECBASEBLOCK.getBlock()) { - val tileEntity = world.getTileEntity(x, y, z) - if (tileEntity == null) - return null - if (tileEntity.isInstanceOf[TileEntityFluidInterface]) - return new ContainerFluidInterface(player, tileEntity.asInstanceOf[IFluidInterface]); - else if (tileEntity.isInstanceOf[TileEntityFluidFiller]) - return new ContainerFluidFiller(player.inventory, tileEntity.asInstanceOf[TileEntityFluidFiller]) - return null - } - if (world != null && side != ForgeDirection.UNKNOWN) - return getPartContainer(side, player, world, x, y, z).asInstanceOf[AnyRef] - getContainer(ID - 6, player, temp).asInstanceOf[AnyRef] - } + override def getServerGuiElement( + ID: Int, + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): AnyRef = { + val con: Any = getContainerBlockElement(player, world, x, y, z) + if (con != null) + return con.asInstanceOf[AnyRef] + var side = ForgeDirection.getOrientation(ID) + if ( + world != null && world.getBlock(x, y, z) == BlockEnum.FLUIDCRAFTER + .getBlock() + ) { + val tileEntity = world.getTileEntity(x, y, z) + if ( + tileEntity == null || !(tileEntity.isInstanceOf[TileEntityFluidCrafter]) + ) + return null + return new ContainerFluidCrafter( + player.inventory, + tileEntity.asInstanceOf[TileEntityFluidCrafter].getInventory() + ) + } + if ( + world != null && world.getBlock(x, y, z) == BlockEnum.ECBASEBLOCK + .getBlock() + ) { + val tileEntity = world.getTileEntity(x, y, z) + if (tileEntity == null) + return null + if (tileEntity.isInstanceOf[TileEntityFluidInterface]) + return new ContainerFluidInterface( + player, + tileEntity.asInstanceOf[IFluidInterface] + ); + else if (tileEntity.isInstanceOf[TileEntityFluidFiller]) + return new ContainerFluidFiller( + player.inventory, + tileEntity.asInstanceOf[TileEntityFluidFiller] + ) + return null + } + if (ID >= 100) { + side = ForgeDirection.getOrientation(ID % 100) + val part = world + .getTileEntity(x, y, z) + .asInstanceOf[IPartHost] + .getPart(side) + .asInstanceOf[IPriorityHost] + return new ContainerPriority(player.inventory, part) + } + if (world != null && side != ForgeDirection.UNKNOWN) + return getPartContainer(side, player, world, x, y, z).asInstanceOf[AnyRef] + getContainer(ID - 6, player, temp).asInstanceOf[AnyRef] + } - def getGuiBlockElement(player: EntityPlayer, world: World, x:Int, y: Int, z: Int): Any = { - if(world == null || player == null) - return null - val block = world.getBlock(x, y, z) - if (block == null) - return null - block match{ - case guiBlock: TGuiBlock => return guiBlock.getClientGuiElement(player, world, x, y, z) - case _ => return null - } - } + def getGuiBlockElement( + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = { + if (world == null || player == null) + return null + val block = world.getBlock(x, y, z) + if (block == null) + return null + block match { + case guiBlock: TGuiBlock => + return guiBlock.getClientGuiElement(player, world, x, y, z) + case _ => return null + } + } - def getContainerBlockElement(player: EntityPlayer, world: World, x:Int, y: Int, z: Int): Any = { - if(world == null || player == null) - return null - val block = world.getBlock(x, y, z) - if (block == null) - return null - block match{ - case guiBlock: TGuiBlock => return guiBlock.getServerGuiElement(player, world, x, y, z) - case _ => return null - } - } + def getContainerBlockElement( + player: EntityPlayer, + world: World, + x: Int, + y: Int, + z: Int + ): Any = { + if (world == null || player == null) + return null + val block = world.getBlock(x, y, z) + if (block == null) + return null + block match { + case guiBlock: TGuiBlock => + return guiBlock.getServerGuiElement(player, world, x, y, z) + case _ => return null + } + } } diff --git a/src/main/scala/extracells/network/handler/other/HandlerFluidContainerSlot.java b/src/main/scala/extracells/network/handler/other/HandlerFluidContainerSlot.java index 9779442d4..39c706174 100644 --- a/src/main/scala/extracells/network/handler/other/HandlerFluidContainerSlot.java +++ b/src/main/scala/extracells/network/handler/other/HandlerFluidContainerSlot.java @@ -5,13 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.other.PacketFluidContainerSlot; -public class HandlerFluidContainerSlot implements - IMessageHandler { +public class HandlerFluidContainerSlot implements IMessageHandler { - @Override - public IMessage onMessage(PacketFluidContainerSlot message, - MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketFluidContainerSlot message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/other/HandlerFluidSlot.java b/src/main/scala/extracells/network/handler/other/HandlerFluidSlot.java index 930b78710..c980f46e1 100644 --- a/src/main/scala/extracells/network/handler/other/HandlerFluidSlot.java +++ b/src/main/scala/extracells/network/handler/other/HandlerFluidSlot.java @@ -5,12 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.other.PacketFluidSlot; -public class HandlerFluidSlot implements - IMessageHandler { +public class HandlerFluidSlot implements IMessageHandler { - @Override - public IMessage onMessage(PacketFluidSlot message, MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketFluidSlot message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/other/HandlerGuiSwitch.java b/src/main/scala/extracells/network/handler/other/HandlerGuiSwitch.java new file mode 100644 index 000000000..2241154cd --- /dev/null +++ b/src/main/scala/extracells/network/handler/other/HandlerGuiSwitch.java @@ -0,0 +1,25 @@ +package extracells.network.handler.other; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.tileentity.TileEntity; + +import cpw.mods.fml.common.network.simpleimpl.IMessage; +import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; +import cpw.mods.fml.common.network.simpleimpl.MessageContext; +import extracells.network.GuiHandler; +import extracells.network.packet.other.PacketGuiSwitch; + +public class HandlerGuiSwitch implements IMessageHandler { + + @Override + public IMessage onMessage(PacketGuiSwitch message, MessageContext ctx) { + EntityPlayerMP player = ctx.getServerHandler().playerEntity; + TileEntity te = message.te; + if (te == null) { + GuiHandler.launchGui(message.guiIndex, player, null, 0, 0, 0); + } else { + GuiHandler.launchGui(message.guiIndex, player, te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord); + } + return null; + } +} diff --git a/src/main/scala/extracells/network/handler/part/HandlerBusFluidIO.java b/src/main/scala/extracells/network/handler/part/HandlerBusFluidIO.java index 08181f726..f4eec3dbb 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerBusFluidIO.java +++ b/src/main/scala/extracells/network/handler/part/HandlerBusFluidIO.java @@ -5,12 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketBusFluidIO; -public class HandlerBusFluidIO implements - IMessageHandler { +public class HandlerBusFluidIO implements IMessageHandler { - @Override - public IMessage onMessage(PacketBusFluidIO message, MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketBusFluidIO message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/part/HandlerBusFluidStorage.java b/src/main/scala/extracells/network/handler/part/HandlerBusFluidStorage.java index 991d773c6..775368957 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerBusFluidStorage.java +++ b/src/main/scala/extracells/network/handler/part/HandlerBusFluidStorage.java @@ -5,12 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketBusFluidStorage; -public class HandlerBusFluidStorage implements - IMessageHandler { +public class HandlerBusFluidStorage implements IMessageHandler { - @Override - public IMessage onMessage(PacketBusFluidStorage message, MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketBusFluidStorage message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/part/HandlerFluidEmitter.java b/src/main/scala/extracells/network/handler/part/HandlerFluidEmitter.java index c819bd902..eb6f950d5 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerFluidEmitter.java +++ b/src/main/scala/extracells/network/handler/part/HandlerFluidEmitter.java @@ -5,12 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketFluidEmitter; -public class HandlerFluidEmitter implements - IMessageHandler { +public class HandlerFluidEmitter implements IMessageHandler { - @Override - public IMessage onMessage(PacketFluidEmitter message, MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketFluidEmitter message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/part/HandlerFluidInterface.java b/src/main/scala/extracells/network/handler/part/HandlerFluidInterface.java index 38059641f..8681a34ed 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerFluidInterface.java +++ b/src/main/scala/extracells/network/handler/part/HandlerFluidInterface.java @@ -5,13 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketFluidInterface; -public class HandlerFluidInterface implements - IMessageHandler { - - @Override - public IMessage onMessage(PacketFluidInterface message, MessageContext ctx) { - message.execute(); - return null; - } +public class HandlerFluidInterface implements IMessageHandler { + @Override + public IMessage onMessage(PacketFluidInterface message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/part/HandlerFluidPlaneFormation.java b/src/main/scala/extracells/network/handler/part/HandlerFluidPlaneFormation.java index 086b9198b..6abbe788f 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerFluidPlaneFormation.java +++ b/src/main/scala/extracells/network/handler/part/HandlerFluidPlaneFormation.java @@ -5,13 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketFluidPlaneFormation; -public class HandlerFluidPlaneFormation implements - IMessageHandler { +public class HandlerFluidPlaneFormation implements IMessageHandler { - @Override - public IMessage onMessage(PacketFluidPlaneFormation message, - MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketFluidPlaneFormation message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/part/HandlerFluidStorage.java b/src/main/scala/extracells/network/handler/part/HandlerFluidStorage.java index be0dd3d3e..bacd1f40d 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerFluidStorage.java +++ b/src/main/scala/extracells/network/handler/part/HandlerFluidStorage.java @@ -5,12 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketFluidStorage; -public class HandlerFluidStorage implements - IMessageHandler { +public class HandlerFluidStorage implements IMessageHandler { - @Override - public IMessage onMessage(PacketFluidStorage message, MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketFluidStorage message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/part/HandlerFluidTerminal.java b/src/main/scala/extracells/network/handler/part/HandlerFluidTerminal.java index dfd0dc454..08898759e 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerFluidTerminal.java +++ b/src/main/scala/extracells/network/handler/part/HandlerFluidTerminal.java @@ -5,12 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketFluidTerminal; -public class HandlerFluidTerminal implements - IMessageHandler { +public class HandlerFluidTerminal implements IMessageHandler { - @Override - public IMessage onMessage(PacketFluidTerminal message, MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketFluidTerminal message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/handler/part/HandlerOreDictExport.java b/src/main/scala/extracells/network/handler/part/HandlerOreDictExport.java index 35a376dd5..8b0793344 100644 --- a/src/main/scala/extracells/network/handler/part/HandlerOreDictExport.java +++ b/src/main/scala/extracells/network/handler/part/HandlerOreDictExport.java @@ -5,12 +5,11 @@ import cpw.mods.fml.common.network.simpleimpl.MessageContext; import extracells.network.packet.part.PacketOreDictExport; -public class HandlerOreDictExport implements - IMessageHandler { +public class HandlerOreDictExport implements IMessageHandler { - @Override - public IMessage onMessage(PacketOreDictExport message, MessageContext ctx) { - message.execute(); - return null; - } + @Override + public IMessage onMessage(PacketOreDictExport message, MessageContext ctx) { + message.execute(); + return null; + } } diff --git a/src/main/scala/extracells/network/packet/other/IFluidSlotGui.java b/src/main/scala/extracells/network/packet/other/IFluidSlotGui.java index d13117215..1f2098f8d 100644 --- a/src/main/scala/extracells/network/packet/other/IFluidSlotGui.java +++ b/src/main/scala/extracells/network/packet/other/IFluidSlotGui.java @@ -1,10 +1,10 @@ package extracells.network.packet.other; -import net.minecraftforge.fluids.Fluid; - import java.util.List; +import net.minecraftforge.fluids.Fluid; + public interface IFluidSlotGui { - public void updateFluids(List _fluids); + public void updateFluids(List _fluids); } diff --git a/src/main/scala/extracells/network/packet/other/IFluidSlotPartOrBlock.java b/src/main/scala/extracells/network/packet/other/IFluidSlotPartOrBlock.java index 8dfcc1b80..cd1bc7c18 100644 --- a/src/main/scala/extracells/network/packet/other/IFluidSlotPartOrBlock.java +++ b/src/main/scala/extracells/network/packet/other/IFluidSlotPartOrBlock.java @@ -5,5 +5,5 @@ public interface IFluidSlotPartOrBlock { - public void setFluid(int _index, Fluid _fluid, EntityPlayer _player); + public void setFluid(int _index, Fluid _fluid, EntityPlayer _player); } diff --git a/src/main/scala/extracells/network/packet/other/PacketFluidContainerSlot.java b/src/main/scala/extracells/network/packet/other/PacketFluidContainerSlot.java index 864b5d0d4..62c01be75 100644 --- a/src/main/scala/extracells/network/packet/other/PacketFluidContainerSlot.java +++ b/src/main/scala/extracells/network/packet/other/PacketFluidContainerSlot.java @@ -1,59 +1,57 @@ package extracells.network.packet.other; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + import cpw.mods.fml.common.network.ByteBufUtils; import extracells.network.AbstractPacket; import extracells.tileentity.TileEntityFluidFiller; import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; public class PacketFluidContainerSlot extends AbstractPacket { - private ItemStack container; - private TileEntityFluidFiller fluidFiller; - - public PacketFluidContainerSlot() {} - - public PacketFluidContainerSlot(TileEntityFluidFiller _fluidFiller, - ItemStack _container, EntityPlayer _player) { - super(_player); - this.mode = 0; - this.fluidFiller = _fluidFiller; - this.container = _container; - } - - @Override - public void execute() { - switch (this.mode) { - case 0: - this.container.stackSize = 1; - this.fluidFiller.containerItem = this.container; - if (this.fluidFiller.hasWorldObj()) - this.fluidFiller.getWorldObj().markBlockForUpdate( - this.fluidFiller.xCoord, this.fluidFiller.yCoord, - this.fluidFiller.zCoord); - this.fluidFiller.postUpdateEvent(); - break; - } - } - - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - this.fluidFiller = (TileEntityFluidFiller) readTileEntity(in); - this.container = ByteBufUtils.readItemStack(in); - break; - } - } - - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - writeTileEntity(this.fluidFiller, out); - ByteBufUtils.writeItemStack(out, this.container); - break; - } - } + private ItemStack container; + private TileEntityFluidFiller fluidFiller; + + public PacketFluidContainerSlot() {} + + public PacketFluidContainerSlot(TileEntityFluidFiller _fluidFiller, ItemStack _container, EntityPlayer _player) { + super(_player); + this.mode = 0; + this.fluidFiller = _fluidFiller; + this.container = _container; + } + + @Override + public void execute() { + switch (this.mode) { + case 0: + this.container.stackSize = 1; + this.fluidFiller.containerItem = this.container; + if (this.fluidFiller.hasWorldObj()) this.fluidFiller.getWorldObj() + .markBlockForUpdate(this.fluidFiller.xCoord, this.fluidFiller.yCoord, this.fluidFiller.zCoord); + this.fluidFiller.postUpdateEvent(); + break; + } + } + + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + this.fluidFiller = (TileEntityFluidFiller) readTileEntity(in); + this.container = ByteBufUtils.readItemStack(in); + break; + } + } + + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + writeTileEntity(this.fluidFiller, out); + ByteBufUtils.writeItemStack(out, this.container); + break; + } + } } diff --git a/src/main/scala/extracells/network/packet/other/PacketFluidSlot.java b/src/main/scala/extracells/network/packet/other/PacketFluidSlot.java index 7cf3a23be..f83dfd7ec 100644 --- a/src/main/scala/extracells/network/packet/other/PacketFluidSlot.java +++ b/src/main/scala/extracells/network/packet/other/PacketFluidSlot.java @@ -1,97 +1,95 @@ package extracells.network.packet.other; -import extracells.network.AbstractPacket; -import extracells.part.PartECBase; -import io.netty.buffer.ByteBuf; +import java.util.ArrayList; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraftforge.fluids.Fluid; -import java.util.ArrayList; -import java.util.List; +import extracells.network.AbstractPacket; +import extracells.part.PartECBase; +import io.netty.buffer.ByteBuf; public class PacketFluidSlot extends AbstractPacket { - private int index; - private Fluid fluid; - private IFluidSlotPartOrBlock partOrBlock; - private List filterFluids; + private int index; + private Fluid fluid; + private IFluidSlotPartOrBlock partOrBlock; + private List filterFluids; - public PacketFluidSlot() {} + public PacketFluidSlot() {} - public PacketFluidSlot(IFluidSlotPartOrBlock _partOrBlock, int _index, - Fluid _fluid, EntityPlayer _player) { - super(_player); - this.mode = 0; - this.partOrBlock = _partOrBlock; - this.index = _index; - this.fluid = _fluid; - } + public PacketFluidSlot(IFluidSlotPartOrBlock _partOrBlock, int _index, Fluid _fluid, EntityPlayer _player) { + super(_player); + this.mode = 0; + this.partOrBlock = _partOrBlock; + this.index = _index; + this.fluid = _fluid; + } - public PacketFluidSlot(List _filterFluids) { - this.mode = 1; - this.filterFluids = _filterFluids; - } + public PacketFluidSlot(List _filterFluids) { + this.mode = 1; + this.filterFluids = _filterFluids; + } - @Override - public void execute() { - switch (this.mode) { - case 0: - this.partOrBlock.setFluid(this.index, this.fluid, this.player); - break; - case 1: - Gui gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof IFluidSlotGui) { - IFluidSlotGui partGui = (IFluidSlotGui) gui; - partGui.updateFluids(this.filterFluids); - } - break; - } - } + @Override + public void execute() { + switch (this.mode) { + case 0: + this.partOrBlock.setFluid(this.index, this.fluid, this.player); + break; + case 1: + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof IFluidSlotGui) { + IFluidSlotGui partGui = (IFluidSlotGui) gui; + partGui.updateFluids(this.filterFluids); + } + break; + } + } - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - if (in.readBoolean()) - this.partOrBlock = (IFluidSlotPartOrBlock) readPart(in); - else - this.partOrBlock = (IFluidSlotPartOrBlock) readTileEntity(in); - this.index = in.readInt(); - this.fluid = readFluid(in); - break; - case 1: - this.filterFluids = new ArrayList(); - int size = in.readInt(); - for (int i = 0; i < size; i++) { - this.filterFluids.add(readFluid(in)); - } - break; - } - } + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + if (in.readBoolean()) this.partOrBlock = (IFluidSlotPartOrBlock) readPart(in); + else this.partOrBlock = (IFluidSlotPartOrBlock) readTileEntity(in); + this.index = in.readInt(); + this.fluid = readFluid(in); + break; + case 1: + this.filterFluids = new ArrayList<>(); + int size = in.readInt(); + for (int i = 0; i < size; i++) { + this.filterFluids.add(readFluid(in)); + } + break; + } + } - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - if (this.partOrBlock instanceof PartECBase) { - out.writeBoolean(true); - writePart((PartECBase) this.partOrBlock, out); - } else { - out.writeBoolean(false); - writeTileEntity((TileEntity) this.partOrBlock, out); - } - out.writeInt(this.index); - writeFluid(this.fluid, out); - break; - case 1: - out.writeInt(this.filterFluids.size()); - for (int i = 0; i < this.filterFluids.size(); i++) { - writeFluid(this.filterFluids.get(i), out); - } - break; - } - } + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + if (this.partOrBlock instanceof PartECBase) { + out.writeBoolean(true); + writePart((PartECBase) this.partOrBlock, out); + } else { + out.writeBoolean(false); + writeTileEntity((TileEntity) this.partOrBlock, out); + } + out.writeInt(this.index); + writeFluid(this.fluid, out); + break; + case 1: + out.writeInt(this.filterFluids.size()); + for (Fluid filterFluid : this.filterFluids) { + writeFluid(filterFluid, out); + } + break; + } + } } diff --git a/src/main/scala/extracells/network/packet/other/PacketGuiSwitch.java b/src/main/scala/extracells/network/packet/other/PacketGuiSwitch.java new file mode 100644 index 000000000..63fa5dc08 --- /dev/null +++ b/src/main/scala/extracells/network/packet/other/PacketGuiSwitch.java @@ -0,0 +1,41 @@ +package extracells.network.packet.other; + +import net.minecraft.tileentity.TileEntity; + +import extracells.network.AbstractPacket; +import io.netty.buffer.ByteBuf; + +public class PacketGuiSwitch extends AbstractPacket { + + public int guiIndex; + public TileEntity te; + + public PacketGuiSwitch() {} + + public PacketGuiSwitch(int guiIndex, TileEntity te) { + this.guiIndex = guiIndex; + this.te = te; + } + + @Override + public void execute() {} + + @Override + public void readData(ByteBuf in) { + guiIndex = in.readInt(); + if (in.readBoolean()) { + te = readTileEntity(in); + } + } + + @Override + public void writeData(ByteBuf out) { + out.writeInt(guiIndex); + if (te == null) { + out.writeBoolean(false); + } else { + out.writeBoolean(true); + writeTileEntity(te, out); + } + } +} diff --git a/src/main/scala/extracells/network/packet/part/PacketBusFluidIO.java b/src/main/scala/extracells/network/packet/part/PacketBusFluidIO.java index 1b87d742a..31c950ac4 100644 --- a/src/main/scala/extracells/network/packet/part/PacketBusFluidIO.java +++ b/src/main/scala/extracells/network/packet/part/PacketBusFluidIO.java @@ -1,137 +1,136 @@ package extracells.network.packet.part; -import appeng.api.config.RedstoneMode; -import extracells.gui.GuiBusFluidIO; -import extracells.network.AbstractPacket; -import extracells.part.PartFluidIO; -import io.netty.buffer.ByteBuf; +import java.util.List; + import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.fluids.Fluid; -import java.util.List; +import appeng.api.config.RedstoneMode; +import extracells.gui.GuiBusFluidIO; +import extracells.network.AbstractPacket; +import extracells.part.PartFluidIO; +import io.netty.buffer.ByteBuf; public class PacketBusFluidIO extends AbstractPacket { - private List filterFluids; - private PartFluidIO part; - private byte action; - private byte ordinal; - private byte filterSize; - private boolean redstoneControlled; - - @SuppressWarnings("unused") - public PacketBusFluidIO() {} + private List filterFluids; + private PartFluidIO part; + private byte action; + private byte ordinal; + private byte filterSize; + private boolean redstoneControlled; - public PacketBusFluidIO(boolean _redstoneControlled) { - super(); - this.mode = 4; - this.redstoneControlled = _redstoneControlled; - } + @SuppressWarnings("unused") + public PacketBusFluidIO() {} - public PacketBusFluidIO(byte _filterSize) { - super(); - this.mode = 3; - this.filterSize = _filterSize; - } + public PacketBusFluidIO(boolean _redstoneControlled) { + super(); + this.mode = 4; + this.redstoneControlled = _redstoneControlled; + } - public PacketBusFluidIO(EntityPlayer _player, byte _action, - PartFluidIO _part) { - super(_player); - this.mode = 0; - this.action = _action; - this.part = _part; - } + public PacketBusFluidIO(byte _filterSize) { + super(); + this.mode = 3; + this.filterSize = _filterSize; + } - public PacketBusFluidIO(EntityPlayer _player, PartFluidIO _part) { - super(_player); - this.mode = 2; - this.part = _part; - } + public PacketBusFluidIO(EntityPlayer _player, byte _action, PartFluidIO _part) { + super(_player); + this.mode = 0; + this.action = _action; + this.part = _part; + } - public PacketBusFluidIO(RedstoneMode _redstoneMode) { - super(); - this.mode = 1; - this.ordinal = (byte) _redstoneMode.ordinal(); - } + public PacketBusFluidIO(EntityPlayer _player, PartFluidIO _part) { + super(_player); + this.mode = 2; + this.part = _part; + } - @Override - public void execute() { - Gui gui; - switch (this.mode) { - case 0: + public PacketBusFluidIO(RedstoneMode _redstoneMode) { + super(); + this.mode = 1; + this.ordinal = (byte) _redstoneMode.ordinal(); + } - this.part.loopRedstoneMode(this.player); - break; - case 1: - gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiBusFluidIO) { - GuiBusFluidIO partGui = (GuiBusFluidIO) gui; - partGui.updateRedstoneMode(RedstoneMode.values()[this.ordinal]); - } - break; - case 2: - this.part.sendInformation(this.player); - break; - case 3: - gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiBusFluidIO) { - GuiBusFluidIO partGui = (GuiBusFluidIO) gui; - partGui.changeConfig(this.filterSize); - } - break; - case 4: - gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiBusFluidIO) { - GuiBusFluidIO partGui = (GuiBusFluidIO) gui; - partGui.setRedstoneControlled(this.redstoneControlled); - } - break; - } - } + @Override + public void execute() { + Gui gui; + switch (this.mode) { + case 0: + this.part.loopRedstoneMode(this.player); + break; + case 1: + gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiBusFluidIO) { + GuiBusFluidIO partGui = (GuiBusFluidIO) gui; + partGui.updateRedstoneMode(RedstoneMode.values()[this.ordinal]); + } + break; + case 2: + this.part.sendInformation(this.player); + break; + case 3: + gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiBusFluidIO) { + GuiBusFluidIO partGui = (GuiBusFluidIO) gui; + partGui.changeConfig(this.filterSize); + } + break; + case 4: + gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiBusFluidIO) { + GuiBusFluidIO partGui = (GuiBusFluidIO) gui; + partGui.setRedstoneControlled(this.redstoneControlled); + } + break; + } + } - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - this.part = (PartFluidIO) readPart(in); - this.action = in.readByte(); - break; - case 1: - this.ordinal = in.readByte(); - break; - case 2: - this.part = (PartFluidIO) readPart(in); - break; - case 3: - this.filterSize = in.readByte(); - break; - case 4: - this.redstoneControlled = in.readBoolean(); - break; - } - } + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + this.part = (PartFluidIO) readPart(in); + this.action = in.readByte(); + break; + case 1: + this.ordinal = in.readByte(); + break; + case 2: + this.part = (PartFluidIO) readPart(in); + break; + case 3: + this.filterSize = in.readByte(); + break; + case 4: + this.redstoneControlled = in.readBoolean(); + break; + } + } - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - writePart(this.part, out); - out.writeByte(this.action); - break; - case 1: - out.writeByte(this.ordinal); - break; - case 2: - writePart(this.part, out); - break; - case 3: - out.writeByte(this.filterSize); - break; - case 4: - out.writeBoolean(this.redstoneControlled); - break; - } - } + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + writePart(this.part, out); + out.writeByte(this.action); + break; + case 1: + out.writeByte(this.ordinal); + break; + case 2: + writePart(this.part, out); + break; + case 3: + out.writeByte(this.filterSize); + break; + case 4: + out.writeBoolean(this.redstoneControlled); + break; + } + } } diff --git a/src/main/scala/extracells/network/packet/part/PacketBusFluidStorage.java b/src/main/scala/extracells/network/packet/part/PacketBusFluidStorage.java index 6c3850cf9..0bf37a487 100644 --- a/src/main/scala/extracells/network/packet/part/PacketBusFluidStorage.java +++ b/src/main/scala/extracells/network/packet/part/PacketBusFluidStorage.java @@ -1,5 +1,10 @@ package extracells.network.packet.part; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; + import appeng.api.config.AccessRestriction; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -8,87 +13,77 @@ import extracells.network.AbstractPacket; import extracells.part.PartFluidStorage; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; public class PacketBusFluidStorage extends AbstractPacket { - PartFluidStorage part; - AccessRestriction access; - - public PacketBusFluidStorage() {} - - public PacketBusFluidStorage(EntityPlayer _player, - AccessRestriction _access, boolean toClient) { - super(_player); - if (toClient) - this.mode = 1; - else - this.mode = 2; - this.access = _access; - } + PartFluidStorage part; + AccessRestriction access; - public PacketBusFluidStorage(EntityPlayer _player, PartFluidStorage _part) { - super(_player); - this.mode = 0; - this.player = _player; - this.part = _part; - } + public PacketBusFluidStorage() {} - @Override - public void execute() { - switch (this.mode) { - case 0: - this.part.sendInformation(this.player); - break; - case 1: - try { - handleClient(); - } catch (Throwable e) {} - break; - case 2: - Container con = this.player.openContainer; - if (con != null && con instanceof ContainerBusFluidStorage) { - ((ContainerBusFluidStorage) con).part.updateAccess(this.access); - new PacketBusFluidStorage(this.player, this.access, true) - .sendPacketToPlayer(this.player); - } - } - } + public PacketBusFluidStorage(EntityPlayer _player, AccessRestriction _access, boolean toClient) { + super(_player); + if (toClient) this.mode = 1; + else this.mode = 2; + this.access = _access; + } - @SideOnly(Side.CLIENT) - void handleClient() { - GuiScreen screen = Minecraft.getMinecraft().currentScreen; - if (screen != null && screen instanceof GuiBusFluidStorage) { - ((GuiBusFluidStorage) screen).updateAccessRestriction(this.access); - } - } + public PacketBusFluidStorage(EntityPlayer _player, PartFluidStorage _part) { + super(_player); + this.mode = 0; + this.player = _player; + this.part = _part; + } - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - this.part = (PartFluidStorage) readPart(in); - break; - case 1: - case 2: - this.access = AccessRestriction.valueOf(readString(in)); - } + @Override + public void execute() { + switch (this.mode) { + case 0: + this.part.sendInformation(this.player); + break; + case 1: + try { + handleClient(); + } catch (Throwable e) {} + break; + case 2: + Container con = this.player.openContainer; + if (con != null && con instanceof ContainerBusFluidStorage) { + ((ContainerBusFluidStorage) con).part.updateAccess(this.access); + new PacketBusFluidStorage(this.player, this.access, true).sendPacketToPlayer(this.player); + } + } + } - } + @SideOnly(Side.CLIENT) + void handleClient() { + GuiScreen screen = Minecraft.getMinecraft().currentScreen; + if (screen != null && screen instanceof GuiBusFluidStorage) { + ((GuiBusFluidStorage) screen).updateAccessRestriction(this.access); + } + } - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - writePart(this.part, out); - break; - case 1: - case 2: - writeString(this.access.name(), out); - } + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + this.part = (PartFluidStorage) readPart(in); + break; + case 1: + case 2: + this.access = AccessRestriction.valueOf(readString(in)); + } + } - } + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + writePart(this.part, out); + break; + case 1: + case 2: + writeString(this.access.name(), out); + } + } } diff --git a/src/main/scala/extracells/network/packet/part/PacketFluidEmitter.java b/src/main/scala/extracells/network/packet/part/PacketFluidEmitter.java index 7ed2998db..a77b1f428 100644 --- a/src/main/scala/extracells/network/packet/part/PacketFluidEmitter.java +++ b/src/main/scala/extracells/network/packet/part/PacketFluidEmitter.java @@ -1,139 +1,137 @@ package extracells.network.packet.part; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.entity.player.EntityPlayer; + import appeng.api.config.RedstoneMode; import extracells.gui.GuiFluidEmitter; import extracells.network.AbstractPacket; import extracells.part.PartFluidLevelEmitter; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.entity.player.EntityPlayer; public class PacketFluidEmitter extends AbstractPacket { - private long wantedAmount; - private PartFluidLevelEmitter part; - private RedstoneMode redstoneMode; - private boolean toggle; + private long wantedAmount; + private PartFluidLevelEmitter part; + private RedstoneMode redstoneMode; + private boolean toggle; - public PacketFluidEmitter() {} + public PacketFluidEmitter() {} - public PacketFluidEmitter(boolean _toggle, PartFluidLevelEmitter _part, - EntityPlayer _player) { - this.mode = 3; - this.toggle = _toggle; - this.part = _part; - this.player = _player; - } + public PacketFluidEmitter(boolean _toggle, PartFluidLevelEmitter _part, EntityPlayer _player) { + this.mode = 3; + this.toggle = _toggle; + this.part = _part; + this.player = _player; + } - public PacketFluidEmitter(int _wantedAmount, PartFluidLevelEmitter _part, - EntityPlayer _player) { - this.mode = 0; - this.wantedAmount = _wantedAmount; - this.part = _part; - this.player = _player; - } + public PacketFluidEmitter(int _wantedAmount, PartFluidLevelEmitter _part, EntityPlayer _player) { + this.mode = 0; + this.wantedAmount = _wantedAmount; + this.part = _part; + this.player = _player; + } - public PacketFluidEmitter(long _wantedAmount, EntityPlayer _player) { - this.mode = 2; - this.wantedAmount = _wantedAmount; - this.player = _player; - } + public PacketFluidEmitter(long _wantedAmount, EntityPlayer _player) { + this.mode = 2; + this.wantedAmount = _wantedAmount; + this.player = _player; + } - public PacketFluidEmitter(RedstoneMode _redstoneMode, EntityPlayer _player) { - this.mode = 4; - this.redstoneMode = _redstoneMode; - this.player = _player; - } + public PacketFluidEmitter(RedstoneMode _redstoneMode, EntityPlayer _player) { + this.mode = 4; + this.redstoneMode = _redstoneMode; + this.player = _player; + } - public PacketFluidEmitter(String textField, PartFluidLevelEmitter _part, - EntityPlayer _player) { - this.mode = 1; - this.wantedAmount = textField.isEmpty() ? 0 : Long.parseLong(textField); - this.part = _part; - this.player = _player; - } + public PacketFluidEmitter(String textField, PartFluidLevelEmitter _part, EntityPlayer _player) { + this.mode = 1; + this.wantedAmount = textField.isEmpty() ? 0 : Long.parseLong(textField); + this.part = _part; + this.player = _player; + } - @Override - public void execute() { - switch (this.mode) { - case 0: - this.part.changeWantedAmount((int) this.wantedAmount, this.player); - break; - case 1: - this.part.setWantedAmount(this.wantedAmount, this.player); - break; - case 2: - if (this.player != null && this.player.isClientWorld()) { - Gui gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiFluidEmitter) { - ((GuiFluidEmitter) gui).setAmountField(this.wantedAmount); - } - } - break; - case 3: - if (this.toggle) { - this.part.toggleMode(this.player); - } else { - this.part.syncClientGui(this.player); - } - break; - case 4: - if (this.player != null && this.player.isClientWorld()) { - Gui gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiFluidEmitter) { - ((GuiFluidEmitter) gui).setRedstoneMode(this.redstoneMode); - } - } - break; - } - } + @Override + public void execute() { + switch (this.mode) { + case 0: + this.part.changeWantedAmount((int) this.wantedAmount, this.player); + break; + case 1: + this.part.setWantedAmount(this.wantedAmount, this.player); + break; + case 2: + if (this.player != null && this.player.isClientWorld()) { + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiFluidEmitter) { + ((GuiFluidEmitter) gui).setAmountField(this.wantedAmount); + } + } + break; + case 3: + if (this.toggle) { + this.part.toggleMode(this.player); + } else { + this.part.syncClientGui(this.player); + } + break; + case 4: + if (this.player != null && this.player.isClientWorld()) { + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiFluidEmitter) { + ((GuiFluidEmitter) gui).setRedstoneMode(this.redstoneMode); + } + } + break; + } + } - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - this.wantedAmount = in.readLong(); - this.part = (PartFluidLevelEmitter) readPart(in); - break; - case 1: - this.wantedAmount = in.readLong(); - this.part = (PartFluidLevelEmitter) readPart(in); - break; - case 2: - this.wantedAmount = in.readLong(); - break; - case 3: - this.toggle = in.readBoolean(); - this.part = (PartFluidLevelEmitter) readPart(in); - break; - case 4: - this.redstoneMode = RedstoneMode.values()[in.readInt()]; - break; - } - } + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + this.wantedAmount = in.readLong(); + this.part = (PartFluidLevelEmitter) readPart(in); + break; + case 1: + this.wantedAmount = in.readLong(); + this.part = (PartFluidLevelEmitter) readPart(in); + break; + case 2: + this.wantedAmount = in.readLong(); + break; + case 3: + this.toggle = in.readBoolean(); + this.part = (PartFluidLevelEmitter) readPart(in); + break; + case 4: + this.redstoneMode = RedstoneMode.values()[in.readInt()]; + break; + } + } - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - out.writeLong(this.wantedAmount); - writePart(this.part, out); - break; - case 1: - out.writeLong(this.wantedAmount); - writePart(this.part, out); - break; - case 2: - out.writeLong(this.wantedAmount); - break; - case 3: - out.writeBoolean(this.toggle); - writePart(this.part, out); - break; - case 4: - out.writeInt(this.redstoneMode.ordinal()); - break; - } - } + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + out.writeLong(this.wantedAmount); + writePart(this.part, out); + break; + case 1: + out.writeLong(this.wantedAmount); + writePart(this.part, out); + break; + case 2: + out.writeLong(this.wantedAmount); + break; + case 3: + out.writeBoolean(this.toggle); + writePart(this.part, out); + break; + case 4: + out.writeInt(this.redstoneMode.ordinal()); + break; + } + } } diff --git a/src/main/scala/extracells/network/packet/part/PacketFluidInterface.java b/src/main/scala/extracells/network/packet/part/PacketFluidInterface.java index 4d922c33d..379eab4b1 100644 --- a/src/main/scala/extracells/network/packet/part/PacketFluidInterface.java +++ b/src/main/scala/extracells/network/packet/part/PacketFluidInterface.java @@ -1,5 +1,12 @@ package extracells.network.packet.part; +import net.minecraft.client.Minecraft; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -7,138 +14,115 @@ import extracells.gui.GuiFluidInterface; import extracells.network.AbstractPacket; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; public class PacketFluidInterface extends AbstractPacket { - FluidStack[] tank; - Integer[] filter; - int fluidID; - int filterSlot; - - public PacketFluidInterface() {} - - public PacketFluidInterface(FluidStack[] _tank, Integer[] _filter, - EntityPlayer _player) { - super(_player); - this.mode = 0; - this.tank = _tank; - this.filter = _filter; - } - - public PacketFluidInterface(int _fluidID, int _filterSlot, - EntityPlayer _player) { - super(_player); - this.mode = 1; - this.fluidID = _fluidID; - this.filterSlot = _filterSlot; - } - - @Override - public void execute() { - switch (this.mode) { - case 0: - mode0(); - break; - case 1: - if (this.player.openContainer != null - && this.player.openContainer instanceof ContainerFluidInterface) { - ContainerFluidInterface container = (ContainerFluidInterface) this.player.openContainer; - container.fluidInterface.setFilter( - ForgeDirection.getOrientation(this.filterSlot), - FluidRegistry.getFluid(this.fluidID)); - } - break; - default: - } + FluidStack[] tank; + Integer[] filter; + int fluidID; + int filterSlot; - } + public PacketFluidInterface() {} - @SideOnly(Side.CLIENT) - private void mode0() { - EntityPlayer p = Minecraft.getMinecraft().thePlayer; - if (p.openContainer != null - && p.openContainer instanceof ContainerFluidInterface) { - ContainerFluidInterface container = (ContainerFluidInterface) p.openContainer; - if (Minecraft.getMinecraft().currentScreen != null - && Minecraft.getMinecraft().currentScreen instanceof GuiFluidInterface) { - GuiFluidInterface gui = (GuiFluidInterface) Minecraft - .getMinecraft().currentScreen; - for (int i = 0; i < this.tank.length; i++) { - container.fluidInterface.setFluidTank( - ForgeDirection.getOrientation(i), this.tank[i]); - } - for (int i = 0; i < this.filter.length; i++) { - if (gui.filter[i] != null) - gui.filter[i].setFluid(FluidRegistry - .getFluid(this.filter[i])); - } - } - } - } + public PacketFluidInterface(FluidStack[] _tank, Integer[] _filter, EntityPlayer _player) { + super(_player); + this.mode = 0; + this.tank = _tank; + this.filter = _filter; + } - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - NBTTagCompound tag = ByteBufUtils.readTag(in); - this.tank = new FluidStack[tag.getInteger("lengthTank")]; - for (int i = 0; i < this.tank.length; i++) { - if (tag.hasKey("tank#" + i)) - this.tank[i] = FluidStack.loadFluidStackFromNBT(tag - .getCompoundTag("tank#" + i)); - else - this.tank[i] = null; - } - this.filter = new Integer[tag.getInteger("lengthFilter")]; - for (int i = 0; i < this.filter.length; i++) { - if (tag.hasKey("filter#" + i)) - this.filter[i] = tag.getInteger("filter#" + i); - else - this.filter[i] = -1; - } - break; - case 1: - this.filterSlot = in.readInt(); - this.fluidID = in.readInt(); - break; - default: - } + public PacketFluidInterface(int _fluidID, int _filterSlot, EntityPlayer _player) { + super(_player); + this.mode = 1; + this.fluidID = _fluidID; + this.filterSlot = _filterSlot; + } - } + @Override + public void execute() { + switch (this.mode) { + case 0: + mode0(); + break; + case 1: + if (this.player.openContainer != null && this.player.openContainer instanceof ContainerFluidInterface) { + ContainerFluidInterface container = (ContainerFluidInterface) this.player.openContainer; + container.fluidInterface.setFilter( + ForgeDirection.getOrientation(this.filterSlot), + FluidRegistry.getFluid(this.fluidID)); + } + break; + default: + } + } - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - NBTTagCompound tag = new NBTTagCompound(); - tag.setInteger("lengthTank", this.tank.length); - for (int i = 0; i < this.tank.length; i++) { - if (this.tank[i] != null) { - tag.setTag("tank#" + i, - this.tank[i].writeToNBT(new NBTTagCompound())); - } - } - tag.setInteger("lengthFilter", this.filter.length); - for (int i = 0; i < this.filter.length; i++) { - if (this.filter[i] != null) { - tag.setInteger("filter#" + i, this.filter[i]); - } - } - ByteBufUtils.writeTag(out, tag); - break; - case 1: - out.writeInt(this.filterSlot); - out.writeInt(this.fluidID); - break; - default: - } + @SideOnly(Side.CLIENT) + private void mode0() { + EntityPlayer p = Minecraft.getMinecraft().thePlayer; + if (p.openContainer != null && p.openContainer instanceof ContainerFluidInterface) { + ContainerFluidInterface container = (ContainerFluidInterface) p.openContainer; + if (Minecraft.getMinecraft().currentScreen != null + && Minecraft.getMinecraft().currentScreen instanceof GuiFluidInterface) { + GuiFluidInterface gui = (GuiFluidInterface) Minecraft.getMinecraft().currentScreen; + for (int i = 0; i < this.tank.length; i++) { + container.fluidInterface.setFluidTank(ForgeDirection.getOrientation(i), this.tank[i]); + } + for (int i = 0; i < this.filter.length; i++) { + if (gui.filter[i] != null) gui.filter[i].setFluid(FluidRegistry.getFluid(this.filter[i])); + } + } + } + } - } + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + NBTTagCompound tag = ByteBufUtils.readTag(in); + this.tank = new FluidStack[tag.getInteger("lengthTank")]; + for (int i = 0; i < this.tank.length; i++) { + if (tag.hasKey("tank#" + i)) + this.tank[i] = FluidStack.loadFluidStackFromNBT(tag.getCompoundTag("tank#" + i)); + else this.tank[i] = null; + } + this.filter = new Integer[tag.getInteger("lengthFilter")]; + for (int i = 0; i < this.filter.length; i++) { + if (tag.hasKey("filter#" + i)) this.filter[i] = tag.getInteger("filter#" + i); + else this.filter[i] = -1; + } + break; + case 1: + this.filterSlot = in.readInt(); + this.fluidID = in.readInt(); + break; + default: + } + } + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + NBTTagCompound tag = new NBTTagCompound(); + tag.setInteger("lengthTank", this.tank.length); + for (int i = 0; i < this.tank.length; i++) { + if (this.tank[i] != null) { + tag.setTag("tank#" + i, this.tank[i].writeToNBT(new NBTTagCompound())); + } + } + tag.setInteger("lengthFilter", this.filter.length); + for (int i = 0; i < this.filter.length; i++) { + if (this.filter[i] != null) { + tag.setInteger("filter#" + i, this.filter[i]); + } + } + ByteBufUtils.writeTag(out, tag); + break; + case 1: + out.writeInt(this.filterSlot); + out.writeInt(this.fluidID); + break; + default: + } + } } diff --git a/src/main/scala/extracells/network/packet/part/PacketFluidPlaneFormation.java b/src/main/scala/extracells/network/packet/part/PacketFluidPlaneFormation.java index 21cb97dd5..d8216fe52 100644 --- a/src/main/scala/extracells/network/packet/part/PacketFluidPlaneFormation.java +++ b/src/main/scala/extracells/network/packet/part/PacketFluidPlaneFormation.java @@ -1,48 +1,48 @@ package extracells.network.packet.part; +import net.minecraft.entity.player.EntityPlayer; + import extracells.network.AbstractPacket; import extracells.part.PartFluidPlaneFormation; import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayer; public class PacketFluidPlaneFormation extends AbstractPacket { - private PartFluidPlaneFormation part; - - @SuppressWarnings("unused") - public PacketFluidPlaneFormation() {} - - public PacketFluidPlaneFormation(EntityPlayer _player, - PartFluidPlaneFormation _part) { - super(_player); - this.mode = 0; - this.part = _part; - } - - @Override - public void execute() { - switch (this.mode) { - case 0: - this.part.sendInformation(this.player); - break; - } - } - - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - this.part = (PartFluidPlaneFormation) readPart(in); - break; - } - } - - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - writePart(this.part, out); - break; - } - } + private PartFluidPlaneFormation part; + + @SuppressWarnings("unused") + public PacketFluidPlaneFormation() {} + + public PacketFluidPlaneFormation(EntityPlayer _player, PartFluidPlaneFormation _part) { + super(_player); + this.mode = 0; + this.part = _part; + } + + @Override + public void execute() { + switch (this.mode) { + case 0: + this.part.sendInformation(this.player); + break; + } + } + + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + this.part = (PartFluidPlaneFormation) readPart(in); + break; + } + } + + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + writePart(this.part, out); + break; + } + } } diff --git a/src/main/scala/extracells/network/packet/part/PacketFluidStorage.java b/src/main/scala/extracells/network/packet/part/PacketFluidStorage.java index eed7a8c32..7a28bee98 100644 --- a/src/main/scala/extracells/network/packet/part/PacketFluidStorage.java +++ b/src/main/scala/extracells/network/packet/part/PacketFluidStorage.java @@ -1,5 +1,11 @@ package extracells.network.packet.part; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.AEApi; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; @@ -12,148 +18,177 @@ import extracells.integration.Integration; import extracells.network.AbstractPacket; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; public class PacketFluidStorage extends AbstractPacket { - private IItemList fluidStackList; - private Fluid currentFluid; - private boolean hasTermHandler; - - @SuppressWarnings("unused") - public PacketFluidStorage() {} - - public PacketFluidStorage(EntityPlayer _player) { - super(_player); - this.mode = 2; - } - - public PacketFluidStorage(EntityPlayer _player, boolean _hasTermHandler) { - super(_player); - this.mode = 3; - this.hasTermHandler = _hasTermHandler; - } - - public PacketFluidStorage(EntityPlayer _player, Fluid _currentFluid) { - super(_player); - this.mode = 1; - this.currentFluid = _currentFluid; - } - - public PacketFluidStorage(EntityPlayer _player, IItemList _list) { - super(_player); - this.mode = 0; - this.fluidStackList = _list; - } - - @Override - public void execute() { - switch (this.mode) { - case 0: - case0(); - break; - case 1: - if (this.player != null && this.player.openContainer instanceof ContainerFluidStorage) { - ((ContainerFluidStorage) this.player.openContainer).receiveSelectedFluid(this.currentFluid); - }else if (this.player != null && Integration.Mods.MEKANISMGAS.isEnabled() && this.player.openContainer instanceof ContainerGasStorage) { - ((ContainerGasStorage) this.player.openContainer).receiveSelectedFluid(this.currentFluid); - } - break; - case 2: - if (this.player != null) { - if (!this.player.worldObj.isRemote) { - if (this.player.openContainer instanceof ContainerFluidStorage) { - ((ContainerFluidStorage) this.player.openContainer).forceFluidUpdate(); - ((ContainerFluidStorage) this.player.openContainer).doWork(); - }else if (this.player.openContainer instanceof ContainerGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) { - ((ContainerGasStorage) this.player.openContainer).forceFluidUpdate(); - ((ContainerGasStorage) this.player.openContainer).doWork(); - } - } - } - break; - case 3: - case3(); - break; - } - } - - @SideOnly(Side.CLIENT) - private void case0(){ - if (this.player != null && this.player.isClientWorld()) { - Gui gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiFluidStorage) { - ContainerFluidStorage container = (ContainerFluidStorage) ((GuiFluidStorage) gui).inventorySlots; - container.updateFluidList(this.fluidStackList); - }else if (gui instanceof GuiGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) { - ContainerGasStorage container = (ContainerGasStorage) ((GuiGasStorage) gui).inventorySlots; - container.updateFluidList(this.fluidStackList); - } - } - } - - @SideOnly(Side.CLIENT) - private void case3(){ - if (this.player != null && this.player.isClientWorld()) { - Gui gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiFluidStorage) { - ContainerFluidStorage container = (ContainerFluidStorage) ((GuiFluidStorage) gui).inventorySlots; - container.hasWirelessTermHandler = this.hasTermHandler; - }else if (gui instanceof GuiGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) { - ContainerGasStorage container = (ContainerGasStorage) ((GuiGasStorage) gui).inventorySlots; - container.hasWirelessTermHandler = this.hasTermHandler; - } - } - } - - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - this.fluidStackList = AEApi.instance().storage().createFluidList(); - while (in.readableBytes() > 0) { - Fluid fluid = readFluid(in); - long fluidAmount = in.readLong(); - if (fluid != null) { - IAEFluidStack stack = AEApi.instance().storage().createFluidStack(new FluidStack(fluid, 1)); - stack.setStackSize(fluidAmount); - this.fluidStackList.add(stack); - } - } - break; - case 1: - this.currentFluid = readFluid(in); - break; - case 2: - break; - case 3: - this.hasTermHandler = in.readBoolean(); - break; - } - } - - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - for (IAEFluidStack stack : this.fluidStackList) { - FluidStack fluidStack = stack.getFluidStack(); - writeFluid(fluidStack.getFluid(), out); - out.writeLong(fluidStack.amount); - } - break; - case 1: - writeFluid(this.currentFluid, out); - break; - case 2: - break; - case 3: - out.writeBoolean(this.hasTermHandler); - break; - } - } + private IItemList fluidStackList; + private Fluid currentFluid; + Iterable change; + private boolean hasTermHandler; + + @SuppressWarnings("unused") + public PacketFluidStorage() {} + + public PacketFluidStorage(EntityPlayer _player, Iterable _change, IItemList _list) { + super(_player); + this.mode = 4; + this.change = _change; + this.fluidStackList = _list; + } + + public PacketFluidStorage(EntityPlayer _player) { + super(_player); + this.mode = 2; + } + + public PacketFluidStorage(EntityPlayer _player, boolean _hasTermHandler) { + super(_player); + this.mode = 3; + this.hasTermHandler = _hasTermHandler; + } + + public PacketFluidStorage(EntityPlayer _player, Fluid _currentFluid) { + super(_player); + this.mode = 1; + this.currentFluid = _currentFluid; + } + + public PacketFluidStorage(EntityPlayer _player, IItemList _list) { + super(_player); + this.mode = 0; + this.fluidStackList = _list; + } + + @Override + public void execute() { + switch (this.mode) { + case 0: + case0(); + break; + case 1: + if (this.player != null && this.player.openContainer instanceof ContainerFluidStorage) { + ((ContainerFluidStorage) this.player.openContainer).receiveSelectedFluid(this.currentFluid); + } else if (this.player != null && Integration.Mods.MEKANISMGAS.isEnabled() + && this.player.openContainer instanceof ContainerGasStorage) { + ((ContainerGasStorage) this.player.openContainer).receiveSelectedFluid(this.currentFluid); + } + break; + case 2: + if (this.player != null) { + if (!this.player.worldObj.isRemote) { + if (this.player.openContainer instanceof ContainerFluidStorage) { + ((ContainerFluidStorage) this.player.openContainer).forceFluidUpdate(); + ((ContainerFluidStorage) this.player.openContainer).doWork(); + } else if (this.player.openContainer instanceof ContainerGasStorage + && Integration.Mods.MEKANISMGAS.isEnabled()) { + ((ContainerGasStorage) this.player.openContainer).forceFluidUpdate(); + ((ContainerGasStorage) this.player.openContainer).doWork(); + } + } + } + break; + case 3: + case3(); + break; + case 4: + case4(); + break; + } + } + + @SideOnly(Side.CLIENT) + public void case4() { + if (this.player != null && this.player.isClientWorld()) { + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiFluidStorage) { + ContainerFluidStorage container = (ContainerFluidStorage) ((GuiFluidStorage) gui).inventorySlots; + container.updateFluidList(this.fluidStackList, true); + } else if (gui instanceof GuiGasStorage) { + ContainerGasStorage container = (ContainerGasStorage) ((GuiGasStorage) gui).inventorySlots; + container.updateFluidList(this.fluidStackList, true); + } + } + } + + @SideOnly(Side.CLIENT) + private void case0() { + if (this.player != null && this.player.isClientWorld()) { + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiFluidStorage) { + ContainerFluidStorage container = (ContainerFluidStorage) ((GuiFluidStorage) gui).inventorySlots; + container.updateFluidList(this.fluidStackList); + } else if (gui instanceof GuiGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) { + ContainerGasStorage container = (ContainerGasStorage) ((GuiGasStorage) gui).inventorySlots; + container.updateFluidList(this.fluidStackList); + } + } + } + + @SideOnly(Side.CLIENT) + private void case3() { + if (this.player != null && this.player.isClientWorld()) { + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiFluidStorage) { + ContainerFluidStorage container = (ContainerFluidStorage) ((GuiFluidStorage) gui).inventorySlots; + container.hasWirelessTermHandler = this.hasTermHandler; + } else if (gui instanceof GuiGasStorage && Integration.Mods.MEKANISMGAS.isEnabled()) { + ContainerGasStorage container = (ContainerGasStorage) ((GuiGasStorage) gui).inventorySlots; + container.hasWirelessTermHandler = this.hasTermHandler; + } + } + } + + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + case 4: + this.fluidStackList = AEApi.instance().storage().createFluidList(); + while (in.readableBytes() > 0) { + Fluid fluid = readFluid(in); + long fluidAmount = in.readLong(); + if (fluid != null) { + IAEFluidStack stack = AEApi.instance().storage().createFluidStack(new FluidStack(fluid, 1)); + stack.setStackSize(fluidAmount); + this.fluidStackList.add(stack); + } + } + break; + case 1: + this.currentFluid = readFluid(in); + break; + case 2: + break; + case 3: + this.hasTermHandler = in.readBoolean(); + break; + } + } + + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + for (IAEFluidStack stack : this.fluidStackList) { + FluidStack fluidStack = stack.getFluidStack(); + writeFluid(fluidStack.getFluid(), out); + out.writeLong(fluidStack.amount); + } + break; + case 1: + writeFluid(this.currentFluid, out); + break; + case 2: + break; + case 3: + out.writeBoolean(this.hasTermHandler); + break; + case 4: + for (IAEFluidStack stack : this.change) { + writeFluid(stack.getFluid(), out); + out.writeLong(stack.getStackSize()); + } + break; + } + } } diff --git a/src/main/scala/extracells/network/packet/part/PacketFluidTerminal.java b/src/main/scala/extracells/network/packet/part/PacketFluidTerminal.java index 602368471..f55de9341 100644 --- a/src/main/scala/extracells/network/packet/part/PacketFluidTerminal.java +++ b/src/main/scala/extracells/network/packet/part/PacketFluidTerminal.java @@ -1,5 +1,11 @@ package extracells.network.packet.part; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.AEApi; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IItemList; @@ -12,150 +18,177 @@ import extracells.network.AbstractPacket; import extracells.part.PartFluidTerminal; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; public class PacketFluidTerminal extends AbstractPacket { - IItemList fluidStackList; - Fluid currentFluid; - PartFluidTerminal terminalFluid; - - @SuppressWarnings("unused") - public PacketFluidTerminal() {} - - public PacketFluidTerminal(EntityPlayer _player, Fluid _currentFluid) { - super(_player); - this.mode = 2; - this.currentFluid = _currentFluid; - } - - public PacketFluidTerminal(EntityPlayer _player, Fluid _currentFluid, - PartFluidTerminal _terminalFluid) { - super(_player); - this.mode = 1; - this.currentFluid = _currentFluid; - this.terminalFluid = _terminalFluid; - } - - public PacketFluidTerminal(EntityPlayer _player, - IItemList _list) { - super(_player); - this.mode = 0; - this.fluidStackList = _list; - } - - public PacketFluidTerminal(EntityPlayer _player, - PartFluidTerminal _terminalFluid) { - super(_player); - this.mode = 3; - this.terminalFluid = _terminalFluid; - } - - @Override - public void execute() { - switch (this.mode) { - case 0: - case0(); - break; - case 1: - this.terminalFluid.setCurrentFluid(this.currentFluid); - break; - case 2: - case2(); - break; - case 3: - if (this.player != null && this.player.openContainer instanceof ContainerFluidTerminal) { - ContainerFluidTerminal fluidContainer = (ContainerFluidTerminal) this.player.openContainer; - fluidContainer.forceFluidUpdate(); - this.terminalFluid.sendCurrentFluid(fluidContainer); - } else if (this.player != null && this.player.openContainer instanceof ContainerGasTerminal) { - ContainerGasTerminal fluidContainer = (ContainerGasTerminal) this.player.openContainer; - fluidContainer.forceFluidUpdate(); - this.terminalFluid.sendCurrentFluid(fluidContainer); - } - break; - } - } - - @SideOnly(Side.CLIENT) - public void case0(){ - if (this.player != null && this.player.isClientWorld()) { - Gui gui = Minecraft.getMinecraft().currentScreen; - if (gui instanceof GuiFluidTerminal) { - ContainerFluidTerminal container = (ContainerFluidTerminal) ((GuiFluidTerminal) gui).inventorySlots; - container.updateFluidList(this.fluidStackList); - } else if (gui instanceof GuiGasTerminal) { - ContainerGasTerminal container = (ContainerGasTerminal) ((GuiGasTerminal) gui).inventorySlots; - container.updateFluidList(this.fluidStackList); - } - } - } - - @SideOnly(Side.CLIENT) - public void case2(){ - if (this.player != null && Minecraft.getMinecraft().currentScreen instanceof GuiFluidTerminal) { - GuiFluidTerminal gui = (GuiFluidTerminal) Minecraft.getMinecraft().currentScreen; - ((ContainerFluidTerminal) gui.getContainer()).receiveSelectedFluid(this.currentFluid); - } else if (this.player != null && Minecraft.getMinecraft().currentScreen instanceof GuiGasTerminal) { - GuiGasTerminal gui = (GuiGasTerminal) Minecraft.getMinecraft().currentScreen; - ((ContainerGasTerminal) gui.getContainer()).receiveSelectedFluid(this.currentFluid); - } - } - - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - this.fluidStackList = AEApi.instance().storage().createFluidList(); - while (in.readableBytes() > 0) { - Fluid fluid = readFluid(in); - long fluidAmount = in.readLong(); - if (fluid == null || fluidAmount <= 0) { - continue; - } - IAEFluidStack stack = AEApi.instance().storage() - .createFluidStack(new FluidStack(fluid, 1)); - stack.setStackSize(fluidAmount); - this.fluidStackList.add(stack); - } - break; - case 1: - this.terminalFluid = (PartFluidTerminal) readPart(in); - this.currentFluid = readFluid(in); - break; - case 2: - this.currentFluid = readFluid(in); - break; - case 3: - this.terminalFluid = (PartFluidTerminal) readPart(in); - break; - } - } - - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - for (IAEFluidStack stack : this.fluidStackList) { - FluidStack fluidStack = stack.getFluidStack(); - writeFluid(fluidStack.getFluid(), out); - out.writeLong(fluidStack.amount); - } - break; - case 1: - writePart(this.terminalFluid, out); - writeFluid(this.currentFluid, out); - break; - case 2: - writeFluid(this.currentFluid, out); - break; - case 3: - writePart(this.terminalFluid, out); - break; - } - } + IItemList fluidStackList; + Fluid currentFluid; + PartFluidTerminal terminalFluid; + + Iterable change; + + @SuppressWarnings("unused") + public PacketFluidTerminal() {} + + public PacketFluidTerminal(EntityPlayer _player, Iterable _change, IItemList _list) { + super(_player); + this.mode = 4; + this.change = _change; + this.fluidStackList = _list; + } + + public PacketFluidTerminal(EntityPlayer _player, Fluid _currentFluid) { + super(_player); + this.mode = 2; + this.currentFluid = _currentFluid; + } + + public PacketFluidTerminal(EntityPlayer _player, Fluid _currentFluid, PartFluidTerminal _terminalFluid) { + super(_player); + this.mode = 1; + this.currentFluid = _currentFluid; + this.terminalFluid = _terminalFluid; + } + + public PacketFluidTerminal(EntityPlayer _player, IItemList _list) { + super(_player); + this.mode = 0; + this.fluidStackList = _list; + } + + public PacketFluidTerminal(EntityPlayer _player, PartFluidTerminal _terminalFluid) { + super(_player); + this.mode = 3; + this.terminalFluid = _terminalFluid; + } + + @Override + public void execute() { + switch (this.mode) { + case 0: + case0(); + break; + case 1: + this.terminalFluid.setCurrentFluid(this.currentFluid); + break; + case 2: + case2(); + break; + case 3: + case3(); + break; + case 4: + case4(); + break; + } + } + + @SideOnly(Side.CLIENT) + public void case4() { + if (this.player != null && this.player.isClientWorld()) { + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiFluidTerminal) { + ContainerFluidTerminal container = (ContainerFluidTerminal) ((GuiFluidTerminal) gui).inventorySlots; + container.updateFluidList(this.fluidStackList, true); + } else if (gui instanceof GuiGasTerminal) { + ContainerGasTerminal container = (ContainerGasTerminal) ((GuiGasTerminal) gui).inventorySlots; + container.updateFluidList(this.fluidStackList, true); + } + } + } + + public void case3() { + if (this.player != null && this.player.openContainer instanceof ContainerFluidTerminal) { + ContainerFluidTerminal fluidContainer = (ContainerFluidTerminal) this.player.openContainer; + fluidContainer.forceFluidUpdate(); + this.terminalFluid.sendCurrentFluid(fluidContainer); + } else if (this.player != null && this.player.openContainer instanceof ContainerGasTerminal) { + ContainerGasTerminal fluidContainer = (ContainerGasTerminal) this.player.openContainer; + fluidContainer.forceFluidUpdate(); + this.terminalFluid.sendCurrentFluid(fluidContainer); + } + } + + @SideOnly(Side.CLIENT) + public void case0() { + if (this.player != null && this.player.isClientWorld()) { + Gui gui = Minecraft.getMinecraft().currentScreen; + if (gui instanceof GuiFluidTerminal) { + ContainerFluidTerminal container = (ContainerFluidTerminal) ((GuiFluidTerminal) gui).inventorySlots; + container.updateFluidList(this.fluidStackList); + } else if (gui instanceof GuiGasTerminal) { + ContainerGasTerminal container = (ContainerGasTerminal) ((GuiGasTerminal) gui).inventorySlots; + container.updateFluidList(this.fluidStackList); + } + } + } + + @SideOnly(Side.CLIENT) + public void case2() { + if (this.player != null && Minecraft.getMinecraft().currentScreen instanceof GuiFluidTerminal) { + GuiFluidTerminal gui = (GuiFluidTerminal) Minecraft.getMinecraft().currentScreen; + ((ContainerFluidTerminal) gui.getContainer()).receiveSelectedFluid(this.currentFluid); + } else if (this.player != null && Minecraft.getMinecraft().currentScreen instanceof GuiGasTerminal) { + GuiGasTerminal gui = (GuiGasTerminal) Minecraft.getMinecraft().currentScreen; + ((ContainerGasTerminal) gui.getContainer()).receiveSelectedFluid(this.currentFluid); + } + } + + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + case 4: + this.fluidStackList = AEApi.instance().storage().createFluidList(); + while (in.readableBytes() > 0) { + Fluid fluid = readFluid(in); + long fluidAmount = in.readLong(); + if (fluid == null) { + continue; + } + IAEFluidStack stack = AEApi.instance().storage().createFluidStack(new FluidStack(fluid, 1)); + stack.setStackSize(fluidAmount); + this.fluidStackList.add(stack); + } + break; + case 1: + this.terminalFluid = (PartFluidTerminal) readPart(in); + this.currentFluid = readFluid(in); + break; + case 2: + this.currentFluid = readFluid(in); + break; + case 3: + this.terminalFluid = (PartFluidTerminal) readPart(in); + break; + } + } + + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + for (IAEFluidStack stack : this.fluidStackList) { + writeFluid(stack.getFluid(), out); + out.writeLong(stack.getStackSize()); + } + break; + case 1: + writePart(this.terminalFluid, out); + writeFluid(this.currentFluid, out); + break; + case 2: + writeFluid(this.currentFluid, out); + break; + case 3: + writePart(this.terminalFluid, out); + break; + case 4: + for (IAEFluidStack stack : this.change) { + writeFluid(stack.getFluid(), out); + out.writeLong(stack.getStackSize()); + } + break; + } + } } diff --git a/src/main/scala/extracells/network/packet/part/PacketOreDictExport.java b/src/main/scala/extracells/network/packet/part/PacketOreDictExport.java index e830a712f..d2b2c6d04 100644 --- a/src/main/scala/extracells/network/packet/part/PacketOreDictExport.java +++ b/src/main/scala/extracells/network/packet/part/PacketOreDictExport.java @@ -1,5 +1,8 @@ package extracells.network.packet.part; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.Container; + import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @@ -7,71 +10,64 @@ import extracells.gui.GuiOreDictExport; import extracells.network.AbstractPacket; import io.netty.buffer.ByteBuf; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.Container; public class PacketOreDictExport extends AbstractPacket { - private String filter; - private Side side; - - public PacketOreDictExport() {} + private String filter; + private Side side; - public PacketOreDictExport(EntityPlayer _player, String filter, Side side) { - super(_player); - this.mode = 0; - this.filter = filter; - this.side = side; - } + public PacketOreDictExport() {} - @Override - public void execute() { - switch (this.mode) { - case 0: - if (this.side.isClient()) - try { - handleClient(); - } catch (Throwable e) {} - else - handleServer(); - break; - } - } + public PacketOreDictExport(EntityPlayer _player, String filter, Side side) { + super(_player); + this.mode = 0; + this.filter = filter; + this.side = side; + } - @SideOnly(Side.CLIENT) - private void handleClient() { - GuiOreDictExport.updateFilter(this.filter); - } + @Override + public void execute() { + switch (this.mode) { + case 0: + if (this.side.isClient()) try { + handleClient(); + } catch (Throwable e) {} + else handleServer(); + break; + } + } - private void handleServer() { - Container con = this.player.openContainer; - if (con != null && con instanceof ContainerOreDictExport) { - ContainerOreDictExport c = (ContainerOreDictExport) con; - c.part.filter = this.filter; - } - } + @SideOnly(Side.CLIENT) + private void handleClient() { + GuiOreDictExport.updateFilter(this.filter); + } - @Override - public void readData(ByteBuf in) { - switch (this.mode) { - case 0: - if (in.readBoolean()) - this.side = Side.SERVER; - else - this.side = Side.CLIENT; - this.filter = ByteBufUtils.readUTF8String(in); - break; - } - } + private void handleServer() { + Container con = this.player.openContainer; + if (con != null && con instanceof ContainerOreDictExport) { + ContainerOreDictExport c = (ContainerOreDictExport) con; + c.part.setFilter(this.filter); + } + } - @Override - public void writeData(ByteBuf out) { - switch (this.mode) { - case 0: - out.writeBoolean(this.side.isServer()); - ByteBufUtils.writeUTF8String(out, this.filter); - break; + @Override + public void readData(ByteBuf in) { + switch (this.mode) { + case 0: + if (in.readBoolean()) this.side = Side.SERVER; + else this.side = Side.CLIENT; + this.filter = ByteBufUtils.readUTF8String(in); + break; + } + } - } - } + @Override + public void writeData(ByteBuf out) { + switch (this.mode) { + case 0: + out.writeBoolean(this.side.isServer()); + ByteBufUtils.writeUTF8String(out, this.filter); + break; + } + } } diff --git a/src/main/scala/extracells/part/PartBattery.java b/src/main/scala/extracells/part/PartBattery.java index 01d3adf5e..043d7ef1f 100644 --- a/src/main/scala/extracells/part/PartBattery.java +++ b/src/main/scala/extracells/part/PartBattery.java @@ -1,5 +1,15 @@ package extracells.part; +import java.io.IOException; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.IIcon; + import appeng.api.config.AccessRestriction; import appeng.api.config.Actionable; import appeng.api.config.PowerMultiplier; @@ -17,177 +27,150 @@ import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.IIcon; - -import java.io.IOException; -import java.util.List; -public class PartBattery extends PartECBase implements IAEPowerStorage, - IInventoryUpdateReceiver { - - private IIcon batteryIcon = TextureManager.BATTERY_FRONT.getTexture(); - private ItemStack battery; - IAEItemPowerStorage handler; - private ECPrivateInventory inventory = new ECPrivateInventory( - "extracells.part.battery", 1, 1) { - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return itemStack != null - && itemStack.getItem() instanceof IAEItemPowerStorage; - } - }; - - @Override - public void getDrops( List drops, boolean wrenched) { - for (ItemStack stack : inventory.slots) { - if (stack == null) - continue; - drops.add(stack); - } - } - - @Override - public int cableConnectionRenderTo() { - return 2; - } - - @Override - public double extractAEPower(double amt, Actionable mode, - PowerMultiplier usePowerMultiplier) { - if (this.handler == null || this.battery == null) - return 0; - return this.handler.extractAEPower( - mode == Actionable.MODULATE ? this.battery : this.battery - .copy(), usePowerMultiplier.multiply(amt)); - } - - @Override - public double getAECurrentPower() { - if (this.handler == null || this.battery == null) - return 0; - return this.handler.getAECurrentPower(this.battery); - } - - @Override - public double getAEMaxPower() { - if (this.handler == null || this.battery == null) - return 0; - return this.handler.getAEMaxPower(this.battery); - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 14, 14, 14, 16); - } - - @Override - public AccessRestriction getPowerFlow() { - if (this.handler == null || this.battery == null) - return AccessRestriction.NO_ACCESS; - return this.handler.getPowerFlow(this.battery); - } - - @Override - public double injectAEPower(double amt, Actionable mode) { - if (this.handler == null || this.battery == null) - return 0; - return this.handler.injectAEPower( - mode == Actionable.MODULATE ? this.battery : this.battery - .copy(), amt); - } - - @Override - public boolean isAEPublicPowerStorage() { - return true; - } - - @Override - public void onInventoryChanged() { - this.battery = this.inventory.getStackInSlot(0); - if (this.battery != null - && this.battery.getItem() instanceof IAEItemPowerStorage) { - this.batteryIcon = this.battery.getIconIndex(); - this.handler = (IAEItemPowerStorage) this.battery.getItem(); - } else { - this.batteryIcon = null; - this.handler = null; - } - IGridNode node = getGridNode(); - if (node != null) { - IGrid grid = node.getGrid(); - if (grid != null) { - grid.postEvent(new MENetworkPowerStorage(this, - MENetworkPowerStorage.PowerEventType.REQUEST_POWER)); - } - getHost().markForUpdate(); - } - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - this.inventory.readFromNBT(data.getTagList("inventory", 10)); - onInventoryChanged(); - } - - @Override - public boolean readFromStream(ByteBuf data) throws IOException { - super.readFromStream(data); - String iconName = AbstractPacket.readString(data); - if (!iconName.equals("none")) { - this.batteryIcon = ((TextureMap) Minecraft.getMinecraft() - .getTextureManager() - .getTexture(TextureMap.locationBlocksTexture)) - .getAtlasSprite(iconName); - } else { - this.batteryIcon = TextureManager.BATTERY_FRONT.getTexture(); - } - return true; - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - IIcon side = TextureManager.BUS_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.BATTERY_FRONT.getTextures()[0], side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderInventoryBox(renderer); - - rh.setBounds(5, 5, 13, 11, 11, 14); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - IIcon side = TextureManager.BUS_SIDE.getTexture(); - rh.setTexture(side, side, side, this.batteryIcon, side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - - rh.setBounds(5, 5, 13, 11, 11, 14); - renderStaticBusLights(x, y, z, rh, renderer); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - data.setTag("inventory", this.inventory.writeToNBT()); - } - - @Override - public void writeToStream(ByteBuf data) throws IOException { - super.writeToStream(data); - AbstractPacket.writeString(this.battery != null ? this.battery - .getItem().getIconIndex(this.battery).getIconName() : "none", - data); - } +public class PartBattery extends PartECBase implements IAEPowerStorage, IInventoryUpdateReceiver { + + private IIcon batteryIcon = TextureManager.BATTERY_FRONT.getTexture(); + private ItemStack battery; + IAEItemPowerStorage handler; + private ECPrivateInventory inventory = new ECPrivateInventory("extracells.part.battery", 1, 1) { + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return itemStack != null && itemStack.getItem() instanceof IAEItemPowerStorage; + } + }; + + @Override + public void getDrops(List drops, boolean wrenched) { + for (ItemStack stack : inventory.slots) { + if (stack == null) continue; + drops.add(stack); + } + } + + @Override + public int cableConnectionRenderTo() { + return 2; + } + + @Override + public double extractAEPower(double amt, Actionable mode, PowerMultiplier usePowerMultiplier) { + if (this.handler == null || this.battery == null) return 0; + return this.handler.extractAEPower( + mode == Actionable.MODULATE ? this.battery : this.battery.copy(), + usePowerMultiplier.multiply(amt)); + } + + @Override + public double getAECurrentPower() { + if (this.handler == null || this.battery == null) return 0; + return this.handler.getAECurrentPower(this.battery); + } + + @Override + public double getAEMaxPower() { + if (this.handler == null || this.battery == null) return 0; + return this.handler.getAEMaxPower(this.battery); + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + } + + @Override + public AccessRestriction getPowerFlow() { + if (this.handler == null || this.battery == null) return AccessRestriction.NO_ACCESS; + return this.handler.getPowerFlow(this.battery); + } + + @Override + public double injectAEPower(double amt, Actionable mode) { + if (this.handler == null || this.battery == null) return 0; + return this.handler.injectAEPower(mode == Actionable.MODULATE ? this.battery : this.battery.copy(), amt); + } + + @Override + public boolean isAEPublicPowerStorage() { + return true; + } + + @Override + public void onInventoryChanged() { + this.battery = this.inventory.getStackInSlot(0); + if (this.battery != null && this.battery.getItem() instanceof IAEItemPowerStorage) { + this.batteryIcon = this.battery.getIconIndex(); + this.handler = (IAEItemPowerStorage) this.battery.getItem(); + } else { + this.batteryIcon = null; + this.handler = null; + } + IGridNode node = getGridNode(); + if (node != null) { + IGrid grid = node.getGrid(); + if (grid != null) { + grid.postEvent(new MENetworkPowerStorage(this, MENetworkPowerStorage.PowerEventType.REQUEST_POWER)); + } + getHost().markForUpdate(); + } + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.inventory.readFromNBT(data.getTagList("inventory", 10)); + onInventoryChanged(); + } + + @Override + public boolean readFromStream(ByteBuf data) throws IOException { + super.readFromStream(data); + String iconName = AbstractPacket.readString(data); + if (!iconName.equals("none")) { + this.batteryIcon = ((TextureMap) Minecraft.getMinecraft().getTextureManager() + .getTexture(TextureMap.locationBlocksTexture)).getAtlasSprite(iconName); + } else { + this.batteryIcon = TextureManager.BATTERY_FRONT.getTexture(); + } + return true; + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + IIcon side = TextureManager.BUS_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.BATTERY_FRONT.getTextures()[0], side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + renderInventoryBusLights(rh, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + IIcon side = TextureManager.BUS_SIDE.getTexture(); + rh.setTexture(side, side, side, this.batteryIcon, side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + renderStaticBusLights(x, y, z, rh, renderer); + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setTag("inventory", this.inventory.writeToNBT()); + } + + @Override + public void writeToStream(ByteBuf data) throws IOException { + super.writeToStream(data); + AbstractPacket.writeString( + this.battery != null ? this.battery.getItem().getIconIndex(this.battery).getIconName() : "none", + data); + } } diff --git a/src/main/scala/extracells/part/PartDrive.java b/src/main/scala/extracells/part/PartDrive.java index 38eb78167..b64e2a22e 100644 --- a/src/main/scala/extracells/part/PartDrive.java +++ b/src/main/scala/extracells/part/PartDrive.java @@ -1,5 +1,19 @@ package extracells.part; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.AEApi; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; @@ -22,300 +36,262 @@ import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; import io.netty.buffer.ByteBuf; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -public class PartDrive extends PartECBase implements ICellContainer, - IInventoryUpdateReceiver { - - private int priority = 0; // TODO - private short[] blinkTimers; // TODO - private byte[] cellStatuses = new byte[6]; - List fluidHandlers = new ArrayList(); - List itemHandlers = new ArrayList(); - private ECPrivateInventory inventory = new ECPrivateInventory( - "extracells.part.drive", 6, 1, this) { - - ICellRegistry cellRegistry = AEApi.instance().registries().cell(); - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return this.cellRegistry.isCellHandled(itemStack); - } - }; - - @Override - public void addToWorld() { - super.addToWorld(); - onInventoryChanged(); - } - - @Override - public void blinkCell(int slot) { - if (slot > 0 && slot < this.blinkTimers.length) - this.blinkTimers[slot] = 15; - } - - @Override - public int cableConnectionRenderTo() { - return 2; - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 14, 14, 14, 16); - bch.addBox(5, 5, 13, 11, 11, 14); - } - - @Override - public List getCellArray(StorageChannel channel) { - if (!isActive()) - return new ArrayList(); - return channel == StorageChannel.ITEMS ? this.itemHandlers - : this.fluidHandlers; - } - - @Override - public Object getClientGuiElement(EntityPlayer player) { - return new GuiDrive(this, player); - } - - public int getColorByStatus(int status) { - switch (status) { - case 1: - return 0x00FF00; - case 2: - return 0xFFFF00; - case 3: - return 0xFF0000; - default: - return 0x000000; - } - } - - @Override - public void getDrops(List drops, boolean wrenched) { - if (!wrenched) - for (int i = 0; i < this.inventory.getSizeInventory(); i++) { - ItemStack cell = this.inventory.getStackInSlot(i); - if (cell != null) - drops.add(cell); - } - } - - public ECPrivateInventory getInventory() { - return this.inventory; - } - - @Override - public int getPriority() { - return this.priority; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerDrive(this, player); - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, - (IPart) this)) { - return super.onActivate(player, pos); - } - return false; - } - - @Override - public void onInventoryChanged() { - this.itemHandlers = updateHandlers(StorageChannel.ITEMS); - this.fluidHandlers = updateHandlers(StorageChannel.FLUIDS); - for (int i = 0; i < this.cellStatuses.length; i++) { - ItemStack stackInSlot = this.inventory.getStackInSlot(i); - IMEInventoryHandler inventoryHandler = AEApi.instance() - .registries().cell() - .getCellInventory(stackInSlot, null, StorageChannel.ITEMS); - if (inventoryHandler == null) - inventoryHandler = AEApi - .instance() - .registries() - .cell() - .getCellInventory(stackInSlot, null, - StorageChannel.FLUIDS); - - ICellHandler cellHandler = AEApi.instance().registries().cell() - .getHandler(stackInSlot); - if (cellHandler == null || inventoryHandler == null) { - this.cellStatuses[i] = 0; - } else { - this.cellStatuses[i] = (byte) cellHandler.getStatusForCell( - stackInSlot, inventoryHandler); - } - } - IGridNode node = getGridNode(); - if (node != null) { - IGrid grid = node.getGrid(); - if (grid != null) { - grid.postEvent(new MENetworkCellArrayUpdate()); - } - getHost().markForUpdate(); - } - saveData(); - } - - @MENetworkEventSubscribe - public void powerChange(MENetworkPowerStatusChange event) { - IGridNode node = getGridNode(); - if (node != null) { - boolean isNowActive = node.isActive(); - if (isNowActive != isActive()) { - setActive(isNowActive); - onNeighborChanged(); - getHost().markForUpdate(); - } - } - node.getGrid().postEvent(new MENetworkCellArrayUpdate()); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - this.inventory.readFromNBT(data.getTagList("inventory", 10)); - onInventoryChanged(); - } - - @Override - public boolean readFromStream(ByteBuf data) throws IOException { - super.readFromStream(data); - for (int i = 0; i < this.cellStatuses.length; i++) - this.cellStatuses[i] = data.readByte(); - return true; - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - IIcon side = TextureManager.DRIVE_SIDE.getTexture(); - IIcon[] front = TextureManager.DRIVE_FRONT.getTextures(); - rh.setBounds(2, 2, 14, 14, 14, 15.999F); - rh.renderInventoryFace(front[3], ForgeDirection.SOUTH, renderer); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.setTexture(side, side, side, front[0], side, side); - rh.renderInventoryBox(renderer); - - rh.setBounds(5, 5, 13, 11, 11, 14); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - IIcon side = TextureManager.DRIVE_SIDE.getTexture(); - IIcon[] front = TextureManager.DRIVE_FRONT.getTextures(); - rh.setBounds(2, 2, 14, 14, 14, 15.999F); - rh.renderFace(x, y, z, front[3], ForgeDirection.SOUTH, renderer); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.setTexture(side, side, side, front[0], side, side); - rh.renderBlock(x, y, z, renderer); - - ts.setColorOpaque_I(0xFFFFFF); - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 3; j++) { - if (this.cellStatuses[j + i * 3] > 0) { - if (getSide() == ForgeDirection.EAST - || getSide() == ForgeDirection.WEST ? i == 1 - : i == 0) - rh.setBounds(8, 12 - j * 3, 14, 13, 10 - j * 3, 16); - else - rh.setBounds(3, 12 - j * 3, 14, 8, 10 - j * 3, 16); - rh.renderFace(x, y, z, front[1], ForgeDirection.SOUTH, - renderer); - } - } - } - - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 3; j++) { - if (getSide() == ForgeDirection.EAST - || getSide() == ForgeDirection.WEST ? i == 1 : i == 0) - rh.setBounds(8, 12 - j * 3, 14, 13, 10 - j * 3, 16); - else - rh.setBounds(3, 12 - j * 3, 14, 8, 10 - j * 3, 16); - ts.setColorOpaque_I(getColorByStatus(this.cellStatuses[j + i - * 3])); - ts.setBrightness(13 << 20 | 13 << 4); - rh.renderFace(x, y, z, front[2], ForgeDirection.SOUTH, renderer); - } - } - rh.setBounds(5, 5, 13, 11, 11, 14); - renderStaticBusLights(x, y, z, rh, renderer); - } - - @Override - public void saveChanges(IMEInventory cellInventory) { - getHost().markForSave(); - } - - @Override - public void setPartHostInfo(ForgeDirection _side, IPartHost _host, - TileEntity _tile) { - super.setPartHostInfo(_side, _host, _tile); - onInventoryChanged(); - } - - @MENetworkEventSubscribe - public void updateChannels(MENetworkChannelsChanged channel) { - IGridNode node = getGridNode(); - if (node != null) { - boolean isNowActive = node.isActive(); - if (isNowActive != isActive()) { - setActive(isNowActive); - onNeighborChanged(); - getHost().markForUpdate(); - } - } - node.getGrid().postEvent(new MENetworkCellArrayUpdate()); - } - - private List updateHandlers(StorageChannel channel) { - ICellRegistry cellRegistry = AEApi.instance().registries().cell(); - List handlers = new ArrayList(); - for (int i = 0; i < this.inventory.getSizeInventory(); i++) { - ItemStack cell = this.inventory.getStackInSlot(i); - if (cellRegistry.isCellHandled(cell)) { - IMEInventoryHandler cellInventory = cellRegistry - .getCellInventory(cell, null, channel); - if (cellInventory != null) - handlers.add(cellInventory); - } - } - return handlers; - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - data.setTag("inventory", this.inventory.writeToNBT()); - } - - @Override - public void writeToStream(ByteBuf data) throws IOException { - super.writeToStream(data); - for (byte aCellStati : this.cellStatuses) { - data.writeByte(aCellStati); - } - } +public class PartDrive extends PartECBase implements ICellContainer, IInventoryUpdateReceiver { + + private int priority = 0; // TODO + private short[] blinkTimers; // TODO + private byte[] cellStatuses = new byte[6]; + List fluidHandlers = new ArrayList(); + List itemHandlers = new ArrayList(); + private ECPrivateInventory inventory = new ECPrivateInventory("extracells.part.drive", 6, 1, this) { + + ICellRegistry cellRegistry = AEApi.instance().registries().cell(); + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return this.cellRegistry.isCellHandled(itemStack); + } + }; + + @Override + public void addToWorld() { + super.addToWorld(); + onInventoryChanged(); + } + + @Override + public void blinkCell(int slot) { + if (slot > 0 && slot < this.blinkTimers.length) this.blinkTimers[slot] = 15; + } + + @Override + public int cableConnectionRenderTo() { + return 2; + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 13, 11, 11, 14); + } + + @Override + public List getCellArray(StorageChannel channel) { + if (!isActive()) return new ArrayList(); + return channel == StorageChannel.ITEMS ? this.itemHandlers : this.fluidHandlers; + } + + @Override + public Object getClientGuiElement(EntityPlayer player) { + return new GuiDrive(this, player); + } + + public int getColorByStatus(int status) { + switch (status) { + case 1: + return 0x00FF00; + case 2: + return 0xFFFF00; + case 3: + return 0xFF0000; + default: + return 0x000000; + } + } + + @Override + public void getDrops(List drops, boolean wrenched) { + if (!wrenched) for (int i = 0; i < this.inventory.getSizeInventory(); i++) { + ItemStack cell = this.inventory.getStackInSlot(i); + if (cell != null) drops.add(cell); + } + } + + public ECPrivateInventory getInventory() { + return this.inventory; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerDrive(this, player); + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this)) { + return super.onActivate(player, pos); + } + return false; + } + + @Override + public void onInventoryChanged() { + this.itemHandlers = updateHandlers(StorageChannel.ITEMS); + this.fluidHandlers = updateHandlers(StorageChannel.FLUIDS); + for (int i = 0; i < this.cellStatuses.length; i++) { + ItemStack stackInSlot = this.inventory.getStackInSlot(i); + IMEInventoryHandler inventoryHandler = AEApi.instance().registries().cell() + .getCellInventory(stackInSlot, null, StorageChannel.ITEMS); + if (inventoryHandler == null) inventoryHandler = AEApi.instance().registries().cell() + .getCellInventory(stackInSlot, null, StorageChannel.FLUIDS); + + ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler(stackInSlot); + if (cellHandler == null || inventoryHandler == null) { + this.cellStatuses[i] = 0; + } else { + this.cellStatuses[i] = (byte) cellHandler.getStatusForCell(stackInSlot, inventoryHandler); + } + } + IGridNode node = getGridNode(); + if (node != null) { + IGrid grid = node.getGrid(); + if (grid != null) { + grid.postEvent(new MENetworkCellArrayUpdate()); + } + getHost().markForUpdate(); + } + saveData(); + } + + @MENetworkEventSubscribe + public void powerChange(MENetworkPowerStatusChange event) { + IGridNode node = getGridNode(); + if (node != null) { + boolean isNowActive = node.isActive(); + if (isNowActive != isActive()) { + setActive(isNowActive); + onNeighborChanged(); + getHost().markForUpdate(); + } + } + node.getGrid().postEvent(new MENetworkCellArrayUpdate()); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.inventory.readFromNBT(data.getTagList("inventory", 10)); + onInventoryChanged(); + } + + @Override + public boolean readFromStream(ByteBuf data) throws IOException { + super.readFromStream(data); + for (int i = 0; i < this.cellStatuses.length; i++) this.cellStatuses[i] = data.readByte(); + return true; + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + IIcon side = TextureManager.DRIVE_SIDE.getTexture(); + IIcon[] front = TextureManager.DRIVE_FRONT.getTextures(); + rh.setBounds(2, 2, 14, 14, 14, 15.999F); + rh.renderInventoryFace(front[3], ForgeDirection.SOUTH, renderer); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.setTexture(side, side, side, front[0], side, side); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + renderInventoryBusLights(rh, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + // Render Front Screen + IIcon side = TextureManager.DRIVE_SIDE.getTexture(); + IIcon[] front = TextureManager.DRIVE_FRONT.getTextures(); + rh.setBounds(2, 2, 14, 14, 14, 15.999F); + rh.renderFace(x, y, z, front[3], ForgeDirection.SOUTH, renderer); + + rh.setBounds(3, 3, 16, 13, 13, 16); + rh.setTexture(side, side, side, front[0], side, side); + rh.renderFace(x, y, z, front[0], ForgeDirection.SOUTH, renderer); + + Tessellator.instance.setColorOpaque_I(0xFFFFFF); + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 3; j++) { + if (this.cellStatuses[j + i * 3] > 0) { + if (getSide() == ForgeDirection.EAST || getSide() == ForgeDirection.WEST ? i == 1 : i == 0) + rh.setBounds(8, 12 - j * 3, 14, 13, 10 - j * 3, 16); + else rh.setBounds(3, 12 - j * 3, 14, 8, 10 - j * 3, 16); + rh.renderFace(x, y, z, front[1], ForgeDirection.SOUTH, renderer); + } + } + } + + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 3; j++) { + if (getSide() == ForgeDirection.EAST || getSide() == ForgeDirection.WEST ? i == 1 : i == 0) + rh.setBounds(8, 12 - j * 3, 14, 13, 10 - j * 3, 16); + else rh.setBounds(3, 12 - j * 3, 14, 8, 10 - j * 3, 16); + Tessellator.instance.setColorOpaque_I(getColorByStatus(this.cellStatuses[j + i * 3])); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + rh.renderFace(x, y, z, front[2], ForgeDirection.SOUTH, renderer); + } + } + + renderFrontPanel(x, y, z, rh, renderer); + renderBackPanel(x, y, z, rh, renderer); + renderPowerStatus(x, y, z, rh, renderer); + } + + @Override + public void saveChanges(IMEInventory cellInventory) { + getHost().markForSave(); + } + + @Override + public void setPartHostInfo(ForgeDirection _side, IPartHost _host, TileEntity _tile) { + super.setPartHostInfo(_side, _host, _tile); + onInventoryChanged(); + } + + @MENetworkEventSubscribe + public void updateChannels(MENetworkChannelsChanged channel) { + IGridNode node = getGridNode(); + if (node != null) { + boolean isNowActive = node.isActive(); + if (isNowActive != isActive()) { + setActive(isNowActive); + onNeighborChanged(); + getHost().markForUpdate(); + } + } + node.getGrid().postEvent(new MENetworkCellArrayUpdate()); + } + + private List updateHandlers(StorageChannel channel) { + ICellRegistry cellRegistry = AEApi.instance().registries().cell(); + List handlers = new ArrayList(); + for (int i = 0; i < this.inventory.getSizeInventory(); i++) { + ItemStack cell = this.inventory.getStackInSlot(i); + if (cellRegistry.isCellHandled(cell)) { + IMEInventoryHandler cellInventory = cellRegistry.getCellInventory(cell, null, channel); + if (cellInventory != null) handlers.add(cellInventory); + } + } + return handlers; + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setTag("inventory", this.inventory.writeToNBT()); + } + + @Override + public void writeToStream(ByteBuf data) throws IOException { + super.writeToStream(data); + for (byte aCellStati : this.cellStatuses) { + data.writeByte(aCellStati); + } + } } diff --git a/src/main/scala/extracells/part/PartECBase.java b/src/main/scala/extracells/part/PartECBase.java index 3fdde8474..5be83f34a 100644 --- a/src/main/scala/extracells/part/PartECBase.java +++ b/src/main/scala/extracells/part/PartECBase.java @@ -1,5 +1,24 @@ package extracells.part; +import java.io.IOException; +import java.util.List; +import java.util.Random; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.player.EntityPlayer; +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.IIcon; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.IFluidHandler; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.implementations.IPowerChannelState; @@ -17,6 +36,8 @@ import appeng.api.util.AECableType; import appeng.api.util.AEColor; import appeng.api.util.DimensionalCoord; +import appeng.client.texture.CableBusTextures; +import appeng.items.parts.ItemMultiPart; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Optional; import cpw.mods.fml.relauncher.Side; @@ -29,471 +50,469 @@ import extracells.render.TextureManager; import io.netty.buffer.ByteBuf; import mekanism.api.gas.IGasHandler; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityLivingBase; -import net.minecraft.entity.player.EntityPlayer; -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.IIcon; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.IFluidHandler; - -import java.io.IOException; -import java.util.List; -import java.util.Random; -public abstract class PartECBase implements IPart, IGridHost, IActionHost, - IPowerChannelState { - - private IGridNode node; - private ForgeDirection side; - private IPartHost host; - protected TileEntity tile; - private ECBaseGridBlock gridBlock; - private double powerUsage; - private TileEntity hostTile; - private IFluidHandler facingTank; - private Object facingGasTank; - private boolean redstonePowered; - private boolean isActive; - private boolean isPowerd = false; - private EntityPlayer owner; - - @Override - public void addToWorld() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) - return; - this.gridBlock = new ECBaseGridBlock(this); - this.node = AEApi.instance().createGridNode(this.gridBlock); - if (this.node != null) { - if (this.owner != null) - this.node.setPlayerID(AEApi.instance().registries().players() - .getID(this.owner)); - this.node.updateState(); - } - setPower(null); - onNeighborChanged(); - } - - @Override - public abstract int cableConnectionRenderTo(); - - @Override - public boolean canBePlacedOn(BusSupport what) { - return what != BusSupport.DENSE_CABLE; - } - - @Override - public boolean canConnectRedstone() { - return false; - } - - protected final IAEFluidStack extractFluid(IAEFluidStack toExtract, - Actionable action) { - if (this.gridBlock == null || this.facingTank == null) - return null; - IMEMonitor monitor = this.gridBlock.getFluidMonitor(); - if (monitor == null) - return null; - return monitor.extractItems(toExtract, action, new MachineSource(this)); - } - - protected final IAEFluidStack extractGasFluid(IAEFluidStack toExtract, - Actionable action) { - if (this.gridBlock == null || this.facingGasTank == null) - return null; - IMEMonitor monitor = this.gridBlock.getFluidMonitor(); - if (monitor == null) - return null; - return monitor.extractItems(toExtract, action, new MachineSource(this)); - } - - protected final IAEFluidStack extractGas(IAEFluidStack toExtract, - Actionable action) { - if (this.gridBlock == null || this.facingGasTank == null) - return null; - IMEMonitor monitor = this.gridBlock.getFluidMonitor(); - if (monitor == null) - return null; - return monitor.extractItems(toExtract, action, new MachineSource(this)); - } - - @Override - public final IGridNode getActionableNode() { - return this.node; - } - - @Override - public abstract void getBoxes(IPartCollisionHelper bch); - - @Override - public IIcon getBreakingTexture() { - return TextureManager.BUS_SIDE.getTexture(); - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) { - return AECableType.GLASS; - } - - public Object getClientGuiElement(EntityPlayer player) { - return null; - } - - @Override - public void getDrops(List drops, boolean wrenched) {} - - @Override - public final IGridNode getExternalFacingNode() { - return null; - } - - public IFluidHandler getFacingTank() { - return this.facingTank; - } - - @Optional.Method(modid = "MekanismAPI|gas") - public IGasHandler getFacingGasTank(){ - return (IGasHandler) facingGasTank; - } - - public ECBaseGridBlock getGridBlock() { - return this.gridBlock; - } - - @Override - public IGridNode getGridNode() { - return this.node; - } - - @Override - public final IGridNode getGridNode(ForgeDirection dir) { - return this.node; - } - - public IPartHost getHost() { - return this.host; - } - - public TileEntity getHostTile() { - return this.hostTile; - } - - @Override - public ItemStack getItemStack(PartItemStack type) { - ItemStack is = new ItemStack(ItemEnum.PARTITEM.getItem(), 1, - PartEnum.getPartID(this)); - if (type != PartItemStack.Break) { - NBTTagCompound itemNbt = new NBTTagCompound(); - writeToNBT(itemNbt); - if (itemNbt.hasKey("node")) - itemNbt.removeTag("node"); - is.setTagCompound(itemNbt); - } - return is; - } - - @Override - public int getLightLevel() { - return isActive() ? 15 : 0; - } - - public final DimensionalCoord getLocation() { - return new DimensionalCoord(this.tile.getWorldObj(), this.tile.xCoord, - this.tile.yCoord, this.tile.zCoord); - } - - public double getPowerUsage() { - return this.powerUsage; - } - - public Object getServerGuiElement(EntityPlayer player) { - return null; - } - - public ForgeDirection getSide() { - return this.side; - } - - public List getWailaBodey(NBTTagCompound tag, List oldList) { - return oldList; - } - - public NBTTagCompound getWailaTag(NBTTagCompound tag) { - return tag; - } - - public void initializePart(ItemStack partStack) { - if (partStack.hasTagCompound()) { - readFromNBT(partStack.getTagCompound()); - } - } - - protected final IAEFluidStack injectFluid(IAEFluidStack toInject, - Actionable action) { - if (this.gridBlock == null || this.facingTank == null) { - return toInject; - } - IMEMonitor monitor = this.gridBlock.getFluidMonitor(); - if (monitor == null) { - return toInject; - } - return monitor.injectItems(toInject, action, new MachineSource(this)); - } - - protected final IAEFluidStack injectGas(IAEFluidStack toInject, Actionable action) { - if (this.gridBlock == null || this.facingGasTank == null) { - return toInject; - } - IMEMonitor monitor = this.gridBlock.getFluidMonitor(); - if (monitor == null) { - return toInject; - } - return monitor.injectItems(toInject, action, new MachineSource(this)); - } - - @Override - public boolean isActive() { - return this.node != null ? this.node.isActive() : this.isActive; - } - - @Override - public boolean isLadder(EntityLivingBase entity) { - return false; - } - - @Override - public boolean isPowered() { - return this.isPowerd; - } - - @Override - public int isProvidingStrongPower() { - return 0; - } - - @Override - public int isProvidingWeakPower() { - return 0; - } - - protected boolean isRedstonePowered() { - return this.redstonePowered; - } - - @Override - public boolean isSolid() { - return false; - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (player != null && player instanceof EntityPlayerMP) - GuiHandler.launchGui(GuiHandler.getGuiId(this), player, - this.hostTile.getWorldObj(), this.hostTile.xCoord, - this.hostTile.yCoord, this.hostTile.zCoord); - return true; - } - - @Override - public void onEntityCollision(Entity entity) {} - - public boolean isValid() { - if (this.hostTile != null && this.hostTile.hasWorldObj()) { - DimensionalCoord loc = this.getLocation(); - TileEntity host = this.hostTile.getWorldObj().getTileEntity(loc.x, loc.y, loc.z); - if (host instanceof IPartHost) { - return ((IPartHost) host).getPart(this.side) == this; - } - else return false; - } - else return false; - } - - @Override - public void onNeighborChanged() { - if (this.hostTile == null) - return; - World world = this.hostTile.getWorldObj(); - int x = this.hostTile.xCoord; - int y = this.hostTile.yCoord; - int z = this.hostTile.zCoord; - TileEntity tileEntity = world.getTileEntity(x + this.side.offsetX, y - + this.side.offsetY, z + this.side.offsetZ); - this.facingTank = null; - if (tileEntity instanceof IFluidHandler) - this.facingTank = (IFluidHandler) tileEntity; - if (Integration.Mods.MEKANISMGAS.isEnabled()) - updateCheckGasTank(tileEntity); - this.redstonePowered = world.isBlockIndirectlyGettingPowered(x, y, z) - || world.isBlockIndirectlyGettingPowered(x, y + 1, z); - } - - @Optional.Method(modid = "MekanismAPI|gas") - private void updateCheckGasTank(TileEntity tile) { - this.facingGasTank = null; - if (tile != null && tile instanceof IGasHandler){ - this.facingGasTank = tile; - } - } - - @Override - public void onPlacement(EntityPlayer player, ItemStack held, - ForgeDirection side) { - this.owner = player; - } - - @Override - public boolean onShiftActivate(EntityPlayer player, Vec3 pos) { - return false; - } - - @Override - public void randomDisplayTick(World world, int x, int y, int z, Random r) {} - - @Override - public void readFromNBT(NBTTagCompound data) { - if (data.hasKey("node") && this.node != null) { - this.node.loadFromNBT("node0", data.getCompoundTag("node")); - this.node.updateState(); - } - } - - @Override - public boolean readFromStream(ByteBuf data) throws IOException { - this.isActive = data.readBoolean(); - this.isPowerd = data.readBoolean(); - return true; - } - - @Override - public void removeFromWorld() { - if (this.node != null) - this.node.destroy(); - } - - @Override - @SideOnly(Side.CLIENT) - public void renderDynamic(double x, double y, double z, - IPartRenderHelper rh, RenderBlocks renderer) {} - - @Override - @SideOnly(Side.CLIENT) - public abstract void renderInventory(IPartRenderHelper rh, - RenderBlocks renderer); - - @SideOnly(Side.CLIENT) - public void renderInventoryBusLights(IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - rh.setInvColor(0xFFFFFF); - IIcon otherIcon = TextureManager.BUS_COLOR.getTextures()[0]; - IIcon side = TextureManager.BUS_SIDE.getTexture(); - rh.setTexture(otherIcon, otherIcon, side, side, otherIcon, otherIcon); - rh.renderInventoryBox(renderer); - - ts.setBrightness(13 << 20 | 13 << 4); - rh.setInvColor(AEColor.Transparent.blackVariant); - rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.UP, renderer); - rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.DOWN, renderer); - rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.NORTH, renderer); - rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.EAST, renderer); - rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.SOUTH, renderer); - rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.WEST, renderer); - } - - @Override - @SideOnly(Side.CLIENT) - public abstract void renderStatic(int x, int y, int z, - IPartRenderHelper rh, RenderBlocks renderer); - - @SideOnly(Side.CLIENT) - public void renderStaticBusLights(int x, int y, int z, - IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon otherIcon = TextureManager.BUS_COLOR.getTextures()[0]; - IIcon side = TextureManager.BUS_SIDE.getTexture(); - rh.setTexture(otherIcon, otherIcon, side, side, otherIcon, otherIcon); - rh.renderBlock(x, y, z, renderer); - - if (isActive()) { - ts.setBrightness(13 << 20 | 13 << 4); - ts.setColorOpaque_I(this.host.getColor().blackVariant); - } else { - ts.setColorOpaque_I(0x000000); - } - rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.UP, renderer); - rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.DOWN, renderer); - rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.NORTH, renderer); - rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.EAST, renderer); - rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.SOUTH, renderer); - rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.WEST, renderer); - } - - @Override - public boolean requireDynamicRender() { - return false; - } - - protected final void saveData() { - if (this.host != null) - this.host.markForSave(); - } - - @Override - public void securityBreak() { - getHost().removePart(this.side, false); // TODO drop item - } - - protected void setActive(boolean _active) { - this.isActive = _active; - } - - @Override - public void setPartHostInfo(ForgeDirection _side, IPartHost _host, - TileEntity _tile) { - this.side = _side; - this.host = _host; - this.tile = _tile; - this.hostTile = _tile; - setPower(null); - } - - @MENetworkEventSubscribe - @SuppressWarnings("unused") - public void setPower(MENetworkPowerStatusChange notUsed) { - if (this.node != null) { - this.isActive = this.node.isActive(); - IGrid grid = this.node.getGrid(); - if (grid != null) { - IEnergyGrid energy = grid.getCache(IEnergyGrid.class); - if (energy != null) - this.isPowerd = energy.isNetworkPowered(); - } - this.host.markForUpdate(); - } - } - - @Override - public void writeToNBT(NBTTagCompound data) { - if (this.node != null) { - NBTTagCompound nodeTag = new NBTTagCompound(); - this.node.saveToNBT("node0", nodeTag); - data.setTag("node", nodeTag); - } - } - - @Override - public void writeToStream(ByteBuf data) throws IOException { - data.writeBoolean(this.node != null && this.node.isActive()); - data.writeBoolean(this.isPowerd); - } +public abstract class PartECBase implements IPart, IGridHost, IActionHost, IPowerChannelState { + + private IGridNode node; + private ForgeDirection side; + private IPartHost host; + protected TileEntity tile; + private ECBaseGridBlock gridBlock; + private double powerUsage; + private TileEntity hostTile; + private IFluidHandler facingTank; + private Object facingGasTank; + private boolean redstonePowered; + private boolean isActive; + private boolean isPowerd = false; + private EntityPlayer owner; + private ItemStack is; + + public PartECBase() { + this.is = new ItemStack(ItemEnum.PARTITEM.getItem(), 1, PartEnum.getPartID(this)); + } + + @Override + public void addToWorld() { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return; + this.gridBlock = new ECBaseGridBlock(this); + this.node = AEApi.instance().createGridNode(this.gridBlock); + if (this.node != null) { + if (this.owner != null) this.node.setPlayerID(AEApi.instance().registries().players().getID(this.owner)); + this.node.updateState(); + } + setPower(null); + onNeighborChanged(); + } + + @Override + public abstract int cableConnectionRenderTo(); + + @Override + public boolean canBePlacedOn(BusSupport what) { + return what != BusSupport.DENSE_CABLE; + } + + @Override + public boolean canConnectRedstone() { + return false; + } + + protected final IAEFluidStack extractFluid(IAEFluidStack toExtract, Actionable action) { + if (this.gridBlock == null || this.facingTank == null) return null; + IMEMonitor monitor = this.gridBlock.getFluidMonitor(); + if (monitor == null) return null; + return monitor.extractItems(toExtract, action, new MachineSource(this)); + } + + protected final IAEFluidStack extractGasFluid(IAEFluidStack toExtract, Actionable action) { + if (this.gridBlock == null || this.facingGasTank == null) return null; + IMEMonitor monitor = this.gridBlock.getFluidMonitor(); + if (monitor == null) return null; + return monitor.extractItems(toExtract, action, new MachineSource(this)); + } + + protected final IAEFluidStack extractGas(IAEFluidStack toExtract, Actionable action) { + if (this.gridBlock == null || this.facingGasTank == null) return null; + IMEMonitor monitor = this.gridBlock.getFluidMonitor(); + if (monitor == null) return null; + return monitor.extractItems(toExtract, action, new MachineSource(this)); + } + + @Override + public final IGridNode getActionableNode() { + return this.node; + } + + @Override + public abstract void getBoxes(IPartCollisionHelper bch); + + @Override + public IIcon getBreakingTexture() { + return TextureManager.BUS_SIDE.getTexture(); + } + + @Override + public AECableType getCableConnectionType(ForgeDirection dir) { + return AECableType.GLASS; + } + + public Object getClientGuiElement(EntityPlayer player) { + return null; + } + + @Override + public void getDrops(List drops, boolean wrenched) {} + + @Override + public final IGridNode getExternalFacingNode() { + return null; + } + + public IFluidHandler getFacingTank() { + return this.facingTank; + } + + @Optional.Method(modid = "MekanismAPI|gas") + public IGasHandler getFacingGasTank() { + return (IGasHandler) facingGasTank; + } + + public ECBaseGridBlock getGridBlock() { + return this.gridBlock; + } + + @Override + public IGridNode getGridNode() { + return this.node; + } + + @Override + public final IGridNode getGridNode(ForgeDirection dir) { + return this.node; + } + + public IPartHost getHost() { + return this.host; + } + + public TileEntity getHostTile() { + return this.hostTile; + } + + @Override + public ItemStack getItemStack(PartItemStack type) { + return this.is; + } + + @Override + public int getLightLevel() { + return 0; + } + + public final DimensionalCoord getLocation() { + return new DimensionalCoord(this.tile.getWorldObj(), this.tile.xCoord, this.tile.yCoord, this.tile.zCoord); + } + + public double getPowerUsage() { + return this.powerUsage; + } + + public Object getServerGuiElement(EntityPlayer player) { + return null; + } + + public ForgeDirection getSide() { + return this.side; + } + + public List getWailaBodey(NBTTagCompound tag, List oldList) { + return oldList; + } + + public NBTTagCompound getWailaTag(NBTTagCompound tag) { + return tag; + } + + public void initializePart(ItemStack partStack) { + if (partStack.hasTagCompound()) { + readFromNBT(partStack.getTagCompound()); + } + } + + protected final IAEFluidStack injectFluid(IAEFluidStack toInject, Actionable action) { + if (this.gridBlock == null || this.facingTank == null) { + return toInject; + } + IMEMonitor monitor = this.gridBlock.getFluidMonitor(); + if (monitor == null) { + return toInject; + } + return monitor.injectItems(toInject, action, new MachineSource(this)); + } + + protected final IAEFluidStack injectGas(IAEFluidStack toInject, Actionable action) { + if (this.gridBlock == null || this.facingGasTank == null) { + return toInject; + } + IMEMonitor monitor = this.gridBlock.getFluidMonitor(); + if (monitor == null) { + return toInject; + } + return monitor.injectItems(toInject, action, new MachineSource(this)); + } + + @Override + public boolean isActive() { + return this.node != null ? this.node.isActive() : this.isActive; + } + + @Override + public boolean isLadder(EntityLivingBase entity) { + return false; + } + + @Override + public boolean isPowered() { + return this.isPowerd; + } + + @Override + public int isProvidingStrongPower() { + return 0; + } + + @Override + public int isProvidingWeakPower() { + return 0; + } + + protected boolean isRedstonePowered() { + return this.redstonePowered; + } + + @Override + public boolean isSolid() { + return false; + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (player != null && player instanceof EntityPlayerMP) GuiHandler.launchGui( + GuiHandler.getGuiId(this), + player, + this.hostTile.getWorldObj(), + this.hostTile.xCoord, + this.hostTile.yCoord, + this.hostTile.zCoord); + return true; + } + + @Override + public void onEntityCollision(Entity entity) {} + + public boolean isValid() { + if (this.hostTile != null && this.hostTile.hasWorldObj()) { + DimensionalCoord loc = this.getLocation(); + TileEntity host = this.hostTile.getWorldObj().getTileEntity(loc.x, loc.y, loc.z); + if (host instanceof IPartHost) { + return ((IPartHost) host).getPart(this.side) == this; + } else return false; + } else return false; + } + + @Override + public void onNeighborChanged() { + if (this.hostTile == null) return; + World world = this.hostTile.getWorldObj(); + int x = this.hostTile.xCoord; + int y = this.hostTile.yCoord; + int z = this.hostTile.zCoord; + TileEntity tileEntity = world + .getTileEntity(x + this.side.offsetX, y + this.side.offsetY, z + this.side.offsetZ); + this.facingTank = null; + if (tileEntity instanceof IFluidHandler) this.facingTank = (IFluidHandler) tileEntity; + if (Integration.Mods.MEKANISMGAS.isEnabled()) updateCheckGasTank(tileEntity); + this.redstonePowered = world.isBlockIndirectlyGettingPowered(x, y, z) + || world.isBlockIndirectlyGettingPowered(x, y + 1, z); + } + + @Optional.Method(modid = "MekanismAPI|gas") + private void updateCheckGasTank(TileEntity tile) { + this.facingGasTank = null; + if (tile != null && tile instanceof IGasHandler) { + this.facingGasTank = tile; + } + } + + @Override + public void onPlacement(EntityPlayer player, ItemStack held, ForgeDirection side) { + this.owner = player; + } + + @Override + public boolean onShiftActivate(EntityPlayer player, Vec3 pos) { + return false; + } + + @Override + public void randomDisplayTick(World world, int x, int y, int z, Random r) {} + + @Override + public void readFromNBT(NBTTagCompound data) { + if (data.hasKey("node") && this.node != null) { + this.node.loadFromNBT("node0", data.getCompoundTag("node")); + this.node.updateState(); + } + } + + @Override + public boolean readFromStream(ByteBuf data) throws IOException { + this.isActive = data.readBoolean(); + this.isPowerd = data.readBoolean(); + return true; + } + + @Override + public void removeFromWorld() { + if (this.node != null) this.node.destroy(); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic(double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer) {} + + @Override + @SideOnly(Side.CLIENT) + public abstract void renderInventory(IPartRenderHelper rh, RenderBlocks renderer); + + @SideOnly(Side.CLIENT) + public void renderInventoryBusLights(IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + rh.setInvColor(0xFFFFFF); + IIcon otherIcon = TextureManager.BUS_COLOR.getTextures()[0]; + IIcon side = TextureManager.BUS_SIDE.getTexture(); + rh.setTexture(otherIcon, otherIcon, side, side, otherIcon, otherIcon); + rh.renderInventoryBox(renderer); + + ts.setBrightness(13 << 20 | 13 << 4); + rh.setInvColor(AEColor.Transparent.blackVariant); + rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.UP, renderer); + rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.DOWN, renderer); + rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.NORTH, renderer); + rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.EAST, renderer); + rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.SOUTH, renderer); + rh.renderInventoryFace(TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.WEST, renderer); + } + + protected void renderBackPanel(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + final IIcon sideStatusTexture = CableBusTextures.PartMonitorSidesStatus.getIcon(); + final IIcon noTexture = ItemMultiPart.instance.getIconFromDamage(380); + + rh.setTexture( + sideStatusTexture, + sideStatusTexture, + backTexture, + noTexture, + sideStatusTexture, + sideStatusTexture); + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); + } + + protected void renderPowerStatus(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + if (isActive()) { + final int l = 14; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(host.getColor().blackVariant); + } else if (isPowered()) { + final int l = 9; + Tessellator.instance.setBrightness(l << 20 | l << 4); + Tessellator.instance.setColorOpaque_I(host.getColor().whiteVariant); + } else { + Tessellator.instance.setBrightness(0); + Tessellator.instance.setColorOpaque_I(0x000000); + } + + 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); + } + + protected void renderFrontPanel(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + final IIcon noTexture = ItemMultiPart.instance.getIconFromDamage(380); + + rh.setTexture(sideTexture, sideTexture, backTexture, noTexture, sideTexture, sideTexture); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public abstract void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer); + + @SideOnly(Side.CLIENT) + public void renderStaticBusLights(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon otherIcon = TextureManager.BUS_COLOR.getTextures()[0]; + IIcon side = TextureManager.BUS_SIDE.getTexture(); + rh.setTexture(otherIcon, otherIcon, side, side, otherIcon, otherIcon); + rh.renderBlock(x, y, z, renderer); + + if (isActive()) { + ts.setBrightness(13 << 20 | 13 << 4); + ts.setColorOpaque_I(this.host.getColor().blackVariant); + } else { + ts.setColorOpaque_I(0x000000); + } + rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.UP, renderer); + rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.DOWN, renderer); + rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.NORTH, renderer); + rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.EAST, renderer); + rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.SOUTH, renderer); + rh.renderFace(x, y, z, TextureManager.BUS_COLOR.getTextures()[1], ForgeDirection.WEST, renderer); + } + + @Override + public boolean requireDynamicRender() { + return false; + } + + protected final void saveData() { + if (this.host != null) this.host.markForSave(); + } + + @Override + public void securityBreak() { + getHost().removePart(this.side, false); // TODO drop item + } + + protected void setActive(boolean _active) { + this.isActive = _active; + } + + @Override + public void setPartHostInfo(ForgeDirection _side, IPartHost _host, TileEntity _tile) { + this.side = _side; + this.host = _host; + this.tile = _tile; + this.hostTile = _tile; + setPower(null); + } + + @MENetworkEventSubscribe + @SuppressWarnings("unused") + public void setPower(MENetworkPowerStatusChange notUsed) { + if (this.node != null) { + this.isActive = this.node.isActive(); + IGrid grid = this.node.getGrid(); + if (grid != null) { + IEnergyGrid energy = grid.getCache(IEnergyGrid.class); + if (energy != null) this.isPowerd = energy.isNetworkPowered(); + } + this.host.markForUpdate(); + } + } + + @Override + public void writeToNBT(NBTTagCompound data) { + if (this.node != null) { + NBTTagCompound nodeTag = new NBTTagCompound(); + this.node.saveToNBT("node0", nodeTag); + data.setTag("node", nodeTag); + } + } + + @Override + public void writeToStream(ByteBuf data) throws IOException { + data.writeBoolean(this.node != null && this.node.isActive()); + data.writeBoolean(this.isPowerd); + } } diff --git a/src/main/scala/extracells/part/PartFluidConversionMonitor.java b/src/main/scala/extracells/part/PartFluidConversionMonitor.java index 21e09d181..dc41a2a75 100644 --- a/src/main/scala/extracells/part/PartFluidConversionMonitor.java +++ b/src/main/scala/extracells/part/PartFluidConversionMonitor.java @@ -1,5 +1,18 @@ package extracells.part; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.FluidStack; + +import org.apache.commons.lang3.tuple.MutablePair; + import appeng.api.config.Actionable; import appeng.api.networking.security.MachineSource; import appeng.api.parts.IPartHost; @@ -9,196 +22,129 @@ import appeng.api.util.AEColor; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; +import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.FluidUtil; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidContainerItem; -import org.apache.commons.lang3.tuple.MutablePair; public class PartFluidConversionMonitor extends PartFluidStorageMonitor { - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - boolean b = super.onActivate(player, pos); - if (b) - return b; - if (player == null || player.worldObj == null) - return true; - if (player.worldObj.isRemote) - return true; - ItemStack s = player.getCurrentEquippedItem(); - IMEMonitor mon = getFluidStorage(); - if (this.locked && s != null && mon != null) { - ItemStack s2 = s.copy(); - s2.stackSize = 1; - if (FluidUtil.isFilled(s2)) { - FluidStack f = FluidUtil.getFluidFromContainer(s2); - if (f == null) - return true; - IAEFluidStack fl = FluidUtil.createAEFluidStack(f); - IAEFluidStack not = mon.injectItems(fl.copy(), - Actionable.SIMULATE, new MachineSource(this)); - if (mon.canAccept(fl) - && (not == null || not.getStackSize() == 0L)) { - mon.injectItems(fl, Actionable.MODULATE, new MachineSource( - this)); - - MutablePair empty1 = FluidUtil - .drainStack(s2, f); - ItemStack empty = empty1.right; - if (empty != null) { - dropItems(getHost().getTile().getWorldObj(), getHost() - .getTile().xCoord + getSide().offsetX, - getHost().getTile().yCoord + getSide().offsetY, - getHost().getTile().zCoord + getSide().offsetZ, - empty); - } - ItemStack s3 = s.copy(); - s3.stackSize = s3.stackSize - 1; - if (s3.stackSize == 0) { - player.inventory.setInventorySlotContents( - player.inventory.currentItem, null); - } else { - player.inventory.setInventorySlotContents( - player.inventory.currentItem, s3); - } - } - return true; - } else if (FluidUtil.isEmpty(s2)) { - if (this.fluid == null) - return true; - IAEFluidStack extract; - if (s2.getItem() instanceof IFluidContainerItem) { - extract = mon.extractItems(FluidUtil.createAEFluidStack( - this.fluid, ((IFluidContainerItem) s2.getItem()) - .getCapacity(s2)), Actionable.SIMULATE, - new MachineSource(this)); - } else - extract = mon.extractItems( - FluidUtil.createAEFluidStack(this.fluid), - Actionable.SIMULATE, new MachineSource(this)); - if (extract != null) { - mon.extractItems(FluidUtil - .createAEFluidStack(new FluidStack(this.fluid, - (int) extract.getStackSize())), - Actionable.MODULATE, new MachineSource(this)); - MutablePair empty1 = FluidUtil - .fillStack(s2, extract.getFluidStack()); - if (empty1.left == 0) { - mon.injectItems(FluidUtil - .createAEFluidStack(new FluidStack(this.fluid, - (int) extract.getStackSize())), - Actionable.MODULATE, new MachineSource(this)); - return true; - } - ItemStack empty = empty1.right; - if (empty != null) { - dropItems(getHost().getTile().getWorldObj(), getHost() - .getTile().xCoord + getSide().offsetX, - getHost().getTile().yCoord + getSide().offsetY, - getHost().getTile().zCoord + getSide().offsetZ, - empty); - } - ItemStack s3 = s.copy(); - s3.stackSize = s3.stackSize - 1; - if (s3.stackSize == 0) { - player.inventory.setInventorySlotContents( - player.inventory.currentItem, null); - } else { - player.inventory.setInventorySlotContents( - player.inventory.currentItem, s3); - } - } - return true; - } - } - return false; - } - - @Override - @SideOnly(Side.CLIENT) - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); - rh.setTexture(side); - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderInventoryBox(renderer); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderInventoryBox(renderer); - - ts.setBrightness(13 << 20 | 13 << 4); - - rh.setInvColor(0xFFFFFF); - rh.renderInventoryFace(TextureManager.BUS_BORDER.getTexture(), - ForgeDirection.SOUTH, renderer); - - rh.setBounds(3, 3, 15, 13, 13, 16); - rh.setInvColor(AEColor.Transparent.blackVariant); - rh.renderInventoryFace( - TextureManager.CONVERSION_MONITOR.getTextures()[0], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(AEColor.Transparent.mediumVariant); - rh.renderInventoryFace( - TextureManager.CONVERSION_MONITOR.getTextures()[1], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(AEColor.Transparent.whiteVariant); - rh.renderInventoryFace( - TextureManager.CONVERSION_MONITOR.getTextures()[2], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 12, 11, 11, 13); - renderInventoryBusLights(rh, renderer); - } - - @Override - @SideOnly(Side.CLIENT) - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); - rh.setTexture(side); - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderBlock(x, y, z, renderer); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - - if (isActive()) - Tessellator.instance.setBrightness(13 << 20 | 13 << 4); - - ts.setColorOpaque_I(0xFFFFFF); - rh.renderFace(x, y, z, TextureManager.BUS_BORDER.getTexture(), - ForgeDirection.SOUTH, renderer); - - IPartHost host = getHost(); - rh.setBounds(3, 3, 15, 13, 13, 16); - ts.setColorOpaque_I(host.getColor().mediumVariant); - rh.renderFace(x, y, z, - TextureManager.CONVERSION_MONITOR.getTextures()[0], - ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(host.getColor().whiteVariant); - rh.renderFace(x, y, z, - TextureManager.CONVERSION_MONITOR.getTextures()[1], - ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(host.getColor().blackVariant); - rh.renderFace(x, y, z, - TextureManager.CONVERSION_MONITOR.getTextures()[2], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 12, 11, 11, 13); - renderStaticBusLights(x, y, z, rh, renderer); - } - + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (super.onActivate(player, pos)) return true; + if (player == null || player.worldObj == null) return true; + if (player.worldObj.isRemote) return true; + ItemStack heldItem = player.getCurrentEquippedItem(); + IMEMonitor mon = getFluidStorage(); + if (this.locked && heldItem != null && mon != null) { + ItemStack container = heldItem.copy(); + container.stackSize = 1; + MachineSource src = new MachineSource(this); + ItemStack result = null; + if (FluidUtil.isFilled(container)) { + FluidStack f = FluidUtil.getFluidFromContainer(container); + if (f == null) { + return true; + } + ItemStack simulation = FluidUtil.drainItemIntoAe(container, mon, Actionable.SIMULATE, src); + if (simulation == null) { + return true; + } + result = FluidUtil.drainItemIntoAe(container, mon, Actionable.MODULATE, src); + } else if (FluidUtil.isEmpty(container)) { + if (this.fluid == null) return true; + MutablePair simulation = FluidUtil.fillItemFromAe( + container, + new FluidStack(this.fluid, Integer.MAX_VALUE), + mon, + Actionable.SIMULATE, + src); + if (simulation == null || simulation.getLeft() == null) { + return true; + } + result = FluidUtil.fillItemFromAe( + container, + new FluidStack(this.fluid, Integer.MAX_VALUE), + mon, + Actionable.MODULATE, + src).getLeft(); + } + if (result == null) { + return true; + } + TileEntity tile = this.getHost().getTile(); + ForgeDirection side = this.getSide(); + this.dropItems( + tile.getWorldObj(), + tile.xCoord + side.offsetX, + tile.yCoord + side.offsetY, + tile.zCoord + side.offsetZ, + result); + ItemStack newHeldItem = heldItem.copy(); + newHeldItem.stackSize--; + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + newHeldItem.stackSize <= 0 ? null : newHeldItem); + return true; + } + return false; + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); + rh.setTexture(side); + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + ts.setBrightness(13 << 20 | 13 << 4); + + rh.setInvColor(0xFFFFFF); + rh.renderInventoryFace(TextureManager.BUS_BORDER.getTexture(), ForgeDirection.SOUTH, renderer); + + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.setInvColor(AEColor.Transparent.blackVariant); + rh.renderInventoryFace(TextureManager.CONVERSION_MONITOR.getTextures()[0], ForgeDirection.SOUTH, renderer); + rh.setInvColor(AEColor.Transparent.mediumVariant); + rh.renderInventoryFace(TextureManager.CONVERSION_MONITOR.getTextures()[1], ForgeDirection.SOUTH, renderer); + rh.setInvColor(AEColor.Transparent.whiteVariant); + rh.renderInventoryFace(TextureManager.CONVERSION_MONITOR.getTextures()[2], ForgeDirection.SOUTH, renderer); + + rh.setBounds(5, 5, 12, 11, 11, 13); + renderInventoryBusLights(rh, renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + final IPartHost host = getHost(); + + // Render Front Screen + rh.setBounds(3, 3, 15, 13, 13, 16); + Tessellator.instance.setColorOpaque_I(host.getColor().mediumVariant); + rh.renderFace(x, y, z, TextureManager.CONVERSION_MONITOR.getTextures()[0], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setColorOpaque_I(host.getColor().whiteVariant); + rh.renderFace(x, y, z, TextureManager.CONVERSION_MONITOR.getTextures()[1], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setColorOpaque_I(host.getColor().blackVariant); + rh.renderFace(x, y, z, TextureManager.CONVERSION_MONITOR.getTextures()[2], ForgeDirection.SOUTH, renderer); + + renderFrontPanel(x, y, z, rh, renderer); + renderBackPanel(x, y, z, rh, renderer); + renderPowerStatus(x, y, z, rh, renderer); + } + + @Override + public NBTTagCompound transformPart(NBTTagCompound def) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FluidCraft.replace(def, PartEnum.FLUIDCONVERSIONMONITOR); + } + return def; + } } diff --git a/src/main/scala/extracells/part/PartFluidExport.java b/src/main/scala/extracells/part/PartFluidExport.java index daacc9773..327003646 100644 --- a/src/main/scala/extracells/part/PartFluidExport.java +++ b/src/main/scala/extracells/part/PartFluidExport.java @@ -1,158 +1,188 @@ package extracells.part; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidHandler; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; +import appeng.api.networking.ticking.TickRateModulation; import appeng.api.parts.IPart; import appeng.api.parts.IPartCollisionHelper; import appeng.api.parts.IPartRenderHelper; import appeng.api.storage.data.IAEFluidStack; import appeng.api.util.AEColor; +import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; +import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.PermissionUtil; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidHandler; - -import java.util.ArrayList; -import java.util.List; public class PartFluidExport extends PartFluidIO { - @Override - public int cableConnectionRenderTo() { - return 5; - } - - @Override - public boolean doWork(int rate, int TicksSinceLastCall) { - IFluidHandler facingTank = getFacingTank(); - if (facingTank == null || !isActive()) - return false; - List filter = new ArrayList(); - filter.add(this.filterFluids[4]); - - if (this.filterSize >= 1) { - for (byte i = 1; i < 9; i += 2) { - if (i != 4) { - filter.add(this.filterFluids[i]); - } - } - } - - if (this.filterSize >= 2) { - for (byte i = 0; i < 9; i += 2) { - if (i != 4) { - filter.add(this.filterFluids[i]); - } - } - } - - for (Fluid fluid : filter) { - if (fluid != null) { - IAEFluidStack stack = extractFluid(AEApi.instance().storage().createFluidStack(new FluidStack(fluid, rate * TicksSinceLastCall)), Actionable.SIMULATE); - - if (stack == null) - continue; - int filled = facingTank.fill(getSide().getOpposite(), stack.getFluidStack(), true); - - if (filled > 0) { - extractFluid(AEApi.instance().storage().createFluidStack(new FluidStack(fluid, filled)), Actionable.MODULATE); - return true; - } - } - } - return false; - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(6, 6, 12, 10, 10, 13); - bch.addBox(4, 4, 13, 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 double getPowerUsage() { - return 1.0D; - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, - (IPart) this)) { - return super.onActivate(player, pos); - } - return false; - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); - rh.setBounds(6, 6, 12, 10, 10, 13); - rh.renderInventoryBox(renderer); - - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderInventoryBox(renderer); - - rh.setBounds(5, 5, 14, 11, 11, 15); - rh.renderInventoryBox(renderer); - - IIcon side = TextureManager.EXPORT_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.EXPORT_FRONT.getTexture(), side, side); - rh.setBounds(6, 6, 15, 10, 10, 16); - rh.renderInventoryBox(renderer); - - rh.setInvColor(AEColor.Cyan.blackVariant); - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderInventoryFace(TextureManager.EXPORT_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(6, 6, 11, 10, 10, 12); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); - rh.setBounds(6, 6, 12, 10, 10, 13); - rh.renderBlock(x, y, z, renderer); - - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderBlock(x, y, z, renderer); - - rh.setBounds(5, 5, 14, 11, 11, 15); - rh.renderBlock(x, y, z, renderer); - - IIcon side = TextureManager.EXPORT_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.EXPORT_FRONT.getTextures()[0], side, side); - rh.setBounds(6, 6, 15, 10, 10, 16); - rh.renderBlock(x, y, z, renderer); - - ts.setColorOpaque_I(getHost().getColor().blackVariant); - if (isActive()) - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderFace(x, y, z, TextureManager.EXPORT_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(6, 6, 11, 10, 10, 12); - renderStaticBusLights(x, y, z, rh, renderer); - } + @Override + public int cableConnectionRenderTo() { + return 5; + } + + @Override + public TickRateModulation doWork(int rate, int TicksSinceLastCall) { + if (!isActive() || tile == null) return TickRateModulation.IDLE; + IFluidHandler facingTank = getFacingTank(); + if (facingTank == null) return TickRateModulation.IDLE; + List filter = new ArrayList<>(); + filter.add(this.filterFluids[4]); + + if (this.filterSize >= 1) { + for (byte i = 1; i < 9; i += 2) { + if (i != 4) { + filter.add(this.filterFluids[i]); + } + } + } + + if (this.filterSize >= 2) { + for (byte i = 0; i < 9; i += 2) { + if (i != 4) { + filter.add(this.filterFluids[i]); + } + } + } + + for (Fluid fluid : filter) { + if (fluid != null) { + IAEFluidStack stack = extractFluid( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, rate * TicksSinceLastCall)), + Actionable.SIMULATE); + + if (stack == null || stack.getStackSize() <= 0) continue; + + int filled = facingTank.fill(this.getSide().getOpposite(), stack.getFluidStack(), false); + if (filled > 0) { + stack.setStackSize(filled); + stack = this.extractFluid(stack, Actionable.MODULATE); + if (stack != null && stack.getStackSize() > 0) { + int actuallyFilled = facingTank.fill(this.getSide().getOpposite(), stack.getFluidStack(), true); + if (actuallyFilled < stack.getStackSize()) { + // try to return to AE + int toReturn = (int) stack.getStackSize() - actuallyFilled; + IAEFluidStack returned = injectFluid( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, toReturn)), + Actionable.MODULATE); + if (returned != null) { + FMLLog.severe( + "[ExtraCells2] Export bus at %d:%d,%d,%d voided %d mL of %s", + tile.getWorldObj().provider.dimensionId, + tile.xCoord, + tile.yCoord, + tile.zCoord, + toReturn - returned.getStackSize(), + fluid.getName()); + } + } + return TickRateModulation.FASTER; + } + } + } + } + return TickRateModulation.SLOWER; + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(6, 6, 12, 10, 10, 13); + bch.addBox(4, 4, 13, 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 double getPowerUsage() { + return 1.0D; + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this)) { + return super.onActivate(player, pos); + } + return false; + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); + rh.setBounds(6, 6, 12, 10, 10, 13); + rh.renderInventoryBox(renderer); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); + + IIcon side = TextureManager.EXPORT_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.EXPORT_FRONT.getTexture(), side, side); + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderInventoryBox(renderer); + + rh.setInvColor(AEColor.Cyan.blackVariant); + ts.setBrightness(15 << 20 | 15 << 4); + rh.renderInventoryFace(TextureManager.EXPORT_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + + rh.setBounds(6, 6, 11, 10, 10, 12); + renderInventoryBusLights(rh, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); + rh.setBounds(6, 6, 12, 10, 10, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); + + IIcon side = TextureManager.EXPORT_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.EXPORT_FRONT.getTextures()[0], side, side); + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); + + ts.setColorOpaque_I(getHost().getColor().blackVariant); + if (isActive()) ts.setBrightness(15 << 20 | 15 << 4); + rh.renderFace(x, y, z, TextureManager.EXPORT_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + + rh.setBounds(6, 6, 11, 10, 10, 12); + renderStaticBusLights(x, y, z, rh, renderer); + } + + @Override + public NBTTagCompound transformPart(NBTTagCompound def) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FluidCraft.replace(def, PartEnum.FLUIDEXPORT); + } + return def; + } } diff --git a/src/main/scala/extracells/part/PartFluidIO.java b/src/main/scala/extracells/part/PartFluidIO.java index 36c3e5844..84bc3c2d2 100644 --- a/src/main/scala/extracells/part/PartFluidIO.java +++ b/src/main/scala/extracells/part/PartFluidIO.java @@ -1,5 +1,22 @@ package extracells.part; +import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; + import appeng.api.AEApi; import appeng.api.config.RedstoneMode; import appeng.api.networking.IGridNode; @@ -7,281 +24,298 @@ import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; import appeng.api.parts.IPartCollisionHelper; +import appeng.api.parts.IPartDeprecated; import appeng.api.parts.IPartHost; import appeng.api.parts.IPartRenderHelper; -import appeng.api.parts.PartItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import extracells.Extracells; import extracells.container.ContainerBusFluidIO; import extracells.gui.GuiBusFluidIO; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; +import extracells.item.ItemPartECBase; import extracells.network.packet.other.IFluidSlotPartOrBlock; import extracells.network.packet.other.PacketFluidSlot; import extracells.network.packet.part.PacketBusFluidIO; import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; import io.netty.buffer.ByteBuf; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -public abstract class PartFluidIO extends PartECBase implements IGridTickable, - IInventoryUpdateReceiver, IFluidSlotPartOrBlock { - - public Fluid[] filterFluids = new Fluid[9]; - private RedstoneMode redstoneMode = RedstoneMode.IGNORE; - protected byte filterSize; - protected byte speedState; - protected boolean redstoneControlled; - private boolean lastRedstone; - private ECPrivateInventory upgradeInventory = new ECPrivateInventory("", 4, - 1, this) { - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - if (itemStack == null) - return false; - if (AEApi.instance().definitions().materials().cardCapacity().isSameAs(itemStack)) - return true; - else if (AEApi.instance().definitions().materials().cardSpeed().isSameAs(itemStack)) - return true; - else if (AEApi.instance().definitions().materials().cardRedstone().isSameAs(itemStack)) - return true; - return false; - } - }; - - @Override - public void getDrops( List drops, boolean wrenched) { - for (ItemStack stack : upgradeInventory.slots) { - if (stack == null) - continue; - drops.add(stack); - } - } - - @Override - public ItemStack getItemStack(PartItemStack type) { - ItemStack stack = super.getItemStack(type); - if (type.equals(PartItemStack.Wrench)) - stack.getTagCompound().removeTag("upgradeInventory"); - return stack; - } - - - @Override - public int cableConnectionRenderTo() { - return 5; - } - - private boolean canDoWork() { - boolean redstonePowered = isRedstonePowered(); - if (!this.redstoneControlled) - return true; - switch (getRedstoneMode()) { - case IGNORE: - return true; - case LOW_SIGNAL: - return !redstonePowered; - case HIGH_SIGNAL: - return redstonePowered; - case SIGNAL_PULSE: - return false; - } - return false; - } - - public byte getSpeedState(){ - return this.speedState; - } - - public abstract boolean doWork(int rate, int TicksSinceLastCall); - - @Override - public abstract void getBoxes(IPartCollisionHelper bch); - - @Override - public Object getClientGuiElement(EntityPlayer player) { - return new GuiBusFluidIO(this, player); - } - - @Override - public int getLightLevel() { - return 0; - } - - public RedstoneMode getRedstoneMode() { - return this.redstoneMode; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerBusFluidIO(this, player); - } - - @Override - public final TickingRequest getTickingRequest(IGridNode node) { - return new TickingRequest(1, 20, false, false); - } - - public ECPrivateInventory getUpgradeInventory() { - return this.upgradeInventory; - } - - @Override - public List getWailaBodey(NBTTagCompound tag, List oldList) { - if (tag.hasKey("speed")) - oldList.add(tag.getInteger("speed") + "mB/t"); - else - oldList.add("125mB/t"); - return oldList; - } - - @Override - public NBTTagCompound getWailaTag(NBTTagCompound tag) { - tag.setInteger("speed", 125 + this.speedState * 125); - return tag; - } - - public void loopRedstoneMode(EntityPlayer player) { - if (this.redstoneMode.ordinal() + 1 < RedstoneMode.values().length) - this.redstoneMode = RedstoneMode.values()[this.redstoneMode.ordinal() + 1]; - else - this.redstoneMode = RedstoneMode.values()[0]; - new PacketBusFluidIO(this.redstoneMode).sendPacketToPlayer(player); - saveData(); - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - boolean activate = super.onActivate(player, pos); - onInventoryChanged(); - return activate; - } - - @Override - public void onInventoryChanged() { - this.filterSize = 0; - this.redstoneControlled = false; - this.speedState = 0; - for (int i = 0; i < this.upgradeInventory.getSizeInventory(); i++) { - ItemStack currentStack = this.upgradeInventory.getStackInSlot(i); - if (currentStack != null) { - if (AEApi.instance().definitions().materials().cardCapacity().isSameAs(currentStack)) - this.filterSize++; - if (AEApi.instance().definitions().materials().cardRedstone().isSameAs(currentStack)) - this.redstoneControlled = true; - if (AEApi.instance().definitions().materials().cardSpeed().isSameAs(currentStack)) - this.speedState++; - } - } - - try { - if (getHost().getLocation().getWorld().isRemote) - return; - } catch (Throwable ignored) {} - new PacketBusFluidIO(this.filterSize).sendPacketToAllPlayers(); - new PacketBusFluidIO(this.redstoneControlled).sendPacketToAllPlayers(); - saveData(); - } - - @Override - public void onNeighborChanged() { - super.onNeighborChanged(); - boolean redstonePowered = isRedstonePowered(); - this.lastRedstone = redstonePowered; - } - - @Override - public final void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - this.redstoneMode = RedstoneMode.values()[data - .getInteger("redstoneMode")]; - for (int i = 0; i < 9; i++) { - this.filterFluids[i] = FluidRegistry.getFluid(data - .getString("FilterFluid#" + i)); - } - this.upgradeInventory.readFromNBT(data.getTagList("upgradeInventory", - 10)); - onInventoryChanged(); - } - - @Override - public final boolean readFromStream(ByteBuf data) throws IOException { - return super.readFromStream(data); - } - - @SideOnly(Side.CLIENT) - @Override - public final void renderDynamic(double x, double y, double z, - IPartRenderHelper rh, RenderBlocks renderer) {} - - @SideOnly(Side.CLIENT) - @Override - public abstract void renderInventory(IPartRenderHelper rh, - RenderBlocks renderer); - - @SideOnly(Side.CLIENT) - @Override - public abstract void renderStatic(int x, int y, int z, - IPartRenderHelper rh, RenderBlocks renderer); - - public void sendInformation(EntityPlayer player) { - new PacketFluidSlot(Arrays.asList(this.filterFluids)) - .sendPacketToPlayer(player); - new PacketBusFluidIO(this.redstoneMode).sendPacketToPlayer(player); - new PacketBusFluidIO(this.filterSize).sendPacketToPlayer(player); - } - - @Override - public final void setFluid(int index, Fluid fluid, EntityPlayer player) { - this.filterFluids[index] = fluid; - new PacketFluidSlot(Arrays.asList(this.filterFluids)) - .sendPacketToPlayer(player); - saveData(); - } - - @Override - public void setPartHostInfo(ForgeDirection _side, IPartHost _host, - TileEntity _tile) { - super.setPartHostInfo(_side, _host, _tile); - onInventoryChanged(); - } - - @Override - public final TickRateModulation tickingRequest(IGridNode node, - int TicksSinceLastCall) { - if (canDoWork()) - return doWork(125 + this.speedState * 125, TicksSinceLastCall) ? TickRateModulation.FASTER - : TickRateModulation.SLOWER; - return TickRateModulation.SLOWER; - } - - @Override - public final void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - data.setInteger("redstoneMode", this.redstoneMode.ordinal()); - for (int i = 0; i < this.filterFluids.length; i++) { - Fluid fluid = this.filterFluids[i]; - if (fluid != null) - data.setString("FilterFluid#" + i, fluid.getName()); - else - data.setString("FilterFluid#" + i, ""); - } - data.setTag("upgradeInventory", this.upgradeInventory.writeToNBT()); - } - - @Override - public final void writeToStream(ByteBuf data) throws IOException { - super.writeToStream(data); - } +public abstract class PartFluidIO extends PartECBase + implements IGridTickable, IInventoryUpdateReceiver, IFluidSlotPartOrBlock, IPartDeprecated { + + public Fluid[] filterFluids = new Fluid[9]; + private RedstoneMode redstoneMode = RedstoneMode.IGNORE; + protected byte filterSize; + protected byte speedState; + protected boolean redstoneControlled; + private boolean lastRedstone; + private final ECPrivateInventory upgradeInventory = new ECPrivateInventory("", 4, 1, this) { + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + if (itemStack == null) return false; + if (AEApi.instance().definitions().materials().cardCapacity().isSameAs(itemStack)) return true; + else if (AEApi.instance().definitions().materials().cardSpeed().isSameAs(itemStack)) return true; + else return AEApi.instance().definitions().materials().cardRedstone().isSameAs(itemStack); + } + }; + + @Override + public void getDrops(List drops, boolean wrenched) { + for (ItemStack stack : drops) { + if (stack.getItem().getClass() == ItemPartECBase.class) { + stack.stackTagCompound = null; + } + } + + for (ItemStack stack : upgradeInventory.slots) { + if (stack == null) continue; + drops.add(stack); + } + } + + @Override + public int cableConnectionRenderTo() { + return 5; + } + + private boolean canDoWork() { + boolean redstonePowered = isRedstonePowered(); + if (!this.redstoneControlled) return true; + switch (getRedstoneMode()) { + case IGNORE: + return true; + case LOW_SIGNAL: + return !redstonePowered; + case HIGH_SIGNAL: + return redstonePowered; + case SIGNAL_PULSE: + return false; + } + return false; + } + + public byte getSpeedState() { + return this.speedState; + } + + public abstract TickRateModulation doWork(int rate, int TicksSinceLastCall); + + @Override + public abstract void getBoxes(IPartCollisionHelper bch); + + @Override + public Object getClientGuiElement(EntityPlayer player) { + return new GuiBusFluidIO(this, player); + } + + public RedstoneMode getRedstoneMode() { + return this.redstoneMode; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerBusFluidIO(this, player); + } + + @Override + public final TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(5, 60, false, false); + } + + public ECPrivateInventory getUpgradeInventory() { + return this.upgradeInventory; + } + + @Override + public List getWailaBodey(NBTTagCompound tag, List oldList) { + if (tag.hasKey("speed")) oldList.add(tag.getInteger("speed") + "mB/t"); + else oldList.add(String.format("%smB/t", Extracells.basePartSpeed())); + return oldList; + } + + @Override + public NBTTagCompound getWailaTag(NBTTagCompound tag) { + tag.setInteger("speed", Extracells.basePartSpeed() + this.speedState * Extracells.basePartSpeed()); + return tag; + } + + public void loopRedstoneMode(EntityPlayer player) { + if (this.redstoneMode.ordinal() + 1 < RedstoneMode.values().length) + this.redstoneMode = RedstoneMode.values()[this.redstoneMode.ordinal() + 1]; + else this.redstoneMode = RedstoneMode.values()[0]; + new PacketBusFluidIO(this.redstoneMode).sendPacketToPlayer(player); + saveData(); + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + boolean activate = super.onActivate(player, pos); + onInventoryChanged(); + return activate; + } + + @Override + public void onInventoryChanged() { + this.filterSize = 0; + this.redstoneControlled = false; + this.speedState = 0; + for (int i = 0; i < this.upgradeInventory.getSizeInventory(); i++) { + ItemStack currentStack = this.upgradeInventory.getStackInSlot(i); + if (currentStack != null) { + if (AEApi.instance().definitions().materials().cardCapacity().isSameAs(currentStack)) this.filterSize++; + if (AEApi.instance().definitions().materials().cardRedstone().isSameAs(currentStack)) + this.redstoneControlled = true; + if (AEApi.instance().definitions().materials().cardSpeed().isSameAs(currentStack)) this.speedState++; + } + } + + try { + if (getHost().getLocation().getWorld().isRemote) return; + } catch (Throwable ignored) {} + new PacketBusFluidIO(this.filterSize).sendPacketToAllPlayers(); + new PacketBusFluidIO(this.redstoneControlled).sendPacketToAllPlayers(); + saveData(); + } + + @Override + public void onNeighborChanged() { + super.onNeighborChanged(); + boolean redstonePowered = isRedstonePowered(); + this.lastRedstone = redstonePowered; + } + + /** + * Map for converting slots from bus EC2 -> AE2FC + */ + private static int[] FILTER_MAP = null; + static { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FILTER_MAP = new int[] { 5, 3, 6, 1, 0, 2, 7, 4, 8 }; + } + } + + @Override + public final void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.redstoneMode = RedstoneMode.values()[data.getInteger("redstoneMode")]; + for (int i = 0; i < 9; i++) { + this.filterFluids[i] = FluidRegistry.getFluid(data.getString("FilterFluid#" + i)); + } + this.upgradeInventory.readFromNBT(data.getTagList("upgradeInventory", 10)); + onInventoryChanged(); + } + + @Override + public NBTTagCompound transformNBT(NBTTagCompound extra) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + // Transform NBT in place + // Fluid Filter + NBTTagCompound fluidFilterNew = new NBTTagCompound(); + for (int slot = 0; slot < 9; ++slot) { + String oldFilterName = "FilterFluid#" + slot; + fluidFilterNew + .setTag("#" + FILTER_MAP[slot], FluidCraft.createFluidDisplay(extra.getString(oldFilterName))); + extra.removeTag(oldFilterName); + } + extra.setTag("config", fluidFilterNew); + // Upgrades + NBTTagList upgrades = extra.getTagList("upgradeInventory", TAG_COMPOUND); + NBTTagCompound upgradesNew = new NBTTagCompound(); + for (int i = 0; i < 4; ++i) { + NBTTagCompound upgrade = upgrades.getCompoundTagAt(i); + upgrade.removeTag("Slot"); + upgradesNew.setTag("#" + i, upgrade); + } + extra.removeTag("upgradeInventory"); + extra.setTag("upgrades", upgradesNew); + // Redstone mode + RedstoneMode redstoneMode = RedstoneMode.values()[extra.getInteger("redstoneMode")]; + switch (redstoneMode) { + case LOW_SIGNAL: + extra.setString("REDSTONE_CONTROLLED", "LOW_SIGNAL"); + break; + case HIGH_SIGNAL: + extra.setString("REDSTONE_CONTROLLED", "HIGH_SIGNAL"); + break; + case SIGNAL_PULSE: + extra.setString("REDSTONE_CONTROLLED", "SIGNAL_PULSE"); + break; + default: + extra.setString("REDSTONE_CONTROLLED", "IGNORE"); + break; + } + extra.removeTag("redstoneMode"); + // Part data + extra.setTag("part", extra.getCompoundTag("node").getCompoundTag("node0")); + extra.removeTag("node"); + // Extra tags + extra.setString("CRAFT_ONLY", "NO"); + extra.setString("FUZZY_MODE", "IGNORE_ALL"); + extra.setString("SCHEDULING_MODE", "DEFAULT"); + } + return extra; + } + + @Override + public final boolean readFromStream(ByteBuf data) throws IOException { + return super.readFromStream(data); + } + + @SideOnly(Side.CLIENT) + @Override + public final void renderDynamic(double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer) {} + + @SideOnly(Side.CLIENT) + @Override + public abstract void renderInventory(IPartRenderHelper rh, RenderBlocks renderer); + + @SideOnly(Side.CLIENT) + @Override + public abstract void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer); + + public void sendInformation(EntityPlayer player) { + new PacketFluidSlot(Arrays.asList(this.filterFluids)).sendPacketToPlayer(player); + new PacketBusFluidIO(this.redstoneMode).sendPacketToPlayer(player); + new PacketBusFluidIO(this.filterSize).sendPacketToPlayer(player); + } + + @Override + public final void setFluid(int index, Fluid fluid, EntityPlayer player) { + this.filterFluids[index] = fluid; + new PacketFluidSlot(Arrays.asList(this.filterFluids)).sendPacketToPlayer(player); + saveData(); + } + + @Override + public void setPartHostInfo(ForgeDirection _side, IPartHost _host, TileEntity _tile) { + super.setPartHostInfo(_side, _host, _tile); + onInventoryChanged(); + } + + @Override + public final TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { + return canDoWork() + ? doWork(Extracells.basePartSpeed() + this.speedState * Extracells.basePartSpeed(), TicksSinceLastCall) + : TickRateModulation.IDLE; + } + + @Override + public final void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setInteger("redstoneMode", this.redstoneMode.ordinal()); + for (int i = 0; i < this.filterFluids.length; i++) { + Fluid fluid = this.filterFluids[i]; + if (fluid != null) data.setString("FilterFluid#" + i, fluid.getName()); + else data.setString("FilterFluid#" + i, ""); + } + data.setTag("upgradeInventory", this.upgradeInventory.writeToNBT()); + } + + @Override + public final void writeToStream(ByteBuf data) throws IOException { + super.writeToStream(data); + } } diff --git a/src/main/scala/extracells/part/PartFluidImport.java b/src/main/scala/extracells/part/PartFluidImport.java index ad6b24beb..20a19b1fd 100644 --- a/src/main/scala/extracells/part/PartFluidImport.java +++ b/src/main/scala/extracells/part/PartFluidImport.java @@ -1,228 +1,254 @@ package extracells.part; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.FluidTankInfo; +import net.minecraftforge.fluids.IFluidHandler; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; +import appeng.api.networking.ticking.TickRateModulation; import appeng.api.parts.IPart; import appeng.api.parts.IPartCollisionHelper; import appeng.api.parts.IPartRenderHelper; import appeng.api.storage.data.IAEFluidStack; import appeng.api.util.AEColor; +import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import extracells.Extracells; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; +import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.PermissionUtil; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.FluidTankInfo; -import net.minecraftforge.fluids.IFluidHandler; - -import java.util.ArrayList; -import java.util.List; public class PartFluidImport extends PartFluidIO implements IFluidHandler { - @Override - public int cableConnectionRenderTo() { - return 5; - } - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return false; - } - - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return true; - } - - @Override - public boolean doWork(int rate, int TicksSinceLastCall) { - if (getFacingTank() == null || !isActive()) - return false; - boolean empty = true; - - List filter = new ArrayList(); - filter.add(this.filterFluids[4]); - - if (this.filterSize >= 1) { - for (byte i = 1; i < 9; i += 2) { - if (i != 4) { - filter.add(this.filterFluids[i]); - } - } - } - - if (this.filterSize >= 2) { - for (byte i = 0; i < 9; i += 2) { - if (i != 4) { - filter.add(this.filterFluids[i]); - } - } - } - - for (Fluid fluid : filter) { - if (fluid != null) { - empty = false; - - if (fillToNetwork(fluid, rate * TicksSinceLastCall)) { - return true; - } - } - } - return empty && fillToNetwork(null, rate * TicksSinceLastCall); - } - - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, - boolean doDrain) { - return null; - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - return null; - } - - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - boolean redstonePowered = isRedstonePowered(); - if (resource == null || redstonePowered && getRedstoneMode() == RedstoneMode.LOW_SIGNAL || !redstonePowered && getRedstoneMode() == RedstoneMode.HIGH_SIGNAL) - return 0; - int drainAmount = Math.min(125 + this.speedState * 125, resource.amount); - FluidStack toFill = new FluidStack(resource.getFluid(), drainAmount); - Actionable action = doFill ? Actionable.MODULATE : Actionable.SIMULATE; - IAEFluidStack filled = injectFluid(AEApi.instance().storage().createFluidStack(toFill), action); - if (filled == null) - return toFill.amount; - return toFill.amount - (int) filled.getStackSize(); - } - - protected boolean fillToNetwork(Fluid fluid, int toDrain) { - FluidStack drained; - IFluidHandler facingTank = getFacingTank(); - ForgeDirection side = getSide(); - if (fluid == null) { - drained = facingTank.drain(side.getOpposite(), toDrain, false); - } else { - drained = facingTank.drain(side.getOpposite(), new FluidStack( - fluid, toDrain), false); - } - - if (drained == null || drained.amount <= 0 || drained.getFluidID() <= 0) - return false; - - IAEFluidStack toFill = AEApi.instance().storage() - .createFluidStack(drained); - IAEFluidStack notInjected = injectFluid(toFill, Actionable.MODULATE); - - if (notInjected != null) { - int amount = (int) (toFill.getStackSize() - notInjected - .getStackSize()); - if (amount > 0) { - if (fluid == null) - facingTank.drain(side.getOpposite(), amount, true); - else - facingTank.drain(side.getOpposite(), - new FluidStack(toFill.getFluid(), amount), true); - return true; - } else { - return false; - } - } else { - if (fluid == null) - facingTank.drain(side.getOpposite(), - toFill.getFluidStack().amount, true); - else - facingTank.drain(side.getOpposite(), toFill.getFluidStack(), - true); - return true; - } - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(4, 4, 14, 12, 12, 16); - bch.addBox(5, 5, 13, 11, 11, 14); - bch.addBox(6, 6, 12, 10, 10, 13); - bch.addBox(6, 6, 11, 10, 10, 12); - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return new FluidTankInfo[0]; - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - return PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this) && super.onActivate(player, pos); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.IMPORT_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.IMPORT_FRONT.getTexture(), side, side); - rh.setBounds(4, 4, 14, 12, 12, 16); - rh.renderInventoryBox(renderer); - - rh.setTexture(side); - rh.setBounds(5, 5, 13, 11, 11, 14); - rh.renderInventoryBox(renderer); - rh.setBounds(6, 6, 12, 10, 10, 13); - rh.renderInventoryBox(renderer); - - rh.setBounds(4, 4, 14, 12, 12, 16); - rh.setInvColor(AEColor.Cyan.blackVariant); - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderInventoryFace(TextureManager.IMPORT_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(6, 6, 11, 10, 10, 12); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.IMPORT_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.IMPORT_FRONT.getTextures()[0], side, side); - rh.setBounds(4, 4, 14, 12, 12, 16); - rh.renderBlock(x, y, z, renderer); - - ts.setColorOpaque_I(getHost().getColor().blackVariant); - if (isActive()) - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderFace(x, y, z, TextureManager.IMPORT_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - - rh.setTexture(side); - 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.setBounds(6, 6, 11, 10, 10, 12); - renderStaticBusLights(x, y, z, rh, renderer); - } + @Override + public int cableConnectionRenderTo() { + return 5; + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return false; + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return true; + } + + @Override + public TickRateModulation doWork(int rate, int TicksSinceLastCall) { + if (!isActive() || getFacingTank() == null) return TickRateModulation.IDLE; + boolean empty = true; + + List filter = new ArrayList(); + filter.add(this.filterFluids[4]); + + if (this.filterSize >= 1) { + for (byte i = 1; i < 9; i += 2) { + if (i != 4) { + filter.add(this.filterFluids[i]); + } + } + } + + if (this.filterSize >= 2) { + for (byte i = 0; i < 9; i += 2) { + if (i != 4) { + filter.add(this.filterFluids[i]); + } + } + } + + for (Fluid fluid : filter) { + if (fluid != null) { + empty = false; + + if (fillToNetwork(fluid, rate * TicksSinceLastCall)) { + return TickRateModulation.FASTER; + } + } + } + return (empty && fillToNetwork(null, rate * TicksSinceLastCall)) ? TickRateModulation.FASTER + : TickRateModulation.SLOWER; + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + return null; + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + return null; + } + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + boolean redstonePowered = isRedstonePowered(); + if (resource == null || redstonePowered && getRedstoneMode() == RedstoneMode.LOW_SIGNAL + || !redstonePowered && getRedstoneMode() == RedstoneMode.HIGH_SIGNAL) + return 0; + int drainAmount = Math + .min(Extracells.basePartSpeed() + this.speedState * Extracells.basePartSpeed(), resource.amount); + FluidStack toFill = new FluidStack(resource.getFluid(), drainAmount); + Actionable action = doFill ? Actionable.MODULATE : Actionable.SIMULATE; + IAEFluidStack filled = injectFluid(AEApi.instance().storage().createFluidStack(toFill), action); + if (filled == null) return toFill.amount; + return toFill.amount - (int) filled.getStackSize(); + } + + protected boolean fillToNetwork(Fluid fluid, int toDrain) { + FluidStack drained; + IFluidHandler facingTank = getFacingTank(); + ForgeDirection side = getSide(); + if (fluid == null) { + drained = facingTank.drain(side.getOpposite(), toDrain, false); + } else { + drained = facingTank.drain(side.getOpposite(), new FluidStack(fluid, toDrain), false); + if (drained != null && drained.getFluidID() != fluid.getID()) { + return false; + } + } + + if (drained == null || drained.amount <= 0 || drained.getFluidID() <= 0) return false; + + IAEFluidStack toFill = AEApi.instance().storage().createFluidStack(drained); + IAEFluidStack notInjected = injectFluid(toFill, Actionable.SIMULATE); + + int amount = toFill.getFluidStack().amount; + if (notInjected != null) { + amount -= notInjected.getFluidStack().amount; + } + if (amount > 0) { + FluidStack actuallyDrained; + if (fluid == null) { + actuallyDrained = facingTank.drain(side.getOpposite(), amount, true); + } else { + actuallyDrained = facingTank.drain(side.getOpposite(), new FluidStack(toFill.getFluid(), amount), true); + if (actuallyDrained != null && actuallyDrained.getFluidID() != fluid.getID()) { + return false; + } + } + if (actuallyDrained == null || actuallyDrained.amount <= 0) { + return false; + } + toFill.setStackSize(actuallyDrained.amount); + IAEFluidStack actuallyNotInjected = injectFluid(toFill, Actionable.MODULATE); + if (actuallyNotInjected != null && actuallyNotInjected.getStackSize() > 0) { + // attempt to return fluid + int returned = facingTank.fill(side.getOpposite(), actuallyNotInjected.getFluidStack(), true); + if (returned != actuallyNotInjected.getStackSize()) { + FMLLog.severe( + "[ExtraCells2] Import bus at %d:%d,%d,%d voided %d mL of %s", + tile.getWorldObj().provider.dimensionId, + tile.xCoord, + tile.yCoord, + tile.zCoord, + actuallyNotInjected.getStackSize() - returned, + fluid.getName()); + } + } + return true; + } else { + return false; + } + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(4, 4, 14, 12, 12, 16); + bch.addBox(5, 5, 13, 11, 11, 14); + bch.addBox(6, 6, 12, 10, 10, 13); + bch.addBox(6, 6, 11, 10, 10, 12); + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return new FluidTankInfo[0]; + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + return PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this) + && super.onActivate(player, pos); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = TextureManager.IMPORT_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.IMPORT_FRONT.getTexture(), side, side); + rh.setBounds(4, 4, 14, 12, 12, 16); + rh.renderInventoryBox(renderer); + + rh.setTexture(side); + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderInventoryBox(renderer); + rh.setBounds(6, 6, 12, 10, 10, 13); + rh.renderInventoryBox(renderer); + + rh.setBounds(4, 4, 14, 12, 12, 16); + rh.setInvColor(AEColor.Cyan.blackVariant); + ts.setBrightness(15 << 20 | 15 << 4); + rh.renderInventoryFace(TextureManager.IMPORT_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + + rh.setBounds(6, 6, 11, 10, 10, 12); + renderInventoryBusLights(rh, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = TextureManager.IMPORT_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.IMPORT_FRONT.getTextures()[0], side, side); + rh.setBounds(4, 4, 14, 12, 12, 16); + rh.renderBlock(x, y, z, renderer); + + ts.setColorOpaque_I(getHost().getColor().blackVariant); + if (isActive()) ts.setBrightness(15 << 20 | 15 << 4); + rh.renderFace(x, y, z, TextureManager.IMPORT_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + + rh.setTexture(side); + 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.setBounds(6, 6, 11, 10, 10, 12); + renderStaticBusLights(x, y, z, rh, renderer); + } + + @Override + public NBTTagCompound transformPart(NBTTagCompound def) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FluidCraft.replace(def, PartEnum.FLUIDIMPORT); + } + return def; + } } diff --git a/src/main/scala/extracells/part/PartFluidInterface.java b/src/main/scala/extracells/part/PartFluidInterface.java index de66976ab..3ea08c234 100644 --- a/src/main/scala/extracells/part/PartFluidInterface.java +++ b/src/main/scala/extracells/part/PartFluidInterface.java @@ -1,5 +1,29 @@ package extracells.part; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.StatCollector; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.Constants; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.*; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; @@ -19,16 +43,19 @@ import appeng.api.networking.ticking.TickingRequest; import appeng.api.parts.IPart; import appeng.api.parts.IPartCollisionHelper; +import appeng.api.parts.IPartDeprecated; import appeng.api.parts.IPartRenderHelper; -import appeng.api.parts.PartItemStack; import appeng.api.storage.IMEMonitor; import appeng.api.storage.IStorageMonitorable; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEStack; +import appeng.util.InventoryAdaptor; +import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import extracells.Extracells; import extracells.api.IFluidInterface; import extracells.api.crafting.IFluidCraftingPatternDetails; import extracells.container.ContainerFluidInterface; @@ -36,1055 +63,880 @@ import extracells.crafting.CraftingPattern; import extracells.crafting.CraftingPattern2; import extracells.gui.GuiFluidInterface; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; import extracells.network.packet.other.IFluidSlotPartOrBlock; import extracells.registries.ItemEnum; import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.EmptyMeItemMonitor; -import extracells.util.ItemUtils; +import extracells.util.FluidUtil; import extracells.util.PermissionUtil; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.util.StatCollector; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.*; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -public class PartFluidInterface extends PartECBase implements IFluidHandler, - IFluidInterface, IFluidSlotPartOrBlock, ITileStorageMonitorable, - IStorageMonitorable, IGridTickable, ICraftingProvider { - - private class FluidInterfaceInventory implements IInventory { - - private ItemStack[] inv = new ItemStack[9]; - - @Override - public void closeInventory() {} - - @Override - public ItemStack decrStackSize(int slot, int amt) { - ItemStack stack = getStackInSlot(slot); - if (stack != null) { - if (stack.stackSize <= amt) { - setInventorySlotContents(slot, null); - } else { - stack = stack.splitStack(amt); - if (stack.stackSize == 0) { - setInventorySlotContents(slot, null); - } - } - } - PartFluidInterface.this.update = true; - return stack; - } - - @Override - public String getInventoryName() { - return "inventory.fluidInterface"; - } - - @Override - public int getInventoryStackLimit() { - return 1; - } - - @Override - public int getSizeInventory() { - return this.inv.length; - } - - @Override - public ItemStack getStackInSlot(int slot) { - return this.inv[slot]; - } - - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return null; - } - - @Override - public boolean hasCustomInventoryName() { - return false; - } - - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - if (stack.getItem() instanceof ICraftingPatternItem) { - IGridNode n = getGridNode(); - World w; - if (n == null) { - w = getClientWorld(); - } else { - w = n.getWorld(); - } - if (w == null) - return false; - ICraftingPatternDetails details = ((ICraftingPatternItem) stack - .getItem()).getPatternForItem(stack, w); - return details != null; - } - return false; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer player) { - return true; - } - - @Override - public void markDirty() {} - - @Override - public void openInventory() {} - - public void readFromNBT(NBTTagCompound tagCompound) { - - NBTTagList tagList = tagCompound.getTagList("Inventory", 10); - for (int i = 0; i < tagList.tagCount(); i++) { - NBTTagCompound tag = tagList.getCompoundTagAt(i); - byte slot = tag.getByte("Slot"); - if (slot >= 0 && slot < this.inv.length) { - this.inv[slot] = ItemStack.loadItemStackFromNBT(tag); - } - } - } - - @Override - public void setInventorySlotContents(int slot, ItemStack stack) { - this.inv[slot] = stack; - if (stack != null && stack.stackSize > getInventoryStackLimit()) { - stack.stackSize = getInventoryStackLimit(); - } - PartFluidInterface.this.update = true; - } - - public void writeToNBT(NBTTagCompound tagCompound) { - NBTTagList itemList = new NBTTagList(); - for (int i = 0; i < this.inv.length; i++) { - ItemStack stack = this.inv[i]; - if (stack != null) { - NBTTagCompound tag = new NBTTagCompound(); - tag.setByte("Slot", (byte) i); - stack.writeToNBT(tag); - itemList.appendTag(tag); - } - } - tagCompound.setTag("Inventory", itemList); - } - } - - List listeners = new ArrayList(); - private List patternHandlers = new ArrayList(); - private HashMap patternConvert = new HashMap(); - private List requestedItems = new ArrayList(); - private List removeList = new ArrayList(); - public final FluidInterfaceInventory inventory = new FluidInterfaceInventory(); - - private boolean update = false; - private List export = new ArrayList(); - private List removeFromExport = new ArrayList(); - - private List addToExport = new ArrayList(); - private IAEItemStack toExport = null; - - private final Item encodedPattern = AEApi.instance().definitions().items().encodedPattern().maybeItem().orNull(); - private FluidTank tank = new FluidTank(10000) { - @Override - public FluidTank readFromNBT(NBTTagCompound nbt) { - if (!nbt.hasKey("Empty")) { - FluidStack fluid = FluidStack.loadFluidStackFromNBT(nbt); - setFluid(fluid); - } else { - setFluid(null); - } - return this; - } - }; - private int fluidFilter = -1; - public boolean doNextUpdate = false; - private boolean needBreake = false; - - private int tickCount = 0; - - @Override - public int cableConnectionRenderTo() { - return 3; - } - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - FluidStack tankFluid = this.tank.getFluid(); - return tankFluid != null && tankFluid.getFluid() == fluid; - } - - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return this.tank.fill(new FluidStack(fluid, 1), false) > 0; - } - - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, - boolean doDrain) { - FluidStack tankFluid = this.tank.getFluid(); - if (resource == null || tankFluid == null - || tankFluid.getFluid() != resource.getFluid()) - return null; - return drain(from, resource.amount, doDrain); - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - FluidStack drained = this.tank.drain(maxDrain, doDrain); - if (drained != null) - getHost().markForUpdate(); - this.doNextUpdate = true; - return drained; - } - - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - if (resource == null) - return 0; - - if ((this.tank.getFluid() == null || this.tank.getFluid().getFluid() == resource - .getFluid()) - && resource.getFluid() == FluidRegistry - .getFluid(this.fluidFilter)) { - int added = this.tank.fill(resource.copy(), doFill); - if (added == resource.amount) { - this.doNextUpdate = true; - return added; - } - added += fillToNetwork(new FluidStack(resource.getFluid(), - resource.amount - added), doFill); - this.doNextUpdate = true; - return added; - } - - int filled = 0; - filled += fillToNetwork(resource, doFill); - - if (filled < resource.amount) - filled += this.tank.fill(new FluidStack(resource.getFluid(), - resource.amount - filled), doFill); - if (filled > 0) - getHost().markForUpdate(); - this.doNextUpdate = true; - return filled; - } - - public int fillToNetwork(FluidStack resource, boolean doFill) { - IGridNode node = getGridNode(ForgeDirection.UNKNOWN); - if (node == null || resource == null) - return 0; - IGrid grid = node.getGrid(); - if (grid == null) - return 0; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return 0; - IAEFluidStack notRemoved; - FluidStack copy = resource.copy(); - if (doFill) { - notRemoved = storage.getFluidInventory().injectItems( - AEApi.instance().storage().createFluidStack(resource), - Actionable.MODULATE, new MachineSource(this)); - } else { - notRemoved = storage.getFluidInventory().injectItems( - AEApi.instance().storage().createFluidStack(resource), - Actionable.SIMULATE, new MachineSource(this)); - } - if (notRemoved == null) - return resource.amount; - return (int) (resource.amount - notRemoved.getStackSize()); - } - - private void forceUpdate() { - getHost().markForUpdate(); - for (IContainerListener listener : this.listeners) { - if (listener != null) - listener.updateContainer(); - } - this.doNextUpdate = false; - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 14, 14, 14, 16); - bch.addBox(5, 5, 12, 11, 11, 14); - - } - - @Override - public Object getClientGuiElement(EntityPlayer player) { - return new GuiFluidInterface(player, this, getSide()); - } - - @SideOnly(Side.CLIENT) - private World getClientWorld() { - return Minecraft.getMinecraft().theWorld; - } - - @Override - public void getDrops(List drops, boolean wrenched) { - for (int i = 0; i < this.inventory.getSizeInventory(); i++) { - ItemStack pattern = this.inventory.getStackInSlot(i); - if (pattern != null) - drops.add(pattern); - } - } - - - - @Override - public Fluid getFilter(ForgeDirection side) { - return FluidRegistry.getFluid(this.fluidFilter); - } - - @Override - public IMEMonitor getFluidInventory() { - if (getGridNode(ForgeDirection.UNKNOWN) == null) - return null; - IGrid grid = getGridNode(ForgeDirection.UNKNOWN).getGrid(); - if (grid == null) - return null; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return null; - return storage.getFluidInventory(); - } - - @Override - public IFluidTank getFluidTank(ForgeDirection side) { - return this.tank; - } - - @Override - public IMEMonitor getItemInventory() { - return new EmptyMeItemMonitor(); - } - - @Override - public ItemStack getItemStack(PartItemStack type) { - ItemStack is = new ItemStack(ItemEnum.PARTITEM.getItem(), 1, - PartEnum.getPartID(this)); - if (type != PartItemStack.Break) { - is.setTagCompound(writeFilter(new NBTTagCompound())); - } - return is; - } - - @Override - public IStorageMonitorable getMonitorable(ForgeDirection side, - BaseActionSource src) { - return this; - } - - @Override - public IInventory getPatternInventory() { - return this.inventory; - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerFluidInterface(player, this); - } - - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return new FluidTankInfo[] { this.tank.getInfo() }; - } - - @Override - public TickingRequest getTickingRequest(IGridNode node) { - return new TickingRequest(1, 40, false, false); - } - - @Override - public List getWailaBodey(NBTTagCompound tag, List list) { - FluidStack fluid = null; - int id = -1; - int amount = 0; - if (tag.hasKey("fluidID") && tag.hasKey("amount")) { - id = tag.getInteger("fluidID"); - amount = tag.getInteger("amount"); - } - if (id != -1) - fluid = new FluidStack(id, amount); - if (fluid == null) { - list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " - + StatCollector - .translateToLocal("extracells.tooltip.empty1")); - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": 0mB / 10000mB"); - } else { - list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " + fluid.getLocalizedName()); - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": " - + fluid.amount + "mB / 10000mB"); - } - return list; - } - - @Override - public NBTTagCompound getWailaTag(NBTTagCompound tag) { - if (this.tank.getFluid() == null - || this.tank.getFluid().getFluid() == null) - tag.setInteger("fluidID", -1); - else - tag.setInteger("fluidID", this.tank.getFluid().getFluidID()); - tag.setInteger("amount", this.tank.getFluidAmount()); - return tag; - } - - @Override - public void initializePart(ItemStack partStack) { - if (partStack.hasTagCompound()) { - readFilter(partStack.getTagCompound()); - } - } - - @Override - public boolean isBusy() { - return !this.export.isEmpty(); - } - - private ItemStack makeCraftingPatternItem(ICraftingPatternDetails details) { - if (details == null) - return null; - NBTTagList in = new NBTTagList(); - NBTTagList out = new NBTTagList(); - for (IAEItemStack s : details.getInputs()) { - if (s == null) - in.appendTag(new NBTTagCompound()); - else - in.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); - } - for (IAEItemStack s : details.getOutputs()) { - if (s == null) - out.appendTag(new NBTTagCompound()); - else - out.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); - } - NBTTagCompound itemTag = new NBTTagCompound(); - itemTag.setTag("in", in); - itemTag.setTag("out", out); - itemTag.setBoolean("crafting", details.isCraftable()); - ItemStack pattern = new ItemStack(this.encodedPattern); - pattern.setTagCompound(itemTag); - return pattern; - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, - (IPart) this)) { - return super.onActivate(player, pos); - } - return false; - } - - @Override - public void provideCrafting(ICraftingProviderHelper craftingTracker) { - this.patternHandlers = new ArrayList(); - this.patternConvert.clear(); - - for (ItemStack currentPatternStack : this.inventory.inv) { - if (currentPatternStack != null - && currentPatternStack.getItem() != null - && currentPatternStack.getItem() instanceof ICraftingPatternItem) { - ICraftingPatternItem currentPattern = (ICraftingPatternItem) currentPatternStack - .getItem(); - - if (currentPattern != null - && currentPattern.getPatternForItem( - currentPatternStack, getGridNode().getWorld()) != null) { - IFluidCraftingPatternDetails pattern = new CraftingPattern2( - currentPattern.getPatternForItem( - currentPatternStack, getGridNode() - .getWorld())); - this.patternHandlers.add(pattern); - ItemStack is = makeCraftingPatternItem(pattern); - if (is == null) - continue; - ICraftingPatternDetails p = ((ICraftingPatternItem) is - .getItem()).getPatternForItem(is, getGridNode() - .getWorld()); - this.patternConvert.put(p, pattern); - craftingTracker.addCraftingOption(this, p); - } - } - } - } - - private void pushItems() { - for (IAEStack s : this.removeFromExport) { - this.export.remove(s); - } - this.removeFromExport.clear(); - for (IAEStack s : this.addToExport) { - this.export.add(s); - } - this.addToExport.clear(); - if (getGridNode().getWorld() == null || this.export.isEmpty()) - return; - ForgeDirection dir = getSide(); - TileEntity tile = getGridNode().getWorld().getTileEntity( - getGridNode().getGridBlock().getLocation().x + dir.offsetX, - getGridNode().getGridBlock().getLocation().y + dir.offsetY, - getGridNode().getGridBlock().getLocation().z + dir.offsetZ); - if (tile != null) { - IAEStack stack0 = this.export.iterator().next(); - IAEStack stack = stack0.copy(); - if (stack instanceof IAEItemStack && tile instanceof IInventory) { - if (tile instanceof ISidedInventory) { - ISidedInventory inv = (ISidedInventory) tile; - for (int i : inv.getAccessibleSlotsFromSide(dir - .getOpposite().ordinal())) { - if (inv.canInsertItem(i, ((IAEItemStack) stack) - .getItemStack(), dir.getOpposite().ordinal())) { - if (inv.getStackInSlot(i) == null) { - inv.setInventorySlotContents(i, - ((IAEItemStack) stack).getItemStack()); - this.removeFromExport.add(stack0); - return; - } else if (ItemUtils.areItemEqualsIgnoreStackSize( - inv.getStackInSlot(i), - ((IAEItemStack) stack).getItemStack())) { - int max = inv.getInventoryStackLimit(); - int current = inv.getStackInSlot(i).stackSize; - int outStack = (int) stack.getStackSize(); - if (max == current) - continue; - if (current + outStack <= max) { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = s.stackSize + outStack; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - return; - } else { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = max; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - stack.setStackSize(outStack - max + current); - this.addToExport.add(stack); - return; - } - } - } - } - } else { - IInventory inv = (IInventory) tile; - for (int i = 0; i < inv.getSizeInventory(); i++) { - if (inv.isItemValidForSlot(i, - ((IAEItemStack) stack).getItemStack())) { - if (inv.getStackInSlot(i) == null) { - inv.setInventorySlotContents(i, - ((IAEItemStack) stack).getItemStack()); - this.removeFromExport.add(stack0); - return; - } else if (ItemUtils.areItemEqualsIgnoreStackSize( - inv.getStackInSlot(i), - ((IAEItemStack) stack).getItemStack())) { - int max = inv.getInventoryStackLimit(); - int current = inv.getStackInSlot(i).stackSize; - int outStack = (int) stack.getStackSize(); - if (max == current) - continue; - if (current + outStack <= max) { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = s.stackSize + outStack; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - return; - } else { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = max; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - stack.setStackSize(outStack - max + current); - this.addToExport.add(stack); - return; - } - } - } - } - } - } else if (stack instanceof IAEFluidStack - && tile instanceof IFluidHandler) { - IFluidHandler handler = (IFluidHandler) tile; - IAEFluidStack fluid = (IAEFluidStack) stack; - if (handler.canFill(dir.getOpposite(), fluid.copy().getFluid())) { - int amount = handler.fill(dir.getOpposite(), fluid - .getFluidStack().copy(), false); - if (amount == 0) - return; - if (amount == fluid.getStackSize()) { - handler.fill(dir.getOpposite(), fluid.getFluidStack() - .copy(), true); - this.removeFromExport.add(stack0); - } else { - IAEFluidStack f = fluid.copy(); - f.setStackSize(f.getStackSize() - amount); - FluidStack fl = fluid.getFluidStack().copy(); - fl.amount = amount; - handler.fill(dir.getOpposite(), fl, true); - this.removeFromExport.add(stack0); - this.addToExport.add(f); - return; - } - } - } - } - } - - @Override - public boolean pushPattern(ICraftingPatternDetails patDetails, - InventoryCrafting table) { - if (isBusy() || !this.patternConvert.containsKey(patDetails)) - return false; - ICraftingPatternDetails patternDetails = this.patternConvert - .get(patDetails); - if (patternDetails instanceof CraftingPattern) { - CraftingPattern patter = (CraftingPattern) patternDetails; - HashMap fluids = new HashMap(); - for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { - if (fluids.containsKey(stack.getFluid())) { - Long amount = fluids.get(stack.getFluid()) - + stack.getStackSize(); - fluids.remove(stack.getFluid()); - fluids.put(stack.getFluid(), amount); - } else { - fluids.put(stack.getFluid(), stack.getStackSize()); - } - } - IGrid grid = getGridNode().getGrid(); - if (grid == null) - return false; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return false; - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory() - .extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack(fluid, - (int) (amount + 0))), - Actionable.SIMULATE, new MachineSource(this)); - if (extractFluid == null - || extractFluid.getStackSize() != amount) { - return false; - } - } - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory() - .extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack(fluid, - (int) (amount + 0))), - Actionable.MODULATE, new MachineSource(this)); - this.export.add(extractFluid); - } - for (IAEItemStack s : patter.getCondensedInputs()) { - if (s == null) - continue; - if (s.getItem() == ItemEnum.FLUIDPATTERN.getItem()) { - this.toExport = s.copy(); - continue; - } - this.export.add(s); - } - } - return true; - } - - public void readFilter(NBTTagCompound tag) { - if (tag.hasKey("filter")) - this.fluidFilter = tag.getInteger("filter"); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - if (data.hasKey("tank")) - this.tank.readFromNBT(data.getCompoundTag("tank")); - if (data.hasKey("filter")) - this.fluidFilter = data.getInteger("filter"); - if (data.hasKey("inventory")) - this.inventory.readFromNBT(data.getCompoundTag("inventory")); - if (data.hasKey("export")) - readOutputFromNBT(data.getCompoundTag("export")); - } - - @Override - public boolean readFromStream(ByteBuf data) throws IOException { - super.readFromStream(data); - NBTTagCompound tag = ByteBufUtils.readTag(data); - if (tag.hasKey("tank")) - this.tank.readFromNBT(tag.getCompoundTag("tank")); - if (tag.hasKey("filter")) - this.fluidFilter = tag.getInteger("filter"); - if (tag.hasKey("inventory")) - this.inventory.readFromNBT(tag.getCompoundTag("inventory")); - return true; - } - - private void readOutputFromNBT(NBTTagCompound tag) { - this.addToExport.clear(); - this.removeFromExport.clear(); - this.export.clear(); - int i = tag.getInteger("remove"); - for (int j = 0; j < i; j++) { - if (tag.getBoolean("remove-" + j + "-isItem")) { - IAEItemStack s = AEApi - .instance() - .storage() - .createItemStack( - ItemStack.loadItemStackFromNBT(tag - .getCompoundTag("remove-" + j))); - s.setStackSize(tag.getLong("remove-" + j + "-amount")); - this.removeFromExport.add(s); - } else { - IAEFluidStack s = AEApi - .instance() - .storage() - .createFluidStack( - FluidStack.loadFluidStackFromNBT(tag - .getCompoundTag("remove-" + j))); - s.setStackSize(tag.getLong("remove-" + j + "-amount")); - this.removeFromExport.add(s); - } - } - i = tag.getInteger("add"); - for (int j = 0; j < i; j++) { - if (tag.getBoolean("add-" + j + "-isItem")) { - IAEItemStack s = AEApi - .instance() - .storage() - .createItemStack( - ItemStack.loadItemStackFromNBT(tag - .getCompoundTag("add-" + j))); - s.setStackSize(tag.getLong("add-" + j + "-amount")); - this.addToExport.add(s); - } else { - IAEFluidStack s = AEApi - .instance() - .storage() - .createFluidStack( - FluidStack.loadFluidStackFromNBT(tag - .getCompoundTag("add-" + j))); - s.setStackSize(tag.getLong("add-" + j + "-amount")); - this.addToExport.add(s); - } - } - i = tag.getInteger("export"); - for (int j = 0; j < i; j++) { - if (tag.getBoolean("export-" + j + "-isItem")) { - IAEItemStack s = AEApi - .instance() - .storage() - .createItemStack( - ItemStack.loadItemStackFromNBT(tag - .getCompoundTag("export-" + j))); - s.setStackSize(tag.getLong("export-" + j + "-amount")); - this.export.add(s); - } else { - IAEFluidStack s = AEApi - .instance() - .storage() - .createFluidStack( - FluidStack.loadFluidStackFromNBT(tag - .getCompoundTag("export-" + j))); - s.setStackSize(tag.getLong("export-" + j + "-amount")); - this.export.add(s); - } - } - } - - public void registerListener(IContainerListener listener) { - this.listeners.add(listener); - } - - public void removeListener(IContainerListener listener) { - this.listeners.remove(listener); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.BUS_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.INTERFACE.getTextures()[0], side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderInventoryBox(renderer); - - rh.renderInventoryFace(TextureManager.INTERFACE.getTextures()[0], - ForgeDirection.SOUTH, renderer); - - rh.setTexture(side); - rh.setBounds(5, 5, 12, 11, 11, 14); - rh.renderInventoryBox(renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.BUS_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.INTERFACE.getTextures()[0], side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - - ts.setBrightness(20971520); - rh.renderFace(x, y, z, TextureManager.INTERFACE.getTextures()[0], - ForgeDirection.SOUTH, renderer); - - rh.setTexture(side); - rh.setBounds(5, 5, 12, 11, 11, 14); - rh.renderBlock(x, y, z, renderer); - } - - @Override - public void setFilter(ForgeDirection side, Fluid fluid) { - if (fluid == null) { - this.fluidFilter = -1; - this.doNextUpdate = true; - return; - } - this.fluidFilter = fluid.getID(); - this.doNextUpdate = true; - - } - - @Override - public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { - setFilter(ForgeDirection.getOrientation(_index), _fluid); - } - - @Override - public void setFluidTank(ForgeDirection side, FluidStack fluid) { - this.tank.setFluid(fluid); - this.doNextUpdate = true; - } - - @Override - public TickRateModulation tickingRequest(IGridNode node, - int TicksSinceLastCall) { - if (this.doNextUpdate) - forceUpdate(); - IGrid grid = node.getGrid(); - if (grid == null) - return TickRateModulation.URGENT; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return TickRateModulation.URGENT; - pushItems(); - if (this.toExport != null) { - storage.getItemInventory().injectItems(this.toExport, - Actionable.MODULATE, new MachineSource(this)); - this.toExport = null; - } - if (this.update) { - this.update = false; - if (getGridNode() != null && getGridNode().getGrid() != null) { - getGridNode().getGrid() - .postEvent( - new MENetworkCraftingPatternChange(this, - getGridNode())); - } - } - if (this.tank.getFluid() != null - && FluidRegistry.getFluid(this.fluidFilter) != this.tank - .getFluid().getFluid()) { - FluidStack s = this.tank.drain(125, false); - if (s != null) { - IAEFluidStack notAdded = storage.getFluidInventory() - .injectItems( - AEApi.instance().storage() - .createFluidStack(s.copy()), - Actionable.SIMULATE, new MachineSource(this)); - if (notAdded != null) { - int toAdd = (int) (s.amount - notAdded.getStackSize()); - storage.getFluidInventory().injectItems( - AEApi.instance() - .storage() - .createFluidStack( - this.tank.drain(toAdd, true)), - Actionable.MODULATE, new MachineSource(this)); - this.doNextUpdate = true; - this.needBreake = false; - } else { - storage.getFluidInventory().injectItems( - AEApi.instance() - .storage() - .createFluidStack( - this.tank.drain(s.amount, true)), - Actionable.MODULATE, new MachineSource(this)); - this.doNextUpdate = true; - this.needBreake = false; - } - } - } - if ((this.tank.getFluid() == null || this.tank.getFluid().getFluid() == FluidRegistry - .getFluid(this.fluidFilter)) - && FluidRegistry.getFluid(this.fluidFilter) != null) { - IAEFluidStack extracted = storage.getFluidInventory().extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack(FluidRegistry - .getFluid(this.fluidFilter), 125)), - Actionable.SIMULATE, new MachineSource(this)); - if (extracted == null) - return TickRateModulation.URGENT; - int accepted = this.tank.fill(extracted.getFluidStack(), false); - if (accepted == 0) - return TickRateModulation.URGENT; - this.tank - .fill(storage - .getFluidInventory() - .extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack( - FluidRegistry - .getFluid(this.fluidFilter), - accepted)), - Actionable.MODULATE, - new MachineSource(this)).getFluidStack(), - true); - this.doNextUpdate = true; - this.needBreake = false; - } - return TickRateModulation.URGENT; - } - - public NBTTagCompound writeFilter(NBTTagCompound tag) { - if (FluidRegistry.getFluid(this.fluidFilter) == null) - return null; - tag.setInteger("filter", this.fluidFilter); - return tag; - } - - private NBTTagCompound writeOutputToNBT(NBTTagCompound tag) { - int i = 0; - for (IAEStack s : this.removeFromExport) { - if (s != null) { - tag.setBoolean("remove-" + i + "-isItem", s.isItem()); - NBTTagCompound data = new NBTTagCompound(); - if (s.isItem()) { - ((IAEItemStack) s).getItemStack().writeToNBT(data); - } else { - ((IAEFluidStack) s).getFluidStack().writeToNBT(data); - } - tag.setTag("remove-" + i, data); - tag.setLong("remove-" + i + "-amount", s.getStackSize()); - } - i++; - } - tag.setInteger("remove", this.removeFromExport.size()); - i = 0; - for (IAEStack s : this.addToExport) { - if (s != null) { - tag.setBoolean("add-" + i + "-isItem", s.isItem()); - NBTTagCompound data = new NBTTagCompound(); - if (s.isItem()) { - ((IAEItemStack) s).getItemStack().writeToNBT(data); - } else { - ((IAEFluidStack) s).getFluidStack().writeToNBT(data); - }; - tag.setTag("add-" + i, data); - tag.setLong("add-" + i + "-amount", s.getStackSize()); - } - i++; - } - tag.setInteger("add", this.addToExport.size()); - i = 0; - for (IAEStack s : this.export) { - if (s != null) { - tag.setBoolean("export-" + i + "-isItem", s.isItem()); - NBTTagCompound data = new NBTTagCompound(); - if (s.isItem()) { - ((IAEItemStack) s).getItemStack().writeToNBT(data); - } else { - ((IAEFluidStack) s).getFluidStack().writeToNBT(data); - } - tag.setTag("export-" + i, data); - tag.setLong("export-" + i + "-amount", s.getStackSize()); - } - i++; - } - tag.setInteger("export", this.export.size()); - return tag; - } - - @Override - public void writeToNBT(NBTTagCompound data) { - writeToNBTWithoutExport(data); - NBTTagCompound tag = new NBTTagCompound(); - writeOutputToNBT(tag); - data.setTag("export", tag); - } - - public void writeToNBTWithoutExport(NBTTagCompound data) { - super.writeToNBT(data); - data.setTag("tank", this.tank.writeToNBT(new NBTTagCompound())); - data.setInteger("filter", this.fluidFilter); - NBTTagCompound inventory = new NBTTagCompound(); - this.inventory.writeToNBT(inventory); - data.setTag("inventory", inventory); - } - - @Override - public void writeToStream(ByteBuf data) throws IOException { - super.writeToStream(data); - NBTTagCompound tag = new NBTTagCompound(); - tag.setTag("tank", this.tank.writeToNBT(new NBTTagCompound())); - tag.setInteger("filter", this.fluidFilter); - NBTTagCompound inventory = new NBTTagCompound(); - this.inventory.writeToNBT(inventory); - tag.setTag("inventory", inventory); - ByteBufUtils.writeTag(data, tag); - } +public class PartFluidInterface extends PartECBase implements IFluidHandler, IFluidInterface, IFluidSlotPartOrBlock, + ITileStorageMonitorable, IStorageMonitorable, IGridTickable, ICraftingProvider, IPartDeprecated { + + private final HashMap patternConvert = new HashMap(); + + List listeners = new ArrayList(); + private List patternHandlers = new ArrayList(); + private final List requestedItems = new ArrayList(); + private final List removeList = new ArrayList(); + private final List export = new ArrayList(); + private final ICraftingPatternDetails[] originalPatternsCache = new ICraftingPatternDetails[9]; + public final FluidInterfaceInventory inventory = new FluidInterfaceInventory(); + + private boolean update = false; + private final List removeFromExport = new ArrayList(); + private final List addToExport = new ArrayList(); + private final FluidTank tank = new FluidTank(10000); + private IAEItemStack toExport = null; + + private final Item encodedPattern = AEApi.instance().definitions().items().encodedPattern().maybeItem().orNull(); + private final int tickCount = 0; + private int fluidFilter = -1; + public boolean doNextUpdate = false; + private boolean needBreak = false; + + @Override + public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { + if (this.doNextUpdate) forceUpdate(); + IGrid grid = node.getGrid(); + if (grid == null) return TickRateModulation.IDLE; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return TickRateModulation.IDLE; + pushItems(); + boolean didWork = false; + if (this.toExport != null) { + storage.getItemInventory().injectItems(this.toExport, Actionable.MODULATE, new MachineSource(this)); + this.toExport = null; + didWork = true; + } + if (this.update) { + this.update = false; + if (getGridNode() != null && getGridNode().getGrid() != null) { + getGridNode().getGrid().postEvent(new MENetworkCraftingPatternChange(this, getGridNode())); + getHost().markForSave(); + } + } + if (this.tank.getFluid() != null + && FluidRegistry.getFluid(this.fluidFilter) != this.tank.getFluid().getFluid()) { + FluidStack s = this.tank.drain(Extracells.basePartSpeed() * TicksSinceLastCall, false); + if (s != null) { + IAEFluidStack notAdded = storage.getFluidInventory().injectItems( + AEApi.instance().storage().createFluidStack(s), + Actionable.SIMULATE, + new MachineSource(this)); + int toAdd = s.amount - (notAdded != null ? (int) notAdded.getStackSize() : 0); + IAEFluidStack actuallyNotInjected = storage.getFluidInventory().injectItems( + AEApi.instance().storage().createFluidStack(this.tank.drain(toAdd, true)), + Actionable.MODULATE, + new MachineSource(this)); + if (actuallyNotInjected != null) { + int returned = this.tank.fill(actuallyNotInjected.getFluidStack(), true); + if (returned != actuallyNotInjected.getStackSize()) { + FMLLog.severe( + "[ExtraCells2] Interface tank import at %d:%d,%d,%d voided %d mL of %s", + tile.getWorldObj().provider.dimensionId, + tile.xCoord, + tile.yCoord, + tile.zCoord, + actuallyNotInjected.getStackSize() - returned, + actuallyNotInjected.getFluid().getName()); + } + } + this.doNextUpdate = true; + this.needBreak = false; + didWork = true; + } + } + if ((this.tank.getFluid() == null + || (this.tank.getFluid().getFluid() == FluidRegistry.getFluid(this.fluidFilter) + && this.tank.getFluidAmount() < this.tank.getCapacity())) + && FluidRegistry.getFluid(this.fluidFilter) != null) { + IAEFluidStack request = FluidUtil + .createAEFluidStack(this.fluidFilter, (long) Extracells.basePartSpeed() * TicksSinceLastCall); + IAEFluidStack extracted = storage.getFluidInventory() + .extractItems(request, Actionable.SIMULATE, new MachineSource(this)); + if (extracted == null) return TickRateModulation.SLOWER; + int accepted = this.tank.fill(extracted.getFluidStack(), false); + if (accepted == 0) return TickRateModulation.SLOWER; + request.setStackSize(Long.min(accepted, extracted.getStackSize())); + extracted = storage.getFluidInventory().extractItems(request, Actionable.MODULATE, new MachineSource(this)); + if (extracted == null || extracted.getStackSize() <= 0) { + return TickRateModulation.SLOWER; + } + accepted = this.tank.fill(extracted.getFluidStack(), true); + if (extracted.getStackSize() != accepted) { + // This should never happen, but log it in case it does + FMLLog.severe( + "[ExtraCells2] Interface tank export at %d:%d,%d,%d voided %d mL of %s", + tile.getWorldObj().provider.dimensionId, + tile.xCoord, + tile.yCoord, + tile.zCoord, + extracted.getStackSize() - accepted, + request.getFluid().getName()); + } + this.doNextUpdate = true; + this.needBreak = false; + didWork = true; + } + return didWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER; + } + + @Override + public int cableConnectionRenderTo() { + return 3; + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + FluidStack tankFluid = this.tank.getFluid(); + return tankFluid != null && tankFluid.getFluid() == fluid; + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return this.tank.fill(new FluidStack(fluid, 1), false) > 0; + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + FluidStack tankFluid = this.tank.getFluid(); + if (resource == null || tankFluid == null || tankFluid.getFluid() != resource.getFluid()) return null; + return drain(from, resource.amount, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + FluidStack drained = this.tank.drain(maxDrain, doDrain); + if (drained != null) getHost().markForUpdate(); + this.doNextUpdate = true; + return drained; + } + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + if (resource == null) return 0; + + if ((this.tank.getFluid() == null || this.tank.getFluid().getFluid() == resource.getFluid()) + && resource.getFluid() == FluidRegistry.getFluid(this.fluidFilter)) { + int added = this.tank.fill(resource.copy(), doFill); + if (added == resource.amount) { + this.doNextUpdate = true; + return added; + } + added += fillToNetwork(new FluidStack(resource.getFluid(), resource.amount - added), doFill); + this.doNextUpdate = true; + return added; + } + + int filled = 0; + filled += fillToNetwork(resource, doFill); + + if (filled < resource.amount) + filled += this.tank.fill(new FluidStack(resource.getFluid(), resource.amount - filled), doFill); + if (filled > 0) getHost().markForUpdate(); + this.doNextUpdate = true; + return filled; + } + + public int fillToNetwork(FluidStack resource, boolean doFill) { + IGridNode node = getGridNode(ForgeDirection.UNKNOWN); + if (node == null || resource == null) return 0; + IGrid grid = node.getGrid(); + if (grid == null) return 0; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return 0; + IAEFluidStack notRemoved = storage.getFluidInventory().injectItems( + AEApi.instance().storage().createFluidStack(resource), + doFill ? Actionable.MODULATE : Actionable.SIMULATE, + new MachineSource(this)); + if (notRemoved == null) return resource.amount; + return (int) (resource.amount - notRemoved.getStackSize()); + } + + private void forceUpdate() { + getHost().markForUpdate(); + for (IContainerListener listener : this.listeners) { + if (listener != null) listener.updateContainer(); + } + this.doNextUpdate = false; + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 12, 11, 11, 14); + } + + @Override + public Object getClientGuiElement(EntityPlayer player) { + return new GuiFluidInterface(player, this, getSide()); + } + + @SideOnly(Side.CLIENT) + private World getClientWorld() { + return Minecraft.getMinecraft().theWorld; + } + + @Override + public void getDrops(List drops, boolean wrenched) { + for (int i = 0; i < this.inventory.getSizeInventory(); i++) { + ItemStack pattern = this.inventory.getStackInSlot(i); + if (pattern != null) drops.add(pattern); + } + } + + @Override + public Fluid getFilter(ForgeDirection side) { + return FluidRegistry.getFluid(this.fluidFilter); + } + + @Override + public IMEMonitor getFluidInventory() { + if (getGridNode(ForgeDirection.UNKNOWN) == null) return null; + IGrid grid = getGridNode(ForgeDirection.UNKNOWN).getGrid(); + if (grid == null) return null; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return null; + return storage.getFluidInventory(); + } + + @Override + public IFluidTank getFluidTank(ForgeDirection side) { + return this.tank; + } + + @Override + public IMEMonitor getItemInventory() { + return new EmptyMeItemMonitor(); + } + + @Override + public IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src) { + return this; + } + + @Override + public IInventory getPatternInventory() { + return this.inventory; + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerFluidInterface(player, this); + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return new FluidTankInfo[] { this.tank.getInfo() }; + } + + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(5, 120, false, false); + } + + @Override + public List getWailaBodey(NBTTagCompound tag, List list) { + FluidStack fluid = null; + int id = -1; + int amount = 0; + if (tag.hasKey("fluidID") && tag.hasKey("amount")) { + id = tag.getInteger("fluidID"); + amount = tag.getInteger("amount"); + } + if (id != -1) fluid = new FluidStack(id, amount); + if (fluid == null) { + list.add( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + StatCollector.translateToLocal("extracells.tooltip.empty1")); + list.add(StatCollector.translateToLocal("extracells.tooltip.amount") + ": 0mB / 10000mB"); + } else { + list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + fluid.getLocalizedName()); + list.add( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + fluid.amount + "mB / 10000mB"); + } + return list; + } + + @Override + public NBTTagCompound getWailaTag(NBTTagCompound tag) { + if (this.tank.getFluid() == null || this.tank.getFluid().getFluid() == null) tag.setInteger("fluidID", -1); + else tag.setInteger("fluidID", this.tank.getFluid().getFluidID()); + tag.setInteger("amount", this.tank.getFluidAmount()); + return tag; + } + + @Override + public void initializePart(ItemStack partStack) { + if (partStack.hasTagCompound()) { + readFilter(partStack.getTagCompound()); + } + } + + @Override + public boolean isBusy() { + return !this.export.isEmpty(); + } + + private ItemStack makeCraftingPatternItem(ICraftingPatternDetails details) { + if (details == null) return null; + NBTTagList in = new NBTTagList(); + NBTTagList out = new NBTTagList(); + for (IAEItemStack s : details.getInputs()) { + if (s == null) in.appendTag(new NBTTagCompound()); + else in.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); + } + for (IAEItemStack s : details.getOutputs()) { + if (s == null) out.appendTag(new NBTTagCompound()); + else out.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); + } + NBTTagCompound itemTag = new NBTTagCompound(); + itemTag.setTag("in", in); + itemTag.setTag("out", out); + itemTag.setBoolean("crafting", details.isCraftable()); + ItemStack pattern = new ItemStack(this.encodedPattern); + pattern.setTagCompound(itemTag); + return pattern; + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this)) { + return super.onActivate(player, pos); + } + return false; + } + + @Override + public void provideCrafting(ICraftingProviderHelper craftingTracker) { + this.patternHandlers = new ArrayList(); + this.patternConvert.clear(); + + if (!this.isActive()) { + return; + } + ItemStack[] inv = this.inventory.inv; + for (int i = 0, invLength = inv.length; i < invLength; i++) { + ItemStack currentPatternStack = inv[i]; + if (currentPatternStack != null && currentPatternStack.getItem() != null + && currentPatternStack.getItem() instanceof ICraftingPatternItem) { + ICraftingPatternItem currentPattern = (ICraftingPatternItem) currentPatternStack.getItem(); + + ICraftingPatternDetails originalPattern = originalPatternsCache[i]; + if (originalPattern == null) { + originalPattern = currentPattern.getPatternForItem(currentPatternStack, getGridNode().getWorld()); + originalPatternsCache[i] = originalPattern; + } + if (originalPattern != null) { + IFluidCraftingPatternDetails pattern = new CraftingPattern2(originalPattern); + this.patternHandlers.add(pattern); + ItemStack is = makeCraftingPatternItem(pattern); + if (is == null) continue; + ICraftingPatternDetails p = ((ICraftingPatternItem) is.getItem()) + .getPatternForItem(is, getGridNode().getWorld()); + if (p == null) continue; + this.patternConvert.put(p, pattern); + craftingTracker.addCraftingOption(this, p); + } + } + } + } + + private void pushItems() { + for (IAEStack s : this.removeFromExport) { + this.export.remove(s); + } + this.removeFromExport.clear(); + for (IAEStack s : this.addToExport) { + this.export.add(s); + } + this.addToExport.clear(); + if (getGridNode().getWorld() == null || this.export.isEmpty()) return; + ForgeDirection dir = getSide(); + TileEntity tile = getGridNode().getWorld().getTileEntity( + getGridNode().getGridBlock().getLocation().x + dir.offsetX, + getGridNode().getGridBlock().getLocation().y + dir.offsetY, + getGridNode().getGridBlock().getLocation().z + dir.offsetZ); + if (tile != null) { + IAEStack stack0 = this.export.get(0); + IAEStack stack = stack0.copy(); + if (stack instanceof IAEItemStack && tile instanceof IInventory) { + InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(tile, dir.getOpposite()); + if (adaptor != null) { + final ItemStack adding = ((IAEItemStack) stack).getItemStack(); + final int originalAddingAmount = adding.stackSize; + final ItemStack leftover = adaptor.addItems(adding); + // calculate how much to remove, because getItemStack() limits stack size from a long to an int + final int leftoverAmount = leftover == null ? 0 : leftover.stackSize; + final int removedAmount = originalAddingAmount - leftoverAmount; + if ((long) removedAmount == stack0.getStackSize()) { + this.export.remove(0); + } else { + this.export.get(0).setStackSize(stack0.getStackSize() - removedAmount); + } + } + } else if (stack instanceof IAEFluidStack && tile instanceof IFluidHandler) { + IFluidHandler handler = (IFluidHandler) tile; + IAEFluidStack fluid = (IAEFluidStack) stack; + if (handler.canFill(dir.getOpposite(), fluid.copy().getFluid())) { + int amount = handler.fill(dir.getOpposite(), fluid.getFluidStack().copy(), false); + if (amount == 0) return; + if (amount == fluid.getStackSize()) { + amount = handler.fill(dir.getOpposite(), fluid.getFluidStack().copy(), true); + } + if (amount == fluid.getStackSize()) { + this.removeFromExport.add(stack0); + } else { + IAEFluidStack f = fluid.copy(); + f.setStackSize(f.getStackSize() - amount); + FluidStack fl = fluid.getFluidStack().copy(); + fl.amount = amount; + handler.fill(dir.getOpposite(), fl, true); + this.removeFromExport.add(stack0); + this.addToExport.add(f); + } + } + } + } + } + + @Override + public boolean pushPattern(ICraftingPatternDetails patDetails, InventoryCrafting table) { + if (isBusy() || !this.patternConvert.containsKey(patDetails)) return false; + ICraftingPatternDetails patternDetails = this.patternConvert.get(patDetails); + if (patternDetails instanceof CraftingPattern) { + CraftingPattern patter = (CraftingPattern) patternDetails; + HashMap fluids = new HashMap(); + for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { + if (fluids.containsKey(stack.getFluid())) { + Long amount = fluids.get(stack.getFluid()) + stack.getStackSize(); + fluids.remove(stack.getFluid()); + fluids.put(stack.getFluid(), amount); + } else { + fluids.put(stack.getFluid(), stack.getStackSize()); + } + } + IGrid grid = getGridNode().getGrid(); + if (grid == null) return false; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return false; + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, amount.intValue())), + Actionable.SIMULATE, + new MachineSource(this)); + if (extractFluid == null || extractFluid.getStackSize() != amount) { + return false; + } + } + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, amount.intValue())), + Actionable.MODULATE, + new MachineSource(this)); + this.export.add(extractFluid); + } + for (IAEItemStack s : patter.getCondensedInputs()) { + if (s == null) continue; + if (s.getItem() == ItemEnum.FLUIDPATTERN.getItem()) { + this.toExport = s.copy(); + continue; + } + this.export.add(s); + } + } + return true; + } + + public void readFilter(NBTTagCompound tag) { + if (tag.hasKey("filter")) this.fluidFilter = tag.getInteger("filter"); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("tank")) this.tank.readFromNBT(data.getCompoundTag("tank")); + if (data.hasKey("filter")) this.fluidFilter = data.getInteger("filter"); + if (data.hasKey("inventory")) this.inventory.readFromNBT(data.getCompoundTag("inventory")); + if (data.hasKey("export")) readOutputFromNBT(data.getCompoundTag("export")); + } + + @Override + public boolean readFromStream(ByteBuf data) throws IOException { + super.readFromStream(data); + NBTTagCompound tag = ByteBufUtils.readTag(data); + if (tag.hasKey("tank")) this.tank.readFromNBT(tag.getCompoundTag("tank")); + if (tag.hasKey("filter")) this.fluidFilter = tag.getInteger("filter"); + if (tag.hasKey("inventory")) this.inventory.readFromNBT(tag.getCompoundTag("inventory")); + return true; + } + + private void readOutputFromNBT(NBTTagCompound tag) { + this.addToExport.clear(); + this.removeFromExport.clear(); + this.export.clear(); + int i = tag.getInteger("remove"); + for (int j = 0; j < i; j++) { + if (tag.getBoolean("remove-" + j + "-isItem")) { + IAEItemStack s = AEApi.instance().storage() + .createItemStack(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("remove-" + j))); + s.setStackSize(tag.getLong("remove-" + j + "-amount")); + this.removeFromExport.add(s); + } else { + IAEFluidStack s = AEApi.instance().storage() + .createFluidStack(FluidStack.loadFluidStackFromNBT(tag.getCompoundTag("remove-" + j))); + s.setStackSize(tag.getLong("remove-" + j + "-amount")); + this.removeFromExport.add(s); + } + } + i = tag.getInteger("add"); + for (int j = 0; j < i; j++) { + if (tag.getBoolean("add-" + j + "-isItem")) { + IAEItemStack s = AEApi.instance().storage() + .createItemStack(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("add-" + j))); + s.setStackSize(tag.getLong("add-" + j + "-amount")); + this.addToExport.add(s); + } else { + IAEFluidStack s = AEApi.instance().storage() + .createFluidStack(FluidStack.loadFluidStackFromNBT(tag.getCompoundTag("add-" + j))); + s.setStackSize(tag.getLong("add-" + j + "-amount")); + this.addToExport.add(s); + } + } + i = tag.getInteger("export"); + for (int j = 0; j < i; j++) { + if (tag.getBoolean("export-" + j + "-isItem")) { + IAEItemStack s = AEApi.instance().storage() + .createItemStack(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("export-" + j))); + s.setStackSize(tag.getLong("export-" + j + "-amount")); + this.export.add(s); + } else { + IAEFluidStack s = AEApi.instance().storage() + .createFluidStack(FluidStack.loadFluidStackFromNBT(tag.getCompoundTag("export-" + j))); + s.setStackSize(tag.getLong("export-" + j + "-amount")); + this.export.add(s); + } + } + } + + public void registerListener(IContainerListener listener) { + this.listeners.add(listener); + } + + public void removeListener(IContainerListener listener) { + this.listeners.remove(listener); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = TextureManager.BUS_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.INTERFACE.getTextures()[0], side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + rh.renderInventoryFace(TextureManager.INTERFACE.getTextures()[0], ForgeDirection.SOUTH, renderer); + + rh.setTexture(side); + rh.setBounds(5, 5, 12, 11, 11, 14); + rh.renderInventoryBox(renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = TextureManager.BUS_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.INTERFACE.getTextures()[0], side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + + ts.setBrightness(20971520); + rh.renderFace(x, y, z, TextureManager.INTERFACE.getTextures()[0], ForgeDirection.SOUTH, renderer); + + rh.setTexture(side); + rh.setBounds(5, 5, 12, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); + } + + @Override + public void setFilter(ForgeDirection side, Fluid fluid) { + if (fluid == null) { + this.fluidFilter = -1; + this.doNextUpdate = true; + return; + } + this.fluidFilter = fluid.getID(); + this.doNextUpdate = true; + } + + @Override + public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { + setFilter(ForgeDirection.getOrientation(_index), _fluid); + } + + @Override + public void setFluidTank(ForgeDirection side, FluidStack fluid) { + this.tank.setFluid(fluid); + this.doNextUpdate = true; + } + + @Override + public NBTTagCompound transformPart(NBTTagCompound def) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FluidCraft.replace(def, PartEnum.INTERFACE); + } + return def; + } + + @Override + public NBTTagCompound transformNBT(NBTTagCompound extra) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + // Internal fluids - ConfigInv and FluidInv + NBTTagCompound tank = extra.getCompoundTag("tank"); + NBTTagCompound configTank = new NBTTagCompound(); + configTank.setTag("#0", FluidCraft.createFluidDisplay(tank.getString("FluidName"))); + extra.setTag("ConfigInv", configTank); + NBTTagCompound fluidTank = new NBTTagCompound(); + NBTTagCompound fluid = FluidCraft.createFluidNBT(tank.getString("FluidName"), tank.getLong("Amount")); + fluidTank.setTag("#0", fluid); + extra.setTag("FluidInv", fluidTank); + extra.removeTag("tank"); + // Patterns + NBTTagList patterns = extra.getCompoundTag("inventory").getTagList("Inventory", Constants.NBT.TAG_COMPOUND); + NBTTagCompound newPatterns = new NBTTagCompound(); + for (int i = 0; i < patterns.tagCount(); ++i) { + NBTTagCompound p = patterns.getCompoundTagAt(i); + p.removeTag("Slot"); + newPatterns.setTag("#" + i, p); + } + extra.removeTag("inventory"); + extra.setTag("patterns", newPatterns); + // Part + extra.setTag("part", extra.getCompoundTag("node").getCompoundTag("node0")); + extra.removeTag("node"); + } + return extra; + } + + private class FluidInterfaceInventory implements IInventory { + + private final ItemStack[] inv = new ItemStack[9]; + + @Override + public void closeInventory() {} + + @Override + public ItemStack decrStackSize(int slot, int amt) { + ItemStack stack = getStackInSlot(slot); + if (stack != null) { + if (stack.stackSize <= amt) { + setInventorySlotContents(slot, null); + } else { + stack = stack.splitStack(amt); + if (stack.stackSize == 0) { + setInventorySlotContents(slot, null); + } + } + } + PartFluidInterface.this.update = true; + return stack; + } + + @Override + public String getInventoryName() { + return "inventory.fluidInterface"; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public int getSizeInventory() { + return this.inv.length; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return this.inv[slot]; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return null; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + if (stack.getItem() instanceof ICraftingPatternItem) { + IGridNode n = getGridNode(); + World w; + if (n == null) { + w = getClientWorld(); + } else { + w = n.getWorld(); + } + if (w == null) return false; + ICraftingPatternDetails details = ((ICraftingPatternItem) stack.getItem()).getPatternForItem(stack, w); + return details != null; + } + return false; + } + + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + return PartFluidInterface.this.isValid(); + } + + @Override + public void markDirty() {} + + @Override + public void openInventory() {} + + public void readFromNBT(NBTTagCompound tagCompound) { + + NBTTagList tagList = tagCompound.getTagList("Inventory", 10); + for (int i = 0; i < tagList.tagCount(); i++) { + NBTTagCompound tag = tagList.getCompoundTagAt(i); + byte slot = tag.getByte("Slot"); + if (slot >= 0 && slot < this.inv.length) { + this.inv[slot] = ItemStack.loadItemStackFromNBT(tag); + } + } + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + this.inv[slot] = stack; + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + PartFluidInterface.this.originalPatternsCache[slot] = null; + PartFluidInterface.this.update = true; + } + + public void writeToNBT(NBTTagCompound tagCompound) { + NBTTagList itemList = new NBTTagList(); + for (int i = 0; i < this.inv.length; i++) { + ItemStack stack = this.inv[i]; + if (stack != null) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setByte("Slot", (byte) i); + stack.writeToNBT(tag); + itemList.appendTag(tag); + } + } + tagCompound.setTag("Inventory", itemList); + } + } + + public NBTTagCompound writeFilter(NBTTagCompound tag) { + if (FluidRegistry.getFluid(this.fluidFilter) == null) return null; + tag.setInteger("filter", this.fluidFilter); + return tag; + } + + private NBTTagCompound writeOutputToNBT(NBTTagCompound tag) { + int i = 0; + for (IAEStack s : this.removeFromExport) { + if (s != null) { + tag.setBoolean("remove-" + i + "-isItem", s.isItem()); + NBTTagCompound data = new NBTTagCompound(); + if (s.isItem()) { + ((IAEItemStack) s).getItemStack().writeToNBT(data); + } else { + ((IAEFluidStack) s).getFluidStack().writeToNBT(data); + } + tag.setTag("remove-" + i, data); + tag.setLong("remove-" + i + "-amount", s.getStackSize()); + } + i++; + } + tag.setInteger("remove", this.removeFromExport.size()); + i = 0; + for (IAEStack s : this.addToExport) { + if (s != null) { + tag.setBoolean("add-" + i + "-isItem", s.isItem()); + NBTTagCompound data = new NBTTagCompound(); + if (s.isItem()) { + ((IAEItemStack) s).getItemStack().writeToNBT(data); + } else { + ((IAEFluidStack) s).getFluidStack().writeToNBT(data); + } + tag.setTag("add-" + i, data); + tag.setLong("add-" + i + "-amount", s.getStackSize()); + } + i++; + } + tag.setInteger("add", this.addToExport.size()); + i = 0; + for (IAEStack s : this.export) { + if (s != null) { + tag.setBoolean("export-" + i + "-isItem", s.isItem()); + NBTTagCompound data = new NBTTagCompound(); + if (s.isItem()) { + ((IAEItemStack) s).getItemStack().writeToNBT(data); + } else { + ((IAEFluidStack) s).getFluidStack().writeToNBT(data); + } + tag.setTag("export-" + i, data); + tag.setLong("export-" + i + "-amount", s.getStackSize()); + } + i++; + } + tag.setInteger("export", this.export.size()); + return tag; + } + + @Override + public void writeToNBT(NBTTagCompound data) { + writeToNBTWithoutExport(data); + NBTTagCompound tag = new NBTTagCompound(); + writeOutputToNBT(tag); + data.setTag("export", tag); + } + + public void writeToNBTWithoutExport(NBTTagCompound data) { + super.writeToNBT(data); + data.setTag("tank", this.tank.writeToNBT(new NBTTagCompound())); + data.setInteger("filter", this.fluidFilter); + NBTTagCompound inventory = new NBTTagCompound(); + this.inventory.writeToNBT(inventory); + data.setTag("inventory", inventory); + } + + @Override + public void writeToStream(ByteBuf data) throws IOException { + super.writeToStream(data); + NBTTagCompound tag = new NBTTagCompound(); + tag.setTag("tank", this.tank.writeToNBT(new NBTTagCompound())); + tag.setInteger("filter", this.fluidFilter); + NBTTagCompound inventory = new NBTTagCompound(); + this.inventory.writeToNBT(inventory); + tag.setTag("inventory", inventory); + ByteBufUtils.writeTag(data, tag); + } } diff --git a/src/main/scala/extracells/part/PartFluidLevelEmitter.java b/src/main/scala/extracells/part/PartFluidLevelEmitter.java index 7a7d88a4f..0ab7671e5 100644 --- a/src/main/scala/extracells/part/PartFluidLevelEmitter.java +++ b/src/main/scala/extracells/part/PartFluidLevelEmitter.java @@ -1,263 +1,324 @@ package extracells.part; +import java.io.IOException; +import java.util.Random; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +import com.google.common.collect.Lists; + import appeng.api.AEApi; import appeng.api.config.RedstoneMode; import appeng.api.config.SecurityPermissions; +import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; import appeng.api.networking.security.BaseActionSource; import appeng.api.networking.storage.IStackWatcher; import appeng.api.networking.storage.IStackWatcherHost; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.parts.IPartRenderHelper; +import appeng.api.networking.storage.IStorageGrid; +import appeng.api.parts.*; +import appeng.api.storage.IMEMonitor; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; -import com.google.common.collect.Lists; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import extracells.container.ContainerFluidEmitter; import extracells.gui.GuiFluidEmitter; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; import extracells.network.packet.other.IFluidSlotPartOrBlock; import extracells.network.packet.other.PacketFluidSlot; import extracells.network.packet.part.PacketFluidEmitter; +import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.PermissionUtil; import io.netty.buffer.ByteBuf; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import java.io.IOException; -import java.util.Random; +public class PartFluidLevelEmitter extends PartECBase + implements IStackWatcherHost, IFluidSlotPartOrBlock, IPartDeprecated { + + private Fluid fluid; + private RedstoneMode mode = RedstoneMode.HIGH_SIGNAL; + private IStackWatcher watcher; + private long wantedAmount; + private long currentAmount; + private boolean clientRedstoneOutput = false; + + @Override + public int cableConnectionRenderTo() { + return 8; + } + + public void changeWantedAmount(int modifier, EntityPlayer player) { + setWantedAmount(this.wantedAmount + modifier, player); + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(7, 7, 11, 9, 9, 16); + } + + @Override + public Object getClientGuiElement(EntityPlayer player) { + return new GuiFluidEmitter(this, player); + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerFluidEmitter(this, player); + } + + private boolean isPowering() { + switch (this.mode) { + case LOW_SIGNAL: + return this.wantedAmount >= this.currentAmount; + case HIGH_SIGNAL: + return this.wantedAmount < this.currentAmount; + default: + return false; + } + } + + @Override + public int isProvidingStrongPower() { + return isPowering() ? 15 : 0; + } + + @Override + public int isProvidingWeakPower() { + return isProvidingStrongPower(); + } + + private void notifyTargetBlock(TileEntity _tile, ForgeDirection _side) { + // note - params are always the same + _tile.getWorldObj().notifyBlocksOfNeighborChange(_tile.xCoord, _tile.yCoord, _tile.zCoord, Blocks.air); + _tile.getWorldObj().notifyBlocksOfNeighborChange( + _tile.xCoord + _side.offsetX, + _tile.yCoord + _side.offsetY, + _tile.zCoord + _side.offsetZ, + Blocks.air); + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this)) { + return super.onActivate(player, pos); + } + return false; + } + + @Override + public void onStackChange(IItemList o, IAEStack fullStack, IAEStack diffStack, BaseActionSource src, + StorageChannel chan) { + long previousAmount = this.currentAmount; + if (chan == StorageChannel.FLUIDS && diffStack != null + && ((IAEFluidStack) diffStack).getFluid() == this.fluid) { + this.currentAmount = fullStack != null ? fullStack.getStackSize() : 0; + if (Long.compare(currentAmount, wantedAmount) == Long.compare(previousAmount, wantedAmount)) { + // Don't send updates when amount has changed, but not its relation to wantedAmount + return; + } + IGridNode node = getGridNode(); + if (node != null) { + setActive(node.isActive()); + getHost().markForUpdate(); + notifyTargetBlock(getHostTile(), getSide()); + } + } + } + + @Override + public void randomDisplayTick(World world, int x, int y, int z, Random r) { + if (this.clientRedstoneOutput) { + ForgeDirection d = getSide(); + double d0 = d.offsetX * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + double d1 = d.offsetY * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; + 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 void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.fluid = FluidRegistry.getFluid(data.getString("fluid")); + this.mode = RedstoneMode.values()[data.getInteger("mode")]; + this.wantedAmount = data.getLong("wantedAmount"); + if (this.wantedAmount < 0) this.wantedAmount = 0; + } + + @Override + public boolean readFromStream(ByteBuf data) throws IOException { + super.readFromStream(data); + this.clientRedstoneOutput = data.readBoolean(); + if (getHost() != null) getHost().markForUpdate(); + return true; + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + rh.setTexture(TextureManager.LEVEL_FRONT.getTextures()[0]); + rh.setBounds(7, 7, 11, 9, 9, 14); + rh.renderInventoryBox(renderer); + + rh.setTexture(TextureManager.LEVEL_FRONT.getTextures()[1]); + rh.setBounds(7, 7, 14, 9, 9, 16); + rh.renderInventoryBox(renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + rh.setTexture(TextureManager.LEVEL_FRONT.getTextures()[0]); + rh.setBounds(7, 7, 11, 9, 9, 14); + rh.renderBlock(x, y, z, renderer); + rh.setTexture( + this.clientRedstoneOutput ? TextureManager.LEVEL_FRONT.getTextures()[2] + : TextureManager.LEVEL_FRONT.getTextures()[1]); + rh.setBounds(7, 7, 14, 9, 9, 16); + rh.renderBlock(x, y, z, renderer); + } + + private void updateCurrentAmount() { + IGridNode n = getGridNode(); + if (n == null) return; + IGrid g = n.getGrid(); + if (g == null) return; + IStorageGrid s = g.getCache(IStorageGrid.class); + if (s == null) return; + IMEMonitor f = s.getFluidInventory(); + if (f == null) return; + + this.currentAmount = 0L; + for (IAEFluidStack st : f.getStorageList()) { + if (this.fluid != null && st.getFluid() == this.fluid) this.currentAmount = st.getStackSize(); + } + + IPartHost h = getHost(); + if (h != null) h.markForUpdate(); + } + + @Override + public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { + this.fluid = _fluid; + updateCurrentAmount(); + if (this.watcher == null) return; + this.watcher.clear(); + updateWatcher(this.watcher); + new PacketFluidSlot(Lists.newArrayList(this.fluid)).sendPacketToPlayer(_player); + notifyTargetBlock(getHostTile(), getSide()); + saveData(); + } + + public void setWantedAmount(long _wantedAmount, EntityPlayer player) { + this.wantedAmount = _wantedAmount; + if (this.wantedAmount < 0) this.wantedAmount = 0; + + IPartHost h = getHost(); + if (h != null) h.markForUpdate(); + + new PacketFluidEmitter(this.wantedAmount, player).sendPacketToPlayer(player); + notifyTargetBlock(getHostTile(), getSide()); + saveData(); + } + + public void syncClientGui(EntityPlayer player) { + new PacketFluidEmitter(this.mode, player).sendPacketToPlayer(player); + new PacketFluidEmitter(this.wantedAmount, player).sendPacketToPlayer(player); + new PacketFluidSlot(Lists.newArrayList(this.fluid)).sendPacketToPlayer(player); + } + + public void toggleMode(EntityPlayer player) { + switch (this.mode) { + case LOW_SIGNAL: + this.mode = RedstoneMode.HIGH_SIGNAL; + break; + default: + this.mode = RedstoneMode.LOW_SIGNAL; + break; + } + + IPartHost h = getHost(); + if (h != null) h.markForUpdate(); + + new PacketFluidEmitter(this.mode, player).sendPacketToPlayer(player); + notifyTargetBlock(getHostTile(), getSide()); + saveData(); + } + + @Override + public void updateWatcher(IStackWatcher newWatcher) { + this.watcher = newWatcher; + if (this.fluid != null) + this.watcher.add(AEApi.instance().storage().createFluidStack(new FluidStack(this.fluid, 1))); + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + if (this.fluid != null) data.setString("fluid", this.fluid.getName()); + else data.removeTag("fluid"); + data.setInteger("mode", this.mode.ordinal()); + data.setLong("wantedAmount", this.wantedAmount); + } + + @Override + public void writeToStream(ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeBoolean(isPowering()); + } + + @Override + public NBTTagCompound transformPart(NBTTagCompound def) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FluidCraft.replace(def, PartEnum.FLUIDLEVELEMITTER); + } + return def; + } -public class PartFluidLevelEmitter extends PartECBase implements - IStackWatcherHost, IFluidSlotPartOrBlock { - - private Fluid fluid; - private RedstoneMode mode = RedstoneMode.HIGH_SIGNAL; - private IStackWatcher watcher; - private long wantedAmount; - private long currentAmount; - private boolean clientRedstoneOutput = false; - - @Override - public int cableConnectionRenderTo() { - return 8; - } - - public void changeWantedAmount(int modifier, EntityPlayer player) { - setWantedAmount(this.wantedAmount + modifier, player); - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(7, 7, 11, 9, 9, 16); - } - - @Override - public Object getClientGuiElement(EntityPlayer player) { - return new GuiFluidEmitter(this, player); - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerFluidEmitter(this, player); - } - - private boolean isPowering() { - switch (this.mode) { - case LOW_SIGNAL: - return this.wantedAmount >= this.currentAmount; - case HIGH_SIGNAL: - return this.wantedAmount <= this.currentAmount; - default: - return false; - } - } - - @Override - public int isProvidingStrongPower() { - return isPowering() ? 15 : 0; - } - - @Override - public int isProvidingWeakPower() { - return isProvidingStrongPower(); - } - - private void notifyTargetBlock(TileEntity _tile, ForgeDirection _side) { - // note - params are always the same - _tile.getWorldObj().notifyBlocksOfNeighborChange(_tile.xCoord, - _tile.yCoord, _tile.zCoord, Blocks.air); - _tile.getWorldObj().notifyBlocksOfNeighborChange( - _tile.xCoord + _side.offsetX, _tile.yCoord + _side.offsetY, - _tile.zCoord + _side.offsetZ, Blocks.air); - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, - (IPart) this)) { - return super.onActivate(player, pos); - } - return false; - } - - @Override - public void onStackChange(IItemList o, IAEStack fullStack, - IAEStack diffStack, BaseActionSource src, StorageChannel chan) { - if (chan == StorageChannel.FLUIDS && diffStack != null - && ((IAEFluidStack) diffStack).getFluid() == this.fluid) { - this.currentAmount = fullStack != null ? fullStack.getStackSize() - : 0; - - IGridNode node = getGridNode(); - if (node != null) { - setActive(node.isActive()); - getHost().markForUpdate(); - notifyTargetBlock(getHostTile(), getSide()); - } - } - } - - @Override - public void randomDisplayTick(World world, int x, int y, int z, Random r) { - if (this.clientRedstoneOutput) { - ForgeDirection d = getSide(); - double d0 = d.offsetX * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; - double d1 = d.offsetY * 0.45F + (r.nextFloat() - 0.5F) * 0.2D; - 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 void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - this.fluid = FluidRegistry.getFluid(data.getString("fluid")); - this.mode = RedstoneMode.values()[data.getInteger("mode")]; - this.wantedAmount = data.getLong("wantedAmount"); - if (this.wantedAmount < 0) - this.wantedAmount = 0; - } - - @Override - public boolean readFromStream(ByteBuf data) throws IOException { - super.readFromStream(data); - this.clientRedstoneOutput = data.readBoolean(); - if (getHost() != null) - getHost().markForUpdate(); - return true; - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - rh.setTexture(TextureManager.LEVEL_FRONT.getTextures()[0]); - rh.setBounds(7, 7, 11, 9, 9, 14); - rh.renderInventoryBox(renderer); - - rh.setTexture(TextureManager.LEVEL_FRONT.getTextures()[1]); - rh.setBounds(7, 7, 14, 9, 9, 16); - rh.renderInventoryBox(renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - rh.setTexture(TextureManager.LEVEL_FRONT.getTextures()[0]); - rh.setBounds(7, 7, 11, 9, 9, 14); - rh.renderBlock(x, y, z, renderer); - rh.setTexture(this.clientRedstoneOutput ? TextureManager.LEVEL_FRONT - .getTextures()[2] : TextureManager.LEVEL_FRONT.getTextures()[1]); - rh.setBounds(7, 7, 14, 9, 9, 16); - rh.renderBlock(x, y, z, renderer); - } - - @Override - public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { - this.fluid = _fluid; - if (this.watcher == null) - return; - this.watcher.clear(); - updateWatcher(this.watcher); - new PacketFluidSlot(Lists.newArrayList(this.fluid)) - .sendPacketToPlayer(_player); - saveData(); - } - - public void setWantedAmount(long _wantedAmount, EntityPlayer player) { - this.wantedAmount = _wantedAmount; - if (this.wantedAmount < 0) - this.wantedAmount = 0; - new PacketFluidEmitter(this.wantedAmount, player) - .sendPacketToPlayer(player); - notifyTargetBlock(getHostTile(), getSide()); - saveData(); - } - - public void syncClientGui(EntityPlayer player) { - new PacketFluidEmitter(this.mode, player).sendPacketToPlayer(player); - new PacketFluidEmitter(this.wantedAmount, player) - .sendPacketToPlayer(player); - new PacketFluidSlot(Lists.newArrayList(this.fluid)) - .sendPacketToPlayer(player); - } - - public void toggleMode(EntityPlayer player) { - switch (this.mode) { - case LOW_SIGNAL: - this.mode = RedstoneMode.HIGH_SIGNAL; - break; - default: - this.mode = RedstoneMode.LOW_SIGNAL; - break; - } - - notifyTargetBlock(getHostTile(), getSide()); - new PacketFluidEmitter(this.mode, player).sendPacketToPlayer(player); - saveData(); - } - - @Override - public void updateWatcher(IStackWatcher newWatcher) { - this.watcher = newWatcher; - if (this.fluid != null) - this.watcher.add(AEApi.instance().storage() - .createFluidStack(new FluidStack(this.fluid, 1))); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - if (this.fluid != null) - data.setString("fluid", this.fluid.getName()); - else - data.removeTag("fluid"); - data.setInteger("mode", this.mode.ordinal()); - data.setLong("wantedAmount", this.wantedAmount); - } - - @Override - public void writeToStream(ByteBuf data) throws IOException { - super.writeToStream(data); - data.writeBoolean(isPowering()); - } + @Override + public NBTTagCompound transformNBT(NBTTagCompound extra) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + // Fluid + NBTTagCompound fluidSlots = new NBTTagCompound(); + fluidSlots.setTag("#0", FluidCraft.createFluidDisplay(extra.getString("fluid"))); + extra.setTag("config", fluidSlots); + extra.removeTag("fluid"); + // Redstone + RedstoneMode redstoneMode = RedstoneMode.values()[extra.getInteger("mode")]; + if (redstoneMode == RedstoneMode.LOW_SIGNAL) { + extra.setString("REDSTONE_EMITTER", "LOW_SIGNAL"); + } else { + extra.setString("REDSTONE_EMITTER", "HIGH_SIGNAL"); + } + extra.removeTag("mode"); + // Level + long wanted = extra.getLong("wantedAmount"); + extra.setLong("reportingValue", wanted); + extra.setLong("lastReportingValue", wanted); + extra.removeTag("wantedAmount"); + // Part + extra.setTag("part", extra.getCompoundTag("node").getCompoundTag("node0")); + extra.removeTag("node"); + } + return extra; + } } diff --git a/src/main/scala/extracells/part/PartFluidPlaneAnnihilation.java b/src/main/scala/extracells/part/PartFluidPlaneAnnihilation.java index e0c441541..81c7cb091 100644 --- a/src/main/scala/extracells/part/PartFluidPlaneAnnihilation.java +++ b/src/main/scala/extracells/part/PartFluidPlaneAnnihilation.java @@ -1,5 +1,19 @@ package extracells.part; +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; +import net.minecraftforge.fluids.IFluidBlock; + import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; import appeng.api.networking.events.MENetworkChannelChanged; @@ -19,179 +33,129 @@ import extracells.render.TextureManager; import extracells.util.FluidUtil; import extracells.util.PermissionUtil; -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import net.minecraftforge.fluids.IFluidBlock; public class PartFluidPlaneAnnihilation extends PartECBase { - @Override - public int cableConnectionRenderTo() { - return 2; - } - - @SuppressWarnings("unused") - @MENetworkEventSubscribe - public void channelChanged(MENetworkChannelChanged e) { - if (e.node == getGridNode()) - onNeighborChanged(); - } + @Override + public int cableConnectionRenderTo() { + return 2; + } - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 14, 14, 14, 16); - bch.addBox(5, 5, 13, 11, 11, 14); - } + @SuppressWarnings("unused") + @MENetworkEventSubscribe + public void channelChanged(MENetworkChannelChanged e) { + if (e.node == getGridNode()) onNeighborChanged(); + } - @Override - public int getLightLevel() { - return 0; - } + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 13, 11, 11, 14); + } - @Override - public double getPowerUsage() { - return 1.0D; - } + @Override + public double getPowerUsage() { + return 1.0D; + } - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, - (IPart) this)) { - return super.onActivate(player, pos); - } - return false; - } + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this)) { + return super.onActivate(player, pos); + } + return false; + } - @Override - public void onNeighborChanged() { - TileEntity hostTile = getHostTile(); - ECBaseGridBlock gridBlock = getGridBlock(); - if (hostTile == null || gridBlock == null) - return; - IMEMonitor monitor = gridBlock.getFluidMonitor(); - if (monitor == null) - return; - World world = hostTile.getWorldObj(); - int x = hostTile.xCoord; - int y = hostTile.yCoord; - int z = hostTile.zCoord; - ForgeDirection side = getSide(); - Block fluidBlock = world.getBlock(x + side.offsetX, y + side.offsetY, z - + side.offsetZ); - int meta = world.getBlockMetadata(x + side.offsetX, y + side.offsetY, z - + side.offsetZ); + @Override + public void onNeighborChanged() { + TileEntity hostTile = getHostTile(); + ECBaseGridBlock gridBlock = getGridBlock(); + if (hostTile == null || gridBlock == null) return; + IMEMonitor monitor = gridBlock.getFluidMonitor(); + if (monitor == null) return; + World world = hostTile.getWorldObj(); + int x = hostTile.xCoord; + int y = hostTile.yCoord; + int z = hostTile.zCoord; + ForgeDirection side = getSide(); + Block fluidBlock = world.getBlock(x + side.offsetX, y + side.offsetY, z + side.offsetZ); + int meta = world.getBlockMetadata(x + side.offsetX, y + side.offsetY, z + side.offsetZ); - if (fluidBlock instanceof IFluidBlock) { - IFluidBlock block = (IFluidBlock) fluidBlock; - FluidStack drained = block.drain(world, x + side.offsetX, y - + side.offsetY, z + side.offsetZ, false); - if (drained == null) - return; - IAEFluidStack toInject = FluidUtil.createAEFluidStack(drained); - IAEFluidStack notInjected = monitor.injectItems(toInject, - Actionable.SIMULATE, new MachineSource(this)); - if (notInjected != null) - return; - monitor.injectItems(toInject, Actionable.MODULATE, - new MachineSource(this)); - block.drain(world, x + side.offsetX, y + side.offsetY, z - + side.offsetZ, true); - } else if (meta == 0) { - if (fluidBlock == Blocks.flowing_water) { - IAEFluidStack toInject = FluidUtil - .createAEFluidStack(FluidRegistry.WATER); - IAEFluidStack notInjected = monitor.injectItems(toInject, - Actionable.SIMULATE, new MachineSource(this)); - if (notInjected != null) - return; - monitor.injectItems(toInject, Actionable.MODULATE, - new MachineSource(this)); - world.setBlockToAir(x + side.offsetX, y + side.offsetY, z - + side.offsetZ); - } else if (fluidBlock == Blocks.flowing_lava) { - IAEFluidStack toInject = FluidUtil - .createAEFluidStack(FluidRegistry.LAVA); - IAEFluidStack notInjected = monitor.injectItems(toInject, - Actionable.SIMULATE, new MachineSource(this)); - if (notInjected != null) - return; - monitor.injectItems(toInject, Actionable.MODULATE, - new MachineSource(this)); - world.setBlockToAir(x + side.offsetX, y + side.offsetY, z - + side.offsetZ); - } - } - } + if (fluidBlock instanceof IFluidBlock) { + IFluidBlock block = (IFluidBlock) fluidBlock; + FluidStack drained = block.drain(world, x + side.offsetX, y + side.offsetY, z + side.offsetZ, false); + if (drained == null) return; + IAEFluidStack toInject = FluidUtil.createAEFluidStack(drained); + IAEFluidStack notInjected = monitor.injectItems(toInject, Actionable.SIMULATE, new MachineSource(this)); + if (notInjected != null) return; + monitor.injectItems(toInject, Actionable.MODULATE, new MachineSource(this)); + block.drain(world, x + side.offsetX, y + side.offsetY, z + side.offsetZ, true); + } else if (meta == 0) { + if (fluidBlock == Blocks.flowing_water) { + IAEFluidStack toInject = FluidUtil.createAEFluidStack(FluidRegistry.WATER); + IAEFluidStack notInjected = monitor.injectItems(toInject, Actionable.SIMULATE, new MachineSource(this)); + if (notInjected != null) return; + monitor.injectItems(toInject, Actionable.MODULATE, new MachineSource(this)); + world.setBlockToAir(x + side.offsetX, y + side.offsetY, z + side.offsetZ); + } else if (fluidBlock == Blocks.flowing_lava) { + IAEFluidStack toInject = FluidUtil.createAEFluidStack(FluidRegistry.LAVA); + IAEFluidStack notInjected = monitor.injectItems(toInject, Actionable.SIMULATE, new MachineSource(this)); + if (notInjected != null) return; + monitor.injectItems(toInject, Actionable.MODULATE, new MachineSource(this)); + world.setBlockToAir(x + side.offsetX, y + side.offsetY, z + side.offsetZ); + } + } + } - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - IIcon side = TextureManager.PANE_SIDE.getTexture(); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderInventoryBox(renderer); - rh.setBounds(3, 3, 14, 13, 13, 16); - rh.setInvColor(AEColor.Cyan.blackVariant); - rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[0], - ForgeDirection.SOUTH, renderer); - Tessellator.instance.setBrightness(13 << 20 | 13 << 4); - rh.setInvColor(AEColor.Cyan.mediumVariant); - rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(AEColor.Cyan.whiteVariant); - rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[2], - ForgeDirection.SOUTH, renderer); + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + IIcon side = TextureManager.PANE_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + rh.setBounds(3, 3, 14, 13, 13, 16); + rh.setInvColor(AEColor.Cyan.blackVariant); + rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + rh.setInvColor(AEColor.Cyan.mediumVariant); + rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + rh.setInvColor(AEColor.Cyan.whiteVariant); + rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer); - rh.setBounds(5, 5, 13, 11, 11, 14); - renderInventoryBusLights(rh, renderer); - } + rh.setBounds(5, 5, 13, 11, 11, 14); + renderInventoryBusLights(rh, renderer); + } - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - IIcon side = TextureManager.PANE_SIDE.getTexture(); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - rh.setBounds(3, 3, 14, 13, 13, 16); - IPartHost host = getHost(); - if (host != null) { - ts.setColorOpaque_I(host.getColor().blackVariant); - rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[0], - ForgeDirection.SOUTH, renderer); - if (isActive()) - ts.setBrightness(13 << 20 | 13 << 4); - ts.setColorOpaque_I(host.getColor().mediumVariant); - rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(host.getColor().whiteVariant); - rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[2], - ForgeDirection.SOUTH, renderer); - } + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + IIcon side = TextureManager.PANE_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + rh.setBounds(3, 3, 14, 13, 13, 16); + IPartHost host = getHost(); + if (host != null) { + ts.setColorOpaque_I(host.getColor().blackVariant); + rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer); + if (isActive()) ts.setBrightness(13 << 20 | 13 << 4); + ts.setColorOpaque_I(host.getColor().mediumVariant); + rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + ts.setColorOpaque_I(host.getColor().whiteVariant); + rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer); + } - rh.setBounds(5, 5, 13, 11, 11, 14); - renderStaticBusLights(x, y, z, rh, renderer); - } + rh.setBounds(5, 5, 13, 11, 11, 14); + renderStaticBusLights(x, y, z, rh, renderer); + } - @Override - @SuppressWarnings("unused") - @MENetworkEventSubscribe - public void setPower(MENetworkPowerStatusChange notUsed) { - super.setPower(notUsed); - onNeighborChanged(); - } + @Override + @SuppressWarnings("unused") + @MENetworkEventSubscribe + public void setPower(MENetworkPowerStatusChange notUsed) { + super.setPower(notUsed); + onNeighborChanged(); + } } diff --git a/src/main/scala/extracells/part/PartFluidPlaneFormation.java b/src/main/scala/extracells/part/PartFluidPlaneFormation.java index 414fc50d7..fcca32fe8 100644 --- a/src/main/scala/extracells/part/PartFluidPlaneFormation.java +++ b/src/main/scala/extracells/part/PartFluidPlaneFormation.java @@ -1,5 +1,25 @@ package extracells.part; +import java.util.List; + +import net.minecraft.block.Block; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidRegistry; + +import com.google.common.collect.Lists; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.config.RedstoneMode; @@ -16,7 +36,6 @@ import appeng.api.storage.IMEMonitor; import appeng.api.storage.data.IAEFluidStack; import appeng.api.util.AEColor; -import com.google.common.collect.Lists; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import extracells.container.ContainerPlaneFormation; @@ -29,210 +48,167 @@ import extracells.util.FluidUtil; import extracells.util.PermissionUtil; import extracells.util.inventory.ECPrivateInventory; -import net.minecraft.block.Block; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.init.Blocks; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidContainerRegistry; -import net.minecraftforge.fluids.FluidRegistry; - -import java.util.List; -public class PartFluidPlaneFormation extends PartECBase implements - IFluidSlotPartOrBlock, IGridTickable { - - private Fluid fluid; - // TODO redstone control - private RedstoneMode redstoneMode; - private ECPrivateInventory upgradeInventory = new ECPrivateInventory("", 1, - 1) { - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return AEApi.instance().definitions().materials().cardRedstone().isSameAs(itemStack); - } - }; - - @Override - public void getDrops( List drops, boolean wrenched) { - for (ItemStack stack : upgradeInventory.slots) { - if (stack == null) - continue; - drops.add(stack); - } - } - - @Override - public int cableConnectionRenderTo() { - return 2; - } - - public void doWork() { - TileEntity hostTile = getHostTile(); - ECBaseGridBlock gridBlock = getGridBlock(); - ForgeDirection side = getSide(); - - if (this.fluid == null || hostTile == null || gridBlock == null || this.fluid.getBlock() == null) - return; - IMEMonitor monitor = gridBlock.getFluidMonitor(); - if (monitor == null) - return; - World world = hostTile.getWorldObj(); - int x = hostTile.xCoord + side.offsetX; - int y = hostTile.yCoord + side.offsetY; - int z = hostTile.zCoord + side.offsetZ; - Block worldBlock = world.getBlock(x, y, z); - if (worldBlock != null && worldBlock != Blocks.air) - return; - IAEFluidStack canDrain = monitor.extractItems(FluidUtil - .createAEFluidStack(this.fluid, - FluidContainerRegistry.BUCKET_VOLUME), - Actionable.SIMULATE, new MachineSource(this)); - if (canDrain == null - || canDrain.getStackSize() < FluidContainerRegistry.BUCKET_VOLUME) - return; - monitor.extractItems(FluidUtil.createAEFluidStack(this.fluid, - FluidContainerRegistry.BUCKET_VOLUME), Actionable.MODULATE, - new MachineSource(this)); - Block fluidWorldBlock = this.fluid.getBlock(); - world.setBlock(x, y, z, fluidWorldBlock); - world.markBlockForUpdate(x, y, z); - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 14, 14, 14, 16); - bch.addBox(5, 5, 13, 11, 11, 14); - } - - @Override - public Object getClientGuiElement(EntityPlayer player) { - return new GuiFluidPlaneFormation(this, player); - } - - @Override - public int getLightLevel() { - return 0; - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerPlaneFormation(this, player); - } - - @Override - public TickingRequest getTickingRequest(IGridNode node) { - return new TickingRequest(1, 20, false, false); - } - - public ECPrivateInventory getUpgradeInventory() { - return this.upgradeInventory; - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, - (IPart) this)) { - return super.onActivate(player, pos); - } - return false; - } - - @Override - public void readFromNBT(NBTTagCompound data) { - this.fluid = FluidRegistry.getFluid(data.getString("fluid")); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - IIcon side = TextureManager.PANE_SIDE.getTexture(); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderInventoryBox(renderer); - rh.setBounds(3, 3, 14, 13, 13, 16); - rh.setInvColor(AEColor.Cyan.blackVariant); - rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[0], - ForgeDirection.SOUTH, renderer); - Tessellator.instance.setBrightness(13 << 20 | 13 << 4); - rh.setInvColor(ColorUtil.getInvertedInt(AEColor.Cyan.mediumVariant)); - rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(ColorUtil.getInvertedInt(AEColor.Cyan.whiteVariant)); - rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[2], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 13, 11, 11, 14); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - IIcon side = TextureManager.PANE_SIDE.getTexture(); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - rh.setBounds(3, 3, 14, 13, 13, 16); - IPartHost host = getHost(); - if (host != null) { - ts.setColorOpaque_I(host.getColor().blackVariant); - rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[0], - ForgeDirection.SOUTH, renderer); - if (isActive()) - ts.setBrightness(13 << 20 | 13 << 4); - ts.setColorOpaque_I(ColorUtil.getInvertedInt(host.getColor().mediumVariant)); - rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(ColorUtil.getInvertedInt(host.getColor().whiteVariant)); - rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[2], - ForgeDirection.SOUTH, renderer); - } - - rh.setBounds(5, 5, 13, 11, 11, 14); - renderStaticBusLights(x, y, z, rh, renderer); - } - - public void sendInformation(EntityPlayer _player) { - new PacketFluidSlot(Lists.newArrayList(this.fluid)) - .sendPacketToPlayer(_player); - } - - @Override - public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { - this.fluid = _fluid; - new PacketFluidSlot(Lists.newArrayList(this.fluid)) - .sendPacketToPlayer(_player); - saveData(); - } - - @Override - public TickRateModulation tickingRequest(IGridNode node, - int TicksSinceLastCall) { - doWork(); - return TickRateModulation.SAME; - } - - @Override - public void writeToNBT(NBTTagCompound data) { - data.setString("fluid", this.fluid == null ? "" : this.fluid.getName()); - } +public class PartFluidPlaneFormation extends PartECBase implements IFluidSlotPartOrBlock, IGridTickable { + + private Fluid fluid; + // TODO redstone control + private RedstoneMode redstoneMode; + private ECPrivateInventory upgradeInventory = new ECPrivateInventory("", 1, 1) { + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return AEApi.instance().definitions().materials().cardRedstone().isSameAs(itemStack); + } + }; + + @Override + public void getDrops(List drops, boolean wrenched) { + for (ItemStack stack : upgradeInventory.slots) { + if (stack == null) continue; + drops.add(stack); + } + } + + @Override + public int cableConnectionRenderTo() { + return 2; + } + + public void doWork() { + TileEntity hostTile = getHostTile(); + ECBaseGridBlock gridBlock = getGridBlock(); + ForgeDirection side = getSide(); + + if (this.fluid == null || hostTile == null || gridBlock == null || this.fluid.getBlock() == null) return; + IMEMonitor monitor = gridBlock.getFluidMonitor(); + if (monitor == null) return; + World world = hostTile.getWorldObj(); + int x = hostTile.xCoord + side.offsetX; + int y = hostTile.yCoord + side.offsetY; + int z = hostTile.zCoord + side.offsetZ; + Block worldBlock = world.getBlock(x, y, z); + if (worldBlock != null && worldBlock != Blocks.air) return; + IAEFluidStack canDrain = monitor.extractItems( + FluidUtil.createAEFluidStack(this.fluid, FluidContainerRegistry.BUCKET_VOLUME), + Actionable.SIMULATE, + new MachineSource(this)); + if (canDrain == null || canDrain.getStackSize() < FluidContainerRegistry.BUCKET_VOLUME) return; + monitor.extractItems( + FluidUtil.createAEFluidStack(this.fluid, FluidContainerRegistry.BUCKET_VOLUME), + Actionable.MODULATE, + new MachineSource(this)); + Block fluidWorldBlock = this.fluid.getBlock(); + world.setBlock(x, y, z, fluidWorldBlock); + world.markBlockForUpdate(x, y, z); + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(5, 5, 13, 11, 11, 14); + } + + @Override + public Object getClientGuiElement(EntityPlayer player) { + return new GuiFluidPlaneFormation(this, player); + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerPlaneFormation(this, player); + } + + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(2, 120, false, false); + } + + public ECPrivateInventory getUpgradeInventory() { + return this.upgradeInventory; + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this)) { + return super.onActivate(player, pos); + } + return false; + } + + @Override + public void readFromNBT(NBTTagCompound data) { + this.fluid = FluidRegistry.getFluid(data.getString("fluid")); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + IIcon side = TextureManager.PANE_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + rh.setBounds(3, 3, 14, 13, 13, 16); + rh.setInvColor(AEColor.Cyan.blackVariant); + rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setBrightness(13 << 20 | 13 << 4); + rh.setInvColor(ColorUtil.getInvertedInt(AEColor.Cyan.mediumVariant)); + rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + rh.setInvColor(ColorUtil.getInvertedInt(AEColor.Cyan.whiteVariant)); + rh.renderInventoryFace(TextureManager.PANE_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + renderInventoryBusLights(rh, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + IIcon side = TextureManager.PANE_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderBlock(x, y, z, renderer); + rh.setBounds(3, 3, 14, 13, 13, 16); + IPartHost host = getHost(); + if (host != null) { + ts.setColorOpaque_I(host.getColor().blackVariant); + rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer); + if (isActive()) ts.setBrightness(13 << 20 | 13 << 4); + ts.setColorOpaque_I(ColorUtil.getInvertedInt(host.getColor().mediumVariant)); + rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + ts.setColorOpaque_I(ColorUtil.getInvertedInt(host.getColor().whiteVariant)); + rh.renderFace(x, y, z, TextureManager.PANE_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer); + } + + rh.setBounds(5, 5, 13, 11, 11, 14); + renderStaticBusLights(x, y, z, rh, renderer); + } + + public void sendInformation(EntityPlayer _player) { + new PacketFluidSlot(Lists.newArrayList(this.fluid)).sendPacketToPlayer(_player); + } + + @Override + public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { + this.fluid = _fluid; + new PacketFluidSlot(Lists.newArrayList(this.fluid)).sendPacketToPlayer(_player); + saveData(); + } + + @Override + public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { + doWork(); + return TickRateModulation.SAME; + } + + @Override + public void writeToNBT(NBTTagCompound data) { + data.setString("fluid", this.fluid == null ? "" : this.fluid.getName()); + } } diff --git a/src/main/scala/extracells/part/PartFluidStorage.java b/src/main/scala/extracells/part/PartFluidStorage.java index 418a15c69..7c3385cac 100644 --- a/src/main/scala/extracells/part/PartFluidStorage.java +++ b/src/main/scala/extracells/part/PartFluidStorage.java @@ -1,317 +1,389 @@ package extracells.part; +import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidRegistry; + import appeng.api.AEApi; import appeng.api.config.AccessRestriction; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; import appeng.api.networking.events.*; -import appeng.api.parts.IPart; -import appeng.api.parts.IPartCollisionHelper; -import appeng.api.parts.IPartRenderHelper; -import appeng.api.parts.PartItemStack; +import appeng.api.parts.*; import appeng.api.storage.ICellContainer; import appeng.api.storage.IMEInventory; import appeng.api.storage.IMEInventoryHandler; import appeng.api.storage.StorageChannel; import appeng.api.storage.data.IAEFluidStack; import appeng.api.util.AEColor; +import appeng.client.texture.CableBusTextures; +import appeng.helpers.IPriorityHost; +import appeng.items.parts.ItemMultiPart; +import appeng.util.IterationCounter; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import extracells.container.ContainerBusFluidStorage; import extracells.gui.GuiBusFluidStorage; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; import extracells.inventory.HandlerPartStorageFluid; import extracells.network.packet.other.IFluidSlotPartOrBlock; import extracells.network.packet.other.PacketFluidSlot; import extracells.network.packet.part.PacketBusFluidStorage; +import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.PermissionUtil; import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -public class PartFluidStorage extends PartECBase implements ICellContainer, IInventoryUpdateReceiver, IFluidSlotPartOrBlock { - - private HashMap fluidList = new HashMap(); - private int priority = 0; - protected HandlerPartStorageFluid handler = new HandlerPartStorageFluid(this); - private Fluid[] filterFluids = new Fluid[54]; - private AccessRestriction access = AccessRestriction.READ_WRITE; - private ECPrivateInventory upgradeInventory = new ECPrivateInventory("", 1, 1, this) { - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return itemStack != null && AEApi.instance().definitions().materials().cardInverter().isSameAs(itemStack); - } - }; - - @Override - public void getDrops( List drops, boolean wrenched) { - for (ItemStack stack : upgradeInventory.slots) { - if (stack == null) - continue; - drops.add(stack); - } - } - - @Override - public ItemStack getItemStack(PartItemStack type) { - ItemStack stack = super.getItemStack(type); - if (type.equals(PartItemStack.Wrench)) - stack.getTagCompound().removeTag("upgradeInventory"); - return stack; - } - - @Override - public void blinkCell(int slot) {} - - @Override - public int cableConnectionRenderTo() { - return 3; - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 15, 14, 14, 16); - bch.addBox(4, 4, 14, 12, 12, 15); - bch.addBox(5, 5, 13, 11, 11, 14); - } - - @Override - public List getCellArray(StorageChannel channel) { - List list = new ArrayList(); - if (channel == StorageChannel.FLUIDS) { - list.add(this.handler); - } - updateNeighborFluids(); - return list; - } - - @Override - public Object getClientGuiElement(EntityPlayer player) { - return new GuiBusFluidStorage(this, player); - } - - @Override - public int getLightLevel() { - return 0; - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - @Override - public int getPriority() { - return this.priority; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerBusFluidStorage(this, player); - } - - public ECPrivateInventory getUpgradeInventory() { - return this.upgradeInventory; - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - return PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this) && super.onActivate(player, pos); - } - - @Override - public void onInventoryChanged() { - this.handler.setInverted(AEApi.instance().definitions().materials().cardInverter().isSameAs(this.upgradeInventory.getStackInSlot(0))); - saveData(); - } - - @Override - public void onNeighborChanged() { - this.handler.onNeighborChange(); - IGridNode node = getGridNode(); - if (node != null) { - IGrid grid = node.getGrid(); - if (grid != null && this.wasChanged()) { - grid.postEvent(new MENetworkCellArrayUpdate()); - node.getGrid().postEvent(new MENetworkStorageEvent(getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); - node.getGrid().postEvent(new MENetworkCellArrayUpdate()); - } - getHost().markForUpdate(); - } - } - - @MENetworkEventSubscribe - public void powerChange(MENetworkPowerStatusChange event) { - IGridNode node = getGridNode(); - if (node != null) { - boolean isNowActive = node.isActive(); - if (isNowActive != isActive()) { - setActive(isNowActive); - onNeighborChanged(); - getHost().markForUpdate(); - } - } - node.getGrid().postEvent(new MENetworkStorageEvent(getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); - node.getGrid().postEvent(new MENetworkCellArrayUpdate()); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - this.priority = data.getInteger("priority"); - for (int i = 0; i < 9; i++) { - this.filterFluids[i] = FluidRegistry.getFluid(data.getString("FilterFluid#" + i)); - } - if (data.hasKey("access")) { - try { - this.access = AccessRestriction.valueOf(data.getString("access")); - } catch (Throwable e) {} - } - this.upgradeInventory.readFromNBT(data.getTagList("upgradeInventory", 10)); - onInventoryChanged(); - onNeighborChanged(); - this.handler.setPrioritizedFluids(this.filterFluids); - this.handler.setAccessRestriction(this.access); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.STORAGE_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.STORAGE_FRONT.getTextures()[0], side, side); - rh.setBounds(2, 2, 15, 14, 14, 16); - rh.renderInventoryBox(renderer); - - rh.setBounds(4, 4, 14, 12, 12, 15); - rh.renderInventoryBox(renderer); - rh.setBounds(2, 2, 15, 14, 14, 16); - rh.setInvColor(AEColor.Cyan.blackVariant); - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderInventoryFace(TextureManager.STORAGE_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 13, 11, 11, 14); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.STORAGE_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.STORAGE_FRONT.getTexture(), side, side); - rh.setBounds(2, 2, 15, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - - ts.setColorOpaque_I(getHost().getColor().blackVariant); - if (isActive()) - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderFace(x, y, z, TextureManager.STORAGE_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - rh.setBounds(4, 4, 14, 12, 12, 15); - rh.renderBlock(x, y, z, renderer); - - rh.setBounds(5, 5, 13, 11, 11, 14); - renderStaticBusLights(x, y, z, rh, renderer); - } - - @Override - public void saveChanges(IMEInventory cellInventory) { - saveData(); - } - - public void sendInformation(EntityPlayer player) { - new PacketFluidSlot(Arrays.asList(this.filterFluids)) - .sendPacketToPlayer(player); - new PacketBusFluidStorage(player, this.access, true) - .sendPacketToPlayer(player); - } - - @Override - public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { - this.filterFluids[_index] = _fluid; - this.handler.setPrioritizedFluids(this.filterFluids); - sendInformation(_player); - saveData(); - } - - public void updateAccess(AccessRestriction access) { - this.access = access; - this.handler.setAccessRestriction(access); - onNeighborChanged(); - } - - @MENetworkEventSubscribe - public void updateChannels(MENetworkChannelsChanged channel) { - IGridNode node = getGridNode(); - if (node != null) { - boolean isNowActive = node.isActive(); - if (isNowActive != isActive()) { - setActive(isNowActive); - onNeighborChanged(); - getHost().markForUpdate(); - } - } - node.getGrid().postEvent( - new MENetworkStorageEvent(getGridBlock().getFluidMonitor(), - StorageChannel.FLUIDS)); - node.getGrid().postEvent(new MENetworkCellArrayUpdate()); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - data.setInteger("priority", this.priority); - for (int i = 0; i < this.filterFluids.length; i++) { - Fluid fluid = this.filterFluids[i]; - if (fluid != null) - data.setString("FilterFluid#" + i, fluid.getName()); - else - data.setString("FilterFluid#" + i, ""); - } - data.setTag("upgradeInventory", this.upgradeInventory.writeToNBT()); - data.setString("access", this.access.name()); - } - - private void updateNeighborFluids(){ - fluidList.clear(); - if(access == AccessRestriction.READ || access == AccessRestriction.READ_WRITE){ - for(IAEFluidStack stack : handler.getAvailableItems(AEApi.instance().storage().createFluidList())){ - FluidStack s = stack.getFluidStack().copy(); - fluidList.put(s, s.amount); - } - } - } - - private boolean wasChanged(){ - HashMap fluids = new HashMap(); - for(IAEFluidStack stack : handler.getAvailableItems(AEApi.instance().storage().createFluidList())){ - FluidStack s = stack.getFluidStack(); - fluids.put(s, s.amount); - } - return !fluids.equals(fluidList); - } +public class PartFluidStorage extends PartECBase + implements ICellContainer, IInventoryUpdateReceiver, IFluidSlotPartOrBlock, IPriorityHost, IPartDeprecated { + + private final HashMap fluidList = new HashMap(); + private int priority = 0; + protected HandlerPartStorageFluid handler = new HandlerPartStorageFluid(this); + private final Fluid[] filterFluids = new Fluid[54]; + private AccessRestriction access = AccessRestriction.READ_WRITE; + private final ECPrivateInventory upgradeInventory = new ECPrivateInventory("", 1, 1, this) { + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return itemStack != null && AEApi.instance().definitions().materials().cardInverter().isSameAs(itemStack); + } + }; + + @Override + public void getDrops(List drops, boolean wrenched) { + for (ItemStack stack : upgradeInventory.slots) { + if (stack == null) continue; + drops.add(stack); + } + } + + @Override + public void blinkCell(int slot) {} + + @Override + public int cableConnectionRenderTo() { + return 3; + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 15, 14, 14, 16); + bch.addBox(4, 4, 14, 12, 12, 15); + bch.addBox(5, 5, 13, 11, 11, 14); + } + + @Override + public List getCellArray(StorageChannel channel) { + List list = new ArrayList(); + if (channel == StorageChannel.FLUIDS) { + list.add(this.handler); + } + updateNeighborFluids(); + return list; + } + + @Override + public Object getClientGuiElement(EntityPlayer player) { + return new GuiBusFluidStorage(this, player); + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + @Override + public int getPriority() { + return this.priority; + } + + @Override + public void setPriority(int priority) { + this.priority = priority; + } + + @Override + public int getLightLevel() { + return this.isPowered() ? 9 : 0; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerBusFluidStorage(this, player); + } + + public ECPrivateInventory getUpgradeInventory() { + return this.upgradeInventory; + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + return PermissionUtil.hasPermission(player, SecurityPermissions.BUILD, (IPart) this) + && super.onActivate(player, pos); + } + + @Override + public void onInventoryChanged() { + this.handler.setInverted( + AEApi.instance().definitions().materials().cardInverter() + .isSameAs(this.upgradeInventory.getStackInSlot(0))); + saveData(); + } + + @Override + public void onNeighborChanged() { + this.handler.onNeighborChange(); + IGridNode node = getGridNode(); + if (node != null) { + IGrid grid = node.getGrid(); + if (grid != null && this.wasChanged()) { + grid.postEvent(new MENetworkCellArrayUpdate()); + node.getGrid() + .postEvent(new MENetworkStorageEvent(getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); + node.getGrid().postEvent(new MENetworkCellArrayUpdate()); + } + getHost().markForUpdate(); + } + } + + @MENetworkEventSubscribe + public void powerChange(MENetworkPowerStatusChange event) { + IGridNode node = getGridNode(); + if (node != null) { + boolean isNowActive = node.isActive(); + if (isNowActive != isActive()) { + setActive(isNowActive); + onNeighborChanged(); + getHost().markForUpdate(); + } + } + node.getGrid().postEvent(new MENetworkStorageEvent(getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); + node.getGrid().postEvent(new MENetworkCellArrayUpdate()); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.priority = data.getInteger("priority"); + for (int i = 0; i < 54; i++) { + this.filterFluids[i] = FluidRegistry.getFluid(data.getString("FilterFluid#" + i)); + } + if (data.hasKey("access")) { + try { + this.access = AccessRestriction.valueOf(data.getString("access")); + } catch (Throwable e) {} + } + this.upgradeInventory.readFromNBT(data.getTagList("upgradeInventory", 10)); + onInventoryChanged(); + onNeighborChanged(); + this.handler.setPrioritizedFluids(this.filterFluids); + this.handler.setAccessRestriction(this.access); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + final IIcon sideTexture = CableBusTextures.PartStorageSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartStorageBack.getIcon(); + final IIcon frontTexture = TextureManager.STORAGE_FRONT.getTexture(); + final IIcon noTexture = ItemMultiPart.instance.getIconFromDamage(220); + + rh.setTexture(sideTexture, sideTexture, noTexture, frontTexture, sideTexture, sideTexture); + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderInventoryBox(renderer); + + rh.setTexture(sideTexture, sideTexture, backTexture, noTexture, sideTexture, sideTexture); + rh.setBounds(2, 2, 14, 14, 14, 15); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 12, 11, 11, 14); + rh.renderInventoryBox(renderer); + + rh.setBounds(2, 2, 15, 14, 14, 16); + rh.setInvColor(AEColor.Cyan.blackVariant); + Tessellator.instance.setBrightness(15 << 20 | 15 << 4); + rh.renderInventoryFace(TextureManager.STORAGE_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + final IPartHost host = getHost(); + final IIcon sideTexture = CableBusTextures.PartStorageSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartStorageBack.getIcon(); + final IIcon frontTexture = TextureManager.STORAGE_FRONT.getTexture(); + final IIcon noTexture = ItemMultiPart.instance.getIconFromDamage(220); + + rh.setTexture(sideTexture, sideTexture, noTexture, frontTexture, sideTexture, sideTexture); + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.renderBlock(x, y, z, renderer); + + Tessellator.instance.setColorOpaque_I(host.getColor().blackVariant); + if (isActive()) Tessellator.instance.setBrightness(14 << 20 | 14 << 4); + rh.renderFace(x, y, z, TextureManager.STORAGE_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + + rh.setTexture(sideTexture, sideTexture, backTexture, noTexture, sideTexture, sideTexture); + rh.setBounds(2, 2, 14, 14, 14, 15); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 5, 12, 11, 11, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 5, 13, 11, 11, 14); + rh.renderBlock(x, y, z, renderer); + + renderPowerStatus(x, y, z, rh, renderer); + } + + @Override + public void saveChanges(IMEInventory cellInventory) { + saveData(); + } + + public void sendInformation(EntityPlayer player) { + new PacketFluidSlot(Arrays.asList(this.filterFluids)).sendPacketToPlayer(player); + new PacketBusFluidStorage(player, this.access, true).sendPacketToPlayer(player); + } + + @Override + public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { + this.filterFluids[_index] = _fluid; + this.handler.setPrioritizedFluids(this.filterFluids); + sendInformation(_player); + saveData(); + } + + public void updateAccess(AccessRestriction access) { + this.access = access; + this.handler.setAccessRestriction(access); + onNeighborChanged(); + } + + @MENetworkEventSubscribe + public void updateChannels(MENetworkChannelsChanged channel) { + IGridNode node = getGridNode(); + if (node != null) { + boolean isNowActive = node.isActive(); + if (isNowActive != isActive()) { + setActive(isNowActive); + onNeighborChanged(); + getHost().markForUpdate(); + } + } + node.getGrid().postEvent(new MENetworkStorageEvent(getGridBlock().getFluidMonitor(), StorageChannel.FLUIDS)); + node.getGrid().postEvent(new MENetworkCellArrayUpdate()); + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setInteger("priority", this.priority); + for (int i = 0; i < this.filterFluids.length; i++) { + Fluid fluid = this.filterFluids[i]; + if (fluid != null) data.setString("FilterFluid#" + i, fluid.getName()); + else data.setString("FilterFluid#" + i, ""); + } + data.setTag("upgradeInventory", this.upgradeInventory.writeToNBT()); + data.setString("access", this.access.name()); + } + + private void updateNeighborFluids() { + fluidList.clear(); + if (access == AccessRestriction.READ || access == AccessRestriction.READ_WRITE) { + for (IAEFluidStack stack : handler + .getAvailableItems(AEApi.instance().storage().createFluidList(), IterationCounter.fetchNewId())) { + fluidList.put(stack, stack.getStackSize()); + } + } + } + + private boolean wasChanged() { + HashMap fluids = new HashMap(); + for (IAEFluidStack stack : handler + .getAvailableItems(AEApi.instance().storage().createFluidList(), IterationCounter.fetchNewId())) { + fluids.put(stack, stack.getStackSize()); + } + return !fluids.equals(fluidList); + } + + @Override + public NBTTagCompound transformPart(NBTTagCompound def) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FluidCraft.replace(def, PartEnum.FLUIDSTORAGE); + } + return def; + } + + private static int[] FILTER_MAP = null; + static { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + // spotless:off + FILTER_MAP = new int[] { + 0, 9, 18, 27, 36, 45, + 1, 10, 19, 28, 37, 46, + 2, 11, 20, 29, 38, 47, + 3, 12, 21, 30, 39, 48, + 4, 13, 22, 31, 40, 49, + 5, 14, 23, 32, 41, 50, + 6, 15, 24, 33, 42, 51, + 7, 16, 25, 34, 43, 52, + 8, 17, 26, 35, 44, 53 }; + //spotless:on + } + } + + @Override + public NBTTagCompound transformNBT(NBTTagCompound extra) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + // Transform in place, less messy IMO + // Fluid filter slots + NBTTagCompound fluidFilterNew = new NBTTagCompound(); + for (int slot = 0; slot < filterFluids.length; ++slot) { + String oldFilterName = "FilterFluid#" + slot; + fluidFilterNew + .setTag("#" + FILTER_MAP[slot], FluidCraft.createFluidDisplay(extra.getString(oldFilterName))); + extra.removeTag(oldFilterName); + } + extra.setTag("config", fluidFilterNew); + + // Part data + extra.setTag("part", extra.getCompoundTag("node").getCompoundTag("node0")); + extra.removeTag("node"); + + // Access + extra.setString("ACCESS", extra.getString("access")); + extra.removeTag("access"); + + // Upgrades + NBTTagList upgrades = extra.getTagList("upgradeInventory", TAG_COMPOUND); + NBTTagCompound upgradeNew = new NBTTagCompound(); + upgradeNew.setTag("#0", upgrades.getCompoundTagAt(0)); + upgradeNew.setTag("#1", new NBTTagCompound()); + upgradeNew.setTag("#2", new NBTTagCompound()); + upgradeNew.setTag("#3", new NBTTagCompound()); + upgradeNew.setTag("#4", new NBTTagCompound()); + extra.setTag("upgrades", upgradeNew); + extra.removeTag("upgradeInventory"); + } + return extra; + } } diff --git a/src/main/scala/extracells/part/PartFluidStorageMonitor.java b/src/main/scala/extracells/part/PartFluidStorageMonitor.java index 7843d9f24..8f9c94d96 100644 --- a/src/main/scala/extracells/part/PartFluidStorageMonitor.java +++ b/src/main/scala/extracells/part/PartFluidStorageMonitor.java @@ -1,5 +1,30 @@ package extracells.part; +import java.io.IOException; +import java.util.List; + +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.client.renderer.GLAllocation; +import net.minecraft.client.renderer.OpenGlHelper; +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.*; +import net.minecraft.world.World; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidContainerRegistry; +import net.minecraftforge.fluids.FluidRegistry; +import net.minecraftforge.fluids.FluidStack; + +import org.lwjgl.opengl.GL11; +import org.lwjgl.opengl.GL12; + import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; import appeng.api.networking.security.BaseActionSource; @@ -7,6 +32,7 @@ import appeng.api.networking.storage.IStackWatcherHost; import appeng.api.networking.storage.IStorageGrid; import appeng.api.parts.IPartCollisionHelper; +import appeng.api.parts.IPartDeprecated; import appeng.api.parts.IPartHost; import appeng.api.parts.IPartRenderHelper; import appeng.api.storage.IMEMonitor; @@ -15,504 +41,441 @@ import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IItemList; import appeng.api.util.AEColor; +import appeng.api.util.INetworkToolAgent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import extracells.integration.Integration; +import extracells.integration.ae2fc.FluidCraft; +import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.FluidUtil; import extracells.util.WrenchUtil; import io.netty.buffer.ByteBuf; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.renderer.GLAllocation; -import net.minecraft.client.renderer.OpenGlHelper; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.entity.item.EntityItem; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.ChatComponentTranslation; -import net.minecraft.util.IIcon; -import net.minecraft.util.StatCollector; -import net.minecraft.util.Vec3; -import net.minecraft.world.World; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidContainerRegistry; -import net.minecraftforge.fluids.FluidRegistry; -import net.minecraftforge.fluids.FluidStack; -import org.lwjgl.opengl.GL11; -import org.lwjgl.opengl.GL12; - -import java.io.IOException; -import java.util.List; -public class PartFluidStorageMonitor extends PartECBase implements IStackWatcherHost { - - Fluid fluid = null; - long amount = 0L; - private Object dspList; - - boolean locked = false; - - IStackWatcher watcher = null; - - @Override - public int cableConnectionRenderTo() { - return 1; - } - - protected void dropItems(World world, int x, int y, int z, ItemStack stack) { - if (world == null) - return; - if (!world.isRemote) { - float f = 0.7F; - double d0 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; - double d1 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; - double d2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; - EntityItem entityitem = new EntityItem(world, x + d0, y + d1, z + d2, stack); - entityitem.delayBeforeCanPickup = 10; - world.spawnEntityInWorld(entityitem); - } - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 14, 14, 14, 16); - bch.addBox(4, 4, 13, 12, 12, 14); - bch.addBox(5, 5, 12, 11, 11, 13); - } - - protected IMEMonitor getFluidStorage() { - IGridNode n = getGridNode(); - if (n == null) - return null; - IGrid g = n.getGrid(); - if (g == null) - return null; - IStorageGrid storage = g.getCache(IStorageGrid.class); - if (storage == null) - return null; - return storage.getFluidInventory(); - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - @Override - public List getWailaBodey(NBTTagCompound data, List list) { - super.getWailaBodey(data, list); - long amount = 0L; - Fluid fluid = null; - if (data.hasKey("locked") && data.getBoolean("locked")) - list.add(StatCollector - .translateToLocal("waila.appliedenergistics2.Locked")); - else - list.add(StatCollector - .translateToLocal("waila.appliedenergistics2.Unlocked")); - if (data.hasKey("amount")) - amount = data.getLong("amount"); - if (data.hasKey("fluid")) { - int id = data.getInteger("fluid"); - if (id != -1) - fluid = FluidRegistry.getFluid(id); - } - if (fluid != null) { - list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " - + fluid.getLocalizedName(new FluidStack(fluid, - FluidContainerRegistry.BUCKET_VOLUME))); - if (isActive()) - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": " - + amount + "mB"); - else - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": 0mB"); - } else { - list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " - + StatCollector - .translateToLocal("extracells.tooltip.empty1")); - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") + ": 0mB"); - } - return list; - } - - @Override - public NBTTagCompound getWailaTag(NBTTagCompound tag) { - super.getWailaTag(tag); - tag.setBoolean("locked", this.locked); - tag.setLong("amount", this.amount); - if (this.fluid == null) - tag.setInteger("fluid", -1); - else - tag.setInteger("fluid", this.fluid.getID()); - return tag; - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (player == null || player.worldObj == null) - return true; - if (player.worldObj.isRemote) - return true; - ItemStack s = player.getCurrentEquippedItem(); - if (s == null) { - if (this.locked) - return false; - if (this.fluid == null) - return true; - if (this.watcher != null) - this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)); - this.fluid = null; - this.amount = 0L; - IPartHost host = getHost(); - if (host != null) - host.markForUpdate(); - return true; - } - if (WrenchUtil.canWrench(s, player, this.tile.xCoord, this.tile.yCoord, - this.tile.zCoord)) { - this.locked = !this.locked; - WrenchUtil.wrenchUsed(s, player, this.tile.xCoord, - this.tile.zCoord, this.tile.yCoord); - IPartHost host = getHost(); - if (host != null) - host.markForUpdate(); - if (this.locked) - player.addChatMessage(new ChatComponentTranslation( - "chat.appliedenergistics2.isNowLocked")); - else - player.addChatMessage(new ChatComponentTranslation( - "chat.appliedenergistics2.isNowUnlocked")); - return true; - } - if (this.locked) - return false; - if (FluidUtil.isFilled(s)) { - if (this.fluid != null && this.watcher != null) - this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)); - this.fluid = FluidUtil.getFluidFromContainer(s).getFluid(); - if (this.watcher != null) - this.watcher.add(FluidUtil.createAEFluidStack(this.fluid)); - IPartHost host = getHost(); - if (host != null) - host.markForUpdate(); - return true; - } - return false; - } - - @Override - public void onStackChange(IItemList arg0, IAEStack arg1, IAEStack arg2, - BaseActionSource arg3, StorageChannel arg4) { - if (this.fluid != null) { - IGridNode n = getGridNode(); - if (n == null) - return; - IGrid g = n.getGrid(); - if (g == null) - return; - IStorageGrid storage = g.getCache(IStorageGrid.class); - if (storage == null) - return; - IMEMonitor fluids = getFluidStorage();; - if (fluids == null) - return; - for (IAEFluidStack s : fluids.getStorageList()) { - if (s.getFluid() == this.fluid) { - this.amount = s.getStackSize(); - IPartHost host = getHost(); - if (host != null) - host.markForUpdate(); - return; - } - } - this.amount = 0L; - IPartHost host = getHost(); - if (host != null) - host.markForUpdate(); - } - - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - if (data.hasKey("amount")) - this.amount = data.getLong("amount"); - if (data.hasKey("fluid")) { - int id = data.getInteger("fluid"); - if (id == -1) - this.fluid = null; - else - this.fluid = FluidRegistry.getFluid(id); - } - if (data.hasKey("locked")) - this.locked = data.getBoolean("locked"); - } - - @Override - public boolean readFromStream(ByteBuf data) throws IOException { - super.readFromStream(data); - this.amount = data.readLong(); - int id = data.readInt(); - if (id == -1) - this.fluid = null; - else - this.fluid = FluidRegistry.getFluid(id); - this.locked = data.readBoolean(); - return true; - } - - @Override - @SideOnly(Side.CLIENT) - public void renderDynamic(double x, double y, double z, - IPartRenderHelper rh, RenderBlocks renderer) { - if (this.fluid == null) - return; - - if (this.dspList == null) - this.dspList = GLAllocation.generateDisplayLists(1); - - Tessellator tess = Tessellator.instance; - - if (!isActive()) - return; - - IAEFluidStack ais = FluidUtil.createAEFluidStack(this.fluid); - ais.setStackSize(this.amount); - if (ais != null) { - GL11.glPushMatrix(); - GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); - - GL11.glNewList((Integer) this.dspList, GL11.GL_COMPILE_AND_EXECUTE); - this.renderFluid(tess, ais); - GL11.glEndList(); - - GL11.glPopMatrix(); - } - } - - @SideOnly(Side.CLIENT) - private void renderFluid(Tessellator tess, IAEFluidStack fluidStack) { - GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); - ForgeDirection d = this.getSide(); - GL11.glTranslated(d.offsetX * 0.77, d.offsetY * 0.77, d.offsetZ * 0.77); - - if (d == ForgeDirection.UP) { - GL11.glScalef(1.0f, -1.0f, 1.0f); - GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); - GL11.glRotatef(90.0F, 0, 0, 1); - } - - if (d == ForgeDirection.DOWN) { - GL11.glScalef(1.0f, -1.0f, 1.0f); - GL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); - GL11.glRotatef(-90.0F, 0, 0, 1); - } - - if (d == ForgeDirection.EAST) { - GL11.glScalef(-1.0f, -1.0f, -1.0f); - GL11.glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); - } - - if (d == ForgeDirection.WEST) { - GL11.glScalef(-1.0f, -1.0f, -1.0f); - GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); - } - - if (d == ForgeDirection.NORTH) { - GL11.glScalef(-1.0f, -1.0f, -1.0f); - } - - if (d == ForgeDirection.SOUTH) { - GL11.glScalef(-1.0f, -1.0f, -1.0f); - GL11.glRotatef(180.0f, 0.0f, 1.0f, 0.0f); - } - - GL11.glPushMatrix(); - try { - - int br = 16 << 20 | 16 << 4; - int var11 = br % 65536; - 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.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL12.GL_RESCALE_NORMAL); - // RenderHelper.enableGUIStandardItemLighting(); - tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); - - IIcon fluidIcon = this.fluid.getIcon(); - if (fluidIcon != null) { - GL11.glTranslatef(0.0f, 0.14f, -0.24f); - GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); - GL11.glTranslated(-8.6F, -16.3, -1.2F); - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - Tessellator cake = Tessellator.instance; - cake.startDrawingQuads(); - try { - cake.setBrightness(255); - cake.setColorRGBA_F(1.0f, 1.0f, 1.0f, 1.0f); - cake.addVertexWithUV(0, 16, 0, fluidIcon.getMinU(), - fluidIcon.getMaxV()); - cake.addVertexWithUV(16, 16, 0, fluidIcon.getMaxU(), - fluidIcon.getMaxV()); - cake.addVertexWithUV(16, 0, 0, fluidIcon.getMaxU(), - fluidIcon.getMinV()); - cake.addVertexWithUV(0, 0, 0, fluidIcon.getMinU(), - fluidIcon.getMinV()); - } finally { - cake.draw(); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - GL11.glPopMatrix(); - - GL11.glTranslatef(0.0f, 0.14f, -0.24f); - GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); - - long qty = fluidStack.getStackSize(); - if (qty > 999999999999L) - qty = 999999999999L; - - String msg = Long.toString(qty) + "mB"; - if (qty > 1000000000) - msg = Long.toString(qty / 1000000000) + "MB"; - else if (qty > 1000000) - msg = Long.toString(qty / 1000000) + "KB"; - else if (qty > 9999) - msg = Long.toString(qty / 1000) + 'B'; - - FontRenderer fr = Minecraft.getMinecraft().fontRenderer; - int width = fr.getStringWidth(msg); - GL11.glTranslatef(-0.5f * width, 0.0f, -1.0f); - fr.drawString(msg, 0, 0, 0); - - GL11.glPopAttrib(); - } - - @Override - @SideOnly(Side.CLIENT) - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); - rh.setTexture(side); - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderInventoryBox(renderer); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderInventoryBox(renderer); - - ts.setBrightness(13 << 20 | 13 << 4); - - rh.setInvColor(0xFFFFFF); - rh.renderInventoryFace(TextureManager.BUS_BORDER.getTexture(), - ForgeDirection.SOUTH, renderer); - - rh.setBounds(3, 3, 15, 13, 13, 16); - rh.setInvColor(AEColor.Transparent.blackVariant); - rh.renderInventoryFace(TextureManager.STORAGE_MONITOR.getTextures()[0], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(AEColor.Transparent.mediumVariant); - rh.renderInventoryFace(TextureManager.STORAGE_MONITOR.getTextures()[1], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(AEColor.Transparent.whiteVariant); - rh.renderInventoryFace(TextureManager.STORAGE_MONITOR.getTextures()[2], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 12, 11, 11, 13); - renderInventoryBusLights(rh, renderer); - } - - @Override - @SideOnly(Side.CLIENT) - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); - rh.setTexture(side); - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderBlock(x, y, z, renderer); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - - if (isActive()) - Tessellator.instance.setBrightness(13 << 20 | 13 << 4); - - ts.setColorOpaque_I(0xFFFFFF); - rh.renderFace(x, y, z, TextureManager.BUS_BORDER.getTexture(), - ForgeDirection.SOUTH, renderer); - - IPartHost host = getHost(); - rh.setBounds(3, 3, 15, 13, 13, 16); - ts.setColorOpaque_I(host.getColor().mediumVariant); - rh.renderFace(x, y, z, TextureManager.STORAGE_MONITOR.getTextures()[0], - ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(host.getColor().whiteVariant); - rh.renderFace(x, y, z, TextureManager.STORAGE_MONITOR.getTextures()[1], - ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(host.getColor().blackVariant); - rh.renderFace(x, y, z, TextureManager.STORAGE_MONITOR.getTextures()[2], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 12, 11, 11, 13); - renderStaticBusLights(x, y, z, rh, renderer); - } - - @Override - public boolean requireDynamicRender() { - return true; - } - - @Override - public void updateWatcher(IStackWatcher w) { - this.watcher = w; - if (this.fluid != null) - w.add(FluidUtil.createAEFluidStack(this.fluid)); - onStackChange(null, null, null, null, null); - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - data.setLong("amount", this.amount); - if (this.fluid == null) - data.setInteger("fluid", -1); - else - data.setInteger("fluid", this.fluid.getID()); - data.setBoolean("locked", this.locked); - } - - @Override - public void writeToStream(ByteBuf data) throws IOException { - super.writeToStream(data); - data.writeLong(this.amount); - if (this.fluid == null) - data.writeInt(-1); - else - data.writeInt(this.fluid.getID()); - data.writeBoolean(this.locked); - - } +public class PartFluidStorageMonitor extends PartECBase + implements IStackWatcherHost, INetworkToolAgent, IPartDeprecated { + + Fluid fluid = null; + long amount = 0L; + private Object dspList; + + boolean locked = false; + + IStackWatcher watcher = null; + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + protected void dropItems(World world, int x, int y, int z, ItemStack stack) { + if (world == null) return; + if (!world.isRemote) { + float f = 0.7F; + double d0 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d1 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + double d2 = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(world, x + d0, y + d1, z + d2, stack); + entityitem.delayBeforeCanPickup = 10; + world.spawnEntityInWorld(entityitem); + } + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(4, 4, 13, 12, 12, 14); + bch.addBox(5, 5, 12, 11, 11, 13); + } + + protected IMEMonitor getFluidStorage() { + IGridNode n = getGridNode(); + if (n == null) return null; + IGrid g = n.getGrid(); + if (g == null) return null; + IStorageGrid storage = g.getCache(IStorageGrid.class); + if (storage == null) return null; + return storage.getFluidInventory(); + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + @Override + public int getLightLevel() { + return this.isPowered() ? 9 : 0; + } + + @Override + public List getWailaBodey(NBTTagCompound data, List list) { + super.getWailaBodey(data, list); + long amount = 0L; + Fluid fluid = null; + if (data.hasKey("locked") && data.getBoolean("locked")) + list.add(StatCollector.translateToLocal("waila.appliedenergistics2.Locked")); + else list.add(StatCollector.translateToLocal("waila.appliedenergistics2.Unlocked")); + if (data.hasKey("amount")) amount = data.getLong("amount"); + if (data.hasKey("fluid")) { + int id = data.getInteger("fluid"); + if (id != -1) fluid = FluidRegistry.getFluid(id); + } + if (fluid != null) { + list.add( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + fluid.getLocalizedName(new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME))); + if (isActive()) + list.add(StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + amount + "mB"); + else list.add(StatCollector.translateToLocal("extracells.tooltip.amount") + ": 0mB"); + } else { + list.add( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + StatCollector.translateToLocal("extracells.tooltip.empty1")); + list.add(StatCollector.translateToLocal("extracells.tooltip.amount") + ": 0mB"); + } + return list; + } + + @Override + public NBTTagCompound getWailaTag(NBTTagCompound tag) { + super.getWailaTag(tag); + tag.setBoolean("locked", this.locked); + tag.setLong("amount", this.amount); + if (this.fluid == null) tag.setInteger("fluid", -1); + else tag.setInteger("fluid", this.fluid.getID()); + return tag; + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (player == null || player.worldObj == null) return true; + if (player.worldObj.isRemote) return true; + ItemStack s = player.getCurrentEquippedItem(); + if (s == null) { + if (this.locked) return false; + if (this.fluid == null) return true; + if (this.watcher != null) this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)); + this.fluid = null; + this.amount = 0L; + IPartHost host = getHost(); + if (host != null) host.markForUpdate(); + return true; + } + if (WrenchUtil.canWrench(s, player, this.tile.xCoord, this.tile.yCoord, this.tile.zCoord)) { + this.locked = !this.locked; + WrenchUtil.wrenchUsed(s, player, this.tile.xCoord, this.tile.zCoord, this.tile.yCoord); + IPartHost host = getHost(); + if (host != null) host.markForUpdate(); + if (this.locked) + player.addChatMessage(new ChatComponentTranslation("chat.appliedenergistics2.isNowLocked")); + else player.addChatMessage(new ChatComponentTranslation("chat.appliedenergistics2.isNowUnlocked")); + return true; + } + if (this.locked) return false; + if (FluidUtil.isFilled(s)) { + if (this.fluid != null && this.watcher != null) + this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)); + this.fluid = FluidUtil.getFluidFromContainer(s).getFluid(); + if (this.watcher != null) this.watcher.add(FluidUtil.createAEFluidStack(this.fluid)); + updateFluidAmount(); + IPartHost host = getHost(); + if (host != null) host.markForUpdate(); + return true; + } + return false; + } + + protected void updateFluidAmount() { + if (this.fluid != null) { + IGridNode n = getGridNode(); + if (n == null) return; + IGrid g = n.getGrid(); + if (g == null) return; + IStorageGrid storage = g.getCache(IStorageGrid.class); + if (storage == null) return; + IMEMonitor fluids = getFluidStorage();; + if (fluids == null) return; + for (IAEFluidStack s : fluids.getStorageList()) { + if (s.getFluid() == this.fluid) { + this.amount = s.getStackSize(); + IPartHost host = getHost(); + if (host != null) host.markForUpdate(); + return; + } + } + this.amount = 0L; + IPartHost host = getHost(); + if (host != null) host.markForUpdate(); + } + } + + @Override + public void onStackChange(IItemList arg0, IAEStack arg1, IAEStack arg2, BaseActionSource arg3, + StorageChannel arg4) { + updateFluidAmount(); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("amount")) this.amount = data.getLong("amount"); + if (data.hasKey("fluid")) { + int id = data.getInteger("fluid"); + if (id == -1) this.fluid = null; + else this.fluid = FluidRegistry.getFluid(id); + } + if (data.hasKey("locked")) this.locked = data.getBoolean("locked"); + } + + @Override + public boolean readFromStream(ByteBuf data) throws IOException { + super.readFromStream(data); + this.amount = data.readLong(); + int id = data.readInt(); + if (id == -1) this.fluid = null; + else this.fluid = FluidRegistry.getFluid(id); + this.locked = data.readBoolean(); + return true; + } + + @Override + @SideOnly(Side.CLIENT) + public void renderDynamic(double x, double y, double z, IPartRenderHelper rh, RenderBlocks renderer) { + if (this.fluid == null) return; + + if (this.dspList == null) this.dspList = GLAllocation.generateDisplayLists(1); + + Tessellator tess = Tessellator.instance; + + if (!isActive()) return; + + IAEFluidStack ais = FluidUtil.createAEFluidStack(this.fluid); + ais.setStackSize(this.amount); + if (ais != null) { + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y + 0.5, z + 0.5); + + GL11.glNewList((Integer) this.dspList, GL11.GL_COMPILE_AND_EXECUTE); + this.renderFluid(tess, ais); + GL11.glEndList(); + + GL11.glPopMatrix(); + } + } + + @SideOnly(Side.CLIENT) + private void renderFluid(Tessellator tess, IAEFluidStack fluidStack) { + GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS); + ForgeDirection d = this.getSide(); + GL11.glTranslated(d.offsetX * 0.77, d.offsetY * 0.77, d.offsetZ * 0.77); + + if (d == ForgeDirection.UP) { + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(90.0F, 0, 0, 1); + } + + if (d == ForgeDirection.DOWN) { + GL11.glScalef(1.0f, -1.0f, 1.0f); + GL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); + GL11.glRotatef(-90.0F, 0, 0, 1); + } + + if (d == ForgeDirection.EAST) { + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(-90.0f, 0.0f, 1.0f, 0.0f); + } + + if (d == ForgeDirection.WEST) { + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(90.0f, 0.0f, 1.0f, 0.0f); + } + + if (d == ForgeDirection.NORTH) { + GL11.glScalef(-1.0f, -1.0f, -1.0f); + } + + if (d == ForgeDirection.SOUTH) { + GL11.glScalef(-1.0f, -1.0f, -1.0f); + GL11.glRotatef(180.0f, 0.0f, 1.0f, 0.0f); + } + + GL11.glPushMatrix(); + try { + + int br = 16 << 20 | 16 << 4; + int var11 = br % 65536; + 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.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL12.GL_RESCALE_NORMAL); + // RenderHelper.enableGUIStandardItemLighting(); + tess.setColorOpaque_F(1.0f, 1.0f, 1.0f); + + IIcon fluidIcon = this.fluid.getIcon(); + if (fluidIcon != null) { + GL11.glTranslatef(0.0f, 0.14f, -0.24f); + GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); + GL11.glTranslated(-8.6F, -16.3, -1.2F); + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + Tessellator cake = Tessellator.instance; + cake.startDrawingQuads(); + try { + cake.setBrightness(255); + cake.setColorRGBA_F( + (this.fluid.getColor() >> 16 & 0xFF) / 255.0F, + (this.fluid.getColor() >> 8 & 0xFF) / 255.0F, + (this.fluid.getColor() & 0xFF) / 255.0F, + 1.0F); + cake.addVertexWithUV(0, 16, 0, fluidIcon.getMinU(), fluidIcon.getMaxV()); + cake.addVertexWithUV(16, 16, 0, fluidIcon.getMaxU(), fluidIcon.getMaxV()); + cake.addVertexWithUV(16, 0, 0, fluidIcon.getMaxU(), fluidIcon.getMinV()); + cake.addVertexWithUV(0, 0, 0, fluidIcon.getMinU(), fluidIcon.getMinV()); + } finally { + cake.draw(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + + GL11.glPopMatrix(); + + GL11.glTranslatef(0.0f, 0.14f, -0.24f); + GL11.glScalef(1.0f / 62.0f, 1.0f / 62.0f, 1.0f / 62.0f); + + long qty = fluidStack.getStackSize(); + if (qty > 999999999999L) qty = 999999999999L; + + String msg = Long.toString(qty) + "mB"; + if (qty > 1000000000) msg = Long.toString(qty / 1000000000) + "MB"; + else if (qty > 1000000) msg = Long.toString(qty / 1000000) + "KB"; + else if (qty > 9999) msg = Long.toString(qty / 1000) + 'B'; + + FontRenderer fr = Minecraft.getMinecraft().fontRenderer; + int width = fr.getStringWidth(msg); + GL11.glTranslatef(-0.5f * width, 0.0f, -1.0f); + fr.drawString(msg, 0, 0, 0); + + GL11.glPopAttrib(); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + + IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); + rh.setTexture(side); + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + ts.setBrightness(13 << 20 | 13 << 4); + + rh.setInvColor(0xFFFFFF); + rh.renderInventoryFace(TextureManager.BUS_BORDER.getTexture(), ForgeDirection.SOUTH, renderer); + + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.setInvColor(AEColor.Transparent.blackVariant); + rh.renderInventoryFace(TextureManager.STORAGE_MONITOR.getTextures()[0], ForgeDirection.SOUTH, renderer); + rh.setInvColor(AEColor.Transparent.mediumVariant); + rh.renderInventoryFace(TextureManager.STORAGE_MONITOR.getTextures()[1], ForgeDirection.SOUTH, renderer); + rh.setInvColor(AEColor.Transparent.whiteVariant); + rh.renderInventoryFace(TextureManager.STORAGE_MONITOR.getTextures()[2], ForgeDirection.SOUTH, renderer); + + rh.setBounds(5, 5, 12, 11, 11, 13); + renderInventoryBusLights(rh, renderer); + } + + @Override + @SideOnly(Side.CLIENT) + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + final IPartHost host = getHost(); + + // Render Front Screen + rh.setBounds(3, 3, 15, 13, 13, 16); + Tessellator.instance.setColorOpaque_I(host.getColor().mediumVariant); + rh.renderFace(x, y, z, TextureManager.STORAGE_MONITOR.getTextures()[0], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setColorOpaque_I(host.getColor().whiteVariant); + rh.renderFace(x, y, z, TextureManager.STORAGE_MONITOR.getTextures()[1], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setColorOpaque_I(host.getColor().blackVariant); + rh.renderFace(x, y, z, TextureManager.STORAGE_MONITOR.getTextures()[2], ForgeDirection.SOUTH, renderer); + + renderFrontPanel(x, y, z, rh, renderer); + renderBackPanel(x, y, z, rh, renderer); + renderPowerStatus(x, y, z, rh, renderer); + } + + @Override + public boolean requireDynamicRender() { + return true; + } + + @Override + public void updateWatcher(IStackWatcher w) { + this.watcher = w; + if (this.fluid != null) w.add(FluidUtil.createAEFluidStack(this.fluid)); + onStackChange(null, null, null, null, null); + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setLong("amount", this.amount); + if (this.fluid == null) data.setInteger("fluid", -1); + else data.setInteger("fluid", this.fluid.getID()); + data.setBoolean("locked", this.locked); + } + + @Override + public void writeToStream(ByteBuf data) throws IOException { + super.writeToStream(data); + data.writeLong(this.amount); + if (this.fluid == null) data.writeInt(-1); + else data.writeInt(this.fluid.getID()); + data.writeBoolean(this.locked); + } + + @Override + public boolean showNetworkInfo(final MovingObjectPosition where) { + return false; + } + + @Override + public NBTTagCompound transformPart(NBTTagCompound def) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + FluidCraft.replace(def, PartEnum.FLUIDMONITOR); + } + return def; + } + + @Override + public NBTTagCompound transformNBT(NBTTagCompound extra) { + if (Integration.Mods.FLUIDCRAFT.isEnabled()) { + // Fluid + // long amount = extra.getLong("amount"); + int fluid = extra.getInteger("fluid"); + Fluid f = FluidRegistry.getFluid(fluid); + NBTTagCompound itemDisplay = FluidCraft.createFluidNBT(f.getName(), 0L); + extra.setTag("configuredItem", itemDisplay); + extra.removeTag("amount"); + extra.removeTag("fluid"); + // Locked and other props + extra.setBoolean("isLocked", extra.getBoolean("locked")); + extra.removeTag("locked"); + extra.setByte("spin", (byte) 0); + extra.setFloat("opacity", 255.0f); + // Part + extra.setTag("part", extra.getCompoundTag("node").getCompoundTag("node0")); + extra.removeTag("node"); + } + return extra; + } } diff --git a/src/main/scala/extracells/part/PartFluidTerminal.java b/src/main/scala/extracells/part/PartFluidTerminal.java index e50d29862..6dfd83415 100644 --- a/src/main/scala/extracells/part/PartFluidTerminal.java +++ b/src/main/scala/extracells/part/PartFluidTerminal.java @@ -1,5 +1,24 @@ package extracells.part; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.item.EntityItem; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.Vec3; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.apache.commons.lang3.tuple.MutablePair; + import appeng.api.config.Actionable; import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGridNode; @@ -7,10 +26,14 @@ import appeng.api.networking.ticking.IGridTickable; import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickingRequest; -import appeng.api.parts.*; +import appeng.api.parts.IPart; +import appeng.api.parts.IPartCollisionHelper; +import appeng.api.parts.IPartHost; +import appeng.api.parts.IPartRenderHelper; import appeng.api.storage.IMEMonitor; import appeng.api.storage.data.IAEFluidStack; import appeng.api.util.AEColor; +import appeng.client.texture.CableBusTextures; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import extracells.container.ContainerFluidTerminal; @@ -23,295 +46,300 @@ import extracells.util.PermissionUtil; import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.util.IIcon; -import net.minecraft.util.Vec3; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import org.apache.commons.lang3.tuple.MutablePair; - -import java.util.ArrayList; -import java.util.List; -public class PartFluidTerminal extends PartECBase implements IGridTickable, - IInventoryUpdateReceiver { - - protected Fluid currentFluid; - private List containers = new ArrayList(); - protected ECPrivateInventory inventory = new ECPrivateInventory( - "extracells.part.fluid.terminal", 2, 64, this) { - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemStack) { - return isItemValidForInputSlot(i, itemStack); - } - }; - - protected boolean isItemValidForInputSlot(int i, ItemStack itemStack) { - return FluidUtil.isFluidContainer(itemStack); - } - protected MachineSource machineSource = new MachineSource(this); - - @Override - public void getDrops( List drops, boolean wrenched) { - for (ItemStack stack : inventory.slots) { - if (stack == null) - continue; - drops.add(stack); - } - } - - @Override - public ItemStack getItemStack(PartItemStack type) { - ItemStack stack = super.getItemStack(type); - if (type.equals(PartItemStack.Wrench)) - stack.getTagCompound().removeTag("inventory"); - return stack; - } - - public void addContainer(ContainerFluidTerminal containerTerminalFluid) { - this.containers.add(containerTerminalFluid); - sendCurrentFluid(); - } - - public void addContainer(ContainerGasTerminal containerTerminalGas) { - this.containers.add(containerTerminalGas); - sendCurrentFluid(); - } - - @Override - public int cableConnectionRenderTo() { - return 1; - } - - public void decreaseFirstSlot() { - ItemStack slot = this.inventory.getStackInSlot(0); - slot.stackSize--; - if (slot.stackSize <= 0) - this.inventory.setInventorySlotContents(0, null); - } - - public void doWork() { - ItemStack secondSlot = this.inventory.getStackInSlot(1); - if (secondSlot != null && secondSlot.stackSize >= secondSlot.getMaxStackSize()) - return; - ItemStack container = this.inventory.getStackInSlot(0); - if (!FluidUtil.isFluidContainer(container)) - return; - container = container.copy(); - container.stackSize = 1; - - ECBaseGridBlock gridBlock = getGridBlock(); - if (gridBlock == null) - return; - IMEMonitor monitor = gridBlock.getFluidMonitor(); - if (monitor == null) - return; - - if (FluidUtil.isEmpty(container)) { - if (this.currentFluid == null) - return; - int capacity = FluidUtil.getCapacity(container); - IAEFluidStack result = monitor.extractItems(FluidUtil.createAEFluidStack(this.currentFluid, capacity), Actionable.SIMULATE, this.machineSource); - int proposedAmount = result == null ? 0 : (int) Math.min(capacity, result.getStackSize()); - MutablePair filledContainer = FluidUtil.fillStack(container, new FluidStack(this.currentFluid, proposedAmount)); - if(filledContainer.getLeft() > proposedAmount) - return; - if (fillSecondSlot(filledContainer.getRight())) { - monitor.extractItems(FluidUtil.createAEFluidStack(this.currentFluid, filledContainer.getLeft()), Actionable.MODULATE, this.machineSource); - decreaseFirstSlot(); - } - } else { - FluidStack containerFluid = FluidUtil.getFluidFromContainer(container); - IAEFluidStack notInjected = monitor.injectItems(FluidUtil.createAEFluidStack(containerFluid), Actionable.SIMULATE, this.machineSource); - if (notInjected != null) - return; - MutablePair drainedContainer = FluidUtil.drainStack(container, containerFluid); - ItemStack emptyContainer = drainedContainer.getRight(); - if (emptyContainer == null || fillSecondSlot(emptyContainer)) { - monitor.injectItems(FluidUtil.createAEFluidStack(containerFluid), Actionable.MODULATE, this.machineSource); - decreaseFirstSlot(); - } - } - } - - public boolean fillSecondSlot(ItemStack itemStack) { - if (itemStack == null) - return false; - ItemStack secondSlot = this.inventory.getStackInSlot(1); - if (secondSlot == null) { - this.inventory.setInventorySlotContents(1, itemStack); - return true; - } else { - if (!secondSlot.isItemEqual(itemStack) || !ItemStack.areItemStackTagsEqual(itemStack, secondSlot)) - return false; - this.inventory.incrStackSize(1, itemStack.stackSize); - return true; - } - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(2, 2, 14, 14, 14, 16); - bch.addBox(4, 4, 13, 12, 12, 14); - bch.addBox(5, 5, 12, 11, 11, 13); - } - - @Override - public Object getClientGuiElement(EntityPlayer player) { - return new GuiFluidTerminal(this, player); - } - - public IInventory getInventory() { - return this.inventory; - } - - @Override - public double getPowerUsage() { - return 0.5D; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerFluidTerminal(this, player); - } - - @Override - public TickingRequest getTickingRequest(IGridNode node) { - return new TickingRequest(1, 20, false, false); - } - - @Override - public boolean onActivate(EntityPlayer player, Vec3 pos) { - if (isActive() && (PermissionUtil.hasPermission(player, SecurityPermissions.INJECT, (IPart) this) || PermissionUtil.hasPermission(player, SecurityPermissions.EXTRACT, (IPart) this))) - return super.onActivate(player, pos); - return false; - } - - @Override - public void onInventoryChanged() { - saveData(); - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - this.inventory.readFromNBT(data.getTagList("inventory", 10)); - } - - public void removeContainer(ContainerFluidTerminal containerTerminalFluid) { - this.containers.remove(containerTerminalFluid); - } - - public void removeContainer(ContainerGasTerminal containerTerminalGas) { - this.containers.remove(containerTerminalGas); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); - rh.setTexture(side); - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderInventoryBox(renderer); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), - side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderInventoryBox(renderer); - - ts.setBrightness(13 << 20 | 13 << 4); - - rh.setInvColor(0xFFFFFF); - rh.renderInventoryFace(TextureManager.BUS_BORDER.getTexture(), - ForgeDirection.SOUTH, renderer); - - rh.setBounds(3, 3, 15, 13, 13, 16); - rh.setInvColor(AEColor.Transparent.blackVariant); - rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[0], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(AEColor.Transparent.mediumVariant); - rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - rh.setInvColor(AEColor.Transparent.whiteVariant); - rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[2], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 12, 11, 11, 13); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - - IIcon side = TextureManager.TERMINAL_SIDE.getTexture(); - rh.setTexture(side); - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderBlock(x, y, z, renderer); - rh.setTexture(side, side, side, TextureManager.BUS_BORDER.getTexture(), side, side); - rh.setBounds(2, 2, 14, 14, 14, 16); - rh.renderBlock(x, y, z, renderer); - - if (isActive()) - Tessellator.instance.setBrightness(13 << 20 | 13 << 4); - - ts.setColorOpaque_I(0xFFFFFF); - rh.renderFace(x, y, z, TextureManager.BUS_BORDER.getTexture(), ForgeDirection.SOUTH, renderer); - - IPartHost host = getHost(); - rh.setBounds(3, 3, 15, 13, 13, 16); - ts.setColorOpaque_I(host.getColor().blackVariant); - rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(host.getColor().mediumVariant); - rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); - ts.setColorOpaque_I(host.getColor().whiteVariant); - rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer); - - rh.setBounds(5, 5, 12, 11, 11, 13); - renderStaticBusLights(x, y, z, rh, renderer); - } - - public void sendCurrentFluid() { - for (Object containerFluidTerminal : this.containers) { - sendCurrentFluid(containerFluidTerminal); - } - } - - public void sendCurrentFluid(Object container) { - if(container instanceof ContainerFluidTerminal){ - ContainerFluidTerminal containerFluidTerminal = (ContainerFluidTerminal) container; - new PacketFluidTerminal(containerFluidTerminal.getPlayer(), this.currentFluid).sendPacketToPlayer(containerFluidTerminal.getPlayer()); - }else if(container instanceof ContainerGasTerminal){ - ContainerGasTerminal containerGasTerminal = (ContainerGasTerminal) container; - new PacketFluidTerminal(containerGasTerminal.getPlayer(), this.currentFluid).sendPacketToPlayer(containerGasTerminal.getPlayer()); - } - - } - - public void setCurrentFluid(Fluid _currentFluid) { - this.currentFluid = _currentFluid; - sendCurrentFluid(); - } - - @Override - public TickRateModulation tickingRequest(IGridNode node, - int TicksSinceLastCall) { - doWork(); - return TickRateModulation.FASTER; - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - data.setTag("inventory", this.inventory.writeToNBT()); - } +public class PartFluidTerminal extends PartECBase implements IGridTickable, IInventoryUpdateReceiver { + + protected Fluid currentFluid; + private final List containers = new ArrayList(); + protected ECPrivateInventory inventory = new ECPrivateInventory("extracells.part.fluid.terminal", 2, 64, this) { + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemStack) { + return isItemValidForInputSlot(i, itemStack); + } + }; + + protected boolean isItemValidForInputSlot(int i, ItemStack itemStack) { + return FluidUtil.isFluidContainer(itemStack); + } + + protected MachineSource machineSource = new MachineSource(this); + + @Override + public void getDrops(List drops, boolean wrenched) { + for (ItemStack stack : inventory.slots) { + if (stack == null) continue; + drops.add(stack); + } + } + + @Override + public int getLightLevel() { + return this.isPowered() ? 9 : 0; + } + + public void addContainer(ContainerFluidTerminal containerTerminalFluid) { + this.containers.add(containerTerminalFluid); + sendCurrentFluid(); + } + + public void addContainer(ContainerGasTerminal containerTerminalGas) { + this.containers.add(containerTerminalGas); + sendCurrentFluid(); + } + + @Override + public int cableConnectionRenderTo() { + return 1; + } + + public void decreaseFirstSlot() { + ItemStack slot = this.inventory.getStackInSlot(0); + slot.stackSize--; + if (slot.stackSize <= 0) this.inventory.setInventorySlotContents(0, null); + } + + public void doWork() { + ItemStack secondSlot = this.inventory.getStackInSlot(1); + if (secondSlot != null && secondSlot.stackSize >= secondSlot.getMaxStackSize()) return; + ItemStack container = this.inventory.getStackInSlot(0); + if (!FluidUtil.isFluidContainer(container)) return; + container = container.copy(); + container.stackSize = 1; + + ECBaseGridBlock gridBlock = getGridBlock(); + if (gridBlock == null) return; + IMEMonitor monitor = gridBlock.getFluidMonitor(); + if (monitor == null) return; + + if (FluidUtil.isEmpty(container)) { + if (this.currentFluid == null) return; + FluidStack request = new FluidStack(this.currentFluid, Integer.MAX_VALUE); + MutablePair simulation = FluidUtil + .fillItemFromAe(container, request, monitor, Actionable.SIMULATE, this.machineSource); + if (simulation == null || simulation.getLeft() == null) { + return; + } + if (!fillSecondSlot(simulation.getLeft(), false)) { + return; + } + request.amount = simulation.getRight().amount; + MutablePair result = FluidUtil + .fillItemFromAe(container, request, monitor, Actionable.MODULATE, this.machineSource); + if (result == null || result.getLeft() == null) { + return; + } + if (!fillSecondSlot(result.getLeft(), true)) { + // Rare case: couldn't withdraw all requested fluid with AE, so a partially filled container can't stack + // with the other containers + TileEntity host = getHostTile(); + if (host == null || host.getWorldObj() == null) { + return; + } + ForgeDirection side = getSide(); + EntityItem overflow = new EntityItem( + host.getWorldObj(), + host.xCoord + side.offsetX, + host.yCoord + side.offsetY, + host.zCoord + side.offsetZ, + result.getLeft()); + host.getWorldObj().spawnEntityInWorld(overflow); + } + decreaseFirstSlot(); + } else { + FluidStack containerFluid = FluidUtil.getFluidFromContainer(container); + + ItemStack simulation = FluidUtil + .drainItemIntoAe(container, monitor, Actionable.SIMULATE, this.machineSource); + if (simulation == null) { + return; + } + if (!fillSecondSlot(simulation, false)) { + return; + } + ItemStack result = FluidUtil.drainItemIntoAe(container, monitor, Actionable.MODULATE, this.machineSource); + if (result == null) { + return; + } + if (!fillSecondSlot(result, true)) { + // Rare case: couldn't withdraw all requested fluid with AE, so a partially filled container can't stack + // with the other containers + TileEntity host = getHostTile(); + if (host == null || host.getWorldObj() == null) { + return; + } + ForgeDirection side = getSide(); + EntityItem overflow = new EntityItem( + host.getWorldObj(), + host.xCoord + side.offsetX, + host.yCoord + side.offsetY, + host.zCoord + side.offsetZ, + result); + host.getWorldObj().spawnEntityInWorld(overflow); + } + decreaseFirstSlot(); + } + } + + public boolean fillSecondSlot(ItemStack itemStack, boolean doFill) { + if (itemStack == null) return false; + ItemStack secondSlot = this.inventory.getStackInSlot(1); + if (secondSlot == null) { + if (doFill) { + this.inventory.setInventorySlotContents(1, itemStack); + } + return true; + } else { + if (!secondSlot.isItemEqual(itemStack) || !ItemStack.areItemStackTagsEqual(itemStack, secondSlot)) + return false; + if (doFill) { + this.inventory.incrStackSize(1, itemStack.stackSize); + } + return true; + } + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(2, 2, 14, 14, 14, 16); + bch.addBox(4, 4, 13, 12, 12, 14); + bch.addBox(5, 5, 12, 11, 11, 13); + } + + @Override + public Object getClientGuiElement(EntityPlayer player) { + return new GuiFluidTerminal(this, player); + } + + public IInventory getInventory() { + return this.inventory; + } + + @Override + public double getPowerUsage() { + return 0.5D; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerFluidTerminal(this, player); + } + + @Override + public TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(2, 20, false, false); + } + + @Override + public boolean onActivate(EntityPlayer player, Vec3 pos) { + if (isActive() && (PermissionUtil.hasPermission(player, SecurityPermissions.INJECT, (IPart) this) + || PermissionUtil.hasPermission(player, SecurityPermissions.EXTRACT, (IPart) this))) + return super.onActivate(player, pos); + return false; + } + + @Override + public void onInventoryChanged() { + saveData(); + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + this.inventory.readFromNBT(data.getTagList("inventory", 10)); + } + + public void removeContainer(ContainerFluidTerminal containerTerminalFluid) { + this.containers.remove(containerTerminalFluid); + } + + public void removeContainer(ContainerGasTerminal containerTerminalGas) { + this.containers.remove(containerTerminalGas); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + final IIcon sideTexture = CableBusTextures.PartMonitorSides.getIcon(); + final IIcon backTexture = CableBusTextures.PartMonitorBack.getIcon(); + + // Back Panel + rh.setTexture(sideTexture, sideTexture, backTexture, sideTexture, sideTexture, sideTexture); + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + + // Front Panel + rh.setTexture( + sideTexture, + sideTexture, + backTexture, + TextureManager.BUS_BORDER.getTexture(), + sideTexture, + sideTexture); + rh.setBounds(2, 2, 14, 14, 14, 16); + rh.renderInventoryBox(renderer); + + // Front Screen + rh.setBounds(3, 3, 15, 13, 13, 16); + rh.setInvColor(AEColor.Transparent.blackVariant); + rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer); + rh.setInvColor(AEColor.Transparent.mediumVariant); + rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + rh.setInvColor(AEColor.Transparent.whiteVariant); + rh.renderInventoryFace(TextureManager.TERMINAL_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + final IPartHost host = getHost(); + + // Render front screen + rh.setBounds(3, 3, 15, 13, 13, 16); + Tessellator.instance.setColorOpaque_I(host.getColor().blackVariant); + rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[0], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setColorOpaque_I(host.getColor().mediumVariant); + rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + Tessellator.instance.setColorOpaque_I(host.getColor().whiteVariant); + rh.renderFace(x, y, z, TextureManager.TERMINAL_FRONT.getTextures()[2], ForgeDirection.SOUTH, renderer); + + renderFrontPanel(x, y, z, rh, renderer); + renderBackPanel(x, y, z, rh, renderer); + renderPowerStatus(x, y, z, rh, renderer); + } + + public void sendCurrentFluid() { + for (Object containerFluidTerminal : this.containers) { + sendCurrentFluid(containerFluidTerminal); + } + } + + public void sendCurrentFluid(Object container) { + if (container instanceof ContainerFluidTerminal) { + ContainerFluidTerminal containerFluidTerminal = (ContainerFluidTerminal) container; + new PacketFluidTerminal(containerFluidTerminal.getPlayer(), this.currentFluid) + .sendPacketToPlayer(containerFluidTerminal.getPlayer()); + } else if (container instanceof ContainerGasTerminal) { + ContainerGasTerminal containerGasTerminal = (ContainerGasTerminal) container; + new PacketFluidTerminal(containerGasTerminal.getPlayer(), this.currentFluid) + .sendPacketToPlayer(containerGasTerminal.getPlayer()); + } + } + + public void setCurrentFluid(Fluid _currentFluid) { + this.currentFluid = _currentFluid; + sendCurrentFluid(); + } + + @Override + public TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { + doWork(); + return TickRateModulation.FASTER; + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setTag("inventory", this.inventory.writeToNBT()); + } } diff --git a/src/main/scala/extracells/part/PartGasConversionMonitor.scala b/src/main/scala/extracells/part/PartGasConversionMonitor.scala index 564a4e089..d969a3c4b 100644 --- a/src/main/scala/extracells/part/PartGasConversionMonitor.scala +++ b/src/main/scala/extracells/part/PartGasConversionMonitor.scala @@ -15,13 +15,12 @@ import net.minecraft.util.{ChatComponentTranslation, Vec3} import net.minecraftforge.fluids.FluidStack import org.apache.commons.lang3.tuple.MutablePair - -class PartGasConversionMonitor extends PartFluidConversionMonitor{ +class PartGasConversionMonitor extends PartFluidConversionMonitor { val isMekEnabled = Integration.Mods.MEKANISMGAS.isEnabled override def onActivate(player: EntityPlayer, pos: Vec3): Boolean = { - if(isMekEnabled) + if (isMekEnabled) onActivateGas(player, pos) else false @@ -43,51 +42,94 @@ class PartGasConversionMonitor extends PartFluidConversionMonitor{ val f = GasUtil.getFluidStack(g) if (f == null) return true val fl = FluidUtil.createAEFluidStack(f) - val not: IAEFluidStack = mon.injectItems(fl.copy, Actionable.SIMULATE, new MachineSource(this)) + val not: IAEFluidStack = + mon.injectItems(fl.copy, Actionable.SIMULATE, new MachineSource(this)) if (mon.canAccept(fl) && (not == null || not.getStackSize == 0L)) { mon.injectItems(fl, Actionable.MODULATE, new MachineSource(this)) - val empty1: MutablePair[Integer, ItemStack] = GasUtil.drainStack(s2, g) + val empty1: MutablePair[Integer, ItemStack] = + GasUtil.drainStack(s2, g) val empty: ItemStack = empty1.right if (empty != null) { - dropItems(getHost.getTile.getWorldObj, getHost.getTile.xCoord + getSide.offsetX, getHost.getTile.yCoord + getSide.offsetY, getHost.getTile.zCoord + getSide.offsetZ, empty) + dropItems( + getHost.getTile.getWorldObj, + getHost.getTile.xCoord + getSide.offsetX, + getHost.getTile.yCoord + getSide.offsetY, + getHost.getTile.zCoord + getSide.offsetZ, + empty + ) } val s3: ItemStack = s.copy s3.stackSize = s3.stackSize - 1 if (s3.stackSize == 0) { - player.inventory.setInventorySlotContents(player.inventory.currentItem, null) - } - else { - player.inventory.setInventorySlotContents(player.inventory.currentItem, s3) + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + null + ) + } else { + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + s3 + ) } } return true - } - else if (GasUtil.isEmpty(s2)) { + } else if (GasUtil.isEmpty(s2)) { if (this.fluid == null) return true var extract: IAEFluidStack = null if (s2.getItem.isInstanceOf[IGasItem]) { - extract = mon.extractItems(GasUtil.createAEFluidStack(GasUtil.getGas(this.fluid), (s2.getItem.asInstanceOf[IGasItem]).getMaxGas(s2)), Actionable.SIMULATE, new MachineSource(this)) - } - else + extract = mon.extractItems( + GasUtil.createAEFluidStack( + GasUtil.getGas(this.fluid), + (s2.getItem.asInstanceOf[IGasItem]).getMaxGas(s2) + ), + Actionable.SIMULATE, + new MachineSource(this) + ) + } else return true if (extract != null) { - mon.extractItems(FluidUtil.createAEFluidStack(new FluidStack(this.fluid, extract.getStackSize.toInt)), Actionable.MODULATE, new MachineSource(this)) - val empty1: MutablePair[Integer, ItemStack] = GasUtil.fillStack(s2, GasUtil.getGasStack(extract.getFluidStack)) + extract = mon.extractItems( + extract, + Actionable.MODULATE, + new MachineSource(this) + ) + if (extract == null || extract.getStackSize <= 0) { + return true + } + val empty1: MutablePair[Integer, ItemStack] = + GasUtil.fillStack(s2, GasUtil.getGasStack(extract.getFluidStack)) if (empty1.left == 0) { - mon.injectItems(FluidUtil.createAEFluidStack(new FluidStack(this.fluid, extract.getStackSize.toInt)), Actionable.MODULATE, new MachineSource(this)) + mon.injectItems( + FluidUtil.createAEFluidStack( + new FluidStack(this.fluid, extract.getStackSize.toInt) + ), + Actionable.MODULATE, + new MachineSource(this) + ) return true } val empty: ItemStack = empty1.right if (empty != null) { - dropItems(getHost.getTile.getWorldObj, getHost.getTile.xCoord + getSide.offsetX, getHost.getTile.yCoord + getSide.offsetY, getHost.getTile.zCoord + getSide.offsetZ, empty) + dropItems( + getHost.getTile.getWorldObj, + getHost.getTile.xCoord + getSide.offsetX, + getHost.getTile.yCoord + getSide.offsetY, + getHost.getTile.zCoord + getSide.offsetZ, + empty + ) } val s3: ItemStack = s.copy s3.stackSize = s3.stackSize - 1 if (s3.stackSize == 0) { - player.inventory.setInventorySlotContents(player.inventory.currentItem, null) - } - else { - player.inventory.setInventorySlotContents(player.inventory.currentItem, s3) + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + null + ) + } else { + player.inventory.setInventorySlotContents( + player.inventory.currentItem, + s3 + ) } } return true @@ -104,25 +146,47 @@ class PartGasConversionMonitor extends PartFluidConversionMonitor{ if (s == null) { if (this.locked) return false if (this.fluid == null) return true - if (this.watcher != null) this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) + if (this.watcher != null) + this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) this.fluid = null this.amount = 0L val host: IPartHost = getHost if (host != null) host.markForUpdate return true } - if (WrenchUtil.canWrench(s, player, this.tile.xCoord, this.tile.yCoord, this.tile.zCoord)) { + if ( + WrenchUtil.canWrench( + s, + player, + this.tile.xCoord, + this.tile.yCoord, + this.tile.zCoord + ) + ) { this.locked = !this.locked - WrenchUtil.wrenchUsed(s, player, this.tile.xCoord, this.tile.zCoord, this.tile.yCoord) + WrenchUtil.wrenchUsed( + s, + player, + this.tile.xCoord, + this.tile.zCoord, + this.tile.yCoord + ) val host: IPartHost = getHost if (host != null) host.markForUpdate - if (this.locked) player.addChatMessage(new ChatComponentTranslation("chat.appliedenergistics2.isNowLocked")) - else player.addChatMessage(new ChatComponentTranslation("chat.appliedenergistics2.isNowUnlocked")) + if (this.locked) + player.addChatMessage( + new ChatComponentTranslation("chat.appliedenergistics2.isNowLocked") + ) + else + player.addChatMessage( + new ChatComponentTranslation("chat.appliedenergistics2.isNowUnlocked") + ) return true } if (this.locked) return false if (GasUtil.isFilled(s)) { - if (this.fluid != null && this.watcher != null) this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) + if (this.fluid != null && this.watcher != null) + this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) val gas = GasUtil.getGasFromContainer(s) val fluidStack = GasUtil.getFluidStack(gas) this.fluid = { @@ -131,7 +195,8 @@ class PartGasConversionMonitor extends PartFluidConversionMonitor{ else fluidStack.getFluid } - if (this.watcher != null) this.watcher.add(FluidUtil.createAEFluidStack(this.fluid)) + if (this.watcher != null) + this.watcher.add(FluidUtil.createAEFluidStack(this.fluid)) val host: IPartHost = getHost if (host != null) host.markForUpdate return true diff --git a/src/main/scala/extracells/part/PartGasExport.scala b/src/main/scala/extracells/part/PartGasExport.scala index b586bf757..df22491d2 100644 --- a/src/main/scala/extracells/part/PartGasExport.scala +++ b/src/main/scala/extracells/part/PartGasExport.scala @@ -1,9 +1,9 @@ package extracells.part import java.util - import appeng.api.AEApi import appeng.api.config.Actionable +import appeng.api.networking.ticking.TickRateModulation import appeng.api.storage.data.IAEFluidStack import cpw.mods.fml.common.Optional import extracells.integration.Integration @@ -11,24 +11,22 @@ import extracells.util.GasUtil import mekanism.api.gas.IGasHandler import net.minecraftforge.fluids.{Fluid, FluidStack} -class PartGasExport extends PartFluidExport{ +class PartGasExport extends PartFluidExport { private val isMekanismEnabled = Integration.Mods.MEKANISMGAS.isEnabled - - override def doWork(rate: Int, tickSinceLastCall: Int): Boolean ={ + override def doWork(rate: Int, tickSinceLastCall: Int): TickRateModulation = { if (isMekanismEnabled) work(rate, tickSinceLastCall) else - false + TickRateModulation.IDLE } - @Optional.Method(modid = "MekanismAPI|gas") - protected def work(rate: Int, ticksSinceLastCall: Int): Boolean ={ + protected def work(rate: Int, ticksSinceLastCall: Int): TickRateModulation = { val facingTank: IGasHandler = getFacingGasTank - if (facingTank == null || !isActive) return false - val filter = new util.ArrayList[Fluid] + if (!isActive || facingTank == null) return TickRateModulation.IDLE + val filter = new util.ArrayList[Fluid] filter.add(this.filterFluids(4)) if (this.filterSize >= 1) { @@ -61,23 +59,35 @@ class PartGasExport extends PartFluidExport{ import scala.collection.JavaConversions._ for (fluid <- filter) { if (fluid != null) { - val stack: IAEFluidStack = extractGasFluid(AEApi.instance.storage.createFluidStack(new FluidStack(fluid, rate * ticksSinceLastCall)), Actionable.SIMULATE) + val stack: IAEFluidStack = extractGasFluid( + AEApi.instance.storage + .createFluidStack(new FluidStack(fluid, rate * ticksSinceLastCall)), + Actionable.SIMULATE + ) if (stack != null) { val gasStack = GasUtil.getGasStack(stack.getFluidStack) - if (gasStack != null && facingTank.canReceiveGas(getSide.getOpposite, gasStack.getGas)) { - val filled: Int = facingTank.receiveGas(getSide.getOpposite, gasStack, true) + if ( + gasStack != null && facingTank.canReceiveGas( + getSide.getOpposite, + gasStack.getGas + ) + ) { + val filled: Int = + facingTank.receiveGas(getSide.getOpposite, gasStack, true) if (filled > 0) { - extractGasFluid(AEApi.instance.storage.createFluidStack(new FluidStack(fluid, filled)), Actionable.MODULATE) - return true + extractGasFluid( + AEApi.instance.storage + .createFluidStack(new FluidStack(fluid, filled)), + Actionable.MODULATE + ) + return TickRateModulation.FASTER } } } } } - return false + return TickRateModulation.SLOWER } - - } diff --git a/src/main/scala/extracells/part/PartGasImport.scala b/src/main/scala/extracells/part/PartGasImport.scala index 0c66a0855..73c9f19d5 100644 --- a/src/main/scala/extracells/part/PartGasImport.scala +++ b/src/main/scala/extracells/part/PartGasImport.scala @@ -1,13 +1,13 @@ package extracells.part -import java.util - import appeng.api.config.Actionable import appeng.api.networking.security.MachineSource +import appeng.api.networking.ticking.TickRateModulation import appeng.api.storage.IMEMonitor import appeng.api.storage.data.IAEFluidStack import cpw.mods.fml.common.Optional import cpw.mods.fml.common.Optional.{Interface, Method} +import extracells.Extracells import extracells.integration.Integration import extracells.integration.mekanism.gas.MekanismGas import extracells.util.{FluidUtil, GasUtil} @@ -15,14 +15,23 @@ import mekanism.api.gas.{Gas, GasStack, IGasHandler} import net.minecraftforge.common.util.ForgeDirection import net.minecraftforge.fluids.{Fluid, FluidStack} +import java.util -@Interface(iface = "mekanism.api.gas.IGasHandler", modid = "MekanismAPI|gas", striprefs = true) -class PartGasImport extends PartFluidImport with IGasHandler{ +@Interface( + iface = "mekanism.api.gas.IGasHandler", + modid = "MekanismAPI|gas", + striprefs = true +) +class PartGasImport extends PartFluidImport with IGasHandler { private val isMekanismEnabled = Integration.Mods.MEKANISMGAS.isEnabled - override def doWork(rate: Int, TicksSinceLastCall: Int): Boolean = { - if ((!isMekanismEnabled) || getFacingGasTank == null || !isActive) return false + override def doWork( + rate: Int, + TicksSinceLastCall: Int + ): TickRateModulation = { + if (!isActive || (!isMekanismEnabled) || getFacingGasTank == null) + return TickRateModulation.IDLE var empty: Boolean = true val filter: util.List[Fluid] = new util.ArrayList[Fluid] filter.add(this.filterFluids(4)) @@ -57,11 +66,15 @@ class PartGasImport extends PartFluidImport with IGasHandler{ if (fluid != null) { empty = false if (fillToNetwork(fluid, rate * TicksSinceLastCall)) { - return true + return TickRateModulation.FASTER } } } - empty && fillToNetwork(null, rate * TicksSinceLastCall) + if (empty && fillToNetwork(null, rate * TicksSinceLastCall)) { + TickRateModulation.FASTER + } else { + TickRateModulation.SLOWER + } } @Optional.Method(modid = "MekanismAPI|gas") @@ -82,12 +95,13 @@ class PartGasImport extends PartFluidImport with IGasHandler{ } if (gasType == null) { drained = facingTank.drawGas(side.getOpposite, toDrain, false) - } - else if (facingTank.canDrawGas(side.getOpposite, gasType)){ + } else if (facingTank.canDrawGas(side.getOpposite, gasType)) { drained = facingTank.drawGas(side.getOpposite, toDrain, false) } - if (drained == null || drained.amount <= 0 || drained.getGas == null) return false - val toFill: IAEFluidStack = FluidUtil.createAEFluidStack(GasUtil.getFluidStack(drained)) + if (drained == null || drained.amount <= 0 || drained.getGas == null) + return false + val toFill: IAEFluidStack = + FluidUtil.createAEFluidStack(GasUtil.getFluidStack(drained)) val notInjected: IAEFluidStack = injectGas(toFill, Actionable.MODULATE) if (notInjected != null) { val amount: Int = (toFill.getStackSize - notInjected.getStackSize).toInt @@ -95,32 +109,43 @@ class PartGasImport extends PartFluidImport with IGasHandler{ facingTank.drawGas(side.getOpposite, amount, true) true - } - else { + } else { false } - } - else { + } else { facingTank.drawGas(side.getOpposite, toFill.getFluidStack.amount, true) true } } @Method(modid = "MekanismAPI|gas") - override def receiveGas(side: ForgeDirection, stack: GasStack, doTransfer: Boolean): Int = { - if (stack == null || stack.amount <= 0 || ! canReceiveGas(side, stack.getGas)) + override def receiveGas( + side: ForgeDirection, + stack: GasStack, + doTransfer: Boolean + ): Int = { + if ( + stack == null || stack.amount <= 0 || !canReceiveGas(side, stack.getGas) + ) return 0 - val amount = Math.min(stack.amount, 125 + this.speedState * 125) + val amount = Math.min( + stack.amount, + Extracells.basePartSpeed + this.speedState * Extracells.basePartSpeed + ) val gasStack = GasUtil.createAEFluidStack(stack.getGas, amount) val notInjected = { if (getGridBlock == null) { gasStack - }else{ + } else { val monitor: IMEMonitor[IAEFluidStack] = getGridBlock.getFluidMonitor if (monitor == null) gasStack else - monitor.injectItems(gasStack, if (true) Actionable.MODULATE else Actionable.SIMULATE, new MachineSource(this)) + monitor.injectItems( + gasStack, + if (true) Actionable.MODULATE else Actionable.SIMULATE, + new MachineSource(this) + ) } } if (notInjected == null) @@ -130,13 +155,19 @@ class PartGasImport extends PartFluidImport with IGasHandler{ } @Method(modid = "MekanismAPI|gas") - override def receiveGas(side: ForgeDirection, stack: GasStack): Int = receiveGas(side, stack, true) + override def receiveGas(side: ForgeDirection, stack: GasStack): Int = + receiveGas(side, stack, true) @Method(modid = "MekanismAPI|gas") - override def drawGas(side: ForgeDirection, amount: Int, doTransfer: Boolean): GasStack = null + override def drawGas( + side: ForgeDirection, + amount: Int, + doTransfer: Boolean + ): GasStack = null @Method(modid = "MekanismAPI|gas") - override def drawGas(side: ForgeDirection, amount: Int): GasStack = drawGas(side, amount, true) + override def drawGas(side: ForgeDirection, amount: Int): GasStack = + drawGas(side, amount, true) @Method(modid = "MekanismAPI|gas") override def canDrawGas(side: ForgeDirection, gasType: Gas): Boolean = false @@ -145,10 +176,10 @@ class PartGasImport extends PartFluidImport with IGasHandler{ override def canReceiveGas(side: ForgeDirection, gasType: Gas): Boolean = { val fluid = MekanismGas.getFluidGasMap.get(gasType) var isEmpty = true - for(filter <- filterFluids){ - if(filter != null){ + for (filter <- filterFluids) { + if (filter != null) { isEmpty = false - if(filter == fluid) + if (filter == fluid) return true } } diff --git a/src/main/scala/extracells/part/PartGasInterface.scala b/src/main/scala/extracells/part/PartGasInterface.scala index c81fbe932..ec4d6a232 100644 --- a/src/main/scala/extracells/part/PartGasInterface.scala +++ b/src/main/scala/extracells/part/PartGasInterface.scala @@ -7,15 +7,23 @@ import mekanism.api.gas.GasTank import net.minecraft.client.renderer.RenderBlocks import net.minecraftforge.common.util.ForgeDirection - -class PartGasInterface extends PartECBase with GasInterfaceBase{ +class PartGasInterface extends PartECBase with GasInterfaceBase { var fluidFilter = -1 override def cableConnectionRenderTo(): Int = ??? - override def renderStatic(x: Int, y: Int, z: Int, rh: IPartRenderHelper, renderer: RenderBlocks): Unit = ??? + override def renderStatic( + x: Int, + y: Int, + z: Int, + rh: IPartRenderHelper, + renderer: RenderBlocks + ): Unit = ??? - override def renderInventory(rh: IPartRenderHelper, renderer: RenderBlocks): Unit = ??? + override def renderInventory( + rh: IPartRenderHelper, + renderer: RenderBlocks + ): Unit = ??? override def getBoxes(bch: IPartCollisionHelper): Unit = ??? @@ -24,5 +32,6 @@ class PartGasInterface extends PartECBase with GasInterfaceBase{ override def getFilter(side: ForgeDirection): Int = fluidFilter - override def setFilter(side: ForgeDirection, fluid: Int): Unit = fluidFilter = fluid + override def setFilter(side: ForgeDirection, fluid: Int): Unit = fluidFilter = + fluid } diff --git a/src/main/scala/extracells/part/PartGasLevelEmitter.scala b/src/main/scala/extracells/part/PartGasLevelEmitter.scala index 6609a4d00..e1b79cde8 100644 --- a/src/main/scala/extracells/part/PartGasLevelEmitter.scala +++ b/src/main/scala/extracells/part/PartGasLevelEmitter.scala @@ -1,6 +1,3 @@ package extracells.part - -class PartGasLevelEmitter extends PartFluidLevelEmitter{ - -} +class PartGasLevelEmitter extends PartFluidLevelEmitter {} diff --git a/src/main/scala/extracells/part/PartGasStorage.scala b/src/main/scala/extracells/part/PartGasStorage.scala index 45afedf48..bec0de7e4 100644 --- a/src/main/scala/extracells/part/PartGasStorage.scala +++ b/src/main/scala/extracells/part/PartGasStorage.scala @@ -2,7 +2,6 @@ package extracells.part import extracells.inventory.HandlerPartStorageGas - -class PartGasStorage extends PartFluidStorage{ +class PartGasStorage extends PartFluidStorage { handler = new HandlerPartStorageGas(this) } diff --git a/src/main/scala/extracells/part/PartGasStorageMonitor.scala b/src/main/scala/extracells/part/PartGasStorageMonitor.scala index a58820175..152a937ec 100644 --- a/src/main/scala/extracells/part/PartGasStorageMonitor.scala +++ b/src/main/scala/extracells/part/PartGasStorageMonitor.scala @@ -8,12 +8,11 @@ import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.util.{ChatComponentTranslation, Vec3} - -class PartGasStorageMonitor extends PartFluidStorageMonitor{ +class PartGasStorageMonitor extends PartFluidStorageMonitor { val isMekEnabled = Integration.Mods.MEKANISMGAS.isEnabled override def onActivate(player: EntityPlayer, pos: Vec3): Boolean = { - if(isMekEnabled) + if (isMekEnabled) onActivateGas(player, pos) else false @@ -27,25 +26,47 @@ class PartGasStorageMonitor extends PartFluidStorageMonitor{ if (s == null) { if (this.locked) return false if (this.fluid == null) return true - if (this.watcher != null) this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) + if (this.watcher != null) + this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) this.fluid = null this.amount = 0L val host: IPartHost = getHost if (host != null) host.markForUpdate return true } - if (WrenchUtil.canWrench(s, player, this.tile.xCoord, this.tile.yCoord, this.tile.zCoord)) { + if ( + WrenchUtil.canWrench( + s, + player, + this.tile.xCoord, + this.tile.yCoord, + this.tile.zCoord + ) + ) { this.locked = !this.locked - WrenchUtil.wrenchUsed(s, player, this.tile.xCoord, this.tile.zCoord, this.tile.yCoord) + WrenchUtil.wrenchUsed( + s, + player, + this.tile.xCoord, + this.tile.zCoord, + this.tile.yCoord + ) val host: IPartHost = getHost if (host != null) host.markForUpdate - if (this.locked) player.addChatMessage(new ChatComponentTranslation("chat.appliedenergistics2.isNowLocked")) - else player.addChatMessage(new ChatComponentTranslation("chat.appliedenergistics2.isNowUnlocked")) + if (this.locked) + player.addChatMessage( + new ChatComponentTranslation("chat.appliedenergistics2.isNowLocked") + ) + else + player.addChatMessage( + new ChatComponentTranslation("chat.appliedenergistics2.isNowUnlocked") + ) return true } if (this.locked) return false if (GasUtil.isFilled(s)) { - if (this.fluid != null && this.watcher != null) this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) + if (this.fluid != null && this.watcher != null) + this.watcher.remove(FluidUtil.createAEFluidStack(this.fluid)) val gas = GasUtil.getGasFromContainer(s) val fluidStack = GasUtil.getFluidStack(gas) this.fluid = { @@ -54,7 +75,8 @@ class PartGasStorageMonitor extends PartFluidStorageMonitor{ else fluidStack.getFluid } - if (this.watcher != null) this.watcher.add(FluidUtil.createAEFluidStack(this.fluid)) + if (this.watcher != null) + this.watcher.add(FluidUtil.createAEFluidStack(this.fluid)) val host: IPartHost = getHost if (host != null) host.markForUpdate return true diff --git a/src/main/scala/extracells/part/PartGasTerminal.scala b/src/main/scala/extracells/part/PartGasTerminal.scala index 86be129d7..92ce9f556 100644 --- a/src/main/scala/extracells/part/PartGasTerminal.scala +++ b/src/main/scala/extracells/part/PartGasTerminal.scala @@ -14,27 +14,31 @@ import net.minecraft.item.ItemStack import net.minecraftforge.fluids.FluidStack import org.apache.commons.lang3.tuple.MutablePair - -class PartGasTerminal extends PartFluidTerminal{ +class PartGasTerminal extends PartFluidTerminal { val mekLoaded = Mods.MEKANISMGAS.isEnabled var doNextFill = false - override protected def isItemValidForInputSlot(i: Int, itemStack: ItemStack): Boolean = { + override protected def isItemValidForInputSlot( + i: Int, + itemStack: ItemStack + ): Boolean = { GasUtil.isGasContainer(itemStack) } override def doWork { - if(mekLoaded) + if (mekLoaded) doWorkGas } @Optional.Method(modid = "MekanismAPI|gas") def doWorkGas { val secondSlot: ItemStack = this.inventory.getStackInSlot(1) - if (secondSlot != null && secondSlot.stackSize >= secondSlot.getMaxStackSize) return + if ( + secondSlot != null && secondSlot.stackSize >= secondSlot.getMaxStackSize + ) return var container: ItemStack = this.inventory.getStackInSlot(0) - if(container == null) + if (container == null) doNextFill = false if (!GasUtil.isGasContainer(container)) return container = container.copy @@ -45,46 +49,96 @@ class PartGasTerminal extends PartFluidTerminal{ if (monitor == null) return val gasStack = GasUtil.getGasFromContainer(container); - if (GasUtil.isEmpty(container) || (gasStack.amount < GasUtil.getCapacity(container) && GasUtil.getFluidStack(gasStack).getFluid == this.currentFluid && doNextFill)) { + if ( + GasUtil.isEmpty(container) || (gasStack.amount < GasUtil.getCapacity( + container + ) && GasUtil + .getFluidStack(gasStack) + .getFluid == this.currentFluid && doNextFill) + ) { if (this.currentFluid == null) return val capacity: Int = GasUtil.getCapacity(container) - val result: IAEFluidStack = monitor.extractItems(FluidUtil.createAEFluidStack(this.currentFluid, capacity), Actionable.SIMULATE, this.machineSource) + val result: IAEFluidStack = monitor.extractItems( + FluidUtil.createAEFluidStack(this.currentFluid, capacity), + Actionable.SIMULATE, + this.machineSource + ) var proposedAmount: Int = 0 if (result == null) proposedAmount = 0 else if (gasStack == null) - proposedAmount = Math.min(capacity, result.getStackSize).toInt - else - proposedAmount = Math.min(capacity - gasStack.amount, result.getStackSize).toInt + proposedAmount = Math.min(capacity, result.getStackSize).toInt + else + proposedAmount = + Math.min(capacity - gasStack.amount, result.getStackSize).toInt - val filledContainer: MutablePair[Integer, ItemStack] = GasUtil.fillStack(container, GasUtil.getGasStack(new FluidStack(this.currentFluid, proposedAmount))) + val filledContainer: MutablePair[Integer, ItemStack] = GasUtil.fillStack( + container, + GasUtil.getGasStack(new FluidStack(this.currentFluid, proposedAmount)) + ) val gasStack2 = GasUtil.getGasFromContainer(filledContainer.getRight) - if(gasStack2 == null) { + if (gasStack2 == null) { doNextFill = false - }else if (container.stackSize == 1 && gasStack2.amount < GasUtil.getCapacity(filledContainer.getRight)) { + } else if ( + container.stackSize == 1 && gasStack2.amount < GasUtil.getCapacity( + filledContainer.getRight + ) + ) { this.inventory.setInventorySlotContents(0, filledContainer.getRight) - monitor.extractItems(FluidUtil.createAEFluidStack(this.currentFluid, filledContainer.getLeft.toLong), Actionable.MODULATE, this.machineSource) + monitor.extractItems( + FluidUtil.createAEFluidStack( + this.currentFluid, + filledContainer.getLeft.toLong + ), + Actionable.MODULATE, + this.machineSource + ) doNextFill = true - }else if (fillSecondSlot(filledContainer.getRight)) { - monitor.extractItems(FluidUtil.createAEFluidStack(this.currentFluid, filledContainer.getLeft.toLong), Actionable.MODULATE, this.machineSource) + } else if (fillSecondSlot(filledContainer.getRight, true)) { + monitor.extractItems( + FluidUtil.createAEFluidStack( + this.currentFluid, + filledContainer.getLeft.toLong + ), + Actionable.MODULATE, + this.machineSource + ) decreaseFirstSlot doNextFill = false } - } - else { + } else { val containerGas = GasUtil.getGasFromContainer(container) - val drainedContainer: MutablePair[Integer, ItemStack] = GasUtil.drainStack(container.copy(), containerGas) + val drainedContainer: MutablePair[Integer, ItemStack] = + GasUtil.drainStack(container.copy(), containerGas) val gasStack = containerGas.copy() gasStack.amount = drainedContainer.getLeft - val notInjected: IAEFluidStack = monitor.injectItems(GasUtil.createAEFluidStack(gasStack), Actionable.SIMULATE, this.machineSource) + val notInjected: IAEFluidStack = monitor.injectItems( + GasUtil.createAEFluidStack(gasStack), + Actionable.SIMULATE, + this.machineSource + ) if (notInjected != null) return val emptyContainer: ItemStack = drainedContainer.getRight - if (emptyContainer != null && GasUtil.getGasFromContainer(emptyContainer) != null && emptyContainer.stackSize == 1) { - monitor.injectItems(GasUtil.createAEFluidStack(gasStack), Actionable.MODULATE, this.machineSource) + if ( + emptyContainer != null && GasUtil.getGasFromContainer( + emptyContainer + ) != null && emptyContainer.stackSize == 1 + ) { + monitor.injectItems( + GasUtil.createAEFluidStack(gasStack), + Actionable.MODULATE, + this.machineSource + ) this.inventory.setInventorySlotContents(0, emptyContainer) - }else if (emptyContainer == null || fillSecondSlot(emptyContainer)) { - monitor.injectItems(GasUtil.createAEFluidStack(containerGas), Actionable.MODULATE, this.machineSource) + } else if ( + emptyContainer == null || fillSecondSlot(emptyContainer, true) + ) { + monitor.injectItems( + GasUtil.createAEFluidStack(containerGas), + Actionable.MODULATE, + this.machineSource + ) decreaseFirstSlot } } diff --git a/src/main/scala/extracells/part/PartOreDictExporter.java b/src/main/scala/extracells/part/PartOreDictExporter.java index bf5489edb..e65d6e263 100644 --- a/src/main/scala/extracells/part/PartOreDictExporter.java +++ b/src/main/scala/extracells/part/PartOreDictExporter.java @@ -1,5 +1,29 @@ package extracells.part; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import java.util.stream.IntStream; + +import net.minecraft.client.renderer.RenderBlocks; +import net.minecraft.client.renderer.Tessellator; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.ISidedInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; +import net.minecraft.util.StatCollector; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.oredict.OreDictionary; + +import org.apache.commons.lang3.StringUtils; + import appeng.api.config.Actionable; import appeng.api.networking.IGrid; import appeng.api.networking.IGridNode; @@ -13,354 +37,428 @@ import appeng.api.networking.ticking.TickingRequest; import appeng.api.parts.IPartCollisionHelper; import appeng.api.parts.IPartRenderHelper; -import appeng.api.parts.PartItemStack; +import appeng.api.storage.IMEMonitor; import appeng.api.storage.data.IAEItemStack; +import appeng.api.storage.data.IItemList; import appeng.api.util.AEColor; +import appeng.util.item.AEItemStack; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import extracells.container.ContainerOreDictExport; import extracells.gui.GuiOreDictExport; -import extracells.registries.ItemEnum; -import extracells.registries.PartEnum; import extracells.render.TextureManager; import extracells.util.ItemUtils; -import net.minecraft.client.renderer.RenderBlocks; -import net.minecraft.client.renderer.Tessellator; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.IIcon; -import net.minecraft.util.StatCollector; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.oredict.OreDictionary; - -import java.util.List; public class PartOreDictExporter extends PartECBase implements IGridTickable { - public String filter = ""; - - @Override - public int cableConnectionRenderTo() { - return 5; - } - - private boolean checkItem(IAEItemStack s) { - if (s == null || this.filter.equals("")) - return false; - int[] ids = OreDictionary.getOreIDs(s.getItemStack()); - for (int id : ids) { - String name = OreDictionary.getOreName(id); - if (this.filter.startsWith("*") && this.filter.endsWith("*")) { - String filter2 = this.filter.replace("*", ""); - if (filter2.equals("")) - return true; - if (name.contains(filter2)) - return true; - continue; - } else if (this.filter.startsWith("*")) { - String filter2 = this.filter.replace("*", ""); - if (name.endsWith(filter2)) - return true; - continue; - } else if (this.filter.endsWith("*")) { - String filter2 = this.filter.replace("*", ""); - if (name.startsWith(filter2)) - return true; - continue; - } else { - if (name.equals(this.filter)) - return true; - continue; - } - } - return false; - } - - public boolean doWork(int rate, int TicksSinceLastCall) { - int amount = rate * TicksSinceLastCall >= 64 ? 64 : rate - * TicksSinceLastCall; - IStorageGrid storage = getStorageGrid(); - IAEItemStack stack = null; - for (IAEItemStack s : storage.getItemInventory().getStorageList()) { - if (checkItem(s.copy())) { - stack = s.copy(); - break; - } - } - if (stack == null) - return false; - stack.setStackSize(amount); - stack = storage.getItemInventory().extractItems(stack.copy(), - Actionable.SIMULATE, new MachineSource(this)); - if (stack == null) - return false; - IAEItemStack exported = exportStack(stack.copy()); - if (exported == null) - return false; - storage.getItemInventory().extractItems(exported, Actionable.MODULATE, - new MachineSource(this)); - return true; - } - - public IAEItemStack exportStack(IAEItemStack stack0) { - if (this.tile == null || !this.tile.hasWorldObj() || stack0 == null) - return null; - ForgeDirection dir = getSide(); - TileEntity tile = this.tile.getWorldObj().getTileEntity( - this.tile.xCoord + dir.offsetX, this.tile.yCoord + dir.offsetY, - this.tile.zCoord + dir.offsetZ); - if (tile == null) - return null; - IAEItemStack stack = stack0.copy(); - if (tile instanceof IInventory) { - if (tile instanceof ISidedInventory) { - ISidedInventory inv = (ISidedInventory) tile; - for (int i : inv.getAccessibleSlotsFromSide(dir.getOpposite() - .ordinal())) { - if (inv.canInsertItem(i, stack.getItemStack(), dir - .getOpposite().ordinal())) { - if (inv.getStackInSlot(i) == null) { - inv.setInventorySlotContents(i, - stack.getItemStack()); - return stack0; - } else if (ItemUtils.areItemEqualsIgnoreStackSize( - inv.getStackInSlot(i), stack.getItemStack())) { - int max = inv.getInventoryStackLimit(); - int current = inv.getStackInSlot(i).stackSize; - int outStack = (int) stack.getStackSize(); - if (max == current) - continue; - if (current + outStack <= max) { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = s.stackSize + outStack; - inv.setInventorySlotContents(i, s); - return stack0; - } else { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = max; - inv.setInventorySlotContents(i, s); - stack.setStackSize(max - current); - return stack; - } - } - } - } - } else { - IInventory inv = (IInventory) tile; - for (int i = 0; i < inv.getSizeInventory(); i++) { - if (inv.isItemValidForSlot(i, stack.getItemStack())) { - if (inv.getStackInSlot(i) == null) { - inv.setInventorySlotContents(i, - stack.getItemStack()); - return stack0; - } else if (ItemUtils.areItemEqualsIgnoreStackSize( - inv.getStackInSlot(i), stack.getItemStack())) { - int max = inv.getInventoryStackLimit(); - int current = inv.getStackInSlot(i).stackSize; - int outStack = (int) stack.getStackSize(); - if (max == current) - continue; - if (current + outStack <= max) { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = s.stackSize + outStack; - inv.setInventorySlotContents(i, s); - return stack0; - } else { - ItemStack s = inv.getStackInSlot(i).copy(); - s.stackSize = max; - inv.setInventorySlotContents(i, s); - stack.setStackSize(max - current); - return stack; - } - } - } - } - } - } - return null; - } - - @Override - public void getBoxes(IPartCollisionHelper bch) { - bch.addBox(6, 6, 12, 10, 10, 13); - bch.addBox(4, 4, 13, 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 Object getClientGuiElement(EntityPlayer player) { - return new GuiOreDictExport(player, this); - } - - @Override - public ItemStack getItemStack(PartItemStack type) { - ItemStack is = new ItemStack(ItemEnum.PARTITEM.getItem(), 1, - PartEnum.getPartID(this)); - if (type != PartItemStack.Break) { - NBTTagCompound tag = new NBTTagCompound(); - tag.setString("filter", this.filter); - is.setTagCompound(tag); - } - return is; - } - - @Override - public double getPowerUsage() { - return 10.0D; - } - - @Override - public Object getServerGuiElement(EntityPlayer player) { - return new ContainerOreDictExport(player, this); - } - - private IStorageGrid getStorageGrid() { - IGridNode node = getGridNode(); - if (node == null) - return null; - IGrid grid = node.getGrid(); - if (grid == null) - return null; - return grid.getCache(IStorageGrid.class); - } - - @Override - public final TickingRequest getTickingRequest(IGridNode node) { - return new TickingRequest(1, 20, false, false); - } - - @Override - public List getWailaBodey(NBTTagCompound data, List list) { - super.getWailaBodey(data, list); - if (data.hasKey("name")) - list.add(StatCollector - .translateToLocal("extracells.tooltip.oredict") - + ": " - + data.getString("name")); - else - list.add(StatCollector - .translateToLocal("extracells.tooltip.oredict") + ":"); - return list; - } - - @Override - public NBTTagCompound getWailaTag(NBTTagCompound tag) { - super.getWailaTag(tag); - tag.setString("name", this.filter); - return tag; - } - - @MENetworkEventSubscribe - public void powerChange(MENetworkPowerStatusChange event) { - IGridNode node = getGridNode(); - if (node != null) { - boolean isNowActive = node.isActive(); - if (isNowActive != isActive()) { - setActive(isNowActive); - onNeighborChanged(); - getHost().markForUpdate(); - } - } - } - - @Override - public void readFromNBT(NBTTagCompound data) { - super.readFromNBT(data); - if (data.hasKey("filter")) - this.filter = data.getString("filter"); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); - rh.setBounds(6, 6, 12, 10, 10, 13); - rh.renderInventoryBox(renderer); - - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderInventoryBox(renderer); - - rh.setBounds(5, 5, 14, 11, 11, 15); - rh.renderInventoryBox(renderer); - - IIcon side = TextureManager.EXPORT_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.EXPORT_FRONT.getTexture(), side, side); - rh.setBounds(6, 6, 15, 10, 10, 16); - rh.renderInventoryBox(renderer); - - rh.setInvColor(AEColor.Black.mediumVariant); - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderInventoryFace(TextureManager.EXPORT_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(6, 6, 11, 10, 10, 12); - renderInventoryBusLights(rh, renderer); - } - - @SideOnly(Side.CLIENT) - @Override - public void renderStatic(int x, int y, int z, IPartRenderHelper rh, - RenderBlocks renderer) { - Tessellator ts = Tessellator.instance; - rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); - rh.setBounds(6, 6, 12, 10, 10, 13); - rh.renderBlock(x, y, z, renderer); - - rh.setBounds(4, 4, 13, 12, 12, 14); - rh.renderBlock(x, y, z, renderer); - - rh.setBounds(5, 5, 14, 11, 11, 15); - rh.renderBlock(x, y, z, renderer); - - IIcon side = TextureManager.EXPORT_SIDE.getTexture(); - rh.setTexture(side, side, side, - TextureManager.EXPORT_FRONT.getTextures()[0], side, side); - rh.setBounds(6, 6, 15, 10, 10, 16); - rh.renderBlock(x, y, z, renderer); - - ts.setColorOpaque_I(AEColor.Black.mediumVariant); - if (isActive()) - ts.setBrightness(15 << 20 | 15 << 4); - rh.renderFace(x, y, z, TextureManager.EXPORT_FRONT.getTextures()[1], - ForgeDirection.SOUTH, renderer); - - rh.setBounds(6, 6, 11, 10, 10, 12); - renderStaticBusLights(x, y, z, rh, renderer); - } - - @Override - public final TickRateModulation tickingRequest(IGridNode node, - int TicksSinceLastCall) { - if (isActive()) - return doWork(10, TicksSinceLastCall) ? TickRateModulation.FASTER - : TickRateModulation.SLOWER; - return TickRateModulation.SLOWER; - } - - @MENetworkEventSubscribe - public void updateChannels(MENetworkChannelsChanged channel) { - IGridNode node = getGridNode(); - if (node != null) { - boolean isNowActive = node.isActive(); - if (isNowActive != isActive()) { - setActive(isNowActive); - onNeighborChanged(); - getHost().markForUpdate(); - } - } - } - - @Override - public void writeToNBT(NBTTagCompound data) { - super.writeToNBT(data); - data.setString("filter", this.filter); - } + private String filter = ""; + + public OreListMatcher filterPredicate = null; + + @Override + public int cableConnectionRenderTo() { + return 5; + } + + public String getFilter() { + return this.filter; + } + + public void setFilter(String filter) { + String temp = this.filter; + this.filter = filter; + try { + if (!Objects.equals(temp, this.filter)) { + updateFilter(); + saveData(); + } + } catch (PatternSyntaxException e) { + this.filter = temp; + } + } + + public void setFilter(String filter, boolean sendToServer) { + String temp = this.filter; + this.filter = filter; + try { + if (!Objects.equals(temp, this.filter)) { + updateFilter(); + } + if (sendToServer) { + saveData(); + } + } catch (PatternSyntaxException e) { + this.filter = temp; + } + } + + private static class OreListMatcher implements Predicate { + + HashSet ores = new HashSet<>(); + + public OreListMatcher(ArrayList input) { + for (ItemStack is : input) ores.add(AEItemStack.create(is)); + } + + public boolean test(AEItemStack t) { + return ores.contains(t); + } + + public HashSet getOres() { + return this.ores; + } + } + + public HashSet getOres() { + if (this.filterPredicate != null) { + return this.filterPredicate.getOres(); + } else { + return new HashSet(); + } + } + + /** + * Call when the filter string has changed to parse and recompile the filter. + */ + public void updateFilter() { + Predicate matcher = null; + if (filter.contains("\\") || filter.contains("^") + || filter.contains("$") + || filter.contains("+") + || filter.contains("(") + || filter.contains(")") + || filter.contains("[") + || filter.contains("]")) { + final Predicate test = Pattern.compile(filter).asPredicate(); + matcher = (is) -> is != null + && IntStream.of(OreDictionary.getOreIDs(is)).mapToObj(OreDictionary::getOreName).anyMatch(test); + } else if (!this.filter.trim().isEmpty()) { + String[] filters = this.filter.split("[&|]"); + String lastFilter = null; + + for (String filter : filters) { + filter = filter.trim(); + boolean negated = filter.startsWith("!"); + if (negated) filter = filter.substring(1); + + Predicate test = filterToItemStackPredicate(filter); + + if (negated) test = test.negate(); + + if (matcher == null) { + matcher = test; + lastFilter = filter; + } else { + int endLast = this.filter.indexOf(lastFilter) + lastFilter.length(); + int startThis = this.filter.indexOf(filter); + boolean or = this.filter.substring(endLast, startThis).contains("|"); + + if (or) { + matcher = matcher.or(test); + } else { + matcher = matcher.and(test); + } + } + } + } + + // Mod name and path evaluation are disabled in this version + if (matcher != null && !this.filter.contains("@") && !this.filter.contains("~")) { + ArrayList filtered = new ArrayList<>(); + for (String name : OreDictionary.getOreNames()) + for (ItemStack s : OreDictionary.getOres(name)) if (matcher.test(s)) filtered.add(s); + filterPredicate = new OreListMatcher(filtered); + } else filterPredicate = null; + } + + /** + * Given a filter string, returns a predicate that matches a given ItemStack + * + * @param filter Filter string. + * @return Predicate for filter string. + */ + private Predicate filterToItemStackPredicate(String filter) { + final Predicate test = filterToPredicate(filter); + return (is) -> is != null + && IntStream.of(OreDictionary.getOreIDs(is)).mapToObj(OreDictionary::getOreName).anyMatch(test); + } + + /** + * Given a filter string, returns a Predicate that matches a string. + * + * @param filter Filter string + * @return Predicate for filter string. + */ + private Predicate filterToPredicate(String filter) { + int numStars = StringUtils.countMatches(filter, "*"); + if (numStars == filter.length()) { + return (str) -> true; + } else if (filter.length() > 2 && filter.startsWith("*") && filter.endsWith("*") && numStars == 2) { + final String pattern = filter.substring(1, filter.length() - 1); + return (str) -> str.contains(pattern); + } else if (filter.length() >= 2 && filter.startsWith("*") && numStars == 1) { + final String pattern = filter.substring(1); + return (str) -> str.endsWith(pattern); + } else if (filter.length() >= 2 && filter.endsWith("*") && numStars == 1) { + final String pattern = filter.substring(0, filter.length() - 1); + return (str) -> str.startsWith(pattern); + } else if (numStars == 0) { + return (str) -> str.equals(filter); + } else { + String filterRegexFragment = filter.replace("*", ".*"); + String regexPattern = "^" + filterRegexFragment + "$"; + final Pattern pattern = Pattern.compile(regexPattern); + return pattern.asPredicate(); + } + } + + public boolean doWork(int rate, int ticksSinceLastCall) { + int amount = Math.min(rate * ticksSinceLastCall, 64); + IStorageGrid storage = getStorageGrid(); + assert storage != null; + IMEMonitor inv = storage.getItemInventory(); + MachineSource src = new MachineSource(this); + + if (this.filterPredicate != null) { + IItemList items = inv.getStorageList(); + for (IAEItemStack stack : items) { + if (stack == null || !this.filterPredicate.test((AEItemStack) stack)) continue; + + IAEItemStack toExtract = stack.copy(); + toExtract.setStackSize(amount); + + IAEItemStack extracted = inv.extractItems(toExtract, Actionable.SIMULATE, src); + if (extracted != null) { + IAEItemStack exported = exportStack(extracted.copy()); + if (exported != null) { + inv.extractItems(exported, Actionable.MODULATE, src); + return true; + } + } + } + } + return false; + } + + public IAEItemStack exportStack(IAEItemStack stack0) { + if (this.tile == null || !this.tile.hasWorldObj() || stack0 == null) return null; + ForgeDirection dir = getSide(); + TileEntity tile = this.tile.getWorldObj().getTileEntity( + this.tile.xCoord + dir.offsetX, + this.tile.yCoord + dir.offsetY, + this.tile.zCoord + dir.offsetZ); + if (tile == null) return null; + IAEItemStack stack = stack0.copy(); + if (tile instanceof IInventory) { + if (tile instanceof ISidedInventory) { + ISidedInventory inv = (ISidedInventory) tile; + for (int i : inv.getAccessibleSlotsFromSide(dir.getOpposite().ordinal())) { + if (inv.canInsertItem(i, stack.getItemStack(), dir.getOpposite().ordinal())) { + if (inv.getStackInSlot(i) == null) { + inv.setInventorySlotContents(i, stack.getItemStack()); + return stack0; + } else + if (ItemUtils.areItemEqualsIgnoreStackSize(inv.getStackInSlot(i), stack.getItemStack())) { + int max = inv.getInventoryStackLimit(); + int current = inv.getStackInSlot(i).stackSize; + int outStack = (int) stack.getStackSize(); + if (max == current) continue; + ItemStack s = inv.getStackInSlot(i).copy(); + if (current + outStack <= max) { + s.stackSize = s.stackSize + outStack; + inv.setInventorySlotContents(i, s); + return stack0; + } else { + s.stackSize = max; + inv.setInventorySlotContents(i, s); + stack.setStackSize(max - current); + return stack; + } + } + } + } + } else { + IInventory inv = (IInventory) tile; + for (int i = 0; i < inv.getSizeInventory(); i++) { + if (inv.isItemValidForSlot(i, stack.getItemStack())) { + if (inv.getStackInSlot(i) == null) { + inv.setInventorySlotContents(i, stack.getItemStack()); + return stack0; + } else + if (ItemUtils.areItemEqualsIgnoreStackSize(inv.getStackInSlot(i), stack.getItemStack())) { + int max = inv.getInventoryStackLimit(); + int current = inv.getStackInSlot(i).stackSize; + int outStack = (int) stack.getStackSize(); + if (max == current) continue; + ItemStack s = inv.getStackInSlot(i).copy(); + if (current + outStack <= max) { + s.stackSize = s.stackSize + outStack; + inv.setInventorySlotContents(i, s); + return stack0; + } else { + s.stackSize = max; + inv.setInventorySlotContents(i, s); + stack.setStackSize(max - current); + return stack; + } + } + } + } + } + } + return null; + } + + @Override + public void getBoxes(IPartCollisionHelper bch) { + bch.addBox(6, 6, 12, 10, 10, 13); + bch.addBox(4, 4, 13, 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 Object getClientGuiElement(EntityPlayer player) { + return new GuiOreDictExport(player, this); + } + + @Override + public double getPowerUsage() { + return 10.0D; + } + + @Override + public Object getServerGuiElement(EntityPlayer player) { + return new ContainerOreDictExport(player, this); + } + + private IStorageGrid getStorageGrid() { + IGridNode node = getGridNode(); + if (node == null) return null; + IGrid grid = node.getGrid(); + if (grid == null) return null; + return grid.getCache(IStorageGrid.class); + } + + @Override + public final TickingRequest getTickingRequest(IGridNode node) { + return new TickingRequest(5, 60, false, false); + } + + @Override + public List getWailaBodey(NBTTagCompound data, List list) { + super.getWailaBodey(data, list); + if (data.hasKey("name")) + list.add(StatCollector.translateToLocal("extracells.tooltip.oredict") + ": " + data.getString("name")); + else list.add(StatCollector.translateToLocal("extracells.tooltip.oredict") + ":"); + return list; + } + + @Override + public NBTTagCompound getWailaTag(NBTTagCompound tag) { + super.getWailaTag(tag); + tag.setString("name", this.filter); + return tag; + } + + @MENetworkEventSubscribe + public void powerChange(MENetworkPowerStatusChange event) { + IGridNode node = getGridNode(); + if (node != null) { + boolean isNowActive = node.isActive(); + if (isNowActive != isActive()) { + setActive(isNowActive); + onNeighborChanged(); + getHost().markForUpdate(); + } + } + } + + @Override + public void readFromNBT(NBTTagCompound data) { + super.readFromNBT(data); + if (data.hasKey("filter")) this.setFilter(data.getString("filter")); + // this.filter = ; + updateFilter(); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderInventory(IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); + rh.setBounds(6, 6, 12, 10, 10, 13); + rh.renderInventoryBox(renderer); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderInventoryBox(renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderInventoryBox(renderer); + + IIcon side = TextureManager.EXPORT_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.EXPORT_FRONT.getTexture(), side, side); + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderInventoryBox(renderer); + + rh.setInvColor(AEColor.Black.mediumVariant); + ts.setBrightness(15 << 20 | 15 << 4); + rh.renderInventoryFace(TextureManager.EXPORT_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + + rh.setBounds(6, 6, 11, 10, 10, 12); + renderInventoryBusLights(rh, renderer); + } + + @SideOnly(Side.CLIENT) + @Override + public void renderStatic(int x, int y, int z, IPartRenderHelper rh, RenderBlocks renderer) { + Tessellator ts = Tessellator.instance; + rh.setTexture(TextureManager.EXPORT_SIDE.getTexture()); + rh.setBounds(6, 6, 12, 10, 10, 13); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(4, 4, 13, 12, 12, 14); + rh.renderBlock(x, y, z, renderer); + + rh.setBounds(5, 5, 14, 11, 11, 15); + rh.renderBlock(x, y, z, renderer); + + IIcon side = TextureManager.EXPORT_SIDE.getTexture(); + rh.setTexture(side, side, side, TextureManager.EXPORT_FRONT.getTextures()[0], side, side); + rh.setBounds(6, 6, 15, 10, 10, 16); + rh.renderBlock(x, y, z, renderer); + + ts.setColorOpaque_I(AEColor.Black.mediumVariant); + if (isActive()) ts.setBrightness(15 << 20 | 15 << 4); + rh.renderFace(x, y, z, TextureManager.EXPORT_FRONT.getTextures()[1], ForgeDirection.SOUTH, renderer); + + rh.setBounds(6, 6, 11, 10, 10, 12); + renderStaticBusLights(x, y, z, rh, renderer); + } + + @Override + public final TickRateModulation tickingRequest(IGridNode node, int TicksSinceLastCall) { + if (isActive()) return doWork(10, TicksSinceLastCall) ? TickRateModulation.FASTER : TickRateModulation.SLOWER; + return TickRateModulation.SLOWER; + } + + @MENetworkEventSubscribe + public void updateChannels(MENetworkChannelsChanged channel) { + IGridNode node = getGridNode(); + if (node != null) { + boolean isNowActive = node.isActive(); + if (isNowActive != isActive()) { + setActive(isNowActive); + onNeighborChanged(); + getHost().markForUpdate(); + } + } + } + + @Override + public void writeToNBT(NBTTagCompound data) { + super.writeToNBT(data); + data.setString("filter", this.filter); + } } diff --git a/src/main/scala/extracells/proxy/ClientProxy.java b/src/main/scala/extracells/proxy/ClientProxy.java index 3b89b9fff..ce170822c 100644 --- a/src/main/scala/extracells/proxy/ClientProxy.java +++ b/src/main/scala/extracells/proxy/ClientProxy.java @@ -1,5 +1,11 @@ package extracells.proxy; +import net.minecraft.client.renderer.texture.TextureMap; +import net.minecraft.item.Item; +import net.minecraftforge.client.MinecraftForgeClient; +import net.minecraftforge.client.event.TextureStitchEvent; +import net.minecraftforge.common.MinecraftForge; + import cpw.mods.fml.client.registry.ClientRegistry; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import extracells.registries.BlockEnum; @@ -12,50 +18,45 @@ import extracells.render.item.ItemRendererWalrus; import extracells.render.tileentity.TileEntityRendererWalrus; import extracells.tileentity.TileEntityWalrus; -import net.minecraft.client.renderer.texture.TextureMap; -import net.minecraft.item.Item; -import net.minecraftforge.client.MinecraftForgeClient; -import net.minecraftforge.client.event.TextureStitchEvent; -import net.minecraftforge.common.MinecraftForge; @SuppressWarnings("unused") public class ClientProxy extends CommonProxy { - public ClientProxy() { - super(); - MinecraftForge.EVENT_BUS.register(this); - } - - @Override - public void registerRenderers() { - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(BlockEnum.CERTUSTANK.getBlock()), - new ItemRendererCertusTank()); - MinecraftForgeClient.registerItemRenderer(ItemEnum.FLUIDPATTERN.getItem(), - new ItemRendererFluidPattern()); - MinecraftForgeClient.registerItemRenderer(Item.getItemFromBlock(BlockEnum.WALRUS.getBlock()), - new ItemRendererWalrus()); - MinecraftForgeClient.registerItemRenderer(ItemEnum.FLUIDITEM.getItem(), new ItemRendererFluid()); - - ClientRegistry.bindTileEntitySpecialRenderer(TileEntityWalrus.class, new TileEntityRendererWalrus()); - - RendererHardMEDrive.registerRenderer(); - } - - @SubscribeEvent - public void registerTextures(TextureStitchEvent.Pre textureStitchEvent) { - TextureMap map = textureStitchEvent.map; - for (TextureManager currentTexture : TextureManager.values()) { - currentTexture.registerTexture(map); - } - } - - @Override - public boolean isClient(){ - return true; - } - - @Override - public boolean isServer(){ - return false; - } + public ClientProxy() { + super(); + MinecraftForge.EVENT_BUS.register(this); + } + + @Override + public void registerRenderers() { + MinecraftForgeClient.registerItemRenderer( + Item.getItemFromBlock(BlockEnum.CERTUSTANK.getBlock()), + new ItemRendererCertusTank()); + MinecraftForgeClient.registerItemRenderer(ItemEnum.FLUIDPATTERN.getItem(), new ItemRendererFluidPattern()); + MinecraftForgeClient + .registerItemRenderer(Item.getItemFromBlock(BlockEnum.WALRUS.getBlock()), new ItemRendererWalrus()); + MinecraftForgeClient.registerItemRenderer(ItemEnum.FLUIDITEM.getItem(), new ItemRendererFluid()); + + ClientRegistry.bindTileEntitySpecialRenderer(TileEntityWalrus.class, new TileEntityRendererWalrus()); + + RendererHardMEDrive.registerRenderer(); + } + + @SubscribeEvent + public void registerTextures(TextureStitchEvent.Pre textureStitchEvent) { + TextureMap map = textureStitchEvent.map; + for (TextureManager currentTexture : TextureManager.values()) { + currentTexture.registerTexture(map); + } + } + + @Override + public boolean isClient() { + return true; + } + + @Override + public boolean isServer() { + return false; + } } diff --git a/src/main/scala/extracells/proxy/CommonProxy.java b/src/main/scala/extracells/proxy/CommonProxy.java index 9853f82d3..46d32403c 100644 --- a/src/main/scala/extracells/proxy/CommonProxy.java +++ b/src/main/scala/extracells/proxy/CommonProxy.java @@ -1,5 +1,9 @@ package extracells.proxy; +import java.io.*; + +import net.minecraftforge.fluids.FluidRegistry; + import appeng.api.AEApi; import appeng.api.IAppEngApi; import appeng.api.recipes.IRecipeHandler; @@ -10,88 +14,88 @@ import extracells.tileentity.*; import extracells.util.FuelBurnTime; import extracells.util.recipe.RecipeUniversalTerminal; -import net.minecraftforge.fluids.FluidRegistry; - -import java.io.*; public class CommonProxy { - private class ExternalRecipeLoader implements IRecipeLoader { - - @Override - public BufferedReader getFile(String path) throws Exception { - return new BufferedReader(new FileReader(new File(path))); - } - } - - private class InternalRecipeLoader implements IRecipeLoader { - - @Override - public BufferedReader getFile(String path) throws Exception { - InputStream resourceAsStream = getClass().getResourceAsStream("/assets/extracells/recipes/" + path); - InputStreamReader reader = new InputStreamReader(resourceAsStream, "UTF-8"); - return new BufferedReader(reader); - } - } - - public void addRecipes(File configFolder) { - IRecipeHandler recipeHandler = AEApi.instance().registries().recipes().createNewRecipehandler(); - File externalRecipe = new File(configFolder.getPath() + File.separator + "AppliedEnergistics2" + File.separator + "extracells.recipe"); - if (externalRecipe.exists()) { - recipeHandler.parseRecipes(new ExternalRecipeLoader(), externalRecipe.getPath()); - } else { - recipeHandler.parseRecipes(new InternalRecipeLoader(), "main.recipe"); - } - recipeHandler.injectRecipes(); - GameRegistry.addRecipe(RecipeUniversalTerminal.THIS()); - } - - public void registerBlocks() { - for (BlockEnum current : BlockEnum.values()) { - GameRegistry.registerBlock(current.getBlock(), current.getItemBlockClass(), current.getInternalName()); - } - } - - public void registerItems() { - for (ItemEnum current : ItemEnum.values()) { - GameRegistry.registerItem(current.getItem(), current.getInternalName()); - } - } - - public void registerMovables() { - IAppEngApi api = AEApi.instance(); - api.registries().movable().whiteListTileEntity(TileEntityCertusTank.class); - api.registries().movable().whiteListTileEntity(TileEntityWalrus.class); - api.registries().movable().whiteListTileEntity(TileEntityFluidCrafter.class); - api.registries().movable().whiteListTileEntity(TileEntityFluidInterface.class); - api.registries().movable().whiteListTileEntity(TileEntityFluidFiller.class); - api.registries().movable().whiteListTileEntity(TileEntityHardMeDrive.class); - api.registries().movable().whiteListTileEntity(TileEntityVibrationChamberFluid.class); - } - - public void registerRenderers() { - // Only Clientside - } - - public void registerTileEntities() { - GameRegistry.registerTileEntity(TileEntityCertusTank.class, "tileEntityCertusTank"); - GameRegistry.registerTileEntity(TileEntityWalrus.class, "tileEntityWalrus"); - GameRegistry.registerTileEntity(TileEntityFluidCrafter.class, "tileEntityFluidCrafter"); - GameRegistry.registerTileEntity(TileEntityFluidInterface.class, "tileEntityFluidInterface"); - GameRegistry.registerTileEntity(TileEntityFluidFiller.class, "tileEntityFluidFiller"); - GameRegistry.registerTileEntity(TileEntityHardMeDrive.class, "tileEntityHardMEDrive"); - GameRegistry.registerTileEntity(TileEntityVibrationChamberFluid.class, "tileEntityVibrationChamberFluid"); - } - - public void registerFluidBurnTimes() { - FuelBurnTime.registerFuel(FluidRegistry.LAVA, 800); - } - - public boolean isClient(){ - return false; - } - - public boolean isServer(){ - return true; - } + private class ExternalRecipeLoader implements IRecipeLoader { + + @Override + public BufferedReader getFile(String path) throws Exception { + return new BufferedReader(new FileReader(new File(path))); + } + } + + private class InternalRecipeLoader implements IRecipeLoader { + + @Override + public BufferedReader getFile(String path) throws Exception { + InputStream resourceAsStream = getClass().getResourceAsStream("/assets/extracells/recipes/" + path); + InputStreamReader reader = new InputStreamReader(resourceAsStream, "UTF-8"); + return new BufferedReader(reader); + } + } + + public void addRecipes(File configFolder) { + IRecipeHandler recipeHandler = AEApi.instance().registries().recipes().createNewRecipehandler(); + File externalRecipe = new File( + configFolder.getPath() + File.separator + "AppliedEnergistics2" + File.separator + "extracells.recipe"); + if (externalRecipe.exists()) { + recipeHandler.parseRecipes(new ExternalRecipeLoader(), externalRecipe.getPath()); + } else { + recipeHandler.parseRecipes(new InternalRecipeLoader(), "main.recipe"); + } + recipeHandler.injectRecipes(); + GameRegistry.addRecipe(RecipeUniversalTerminal.THIS()); + } + + public void registerBlocks() { + for (BlockEnum current : BlockEnum.values()) { + GameRegistry.registerBlock(current.getBlock(), current.getItemBlockClass(), current.getInternalName()); + } + } + + public void registerItems() { + for (ItemEnum current : ItemEnum.values()) { + GameRegistry.registerItem(current.getItem(), current.getInternalName()); + } + } + + public void registerMovables() { + IAppEngApi api = AEApi.instance(); + api.registries().movable().whiteListTileEntity(TileEntityCertusTank.class); + api.registries().movable().whiteListTileEntity(TileEntityWalrus.class); + api.registries().movable().whiteListTileEntity(TileEntityFluidCrafter.class); + api.registries().movable().whiteListTileEntity(TileEntityFluidInterface.class); + api.registries().movable().whiteListTileEntity(TileEntityFluidFiller.class); + api.registries().movable().whiteListTileEntity(TileEntityHardMeDrive.class); + api.registries().movable().whiteListTileEntity(TileEntityVibrationChamberFluid.class); + api.registries().movable().whiteListTileEntity(TileEntityCraftingStorage.class); + } + + public void registerRenderers() { + // Only Clientside + } + + public void registerTileEntities() { + GameRegistry.registerTileEntity(TileEntityCertusTank.class, "tileEntityCertusTank"); + GameRegistry.registerTileEntity(TileEntityWalrus.class, "tileEntityWalrus"); + GameRegistry.registerTileEntity(TileEntityFluidCrafter.class, "tileEntityFluidCrafter"); + GameRegistry.registerTileEntity(TileEntityFluidInterface.class, "tileEntityFluidInterface"); + GameRegistry.registerTileEntity(TileEntityFluidFiller.class, "tileEntityFluidFiller"); + GameRegistry.registerTileEntity(TileEntityHardMeDrive.class, "tileEntityHardMEDrive"); + GameRegistry.registerTileEntity(TileEntityVibrationChamberFluid.class, "tileEntityVibrationChamberFluid"); + GameRegistry.registerTileEntity(TileEntityCraftingStorage.class, "tileEntityCraftingStorage"); + } + + public void registerFluidBurnTimes() { + FuelBurnTime.registerFuel(FluidRegistry.LAVA, 800); + } + + public boolean isClient() { + return false; + } + + public boolean isServer() { + return true; + } } diff --git a/src/main/scala/extracells/registries/BlockEnum.java b/src/main/scala/extracells/registries/BlockEnum.java index 86ee6e808..e99ad208a 100644 --- a/src/main/scala/extracells/registries/BlockEnum.java +++ b/src/main/scala/extracells/registries/BlockEnum.java @@ -1,66 +1,69 @@ package extracells.registries; +import net.minecraft.block.Block; +import net.minecraft.item.ItemBlock; +import net.minecraft.util.StatCollector; + import extracells.Extracells; import extracells.block.*; import extracells.integration.Integration; import extracells.item.ItemBlockCertusTank; import extracells.item.ItemBlockECBase; -import net.minecraft.block.Block; -import net.minecraft.item.ItemBlock; -import net.minecraft.util.StatCollector; +import extracells.item.ItemCraftingStorage; public enum BlockEnum { - CERTUSTANK("certustank", new BlockCertusTank(), ItemBlockCertusTank.class), - WALRUS("walrus", new BlockWalrus()), - FLUIDCRAFTER("fluidcrafter", new BlockFluidCrafter()), - ECBASEBLOCK("ecbaseblock", new ECBaseBlock(), ItemBlockECBase.class), - BLASTRESISTANTMEDRIVE("hardmedrive", BlockHardMEDrive.instance()), - VIBRANTCHAMBERFLUID("vibrantchamberfluid", new BlockVibrationChamberFluid()); - private final String internalName; - private Block block; - private Class itemBlockClass; - private Integration.Mods mod; + CERTUSTANK("certustank", new BlockCertusTank(), ItemBlockCertusTank.class), + WALRUS("walrus", new BlockWalrus()), + FLUIDCRAFTER("fluidcrafter", new BlockFluidCrafter()), + ECBASEBLOCK("ecbaseblock", new ECBaseBlock(), ItemBlockECBase.class), + BLASTRESISTANTMEDRIVE("hardmedrive", BlockHardMEDrive.instance()), + VIBRANTCHAMBERFLUID("vibrantchamberfluid", new BlockVibrationChamberFluid()), + CRAFTINGSTORAGE("craftingstorage", new BlockCraftingStorage(), ItemCraftingStorage.class); + + private final String internalName; + private Block block; + private Class itemBlockClass; + private Integration.Mods mod; - BlockEnum(String _internalName, Block _block, Integration.Mods _mod) { - this(_internalName, _block, ItemBlock.class, _mod); - } + BlockEnum(String _internalName, Block _block, Integration.Mods _mod) { + this(_internalName, _block, ItemBlock.class, _mod); + } - BlockEnum(String _internalName, Block _block) { - this(_internalName, _block, ItemBlock.class); - } + BlockEnum(String _internalName, Block _block) { + this(_internalName, _block, ItemBlock.class); + } - BlockEnum(String _internalName, Block _block, Class _itemBlockClass){ - this(_internalName, _block, _itemBlockClass, null); - } + BlockEnum(String _internalName, Block _block, Class _itemBlockClass) { + this(_internalName, _block, _itemBlockClass, null); + } - BlockEnum(String _internalName, Block _block, Class _itemBlockClass, Integration.Mods _mod) { - this.internalName = _internalName; - this.block = _block; - this.block.setBlockName("extracells.block." + this.internalName); - this.itemBlockClass = _itemBlockClass; - this.mod = _mod; - if(_mod == null || _mod.isEnabled()) - this.block.setCreativeTab(Extracells.ModTab()); - } + BlockEnum(String _internalName, Block _block, Class _itemBlockClass, Integration.Mods _mod) { + this.internalName = _internalName; + this.block = _block; + this.block.setBlockName(String.format("extracells.block.%s", this.internalName)); + this.itemBlockClass = _itemBlockClass; + this.mod = _mod; + if (_mod == null || _mod.isEnabled()) this.block.setCreativeTab(Extracells.ModTab()); + } - public Block getBlock() { - return this.block; - } + public Block getBlock() { + return this.block; + } - public String getInternalName() { - return this.internalName; - } + public String getInternalName() { + return this.internalName; + } - public Class getItemBlockClass() { - return this.itemBlockClass; - } + public Class getItemBlockClass() { + return this.itemBlockClass; + } - public String getStatName() { - return StatCollector.translateToLocal(this.block.getUnlocalizedName() + ".name"); - } + public String getStatName() { + return StatCollector.translateToLocal(this.block.getUnlocalizedName() + ".name"); + } - public Integration.Mods getMod(){ - return mod; - } + public Integration.Mods getMod() { + return mod; + } } diff --git a/src/main/scala/extracells/registries/ItemEnum.java b/src/main/scala/extracells/registries/ItemEnum.java index 1f0343679..7c90afb65 100644 --- a/src/main/scala/extracells/registries/ItemEnum.java +++ b/src/main/scala/extracells/registries/ItemEnum.java @@ -1,72 +1,78 @@ package extracells.registries; -import extracells.Extracells; -import extracells.integration.Integration; -import extracells.item.*; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; +import extracells.Extracells; +import extracells.integration.Integration; +import extracells.item.*; + public enum ItemEnum { - PARTITEM("part.base", new ItemPartECBase()), - FLUIDSTORAGE("storage.fluid", new ItemStorageFluid()), - PHYSICALSTORAGE("storage.physical", new ItemStoragePhysical()), - GASSTORAGE("storage.gas", new ItemStorageGas(), Integration.Mods.MEKANISMGAS), - FLUIDPATTERN("pattern.fluid", new ItemFluidPattern()), - FLUIDWIRELESSTERMINAL("terminal.fluid.wireless", ItemWirelessTerminalFluid.THIS()), - STORAGECOMPONET("storage.component", new ItemStorageComponent()), - STORAGECASING("storage.casing", new ItemStorageCasing()), - FLUIDITEM("fluid.item", new ItemFluid(), null, null), // Internal EC Item - FLUIDSTORAGEPORTABLE("storage.fluid.portable", ItemStoragePortableFluidCell.THIS()), - GASSTORAGEPORTABLE("storage.gas.portable", ItemStoragePortableGasCell.THIS(), Integration.Mods.MEKANISMGAS), - CRAFTINGPATTERN("pattern.crafting", new ItemInternalCraftingPattern(), null, null),// Internal EC Item - UNIVERSALTERMINAL("terminal.universal.wireless", ItemWirelessTerminalUniversal.THIS()), - GASWIRELESSTERMINAL("terminal.gas.wireless", ItemWirelessTerminalGas.THIS(), Integration.Mods.MEKANISMGAS), - OCUPGRADE("oc.upgrade", ItemOCUpgrade.THIS(), Integration.Mods.OPENCOMPUTERS); - private final String internalName; - private Item item; - private Integration.Mods mod; + PARTITEM("part.base", new ItemPartECBase()), + FLUIDSTORAGE("storage.fluid", new ItemStorageFluid()), + PHYSICALSTORAGE("storage.physical", new ItemStoragePhysical()), + PHYSICALSTORAGESINGULARITY("storage.physical.advanced.singularity", + new ItemAdvancedStorageCell(Long.MAX_VALUE / 16, 1, 4096, 15000.0, "singularity")), + PHYSICALSTORAGEQUANTUM("storage.physical.advanced.quantum", + new ItemAdvancedStorageCell(Integer.MAX_VALUE / 16, 1, 1, 1000.0, "quantum")), + PHYSICALSTORAGEVOID("storage.physical.void", new ItemVoidStorageCell()), + GASSTORAGE("storage.gas", new ItemStorageGas(), Integration.Mods.MEKANISMGAS), + FLUIDPATTERN("pattern.fluid", new ItemFluidPattern()), + FLUIDWIRELESSTERMINAL("terminal.fluid.wireless", ItemWirelessTerminalFluid.THIS()), + STORAGECOMPONENT("storage.component", new ItemStorageComponent()), + STORAGECASING("storage.casing", new ItemStorageCasing()), + FLUIDITEM("fluid.item", new ItemFluid(), null, null), // Internal EC Item + FLUIDSTORAGEPORTABLE("storage.fluid.portable", ItemStoragePortableFluidCell.THIS()), + GASSTORAGEPORTABLE("storage.gas.portable", ItemStoragePortableGasCell.THIS(), Integration.Mods.MEKANISMGAS), + CRAFTINGPATTERN("pattern.crafting", new ItemInternalCraftingPattern(), null, null), // Internal EC Item + UNIVERSALTERMINAL("terminal.universal.wireless", ItemWirelessTerminalUniversal.THIS()), + GASWIRELESSTERMINAL("terminal.gas.wireless", ItemWirelessTerminalGas.THIS(), Integration.Mods.MEKANISMGAS), + OCUPGRADE("oc.upgrade", ItemOCUpgrade.THIS(), Integration.Mods.OPENCOMPUTERS); + + private final String internalName; + private Item item; + private Integration.Mods mod; - ItemEnum(String _internalName, Item _item) { - this(_internalName, _item, null); - } + ItemEnum(String _internalName, Item _item) { + this(_internalName, _item, null); + } - ItemEnum(String _internalName, Item _item, Integration.Mods _mod){ - this(_internalName, _item, _mod, Extracells.ModTab()); - } + ItemEnum(String _internalName, Item _item, Integration.Mods _mod) { + this(_internalName, _item, _mod, Extracells.ModTab()); + } - ItemEnum(String _internalName, Item _item, Integration.Mods _mod, CreativeTabs creativeTab) { - this.internalName = _internalName; - this.item = _item; - this.item.setUnlocalizedName("extracells." + this.internalName); - this.mod = _mod; - if ((creativeTab != null) && (_mod == null || _mod.isEnabled())) - this.item.setCreativeTab(Extracells.ModTab()); - } + ItemEnum(String _internalName, Item _item, Integration.Mods _mod, CreativeTabs creativeTab) { + this.internalName = _internalName; + this.item = _item; + this.item.setUnlocalizedName("extracells." + this.internalName); + this.mod = _mod; + if ((creativeTab != null) && (_mod == null || _mod.isEnabled())) this.item.setCreativeTab(Extracells.ModTab()); + } - public ItemStack getDamagedStack(int damage) { - return new ItemStack(this.item, 1, damage); - } + public ItemStack getDamagedStack(int damage) { + return new ItemStack(this.item, 1, damage); + } - public String getInternalName() { - return this.internalName; - } + public String getInternalName() { + return this.internalName; + } - public Item getItem() { - return this.item; - } + public Item getItem() { + return this.item; + } - public ItemStack getSizedStack(int size) { - return new ItemStack(this.item, size); - } + public ItemStack getSizedStack(int size) { + return new ItemStack(this.item, size); + } - public String getStatName() { - return StatCollector.translateToLocal(this.item.getUnlocalizedName()); - } + public String getStatName() { + return StatCollector.translateToLocal(this.item.getUnlocalizedName()); + } - public Integration.Mods getMod(){ - return mod; - } + public Integration.Mods getMod() { + return mod; + } } diff --git a/src/main/scala/extracells/registries/PartEnum.java b/src/main/scala/extracells/registries/PartEnum.java index 2306e8887..036ace419 100644 --- a/src/main/scala/extracells/registries/PartEnum.java +++ b/src/main/scala/extracells/registries/PartEnum.java @@ -1,127 +1,135 @@ package extracells.registries; -import appeng.api.config.Upgrades; -import extracells.integration.Integration; -import extracells.part.*; +import java.util.HashMap; +import java.util.Map; + import net.minecraft.item.ItemStack; import net.minecraft.util.StatCollector; + import org.apache.commons.lang3.tuple.MutablePair; import org.apache.commons.lang3.tuple.Pair; -import java.util.HashMap; -import java.util.Map; +import appeng.api.config.Upgrades; +import extracells.integration.Integration; +import extracells.part.*; public enum PartEnum { - FLUIDEXPORT("fluid.export", PartFluidExport.class, "fluid.IO", generatePair(Upgrades.CAPACITY, 2), generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), - FLUIDIMPORT("fluid.import", PartFluidImport.class, "fluid.IO", generatePair(Upgrades.CAPACITY, 2), generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), - FLUIDSTORAGE("fluid.storage", PartFluidStorage.class, null, generatePair(Upgrades.INVERTER, 1)), - FLUIDTERMINAL("fluid.terminal", PartFluidTerminal.class), - FLUIDLEVELEMITTER("fluid.levelemitter", PartFluidLevelEmitter.class), - FLUIDPANEANNIHILATION("fluid.plane.annihilation", PartFluidPlaneAnnihilation.class, "fluid.plane"), - FLUIDPANEFORMATION("fluid.plane.formation", PartFluidPlaneFormation.class, "fluid.plane"), - DRIVE("drive", PartDrive.class), - BATTERY("battery", PartBattery.class), - INTERFACE("interface", PartFluidInterface.class), - FLUIDMONITOR("fluid.monitor", PartFluidStorageMonitor.class), - FLUIDCONVERSIONMONITOR("fluid.conversion.monitor", PartFluidConversionMonitor.class), - OREDICTEXPORTBUS("oredict.export", PartOreDictExporter.class), - GASIMPORT("gas.import", PartGasImport.class, "gas.IO", Integration.Mods.MEKANISMGAS, generatePair(Upgrades.CAPACITY, 2), generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), - GASEXPORT("gas.export", PartGasExport.class, "gas.IO", Integration.Mods.MEKANISMGAS, generatePair(Upgrades.CAPACITY, 2), generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), - GASTERMINAL("gas.terminal", PartGasTerminal.class, Integration.Mods.MEKANISMGAS), - GASSTORAGE("gas.storage", PartGasStorage.class, null, Integration.Mods.MEKANISMGAS, generatePair(Upgrades.INVERTER, 1)), - GASLEVELEMITTER("gas.levelemitter", PartGasLevelEmitter.class, Integration.Mods.MEKANISMGAS), - GASMONITOR("gas.monitor", PartGasStorageMonitor.class, Integration.Mods.MEKANISMGAS), - GASCONVERSIONMONITOR("gas.conversion.monitor", PartGasConversionMonitor.class, Integration.Mods.MEKANISMGAS); - - private Integration.Mods mod; - - - private static Pair generatePair(Upgrades _upgrade, int integer) { - return new MutablePair(_upgrade, integer); - } - - public static int getPartID(Class partClass) { - for (int i = 0; i < values().length; i++) { - if (values()[i].getPartClass() == partClass) - return i; - } - return -1; - } - - public static int getPartID(PartECBase partECBase) { - return getPartID(partECBase.getClass()); - } - - private String unlocalizedName; - - private Class partClass; - - private String groupName; - - private Map upgrades = new HashMap(); - - PartEnum(String _unlocalizedName, Class _partClass) { - this(_unlocalizedName, _partClass, null, (Integration.Mods )null); - } - - PartEnum(String _unlocalizedName, Class _partClass, Integration.Mods _mod) { - this(_unlocalizedName, _partClass, null, _mod); - } - - PartEnum(String _unlocalizedName, Class _partClass, String _groupName) { - this(_unlocalizedName, _partClass, _groupName, (Integration.Mods )null); - } - - PartEnum(String _unlocalizedName, Class _partClass, String _groupName, Integration.Mods _mod) { - this.unlocalizedName = "extracells.part." + _unlocalizedName; - this.partClass = _partClass; - this.groupName = _groupName == null || _groupName.isEmpty() ? null : "extracells." + _groupName; - this.mod = _mod; - } - - PartEnum(String _unlocalizedName, Class _partClass, String _groupName, Pair... _upgrades) { - this(_unlocalizedName, _partClass, _groupName, (Integration.Mods )null); - for (Pair pair : _upgrades) { - this.upgrades.put(pair.getKey(), pair.getValue()); - } - } - - PartEnum(String _unlocalizedName, Class _partClass, String _groupName, Integration.Mods _mod, Pair... _upgrades) { - this(_unlocalizedName, _partClass, _groupName, _mod); - for (Pair pair : _upgrades) { - this.upgrades.put(pair.getKey(), pair.getValue()); - } - } - - public String getGroupName() { - return this.groupName; - } - - public Class getPartClass() { - return this.partClass; - } - - public String getStatName() { - return StatCollector.translateToLocal(this.unlocalizedName + ".name"); - } - - public String getUnlocalizedName() { - return this.unlocalizedName; - } - - @SuppressWarnings("unchecked") - public Map getUpgrades() { - return this.upgrades; - } - - public PartECBase newInstance(ItemStack partStack) - throws IllegalAccessException, InstantiationException { - PartECBase partECBase = this.partClass.newInstance(); - partECBase.initializePart(partStack); - return partECBase; - } - - public Integration.Mods getMod(){ - return mod; - } + + FLUIDEXPORT("fluid.export", PartFluidExport.class, "fluid.IO", generatePair(Upgrades.CAPACITY, 2), + generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), + FLUIDIMPORT("fluid.import", PartFluidImport.class, "fluid.IO", generatePair(Upgrades.CAPACITY, 2), + generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), + FLUIDSTORAGE("fluid.storage", PartFluidStorage.class, null, generatePair(Upgrades.INVERTER, 1)), + FLUIDTERMINAL("fluid.terminal", PartFluidTerminal.class), + FLUIDLEVELEMITTER("fluid.levelemitter", PartFluidLevelEmitter.class), + FLUIDPANEANNIHILATION("fluid.plane.annihilation", PartFluidPlaneAnnihilation.class, "fluid.plane"), + FLUIDPANEFORMATION("fluid.plane.formation", PartFluidPlaneFormation.class, "fluid.plane"), + DRIVE("drive", PartDrive.class), + BATTERY("battery", PartBattery.class), + INTERFACE("interface", PartFluidInterface.class), + FLUIDMONITOR("fluid.monitor", PartFluidStorageMonitor.class), + FLUIDCONVERSIONMONITOR("fluid.conversion.monitor", PartFluidConversionMonitor.class), + OREDICTEXPORTBUS("oredict.export", PartOreDictExporter.class), + GASIMPORT("gas.import", PartGasImport.class, "gas.IO", Integration.Mods.MEKANISMGAS, + generatePair(Upgrades.CAPACITY, 2), generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), + GASEXPORT("gas.export", PartGasExport.class, "gas.IO", Integration.Mods.MEKANISMGAS, + generatePair(Upgrades.CAPACITY, 2), generatePair(Upgrades.REDSTONE, 1), generatePair(Upgrades.SPEED, 2)), + GASTERMINAL("gas.terminal", PartGasTerminal.class, Integration.Mods.MEKANISMGAS), + GASSTORAGE("gas.storage", PartGasStorage.class, null, Integration.Mods.MEKANISMGAS, + generatePair(Upgrades.INVERTER, 1)), + GASLEVELEMITTER("gas.levelemitter", PartGasLevelEmitter.class, Integration.Mods.MEKANISMGAS), + GASMONITOR("gas.monitor", PartGasStorageMonitor.class, Integration.Mods.MEKANISMGAS), + GASCONVERSIONMONITOR("gas.conversion.monitor", PartGasConversionMonitor.class, Integration.Mods.MEKANISMGAS); + + private Integration.Mods mod; + + private static Pair generatePair(Upgrades _upgrade, int integer) { + return new MutablePair(_upgrade, integer); + } + + public static int getPartID(Class partClass) { + for (int i = 0; i < values().length; i++) { + if (values()[i].getPartClass() == partClass) return i; + } + return -1; + } + + public static int getPartID(PartECBase partECBase) { + return getPartID(partECBase.getClass()); + } + + private String unlocalizedName; + + private Class partClass; + + private String groupName; + + private Map upgrades = new HashMap(); + + PartEnum(String _unlocalizedName, Class _partClass) { + this(_unlocalizedName, _partClass, null, (Integration.Mods) null); + } + + PartEnum(String _unlocalizedName, Class _partClass, Integration.Mods _mod) { + this(_unlocalizedName, _partClass, null, _mod); + } + + PartEnum(String _unlocalizedName, Class _partClass, String _groupName) { + this(_unlocalizedName, _partClass, _groupName, (Integration.Mods) null); + } + + PartEnum(String _unlocalizedName, Class _partClass, String _groupName, + Integration.Mods _mod) { + this.unlocalizedName = "extracells.part." + _unlocalizedName; + this.partClass = _partClass; + this.groupName = _groupName == null || _groupName.isEmpty() ? null : "extracells." + _groupName; + this.mod = _mod; + } + + PartEnum(String _unlocalizedName, Class _partClass, String _groupName, + Pair... _upgrades) { + this(_unlocalizedName, _partClass, _groupName, (Integration.Mods) null); + for (Pair pair : _upgrades) { + this.upgrades.put(pair.getKey(), pair.getValue()); + } + } + + PartEnum(String _unlocalizedName, Class _partClass, String _groupName, Integration.Mods _mod, + Pair... _upgrades) { + this(_unlocalizedName, _partClass, _groupName, _mod); + for (Pair pair : _upgrades) { + this.upgrades.put(pair.getKey(), pair.getValue()); + } + } + + public String getGroupName() { + return this.groupName; + } + + public Class getPartClass() { + return this.partClass; + } + + public String getStatName() { + return StatCollector.translateToLocal(this.unlocalizedName + ".name"); + } + + public String getUnlocalizedName() { + return this.unlocalizedName; + } + + @SuppressWarnings("unchecked") + public Map getUpgrades() { + return this.upgrades; + } + + public PartECBase newInstance(ItemStack partStack) throws IllegalAccessException, InstantiationException { + PartECBase partECBase = this.partClass.newInstance(); + partECBase.initializePart(partStack); + return partECBase; + } + + public Integration.Mods getMod() { + return mod; + } } diff --git a/src/main/scala/extracells/render/RenderHandler.java b/src/main/scala/extracells/render/RenderHandler.java index 8f72bc870..80a2a7fc1 100644 --- a/src/main/scala/extracells/render/RenderHandler.java +++ b/src/main/scala/extracells/render/RenderHandler.java @@ -1,62 +1,62 @@ package extracells.render; -import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; -import extracells.block.BlockCertusTank; -import extracells.render.model.ModelCertusTank; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; +import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; +import extracells.block.BlockCertusTank; +import extracells.render.model.ModelCertusTank; + public class RenderHandler implements ISimpleBlockRenderingHandler { - public static int getId() { - return renderID; - } - - private static int renderID = 0; - ModelCertusTank tank = new ModelCertusTank(); - - public static int renderPass; - - public RenderHandler(int id) { - RenderHandler.renderPass = 0; - renderID = id; - } - - @Override - public int getRenderId() { - return getId(); - } - - @Override - public void renderInventoryBlock(Block block, int metadata, int modelID, - RenderBlocks renderer) {} - - @Override - public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, - Block block, int modelId, RenderBlocks renderer) { - if (block instanceof BlockCertusTank) { - Tessellator tessellator = Tessellator.instance; - tessellator.setColorOpaque_F(1, 1, 1); - boolean oldAO = renderer.enableAO; - renderer.enableAO = false; - if (RenderHandler.renderPass == 0) { - this.tank.renderOuterBlock(block, x, y, z, renderer, world); - } else { - this.tank.renderInnerBlock(block, x, y, z, renderer, world); - TileEntity tileEntity = world.getTileEntity(x, y, z); - this.tank.renderFluid(tileEntity, x, y, z, renderer); - } - renderer.enableAO = oldAO; - return true; - } - return false; - } - - @Override - public boolean shouldRender3DInInventory(int modelId) { - return true; - } + public static int getId() { + return renderID; + } + + private static int renderID = 0; + ModelCertusTank tank = new ModelCertusTank(); + + public static int renderPass; + + public RenderHandler(int id) { + RenderHandler.renderPass = 0; + renderID = id; + } + + @Override + public int getRenderId() { + return getId(); + } + + @Override + public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) {} + + @Override + public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, + RenderBlocks renderer) { + if (block instanceof BlockCertusTank) { + Tessellator tessellator = Tessellator.instance; + tessellator.setColorOpaque_F(1, 1, 1); + boolean oldAO = renderer.enableAO; + renderer.enableAO = false; + if (RenderHandler.renderPass == 0) { + this.tank.renderOuterBlock(block, x, y, z, renderer, world); + } else { + this.tank.renderInnerBlock(block, x, y, z, renderer, world); + TileEntity tileEntity = world.getTileEntity(x, y, z); + this.tank.renderFluid(tileEntity, x, y, z, renderer); + } + renderer.enableAO = oldAO; + return true; + } + return false; + } + + @Override + public boolean shouldRender3DInInventory(int modelId) { + return true; + } } diff --git a/src/main/scala/extracells/render/TextureManager.java b/src/main/scala/extracells/render/TextureManager.java index 0e99d242d..3d7b45571 100644 --- a/src/main/scala/extracells/render/TextureManager.java +++ b/src/main/scala/extracells/render/TextureManager.java @@ -4,66 +4,67 @@ import net.minecraft.util.IIcon; public enum TextureManager { - BUS_SIDE(TextureType.PART, "bus_side"), - BUS_BORDER(TextureType.PART, "bus_border"), - BUS_COLOR(TextureType.PART, "bus_color_border", "bus_color_point"), - EXPORT_FRONT(TextureType.PART, "export_front_1", "export_front_2"), - EXPORT_SIDE(TextureType.PART, "export_side"), - IMPORT_FRONT(TextureType.PART, "import_front_1", "import_front_2"), - IMPORT_SIDE(TextureType.PART, "import_side"), - STORAGE_FRONT( TextureType.PART, "storage_front_1", "storage_front_2"), - STORAGE_SIDE( TextureType.PART, "storage_side"), - TERMINAL_FRONT(TextureType.PART, "terminal_front_1", "terminal_front_2", "terminal_front_3"), - TERMINAL_SIDE( TextureType.PART, "terminal_side"), - PANE_FRONT(TextureType.PART, "pane_front_1", "pane_front_2", "pane_front_3"), - PANE_SIDE( TextureType.PART, "pane_side"), - DRIVE_FRONT(TextureType.PART, "drive_front_1", "drive_front_2", "drive_front_3", "drive_front_4"), - DRIVE_SIDE( TextureType.PART, "drive_side"), - BATTERY_FRONT(TextureType.PART, "battery_front_1"), - BATTERY_SIDE(TextureType.PART, "battery_side"), - LEVEL_FRONT( TextureType.PART, "level_front_1", "level_front_2", "level_front_3"), - LEVEL_SIDE( TextureType.PART, "level_side"), - INTERFACE(TextureType.PART, "fluid_interface"), - STORAGE_MONITOR(TextureType.PART, "storage.monitor_1", "storage.monitor_2", "storage.monitor_3"), - CONVERSION_MONITOR( TextureType.PART, "conversion.monitor_1", "conversion.monitor_2", "conversion.monitor_3"); - private enum TextureType { - ITEM, BLOCK, PART - } + BUS_SIDE(TextureType.PART, "bus_side"), + BUS_BORDER(TextureType.PART, "bus_border"), + BUS_COLOR(TextureType.PART, "bus_color_border", "bus_color_point"), + EXPORT_FRONT(TextureType.PART, "export_front_1", "export_front_2"), + EXPORT_SIDE(TextureType.PART, "export_side"), + IMPORT_FRONT(TextureType.PART, "import_front_1", "import_front_2"), + IMPORT_SIDE(TextureType.PART, "import_side"), + STORAGE_FRONT(TextureType.PART, "storage_front_1", "storage_front_2"), + STORAGE_SIDE(TextureType.PART, "storage_side"), + TERMINAL_FRONT(TextureType.PART, "terminal_front_1", "terminal_front_2", "terminal_front_3"), + TERMINAL_SIDE(TextureType.PART, "terminal_side"), + PANE_FRONT(TextureType.PART, "pane_front_1", "pane_front_2", "pane_front_3"), + PANE_SIDE(TextureType.PART, "pane_side"), + DRIVE_FRONT(TextureType.PART, "drive_front_1", "drive_front_2", "drive_front_3", "drive_front_4"), + DRIVE_SIDE(TextureType.PART, "drive_side"), + BATTERY_FRONT(TextureType.PART, "battery_front_1"), + BATTERY_SIDE(TextureType.PART, "battery_side"), + LEVEL_FRONT(TextureType.PART, "level_front_1", "level_front_2", "level_front_3"), + LEVEL_SIDE(TextureType.PART, "level_side"), + INTERFACE(TextureType.PART, "fluid_interface"), + STORAGE_MONITOR(TextureType.PART, "storage.monitor_1", "storage.monitor_2", "storage.monitor_3"), + CONVERSION_MONITOR(TextureType.PART, "conversion.monitor_1", "conversion.monitor_2", "conversion.monitor_3"); - private TextureType textureType; - private String[] textureNames; + private enum TextureType { + ITEM, + BLOCK, + PART + } - private IIcon[] textures; + private TextureType textureType; + private String[] textureNames; - TextureManager(TextureType _textureType, String... _textureName) { - this.textureType = _textureType; - this.textureNames = _textureName; - this.textures = new IIcon[this.textureNames.length]; - } + private IIcon[] textures; - public IIcon getTexture() { - return this.textures[0]; - } + TextureManager(TextureType _textureType, String... _textureName) { + this.textureType = _textureType; + this.textureNames = _textureName; + this.textures = new IIcon[this.textureNames.length]; + } - public IIcon[] getTextures() { - return this.textures; - } + public IIcon getTexture() { + return this.textures[0]; + } - public void registerTexture(TextureMap textureMap) { + public IIcon[] getTextures() { + return this.textures; + } - if (!(textureMap.getTextureType() == 0 && (this.textureType == TextureType.BLOCK || this.textureType == TextureType.PART)) - && !(textureMap.getTextureType() == 1 && this.textureType == TextureType.ITEM)) - return; + public void registerTexture(TextureMap textureMap) { - for (int i = 0; i < this.textureNames.length; i++) { - if (this.textureType == TextureType.PART) - this.textures[i] = textureMap.registerIcon("extracells:part/" - + this.textureNames[i]); - if (this.textureType == TextureType.BLOCK - || this.textureType == TextureType.ITEM) - this.textures[i] = textureMap.registerIcon("extracells:" - + this.textureNames[i]); - } - } + if (!(textureMap.getTextureType() == 0 + && (this.textureType == TextureType.BLOCK || this.textureType == TextureType.PART)) + && !(textureMap.getTextureType() == 1 && this.textureType == TextureType.ITEM)) + return; + + for (int i = 0; i < this.textureNames.length; i++) { + if (this.textureType == TextureType.PART) + this.textures[i] = textureMap.registerIcon("extracells:part/" + this.textureNames[i]); + if (this.textureType == TextureType.BLOCK || this.textureType == TextureType.ITEM) + this.textures[i] = textureMap.registerIcon("extracells:" + this.textureNames[i]); + } + } } diff --git a/src/main/scala/extracells/render/block/RendererHardMEDrive.scala b/src/main/scala/extracells/render/block/RendererHardMEDrive.scala index f4e74a250..f7b043ab6 100644 --- a/src/main/scala/extracells/render/block/RendererHardMEDrive.scala +++ b/src/main/scala/extracells/render/block/RendererHardMEDrive.scala @@ -1,7 +1,9 @@ - package extracells.render.block -import cpw.mods.fml.client.registry.{ISimpleBlockRenderingHandler, RenderingRegistry} +import cpw.mods.fml.client.registry.{ + ISimpleBlockRenderingHandler, + RenderingRegistry +} import extracells.tileentity.TileEntityHardMeDrive import net.minecraft.block.Block import net.minecraft.client.Minecraft @@ -11,12 +13,12 @@ import net.minecraft.util.{IIcon, ResourceLocation} import net.minecraft.world.IBlockAccess import org.lwjgl.opengl.GL11 - object RendererHardMEDrive extends ISimpleBlockRenderingHandler { var renderID = 0 - val tex = new ResourceLocation("extracells", "textures/blocks/hardmedrive.png") + val tex = + new ResourceLocation("extracells", "textures/blocks/hardmedrive.png") val i = new Icon(5, 11, 5, 7) val i2 = new Icon(5, 11, 8, 10) @@ -31,72 +33,123 @@ object RendererHardMEDrive extends ISimpleBlockRenderingHandler { override def shouldRender3DInInventory(modelId: Int): Boolean = true - override def renderInventoryBlock(block: Block, metadata: Int, modelId: Int, renderer: RenderBlocks) = { + override def renderInventoryBlock( + block: Block, + metadata: Int, + modelId: Int, + renderer: RenderBlocks + ) = { val tessellator = Tessellator.instance - renderer.setRenderBounds(0.0D, 0.0D, 0.0D, 1.0D, 1.0D, 1.0D) - GL11.glTranslatef(-0.5F, -0.5F, -0.5F) + renderer.setRenderBounds(0.0d, 0.0d, 0.0d, 1.0d, 1.0d, 1.0d) + GL11.glTranslatef(-0.5f, -0.5f, -0.5f) tessellator.startDrawingQuads - tessellator.setNormal(0.0F, -1.0F, 0.0F) - renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 0, 3)) + tessellator.setNormal(0.0f, -1.0f, 0.0f) + renderer.renderFaceYNeg( + block, + 0.0d, + 0.0d, + 0.0d, + renderer.getBlockIconFromSideAndMetadata(block, 0, 3) + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 1.0F, 0.0F) - renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 1, 3)) + tessellator.setNormal(0.0f, 1.0f, 0.0f) + renderer.renderFaceYPos( + block, + 0.0d, + 0.0d, + 0.0d, + renderer.getBlockIconFromSideAndMetadata(block, 1, 3) + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, -1.0F) - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 2, 3) ) + tessellator.setNormal(0.0f, 0.0f, -1.0f) + renderer.renderFaceZNeg( + block, + 0.0d, + 0.0d, + 0.0d, + renderer.getBlockIconFromSideAndMetadata(block, 2, 3) + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, 1.0F) - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 3, 3)) + tessellator.setNormal(0.0f, 0.0f, 1.0f) + renderer.renderFaceZPos( + block, + 0.0d, + 0.0d, + 0.0d, + renderer.getBlockIconFromSideAndMetadata(block, 3, 3) + ) tessellator.draw Minecraft.getMinecraft.renderEngine.bindTexture(tex) tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, 1.0F) - renderer.renderMinX = .3125D - renderer.renderMinY = .25D - renderer.renderMaxX = .6875D - renderer.renderMaxY = .375D - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, i) + tessellator.setNormal(0.0f, 0.0f, 1.0f) + renderer.renderMinX = .3125d + renderer.renderMinY = .25d + renderer.renderMaxX = .6875d + renderer.renderMaxY = .375d + renderer.renderFaceZPos(block, 0.0d, 0.0d, 0.0d, i) tessellator.draw - renderer.renderMinY = .43525D - renderer.renderMaxY = .56025D + renderer.renderMinY = .43525d + renderer.renderMaxY = .56025d tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, 1.0F) - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, i) + tessellator.setNormal(0.0f, 0.0f, 1.0f) + renderer.renderFaceZPos(block, 0.0d, 0.0d, 0.0d, i) tessellator.draw - renderer.renderMinY = .62275D - renderer.renderMaxY = .75D + renderer.renderMinY = .62275d + renderer.renderMaxY = .75d tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, 1.0F) - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, i) - renderer.renderMinX = 0.0D - renderer.renderMinY = 0.0D - renderer.renderMaxX = 1.0D - renderer.renderMaxY = 1.0D + tessellator.setNormal(0.0f, 0.0f, 1.0f) + renderer.renderFaceZPos(block, 0.0d, 0.0d, 0.0d, i) + renderer.renderMinX = 0.0d + renderer.renderMinY = 0.0d + renderer.renderMaxX = 1.0d + renderer.renderMaxY = 1.0d tessellator.draw - Minecraft.getMinecraft.renderEngine.bindTexture(TextureMap.locationBlocksTexture) + Minecraft.getMinecraft.renderEngine.bindTexture( + TextureMap.locationBlocksTexture + ) tessellator.startDrawingQuads - tessellator.setNormal(-1.0F, 0.0F, 0.0F) - renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 4, 3)) + tessellator.setNormal(-1.0f, 0.0f, 0.0f) + renderer.renderFaceXNeg( + block, + 0.0d, + 0.0d, + 0.0d, + renderer.getBlockIconFromSideAndMetadata(block, 4, 3) + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(1.0F, 0.0F, 0.0F) - renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, 5, 3)) + tessellator.setNormal(1.0f, 0.0f, 0.0f) + renderer.renderFaceXPos( + block, + 0.0d, + 0.0d, + 0.0d, + renderer.getBlockIconFromSideAndMetadata(block, 5, 3) + ) tessellator.draw - GL11.glTranslatef(0.5F, 0.5F, 0.5F) + GL11.glTranslatef(0.5f, 0.5f, 0.5f) } - override def renderWorldBlock(world: IBlockAccess, x: Int, y: Int, z: Int, block: Block, modelId: Int, renderer: RenderBlocks): Boolean = { + override def renderWorldBlock( + world: IBlockAccess, + x: Int, + y: Int, + z: Int, + block: Block, + modelId: Int, + renderer: RenderBlocks + ): Boolean = { val tessellator = Tessellator.instance renderer.renderStandardBlock(block, x, y, z) - tessellator.addTranslation(x, y, z) + tessellator.addTranslation(x, y, z) val meta = world.getBlockMetadata(x, y, z) val tileEntity = world.getTileEntity(x, y, z) - if( tileEntity == null || (!tileEntity.isInstanceOf[TileEntityHardMeDrive])) + if (tileEntity == null || (!tileEntity.isInstanceOf[TileEntityHardMeDrive])) return false val tileEntityHardMeDrive = tileEntity.asInstanceOf[TileEntityHardMeDrive] @@ -115,155 +168,245 @@ object RendererHardMEDrive extends ISimpleBlockRenderingHandler { tessellator.setBrightness(240) Minecraft.getMinecraft.renderEngine.bindTexture(tex) meta match { - case 2 => renderZNeg(renderer, block, generateRenderInformations(tileEntityHardMeDrive)) - case 3 => renderZPos(renderer, block, generateRenderInformations(tileEntityHardMeDrive)) - case 4 => renderXNeg(renderer, block, generateRenderInformations(tileEntityHardMeDrive)) - case 5 => renderXPos(renderer, block, generateRenderInformations(tileEntityHardMeDrive)) + case 2 => + renderZNeg( + renderer, + block, + generateRenderInformations(tileEntityHardMeDrive) + ) + case 3 => + renderZPos( + renderer, + block, + generateRenderInformations(tileEntityHardMeDrive) + ) + case 4 => + renderXNeg( + renderer, + block, + generateRenderInformations(tileEntityHardMeDrive) + ) + case 5 => + renderXPos( + renderer, + block, + generateRenderInformations(tileEntityHardMeDrive) + ) case _ => } - Minecraft.getMinecraft.renderEngine.bindTexture(TextureMap.locationBlocksTexture) + Minecraft.getMinecraft.renderEngine.bindTexture( + TextureMap.locationBlocksTexture + ) GL11.glPopMatrix(); - if(b) + if (b) tessellator.startDrawingQuads tessellator.addTranslation(-x, -y, -z) true } - def generateRenderInformations(tileEntity: TileEntityHardMeDrive): Array[RenderInformation] = { + def generateRenderInformations( + tileEntity: TileEntityHardMeDrive + ): Array[RenderInformation] = { val renderInformations = new Array[RenderInformation](3) - renderInformations(2) = new RenderInformation(4, tileEntity.getColorByStatus(2)) - renderInformations(1) = new RenderInformation(7, tileEntity.getColorByStatus(1)) - renderInformations(0) = new RenderInformation(10, tileEntity.getColorByStatus(0)) + renderInformations(2) = + new RenderInformation(4, tileEntity.getColorByStatus(2)) + renderInformations(1) = + new RenderInformation(7, tileEntity.getColorByStatus(1)) + renderInformations(0) = + new RenderInformation(10, tileEntity.getColorByStatus(0)) renderInformations } - def renderXPos(renderer : RenderBlocks, block: Block, renderInformations: Array[RenderInformation]){ + def renderXPos( + renderer: RenderBlocks, + block: Block, + renderInformations: Array[RenderInformation] + ) { val tessellator = Tessellator.instance - renderer.renderMinZ = .3125D - renderer.renderMaxZ = .6875D + renderer.renderMinZ = .3125d + renderer.renderMaxZ = .6875d val it = renderInformations.iterator - while(it.hasNext){ + while (it.hasNext) { val renderInformation = it.next - renderer.renderMinY = 1.0D / 16.0D * renderInformation.getPos - renderer.renderMaxY = 1.0D / 16.0D * (renderInformation.getPos + 2) + renderer.renderMinY = 1.0d / 16.0d * renderInformation.getPos + renderer.renderMaxY = 1.0d / 16.0d * (renderInformation.getPos + 2) tessellator.startDrawingQuads - tessellator.setNormal(1.0F, 0.0F, 0.0F) - renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon) + tessellator.setNormal(1.0f, 0.0f, 0.0f) + renderer.renderFaceXPos( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(1.0F, 0.0F, 0.0F) + tessellator.setNormal(1.0f, 0.0f, 0.0f) tessellator.setColorOpaque_I(renderInformation.getColor) - renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon2) + renderer.renderFaceXPos( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon2 + ) tessellator.draw } - renderer.renderMinX = 0.0D - renderer.renderMinY = 0.0D - renderer.renderMinZ = 0.0D - renderer.renderMaxX = 1.0D - renderer.renderMaxY = 1.0D - renderer.renderMaxZ = 1.0D + renderer.renderMinX = 0.0d + renderer.renderMinY = 0.0d + renderer.renderMinZ = 0.0d + renderer.renderMaxX = 1.0d + renderer.renderMaxY = 1.0d + renderer.renderMaxZ = 1.0d } - def renderXNeg(renderer : RenderBlocks, block: Block, renderInformations: Array[RenderInformation]){ + def renderXNeg( + renderer: RenderBlocks, + block: Block, + renderInformations: Array[RenderInformation] + ) { val tessellator = Tessellator.instance - renderer.renderMinZ = .3125D - renderer.renderMaxZ = .6875D + renderer.renderMinZ = .3125d + renderer.renderMaxZ = .6875d val it = renderInformations.iterator - while(it.hasNext){ + while (it.hasNext) { val renderInformation = it.next - renderer.renderMinY = 1.0D / 16.0D * renderInformation.getPos - renderer.renderMaxY = 1.0D / 16.0D * (renderInformation.getPos + 2) + renderer.renderMinY = 1.0d / 16.0d * renderInformation.getPos + renderer.renderMaxY = 1.0d / 16.0d * (renderInformation.getPos + 2) tessellator.startDrawingQuads - tessellator.setNormal(-1.0F, 0.0F, 0.0F) - renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon) + tessellator.setNormal(-1.0f, 0.0f, 0.0f) + renderer.renderFaceXNeg( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(-1.0F, 0.0F, 0.0F) + tessellator.setNormal(-1.0f, 0.0f, 0.0f) tessellator.setColorOpaque_I(renderInformation.getColor) - renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon2) + renderer.renderFaceXNeg( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon2 + ) tessellator.draw } - renderer.renderMinX = 0.0D - renderer.renderMinY = 0.0D - renderer.renderMinZ = 0.0D - renderer.renderMaxX = 1.0D - renderer.renderMaxY = 1.0D - renderer.renderMaxZ = 1.0D + renderer.renderMinX = 0.0d + renderer.renderMinY = 0.0d + renderer.renderMinZ = 0.0d + renderer.renderMaxX = 1.0d + renderer.renderMaxY = 1.0d + renderer.renderMaxZ = 1.0d } - - def renderZPos(renderer : RenderBlocks, block: Block, renderInformations: Array[RenderInformation]){ + def renderZPos( + renderer: RenderBlocks, + block: Block, + renderInformations: Array[RenderInformation] + ) { val tessellator = Tessellator.instance - renderer.renderMinX = .3125D - renderer.renderMaxX = .6875D + renderer.renderMinX = .3125d + renderer.renderMaxX = .6875d val it = renderInformations.iterator - while(it.hasNext){ + while (it.hasNext) { val renderInformation = it.next - renderer.renderMinY = 1.0D / 16.0D * renderInformation.getPos - renderer.renderMaxY = 1.0D / 16.0D * (renderInformation.getPos + 2.0D) + renderer.renderMinY = 1.0d / 16.0d * renderInformation.getPos + renderer.renderMaxY = 1.0d / 16.0d * (renderInformation.getPos + 2.0d) tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, 1.0F) - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon) + tessellator.setNormal(0.0f, 0.0f, 1.0f) + renderer.renderFaceZPos( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, 1.0F) + tessellator.setNormal(0.0f, 0.0f, 1.0f) tessellator.setColorOpaque_I(renderInformation.getColor) - renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon2) + renderer.renderFaceZPos( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon2 + ) tessellator.draw } - renderer.renderMinX = 0.0D - renderer.renderMinY = 0.0D - renderer.renderMinZ = 0.0D - renderer.renderMaxX = 1.0D - renderer.renderMaxY = 1.0D - renderer.renderMaxZ = 1.0D + renderer.renderMinX = 0.0d + renderer.renderMinY = 0.0d + renderer.renderMinZ = 0.0d + renderer.renderMaxX = 1.0d + renderer.renderMaxY = 1.0d + renderer.renderMaxZ = 1.0d } - def renderZNeg(renderer : RenderBlocks, block: Block, renderInformations: Array[RenderInformation]){ + def renderZNeg( + renderer: RenderBlocks, + block: Block, + renderInformations: Array[RenderInformation] + ) { val tessellator = Tessellator.instance - renderer.renderMinX = .3125D - renderer.renderMaxX = .6875D + renderer.renderMinX = .3125d + renderer.renderMaxX = .6875d val it = renderInformations.iterator - while(it.hasNext){ + while (it.hasNext) { val renderInformation = it.next - renderer.renderMinY = 1.0D / 16.0D * renderInformation.getPos - renderer.renderMaxY = 1.0D / 16.0D * (renderInformation.getPos + 2.0D) + renderer.renderMinY = 1.0d / 16.0d * renderInformation.getPos + renderer.renderMaxY = 1.0d / 16.0d * (renderInformation.getPos + 2.0d) tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, -1.0F) - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon) + tessellator.setNormal(0.0f, 0.0f, -1.0f) + renderer.renderFaceZNeg( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon + ) tessellator.draw tessellator.startDrawingQuads - tessellator.setNormal(0.0F, 0.0F, -1.0F) + tessellator.setNormal(0.0f, 0.0f, -1.0f) tessellator.setColorOpaque_I(renderInformation.getColor) - renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, renderInformation.getIcon2) + renderer.renderFaceZNeg( + block, + 0.0d, + 0.0d, + 0.0d, + renderInformation.getIcon2 + ) tessellator.draw } - renderer.renderMinX = 0.0D - renderer.renderMinY = 0.0D - renderer.renderMinZ = 0.0D - renderer.renderMaxX = 1.0D - renderer.renderMaxY = 1.0D - renderer.renderMaxZ = 1.0D + renderer.renderMinX = 0.0d + renderer.renderMinY = 0.0d + renderer.renderMinZ = 0.0d + renderer.renderMaxX = 1.0d + renderer.renderMaxY = 1.0d + renderer.renderMaxZ = 1.0d } - class RenderInformation(pos: Double, color: Int){ + class RenderInformation(pos: Double, color: Int) { def getIcon = i3 def getIcon2 = i3 def getPos = pos def getColor = color } - - protected class Icon(minU: Float, maxU: Float, minV: Float, maxV: Float) extends IIcon { + protected class Icon(minU: Float, maxU: Float, minV: Float, maxV: Float) + extends IIcon { override def getIconHeight: Int = ??? override def getMinU: Float = minU override def getMaxU: Float = maxU - override def getInterpolatedV (p_94207_1_ : Double):Float = { + override def getInterpolatedV(p_94207_1_ : Double): Float = { val f: Float = this.getMaxV - this.getMinV - this.getMinV + f// * (p_94207_1_.toFloat / 16.0F) + this.getMinV + f // * (p_94207_1_.toFloat / 16.0F) } override def getIconName: String = "" @@ -274,9 +417,9 @@ object RendererHardMEDrive extends ISimpleBlockRenderingHandler { override def getMaxV: Float = maxV - override def getInterpolatedU (p_94214_1_ : Double):Float = { + override def getInterpolatedU(p_94214_1_ : Double): Float = { val f: Float = this.getMaxU - this.getMinU - this.getMinU + f// * (p_94214_1_.toFloat / 16.0F) + this.getMinU + f // * (p_94214_1_.toFloat / 16.0F) } } } diff --git a/src/main/scala/extracells/render/item/ItemRendererCertusTank.java b/src/main/scala/extracells/render/item/ItemRendererCertusTank.java index 19012b479..cdf42ddcf 100644 --- a/src/main/scala/extracells/render/item/ItemRendererCertusTank.java +++ b/src/main/scala/extracells/render/item/ItemRendererCertusTank.java @@ -1,6 +1,5 @@ package extracells.render.item; -import extracells.render.model.ModelCertusTank; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; @@ -12,77 +11,86 @@ import net.minecraftforge.client.IItemRenderer; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import org.lwjgl.opengl.GL11; -public class ItemRendererCertusTank implements IItemRenderer { +import org.lwjgl.opengl.GL11; - private ModelCertusTank model = new ModelCertusTank(); +import extracells.render.model.ModelCertusTank; - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - return true; - } +public class ItemRendererCertusTank implements IItemRenderer { - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - Minecraft.getMinecraft().renderEngine.bindTexture(new ResourceLocation( - "extracells", "textures/blocks/texmap_tank.png")); - GL11.glPushMatrix(); - GL11.glPushAttrib(GL11.GL_ENABLE_BIT); - GL11.glEnable(GL11.GL_CULL_FACE); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + private ModelCertusTank model = new ModelCertusTank(); - GL11.glTranslatef(0.5F, 0.5F, 0.5F); - GL11.glScalef(1, -1, -1); - this.model.render(0.0625f); - GL11.glScalef(1, -1, 1); - this.model.render(0.0625f); + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return true; + } - if (item != null && item.hasTagCompound()) { - FluidStack storedFluid = FluidStack.loadFluidStackFromNBT(item - .getTagCompound().getCompoundTag("tileEntity")); - int tankCapacity = 32000; + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + Minecraft.getMinecraft().renderEngine + .bindTexture(new ResourceLocation("extracells", "textures/blocks/texmap_tank.png")); + GL11.glPushMatrix(); + GL11.glPushAttrib(GL11.GL_ENABLE_BIT); + GL11.glEnable(GL11.GL_CULL_FACE); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - if (storedFluid != null && storedFluid.getFluid() != null) { - IIcon fluidIcon = storedFluid.getFluid().getIcon(); + GL11.glTranslatef(0.5F, 0.5F, 0.5F); + GL11.glScalef(1, -1, -1); + this.model.render(0.0625f); + GL11.glScalef(1, -1, 1); + this.model.render(0.0625f); - Tessellator tessellator = Tessellator.instance; - RenderBlocks renderer = new RenderBlocks(); + if (item != null && item.hasTagCompound()) { + FluidStack storedFluid = FluidStack + .loadFluidStackFromNBT(item.getTagCompound().getCompoundTag("tileEntity")); + int tankCapacity = 32000; - GL11.glScalef(1, 1, -1); - renderer.setRenderBounds(0.08F, 0.001F, 0.08F, 0.92, - (float) storedFluid.amount / (float) tankCapacity - * 0.999F, 0.92F); - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - GL11.glTranslatef(-0.5F, -0.5F, -0.5F); - Block waterBlock = FluidRegistry.WATER.getBlock(); + if (storedFluid != null && storedFluid.getFluid() != null) { + IIcon fluidIcon = storedFluid.getFluid().getIcon(); + if (fluidIcon == null) fluidIcon = FluidRegistry.LAVA.getIcon(); + Tessellator tessellator = Tessellator.instance; + RenderBlocks renderer = new RenderBlocks(); - tessellator.startDrawingQuads(); - tessellator.setNormal(0.0F, -1F, 0.0F); - renderer.renderFaceYNeg(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); - tessellator.setNormal(0.0F, 0.0F, -1F); - renderer.renderFaceZNeg(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); - tessellator.setNormal(-1F, 0.0F, 0.0F); - renderer.renderFaceXNeg(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); - tessellator.draw(); - } - } - GL11.glPopAttrib(); - GL11.glPopMatrix(); - } + GL11.glScalef(1, 1, -1); + renderer.setRenderBounds( + 0.08F, + 0.001F, + 0.08F, + 0.92, + (float) storedFluid.amount / (float) tankCapacity * 0.999F, + 0.92F); + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + GL11.glTranslatef(-0.5F, -0.5F, -0.5F); + Block waterBlock = FluidRegistry.WATER.getBlock(); + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F( + (storedFluid.getFluid().getColor() >> 16 & 0xFF) / 255.0F, + (storedFluid.getFluid().getColor() >> 8 & 0xFF) / 255.0F, + (storedFluid.getFluid().getColor() & 0xFF) / 255.0F, + 1.0F); + tessellator.setNormal(0.0F, -1F, 0.0F); + renderer.renderFaceYNeg(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); + tessellator.setNormal(0.0F, 0.0F, -1F); + renderer.renderFaceZNeg(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); + tessellator.setNormal(-1F, 0.0F, 0.0F); + renderer.renderFaceXNeg(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(waterBlock, 0.0D, 0.0D, 0.0D, fluidIcon); + tessellator.draw(); + } + } + GL11.glPopAttrib(); + GL11.glPopMatrix(); + } - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, - ItemRendererHelper helper) { - return true; - } + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } } diff --git a/src/main/scala/extracells/render/item/ItemRendererFluid.java b/src/main/scala/extracells/render/item/ItemRendererFluid.java index 741788508..396e8da9e 100644 --- a/src/main/scala/extracells/render/item/ItemRendererFluid.java +++ b/src/main/scala/extracells/render/item/ItemRendererFluid.java @@ -1,6 +1,5 @@ package extracells.render.item; -import extracells.util.GuiUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.item.ItemStack; @@ -9,37 +8,32 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; -public class ItemRendererFluid implements IItemRenderer { - - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - return true; - } +import extracells.util.GuiUtil; - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - Fluid fluid = FluidRegistry.getFluid(item.getItemDamage()); - if (fluid == null) - return; - IIcon icon = fluid.getIcon(); - if (icon == null) - return; - float f = icon.getMinU(); - float f1 = icon.getMaxU(); - float f2 = icon.getMinV(); - float f3 = icon.getMaxV(); - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - GuiUtil.drawIcon(icon, 0, 0, 0, 16, 16); - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationItemsTexture); +public class ItemRendererFluid implements IItemRenderer { - } + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return true; + } - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, - ItemRendererHelper helper) { - return false; - } + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + Fluid fluid = FluidRegistry.getFluid(item.getItemDamage()); + if (fluid == null) return; + IIcon icon = fluid.getIcon(); + if (icon == null) return; + float f = icon.getMinU(); + float f1 = icon.getMaxU(); + float f2 = icon.getMinV(); + float f3 = icon.getMaxV(); + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + GuiUtil.drawIcon(icon, 0, 0, 0, 16, 16); + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); + } + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return false; + } } diff --git a/src/main/scala/extracells/render/item/ItemRendererFluidPattern.java b/src/main/scala/extracells/render/item/ItemRendererFluidPattern.java index a329bbfef..49bcb3189 100644 --- a/src/main/scala/extracells/render/item/ItemRendererFluidPattern.java +++ b/src/main/scala/extracells/render/item/ItemRendererFluidPattern.java @@ -1,47 +1,43 @@ package extracells.render.item; -import extracells.registries.ItemEnum; -import extracells.util.GuiUtil; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; + import org.lwjgl.opengl.GL11; +import extracells.registries.ItemEnum; +import extracells.util.GuiUtil; + public class ItemRendererFluidPattern implements IItemRenderer { - @Override - public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { - return type != ItemRenderType.ENTITY; - } - - @Override - public void renderItem(ItemRenderType type, ItemStack itemStack, - Object... data) { - Item item = ItemEnum.FLUIDPATTERN.getItem(); - IIcon fluid = item.getIcon(itemStack, 0); - IIcon texture = item.getIcon(itemStack, 1); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - GL11.glColor3f(1, 1, 1); - - if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) - GL11.glTranslated(0, -10, 5); - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationBlocksTexture); - if (fluid != null) - GuiUtil.drawIcon(fluid, 5, 5, 0, 6, 6); - Minecraft.getMinecraft().renderEngine - .bindTexture(TextureMap.locationItemsTexture); - GL11.glTranslated(0, 0, 0.001F); - GuiUtil.drawIcon(texture, 0, 0, 0, 16, 16); - } - - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, - ItemStack itemStack, ItemRendererHelper helper) { - return type == ItemRenderType.ENTITY; - } + @Override + public boolean handleRenderType(ItemStack itemStack, ItemRenderType type) { + return type != ItemRenderType.ENTITY; + } + + @Override + public void renderItem(ItemRenderType type, ItemStack itemStack, Object... data) { + Item item = ItemEnum.FLUIDPATTERN.getItem(); + IIcon fluid = item.getIcon(itemStack, 0); + IIcon texture = item.getIcon(itemStack, 1); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + GL11.glColor3f(1, 1, 1); + + if (type == ItemRenderType.EQUIPPED_FIRST_PERSON) GL11.glTranslated(0, -10, 5); + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationBlocksTexture); + if (fluid != null) GuiUtil.drawIcon(fluid, 5, 5, 0, 6, 6); + Minecraft.getMinecraft().renderEngine.bindTexture(TextureMap.locationItemsTexture); + GL11.glTranslated(0, 0, 0.001F); + GuiUtil.drawIcon(texture, 0, 0, 0, 16, 16); + } + + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack itemStack, ItemRendererHelper helper) { + return type == ItemRenderType.ENTITY; + } } diff --git a/src/main/scala/extracells/render/item/ItemRendererWalrus.java b/src/main/scala/extracells/render/item/ItemRendererWalrus.java index 0e55195da..8ff06968b 100644 --- a/src/main/scala/extracells/render/item/ItemRendererWalrus.java +++ b/src/main/scala/extracells/render/item/ItemRendererWalrus.java @@ -6,48 +6,46 @@ import net.minecraftforge.client.IItemRenderer; import net.minecraftforge.client.model.AdvancedModelLoader; import net.minecraftforge.client.model.IModelCustom; + import org.lwjgl.opengl.GL11; public class ItemRendererWalrus implements IItemRenderer { - IModelCustom modelWalrus = AdvancedModelLoader - .loadModel(new ResourceLocation("extracells", "models/walrus.obj")); - ResourceLocation textureWalrus = new ResourceLocation("extracells", - "textures/blocks/walrus.png"); + IModelCustom modelWalrus = AdvancedModelLoader.loadModel(new ResourceLocation("extracells", "models/walrus.obj")); + ResourceLocation textureWalrus = new ResourceLocation("extracells", "textures/blocks/walrus.png"); - @Override - public boolean handleRenderType(ItemStack item, ItemRenderType type) { - return true; - } + @Override + public boolean handleRenderType(ItemStack item, ItemRenderType type) { + return true; + } - @Override - public void renderItem(ItemRenderType type, ItemStack item, Object... data) { - Minecraft.getMinecraft().renderEngine.bindTexture(this.textureWalrus); - GL11.glPushMatrix(); - switch (type) { - case ENTITY: - break; - case EQUIPPED: - break; - case EQUIPPED_FIRST_PERSON: - GL11.glRotated(180, 0, 1, 0); - GL11.glTranslatef(-1F, 0.5F, -0.5F); - break; - case FIRST_PERSON_MAP: - break; - case INVENTORY: - GL11.glTranslatef(-0.5F, -0.5F, -0.1F); - break; - default: - break; - } - this.modelWalrus.renderAll(); - GL11.glPopMatrix(); - } + @Override + public void renderItem(ItemRenderType type, ItemStack item, Object... data) { + Minecraft.getMinecraft().renderEngine.bindTexture(this.textureWalrus); + GL11.glPushMatrix(); + switch (type) { + case ENTITY: + break; + case EQUIPPED: + break; + case EQUIPPED_FIRST_PERSON: + GL11.glRotated(180, 0, 1, 0); + GL11.glTranslatef(-1F, 0.5F, -0.5F); + break; + case FIRST_PERSON_MAP: + break; + case INVENTORY: + GL11.glTranslatef(-0.5F, -0.5F, -0.1F); + break; + default: + break; + } + this.modelWalrus.renderAll(); + GL11.glPopMatrix(); + } - @Override - public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, - ItemRendererHelper helper) { - return true; - } + @Override + public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { + return true; + } } diff --git a/src/main/scala/extracells/render/model/ModelCertusTank.java b/src/main/scala/extracells/render/model/ModelCertusTank.java index d686932cb..b7b2a5713 100644 --- a/src/main/scala/extracells/render/model/ModelCertusTank.java +++ b/src/main/scala/extracells/render/model/ModelCertusTank.java @@ -1,6 +1,5 @@ package extracells.render.model; -import extracells.tileentity.TileEntityCertusTank; import net.minecraft.block.Block; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; @@ -12,138 +11,132 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; -import org.lwjgl.opengl.GL11; -public class ModelCertusTank extends ModelBase { +import org.lwjgl.opengl.GL11; - ModelRenderer Shape1; +import extracells.tileentity.TileEntityCertusTank; - public ModelCertusTank() { - this.textureWidth = 64; - this.textureHeight = 64; +public class ModelCertusTank extends ModelBase { - this.Shape1 = new ModelRenderer(this, 0, 0); - this.Shape1.addBox(0F, 0F, 0F, 14, 16, 14); - this.Shape1.setRotationPoint(-7F, -8F, -7F); - this.Shape1.setTextureSize(this.textureWidth, this.textureHeight); - this.Shape1.mirror = true; - setRotation(this.Shape1, 0F, 0F, 0F); + ModelRenderer Shape1; - } + public ModelCertusTank() { + this.textureWidth = 64; + this.textureHeight = 64; - public void render(float f) { - this.Shape1.render(f); - } + this.Shape1 = new ModelRenderer(this, 0, 0); + this.Shape1.addBox(0F, 0F, 0F, 14, 16, 14); + this.Shape1.setRotationPoint(-7F, -8F, -7F); + this.Shape1.setTextureSize(this.textureWidth, this.textureHeight); + this.Shape1.mirror = true; + setRotation(this.Shape1, 0F, 0F, 0F); + } - public void renderFluid(TileEntity tileEntity, double x, double y, - double z, RenderBlocks renderer) { - Tessellator tessellator = Tessellator.instance; - if (tileEntity != null - && ((TileEntityCertusTank) tileEntity).getTankInfo(ForgeDirection.UNKNOWN)[0].fluid != null) { - Fluid storedFluid = ((TileEntityCertusTank) tileEntity) - .getRenderFluid(); - float scale = ((TileEntityCertusTank) tileEntity).getRenderScale(); - if (storedFluid != null && scale > 0) { - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - Block id = Block.getBlockById(FluidRegistry.WATER.getID()); - IIcon fluidIcon = storedFluid.getIcon(); - if (fluidIcon == null) - fluidIcon = FluidRegistry.LAVA.getIcon(); - renderer.setRenderBounds(0.08F, 0.001F, 0.08F, 0.92, - scale * 0.999F, 0.92F); - tessellator.setNormal(0.0F, -1F, 0.0F); - renderer.renderFaceYNeg(id, x, y, z, fluidIcon); - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(id, x, y, z, fluidIcon); - tessellator.setNormal(0.0F, 0.0F, -1F); - renderer.renderFaceZNeg(id, x, y, z, fluidIcon); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(id, x, y, z, fluidIcon); - tessellator.setNormal(-1F, 0.0F, 0.0F); - renderer.renderFaceXNeg(id, x, y, z, fluidIcon); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(id, x, y, z, fluidIcon); - } - } - } + public void render(float f) { + this.Shape1.render(f); + } - public void renderInnerBlock(Block block, int x, int y, int z, - RenderBlocks renderer, IBlockAccess world) { - Tessellator tessellator = Tessellator.instance; - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - tessellator.setBrightness(15728640); - boolean tankUp = world.getTileEntity(x, y + 1, z) instanceof TileEntityCertusTank; - boolean tankDown = world.getTileEntity(x, y - 1, z) instanceof TileEntityCertusTank; - int meta = 0; - if (tankUp && tankDown) - meta = 3; - else if (tankUp) - meta = 2; - else if (tankDown) - meta = 1; - if (!tankUp) { - tessellator.setNormal(0, -1, 0); - renderer.renderFaceYNeg(block, x, y + 0.99F, z, block.getIcon(1, 0)); - } - if (!tankDown) { - tessellator.setNormal(0, 1, 0); - renderer.renderFaceYPos(block, x, y - 0.99F, z, block.getIcon(0, 0)); - } - IIcon sideIcon = block.getIcon(3, meta); - tessellator.setNormal(0, 0, -1); - renderer.renderFaceZNeg(block, x, y, z + 0.875F, sideIcon); - tessellator.setNormal(0, 0, 1); - renderer.renderFaceZPos(block, x, y, z - 0.875F, sideIcon); - tessellator.setNormal(-1, 0, 0); - renderer.renderFaceXNeg(block, x + 0.875F, y, z, sideIcon); - tessellator.setNormal(1, 0, 0); - renderer.renderFaceXPos(block, x - 0.875F, y, z, sideIcon); - GL11.glPopMatrix(); - } + public void renderFluid(TileEntity tileEntity, double x, double y, double z, RenderBlocks renderer) { + Tessellator tessellator = Tessellator.instance; + if (tileEntity != null + && ((TileEntityCertusTank) tileEntity).getTankInfo(ForgeDirection.UNKNOWN)[0].fluid != null) { + Fluid storedFluid = ((TileEntityCertusTank) tileEntity).getRenderFluid(); + float scale = ((TileEntityCertusTank) tileEntity).getRenderScale(); + if (storedFluid != null && scale > 0) { + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + Block id = Block.getBlockById(FluidRegistry.WATER.getID()); + IIcon fluidIcon = storedFluid.getIcon(); + if (fluidIcon == null) fluidIcon = FluidRegistry.LAVA.getIcon(); + renderer.setRenderBounds(0.08F, 0.001F, 0.08F, 0.92, scale * 0.999F, 0.92F); + tessellator.setColorRGBA_F( + (storedFluid.getColor() >> 16 & 0xFF) / 255.0F, + (storedFluid.getColor() >> 8 & 0xFF) / 255.0F, + (storedFluid.getColor() & 0xFF) / 255.0F, + 1.0F); + tessellator.setNormal(0.0F, -1F, 0.0F); + renderer.renderFaceYNeg(id, x, y, z, fluidIcon); + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(id, x, y, z, fluidIcon); + tessellator.setNormal(0.0F, 0.0F, -1F); + renderer.renderFaceZNeg(id, x, y, z, fluidIcon); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(id, x, y, z, fluidIcon); + tessellator.setNormal(-1F, 0.0F, 0.0F); + renderer.renderFaceXNeg(id, x, y, z, fluidIcon); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(id, x, y, z, fluidIcon); + } + } + } - public void renderOuterBlock(Block block, int x, int y, int z, - RenderBlocks renderer, IBlockAccess world) { - Tessellator tessellator = Tessellator.instance; - GL11.glPushMatrix(); - GL11.glEnable(GL11.GL_BLEND); - GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); - boolean tankUp = world.getTileEntity(x, y + 1, z) instanceof TileEntityCertusTank; - boolean tankDown = world.getTileEntity(x, y - 1, z) instanceof TileEntityCertusTank; - int meta = 0; - if (tankUp && tankDown) - meta = 3; - else if (tankUp) - meta = 2; - else if (tankDown) - meta = 1; - if (!tankDown) { - tessellator.setNormal(0.0F, -1F, 0.0F); - renderer.renderFaceYNeg(block, x, y, z, block.getIcon(0, 0)); - } - if (!tankUp) { - tessellator.setNormal(0.0F, 1.0F, 0.0F); - renderer.renderFaceYPos(block, x, y, z, block.getIcon(1, 0)); - } + public void renderInnerBlock(Block block, int x, int y, int z, RenderBlocks renderer, IBlockAccess world) { + Tessellator tessellator = Tessellator.instance; + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + tessellator.setBrightness(15728640); + boolean tankUp = world.getTileEntity(x, y + 1, z) instanceof TileEntityCertusTank; + boolean tankDown = world.getTileEntity(x, y - 1, z) instanceof TileEntityCertusTank; + int meta = 0; + if (tankUp && tankDown) meta = 3; + else if (tankUp) meta = 2; + else if (tankDown) meta = 1; + if (!tankUp) { + tessellator.setNormal(0, -1, 0); + renderer.renderFaceYNeg(block, x, y + 0.99F, z, block.getIcon(1, 0)); + } + if (!tankDown) { + tessellator.setNormal(0, 1, 0); + renderer.renderFaceYPos(block, x, y - 0.99F, z, block.getIcon(0, 0)); + } + IIcon sideIcon = block.getIcon(3, meta); + tessellator.setNormal(0, 0, -1); + renderer.renderFaceZNeg(block, x, y, z + 0.875F, sideIcon); + tessellator.setNormal(0, 0, 1); + renderer.renderFaceZPos(block, x, y, z - 0.875F, sideIcon); + tessellator.setNormal(-1, 0, 0); + renderer.renderFaceXNeg(block, x + 0.875F, y, z, sideIcon); + tessellator.setNormal(1, 0, 0); + renderer.renderFaceXPos(block, x - 0.875F, y, z, sideIcon); + GL11.glPopMatrix(); + } - IIcon sideIcon = block.getIcon(3, meta); - tessellator.setNormal(0.0F, 0.0F, -1F); - renderer.renderFaceZNeg(block, x, y, z, sideIcon); - tessellator.setNormal(0.0F, 0.0F, 1.0F); - renderer.renderFaceZPos(block, x, y, z, sideIcon); - tessellator.setNormal(-1F, 0.0F, 0.0F); - renderer.renderFaceXNeg(block, x, y, z, sideIcon); - tessellator.setNormal(1.0F, 0.0F, 0.0F); - renderer.renderFaceXPos(block, x, y, z, sideIcon); - GL11.glPopMatrix(); - } + public void renderOuterBlock(Block block, int x, int y, int z, RenderBlocks renderer, IBlockAccess world) { + Tessellator tessellator = Tessellator.instance; + GL11.glPushMatrix(); + GL11.glEnable(GL11.GL_BLEND); + GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); + boolean tankUp = world.getTileEntity(x, y + 1, z) instanceof TileEntityCertusTank; + boolean tankDown = world.getTileEntity(x, y - 1, z) instanceof TileEntityCertusTank; + int meta = 0; + if (tankUp && tankDown) meta = 3; + else if (tankUp) meta = 2; + else if (tankDown) meta = 1; + if (!tankDown) { + tessellator.setNormal(0.0F, -1F, 0.0F); + renderer.renderFaceYNeg(block, x, y, z, block.getIcon(0, 0)); + } + if (!tankUp) { + tessellator.setNormal(0.0F, 1.0F, 0.0F); + renderer.renderFaceYPos(block, x, y, z, block.getIcon(1, 0)); + } - private void setRotation(ModelRenderer model, float x, float y, float z) { - model.rotateAngleX = x; - model.rotateAngleY = y; - model.rotateAngleZ = z; - } + IIcon sideIcon = block.getIcon(3, meta); + tessellator.setNormal(0.0F, 0.0F, -1F); + renderer.renderFaceZNeg(block, x, y, z, sideIcon); + tessellator.setNormal(0.0F, 0.0F, 1.0F); + renderer.renderFaceZPos(block, x, y, z, sideIcon); + tessellator.setNormal(-1F, 0.0F, 0.0F); + renderer.renderFaceXNeg(block, x, y, z, sideIcon); + tessellator.setNormal(1.0F, 0.0F, 0.0F); + renderer.renderFaceXPos(block, x, y, z, sideIcon); + GL11.glPopMatrix(); + } + private void setRotation(ModelRenderer model, float x, float y, float z) { + model.rotateAngleX = x; + model.rotateAngleY = y; + model.rotateAngleZ = z; + } } diff --git a/src/main/scala/extracells/render/tileentity/TileEntityRendererWalrus.java b/src/main/scala/extracells/render/tileentity/TileEntityRendererWalrus.java index 5230b7b21..2befdbad9 100644 --- a/src/main/scala/extracells/render/tileentity/TileEntityRendererWalrus.java +++ b/src/main/scala/extracells/render/tileentity/TileEntityRendererWalrus.java @@ -6,30 +6,28 @@ import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.AdvancedModelLoader; import net.minecraftforge.client.model.IModelCustom; + import org.lwjgl.opengl.GL11; public class TileEntityRendererWalrus extends TileEntitySpecialRenderer { - IModelCustom modelWalrus = AdvancedModelLoader - .loadModel(new ResourceLocation("extracells", "models/walrus.obj")); - ResourceLocation textureWalrus = new ResourceLocation("extracells", - "textures/blocks/walrus.png"); + IModelCustom modelWalrus = AdvancedModelLoader.loadModel(new ResourceLocation("extracells", "models/walrus.obj")); + ResourceLocation textureWalrus = new ResourceLocation("extracells", "textures/blocks/walrus.png"); - @Override - public void renderTileEntityAt(TileEntity tileentity, double x, double y, - double z, float partialTickTime) { - Minecraft.getMinecraft().renderEngine.bindTexture(this.textureWalrus); - GL11.glPushMatrix(); - GL11.glTranslated(x + 0.5, y, z + 0.5); - int orientation = tileentity.getBlockMetadata(); - if (orientation == 4) { - GL11.glRotatef(90, 0, 1, 0); - } else if (orientation == 5) { - GL11.glRotatef(-90, 0, 1, 0); - } else if (orientation == 3) { - GL11.glRotatef(180, 0, 1, 0); - } - this.modelWalrus.renderAll(); - GL11.glPopMatrix(); - } + @Override + public void renderTileEntityAt(TileEntity tileentity, double x, double y, double z, float partialTickTime) { + Minecraft.getMinecraft().renderEngine.bindTexture(this.textureWalrus); + GL11.glPushMatrix(); + GL11.glTranslated(x + 0.5, y, z + 0.5); + int orientation = tileentity.getBlockMetadata(); + if (orientation == 4) { + GL11.glRotatef(90, 0, 1, 0); + } else if (orientation == 5) { + GL11.glRotatef(-90, 0, 1, 0); + } else if (orientation == 3) { + GL11.glRotatef(180, 0, 1, 0); + } + this.modelWalrus.renderAll(); + GL11.glPopMatrix(); + } } diff --git a/src/main/scala/extracells/tileentity/IListenerTile.java b/src/main/scala/extracells/tileentity/IListenerTile.java index e8e83e5b4..9eccc2765 100644 --- a/src/main/scala/extracells/tileentity/IListenerTile.java +++ b/src/main/scala/extracells/tileentity/IListenerTile.java @@ -4,10 +4,9 @@ public interface IListenerTile { - public void registerListener(); + public void registerListener(); - public void removeListener(); - - public void updateGrid(IGrid oldGrid, IGrid newGrid); + public void removeListener(); + public void updateGrid(IGrid oldGrid, IGrid newGrid); } diff --git a/src/main/scala/extracells/tileentity/TNetworkStorage.scala b/src/main/scala/extracells/tileentity/TNetworkStorage.scala index bf5c55c44..6947e9fee 100644 --- a/src/main/scala/extracells/tileentity/TNetworkStorage.scala +++ b/src/main/scala/extracells/tileentity/TNetworkStorage.scala @@ -6,12 +6,11 @@ import appeng.api.storage.IMEMonitor import appeng.api.storage.data.{IAEFluidStack, IAEItemStack} import net.minecraftforge.common.util.ForgeDirection - trait TNetworkStorage { def getStorageGrid(side: ForgeDirection): IStorageGrid = { - if(!this.isInstanceOf[IGridHost]) - return null + if (!this.isInstanceOf[IGridHost]) + return null val host = this.asInstanceOf[IGridHost] if (host.getGridNode(side) == null) return null val grid: IGrid = host.getGridNode(side).getGrid diff --git a/src/main/scala/extracells/tileentity/TPowerStorage.scala b/src/main/scala/extracells/tileentity/TPowerStorage.scala index 2a6818af9..cccd0a008 100644 --- a/src/main/scala/extracells/tileentity/TPowerStorage.scala +++ b/src/main/scala/extracells/tileentity/TPowerStorage.scala @@ -4,8 +4,7 @@ import appeng.api.config.{AccessRestriction, Actionable, PowerMultiplier} import appeng.api.networking.energy.IAEPowerStorage import net.minecraft.nbt.NBTTagCompound - -trait TPowerStorage extends IAEPowerStorage{ +trait TPowerStorage extends IAEPowerStorage { val powerInformation = new PowerInformation @@ -15,41 +14,45 @@ trait TPowerStorage extends IAEPowerStorage{ override def getAEMaxPower = powerInformation.maxPower - def setMaxPower(power: Double):Unit = powerInformation.maxPower = power + def setMaxPower(power: Double): Unit = powerInformation.maxPower = power override def injectAEPower(amt: Double, mode: Actionable) = { val maxStore = powerInformation.maxPower - powerInformation.currentPower val notStorred = { - if(maxStore - amt >= 0) + if (maxStore - amt >= 0) 0 else amt - maxStore } - if(mode == Actionable.MODULATE) + if (mode == Actionable.MODULATE) powerInformation.currentPower += amt - notStorred notStorred } override def isAEPublicPowerStorage = true - override def extractAEPower(amount: Double, mode: Actionable, usePowerMultiplier : PowerMultiplier) = { + override def extractAEPower( + amount: Double, + mode: Actionable, + usePowerMultiplier: PowerMultiplier + ) = { val toExtract = Math.min(amount, powerInformation.currentPower) if (mode == Actionable.MODULATE) powerInformation.currentPower -= toExtract toExtract } - def readPowerFromNBT(tag: NBTTagCompound)= { - if(tag.hasKey("currenPowerBattery")) + def readPowerFromNBT(tag: NBTTagCompound) = { + if (tag.hasKey("currenPowerBattery")) powerInformation.currentPower = tag.getDouble("currenPowerBattery") } - def writePowerToNBT(tag: NBTTagCompound) = tag.setDouble("currenPowerBattery", powerInformation.currentPower) - + def writePowerToNBT(tag: NBTTagCompound) = + tag.setDouble("currenPowerBattery", powerInformation.currentPower) - class PowerInformation{ - var currentPower = 0.0D + class PowerInformation { + var currentPower = 0.0d - var maxPower = 500.0D + var maxPower = 500.0d } } diff --git a/src/main/scala/extracells/tileentity/TileBase.scala b/src/main/scala/extracells/tileentity/TileBase.scala index c19d880ce..8c5a5d704 100644 --- a/src/main/scala/extracells/tileentity/TileBase.scala +++ b/src/main/scala/extracells/tileentity/TileBase.scala @@ -2,7 +2,4 @@ package extracells.tileentity import net.minecraft.tileentity.TileEntity - -class TileBase extends TileEntity with TNetworkStorage{ - -} +class TileBase extends TileEntity with TNetworkStorage {} diff --git a/src/main/scala/extracells/tileentity/TileEntityCertusTank.java b/src/main/scala/extracells/tileentity/TileEntityCertusTank.java index 11dcbd380..b69ff8a88 100644 --- a/src/main/scala/extracells/tileentity/TileEntityCertusTank.java +++ b/src/main/scala/extracells/tileentity/TileEntityCertusTank.java @@ -1,6 +1,5 @@ package extracells.tileentity; -import extracells.network.ChannelHandler; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; @@ -9,301 +8,269 @@ import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.*; +import extracells.network.ChannelHandler; + public class TileEntityCertusTank extends TileEntity implements IFluidHandler { - private FluidStack lastBeforeUpdate = null; - public FluidTank tank = new FluidTank(32000) { - - @Override - public FluidTank readFromNBT(NBTTagCompound nbt) { - if (!nbt.hasKey("Empty")) { - FluidStack fluid = FluidStack.loadFluidStackFromNBT(nbt); - setFluid(fluid); - } else { - setFluid(null); - } - return this; - } - }; - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - return this.tank.getFluid() == null - || this.tank.getFluid().getFluid() == fluid; - } - - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return this.tank.getFluid() == null - || this.tank.getFluid().getFluid() == fluid; - } - - public void compareAndUpdate() { - if (!this.worldObj.isRemote) { - FluidStack current = this.tank.getFluid(); - - if (current != null) { - if (this.lastBeforeUpdate != null) { - if (Math.abs(current.amount - this.lastBeforeUpdate.amount) >= 500) { - ChannelHandler.sendPacketToAllPlayers( - getDescriptionPacket(), this.worldObj); - this.lastBeforeUpdate = current.copy(); - } else if (this.lastBeforeUpdate.amount < this.tank - .getCapacity() - && current.amount == this.tank.getCapacity() - || this.lastBeforeUpdate.amount == this.tank - .getCapacity() - && current.amount < this.tank.getCapacity()) { - ChannelHandler.sendPacketToAllPlayers( - getDescriptionPacket(), this.worldObj); - this.lastBeforeUpdate = current.copy(); - } - } else { - ChannelHandler.sendPacketToAllPlayers( - getDescriptionPacket(), this.worldObj); - this.lastBeforeUpdate = current.copy(); - } - } else if (this.lastBeforeUpdate != null) { - ChannelHandler.sendPacketToAllPlayers(getDescriptionPacket(), - this.worldObj); - this.lastBeforeUpdate = null; - } - } - } - - /* Multiblock stuff */ - public FluidStack drain(FluidStack fluid, boolean doDrain, - boolean findMainTank) { - if (findMainTank) { - int yOff = 0; - TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord + yOff, this.zCoord); - TileEntityCertusTank mainTank = this; - while (true) { - if (offTE != null && offTE instanceof TileEntityCertusTank) { - Fluid offFluid = ((TileEntityCertusTank) offTE).getFluid(); - if (offFluid != null && offFluid == fluid.getFluid()) { - mainTank = (TileEntityCertusTank) this.worldObj - .getTileEntity(this.xCoord, this.yCoord + yOff, - this.zCoord); - yOff++; - offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord + yOff, this.zCoord); - continue; - } - } - break; - } - - return mainTank != null ? mainTank.drain(fluid, doDrain, false) - : null; - } - - FluidStack drained = this.tank.drain(fluid.amount, doDrain); - compareAndUpdate(); - - if (drained == null || drained.amount < fluid.amount) { - TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord - 1, this.zCoord); - if (offTE instanceof TileEntityCertusTank) { - TileEntityCertusTank tank = (TileEntityCertusTank) offTE; - FluidStack externallyDrained = tank.drain(new FluidStack( - fluid.getFluid(), fluid.amount - - (drained != null ? drained.amount : 0)), - doDrain, false); - - if (externallyDrained != null) - return new FluidStack(fluid.getFluid(), - (drained != null ? drained.amount : 0) - + externallyDrained.amount); - else - return drained; - } - } - - return drained; - } - - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, - boolean doDrain) { - if (this.tank.getFluid() == null || resource == null - || resource.getFluid() != this.tank.getFluid().getFluid()) - return null; - - return drain(resource, doDrain, true); - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - if (this.tank.getFluid() == null) - return null; - - return drain(from, new FluidStack(this.tank.getFluid(), maxDrain), - doDrain); - } - - public int fill(FluidStack fluid, boolean doFill, boolean findMainTank) { - if (findMainTank) { - int yOff = 0; - TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord - yOff, this.zCoord); - TileEntityCertusTank mainTank = this; - while (true) { - if (offTE != null && offTE instanceof TileEntityCertusTank) { - Fluid offFluid = ((TileEntityCertusTank) offTE).getFluid(); - if (offFluid == null || offFluid == fluid.getFluid()) { - mainTank = (TileEntityCertusTank) this.worldObj - .getTileEntity(this.xCoord, this.yCoord - yOff, - this.zCoord); - yOff++; - offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord - yOff, this.zCoord); - continue; - } - } - break; - } - - return mainTank != null ? mainTank.fill(fluid, doFill, false) : 0; - } - - int filled = this.tank.fill(fluid, doFill); - compareAndUpdate(); - - if (filled < fluid.amount) { - TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord + 1, this.zCoord); - if (offTE instanceof TileEntityCertusTank) { - TileEntityCertusTank tank = (TileEntityCertusTank) offTE; - return filled - + tank.fill(new FluidStack(fluid.getFluid(), fluid.amount - - filled), doFill, false); - } - } - - return filled; - } - - /* IFluidHandler */ - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - if (resource == null || this.tank.getFluid() != null - && resource.getFluid() != this.tank.getFluid().getFluid()) - return 0; - return fill(resource, doFill, true); - } - - @Override - public Packet getDescriptionPacket() { - NBTTagCompound nbtTag = new NBTTagCompound(); - writeToNBT(nbtTag); - return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, - this.zCoord, 1, nbtTag); - } - - public Fluid getFluid() { - FluidStack tankFluid = this.tank.getFluid(); - return tankFluid != null && tankFluid.amount > 0 ? tankFluid.getFluid() - : null; - } - - public Fluid getRenderFluid() { - return this.tank.getFluid() != null ? this.tank.getFluid().getFluid() - : null; - } - - public float getRenderScale() { - return (float) this.tank.getFluidAmount() / this.tank.getCapacity(); - } - - public FluidTankInfo[] getTankInfo(boolean goToMainTank) { - if (!goToMainTank) - return new FluidTankInfo[] { this.tank.getInfo() }; - - int amount = 0, capacity = 0; - Fluid fluid = null; - - int yOff = 0; - TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord - - yOff, this.zCoord); - TileEntityCertusTank mainTank = this; - while (true) { - if (offTE != null && offTE instanceof TileEntityCertusTank) { - if (((TileEntityCertusTank) offTE).getFluid() == null - || ((TileEntityCertusTank) offTE).getFluid() == getFluid()) { - mainTank = (TileEntityCertusTank) this.worldObj - .getTileEntity(this.xCoord, this.yCoord - yOff, - this.zCoord); - yOff++; - offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord - yOff, this.zCoord); - continue; - } - } - break; - } - - yOff = 0; - offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + yOff, - this.zCoord); - while (true) { - if (offTE != null && offTE instanceof TileEntityCertusTank) { - mainTank = (TileEntityCertusTank) offTE; - if (mainTank.getFluid() == null - || mainTank.getFluid() == getFluid()) { - FluidTankInfo info = mainTank.getTankInfo(false)[0]; - if (info != null) { - capacity += info.capacity; - if (info.fluid != null) { - amount += info.fluid.amount; - if (info.fluid.getFluid() != null) - fluid = info.fluid.getFluid(); - } - } - yOff++; - offTE = this.worldObj.getTileEntity(this.xCoord, - this.yCoord + yOff, this.zCoord); - continue; - } - } - break; - } - - return new FluidTankInfo[] { new FluidTankInfo( - fluid != null ? new FluidStack(fluid, amount) : null, capacity) }; - } - - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - return getTankInfo(true); - } - - @Override - public void onDataPacket(NetworkManager net, - S35PacketUpdateTileEntity packet) { - this.worldObj.markBlockRangeForRenderUpdate(this.xCoord, this.yCoord, - this.zCoord, this.xCoord, this.yCoord, this.zCoord); - readFromNBT(packet.func_148857_g()); - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - readFromNBTWithoutCoords(tag); - } - - public void readFromNBTWithoutCoords(NBTTagCompound tag) { - this.tank.readFromNBT(tag); - } - - @Override - public void writeToNBT(NBTTagCompound tag) { - super.writeToNBT(tag); - writeToNBTWithoutCoords(tag); - } - - public void writeToNBTWithoutCoords(NBTTagCompound tag) { - this.tank.writeToNBT(tag); - } -} \ No newline at end of file + private FluidStack lastBeforeUpdate = null; + public FluidTank tank = new FluidTank(32000) { + + @Override + public FluidTank readFromNBT(NBTTagCompound nbt) { + if (!nbt.hasKey("Empty")) { + FluidStack fluid = FluidStack.loadFluidStackFromNBT(nbt); + setFluid(fluid); + } else { + setFluid(null); + } + return this; + } + }; + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + return this.tank.getFluid() == null || this.tank.getFluid().getFluid() == fluid; + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return this.tank.getFluid() == null || this.tank.getFluid().getFluid() == fluid; + } + + public void compareAndUpdate() { + if (!this.worldObj.isRemote) { + FluidStack current = this.tank.getFluid(); + + if (current != null) { + if (this.lastBeforeUpdate != null) { + if (Math.abs(current.amount - this.lastBeforeUpdate.amount) >= 500) { + ChannelHandler.sendPacketToAllPlayers(getDescriptionPacket(), this.worldObj); + this.lastBeforeUpdate = current.copy(); + } else if (this.lastBeforeUpdate.amount < this.tank.getCapacity() + && current.amount == this.tank.getCapacity() + || this.lastBeforeUpdate.amount == this.tank.getCapacity() + && current.amount < this.tank.getCapacity()) { + ChannelHandler.sendPacketToAllPlayers(getDescriptionPacket(), this.worldObj); + this.lastBeforeUpdate = current.copy(); + } + } else { + ChannelHandler.sendPacketToAllPlayers(getDescriptionPacket(), this.worldObj); + this.lastBeforeUpdate = current.copy(); + } + } else if (this.lastBeforeUpdate != null) { + ChannelHandler.sendPacketToAllPlayers(getDescriptionPacket(), this.worldObj); + this.lastBeforeUpdate = null; + } + } + } + + /* Multiblock stuff */ + public FluidStack drain(FluidStack fluid, boolean doDrain, boolean findMainTank) { + if (findMainTank) { + int yOff = 0; + TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + yOff, this.zCoord); + TileEntityCertusTank mainTank = this; + while (true) { + if (offTE != null && offTE instanceof TileEntityCertusTank) { + Fluid offFluid = ((TileEntityCertusTank) offTE).getFluid(); + if (offFluid != null && offFluid == fluid.getFluid()) { + mainTank = (TileEntityCertusTank) this.worldObj + .getTileEntity(this.xCoord, this.yCoord + yOff, this.zCoord); + yOff++; + offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + yOff, this.zCoord); + continue; + } + } + break; + } + + return mainTank != null ? mainTank.drain(fluid, doDrain, false) : null; + } + + FluidStack drained = this.tank.drain(fluid.amount, doDrain); + compareAndUpdate(); + + if (drained == null || drained.amount < fluid.amount) { + TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord - 1, this.zCoord); + if (offTE instanceof TileEntityCertusTank) { + TileEntityCertusTank tank = (TileEntityCertusTank) offTE; + FluidStack externallyDrained = tank.drain( + new FluidStack(fluid.getFluid(), fluid.amount - (drained != null ? drained.amount : 0)), + doDrain, + false); + + if (externallyDrained != null) return new FluidStack( + fluid.getFluid(), + (drained != null ? drained.amount : 0) + externallyDrained.amount); + else return drained; + } + } + + return drained; + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + if (this.tank.getFluid() == null || resource == null || resource.getFluid() != this.tank.getFluid().getFluid()) + return null; + + return drain(resource, doDrain, true); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + if (this.tank.getFluid() == null) return null; + + return drain(from, new FluidStack(this.tank.getFluid(), maxDrain), doDrain); + } + + public int fill(FluidStack fluid, boolean doFill, boolean findMainTank) { + if (findMainTank) { + int yOff = 0; + TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord - yOff, this.zCoord); + TileEntityCertusTank mainTank = this; + while (true) { + if (offTE != null && offTE instanceof TileEntityCertusTank) { + Fluid offFluid = ((TileEntityCertusTank) offTE).getFluid(); + if (offFluid == null || offFluid == fluid.getFluid()) { + mainTank = (TileEntityCertusTank) this.worldObj + .getTileEntity(this.xCoord, this.yCoord - yOff, this.zCoord); + yOff++; + offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord - yOff, this.zCoord); + continue; + } + } + break; + } + + return mainTank != null ? mainTank.fill(fluid, doFill, false) : 0; + } + + int filled = this.tank.fill(fluid, doFill); + compareAndUpdate(); + + if (filled < fluid.amount) { + TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + 1, this.zCoord); + if (offTE instanceof TileEntityCertusTank) { + TileEntityCertusTank tank = (TileEntityCertusTank) offTE; + return filled + tank.fill(new FluidStack(fluid.getFluid(), fluid.amount - filled), doFill, false); + } + } + + return filled; + } + + /* IFluidHandler */ + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + if (resource == null || this.tank.getFluid() != null && resource.getFluid() != this.tank.getFluid().getFluid()) + return 0; + return fill(resource, doFill, true); + } + + @Override + public Packet getDescriptionPacket() { + NBTTagCompound nbtTag = new NBTTagCompound(); + writeToNBT(nbtTag); + return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, nbtTag); + } + + public Fluid getFluid() { + FluidStack tankFluid = this.tank.getFluid(); + return tankFluid != null && tankFluid.amount > 0 ? tankFluid.getFluid() : null; + } + + public Fluid getRenderFluid() { + return this.tank.getFluid() != null ? this.tank.getFluid().getFluid() : null; + } + + public float getRenderScale() { + return (float) this.tank.getFluidAmount() / this.tank.getCapacity(); + } + + public FluidTankInfo[] getTankInfo(boolean goToMainTank) { + if (!goToMainTank) return new FluidTankInfo[] { this.tank.getInfo() }; + + int amount = 0, capacity = 0; + Fluid fluid = null; + + int yOff = 0; + TileEntity offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord - yOff, this.zCoord); + TileEntityCertusTank mainTank = this; + while (true) { + if (offTE != null && offTE instanceof TileEntityCertusTank) { + if (((TileEntityCertusTank) offTE).getFluid() == null + || ((TileEntityCertusTank) offTE).getFluid() == getFluid()) { + mainTank = (TileEntityCertusTank) this.worldObj + .getTileEntity(this.xCoord, this.yCoord - yOff, this.zCoord); + yOff++; + offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord - yOff, this.zCoord); + continue; + } + } + break; + } + + yOff = 0; + offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + yOff, this.zCoord); + while (true) { + if (offTE != null && offTE instanceof TileEntityCertusTank) { + mainTank = (TileEntityCertusTank) offTE; + if (mainTank.getFluid() == null || mainTank.getFluid() == getFluid()) { + FluidTankInfo info = mainTank.getTankInfo(false)[0]; + if (info != null) { + capacity += info.capacity; + if (info.fluid != null) { + amount += info.fluid.amount; + if (info.fluid.getFluid() != null) fluid = info.fluid.getFluid(); + } + } + yOff++; + offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + yOff, this.zCoord); + continue; + } + } + break; + } + + return new FluidTankInfo[] { + new FluidTankInfo(fluid != null ? new FluidStack(fluid, amount) : null, capacity) }; + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + return getTankInfo(true); + } + + @Override + public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity packet) { + this.worldObj.markBlockRangeForRenderUpdate( + this.xCoord, + this.yCoord, + this.zCoord, + this.xCoord, + this.yCoord, + this.zCoord); + readFromNBT(packet.func_148857_g()); + } + + @Override + public void readFromNBT(NBTTagCompound tag) { + super.readFromNBT(tag); + readFromNBTWithoutCoords(tag); + } + + public void readFromNBTWithoutCoords(NBTTagCompound tag) { + this.tank.readFromNBT(tag); + } + + @Override + public void writeToNBT(NBTTagCompound tag) { + super.writeToNBT(tag); + writeToNBTWithoutCoords(tag); + } + + public void writeToNBTWithoutCoords(NBTTagCompound tag) { + this.tank.writeToNBT(tag); + } +} diff --git a/src/main/scala/extracells/tileentity/TileEntityCraftingStorage.java b/src/main/scala/extracells/tileentity/TileEntityCraftingStorage.java new file mode 100644 index 000000000..41da94f97 --- /dev/null +++ b/src/main/scala/extracells/tileentity/TileEntityCraftingStorage.java @@ -0,0 +1,48 @@ +package extracells.tileentity; + +import static extracells.registries.BlockEnum.CRAFTINGSTORAGE; + +import net.minecraft.item.ItemStack; + +import appeng.tile.crafting.TileCraftingStorageTile; +import appeng.tile.crafting.TileCraftingTile; + +public class TileEntityCraftingStorage extends TileCraftingStorageTile { + + private static final int KILO_SCALAR = 1024; + + @Override + protected ItemStack getItemFromTile(final Object obj) { + final int storage = (int) ((TileCraftingTile) obj).getStorageBytes() / KILO_SCALAR; + + switch (storage) { + case 256: + return new ItemStack(CRAFTINGSTORAGE.getBlock(), 1, 0); + case 1024: + return new ItemStack(CRAFTINGSTORAGE.getBlock(), 1, 1); + case 4096: + return new ItemStack(CRAFTINGSTORAGE.getBlock(), 1, 2); + case 16384: + return new ItemStack(CRAFTINGSTORAGE.getBlock(), 1, 3); + } + return super.getItemFromTile(obj); + } + + @Override + public long getStorageBytes() { + if (this.worldObj == null || this.notLoaded()) return 0; + + switch (this.blockMetadata & 3) { + case 0: + return 256 * KILO_SCALAR; + case 1: + return 1024 * KILO_SCALAR; + case 2: + return 4096 * KILO_SCALAR; + case 3: + return 16384 * KILO_SCALAR; + default: + return 0; + } + } +} diff --git a/src/main/scala/extracells/tileentity/TileEntityFluidCrafter.java b/src/main/scala/extracells/tileentity/TileEntityFluidCrafter.java index 90b1a3cb2..ec721403d 100644 --- a/src/main/scala/extracells/tileentity/TileEntityFluidCrafter.java +++ b/src/main/scala/extracells/tileentity/TileEntityFluidCrafter.java @@ -1,5 +1,19 @@ package extracells.tileentity; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.implementations.ICraftingPatternItem; @@ -18,481 +32,462 @@ import extracells.api.IECTileEntity; import extracells.crafting.CraftingPattern; import extracells.gridblock.ECFluidGridBlock; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class TileEntityFluidCrafter extends TileBase implements IActionHost, - ICraftingProvider, ICraftingWatcherHost, IECTileEntity { - - private class FluidCrafterInventory implements IInventory { - - private ItemStack[] inv = new ItemStack[9]; - - @Override - public void closeInventory() {} - - @Override - public ItemStack decrStackSize(int slot, int amt) { - ItemStack stack = getStackInSlot(slot); - if (stack != null) { - if (stack.stackSize <= amt) { - setInventorySlotContents(slot, null); - } else { - stack = stack.splitStack(amt); - if (stack.stackSize == 0) { - setInventorySlotContents(slot, null); - } - } - } - TileEntityFluidCrafter.this.update = true; - return stack; - } - - @Override - public String getInventoryName() { - return "inventory.fluidCrafter"; - } - - @Override - public int getInventoryStackLimit() { - return 1; - } - - @Override - public int getSizeInventory() { - return this.inv.length; - } - - @Override - public ItemStack getStackInSlot(int slot) { - return this.inv[slot]; - } - - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return null; - } - - @Override - public boolean hasCustomInventoryName() { - return false; - } - - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - if (stack.getItem() instanceof ICraftingPatternItem) { - ICraftingPatternDetails details = ((ICraftingPatternItem) stack - .getItem()).getPatternForItem(stack, getWorldObj()); - return details != null && details.isCraftable(); - } - return false; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer player) { - return true; - } - - @Override - public void markDirty() {} - - @Override - public void openInventory() {} - - public void readFromNBT(NBTTagCompound tagCompound) { - - NBTTagList tagList = tagCompound.getTagList("Inventory", 10); - for (int i = 0; i < tagList.tagCount(); i++) { - NBTTagCompound tag = tagList.getCompoundTagAt(i); - byte slot = tag.getByte("Slot"); - if (slot >= 0 && slot < this.inv.length) { - this.inv[slot] = ItemStack.loadItemStackFromNBT(tag); - } - } - } - - @Override - public void setInventorySlotContents(int slot, ItemStack stack) { - this.inv[slot] = stack; - if (stack != null && stack.stackSize > getInventoryStackLimit()) { - stack.stackSize = getInventoryStackLimit(); - } - TileEntityFluidCrafter.this.update = true; - } - - public void writeToNBT(NBTTagCompound tagCompound) { - - NBTTagList itemList = new NBTTagList(); - for (int i = 0; i < this.inv.length; i++) { - ItemStack stack = this.inv[i]; - if (stack != null) { - NBTTagCompound tag = new NBTTagCompound(); - tag.setByte("Slot", (byte) i); - stack.writeToNBT(tag); - itemList.appendTag(tag); - } - } - tagCompound.setTag("Inventory", itemList); - } - - } - - private ECFluidGridBlock gridBlock; - private IGridNode node = null; - private List patternHandlers = new ArrayList(); - private List requestedItems = new ArrayList(); - private List removeList = new ArrayList(); - private ICraftingPatternDetails[] patternHandlerSlot = new ICraftingPatternDetails[9]; - private ItemStack[] oldStack = new ItemStack[9]; - private boolean isBusy = false; - - private ICraftingWatcher watcher = null; - - private boolean isFirstGetGridNode = true; - - public final FluidCrafterInventory inventory; - private Long finishCraftingTime = 0L; - private ItemStack returnStack = null; - - private ItemStack[] optionalReturnStack = new ItemStack[0]; - - private boolean update = false; - - private final TileEntityFluidCrafter instance; - - public TileEntityFluidCrafter() { - super(); - this.gridBlock = new ECFluidGridBlock(this); - this.inventory = new FluidCrafterInventory(); - this.instance = this; - } - - @Override - public IGridNode getActionableNode() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) - return null; - if (this.node == null) { - this.node = AEApi.instance().createGridNode(this.gridBlock); - } - return this.node; - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) { - return AECableType.SMART; - } - - public IGridNode getGridNode() { - return getGridNode(ForgeDirection.UNKNOWN); - } - - @Override - public IGridNode getGridNode(ForgeDirection dir) { - if (FMLCommonHandler.instance().getSide().isClient() - && (getWorldObj() == null || getWorldObj().isRemote)) - return null; - if (this.isFirstGetGridNode) { - this.isFirstGetGridNode = false; - getActionableNode().updateState(); - } - return this.node; - } - - public IInventory getInventory() { - return this.inventory; - } - - @Override - public DimensionalCoord getLocation() { - return new DimensionalCoord(this); - } - - @Override - public double getPowerUsage() { - return 0; - } - - @Override - public boolean isBusy() { - return this.isBusy; - } - - @Override - public void onRequestChange(ICraftingGrid craftingGrid, IAEItemStack what) { - if (craftingGrid.isRequesting(what)) { - if (!this.requestedItems.contains(what)) { - this.requestedItems.add(what); - } - } else if (this.requestedItems.contains(what)) { - this.requestedItems.remove(what); - } - - } - - @Override - public void provideCrafting(ICraftingProviderHelper craftingTracker) { - this.patternHandlers = new ArrayList(); - ICraftingPatternDetails[] oldHandler = patternHandlerSlot; - patternHandlerSlot = new ICraftingPatternDetails[9]; - for (int i = 0; this.inventory.inv.length > i; i++) { - ItemStack currentPatternStack = this.inventory.inv[i]; - ItemStack oldItem = this.oldStack[i]; - if(currentPatternStack != null && oldItem != null && ItemStack.areItemStacksEqual(currentPatternStack, oldItem)){ - ICraftingPatternDetails pa = oldHandler[i]; - if(pa != null){ - patternHandlerSlot[i] = pa; - patternHandlers.add(pa); - if (pa.getCondensedInputs().length == 0) { - craftingTracker.setEmitable(pa.getCondensedOutputs()[0]); - } else { - craftingTracker.addCraftingOption(this, pa); - } - continue; - } - } - if (currentPatternStack != null - && currentPatternStack.getItem() != null - && currentPatternStack.getItem() instanceof ICraftingPatternItem) { - ICraftingPatternItem currentPattern = (ICraftingPatternItem) currentPatternStack - .getItem(); - - if (currentPattern != null - && currentPattern.getPatternForItem( - currentPatternStack, getWorldObj()) != null - && currentPattern.getPatternForItem( - currentPatternStack, getWorldObj()) - .isCraftable()) { - ICraftingPatternDetails pattern = new CraftingPattern( - currentPattern.getPatternForItem( - currentPatternStack, getWorldObj())); - this.patternHandlers.add(pattern); - this.patternHandlerSlot[i] = pattern; - if (pattern.getCondensedInputs().length == 0) { - craftingTracker.setEmitable(pattern - .getCondensedOutputs()[0]); - } else { - craftingTracker.addCraftingOption(this, pattern); - } - } - } - oldStack[i] = currentPatternStack; - } - updateWatcher(); - } - - @Override - public boolean pushPattern(ICraftingPatternDetails patternDetails, - InventoryCrafting table) { - if (this.isBusy) - return false; - if (patternDetails instanceof CraftingPattern) { - CraftingPattern patter = (CraftingPattern) patternDetails; - HashMap fluids = new HashMap(); - for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { - if (fluids.containsKey(stack.getFluid())) { - Long amount = fluids.get(stack.getFluid()) + stack.getStackSize(); - fluids.remove(stack.getFluid()); - fluids.put(stack.getFluid(), amount); - } else { - fluids.put(stack.getFluid(), stack.getStackSize()); - } - } - IGrid grid = this.node.getGrid(); - if (grid == null) - return false; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return false; - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory().extractItems(AEApi.instance().storage().createFluidStack(new FluidStack(fluid, (int) (amount + 0))), Actionable.SIMULATE, new MachineSource(this)); - if (extractFluid == null || extractFluid.getStackSize() != amount) { - return false; - } - } - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory().extractItems(AEApi.instance().storage().createFluidStack(new FluidStack(fluid, (int) (amount + 0))), Actionable.MODULATE, new MachineSource(this)); - } - this.finishCraftingTime = System.currentTimeMillis() + 1000; - - this.returnStack = patter.getOutput(table, getWorldObj()); - - this.optionalReturnStack = new ItemStack[9]; - for (int i = 0; i < 9; i++) { - ItemStack s = table.getStackInSlot(i); - if (s != null && s.getItem() != null) { - this.optionalReturnStack[i] = s.getItem().getContainerItem(s.copy()); - } - } - - this.isBusy = true; - } - return true; - } - - @Override - public void readFromNBT(NBTTagCompound tagCompound) { - super.readFromNBT(tagCompound); - this.inventory.readFromNBT(tagCompound); - if (hasWorldObj()) { - IGridNode node = getGridNode(); - if (tagCompound.hasKey("nodes") && node != null) { - node.loadFromNBT("node0", tagCompound.getCompoundTag("nodes")); - node.updateState(); - } - } - } - - @Override - public void securityBreak() { - - } - - @Override - public void updateEntity() { - if (getWorldObj() == null || getWorldObj().provider == null) - return; - if (this.update) { - this.update = false; - if (getGridNode() != null && getGridNode().getGrid() != null) { - getGridNode().getGrid().postEvent(new MENetworkCraftingPatternChange(this.instance, getGridNode())); - } - } - if (this.isBusy && this.finishCraftingTime <= System.currentTimeMillis() && getWorldObj() != null && !getWorldObj().isRemote) { - if (this.node == null || this.returnStack == null) - return; - IGrid grid = this.node.getGrid(); - if (grid == null) - return; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return; - storage.getItemInventory().injectItems(AEApi.instance().storage().createItemStack(this.returnStack), Actionable.MODULATE, new MachineSource(this)); - for (ItemStack s : this.optionalReturnStack) { - if (s == null) - continue; - storage.getItemInventory().injectItems(AEApi.instance().storage().createItemStack(s), Actionable.MODULATE, new MachineSource(this)); - } - this.optionalReturnStack = new ItemStack[0]; - this.isBusy = false; - this.returnStack = null; - } - if (!this.isBusy && getWorldObj() != null && !getWorldObj().isRemote) { - for (IAEItemStack stack : this.removeList) { - this.requestedItems.remove(stack); - } - this.removeList.clear(); - if (!this.requestedItems.isEmpty()) { - for (IAEItemStack s : this.requestedItems) { - IGrid grid = this.node.getGrid(); - if (grid == null) - break; - ICraftingGrid crafting = grid.getCache(ICraftingGrid.class); - if (crafting == null) - break; - if (!crafting.isRequesting(s)) { - this.removeList.add(s); - continue; - } - for (ICraftingPatternDetails details : this.patternHandlers) { - if (details.getCondensedOutputs()[0].equals(s)) { - CraftingPattern patter = (CraftingPattern) details; - HashMap fluids = new HashMap(); - for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { - if (fluids.containsKey(stack.getFluid())) { - Long amount = fluids.get(stack.getFluid()) + stack.getStackSize(); - fluids.remove(stack.getFluid()); - fluids.put(stack.getFluid(), amount); - } else { - fluids.put(stack.getFluid(), stack.getStackSize()); - } - } - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - break; - boolean doBreak = false; - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory().extractItems(AEApi.instance().storage().createFluidStack(new FluidStack(fluid, (int) (amount + 0))), Actionable.SIMULATE, new MachineSource(this)); - if (extractFluid == null || extractFluid.getStackSize() != amount) { - doBreak = true; - break; - } - } - if (doBreak) - break; - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory().extractItems(AEApi.instance().storage().createFluidStack(new FluidStack(fluid, (int) (amount + 0))), Actionable.MODULATE, new MachineSource(this)); - } - this.finishCraftingTime = System.currentTimeMillis() + 1000; - - this.returnStack = patter.getCondensedOutputs()[0].getItemStack(); - this.isBusy = true; - return; - } - } - } - } - } - } - - private void updateWatcher() { - this.requestedItems = new ArrayList(); - IGrid grid = null; - IGridNode node = getGridNode(); - ICraftingGrid crafting = null; - if (node != null) { - grid = node.getGrid(); - if (grid != null) { - crafting = grid.getCache(ICraftingGrid.class); - } - } - for (ICraftingPatternDetails patter : this.patternHandlers) { - this.watcher.clear(); - if (patter.getCondensedInputs().length == 0) { - this.watcher.add(patter.getCondensedOutputs()[0]); - - if (crafting != null) { - if (crafting.isRequesting(patter.getCondensedOutputs()[0])) { - this.requestedItems - .add(patter.getCondensedOutputs()[0]); - } - } - } - } - } - - @Override - public void updateWatcher(ICraftingWatcher newWatcher) { - this.watcher = newWatcher; - updateWatcher(); - } - - @Override - public void writeToNBT(NBTTagCompound tagCompound) { - super.writeToNBT(tagCompound); - this.inventory.writeToNBT(tagCompound); - if (!hasWorldObj()) - return; - IGridNode node = getGridNode(); - if (node != null) { - NBTTagCompound nodeTag = new NBTTagCompound(); - node.saveToNBT("node0", nodeTag); - tagCompound.setTag("nodes", nodeTag); - } - } +public class TileEntityFluidCrafter extends TileBase + implements IActionHost, ICraftingProvider, ICraftingWatcherHost, IECTileEntity { + + private class FluidCrafterInventory implements IInventory { + + private ItemStack[] inv = new ItemStack[9]; + + @Override + public void closeInventory() {} + + @Override + public ItemStack decrStackSize(int slot, int amt) { + ItemStack stack = getStackInSlot(slot); + if (stack != null) { + if (stack.stackSize <= amt) { + setInventorySlotContents(slot, null); + } else { + stack = stack.splitStack(amt); + if (stack.stackSize == 0) { + setInventorySlotContents(slot, null); + } + } + } + TileEntityFluidCrafter.this.update = true; + return stack; + } + + @Override + public String getInventoryName() { + return "inventory.fluidCrafter"; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public int getSizeInventory() { + return this.inv.length; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return this.inv[slot]; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return null; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + if (stack.getItem() instanceof ICraftingPatternItem) { + ICraftingPatternDetails details = ((ICraftingPatternItem) stack.getItem()) + .getPatternForItem(stack, getWorldObj()); + return details != null && details.isCraftable(); + } + return false; + } + + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + return true; + } + + @Override + public void markDirty() {} + + @Override + public void openInventory() {} + + public void readFromNBT(NBTTagCompound tagCompound) { + + NBTTagList tagList = tagCompound.getTagList("Inventory", 10); + for (int i = 0; i < tagList.tagCount(); i++) { + NBTTagCompound tag = tagList.getCompoundTagAt(i); + byte slot = tag.getByte("Slot"); + if (slot >= 0 && slot < this.inv.length) { + this.inv[slot] = ItemStack.loadItemStackFromNBT(tag); + } + } + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + this.inv[slot] = stack; + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + TileEntityFluidCrafter.this.update = true; + } + + public void writeToNBT(NBTTagCompound tagCompound) { + + NBTTagList itemList = new NBTTagList(); + for (int i = 0; i < this.inv.length; i++) { + ItemStack stack = this.inv[i]; + if (stack != null) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setByte("Slot", (byte) i); + stack.writeToNBT(tag); + itemList.appendTag(tag); + } + } + tagCompound.setTag("Inventory", itemList); + } + } + + private ECFluidGridBlock gridBlock; + private IGridNode node = null; + private List patternHandlers = new ArrayList(); + private List requestedItems = new ArrayList(); + private List removeList = new ArrayList(); + private ICraftingPatternDetails[] patternHandlerSlot = new ICraftingPatternDetails[9]; + private ItemStack[] oldStack = new ItemStack[9]; + private boolean isBusy = false; + + private ICraftingWatcher watcher = null; + + private boolean isFirstGetGridNode = true; + + public final FluidCrafterInventory inventory; + private Long finishCraftingTime = 0L; + private ItemStack returnStack = null; + + private ItemStack[] optionalReturnStack = new ItemStack[0]; + + private boolean update = false; + + private final TileEntityFluidCrafter instance; + + public TileEntityFluidCrafter() { + super(); + this.gridBlock = new ECFluidGridBlock(this); + this.inventory = new FluidCrafterInventory(); + this.instance = this; + } + + @Override + public IGridNode getActionableNode() { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return null; + if (this.node == null) { + this.node = AEApi.instance().createGridNode(this.gridBlock); + } + return this.node; + } + + @Override + public AECableType getCableConnectionType(ForgeDirection dir) { + return AECableType.SMART; + } + + public IGridNode getGridNode() { + return getGridNode(ForgeDirection.UNKNOWN); + } + + @Override + public IGridNode getGridNode(ForgeDirection dir) { + if (FMLCommonHandler.instance().getSide().isClient() && (getWorldObj() == null || getWorldObj().isRemote)) + return null; + if (this.isFirstGetGridNode) { + this.isFirstGetGridNode = false; + getActionableNode().updateState(); + } + return this.node; + } + + public IInventory getInventory() { + return this.inventory; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public double getPowerUsage() { + return 0; + } + + @Override + public boolean isBusy() { + return this.isBusy; + } + + @Override + public void onRequestChange(ICraftingGrid craftingGrid, IAEItemStack what) { + if (craftingGrid.isRequesting(what)) { + if (!this.requestedItems.contains(what)) { + this.requestedItems.add(what); + } + } else if (this.requestedItems.contains(what)) { + this.requestedItems.remove(what); + } + } + + @Override + public void provideCrafting(ICraftingProviderHelper craftingTracker) { + this.patternHandlers = new ArrayList(); + ICraftingPatternDetails[] oldHandler = patternHandlerSlot; + patternHandlerSlot = new ICraftingPatternDetails[9]; + for (int i = 0; this.inventory.inv.length > i; i++) { + ItemStack currentPatternStack = this.inventory.inv[i]; + ItemStack oldItem = this.oldStack[i]; + if (currentPatternStack != null && oldItem != null + && ItemStack.areItemStacksEqual(currentPatternStack, oldItem)) { + ICraftingPatternDetails pa = oldHandler[i]; + if (pa != null) { + patternHandlerSlot[i] = pa; + patternHandlers.add(pa); + if (pa.getCondensedInputs().length == 0) { + craftingTracker.setEmitable(pa.getCondensedOutputs()[0]); + } else { + craftingTracker.addCraftingOption(this, pa); + } + continue; + } + } + if (currentPatternStack != null && currentPatternStack.getItem() != null + && currentPatternStack.getItem() instanceof ICraftingPatternItem) { + ICraftingPatternItem currentPattern = (ICraftingPatternItem) currentPatternStack.getItem(); + + if (currentPattern != null + && currentPattern.getPatternForItem(currentPatternStack, getWorldObj()) != null + && currentPattern.getPatternForItem(currentPatternStack, getWorldObj()).isCraftable()) { + ICraftingPatternDetails pattern = new CraftingPattern( + currentPattern.getPatternForItem(currentPatternStack, getWorldObj())); + this.patternHandlers.add(pattern); + this.patternHandlerSlot[i] = pattern; + if (pattern.getCondensedInputs().length == 0) { + craftingTracker.setEmitable(pattern.getCondensedOutputs()[0]); + } else { + craftingTracker.addCraftingOption(this, pattern); + } + } + } + oldStack[i] = currentPatternStack; + } + updateWatcher(); + } + + @Override + public boolean pushPattern(ICraftingPatternDetails patternDetails, InventoryCrafting table) { + if (this.isBusy) return false; + if (patternDetails instanceof CraftingPattern) { + CraftingPattern patter = (CraftingPattern) patternDetails; + HashMap fluids = new HashMap(); + for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { + if (fluids.containsKey(stack.getFluid())) { + Long amount = fluids.get(stack.getFluid()) + stack.getStackSize(); + fluids.remove(stack.getFluid()); + fluids.put(stack.getFluid(), amount); + } else { + fluids.put(stack.getFluid(), stack.getStackSize()); + } + } + IGrid grid = this.node.getGrid(); + if (grid == null) return false; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return false; + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, (int) (amount + 0))), + Actionable.SIMULATE, + new MachineSource(this)); + if (extractFluid == null || extractFluid.getStackSize() != amount) { + return false; + } + } + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, (int) (amount + 0))), + Actionable.MODULATE, + new MachineSource(this)); + } + this.finishCraftingTime = System.currentTimeMillis() + 1000; + + this.returnStack = patter.getOutput(table, getWorldObj()); + + this.optionalReturnStack = new ItemStack[9]; + for (int i = 0; i < 9; i++) { + ItemStack s = table.getStackInSlot(i); + if (s != null && s.getItem() != null) { + this.optionalReturnStack[i] = s.getItem().getContainerItem(s.copy()); + } + } + + this.isBusy = true; + } + return true; + } + + @Override + public void readFromNBT(NBTTagCompound tagCompound) { + super.readFromNBT(tagCompound); + this.inventory.readFromNBT(tagCompound); + if (hasWorldObj()) { + IGridNode node = getGridNode(); + if (tagCompound.hasKey("nodes") && node != null) { + node.loadFromNBT("node0", tagCompound.getCompoundTag("nodes")); + node.updateState(); + } + } + } + + @Override + public void securityBreak() {} + + @Override + public void updateEntity() { + if (getWorldObj() == null || getWorldObj().provider == null) return; + if (this.update) { + this.update = false; + if (getGridNode() != null && getGridNode().getGrid() != null) { + getGridNode().getGrid().postEvent(new MENetworkCraftingPatternChange(this.instance, getGridNode())); + } + } + if (this.isBusy && this.finishCraftingTime <= System.currentTimeMillis() + && getWorldObj() != null + && !getWorldObj().isRemote) { + if (this.node == null || this.returnStack == null) return; + IGrid grid = this.node.getGrid(); + if (grid == null) return; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return; + storage.getItemInventory().injectItems( + AEApi.instance().storage().createItemStack(this.returnStack), + Actionable.MODULATE, + new MachineSource(this)); + for (ItemStack s : this.optionalReturnStack) { + if (s == null) continue; + storage.getItemInventory().injectItems( + AEApi.instance().storage().createItemStack(s), + Actionable.MODULATE, + new MachineSource(this)); + } + this.optionalReturnStack = new ItemStack[0]; + this.isBusy = false; + this.returnStack = null; + } + if (!this.isBusy && getWorldObj() != null && !getWorldObj().isRemote) { + for (IAEItemStack stack : this.removeList) { + this.requestedItems.remove(stack); + } + this.removeList.clear(); + if (!this.requestedItems.isEmpty()) { + for (IAEItemStack s : this.requestedItems) { + IGrid grid = this.node.getGrid(); + if (grid == null) break; + ICraftingGrid crafting = grid.getCache(ICraftingGrid.class); + if (crafting == null) break; + if (!crafting.isRequesting(s)) { + this.removeList.add(s); + continue; + } + for (ICraftingPatternDetails details : this.patternHandlers) { + if (details.getCondensedOutputs()[0].equals(s)) { + CraftingPattern patter = (CraftingPattern) details; + HashMap fluids = new HashMap(); + for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { + if (fluids.containsKey(stack.getFluid())) { + Long amount = fluids.get(stack.getFluid()) + stack.getStackSize(); + fluids.remove(stack.getFluid()); + fluids.put(stack.getFluid(), amount); + } else { + fluids.put(stack.getFluid(), stack.getStackSize()); + } + } + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) break; + boolean doBreak = false; + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage() + .createFluidStack(new FluidStack(fluid, (int) (amount + 0))), + Actionable.SIMULATE, + new MachineSource(this)); + if (extractFluid == null || extractFluid.getStackSize() != amount) { + doBreak = true; + break; + } + } + if (doBreak) break; + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage() + .createFluidStack(new FluidStack(fluid, (int) (amount + 0))), + Actionable.MODULATE, + new MachineSource(this)); + } + this.finishCraftingTime = System.currentTimeMillis() + 1000; + + this.returnStack = patter.getCondensedOutputs()[0].getItemStack(); + this.isBusy = true; + return; + } + } + } + } + } + } + + private void updateWatcher() { + this.requestedItems = new ArrayList(); + IGrid grid = null; + IGridNode node = getGridNode(); + ICraftingGrid crafting = null; + if (node != null) { + grid = node.getGrid(); + if (grid != null) { + crafting = grid.getCache(ICraftingGrid.class); + } + } + for (ICraftingPatternDetails patter : this.patternHandlers) { + this.watcher.clear(); + if (patter.getCondensedInputs().length == 0) { + this.watcher.add(patter.getCondensedOutputs()[0]); + + if (crafting != null) { + if (crafting.isRequesting(patter.getCondensedOutputs()[0])) { + this.requestedItems.add(patter.getCondensedOutputs()[0]); + } + } + } + } + } + + @Override + public void updateWatcher(ICraftingWatcher newWatcher) { + this.watcher = newWatcher; + updateWatcher(); + } + + @Override + public void writeToNBT(NBTTagCompound tagCompound) { + super.writeToNBT(tagCompound); + this.inventory.writeToNBT(tagCompound); + if (!hasWorldObj()) return; + IGridNode node = getGridNode(); + if (node != null) { + NBTTagCompound nodeTag = new NBTTagCompound(); + node.saveToNBT("node0", nodeTag); + tagCompound.setTag("nodes", nodeTag); + } + } } diff --git a/src/main/scala/extracells/tileentity/TileEntityFluidFiller.java b/src/main/scala/extracells/tileentity/TileEntityFluidFiller.java index bdd43329d..4dc7c3e4f 100644 --- a/src/main/scala/extracells/tileentity/TileEntityFluidFiller.java +++ b/src/main/scala/extracells/tileentity/TileEntityFluidFiller.java @@ -1,5 +1,23 @@ package extracells.tileentity; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.init.Items; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.Packet; +import net.minecraft.network.play.server.S35PacketUpdateTileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.Fluid; +import net.minecraftforge.fluids.FluidStack; + +import org.apache.commons.lang3.tuple.MutablePair; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.implementations.ICraftingPatternItem; @@ -27,347 +45,275 @@ import extracells.api.IECTileEntity; import extracells.gridblock.ECFluidGridBlock; import extracells.util.FluidUtil; -import net.minecraft.init.Items; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.Fluid; -import net.minecraftforge.fluids.FluidStack; -import org.apache.commons.lang3.tuple.MutablePair; - -import java.util.ArrayList; -import java.util.List; -public class TileEntityFluidFiller extends TileBase implements IActionHost, - ICraftingProvider, IECTileEntity, - IMEMonitorHandlerReceiver, IListenerTile { - - private ECFluidGridBlock gridBlock; - private IGridNode node = null; - List fluids = new ArrayList(); - public ItemStack containerItem = new ItemStack(Items.bucket); - ItemStack returnStack = null; - int ticksToFinish = 0; - - private boolean isFirstGetGridNode = true; - - private final Item encodedPattern = AEApi.instance().definitions().items().encodedPattern().maybeItem().orNull(); - - public TileEntityFluidFiller() { - super(); - this.gridBlock = new ECFluidGridBlock(this); - } - - @MENetworkEventSubscribe - public void cellUpdate(MENetworkCellArrayUpdate event) { - IStorageGrid storage = getStorageGrid(); - if (storage != null) - postChange(storage.getFluidInventory(), null, null); - } - - @Override - public IGridNode getActionableNode() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) - return null; - if (this.node == null) { - this.node = AEApi.instance().createGridNode(this.gridBlock); - } - return this.node; - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) { - return AECableType.DENSE; - } - - @Override - public Packet getDescriptionPacket() { - NBTTagCompound nbtTag = new NBTTagCompound(); - writeToNBT(nbtTag); - return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, - this.zCoord, 1, nbtTag); - } - - @Override - public IGridNode getGridNode(ForgeDirection dir) { - if (FMLCommonHandler.instance().getSide().isClient() - && (getWorldObj() == null || getWorldObj().isRemote)) - return null; - if (this.isFirstGetGridNode) { - this.isFirstGetGridNode = false; - getActionableNode().updateState(); - IStorageGrid storage = getStorageGrid(); - storage.getFluidInventory().addListener(this, null); - } - return this.node; - } - - @Override - public DimensionalCoord getLocation() { - return new DimensionalCoord(this); - } - - private ItemStack getPattern(ItemStack emptyContainer, - ItemStack filledContainer) { - NBTTagList in = new NBTTagList(); - NBTTagList out = new NBTTagList(); - in.appendTag(emptyContainer.writeToNBT(new NBTTagCompound())); - out.appendTag(filledContainer.writeToNBT(new NBTTagCompound())); - NBTTagCompound itemTag = new NBTTagCompound(); - itemTag.setTag("in", in); - itemTag.setTag("out", out); - itemTag.setBoolean("crafting", false); - ItemStack pattern = new ItemStack(this.encodedPattern); - pattern.setTagCompound(itemTag); - return pattern; - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - private IStorageGrid getStorageGrid() { - this.node = getGridNode(ForgeDirection.UNKNOWN); - if (this.node == null) - return null; - IGrid grid = this.node.getGrid(); - if (grid == null) - return null; - return grid.getCache(IStorageGrid.class); - } - - @Override - public boolean isBusy() { - return this.returnStack != null; - } - - @Override - public boolean isValid(Object verificationToken) { - return true; - } - - @Override - public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { - readFromNBT(pkt.func_148857_g()); - } - - @Override - public void onListUpdate() {} - - @Override - public void postChange(IBaseMonitor monitor, - Iterable change, BaseActionSource actionSource) { - List oldFluids = new ArrayList(this.fluids); - boolean mustUpdate = false; - this.fluids.clear(); - for (IAEFluidStack fluid : ((IMEMonitor) monitor) - .getStorageList()) { - if (!oldFluids.contains(fluid.getFluid())) - mustUpdate = true; - else - oldFluids.remove(fluid.getFluid()); - this.fluids.add(fluid.getFluid()); - } - if (!(oldFluids.isEmpty() && !mustUpdate)) { - if (getGridNode(ForgeDirection.UNKNOWN) != null - && getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) { - getGridNode(ForgeDirection.UNKNOWN).getGrid().postEvent( - new MENetworkCraftingPatternChange(this, - getGridNode(ForgeDirection.UNKNOWN))); - } - } - } - - public void postUpdateEvent() { - if (getGridNode(ForgeDirection.UNKNOWN) != null - && getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) { - getGridNode(ForgeDirection.UNKNOWN).getGrid().postEvent( - new MENetworkCraftingPatternChange(this, - getGridNode(ForgeDirection.UNKNOWN))); - } - } - - @MENetworkEventSubscribe - public void powerUpdate(MENetworkPowerStatusChange event) { - IStorageGrid storage = getStorageGrid(); - if (storage != null) - postChange(storage.getFluidInventory(), null, null); - } - - @Override - public void provideCrafting(ICraftingProviderHelper craftingTracker) { - IStorageGrid storage = getStorageGrid(); - if (storage == null) - return; - IMEMonitor fluidStorage = storage.getFluidInventory(); - for (IAEFluidStack fluidStack : fluidStorage.getStorageList()) { - Fluid fluid = fluidStack.getFluid(); - if (fluid == null) - continue; - int maxCapacity = FluidUtil.getCapacity(this.containerItem); - if (maxCapacity == 0) - continue; - MutablePair filled = FluidUtil.fillStack( - this.containerItem.copy(), new FluidStack(fluid, - maxCapacity)); - if (filled.right == null) - continue; - ItemStack pattern = getPattern(this.containerItem, filled.right); - ICraftingPatternItem patter = (ICraftingPatternItem) pattern - .getItem(); - craftingTracker.addCraftingOption(this, - patter.getPatternForItem(pattern, getWorldObj())); - } - - } - - @Override - public boolean pushPattern(ICraftingPatternDetails patternDetails, - InventoryCrafting table) { - if (this.returnStack != null) - return false; - ItemStack filled = patternDetails.getCondensedOutputs()[0] - .getItemStack(); - FluidStack fluid = FluidUtil.getFluidFromContainer(filled); - IStorageGrid storage = getStorageGrid(); - if (storage == null) - return false; - IAEFluidStack fluidStack = AEApi - .instance() - .storage() - .createFluidStack( - new FluidStack( - fluid.getFluid(), - FluidUtil.getCapacity(patternDetails - .getCondensedInputs()[0].getItemStack()))); - IAEFluidStack extracted = storage.getFluidInventory() - .extractItems(fluidStack.copy(), Actionable.SIMULATE, - new MachineSource(this)); - if (extracted == null - || extracted.getStackSize() != fluidStack.getStackSize()) - return false; - storage.getFluidInventory().extractItems(fluidStack, - Actionable.MODULATE, new MachineSource(this)); - this.returnStack = filled; - this.ticksToFinish = 40; - return true; - } - - @Override - public void readFromNBT(NBTTagCompound tagCompound) { - super.readFromNBT(tagCompound); - if (tagCompound.hasKey("container")) - this.containerItem = ItemStack.loadItemStackFromNBT(tagCompound - .getCompoundTag("container")); - else if (tagCompound.hasKey("isContainerEmpty") - && tagCompound.getBoolean("isContainerEmpty")) - this.containerItem = null; - if (tagCompound.hasKey("return")) - this.returnStack = ItemStack.loadItemStackFromNBT(tagCompound - .getCompoundTag("return")); - else if (tagCompound.hasKey("isReturnEmpty") - && tagCompound.getBoolean("isReturnEmpty")) - this.returnStack = null; - if (tagCompound.hasKey("time")) - this.ticksToFinish = tagCompound.getInteger("time"); - if (hasWorldObj()) { - IGridNode node = getGridNode(ForgeDirection.UNKNOWN); - if (tagCompound.hasKey("nodes") && node != null) { - node.loadFromNBT("node0", tagCompound.getCompoundTag("nodes")); - node.updateState(); - } - } - } - - @Override - public void registerListener() { - IStorageGrid storage = getStorageGrid(); - if (storage == null) - return; - postChange(storage.getFluidInventory(), null, null); - storage.getFluidInventory().addListener(this, null); - } - - @Override - public void removeListener() { - IStorageGrid storage = getStorageGrid(); - if (storage == null) - return; - storage.getFluidInventory().removeListener(this); - } - - @Override - public void securityBreak() { - if (this.getWorldObj() != null) - getWorldObj().func_147480_a(this.xCoord, this.yCoord, this.zCoord, - true); - } - - @Override - public void updateEntity() { - if (getWorldObj() == null || getWorldObj().provider == null) - return; - if (this.ticksToFinish > 0) - this.ticksToFinish = this.ticksToFinish - 1; - if (this.ticksToFinish <= 0 && this.returnStack != null) { - IStorageGrid storage = getStorageGrid(); - if (storage == null) - return; - IAEItemStack toInject = AEApi.instance().storage() - .createItemStack(this.returnStack); - if (storage.getItemInventory().canAccept(toInject.copy())) { - IAEItemStack nodAdded = storage.getItemInventory().injectItems( - toInject.copy(), Actionable.SIMULATE, - new MachineSource(this)); - if (nodAdded == null) { - storage.getItemInventory().injectItems(toInject, - Actionable.MODULATE, new MachineSource(this)); - this.returnStack = null; - } - } - } - } - - @Override - public void updateGrid(IGrid oldGrid, IGrid newGrid) { - if (oldGrid != null) { - IStorageGrid storage = oldGrid.getCache(IStorageGrid.class); - if (storage != null) - storage.getFluidInventory().removeListener(this); - } - if (newGrid != null) { - IStorageGrid storage = newGrid.getCache(IStorageGrid.class); - if (storage != null) - storage.getFluidInventory().addListener(this, null);; - } - } - - @Override - public void writeToNBT(NBTTagCompound tagCompound) { - super.writeToNBT(tagCompound); - if (this.containerItem != null) - tagCompound.setTag("container", this.containerItem.writeToNBT(new NBTTagCompound())); - else - tagCompound.setBoolean("isContainerEmpty", true); - if (this.returnStack != null) - tagCompound.setTag("return", this.returnStack.writeToNBT(new NBTTagCompound())); - else - tagCompound.setBoolean("isReturnEmpty", true); - tagCompound.setInteger("time", this.ticksToFinish); - if (!hasWorldObj()) - return; - IGridNode node = getGridNode(ForgeDirection.UNKNOWN); - if (node != null) { - NBTTagCompound nodeTag = new NBTTagCompound(); - node.saveToNBT("node0", nodeTag); - tagCompound.setTag("nodes", nodeTag); - } - } +public class TileEntityFluidFiller extends TileBase implements IActionHost, ICraftingProvider, IECTileEntity, + IMEMonitorHandlerReceiver, IListenerTile { + + private ECFluidGridBlock gridBlock; + private IGridNode node = null; + List fluids = new ArrayList(); + public ItemStack containerItem = new ItemStack(Items.bucket); + ItemStack returnStack = null; + int ticksToFinish = 0; + + private boolean isFirstGetGridNode = true; + + private final Item encodedPattern = AEApi.instance().definitions().items().encodedPattern().maybeItem().orNull(); + + public TileEntityFluidFiller() { + super(); + this.gridBlock = new ECFluidGridBlock(this); + } + + @MENetworkEventSubscribe + public void cellUpdate(MENetworkCellArrayUpdate event) { + IStorageGrid storage = getStorageGrid(); + if (storage != null) postChange(storage.getFluidInventory(), null, null); + } + + @Override + public IGridNode getActionableNode() { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return null; + if (this.node == null) { + this.node = AEApi.instance().createGridNode(this.gridBlock); + } + return this.node; + } + + @Override + public AECableType getCableConnectionType(ForgeDirection dir) { + return AECableType.DENSE; + } + + @Override + public Packet getDescriptionPacket() { + NBTTagCompound nbtTag = new NBTTagCompound(); + writeToNBT(nbtTag); + return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, nbtTag); + } + + @Override + public IGridNode getGridNode(ForgeDirection dir) { + if (FMLCommonHandler.instance().getSide().isClient() && (getWorldObj() == null || getWorldObj().isRemote)) + return null; + if (this.isFirstGetGridNode) { + this.isFirstGetGridNode = false; + getActionableNode().updateState(); + IStorageGrid storage = getStorageGrid(); + storage.getFluidInventory().addListener(this, null); + } + return this.node; + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + private ItemStack getPattern(ItemStack emptyContainer, ItemStack filledContainer) { + NBTTagList in = new NBTTagList(); + NBTTagList out = new NBTTagList(); + in.appendTag(emptyContainer.writeToNBT(new NBTTagCompound())); + out.appendTag(filledContainer.writeToNBT(new NBTTagCompound())); + NBTTagCompound itemTag = new NBTTagCompound(); + itemTag.setTag("in", in); + itemTag.setTag("out", out); + itemTag.setBoolean("crafting", false); + ItemStack pattern = new ItemStack(this.encodedPattern); + pattern.setTagCompound(itemTag); + return pattern; + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + private IStorageGrid getStorageGrid() { + this.node = getGridNode(ForgeDirection.UNKNOWN); + if (this.node == null) return null; + IGrid grid = this.node.getGrid(); + if (grid == null) return null; + return grid.getCache(IStorageGrid.class); + } + + @Override + public boolean isBusy() { + return this.returnStack != null; + } + + @Override + public boolean isValid(Object verificationToken) { + return true; + } + + @Override + public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { + readFromNBT(pkt.func_148857_g()); + } + + @Override + public void onListUpdate() {} + + @Override + public void postChange(IBaseMonitor monitor, Iterable change, + BaseActionSource actionSource) { + List oldFluids = new ArrayList(this.fluids); + boolean mustUpdate = false; + this.fluids.clear(); + for (IAEFluidStack fluid : ((IMEMonitor) monitor).getStorageList()) { + if (!oldFluids.contains(fluid.getFluid())) mustUpdate = true; + else oldFluids.remove(fluid.getFluid()); + this.fluids.add(fluid.getFluid()); + } + if (!(oldFluids.isEmpty() && !mustUpdate)) { + if (getGridNode(ForgeDirection.UNKNOWN) != null && getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) { + getGridNode(ForgeDirection.UNKNOWN).getGrid() + .postEvent(new MENetworkCraftingPatternChange(this, getGridNode(ForgeDirection.UNKNOWN))); + } + } + } + + public void postUpdateEvent() { + if (getGridNode(ForgeDirection.UNKNOWN) != null && getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) { + getGridNode(ForgeDirection.UNKNOWN).getGrid() + .postEvent(new MENetworkCraftingPatternChange(this, getGridNode(ForgeDirection.UNKNOWN))); + } + } + + @MENetworkEventSubscribe + public void powerUpdate(MENetworkPowerStatusChange event) { + IStorageGrid storage = getStorageGrid(); + if (storage != null) postChange(storage.getFluidInventory(), null, null); + } + + @Override + public void provideCrafting(ICraftingProviderHelper craftingTracker) { + IStorageGrid storage = getStorageGrid(); + if (storage == null) return; + IMEMonitor fluidStorage = storage.getFluidInventory(); + for (IAEFluidStack fluidStack : fluidStorage.getStorageList()) { + Fluid fluid = fluidStack.getFluid(); + if (fluid == null) continue; + int maxCapacity = FluidUtil.getCapacity(this.containerItem, fluid); + if (maxCapacity == 0) continue; + MutablePair filled = FluidUtil + .fillStack(this.containerItem.copy(), new FluidStack(fluid, maxCapacity)); + if (filled.right == null) continue; + ItemStack pattern = getPattern(this.containerItem, filled.right); + ICraftingPatternItem patter = (ICraftingPatternItem) pattern.getItem(); + craftingTracker.addCraftingOption(this, patter.getPatternForItem(pattern, getWorldObj())); + } + } + + @Override + public boolean pushPattern(ICraftingPatternDetails patternDetails, InventoryCrafting table) { + if (this.returnStack != null) return false; + ItemStack filled = patternDetails.getCondensedOutputs()[0].getItemStack(); + FluidStack fluid = FluidUtil.getFluidFromContainer(filled); + IStorageGrid storage = getStorageGrid(); + if (storage == null) return false; + IAEFluidStack fluidStack = AEApi.instance().storage().createFluidStack( + new FluidStack( + fluid.getFluid(), + FluidUtil + .getCapacity(patternDetails.getCondensedInputs()[0].getItemStack(), fluid.getFluid()))); + IAEFluidStack extracted = storage.getFluidInventory() + .extractItems(fluidStack.copy(), Actionable.SIMULATE, new MachineSource(this)); + if (extracted == null || extracted.getStackSize() != fluidStack.getStackSize()) return false; + storage.getFluidInventory().extractItems(fluidStack, Actionable.MODULATE, new MachineSource(this)); + this.returnStack = filled; + this.ticksToFinish = 40; + return true; + } + + @Override + public void readFromNBT(NBTTagCompound tagCompound) { + super.readFromNBT(tagCompound); + if (tagCompound.hasKey("container")) + this.containerItem = ItemStack.loadItemStackFromNBT(tagCompound.getCompoundTag("container")); + else if (tagCompound.hasKey("isContainerEmpty") && tagCompound.getBoolean("isContainerEmpty")) + this.containerItem = null; + if (tagCompound.hasKey("return")) + this.returnStack = ItemStack.loadItemStackFromNBT(tagCompound.getCompoundTag("return")); + else if (tagCompound.hasKey("isReturnEmpty") && tagCompound.getBoolean("isReturnEmpty")) + this.returnStack = null; + if (tagCompound.hasKey("time")) this.ticksToFinish = tagCompound.getInteger("time"); + if (hasWorldObj()) { + IGridNode node = getGridNode(ForgeDirection.UNKNOWN); + if (tagCompound.hasKey("nodes") && node != null) { + node.loadFromNBT("node0", tagCompound.getCompoundTag("nodes")); + node.updateState(); + } + } + } + + @Override + public void registerListener() { + IStorageGrid storage = getStorageGrid(); + if (storage == null) return; + postChange(storage.getFluidInventory(), null, null); + storage.getFluidInventory().addListener(this, null); + } + + @Override + public void removeListener() { + IStorageGrid storage = getStorageGrid(); + if (storage == null) return; + storage.getFluidInventory().removeListener(this); + } + + @Override + public void securityBreak() { + if (this.getWorldObj() != null) getWorldObj().func_147480_a(this.xCoord, this.yCoord, this.zCoord, true); + } + + @Override + public void updateEntity() { + if (getWorldObj() == null || getWorldObj().provider == null) return; + if (this.ticksToFinish > 0) this.ticksToFinish = this.ticksToFinish - 1; + if (this.ticksToFinish <= 0 && this.returnStack != null) { + IStorageGrid storage = getStorageGrid(); + if (storage == null) return; + IAEItemStack toInject = AEApi.instance().storage().createItemStack(this.returnStack); + if (storage.getItemInventory().canAccept(toInject.copy())) { + IAEItemStack nodAdded = storage.getItemInventory() + .injectItems(toInject.copy(), Actionable.SIMULATE, new MachineSource(this)); + if (nodAdded == null) { + storage.getItemInventory().injectItems(toInject, Actionable.MODULATE, new MachineSource(this)); + this.returnStack = null; + } + } + } + } + + @Override + public void updateGrid(IGrid oldGrid, IGrid newGrid) { + if (oldGrid != null) { + IStorageGrid storage = oldGrid.getCache(IStorageGrid.class); + if (storage != null) storage.getFluidInventory().removeListener(this); + } + if (newGrid != null) { + IStorageGrid storage = newGrid.getCache(IStorageGrid.class); + if (storage != null) storage.getFluidInventory().addListener(this, null);; + } + } + + @Override + public void writeToNBT(NBTTagCompound tagCompound) { + super.writeToNBT(tagCompound); + if (this.containerItem != null) + tagCompound.setTag("container", this.containerItem.writeToNBT(new NBTTagCompound())); + else tagCompound.setBoolean("isContainerEmpty", true); + if (this.returnStack != null) tagCompound.setTag("return", this.returnStack.writeToNBT(new NBTTagCompound())); + else tagCompound.setBoolean("isReturnEmpty", true); + tagCompound.setInteger("time", this.ticksToFinish); + if (!hasWorldObj()) return; + IGridNode node = getGridNode(ForgeDirection.UNKNOWN); + if (node != null) { + NBTTagCompound nodeTag = new NBTTagCompound(); + node.saveToNBT("node0", nodeTag); + tagCompound.setTag("nodes", nodeTag); + } + } } diff --git a/src/main/scala/extracells/tileentity/TileEntityFluidInterface.java b/src/main/scala/extracells/tileentity/TileEntityFluidInterface.java index b16ec606f..33079db45 100644 --- a/src/main/scala/extracells/tileentity/TileEntityFluidInterface.java +++ b/src/main/scala/extracells/tileentity/TileEntityFluidInterface.java @@ -1,5 +1,24 @@ package extracells.tileentity; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.inventory.IInventory; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.nbt.NBTTagList; +import net.minecraft.network.NetworkManager; +import net.minecraft.network.Packet; +import net.minecraft.network.play.server.S35PacketUpdateTileEntity; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.StatCollector; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.fluids.*; + import appeng.api.AEApi; import appeng.api.config.Actionable; import appeng.api.implementations.ICraftingPatternItem; @@ -21,7 +40,9 @@ import appeng.api.storage.data.IAEStack; import appeng.api.util.AECableType; import appeng.api.util.DimensionalCoord; +import appeng.util.InventoryAdaptor; import cpw.mods.fml.common.FMLCommonHandler; +import cpw.mods.fml.common.FMLLog; import extracells.api.IECTileEntity; import extracells.api.IFluidInterface; import extracells.api.crafting.IFluidCraftingPatternDetails; @@ -33,1055 +54,797 @@ import extracells.network.packet.other.IFluidSlotPartOrBlock; import extracells.registries.ItemEnum; import extracells.util.EmptyMeItemMonitor; -import extracells.util.ItemUtils; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.inventory.IInventory; -import net.minecraft.inventory.ISidedInventory; -import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.item.Item; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.nbt.NBTTagList; -import net.minecraft.network.NetworkManager; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -import net.minecraft.tileentity.TileEntity; -import net.minecraft.util.StatCollector; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.fluids.*; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class TileEntityFluidInterface extends TileBase implements - IActionHost, IFluidHandler, IECTileEntity, IFluidInterface, - IFluidSlotPartOrBlock, ITileStorageMonitorable, IStorageMonitorable, - ICraftingProvider, IWailaTile { - - private class FluidInterfaceInventory implements IInventory { - - private ItemStack[] inv = new ItemStack[9]; - - @Override - public void closeInventory() {} - - @Override - public ItemStack decrStackSize(int slot, int amt) { - ItemStack stack = getStackInSlot(slot); - if (stack != null) { - if (stack.stackSize <= amt) { - setInventorySlotContents(slot, null); - } else { - stack = stack.splitStack(amt); - if (stack.stackSize == 0) { - setInventorySlotContents(slot, null); - } - } - } - TileEntityFluidInterface.this.update = true; - return stack; - } - - @Override - public String getInventoryName() { - return "inventory.fluidInterface"; - } - - @Override - public int getInventoryStackLimit() { - return 1; - } - - @Override - public int getSizeInventory() { - return this.inv.length; - } - - @Override - public ItemStack getStackInSlot(int slot) { - return this.inv[slot]; - } - - @Override - public ItemStack getStackInSlotOnClosing(int slot) { - return null; - } - - @Override - public boolean hasCustomInventoryName() { - return false; - } - - @Override - public boolean isItemValidForSlot(int slot, ItemStack stack) { - if (stack.getItem() instanceof ICraftingPatternItem) { - ICraftingPatternDetails details = ((ICraftingPatternItem) stack - .getItem()).getPatternForItem(stack, getWorldObj()); - return details != null; - } - return false; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer player) { - return true; - } - - @Override - public void markDirty() {} - - @Override - public void openInventory() {} - - public void readFromNBT(NBTTagCompound tagCompound) { - - NBTTagList tagList = tagCompound.getTagList("Inventory", 10); - for (int i = 0; i < tagList.tagCount(); i++) { - NBTTagCompound tag = tagList.getCompoundTagAt(i); - byte slot = tag.getByte("Slot"); - if (slot >= 0 && slot < this.inv.length) { - this.inv[slot] = ItemStack.loadItemStackFromNBT(tag); - } - } - } - - @Override - public void setInventorySlotContents(int slot, ItemStack stack) { - this.inv[slot] = stack; - if (stack != null && stack.stackSize > getInventoryStackLimit()) { - stack.stackSize = getInventoryStackLimit(); - } - TileEntityFluidInterface.this.update = true; - } - - public void writeToNBT(NBTTagCompound tagCompound) { - - NBTTagList itemList = new NBTTagList(); - for (int i = 0; i < this.inv.length; i++) { - ItemStack stack = this.inv[i]; - if (stack != null) { - NBTTagCompound tag = new NBTTagCompound(); - tag.setByte("Slot", (byte) i); - stack.writeToNBT(tag); - itemList.appendTag(tag); - } - } - tagCompound.setTag("Inventory", itemList); - } - } - - List listeners = new ArrayList(); - private ECFluidGridBlock gridBlock; - private IGridNode node = null; - public FluidTank[] tanks = new FluidTank[6]; - public Integer[] fluidFilter = new Integer[this.tanks.length]; - public boolean doNextUpdate = false; - private boolean wasIdle = false; - private int tickCount = 0; - private boolean update = false; - private List patternHandlers = new ArrayList(); - private HashMap patternConvert = new HashMap(); - private List requestedItems = new ArrayList(); - private List removeList = new ArrayList(); - public final FluidInterfaceInventory inventory; - private IAEItemStack toExport = null; - - private final Item encodedPattern = AEApi.instance().definitions().items().encodedPattern() - .maybeItem().orNull(); - private List export = new ArrayList(); - private List removeFromExport = new ArrayList(); - - private List addToExport = new ArrayList(); - - private List watcherList = new ArrayList(); - - private boolean isFirstGetGridNode = true; - - public TileEntityFluidInterface() { - super(); - this.inventory = new FluidInterfaceInventory(); - this.gridBlock = new ECFluidGridBlock(this); - for (int i = 0; i < this.tanks.length; i++) { - this.tanks[i] = new FluidTank(10000) { - @Override - public FluidTank readFromNBT(NBTTagCompound nbt) { - if (!nbt.hasKey("Empty")) { - FluidStack fluid = FluidStack - .loadFluidStackFromNBT(nbt); - setFluid(fluid); - } else { - setFluid(null); - } - return this; - } - }; - this.fluidFilter[i] = -1; - } - } - - @Override - public boolean canDrain(ForgeDirection from, Fluid fluid) { - if (from == ForgeDirection.UNKNOWN) - return false; - FluidStack tankFluid = this.tanks[from.ordinal()].getFluid(); - return tankFluid != null && tankFluid.getFluid() == fluid; - } - - @Override - public boolean canFill(ForgeDirection from, Fluid fluid) { - return from != ForgeDirection.UNKNOWN - && this.tanks[from.ordinal()].fill(new FluidStack(fluid, 1), false) > 0; - } - - @Override - public FluidStack drain(ForgeDirection from, FluidStack resource, - boolean doDrain) { - FluidStack tankFluid = this.tanks[from.ordinal()].getFluid(); - if (resource == null || tankFluid == null - || tankFluid.getFluid() != resource.getFluid()) - return null; - return drain(from, resource.amount, doDrain); - - } - - @Override - public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { - if (from == ForgeDirection.UNKNOWN) - return null; - FluidStack drained = this.tanks[from.ordinal()] - .drain(maxDrain, doDrain); - if (drained != null) - if (getWorldObj() != null) - getWorldObj().markBlockForUpdate(this.xCoord, this.yCoord, - this.zCoord); - this.doNextUpdate = true; - return drained; - } - - @Override - public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { - if (from == ForgeDirection.UNKNOWN || resource == null) - return 0; - - if ((this.tanks[from.ordinal()].getFluid() == null || this.tanks[from - .ordinal()].getFluid().getFluid() == resource.getFluid()) - && resource.getFluid() == FluidRegistry - .getFluid(this.fluidFilter[from.ordinal()])) { - int added = this.tanks[from.ordinal()] - .fill(resource.copy(), doFill); - if (added == resource.amount) { - this.doNextUpdate = true; - return added; - } - added += fillToNetwork(new FluidStack(resource.getFluid(), - resource.amount - added), doFill); - this.doNextUpdate = true; - return added; - } - - int filled = 0; - filled += fillToNetwork(resource, doFill); - - if (filled < resource.amount) - filled += this.tanks[from.ordinal()].fill(new FluidStack( - resource.getFluid(), resource.amount - filled), doFill); - if (filled > 0) - if (getWorldObj() != null) - getWorldObj().markBlockForUpdate(this.xCoord, this.yCoord, - this.zCoord); - this.doNextUpdate = true; - return filled; - } - - public int fillToNetwork(FluidStack resource, boolean doFill) { - IGridNode node = getGridNode(ForgeDirection.UNKNOWN); - if (node == null || resource == null) - return 0; - IGrid grid = node.getGrid(); - if (grid == null) - return 0; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return 0; - IAEFluidStack notRemoved; - FluidStack copy = resource.copy(); - if (doFill) { - notRemoved = storage.getFluidInventory().injectItems( - AEApi.instance().storage().createFluidStack(resource), - Actionable.MODULATE, new MachineSource(this)); - } else { - notRemoved = storage.getFluidInventory().injectItems( - AEApi.instance().storage().createFluidStack(resource), - Actionable.SIMULATE, new MachineSource(this)); - } - if (notRemoved == null) - return resource.amount; - return (int) (resource.amount - notRemoved.getStackSize()); - } - - private void forceUpdate() { - getWorldObj().markBlockForUpdate(this.yCoord, this.yCoord, this.zCoord); - for (IContainerListener listener : this.listeners) { - if (listener != null) - listener.updateContainer(); - } - this.doNextUpdate = false; - } - - @Override - public IGridNode getActionableNode() { - if (FMLCommonHandler.instance().getEffectiveSide().isClient()) - return null; - if (this.node == null) { - this.node = AEApi.instance().createGridNode(this.gridBlock); - } - return this.node; - } - - @Override - public AECableType getCableConnectionType(ForgeDirection dir) { - return AECableType.DENSE; - } - - @Override - public Packet getDescriptionPacket() { - NBTTagCompound nbtTag = new NBTTagCompound(); - writeToNBTWithoutExport(nbtTag); - return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, - this.zCoord, 1, nbtTag); - } - - @Override - public Fluid getFilter(ForgeDirection side) { - if (side == null || side == ForgeDirection.UNKNOWN) - return null; - return FluidRegistry.getFluid(this.fluidFilter[side.ordinal()]); - } - - @Override - public IMEMonitor getFluidInventory() { - return getFluidInventory(ForgeDirection.UNKNOWN); - } - - @Override - public IFluidTank getFluidTank(ForgeDirection side) { - if (side == null || side == ForgeDirection.UNKNOWN) - return null; - return this.tanks[side.ordinal()]; - } - - @Override - public IGridNode getGridNode(ForgeDirection dir) { - if (FMLCommonHandler.instance().getSide().isClient() - && (getWorldObj() == null || getWorldObj().isRemote)) - return null; - if (this.isFirstGetGridNode) { - this.isFirstGetGridNode = false; - getActionableNode().updateState(); - } - return this.node; - } - - @Override - public IMEMonitor getItemInventory() { - return new EmptyMeItemMonitor(); - } - - @Override - public DimensionalCoord getLocation() { - return new DimensionalCoord(this); - } - - @Override - public IStorageMonitorable getMonitorable(ForgeDirection side, - BaseActionSource src) { - return this; - } - - @Override - public IInventory getPatternInventory() { - return this.inventory; - } - - @Override - public double getPowerUsage() { - return 1.0D; - } - - @Override - public FluidTankInfo[] getTankInfo(ForgeDirection from) { - if (from == ForgeDirection.UNKNOWN) - return null; - return new FluidTankInfo[] { this.tanks[from.ordinal()].getInfo() }; - } - - @Override - public List getWailaBody(List list, NBTTagCompound tag, - ForgeDirection side) { - if (side == null || side == ForgeDirection.UNKNOWN) - return list; - list.add(StatCollector.translateToLocal("extracells.tooltip.direction." - + side.ordinal())); - FluidTank[] tanks = new FluidTank[6]; - for (int i = 0; i < tanks.length; i++) { - tanks[i] = new FluidTank(10000) { - @Override - public FluidTank readFromNBT(NBTTagCompound nbt) { - if (!nbt.hasKey("Empty")) { - FluidStack fluid = FluidStack - .loadFluidStackFromNBT(nbt); - setFluid(fluid); - } else { - setFluid(null); - } - return this; - } - }; - } - - for (int i = 0; i < tanks.length; i++) { - if (tag.hasKey("tank#" + i)) - tanks[i].readFromNBT(tag.getCompoundTag("tank#" + i)); - } - FluidTank tank = tanks[side.ordinal()]; - if (tank == null || tank.getFluid() == null - || tank.getFluid().getFluid() == null) { - list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " - + StatCollector - .translateToLocal("extracells.tooltip.empty1")); - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": 0mB / 10000mB"); - } else { - list.add(StatCollector.translateToLocal("extracells.tooltip.fluid") - + ": " + tank.getFluid().getLocalizedName()); - list.add(StatCollector - .translateToLocal("extracells.tooltip.amount") - + ": " - + tank.getFluidAmount() + "mB / 10000mB"); - } - return list; - } - - @Override - public NBTTagCompound getWailaTag(NBTTagCompound tag) { - for (int i = 0; i < this.tanks.length; i++) { - tag.setTag("tank#" + i, - this.tanks[i].writeToNBT(new NBTTagCompound())); - } - return tag; - } - - @Override - public boolean isBusy() { - return !this.export.isEmpty(); - } - - private ItemStack makeCraftingPatternItem(ICraftingPatternDetails details) { - if (details == null) - return null; - NBTTagList in = new NBTTagList(); - NBTTagList out = new NBTTagList(); - for (IAEItemStack s : details.getInputs()) { - if (s == null) - in.appendTag(new NBTTagCompound()); - else - in.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); - } - for (IAEItemStack s : details.getOutputs()) { - if (s == null) - out.appendTag(new NBTTagCompound()); - else - out.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); - } - NBTTagCompound itemTag = new NBTTagCompound(); - itemTag.setTag("in", in); - itemTag.setTag("out", out); - itemTag.setBoolean("crafting", details.isCraftable()); - ItemStack pattern = new ItemStack(this.encodedPattern); - pattern.setTagCompound(itemTag); - return pattern; - } - - @Override - public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { - readFromNBT(pkt.func_148857_g()); - } - - @Override - public void provideCrafting(ICraftingProviderHelper craftingTracker) { - this.patternHandlers = new ArrayList(); - this.patternConvert.clear(); - - for (ItemStack currentPatternStack : this.inventory.inv) { - if (currentPatternStack != null - && currentPatternStack.getItem() != null - && currentPatternStack.getItem() instanceof ICraftingPatternItem) { - ICraftingPatternItem currentPattern = (ICraftingPatternItem) currentPatternStack - .getItem(); - - if (currentPattern != null - && currentPattern.getPatternForItem( - currentPatternStack, getWorldObj()) != null) { - IFluidCraftingPatternDetails pattern = new CraftingPattern2( - currentPattern.getPatternForItem( - currentPatternStack, getWorldObj())); - this.patternHandlers.add(pattern); - ItemStack is = makeCraftingPatternItem(pattern); - if (is == null) - continue; - ICraftingPatternDetails p = ((ICraftingPatternItem) is - .getItem()).getPatternForItem(is, getWorldObj()); - this.patternConvert.put(p, pattern); - craftingTracker.addCraftingOption(this, p); - } - } - } - } - - private void pushItems() { - for (IAEStack s : this.removeFromExport) { - this.export.remove(s); - } - this.removeFromExport.clear(); - for (IAEStack s : this.addToExport) { - this.export.add(s); - } - this.addToExport.clear(); - if (!hasWorldObj() || this.export.isEmpty()) - return; - ForgeDirection[] directions = ForgeDirection.VALID_DIRECTIONS; - for (ForgeDirection dir : directions) { - TileEntity tile = getWorldObj().getTileEntity( - this.xCoord + dir.offsetX, this.yCoord + dir.offsetY, - this.zCoord + dir.offsetZ); - if (tile != null) { - IAEStack stack0 = this.export.iterator().next(); - IAEStack stack = stack0.copy(); - if (stack instanceof IAEItemStack && tile instanceof IInventory) { - if (tile instanceof ISidedInventory) { - ISidedInventory inv = (ISidedInventory) tile; - for (int i : inv.getAccessibleSlotsFromSide(dir - .getOpposite().ordinal())) { - if (inv.canInsertItem(i, ((IAEItemStack) stack) - .getItemStack(), dir.getOpposite() - .ordinal())) { - if (inv.getStackInSlot(i) == null) { - inv.setInventorySlotContents(i, - ((IAEItemStack) stack) - .getItemStack()); - this.removeFromExport.add(stack0); - return; - } else if (ItemUtils.areItemEqualsIgnoreStackSize( - inv.getStackInSlot(i), - ((IAEItemStack) stack).getItemStack())) { - int max = inv.getInventoryStackLimit(); - int current = inv.getStackInSlot(i).stackSize; - int outStack = (int) stack.getStackSize(); - if (max == current) - continue; - if (current + outStack <= max) { - ItemStack s = inv.getStackInSlot(i) - .copy(); - s.stackSize = s.stackSize + outStack; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - return; - } else { - ItemStack s = inv.getStackInSlot(i) - .copy(); - s.stackSize = max; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - stack.setStackSize(outStack - max - + current); - this.addToExport.add(stack); - return; - } - } - } - } - } else { - IInventory inv = (IInventory) tile; - for (int i = 0; i < inv.getSizeInventory(); i++) { - if (inv.isItemValidForSlot(i, - ((IAEItemStack) stack).getItemStack())) { - if (inv.getStackInSlot(i) == null) { - inv.setInventorySlotContents(i, - ((IAEItemStack) stack) - .getItemStack()); - this.removeFromExport.add(stack0); - return; - } else if (ItemUtils.areItemEqualsIgnoreStackSize( - inv.getStackInSlot(i), - ((IAEItemStack) stack).getItemStack())) { - int max = inv.getInventoryStackLimit(); - int current = inv.getStackInSlot(i).stackSize; - int outStack = (int) stack.getStackSize(); - if (max == current) - continue; - if (current + outStack <= max) { - ItemStack s = inv.getStackInSlot(i) - .copy(); - s.stackSize = s.stackSize + outStack; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - return; - } else { - ItemStack s = inv.getStackInSlot(i) - .copy(); - s.stackSize = max; - inv.setInventorySlotContents(i, s); - this.removeFromExport.add(stack0); - stack.setStackSize(outStack - max - + current); - this.addToExport.add(stack); - return; - } - } - } - } - } - } else if (stack instanceof IAEFluidStack - && tile instanceof IFluidHandler) { - IFluidHandler handler = (IFluidHandler) tile; - IAEFluidStack fluid = (IAEFluidStack) stack; - if (handler.canFill(dir.getOpposite(), fluid.copy() - .getFluid())) { - int amount = handler.fill(dir.getOpposite(), fluid - .getFluidStack().copy(), false); - if (amount == 0) - continue; - if (amount == fluid.getStackSize()) { - handler.fill(dir.getOpposite(), fluid - .getFluidStack().copy(), true); - this.removeFromExport.add(stack0); - } else { - IAEFluidStack f = fluid.copy(); - f.setStackSize(f.getStackSize() - amount); - FluidStack fl = fluid.getFluidStack().copy(); - fl.amount = amount; - handler.fill(dir.getOpposite(), fl, true); - this.removeFromExport.add(stack0); - this.addToExport.add(f); - return; - } - } - } - } - } - } - - @Override - public boolean pushPattern(ICraftingPatternDetails patDetails, - InventoryCrafting table) { - if (isBusy() || !this.patternConvert.containsKey(patDetails)) - return false; - ICraftingPatternDetails patternDetails = this.patternConvert - .get(patDetails); - if (patternDetails instanceof CraftingPattern) { - CraftingPattern patter = (CraftingPattern) patternDetails; - HashMap fluids = new HashMap(); - for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { - if (fluids.containsKey(stack.getFluid())) { - Long amount = fluids.get(stack.getFluid()) - + stack.getStackSize(); - fluids.remove(stack.getFluid()); - fluids.put(stack.getFluid(), amount); - } else { - fluids.put(stack.getFluid(), stack.getStackSize()); - } - } - IGrid grid = this.node.getGrid(); - if (grid == null) - return false; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return false; - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory() - .extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack(fluid, - (int) (amount + 0))), - Actionable.SIMULATE, new MachineSource(this)); - if (extractFluid == null - || extractFluid.getStackSize() != amount) { - return false; - } - } - for (Fluid fluid : fluids.keySet()) { - Long amount = fluids.get(fluid); - IAEFluidStack extractFluid = storage.getFluidInventory() - .extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack(fluid, - (int) (amount + 0))), - Actionable.MODULATE, new MachineSource(this)); - this.export.add(extractFluid); - } - for (IAEItemStack s : patter.getCondensedInputs()) { - if (s == null) - continue; - if (s.getItem() == ItemEnum.FLUIDPATTERN.getItem()) { - this.toExport = s.copy(); - continue; - } - this.export.add(s); - } - - } - return true; - } - - public void readFilter(NBTTagCompound tag) { - for (int i = 0; i < this.fluidFilter.length; i++) { - if (tag.hasKey("fluid#" + i)) - this.fluidFilter[i] = tag.getInteger("fluid#" + i); - } - } - - @Override - public void readFromNBT(NBTTagCompound tag) { - super.readFromNBT(tag); - for (int i = 0; i < this.tanks.length; i++) { - if (tag.hasKey("tank#" + i)) - this.tanks[i].readFromNBT(tag.getCompoundTag("tank#" + i)); - if (tag.hasKey("filter#" + i)) - this.fluidFilter[i] = tag.getInteger("filter#" + i); - } - if (hasWorldObj()) { - IGridNode node = getGridNode(ForgeDirection.UNKNOWN); - if (tag.hasKey("nodes") && node != null) { - node.loadFromNBT("node0", tag.getCompoundTag("nodes")); - node.updateState(); - } - } - if (tag.hasKey("inventory")) - this.inventory.readFromNBT(tag.getCompoundTag("inventory")); - if (tag.hasKey("export")) - readOutputFromNBT(tag.getCompoundTag("export")); - } - - private void readOutputFromNBT(NBTTagCompound tag) { - this.addToExport.clear(); - this.removeFromExport.clear(); - this.export.clear(); - int i = tag.getInteger("remove"); - for (int j = 0; j < i; j++) { - if (tag.getBoolean("remove-" + j + "-isItem")) { - IAEItemStack s = AEApi - .instance() - .storage() - .createItemStack( - ItemStack.loadItemStackFromNBT(tag - .getCompoundTag("remove-" + j))); - s.setStackSize(tag.getLong("remove-" + j + "-amount")); - this.removeFromExport.add(s); - } else { - IAEFluidStack s = AEApi - .instance() - .storage() - .createFluidStack( - FluidStack.loadFluidStackFromNBT(tag - .getCompoundTag("remove-" + j))); - s.setStackSize(tag.getLong("remove-" + j + "-amount")); - this.removeFromExport.add(s); - } - } - i = tag.getInteger("add"); - for (int j = 0; j < i; j++) { - if (tag.getBoolean("add-" + j + "-isItem")) { - IAEItemStack s = AEApi - .instance() - .storage() - .createItemStack( - ItemStack.loadItemStackFromNBT(tag - .getCompoundTag("add-" + j))); - s.setStackSize(tag.getLong("add-" + j + "-amount")); - this.addToExport.add(s); - } else { - IAEFluidStack s = AEApi - .instance() - .storage() - .createFluidStack( - FluidStack.loadFluidStackFromNBT(tag - .getCompoundTag("add-" + j))); - s.setStackSize(tag.getLong("add-" + j + "-amount")); - this.addToExport.add(s); - } - } - i = tag.getInteger("export"); - for (int j = 0; j < i; j++) { - if (tag.getBoolean("export-" + j + "-isItem")) { - IAEItemStack s = AEApi - .instance() - .storage() - .createItemStack( - ItemStack.loadItemStackFromNBT(tag - .getCompoundTag("export-" + j))); - s.setStackSize(tag.getLong("export-" + j + "-amount")); - this.export.add(s); - } else { - IAEFluidStack s = AEApi - .instance() - .storage() - .createFluidStack( - FluidStack.loadFluidStackFromNBT(tag - .getCompoundTag("export-" + j))); - s.setStackSize(tag.getLong("export-" + j + "-amount")); - this.export.add(s); - } - } - } - - public void registerListener(IContainerListener listener) { - this.listeners.add(listener); - } - - public void removeListener(IContainerListener listener) { - this.listeners.remove(listener); - } - - @Override - public void securityBreak() { - - } - - @Override - public void setFilter(ForgeDirection side, Fluid fluid) { - if (side == null || side == ForgeDirection.UNKNOWN) - return; - if (fluid == null) { - this.fluidFilter[side.ordinal()] = -1; - this.doNextUpdate = true; - return; - } - this.fluidFilter[side.ordinal()] = fluid.getID(); - this.doNextUpdate = true; - } - - @Override - public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { - setFilter(ForgeDirection.getOrientation(_index), _fluid); - } - - @Override - public void setFluidTank(ForgeDirection side, FluidStack fluid) { - if (side == null || side == ForgeDirection.UNKNOWN) - return; - this.tanks[side.ordinal()].setFluid(fluid); - this.doNextUpdate = true; - } - - private void tick() { - if (this.tickCount >= 40 || !this.wasIdle) { - this.tickCount = 0; - this.wasIdle = true; - } else { - this.tickCount++; - return; - } - if (this.node == null) - return; - IGrid grid = this.node.getGrid(); - if (grid == null) - return; - IStorageGrid storage = grid.getCache(IStorageGrid.class); - if (storage == null) - return; - if (this.toExport != null) { - storage.getItemInventory().injectItems(this.toExport, - Actionable.MODULATE, new MachineSource(this)); - this.toExport = null; - } - for (int i = 0; i < this.tanks.length; i++) { - if (this.tanks[i].getFluid() != null - && FluidRegistry.getFluid(this.fluidFilter[i]) != this.tanks[i] - .getFluid().getFluid()) { - FluidStack s = this.tanks[i].drain(125, false); - if (s != null) { - IAEFluidStack notAdded = storage.getFluidInventory() - .injectItems( - AEApi.instance().storage() - .createFluidStack(s.copy()), - Actionable.SIMULATE, - new MachineSource(this)); - if (notAdded != null) { - int toAdd = (int) (s.amount - notAdded.getStackSize()); - storage.getFluidInventory().injectItems( - AEApi.instance() - .storage() - .createFluidStack( - this.tanks[i] - .drain(toAdd, true)), - Actionable.MODULATE, new MachineSource(this)); - this.doNextUpdate = true; - this.wasIdle = false; - } else { - storage.getFluidInventory().injectItems( - AEApi.instance() - .storage() - .createFluidStack( - this.tanks[i].drain(s.amount, - true)), - Actionable.MODULATE, new MachineSource(this)); - this.doNextUpdate = true; - this.wasIdle = false; - } - } - } - if ((this.tanks[i].getFluid() == null || this.tanks[i].getFluid() - .getFluid() == FluidRegistry.getFluid(this.fluidFilter[i])) - && FluidRegistry.getFluid(this.fluidFilter[i]) != null) { - IAEFluidStack extracted = storage - .getFluidInventory() - .extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack( - FluidRegistry - .getFluid(this.fluidFilter[i]), - 125)), - Actionable.SIMULATE, new MachineSource(this)); - if (extracted == null) - continue; - int accepted = this.tanks[i].fill(extracted.getFluidStack(), - false); - if (accepted == 0) - continue; - this.tanks[i] - .fill(storage - .getFluidInventory() - .extractItems( - AEApi.instance() - .storage() - .createFluidStack( - new FluidStack( - FluidRegistry - .getFluid(this.fluidFilter[i]), - accepted)), - Actionable.MODULATE, - new MachineSource(this)) - .getFluidStack(), true); - this.doNextUpdate = true; - this.wasIdle = false; - } - } - } - - @Override - public void updateEntity() { - if (getWorldObj() == null || getWorldObj().provider == null - || getWorldObj().isRemote) - return; - if (this.update) { - this.update = false; - if (getGridNode(ForgeDirection.UNKNOWN) != null - && getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) { - getGridNode(ForgeDirection.UNKNOWN).getGrid().postEvent( - new MENetworkCraftingPatternChange(this, - getGridNode(ForgeDirection.UNKNOWN))); - } - } - pushItems(); - if (this.doNextUpdate) - forceUpdate(); - tick(); - } - - public NBTTagCompound writeFilter(NBTTagCompound tag) { - for (int i = 0; i < this.fluidFilter.length; i++) { - tag.setInteger("fluid#" + i, this.fluidFilter[i]); - } - return tag; - } - - private NBTTagCompound writeOutputToNBT(NBTTagCompound tag) { - int i = 0; - for (IAEStack s : this.removeFromExport) { - if (s != null) { - tag.setBoolean("remove-" + i + "-isItem", s.isItem()); - NBTTagCompound data = new NBTTagCompound(); - if (s.isItem()) { - ((IAEItemStack) s).getItemStack().writeToNBT(data); - } else { - ((IAEFluidStack) s).getFluidStack().writeToNBT(data); - } - tag.setTag("remove-" + i, data); - tag.setLong("remove-" + i + "-amount", s.getStackSize()); - } - i++; - } - tag.setInteger("remove", this.removeFromExport.size()); - i = 0; - for (IAEStack s : this.addToExport) { - if (s != null) { - tag.setBoolean("add-" + i + "-isItem", s.isItem()); - NBTTagCompound data = new NBTTagCompound(); - if (s.isItem()) { - ((IAEItemStack) s).getItemStack().writeToNBT(data); - } else { - ((IAEFluidStack) s).getFluidStack().writeToNBT(data); - }; - tag.setTag("add-" + i, data); - tag.setLong("add-" + i + "-amount", s.getStackSize()); - } - i++; - } - tag.setInteger("add", this.addToExport.size()); - i = 0; - for (IAEStack s : this.export) { - if (s != null) { - tag.setBoolean("export-" + i + "-isItem", s.isItem()); - NBTTagCompound data = new NBTTagCompound(); - if (s.isItem()) { - ((IAEItemStack) s).getItemStack().writeToNBT(data); - } else { - ((IAEFluidStack) s).getFluidStack().writeToNBT(data); - } - tag.setTag("export-" + i, data); - tag.setLong("export-" + i + "-amount", s.getStackSize()); - } - i++; - } - tag.setInteger("export", this.export.size()); - return tag; - } - - @Override - public void writeToNBT(NBTTagCompound data) { - writeToNBTWithoutExport(data); - NBTTagCompound tag = new NBTTagCompound(); - writeOutputToNBT(tag); - data.setTag("export", tag); - } - - public void writeToNBTWithoutExport(NBTTagCompound tag) { - super.writeToNBT(tag); - for (int i = 0; i < this.tanks.length; i++) { - tag.setTag("tank#" + i, - this.tanks[i].writeToNBT(new NBTTagCompound())); - tag.setInteger("filter#" + i, this.fluidFilter[i]); - } - if (!hasWorldObj()) - return; - IGridNode node = getGridNode(ForgeDirection.UNKNOWN); - if (node != null) { - NBTTagCompound nodeTag = new NBTTagCompound(); - node.saveToNBT("node0", nodeTag); - tag.setTag("nodes", nodeTag); - } - NBTTagCompound inventory = new NBTTagCompound(); - this.inventory.writeToNBT(inventory); - tag.setTag("inventory", inventory); - } +import extracells.util.FluidUtil; + +public class TileEntityFluidInterface extends TileBase + implements IActionHost, IFluidHandler, IECTileEntity, IFluidInterface, IFluidSlotPartOrBlock, + ITileStorageMonitorable, IStorageMonitorable, ICraftingProvider, IWailaTile { + + private class FluidInterfaceInventory implements IInventory { + + private ItemStack[] inv = new ItemStack[9]; + + @Override + public void closeInventory() {} + + @Override + public ItemStack decrStackSize(int slot, int amt) { + ItemStack stack = getStackInSlot(slot); + if (stack != null) { + if (stack.stackSize <= amt) { + setInventorySlotContents(slot, null); + } else { + stack = stack.splitStack(amt); + if (stack.stackSize == 0) { + setInventorySlotContents(slot, null); + } + } + } + TileEntityFluidInterface.this.update = true; + return stack; + } + + @Override + public String getInventoryName() { + return "inventory.fluidInterface"; + } + + @Override + public int getInventoryStackLimit() { + return 1; + } + + @Override + public int getSizeInventory() { + return this.inv.length; + } + + @Override + public ItemStack getStackInSlot(int slot) { + return this.inv[slot]; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slot) { + return null; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public boolean isItemValidForSlot(int slot, ItemStack stack) { + if (stack.getItem() instanceof ICraftingPatternItem) { + ICraftingPatternDetails details = ((ICraftingPatternItem) stack.getItem()) + .getPatternForItem(stack, getWorldObj()); + return details != null; + } + return false; + } + + @Override + public boolean isUseableByPlayer(EntityPlayer player) { + return true; + } + + @Override + public void markDirty() {} + + @Override + public void openInventory() {} + + public void readFromNBT(NBTTagCompound tagCompound) { + + NBTTagList tagList = tagCompound.getTagList("Inventory", 10); + for (int i = 0; i < tagList.tagCount(); i++) { + NBTTagCompound tag = tagList.getCompoundTagAt(i); + byte slot = tag.getByte("Slot"); + if (slot >= 0 && slot < this.inv.length) { + this.inv[slot] = ItemStack.loadItemStackFromNBT(tag); + } + } + } + + @Override + public void setInventorySlotContents(int slot, ItemStack stack) { + this.inv[slot] = stack; + if (stack != null && stack.stackSize > getInventoryStackLimit()) { + stack.stackSize = getInventoryStackLimit(); + } + TileEntityFluidInterface.this.originalPatternsCache[slot] = null; + TileEntityFluidInterface.this.update = true; + } + + public void writeToNBT(NBTTagCompound tagCompound) { + + NBTTagList itemList = new NBTTagList(); + for (int i = 0; i < this.inv.length; i++) { + ItemStack stack = this.inv[i]; + if (stack != null) { + NBTTagCompound tag = new NBTTagCompound(); + tag.setByte("Slot", (byte) i); + stack.writeToNBT(tag); + itemList.appendTag(tag); + } + } + tagCompound.setTag("Inventory", itemList); + } + } + + List listeners = new ArrayList(); + private ECFluidGridBlock gridBlock; + private IGridNode node = null; + public FluidTank[] tanks = new FluidTank[6]; + public Integer[] fluidFilter = new Integer[this.tanks.length]; + public boolean doNextUpdate = false; + private boolean wasIdle = false; + private int tickCount = 0; + private boolean update = false; + private List patternHandlers = new ArrayList(); + private HashMap patternConvert = new HashMap(); + private final ICraftingPatternDetails[] originalPatternsCache = new ICraftingPatternDetails[9]; + private List requestedItems = new ArrayList(); + private List removeList = new ArrayList(); + public final FluidInterfaceInventory inventory; + private IAEItemStack toExport = null; + + private final Item encodedPattern = AEApi.instance().definitions().items().encodedPattern().maybeItem().orNull(); + private List export = new ArrayList(); + + private List addToExport = new ArrayList(); + + private List watcherList = new ArrayList(); + + private boolean isFirstGetGridNode = true; + + public TileEntityFluidInterface() { + super(); + this.inventory = new FluidInterfaceInventory(); + this.gridBlock = new ECFluidGridBlock(this); + for (int i = 0; i < this.tanks.length; i++) { + this.tanks[i] = new FluidTank(10000) { + + @Override + public FluidTank readFromNBT(NBTTagCompound nbt) { + if (!nbt.hasKey("Empty")) { + FluidStack fluid = FluidStack.loadFluidStackFromNBT(nbt); + setFluid(fluid); + } else { + setFluid(null); + } + return this; + } + }; + this.fluidFilter[i] = -1; + } + } + + @Override + public boolean canDrain(ForgeDirection from, Fluid fluid) { + if (from == ForgeDirection.UNKNOWN) return false; + FluidStack tankFluid = this.tanks[from.ordinal()].getFluid(); + return tankFluid != null && tankFluid.getFluid() == fluid; + } + + @Override + public boolean canFill(ForgeDirection from, Fluid fluid) { + return from != ForgeDirection.UNKNOWN && this.tanks[from.ordinal()].fill(new FluidStack(fluid, 1), false) > 0; + } + + @Override + public FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) { + FluidStack tankFluid = this.tanks[from.ordinal()].getFluid(); + if (resource == null || tankFluid == null || tankFluid.getFluid() != resource.getFluid()) return null; + return drain(from, resource.amount, doDrain); + } + + @Override + public FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) { + if (from == ForgeDirection.UNKNOWN) return null; + FluidStack drained = this.tanks[from.ordinal()].drain(maxDrain, doDrain); + if (drained != null) + if (getWorldObj() != null) getWorldObj().markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord); + this.doNextUpdate = true; + return drained; + } + + @Override + public int fill(ForgeDirection from, FluidStack resource, boolean doFill) { + if (from == ForgeDirection.UNKNOWN || resource == null) return 0; + + if ((this.tanks[from.ordinal()].getFluid() == null + || this.tanks[from.ordinal()].getFluid().getFluid() == resource.getFluid()) + && resource.getFluid() == FluidRegistry.getFluid(this.fluidFilter[from.ordinal()])) { + int added = this.tanks[from.ordinal()].fill(resource.copy(), doFill); + if (added == resource.amount) { + this.doNextUpdate = true; + return added; + } + added += fillToNetwork(new FluidStack(resource.getFluid(), resource.amount - added), doFill); + this.doNextUpdate = true; + return added; + } + + int filled = 0; + filled += fillToNetwork(resource, doFill); + + if (filled < resource.amount) filled += this.tanks[from.ordinal()] + .fill(new FluidStack(resource.getFluid(), resource.amount - filled), doFill); + if (filled > 0) + if (getWorldObj() != null) getWorldObj().markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord); + this.doNextUpdate = true; + return filled; + } + + public int fillToNetwork(FluidStack resource, boolean doFill) { + IGridNode node = getGridNode(ForgeDirection.UNKNOWN); + if (node == null || resource == null) return 0; + IGrid grid = node.getGrid(); + if (grid == null) return 0; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return 0; + IAEFluidStack notRemoved = storage.getFluidInventory().injectItems( + AEApi.instance().storage().createFluidStack(resource), + doFill ? Actionable.MODULATE : Actionable.SIMULATE, + new MachineSource(this)); + if (notRemoved == null) return resource.amount; + return (int) (resource.amount - notRemoved.getStackSize()); + } + + private void forceUpdate() { + getWorldObj().markBlockForUpdate(this.yCoord, this.yCoord, this.zCoord); + for (IContainerListener listener : this.listeners) { + if (listener != null) listener.updateContainer(); + } + this.doNextUpdate = false; + } + + @Override + public IGridNode getActionableNode() { + if (FMLCommonHandler.instance().getEffectiveSide().isClient()) return null; + if (this.node == null) { + this.node = AEApi.instance().createGridNode(this.gridBlock); + } + return this.node; + } + + @Override + public AECableType getCableConnectionType(ForgeDirection dir) { + return AECableType.DENSE; + } + + @Override + public Packet getDescriptionPacket() { + NBTTagCompound nbtTag = new NBTTagCompound(); + writeToNBTWithoutExport(nbtTag); + return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, nbtTag); + } + + @Override + public Fluid getFilter(ForgeDirection side) { + if (side == null || side == ForgeDirection.UNKNOWN) return null; + return FluidRegistry.getFluid(this.fluidFilter[side.ordinal()]); + } + + @Override + public IMEMonitor getFluidInventory() { + return getFluidInventory(ForgeDirection.UNKNOWN); + } + + @Override + public IFluidTank getFluidTank(ForgeDirection side) { + if (side == null || side == ForgeDirection.UNKNOWN) return null; + return this.tanks[side.ordinal()]; + } + + @Override + public IGridNode getGridNode(ForgeDirection dir) { + if (FMLCommonHandler.instance().getSide().isClient() && (getWorldObj() == null || getWorldObj().isRemote)) + return null; + if (this.isFirstGetGridNode) { + this.isFirstGetGridNode = false; + getActionableNode().updateState(); + } + return this.node; + } + + @Override + public IMEMonitor getItemInventory() { + return new EmptyMeItemMonitor(); + } + + @Override + public DimensionalCoord getLocation() { + return new DimensionalCoord(this); + } + + @Override + public IStorageMonitorable getMonitorable(ForgeDirection side, BaseActionSource src) { + return this; + } + + @Override + public IInventory getPatternInventory() { + return this.inventory; + } + + @Override + public double getPowerUsage() { + return 1.0D; + } + + @Override + public FluidTankInfo[] getTankInfo(ForgeDirection from) { + if (from == ForgeDirection.UNKNOWN) return null; + return new FluidTankInfo[] { this.tanks[from.ordinal()].getInfo() }; + } + + @Override + public List getWailaBody(List list, NBTTagCompound tag, ForgeDirection side) { + if (side == null || side == ForgeDirection.UNKNOWN) return list; + list.add(StatCollector.translateToLocal("extracells.tooltip.direction." + side.ordinal())); + FluidTank[] tanks = new FluidTank[6]; + for (int i = 0; i < tanks.length; i++) { + tanks[i] = new FluidTank(10000) { + + @Override + public FluidTank readFromNBT(NBTTagCompound nbt) { + if (!nbt.hasKey("Empty")) { + FluidStack fluid = FluidStack.loadFluidStackFromNBT(nbt); + setFluid(fluid); + } else { + setFluid(null); + } + return this; + } + }; + } + + for (int i = 0; i < tanks.length; i++) { + if (tag.hasKey("tank#" + i)) tanks[i].readFromNBT(tag.getCompoundTag("tank#" + i)); + } + FluidTank tank = tanks[side.ordinal()]; + if (tank == null || tank.getFluid() == null || tank.getFluid().getFluid() == null) { + list.add( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + StatCollector.translateToLocal("extracells.tooltip.empty1")); + list.add(StatCollector.translateToLocal("extracells.tooltip.amount") + ": 0mB / 10000mB"); + } else { + list.add( + StatCollector.translateToLocal("extracells.tooltip.fluid") + ": " + + tank.getFluid().getLocalizedName()); + list.add( + StatCollector.translateToLocal("extracells.tooltip.amount") + ": " + + tank.getFluidAmount() + + "mB / 10000mB"); + } + return list; + } + + @Override + public NBTTagCompound getWailaTag(NBTTagCompound tag) { + for (int i = 0; i < this.tanks.length; i++) { + tag.setTag("tank#" + i, this.tanks[i].writeToNBT(new NBTTagCompound())); + } + return tag; + } + + @Override + public boolean isBusy() { + return !this.export.isEmpty(); + } + + private ItemStack makeCraftingPatternItem(ICraftingPatternDetails details) { + if (details == null) return null; + NBTTagList in = new NBTTagList(); + NBTTagList out = new NBTTagList(); + for (IAEItemStack s : details.getInputs()) { + if (s == null) in.appendTag(new NBTTagCompound()); + else in.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); + } + for (IAEItemStack s : details.getOutputs()) { + if (s == null) out.appendTag(new NBTTagCompound()); + else out.appendTag(s.getItemStack().writeToNBT(new NBTTagCompound())); + } + NBTTagCompound itemTag = new NBTTagCompound(); + itemTag.setTag("in", in); + itemTag.setTag("out", out); + itemTag.setBoolean("crafting", details.isCraftable()); + ItemStack pattern = new ItemStack(this.encodedPattern); + pattern.setTagCompound(itemTag); + return pattern; + } + + @Override + public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt) { + readFromNBT(pkt.func_148857_g()); + } + + @Override + public void provideCrafting(ICraftingProviderHelper craftingTracker) { + this.patternHandlers = new ArrayList(); + this.patternConvert.clear(); + + ItemStack[] inv = this.inventory.inv; + for (int i = 0, invLength = inv.length; i < invLength; i++) { + ItemStack currentPatternStack = inv[i]; + if (currentPatternStack != null && currentPatternStack.getItem() != null + && currentPatternStack.getItem() instanceof ICraftingPatternItem) { + ICraftingPatternItem currentPattern = (ICraftingPatternItem) currentPatternStack.getItem(); + + ICraftingPatternDetails originalPattern = originalPatternsCache[i]; + if (originalPattern == null) { + originalPattern = currentPattern.getPatternForItem(currentPatternStack, getWorldObj()); + originalPatternsCache[i] = originalPattern; + } + if (originalPattern != null) { + IFluidCraftingPatternDetails pattern = new CraftingPattern2(originalPattern); + this.patternHandlers.add(pattern); + ItemStack is = makeCraftingPatternItem(pattern); + if (is == null) continue; + ICraftingPatternDetails p = ((ICraftingPatternItem) is.getItem()) + .getPatternForItem(is, getWorldObj()); + this.patternConvert.put(p, pattern); + craftingTracker.addCraftingOption(this, p); + } + } + } + } + + private void pushItems() { + this.export.addAll(this.addToExport); + this.addToExport.clear(); + if (!hasWorldObj() || this.export.isEmpty()) return; + ForgeDirection[] directions = ForgeDirection.VALID_DIRECTIONS; + for (ForgeDirection dir : directions) { + TileEntity tile = getWorldObj() + .getTileEntity(this.xCoord + dir.offsetX, this.yCoord + dir.offsetY, this.zCoord + dir.offsetZ); + if (tile != null) { + IAEStack stack0 = this.export.get(0); + IAEStack stack = stack0.copy(); + if (stack instanceof IAEItemStack && tile instanceof IInventory) { + InventoryAdaptor adaptor = InventoryAdaptor.getAdaptor(tile, dir.getOpposite()); + if (adaptor != null) { + final ItemStack adding = ((IAEItemStack) stack).getItemStack(); + final int originalAddingAmount = adding.stackSize; + final ItemStack leftover = adaptor.addItems(adding); + // calculate how much to remove, because getItemStack() limits stack size from a long to an int + final int leftoverAmount = leftover == null ? 0 : leftover.stackSize; + final int removedAmount = originalAddingAmount - leftoverAmount; + if ((long) removedAmount == stack0.getStackSize()) { + this.export.remove(0); + } else { + this.export.get(0).setStackSize(stack0.getStackSize() - removedAmount); + } + return; + } + } else if (stack instanceof IAEFluidStack && tile instanceof IFluidHandler) { + IFluidHandler handler = (IFluidHandler) tile; + IAEFluidStack fluid = (IAEFluidStack) stack; + if (handler.canFill(dir.getOpposite(), fluid.copy().getFluid())) { + int amount = handler.fill(dir.getOpposite(), fluid.getFluidStack().copy(), false); + if (amount == 0) continue; + if (amount == fluid.getStackSize()) { + handler.fill(dir.getOpposite(), fluid.getFluidStack().copy(), true); + this.export.remove(0); + } else { + FluidStack fl = fluid.getFluidStack().copy(); + fl.amount = amount; + this.export.get(0) + .setStackSize(fluid.getStackSize() - handler.fill(dir.getOpposite(), fl, true)); + return; + } + } + } + } + } + } + + @Override + public boolean pushPattern(ICraftingPatternDetails patDetails, InventoryCrafting table) { + if (isBusy() || !this.patternConvert.containsKey(patDetails)) return false; + ICraftingPatternDetails patternDetails = this.patternConvert.get(patDetails); + if (patternDetails instanceof CraftingPattern) { + CraftingPattern patter = (CraftingPattern) patternDetails; + HashMap fluids = new HashMap(); + for (IAEFluidStack stack : patter.getCondensedFluidInputs()) { + if (fluids.containsKey(stack.getFluid())) { + Long amount = fluids.get(stack.getFluid()) + stack.getStackSize(); + fluids.remove(stack.getFluid()); + fluids.put(stack.getFluid(), amount); + } else { + fluids.put(stack.getFluid(), stack.getStackSize()); + } + } + IGrid grid = this.node.getGrid(); + if (grid == null) return false; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return false; + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, amount.intValue())), + Actionable.SIMULATE, + new MachineSource(this)); + if (extractFluid == null || extractFluid.getStackSize() != amount) { + return false; + } + } + for (Fluid fluid : fluids.keySet()) { + Long amount = fluids.get(fluid); + IAEFluidStack extractFluid = storage.getFluidInventory().extractItems( + AEApi.instance().storage().createFluidStack(new FluidStack(fluid, amount.intValue())), + Actionable.MODULATE, + new MachineSource(this)); + this.export.add(extractFluid.copy()); + } + for (IAEItemStack s : patter.getCondensedInputs()) { + if (s == null) continue; + if (s.getItem() == ItemEnum.FLUIDPATTERN.getItem()) { + this.toExport = s.copy(); + continue; + } + this.export.add(s.copy()); + } + } + return true; + } + + public void readFilter(NBTTagCompound tag) { + for (int i = 0; i < this.fluidFilter.length; i++) { + if (tag.hasKey("fluid#" + i)) this.fluidFilter[i] = tag.getInteger("fluid#" + i); + } + } + + @Override + public void readFromNBT(NBTTagCompound tag) { + super.readFromNBT(tag); + for (int i = 0; i < this.tanks.length; i++) { + if (tag.hasKey("tank#" + i)) this.tanks[i].readFromNBT(tag.getCompoundTag("tank#" + i)); + if (tag.hasKey("filter#" + i)) this.fluidFilter[i] = tag.getInteger("filter#" + i); + } + if (hasWorldObj()) { + IGridNode node = getGridNode(ForgeDirection.UNKNOWN); + if (tag.hasKey("nodes") && node != null) { + node.loadFromNBT("node0", tag.getCompoundTag("nodes")); + node.updateState(); + } + } + if (tag.hasKey("inventory")) this.inventory.readFromNBT(tag.getCompoundTag("inventory")); + if (tag.hasKey("export")) readOutputFromNBT(tag.getCompoundTag("export")); + } + + private void readOutputFromNBT(NBTTagCompound tag) { + this.addToExport.clear(); + this.export.clear(); + int i = tag.getInteger("add"); + for (int j = 0; j < i; j++) { + if (tag.getBoolean("add-" + j + "-isItem")) { + IAEItemStack s = AEApi.instance().storage() + .createItemStack(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("add-" + j))); + s.setStackSize(tag.getLong("add-" + j + "-amount")); + this.addToExport.add(s); + } else { + IAEFluidStack s = AEApi.instance().storage() + .createFluidStack(FluidStack.loadFluidStackFromNBT(tag.getCompoundTag("add-" + j))); + s.setStackSize(tag.getLong("add-" + j + "-amount")); + this.addToExport.add(s); + } + } + i = tag.getInteger("export"); + for (int j = 0; j < i; j++) { + if (tag.getBoolean("export-" + j + "-isItem")) { + IAEItemStack s = AEApi.instance().storage() + .createItemStack(ItemStack.loadItemStackFromNBT(tag.getCompoundTag("export-" + j))); + s.setStackSize(tag.getLong("export-" + j + "-amount")); + this.export.add(s); + } else { + IAEFluidStack s = AEApi.instance().storage() + .createFluidStack(FluidStack.loadFluidStackFromNBT(tag.getCompoundTag("export-" + j))); + s.setStackSize(tag.getLong("export-" + j + "-amount")); + this.export.add(s); + } + } + } + + public void registerListener(IContainerListener listener) { + this.listeners.add(listener); + } + + public void removeListener(IContainerListener listener) { + this.listeners.remove(listener); + } + + @Override + public void securityBreak() {} + + @Override + public void setFilter(ForgeDirection side, Fluid fluid) { + if (side == null || side == ForgeDirection.UNKNOWN) return; + if (fluid == null) { + this.fluidFilter[side.ordinal()] = -1; + this.doNextUpdate = true; + return; + } + this.fluidFilter[side.ordinal()] = fluid.getID(); + this.doNextUpdate = true; + } + + @Override + public void setFluid(int _index, Fluid _fluid, EntityPlayer _player) { + setFilter(ForgeDirection.getOrientation(_index), _fluid); + } + + @Override + public void setFluidTank(ForgeDirection side, FluidStack fluid) { + if (side == null || side == ForgeDirection.UNKNOWN) return; + this.tanks[side.ordinal()].setFluid(fluid); + this.doNextUpdate = true; + } + + private void tick() { + if (this.tickCount >= 40 || !this.wasIdle) { + this.tickCount = 0; + this.wasIdle = true; + } else { + this.tickCount++; + return; + } + if (this.node == null) return; + IGrid grid = this.node.getGrid(); + if (grid == null) return; + IStorageGrid storage = grid.getCache(IStorageGrid.class); + if (storage == null) return; + if (this.toExport != null) { + storage.getItemInventory().injectItems(this.toExport, Actionable.MODULATE, new MachineSource(this)); + this.toExport = null; + } + for (int i = 0; i < this.tanks.length; i++) { + FluidTank tank = this.tanks[i]; + if (tank.getFluid() != null && FluidRegistry.getFluid(this.fluidFilter[i]) != tank.getFluid().getFluid()) { + FluidStack s = tank.drain(1000, false); + if (s != null) { + IAEFluidStack notAdded = storage.getFluidInventory().injectItems( + AEApi.instance().storage().createFluidStack(s), + Actionable.SIMULATE, + new MachineSource(this)); + int toAdd = s.amount - (notAdded != null ? (int) notAdded.getStackSize() : 0); + IAEFluidStack actuallyNotInjected = storage.getFluidInventory().injectItems( + AEApi.instance().storage().createFluidStack(tank.drain(toAdd, true)), + Actionable.MODULATE, + new MachineSource(this)); + if (actuallyNotInjected != null) { + int returned = tank.fill(actuallyNotInjected.getFluidStack(), true); + if (returned != actuallyNotInjected.getStackSize()) { + FMLLog.severe( + "[ExtraCells2] Interface tank import at %d:%d,%d,%d voided %d mL of %s", + this.getWorldObj().provider.dimensionId, + this.xCoord, + this.yCoord, + this.zCoord, + actuallyNotInjected.getStackSize() - returned, + actuallyNotInjected.getFluid().getName()); + } + } + this.doNextUpdate = true; + } + } + if ((tank.getFluid() == null || (tank.getFluid().getFluid() == FluidRegistry.getFluid(this.fluidFilter[i]) + && tank.getFluidAmount() < tank.getCapacity())) + && FluidRegistry.getFluid(this.fluidFilter[i]) != null) { + IAEFluidStack request = FluidUtil.createAEFluidStack(this.fluidFilter[i], 1000); + IAEFluidStack extracted = storage.getFluidInventory() + .extractItems(request, Actionable.SIMULATE, new MachineSource(this)); + if (extracted == null) continue; + int accepted = tank.fill(extracted.getFluidStack(), false); + if (accepted == 0) continue; + request.setStackSize(Long.min(accepted, extracted.getStackSize())); + extracted = storage.getFluidInventory() + .extractItems(request, Actionable.MODULATE, new MachineSource(this)); + if (extracted == null || extracted.getStackSize() <= 0) { + continue; + } + accepted = tank.fill(extracted.getFluidStack(), true); + if (extracted.getStackSize() != accepted) { + // This should never happen, but log it in case it does + FMLLog.severe( + "[ExtraCells2] Interface tank export at %d:%d,%d,%d voided %d mL of %s", + this.getWorldObj().provider.dimensionId, + this.xCoord, + this.yCoord, + this.zCoord, + extracted.getStackSize() - accepted, + request.getFluid().getName()); + } + this.doNextUpdate = true; + } + } + } + + @Override + public void updateEntity() { + if (getWorldObj() == null || getWorldObj().provider == null || getWorldObj().isRemote) return; + if (this.update) { + this.update = false; + if (getGridNode(ForgeDirection.UNKNOWN) != null && getGridNode(ForgeDirection.UNKNOWN).getGrid() != null) { + getGridNode(ForgeDirection.UNKNOWN).getGrid() + .postEvent(new MENetworkCraftingPatternChange(this, getGridNode(ForgeDirection.UNKNOWN))); + } + } + pushItems(); + if (this.doNextUpdate) forceUpdate(); + tick(); + } + + public NBTTagCompound writeFilter(NBTTagCompound tag) { + for (int i = 0; i < this.fluidFilter.length; i++) { + tag.setInteger("fluid#" + i, this.fluidFilter[i]); + } + return tag; + } + + private NBTTagCompound writeOutputToNBT(NBTTagCompound tag) { + int i = 0; + i = 0; + for (IAEStack s : this.addToExport) { + if (s != null) { + tag.setBoolean("add-" + i + "-isItem", s.isItem()); + NBTTagCompound data = new NBTTagCompound(); + if (s.isItem()) { + ((IAEItemStack) s).getItemStack().writeToNBT(data); + } else { + ((IAEFluidStack) s).getFluidStack().writeToNBT(data); + } ; + tag.setTag("add-" + i, data); + tag.setLong("add-" + i + "-amount", s.getStackSize()); + } + i++; + } + tag.setInteger("add", this.addToExport.size()); + i = 0; + for (IAEStack s : this.export) { + if (s != null) { + tag.setBoolean("export-" + i + "-isItem", s.isItem()); + NBTTagCompound data = new NBTTagCompound(); + if (s.isItem()) { + ((IAEItemStack) s).getItemStack().writeToNBT(data); + } else { + ((IAEFluidStack) s).getFluidStack().writeToNBT(data); + } + tag.setTag("export-" + i, data); + tag.setLong("export-" + i + "-amount", s.getStackSize()); + } + i++; + } + tag.setInteger("export", this.export.size()); + return tag; + } + + @Override + public void writeToNBT(NBTTagCompound data) { + writeToNBTWithoutExport(data); + NBTTagCompound tag = new NBTTagCompound(); + writeOutputToNBT(tag); + data.setTag("export", tag); + } + + public void writeToNBTWithoutExport(NBTTagCompound tag) { + super.writeToNBT(tag); + for (int i = 0; i < this.tanks.length; i++) { + tag.setTag("tank#" + i, this.tanks[i].writeToNBT(new NBTTagCompound())); + tag.setInteger("filter#" + i, this.fluidFilter[i]); + } + if (!hasWorldObj()) return; + IGridNode node = getGridNode(ForgeDirection.UNKNOWN); + if (node != null) { + NBTTagCompound nodeTag = new NBTTagCompound(); + node.saveToNBT("node0", nodeTag); + tag.setTag("nodes", nodeTag); + } + NBTTagCompound inventory = new NBTTagCompound(); + this.inventory.writeToNBT(inventory); + tag.setTag("inventory", inventory); + } } diff --git a/src/main/scala/extracells/tileentity/TileEntityHardMeDrive.java b/src/main/scala/extracells/tileentity/TileEntityHardMeDrive.java index 7b68a3ae3..f1f867da0 100644 --- a/src/main/scala/extracells/tileentity/TileEntityHardMeDrive.java +++ b/src/main/scala/extracells/tileentity/TileEntityHardMeDrive.java @@ -1,5 +1,14 @@ package extracells.tileentity; +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.inventory.IInventory; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.network.Packet; +import net.minecraft.network.play.server.S35PacketUpdateTileEntity; +import net.minecraftforge.common.util.ForgeDirection; import appeng.api.AEApi; import appeng.api.networking.IGrid; @@ -13,27 +22,18 @@ import extracells.gridblock.ECGridBlockHardMEDrive; import extracells.util.inventory.ECPrivateInventory; import extracells.util.inventory.IInventoryUpdateReceiver; -import net.minecraft.inventory.IInventory; -import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.network.Packet; -import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -import net.minecraftforge.common.util.ForgeDirection; -import java.util.ArrayList; -import java.util.List; +public class TileEntityHardMeDrive extends TileBase + implements IActionHost, IECTileEntity, ICellContainer, IInventoryUpdateReceiver { -public class TileEntityHardMeDrive extends TileBase implements IActionHost, IECTileEntity, ICellContainer, IInventoryUpdateReceiver{ - - private int priority = 0; + private int priority = 0; boolean isFirstGridNode = true; byte[] cellStatuses = new byte[3]; List fluidHandlers = new ArrayList(); List itemHandlers = new ArrayList(); private final ECGridBlockHardMEDrive gridBlock = new ECGridBlockHardMEDrive(this); - private ECPrivateInventory inventory = new ECPrivateInventory( - "extracells.part.drive", 3, 1, this) { + private ECPrivateInventory inventory = new ECPrivateInventory("extracells.part.drive", 3, 1, this) { ICellRegistry cellRegistry = AEApi.instance().registries().cell(); @@ -43,17 +43,14 @@ public boolean isItemValidForSlot(int i, ItemStack itemStack) { } }; - public IInventory getInventory(){ + public IInventory getInventory() { return inventory; } IGridNode node = null; - @Override - public void blinkCell(int i) { - - } + public void blinkCell(int i) {} @Override public IGridNode getActionableNode() { @@ -62,10 +59,8 @@ public IGridNode getActionableNode() { @Override public List getCellArray(StorageChannel channel) { - if (!isActive()) - return new ArrayList(); - return channel == StorageChannel.ITEMS ? this.itemHandlers - : this.fluidHandlers; + if (!isActive()) return new ArrayList(); + return channel == StorageChannel.ITEMS ? this.itemHandlers : this.fluidHandlers; } @Override @@ -85,12 +80,12 @@ public double getPowerUsage() { @Override public IGridNode getGridNode(ForgeDirection forgeDirection) { - if (isFirstGridNode && hasWorldObj() && !getWorldObj().isRemote){ + if (isFirstGridNode && hasWorldObj() && !getWorldObj().isRemote) { isFirstGridNode = false; - try{ + try { node = AEApi.instance().createGridNode(gridBlock); node.updateState(); - }catch (Exception e){ + } catch (Exception e) { isFirstGridNode = true; } } @@ -104,18 +99,14 @@ public AECableType getCableConnectionType(ForgeDirection forgeDirection) { } @Override - public void securityBreak() { - - } + public void securityBreak() {} @Override - public void saveChanges(IMEInventory imeInventory) { + public void saveChanges(IMEInventory imeInventory) {} - } - - //TODO - boolean isActive(){ - return true; + // TODO + boolean isActive() { + return true; } public int getColorByStatus(int status) { @@ -137,24 +128,16 @@ public void onInventoryChanged() { this.fluidHandlers = updateHandlers(StorageChannel.FLUIDS); for (int i = 0; i < this.cellStatuses.length; i++) { ItemStack stackInSlot = this.inventory.getStackInSlot(i); - IMEInventoryHandler inventoryHandler = AEApi.instance() - .registries().cell() + IMEInventoryHandler inventoryHandler = AEApi.instance().registries().cell() .getCellInventory(stackInSlot, null, StorageChannel.ITEMS); - if (inventoryHandler == null) - inventoryHandler = AEApi - .instance() - .registries() - .cell() - .getCellInventory(stackInSlot, null, - StorageChannel.FLUIDS); - - ICellHandler cellHandler = AEApi.instance().registries().cell() - .getHandler(stackInSlot); + if (inventoryHandler == null) inventoryHandler = AEApi.instance().registries().cell() + .getCellInventory(stackInSlot, null, StorageChannel.FLUIDS); + + ICellHandler cellHandler = AEApi.instance().registries().cell().getHandler(stackInSlot); if (cellHandler == null || inventoryHandler == null) { this.cellStatuses[i] = 0; } else { - this.cellStatuses[i] = (byte) cellHandler.getStatusForCell( - stackInSlot, inventoryHandler); + this.cellStatuses[i] = (byte) cellHandler.getStatusForCell(stackInSlot, inventoryHandler); } } IGridNode node = getGridNode(ForgeDirection.UNKNOWN); @@ -173,24 +156,22 @@ private List updateHandlers(StorageChannel channel) { for (int i = 0; i < this.inventory.getSizeInventory(); i++) { ItemStack cell = this.inventory.getStackInSlot(i); if (cellRegistry.isCellHandled(cell)) { - IMEInventoryHandler cellInventory = cellRegistry - .getCellInventory(cell, null, channel); - if (cellInventory != null) - handlers.add(cellInventory); + IMEInventoryHandler cellInventory = cellRegistry.getCellInventory(cell, null, channel); + if (cellInventory != null) handlers.add(cellInventory); } } return handlers; } @Override - public void readFromNBT(NBTTagCompound tag){ + public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); inventory.readFromNBT(tag.getTagList("inventory", 10)); onInventoryChanged(); } @Override - public void writeToNBT(NBTTagCompound tag){ + public void writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tag.setTag("inventory", inventory.writeToNBT()); } diff --git a/src/main/scala/extracells/tileentity/TileEntityVibrationChamberFluid.scala b/src/main/scala/extracells/tileentity/TileEntityVibrationChamberFluid.scala index 2927f1f96..e19cf72c6 100644 --- a/src/main/scala/extracells/tileentity/TileEntityVibrationChamberFluid.scala +++ b/src/main/scala/extracells/tileentity/TileEntityVibrationChamberFluid.scala @@ -15,7 +15,12 @@ import net.minecraft.network.{NetworkManager, Packet} import net.minecraftforge.common.util.ForgeDirection import net.minecraftforge.fluids._ -class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with IFluidHandler with IActionHost with TPowerStorage { +class TileEntityVibrationChamberFluid + extends TileBase + with IECTileEntity + with IFluidHandler + with IActionHost + with TPowerStorage { private[tileentity] var isFirstGridNode: Boolean = true private final val gridBlock = new ECGridBlockVibrantChamber(this) private[tileentity] var node: IGridNode = null @@ -29,8 +34,7 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I if (!nbt.hasKey("Empty")) { val fluid: FluidStack = FluidStack.loadFluidStackFromNBT(nbt) setFluid(fluid) - } - else { + } else { setFluid(null) } return this @@ -48,7 +52,8 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I worldObj.markBlockForUpdate(this.xCoord, this.yCoord, this.zCoord) val fluidStack: FluidStack = tank.getFluid var bTime: Int = 0 - if (fluidStack != null) bTime = FuelBurnTime.getBurnTime(fluidStack.getFluid) + if (fluidStack != null) + bTime = FuelBurnTime.getBurnTime(fluidStack.getFluid) else bTime = 0 if (fluidStack != null && bTime > 0) { if (tank.getFluid.amount >= 250) { @@ -60,25 +65,23 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I } } timer = 0 - } - else { + } else { timer += 1 } - } - else { + } else { burnTime += 1 if (timerEnergy == 4) { if (energyLeft == 0) { - val energy: IEnergyGrid = getGridNode(ForgeDirection.UNKNOWN).getGrid.getCache(classOf[IEnergyGrid]) - energyLeft = energy.injectPower(24.0D, Actionable.MODULATE) - } - else { - val energy: IEnergyGrid = getGridNode(ForgeDirection.UNKNOWN).getGrid.getCache(classOf[IEnergyGrid]) + val energy: IEnergyGrid = getGridNode(ForgeDirection.UNKNOWN).getGrid + .getCache(classOf[IEnergyGrid]) + energyLeft = energy.injectPower(24.0d, Actionable.MODULATE) + } else { + val energy: IEnergyGrid = getGridNode(ForgeDirection.UNKNOWN).getGrid + .getCache(classOf[IEnergyGrid]) energyLeft = energy.injectPower(energyLeft, Actionable.MODULATE) } timerEnergy = 0 - } - else { + } else { timerEnergy += 1 } } @@ -99,8 +102,7 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I override def getLocation: DimensionalCoord = new DimensionalCoord(this) - override def getPowerUsage = 0.0D - + override def getPowerUsage = 0.0d override def getGridNode(forgeDirection: ForgeDirection): IGridNode = { if (isFirstGridNode && hasWorldObj && !getWorldObj.isRemote) { @@ -108,8 +110,7 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I try { node = AEApi.instance.createGridNode(gridBlock) node.updateState - } - catch { + } catch { case e: Exception => { isFirstGridNode = true } @@ -118,13 +119,12 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I node } - def getGridNodeWithoutUpdate: IGridNode ={ + def getGridNodeWithoutUpdate: IGridNode = { if (isFirstGridNode && hasWorldObj && !getWorldObj.isRemote) { isFirstGridNode = false try { node = AEApi.instance.createGridNode(gridBlock) - } - catch { + } catch { case e: Exception => { isFirstGridNode = true } @@ -133,22 +133,38 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I node } - override def getCableConnectionType(forgeDirection: ForgeDirection) = AECableType.SMART + override def getCableConnectionType(forgeDirection: ForgeDirection) = + AECableType.SMART override def securityBreak {} - override def fill(from: ForgeDirection, resource: FluidStack, doFill: Boolean): Int = { - if (resource == null || resource.getFluid == null || FuelBurnTime.getBurnTime(resource.getFluid) == 0) return 0 + override def fill( + from: ForgeDirection, + resource: FluidStack, + doFill: Boolean + ): Int = { + if ( + resource == null || resource.getFluid == null || FuelBurnTime.getBurnTime( + resource.getFluid + ) == 0 + ) return 0 val filled: Int = tank.fill(resource, doFill) - if (filled != 0 && hasWorldObj) getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord) + if (filled != 0 && hasWorldObj) + getWorldObj.markBlockForUpdate(xCoord, yCoord, zCoord) filled } - override def drain(from: ForgeDirection, resource: FluidStack, doDrain: Boolean): FluidStack = null - - - override def drain(from: ForgeDirection, maxDrain: Int, doDrain: Boolean): FluidStack = null + override def drain( + from: ForgeDirection, + resource: FluidStack, + doDrain: Boolean + ): FluidStack = null + override def drain( + from: ForgeDirection, + maxDrain: Int, + doDrain: Boolean + ): FluidStack = null override def canFill(from: ForgeDirection, fluid: Fluid): Boolean = { if (fluid == null || FuelBurnTime.getBurnTime(fluid) == 0) return false @@ -157,12 +173,11 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I override def canDrain(from: ForgeDirection, fluid: Fluid): Boolean = false - override def getTankInfo(from: ForgeDirection): Array[FluidTankInfo] = Array[FluidTankInfo](tank.getInfo) - + override def getTankInfo(from: ForgeDirection): Array[FluidTankInfo] = + Array[FluidTankInfo](tank.getInfo) def getTank: FluidTank = tank - override def writeToNBT(nbt: NBTTagCompound) { super.writeToNBT(nbt) writePowerToNBT(nbt) @@ -178,14 +193,15 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I super.readFromNBT(nbt) readPowerFromNBT(nbt) if (nbt.hasKey("BurnTime")) this.burnTime = nbt.getInteger("BurnTime") - if (nbt.hasKey("BurnTimeTotal")) this.burnTimeTotal = nbt.getInteger("BurnTimeTotal") + if (nbt.hasKey("BurnTimeTotal")) + this.burnTimeTotal = nbt.getInteger("BurnTimeTotal") if (nbt.hasKey("timer")) this.timer = nbt.getInteger("timer") - if (nbt.hasKey("timerEnergy")) this.timerEnergy = nbt.getInteger("timerEnergy") + if (nbt.hasKey("timerEnergy")) + this.timerEnergy = nbt.getInteger("timerEnergy") if (nbt.hasKey("energyLeft")) this.energyLeft = nbt.getDouble("energyLeft") tank.readFromNBT(nbt) } - def getBurntTimeScaled(scal: Int): Int = { return if (burnTime != 0) burnTime * scal / burnTimeTotal else 0 } @@ -197,10 +213,19 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I override def getDescriptionPacket: Packet = { val nbtTag: NBTTagCompound = new NBTTagCompound writeToNBT(nbtTag) - return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, this.getBlockMetadata, nbtTag) + return new S35PacketUpdateTileEntity( + this.xCoord, + this.yCoord, + this.zCoord, + this.getBlockMetadata, + nbtTag + ) } - override def onDataPacket(net: NetworkManager, pkt: S35PacketUpdateTileEntity) { + override def onDataPacket( + net: NetworkManager, + pkt: S35PacketUpdateTileEntity + ) { readFromNBT(pkt.func_148857_g) } @@ -212,4 +237,3 @@ class TileEntityVibrationChamberFluid extends TileBase with IECTileEntity with I return burnTimeTotal } } - diff --git a/src/main/scala/extracells/tileentity/TileEntityWalrus.java b/src/main/scala/extracells/tileentity/TileEntityWalrus.java index a984cff62..713206860 100644 --- a/src/main/scala/extracells/tileentity/TileEntityWalrus.java +++ b/src/main/scala/extracells/tileentity/TileEntityWalrus.java @@ -4,8 +4,8 @@ public class TileEntityWalrus extends TileEntity { - @Override - public boolean canUpdate() { - return false; - } + @Override + public boolean canUpdate() { + return false; + } } diff --git a/src/main/scala/extracells/util/AdvancedCellHandler.java b/src/main/scala/extracells/util/AdvancedCellHandler.java new file mode 100644 index 000000000..0b358be4c --- /dev/null +++ b/src/main/scala/extracells/util/AdvancedCellHandler.java @@ -0,0 +1,66 @@ +package extracells.util; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; + +import appeng.api.implementations.tiles.IChestOrDrive; +import appeng.api.storage.*; +import appeng.client.texture.ExtraBlockTextures; +import appeng.core.sync.GuiBridge; +import appeng.util.Platform; +import extracells.inventory.AdvancedCellInventory; +import extracells.inventory.AdvancedCellInventoryHandler; + +public class AdvancedCellHandler implements ICellHandler { + + @Override + public boolean isCell(final ItemStack is) { + return AdvancedCellInventory.isCell(is); + } + + @Override + public IMEInventoryHandler getCellInventory(final ItemStack is, final ISaveProvider container, + final StorageChannel channel) { + if (channel == StorageChannel.ITEMS) { + return AdvancedCellInventory.getCell(is, container); + } + return null; + } + + @Override + public IIcon getTopTexture_Light() { + return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); + } + + @Override + public IIcon getTopTexture_Medium() { + return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); + } + + @Override + public IIcon getTopTexture_Dark() { + return ExtraBlockTextures.BlockMEChestItems_Dark.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 int getStatusForCell(final ItemStack is, final IMEInventory handler) { + if (handler instanceof AdvancedCellInventoryHandler) { + final AdvancedCellInventoryHandler ci = (AdvancedCellInventoryHandler) handler; + return ci.getStatusForCell(); + } + return 0; + } + + @Override + public double cellIdleDrain(final ItemStack is, final IMEInventory handler) { + return 10.0; + } +} diff --git a/src/main/scala/extracells/util/ColorUtil.java b/src/main/scala/extracells/util/ColorUtil.java index ca72705cd..8c50cae2e 100644 --- a/src/main/scala/extracells/util/ColorUtil.java +++ b/src/main/scala/extracells/util/ColorUtil.java @@ -4,19 +4,19 @@ public class ColorUtil { - public static Color getInvertedColor(Color color) { - return new Color(0xFFFFFF - color.getRGB()); - } + public static Color getInvertedColor(Color color) { + return new Color(0xFFFFFF - color.getRGB()); + } - public static Color getInvertedColor(int colorCode) { - return getInvertedColor(new Color(colorCode)); - } + public static Color getInvertedColor(int colorCode) { + return getInvertedColor(new Color(colorCode)); + } - public static int getInvertedInt(Color color) { - return getInvertedColor(color).getRGB(); - } + public static int getInvertedInt(Color color) { + return getInvertedColor(color).getRGB(); + } - public static int getInvertedInt(int colorCode) { - return getInvertedColor(colorCode).getRGB(); - } + public static int getInvertedInt(int colorCode) { + return getInvertedColor(colorCode).getRGB(); + } } diff --git a/src/main/scala/extracells/util/DeprecationWarning.java b/src/main/scala/extracells/util/DeprecationWarning.java new file mode 100644 index 000000000..abd7a405f --- /dev/null +++ b/src/main/scala/extracells/util/DeprecationWarning.java @@ -0,0 +1,20 @@ +package extracells.util; + +import java.util.List; + +import net.minecraft.util.EnumChatFormatting; + +public final class DeprecationWarning { + + private DeprecationWarning() {} + + public static void addContentTransferInfo(List tooltip) { + tooltip.add(EnumChatFormatting.RED + "Contents will be kept when converting it in crafting table."); + tooltip.add(EnumChatFormatting.RED + "You don't need to ME-IO to transfer contents."); + } + + public static void addGeneralDeprecationWarning(List tooltip) { + tooltip.add(EnumChatFormatting.RED + "EC2 is going to be removed in the future!"); + tooltip.add(EnumChatFormatting.RED + "Try to put it in crafting table to convert it into AE2/AE2FC device."); + } +} diff --git a/src/main/scala/extracells/util/EmptyMeItemMonitor.java b/src/main/scala/extracells/util/EmptyMeItemMonitor.java index 3b4120fef..5ee318676 100644 --- a/src/main/scala/extracells/util/EmptyMeItemMonitor.java +++ b/src/main/scala/extracells/util/EmptyMeItemMonitor.java @@ -12,71 +12,65 @@ public class EmptyMeItemMonitor implements IMEMonitor { - @Override - public void addListener(IMEMonitorHandlerReceiver l, - Object verificationToken) { - - } - - @Override - public boolean canAccept(IAEItemStack input) { - return false; - } - - @Override - public IAEItemStack extractItems(IAEItemStack request, Actionable mode, - BaseActionSource src) { - // TODO Auto-generated method stub - return null; - } - - @Override - public AccessRestriction getAccess() { - return AccessRestriction.NO_ACCESS; - } - - @Override - public IItemList getAvailableItems(IItemList out) { - return out; - } - - @Override - public StorageChannel getChannel() { - return StorageChannel.ITEMS; - } - - @Override - public int getPriority() { - return 0; - } - - @Override - public int getSlot() { - return 0; - } - - @Override - public IItemList getStorageList() { - return AEApi.instance().storage().createItemList(); - } - - @Override - public IAEItemStack injectItems(IAEItemStack input, Actionable type, - BaseActionSource src) { - return input; - } - - @Override - public boolean isPrioritized(IAEItemStack input) { - return false; - } - - @Override - public void removeListener(IMEMonitorHandlerReceiver l) {} - - @Override - public boolean validForPass(int i) { - return true; - } - + @Override + public void addListener(IMEMonitorHandlerReceiver l, Object verificationToken) {} + + @Override + public boolean canAccept(IAEItemStack input) { + return false; + } + + @Override + public IAEItemStack extractItems(IAEItemStack request, Actionable mode, BaseActionSource src) { + // TODO Auto-generated method stub + return null; + } + + @Override + public AccessRestriction getAccess() { + return AccessRestriction.NO_ACCESS; + } + + @Override + public IItemList getAvailableItems(IItemList out, int iteration) { + return out; + } + + @Override + public StorageChannel getChannel() { + return StorageChannel.ITEMS; + } + + @Override + public int getPriority() { + return 0; + } + + @Override + public int getSlot() { + return 0; + } + + @Override + public IItemList getStorageList() { + return AEApi.instance().storage().createItemList(); + } + + @Override + public IAEItemStack injectItems(IAEItemStack input, Actionable type, BaseActionSource src) { + return input; + } + + @Override + public boolean isPrioritized(IAEItemStack input) { + return false; + } + + @Override + public void removeListener(IMEMonitorHandlerReceiver l) {} + + @Override + public boolean validForPass(int i) { + return true; + } } diff --git a/src/main/scala/extracells/util/ExtraCellsEventHandler.java b/src/main/scala/extracells/util/ExtraCellsEventHandler.java index 38062099d..385fbce6a 100644 --- a/src/main/scala/extracells/util/ExtraCellsEventHandler.java +++ b/src/main/scala/extracells/util/ExtraCellsEventHandler.java @@ -1,5 +1,10 @@ package extracells.util; +import net.minecraft.inventory.Container; +import net.minecraft.tileentity.TileEntity; +import net.minecraftforge.common.util.ForgeDirection; +import net.minecraftforge.event.world.BlockEvent; + import appeng.api.config.SecurityPermissions; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.TickEvent; @@ -7,36 +12,34 @@ import extracells.api.IECTileEntity; import extracells.container.ContainerFluidStorage; import extracells.container.ContainerGasStorage; -import net.minecraft.inventory.Container; -import net.minecraft.tileentity.TileEntity; -import net.minecraftforge.common.util.ForgeDirection; -import net.minecraftforge.event.world.BlockEvent; public class ExtraCellsEventHandler { - @SubscribeEvent - public void onBlockBreak(BlockEvent.BreakEvent event) { - TileEntity tile = event.world.getTileEntity(event.x, event.y, event.z); - if (tile instanceof IECTileEntity) { - if (!PermissionUtil.hasPermission(event.getPlayer(), - SecurityPermissions.BUILD, - ((IECTileEntity) tile).getGridNode(ForgeDirection.UNKNOWN))) - event.setCanceled(true); - } - } + @SubscribeEvent + public void onBlockBreak(BlockEvent.BreakEvent event) { + TileEntity tile = event.world.getTileEntity(event.x, event.y, event.z); + if (tile instanceof IECTileEntity) { + if (!PermissionUtil.hasPermission( + event.getPlayer(), + SecurityPermissions.BUILD, + ((IECTileEntity) tile).getGridNode(ForgeDirection.UNKNOWN))) + event.setCanceled(true); + } + } - @SubscribeEvent - public void onPlayerTick(TickEvent.PlayerTickEvent event) { - if (event.phase == TickEvent.Phase.START && event.side == Side.SERVER - && event.player != null) { - if (event.player.openContainer != null) { - Container con = event.player.openContainer; - if (con instanceof ContainerFluidStorage) { - ((ContainerFluidStorage) con).removeEnergyTick(); - }else if (con instanceof ContainerGasStorage) { - ((ContainerGasStorage) con).removeEnergyTick(); - } - } - } - } + @SubscribeEvent + public void onPlayerTick(TickEvent.PlayerTickEvent event) { + if (event.phase == TickEvent.Phase.START && event.side == Side.SERVER && event.player != null) { + if (event.player.openContainer != null) { + Container con = event.player.openContainer; + if (con instanceof ContainerFluidStorage) { + ((ContainerFluidStorage) con).removeEnergyTick(); + ((ContainerFluidStorage) con).doWork(); + } else if (con instanceof ContainerGasStorage) { + ((ContainerGasStorage) con).removeEnergyTick(); + ((ContainerGasStorage) con).doWork(); + } + } + } + } } diff --git a/src/main/scala/extracells/util/FluidCellHandler.java b/src/main/scala/extracells/util/FluidCellHandler.java index ec35a75fb..083989130 100644 --- a/src/main/scala/extracells/util/FluidCellHandler.java +++ b/src/main/scala/extracells/util/FluidCellHandler.java @@ -1,5 +1,10 @@ package extracells.util; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IIcon; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.implementations.tiles.IChestOrDrive; import appeng.api.implementations.tiles.IMEChest; import appeng.api.networking.security.PlayerSource; @@ -9,80 +14,87 @@ import extracells.inventory.HandlerItemStorageFluid; import extracells.network.GuiHandler; import extracells.render.TextureManager; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; -import net.minecraft.util.IIcon; -import net.minecraftforge.common.util.ForgeDirection; - public class FluidCellHandler implements ICellHandler { - @Override - public double cellIdleDrain(ItemStack is, IMEInventory handler) { - return 0; - } - - @Override - public IMEInventoryHandler getCellInventory(ItemStack itemStack, ISaveProvider saveProvider, StorageChannel channel) { - if (channel == StorageChannel.ITEMS || !(itemStack.getItem() instanceof IFluidStorageCell)) { - return null; - } - return new HandlerItemStorageFluid(itemStack, saveProvider, ((IFluidStorageCell) itemStack.getItem()).getFilter(itemStack)); - } + @Override + public double cellIdleDrain(ItemStack is, IMEInventory handler) { + if (!(is.getItem() instanceof IFluidStorageCell)) { + return 0.0; + } + final IFluidStorageCell cell = (IFluidStorageCell) is.getItem(); + return cell.idleDrain(is); + } - public IMEInventoryHandler getCellInventoryPlayer(ItemStack itemStack, EntityPlayer player) { - return new HandlerItemPlayerStorageFluid(itemStack, null, ((IFluidStorageCell) itemStack.getItem()).getFilter(itemStack), player); - } + @Override + public IMEInventoryHandler getCellInventory(ItemStack itemStack, ISaveProvider saveProvider, + StorageChannel channel) { + if (channel == StorageChannel.ITEMS || !(itemStack.getItem() instanceof IFluidStorageCell)) { + return null; + } + return new HandlerItemStorageFluid( + itemStack, + saveProvider, + ((IFluidStorageCell) itemStack.getItem()).getFilter(itemStack)); + } - @Override - public int getStatusForCell(ItemStack is, IMEInventory handler) { - if (handler == null) { - return 0; - } + public IMEInventoryHandler getCellInventoryPlayer(ItemStack itemStack, EntityPlayer player) { + return new HandlerItemPlayerStorageFluid( + itemStack, + null, + ((IFluidStorageCell) itemStack.getItem()).getFilter(itemStack), + player); + } - HandlerItemStorageFluid inventory = (HandlerItemStorageFluid) handler; - if (inventory.freeBytes() == 0) { - return 3; - } - if (inventory.isFormatted() || inventory.usedTypes() == inventory.totalTypes()) { - return 2; - } + @Override + public int getStatusForCell(ItemStack is, IMEInventory handler) { + if (handler == null) { + return 0; + } - return 1; - } + HandlerItemStorageFluid inventory = (HandlerItemStorageFluid) handler; + if (inventory.freeBytes() == 0) { + return 3; + } + if (inventory.isFormatted() || inventory.usedTypes() == inventory.totalTypes()) { + return 2; + } - @Override - public IIcon getTopTexture_Dark() { - return TextureManager.TERMINAL_FRONT.getTextures()[0]; - } + return 1; + } - @Override - public IIcon getTopTexture_Light() { - return TextureManager.TERMINAL_FRONT.getTextures()[2]; - } + @Override + public IIcon getTopTexture_Dark() { + return TextureManager.TERMINAL_FRONT.getTextures()[0]; + } - @Override - public IIcon getTopTexture_Medium() { - return TextureManager.TERMINAL_FRONT.getTextures()[1]; - } + @Override + public IIcon getTopTexture_Light() { + return TextureManager.TERMINAL_FRONT.getTextures()[2]; + } - @Override - public boolean isCell(ItemStack is) { - return is != null && is.getItem() != null && is.getItem() instanceof IFluidStorageCell; - } + @Override + public IIcon getTopTexture_Medium() { + return TextureManager.TERMINAL_FRONT.getTextures()[1]; + } - @Override - public void openChestGui(EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, IMEInventoryHandler inv, ItemStack is, StorageChannel chan) { - if (chan != StorageChannel.FLUIDS) { - return; - } - IStorageMonitorable monitorable = null; - if (chest != null) { - monitorable = ((IMEChest) chest).getMonitorable(ForgeDirection.UNKNOWN, new PlayerSource(player, chest)); - } - if (monitorable != null) { - GuiHandler.launchGui(GuiHandler.getGuiId(0), player, new Object[]{monitorable.getFluidInventory()}); - } - } + @Override + public boolean isCell(ItemStack is) { + return is != null && is.getItem() != null && is.getItem() instanceof IFluidStorageCell; + } + @Override + public void openChestGui(EntityPlayer player, IChestOrDrive chest, ICellHandler cellHandler, + IMEInventoryHandler inv, ItemStack is, StorageChannel chan) { + if (chan != StorageChannel.FLUIDS) { + return; + } + IStorageMonitorable monitorable = null; + if (chest != null) { + monitorable = ((IMEChest) chest).getMonitorable(ForgeDirection.UNKNOWN, new PlayerSource(player, chest)); + } + if (monitorable != null) { + GuiHandler.launchGui(GuiHandler.getGuiId(0), player, new Object[] { monitorable.getFluidInventory() }); + } + } } diff --git a/src/main/scala/extracells/util/FluidUtil.java b/src/main/scala/extracells/util/FluidUtil.java index 19c0ccb58..9381a61d6 100644 --- a/src/main/scala/extracells/util/FluidUtil.java +++ b/src/main/scala/extracells/util/FluidUtil.java @@ -1,155 +1,325 @@ package extracells.util; -import appeng.api.AEApi; -import appeng.api.storage.data.IAEFluidStack; -import extracells.item.ItemFluidPattern; -import extracells.registries.ItemEnum; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.*; + import org.apache.commons.lang3.tuple.MutablePair; +import appeng.api.AEApi; +import appeng.api.config.Actionable; +import appeng.api.networking.security.BaseActionSource; +import appeng.api.storage.IMEMonitor; +import appeng.api.storage.data.IAEFluidStack; +import appeng.api.storage.data.IItemList; +import cpw.mods.fml.common.FMLLog; +import extracells.item.ItemFluidPattern; +import extracells.registries.ItemEnum; + public class FluidUtil { - public static IAEFluidStack createAEFluidStack(Fluid fluid) { - return createAEFluidStack(new FluidStack(fluid, - FluidContainerRegistry.BUCKET_VOLUME)); - } - - public static IAEFluidStack createAEFluidStack(Fluid fluid, long amount) { - return createAEFluidStack(fluid.getID(), amount); - } - - public static IAEFluidStack createAEFluidStack(FluidStack fluid) { - return AEApi.instance().storage().createFluidStack(fluid); - } - - public static IAEFluidStack createAEFluidStack(int fluidId, long amount) { - return createAEFluidStack(new FluidStack(FluidRegistry.getFluid(fluidId), 1)).setStackSize( - amount); - } - - public static MutablePair drainStack( - ItemStack itemStack, FluidStack fluid) { - if (itemStack == null) - return null; - Item item = itemStack.getItem(); - if (item instanceof IFluidContainerItem) { - FluidStack drained = ((IFluidContainerItem) item).drain(itemStack, - fluid.amount, true); - int amountDrained = drained != null - && drained.getFluid() == fluid.getFluid() ? drained.amount - : 0; - return new MutablePair(amountDrained, itemStack); - } else if (FluidContainerRegistry.isContainer(itemStack)) { - FluidStack content = FluidContainerRegistry - .getFluidForFilledItem(itemStack); - int amountDrained = content != null - && content.getFluid() == fluid.getFluid() ? content.amount - : 0; - return new MutablePair(amountDrained, itemStack - .getItem().getContainerItem(itemStack)); - } - - return null; - } - - public static MutablePair fillStack( - ItemStack itemStack, FluidStack fluid) { - if (itemStack == null) - return null; - Item item = itemStack.getItem(); - //If its a fluid container item instance - if (item instanceof IFluidContainerItem) { - //Call the fill method on it. - int filled = ((IFluidContainerItem) item).fill(itemStack, fluid, - true); - - //Return the filled itemstack. - return new MutablePair(filled, itemStack); - } else if (FluidContainerRegistry.isContainer(itemStack)) { - //Fill it through the fluidcontainer registry. - ItemStack filledContainer = FluidContainerRegistry - .fillFluidContainer(fluid, itemStack); - //get the filled fluidstack. - FluidStack filled = FluidContainerRegistry - .getFluidForFilledItem(filledContainer); - //Return filled container and fill amount. - return new MutablePair( - filled != null ? filled.amount : 0, filledContainer); - - } else if (item == ItemEnum.FLUIDPATTERN.getItem()) { - return new MutablePair(0, - ItemFluidPattern.getPatternForFluid(fluid.getFluid())); - } - - return null; - } - - public static int getCapacity(ItemStack itemStack) { - if (itemStack == null) - return 0; - Item item = itemStack.getItem(); - if (item instanceof IFluidContainerItem) { - return ((IFluidContainerItem) item).getCapacity(itemStack); - } else if (FluidContainerRegistry.isEmptyContainer(itemStack)) { - for (FluidContainerRegistry.FluidContainerData data : FluidContainerRegistry - .getRegisteredFluidContainerData()) { - if (data != null && data.emptyContainer.isItemEqual(itemStack)) { - FluidStack interior = data.fluid; - return interior != null ? interior.amount : 0; - } - } - } - return 0; - } - - public static FluidStack getFluidFromContainer(ItemStack itemStack) { - if (itemStack == null) - return null; - - ItemStack container = itemStack.copy(); - Item item = container.getItem(); - if (item instanceof IFluidContainerItem) { - return ((IFluidContainerItem) item).getFluid(container); - } else if (item == ItemEnum.FLUIDPATTERN.getItem()) { - return new FluidStack(ItemFluidPattern.getFluid(itemStack), 0); - } else { - return FluidContainerRegistry.getFluidForFilledItem(container); - } - } - - public static boolean isEmpty(ItemStack itemStack) { - if (itemStack == null) - return false; - Item item = itemStack.getItem(); - if (item instanceof IFluidContainerItem) { - FluidStack content = ((IFluidContainerItem) item) - .getFluid(itemStack); - return content == null || content.amount <= 0; - } - return item == ItemEnum.FLUIDPATTERN.getItem() - || FluidContainerRegistry.isEmptyContainer(itemStack); - } - - public static boolean isFilled(ItemStack itemStack) { - if (itemStack == null) - return false; - Item item = itemStack.getItem(); - if (item instanceof IFluidContainerItem) { - FluidStack content = ((IFluidContainerItem) item) - .getFluid(itemStack); - return content != null && content.amount > 0; - } - return FluidContainerRegistry.isFilledContainer(itemStack); - } - - public static boolean isFluidContainer(ItemStack itemStack) { - if (itemStack == null) - return false; - Item item = itemStack.getItem(); - return item instanceof IFluidContainerItem - || item == ItemEnum.FLUIDPATTERN.getItem() - || FluidContainerRegistry.isContainer(itemStack); - } + public static IAEFluidStack createAEFluidStack(Fluid fluid) { + return createAEFluidStack(new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME)); + } + + public static IAEFluidStack createAEFluidStack(Fluid fluid, long amount) { + return createAEFluidStack(fluid.getID(), amount); + } + + public static IAEFluidStack createAEFluidStack(FluidStack fluid) { + return AEApi.instance().storage().createFluidStack(fluid); + } + + public static IAEFluidStack createAEFluidStack(int fluidId, long amount) { + return createAEFluidStack(new FluidStack(FluidRegistry.getFluid(fluidId), 1)).setStackSize(amount); + } + + /** + * Drain fluid from an item + * + * @param itemStack Filled fluid container + * @param fluid Fluid type and amount to drain + * @return Amount drained and the emptied container + */ + public static MutablePair drainStack(ItemStack itemStack, FluidStack fluid) { + if (itemStack == null) return null; + Item item = itemStack.getItem(); + if (item instanceof IFluidContainerItem) { + FluidStack drained = ((IFluidContainerItem) item).drain(itemStack, fluid.amount, true); + int amountDrained = drained != null && drained.getFluid() == fluid.getFluid() ? drained.amount : 0; + return new MutablePair(amountDrained, itemStack); + } else if (FluidContainerRegistry.isContainer(itemStack)) { + FluidStack content = FluidContainerRegistry.getFluidForFilledItem(itemStack); + int amountDrained = content != null && content.getFluid() == fluid.getFluid() ? content.amount : 0; + return new MutablePair( + amountDrained, + FluidContainerRegistry.drainFluidContainer(itemStack)); + } + + return null; + } + + /** + * Fill an ItemStack with fluid + * + * @param itemStack Item to fill, stackSize must be 1 + * @param fluid The fluid amount to fill the container with + * @return Pair: amount actually filled, the filled ItemStack + */ + public static MutablePair fillStack(ItemStack itemStack, FluidStack fluid) { + if (itemStack == null || itemStack.stackSize != 1) return null; + Item item = itemStack.getItem(); + // If its a fluid container item instance + if (item instanceof IFluidContainerItem) { + // Call the fill method on it. + int filled = ((IFluidContainerItem) item).fill(itemStack, fluid, true); + + // Return the filled itemstack. + return new MutablePair(filled, itemStack); + } else if (FluidContainerRegistry.isContainer(itemStack)) { + // Fill it through the fluidcontainer registry. + ItemStack filledContainer = FluidContainerRegistry.fillFluidContainer(fluid, itemStack); + // get the filled fluidstack. + FluidStack filled = FluidContainerRegistry.getFluidForFilledItem(filledContainer); + // Return filled container and fill amount. + return new MutablePair(filled != null ? filled.amount : 0, filledContainer); + + } else if (item == ItemEnum.FLUIDPATTERN.getItem()) { + return new MutablePair(0, ItemFluidPattern.getPatternForFluid(fluid.getFluid())); + } + + return null; + } + + /** + * Try to fill a liquid container item from AE fluid storage. Make sure to SIMULATE first. + * + * @param container Item to fill, stackSize must be 1 + * @param request Requested fluid amount, the real amount drained may be smaller + * @param monitor The AE network + * @param mode Whether to simulate or actually move liquids + * @param src Action source for auditing + * @return Null if failed, otherwise the filled container and the fluid stack it was filled with + */ + public static MutablePair fillItemFromAe(ItemStack container, FluidStack request, + IMEMonitor monitor, Actionable mode, BaseActionSource src) { + if (container == null || container.stackSize != 1) { + return null; + } + if (request == null || request.amount <= 0) { + return null; + } + if (monitor == null) { + return null; + } + int capacity = FluidUtil.getCapacity(container, request.getFluid()); + int requestAmount = Integer.min(capacity, request.amount); + IAEFluidStack result = monitor + .extractItems(FluidUtil.createAEFluidStack(request.getFluid(), requestAmount), mode, src); + if (result == null || result.getStackSize() <= 0) { + return null; + } + if (!result.getFluid().equals(request.getFluid())) { + FMLLog.severe( + "[ExtraCells2] ME network returned fluid `%s` when requesting `%s`", + result.getFluid().getName(), + request.getUnlocalizedName()); + return null; + } + if (result.getStackSize() > (long) requestAmount) { + FMLLog.severe( + "[ExtraCells2] ME network returned %d mB of fluid `%s` when requesting %d mB", + result.getStackSize(), + request.getUnlocalizedName(), + requestAmount); + return null; + } + MutablePair filledContainer = FluidUtil.fillStack(container.copy(), result.getFluidStack()); + if (filledContainer.getLeft() > (int) result.getStackSize()) { + FMLLog.severe( + "[ExtraCells2] %d mB of fluid `%s` filled container `%s` with %d mB: check fluid handler implementation", + result.getStackSize(), + request.getUnlocalizedName(), + container.getUnlocalizedName(), + filledContainer.getLeft()); + return null; + } + if (filledContainer.getLeft() < (int) result.getStackSize() && mode == Actionable.MODULATE) { + // Couldn't completely fill container, attempt to return to AE + int remaining = (int) result.getStackSize() - filledContainer.getLeft(); + IAEFluidStack notAdded = monitor + .injectItems(FluidUtil.createAEFluidStack(result.getFluid(), remaining), Actionable.MODULATE, src); + if (notAdded != null && notAdded.getStackSize() > 0) { + FMLLog.severe( + "[ExtraCells2] %d mL of fluid `%s` voided when trying to fill container `%s`", + notAdded.getStackSize(), + notAdded.getFluid().getName(), + container.getUnlocalizedName()); + } + } + return new MutablePair<>( + filledContainer.getRight(), + new FluidStack(request.getFluid(), filledContainer.getLeft())); + } + + /** + * Try to drain a liquid container item into AE fluid storage. Make sure to SIMULATE first. + * + * @param container Item to drain, stackSize must be 1 + * @param monitor The AE network + * @param mode Whether to simulate or actually move liquids + * @param src Action source for auditing + * @return Null if failed, otherwise the drained container + */ + public static ItemStack drainItemIntoAe(ItemStack container, IMEMonitor monitor, Actionable mode, + BaseActionSource src) { + if (container == null || container.stackSize != 1) { + return null; + } + if (monitor == null) { + return null; + } + FluidStack fluidStack = FluidUtil.getFluidFromContainer(container); + MutablePair drained = FluidUtil.drainStack(container.copy(), fluidStack); + fluidStack.amount = drained.getLeft(); + IAEFluidStack notAdded = monitor.injectItems(FluidUtil.createAEFluidStack(fluidStack), mode, src); + if (notAdded == null || notAdded.getStackSize() <= 0) { + return drained.getRight(); + } + if (!notAdded.getFluid().equals(fluidStack.getFluid())) { + FMLLog.severe( + "[ExtraCells2] ME network returned fluid `%s` when injecting `%s`", + notAdded.getFluid().getName(), + fluidStack.getUnlocalizedName()); + return null; + } + if (notAdded.getStackSize() > (long) fluidStack.amount) { + FMLLog.severe( + "[ExtraCells2] ME network returned %d mB of fluid `%s` when injecting %d mB", + notAdded.getStackSize(), + fluidStack.getUnlocalizedName(), + fluidStack.amount); + return null; + } + fluidStack.amount -= (int) notAdded.getStackSize(); + MutablePair partiallyDrained = FluidUtil.drainStack(container.copy(), fluidStack); + if (partiallyDrained.getLeft() > fluidStack.amount) { + FMLLog.severe( + "[ExtraCells2] Voided fluid: %d mB of fluid `%s` drained from container `%s` with %d mB: check fluid handler implementation", + notAdded.getStackSize(), + fluidStack.getUnlocalizedName(), + container.getUnlocalizedName(), + partiallyDrained.getLeft()); + // Void fluid, but at least don't void the container + // This generally shouldn't happen, but might for certain configurations of many storage buses pointing at + // the same almost-full tank + // when emptying items with a fixed fluid capacity that can't be partially emptied + return partiallyDrained.getRight(); + } + if (partiallyDrained.getLeft() < fluidStack.amount) { + // Couldn't completely empty container, attempt to drain AE to avoid duping fluid + if (mode == Actionable.MODULATE) { + int duped = fluidStack.amount - partiallyDrained.getLeft(); + IAEFluidStack extracted = monitor.extractItems( + FluidUtil.createAEFluidStack(notAdded.getFluid(), duped), + Actionable.MODULATE, + src); + if (extracted == null || extracted.getStackSize() < duped) { + FMLLog.severe( + "[ExtraCells2] %d mL of fluid `%s` duped when trying to empty container `%s`", + extracted == null ? duped : (duped - extracted.getStackSize()), + notAdded.getFluid().getName(), + container.getUnlocalizedName()); + } + } else { + return null; + } + } + return partiallyDrained.getRight(); + } + + public static int getCapacity(ItemStack itemStack, Fluid fluid) { + if (itemStack == null) return 0; + Item item = itemStack.getItem(); + if (item instanceof IFluidContainerItem) { + IFluidContainerItem fluidContainerItem = (IFluidContainerItem) item; + int capacity = fluidContainerItem.getCapacity(itemStack); + FluidStack existing = fluidContainerItem.getFluid(itemStack); + if (existing != null) { + if (!existing.getFluid().equals(fluid)) { + return 0; + } + capacity -= existing.amount; + } + return capacity; + } else if (FluidContainerRegistry.isContainer(itemStack)) { + return FluidContainerRegistry.getContainerCapacity(new FluidStack(fluid, Integer.MAX_VALUE), itemStack); + } + return 0; + } + + public static FluidStack getFluidFromContainer(ItemStack itemStack) { + if (itemStack == null) return null; + + ItemStack container = itemStack.copy(); + Item item = container.getItem(); + if (item instanceof IFluidContainerItem) { + return ((IFluidContainerItem) item).getFluid(container); + } else if (item == ItemEnum.FLUIDPATTERN.getItem()) { + return new FluidStack(ItemFluidPattern.getFluid(itemStack), 0); + } else { + return FluidContainerRegistry.getFluidForFilledItem(container); + } + } + + public static boolean isEmpty(ItemStack itemStack) { + if (itemStack == null) return false; + Item item = itemStack.getItem(); + if (item instanceof IFluidContainerItem) { + FluidStack content = ((IFluidContainerItem) item).getFluid(itemStack); + return content == null || content.amount <= 0; + } + return item == ItemEnum.FLUIDPATTERN.getItem() || FluidContainerRegistry.isEmptyContainer(itemStack); + } + + public static boolean isFilled(ItemStack itemStack) { + if (itemStack == null) return false; + Item item = itemStack.getItem(); + if (item instanceof IFluidContainerItem) { + FluidStack content = ((IFluidContainerItem) item).getFluid(itemStack); + return content != null && content.amount > 0; + } + return FluidContainerRegistry.isFilledContainer(itemStack); + } + + public static boolean isFluidContainer(ItemStack itemStack) { + if (itemStack == null) return false; + Item item = itemStack.getItem(); + return item instanceof IFluidContainerItem || item == ItemEnum.FLUIDPATTERN.getItem() + || FluidContainerRegistry.isContainer(itemStack); + } + + public static String formatFluidAmount(long millibuckets, boolean forceLongForm) { + if (!forceLongForm) { + if (millibuckets >= 1_000_000_000_000L) return String.format("%.1fG", millibuckets / 1_000_000_000_000.0); + else if (millibuckets >= 1_000_000_000L) return String.format("%.1fM", millibuckets / 1_000_000_000.0); + else if (millibuckets >= 1_000_000L) return String.format("%.1fk", millibuckets / 1_000_000.0); + else if (millibuckets >= 1_000L) { + return String.format("%.1f", millibuckets / 1_000.0); + } + } + return String.format("%,d%s", millibuckets, forceLongForm ? " mB" : "m"); + } + + public static IItemList filterEmptyFluid(IItemList _fluidStackList) { + IItemList temp = AEApi.instance().storage().createFluidList(); + for (IAEFluidStack fluid : _fluidStackList) { + if (fluid.getStackSize() > 0) temp.add(fluid); + } + return temp; + } + + public static String formatFluidAmount(long millibuckets) { + return formatFluidAmount(millibuckets, false); + } } diff --git a/src/main/scala/extracells/util/FuelBurnTime.scala b/src/main/scala/extracells/util/FuelBurnTime.scala index 2f00cae91..71162a9e9 100644 --- a/src/main/scala/extracells/util/FuelBurnTime.scala +++ b/src/main/scala/extracells/util/FuelBurnTime.scala @@ -1,6 +1,5 @@ package extracells.util - import buildcraft.api.fuels.BuildcraftFuelRegistry import cpw.mods.fml.common.Optional import extracells.integration.Integration @@ -11,18 +10,18 @@ import scala.collection.mutable object FuelBurnTime { val fluidBurnTimes = new mutable.HashMap[Fluid, Integer] - def registerFuel(fluid: Fluid, burnTime: Int): Unit ={ - if(!fluidBurnTimes.contains(fluid)) + def registerFuel(fluid: Fluid, burnTime: Int): Unit = { + if (!fluidBurnTimes.contains(fluid)) fluidBurnTimes.put(fluid, burnTime) } - def getBurnTime(fluid: Fluid): Int ={ - if(fluid == null) + def getBurnTime(fluid: Fluid): Int = { + if (fluid == null) return 0 - if(fluidBurnTimes.contains(fluid)) + if (fluidBurnTimes.contains(fluid)) return fluidBurnTimes.get(fluid).get - if(Integration.Mods.BCFUEL.isEnabled) + if (Integration.Mods.BCFUEL.isEnabled) return getBCBurnTime(fluid) 0 } @@ -30,13 +29,12 @@ object FuelBurnTime { @Optional.Method(modid = "BuildCraftAPI|fuels") private def getBCBurnTime(fluid: Fluid): Int = { val it = BuildcraftFuelRegistry.fuel.getFuels.iterator() - while (it.hasNext){ + while (it.hasNext) { val fuel = it.next - if(fuel.getFluid == fluid) + if (fuel.getFluid == fluid) return fuel.getTotalBurningTime } 0 } - } diff --git a/src/main/scala/extracells/util/GasStorageRegistry.scala b/src/main/scala/extracells/util/GasStorageRegistry.scala index 94df58dc7..2213d1cfc 100644 --- a/src/main/scala/extracells/util/GasStorageRegistry.scala +++ b/src/main/scala/extracells/util/GasStorageRegistry.scala @@ -7,7 +7,6 @@ import net.minecraftforge.common.util.ForgeDirection import scala.collection.mutable - object GasStorageRegistry { private val handler = mutable.MutableList[IExternalGasStorageHandler]() @@ -16,9 +15,13 @@ object GasStorageRegistry { handler += esh } - def getHandler(te: TileEntity, opposite: ForgeDirection, mySrc: BaseActionSource): IExternalGasStorageHandler = { - for(x <- handler){ - if(x.canHandle(te, opposite, mySrc)) + def getHandler( + te: TileEntity, + opposite: ForgeDirection, + mySrc: BaseActionSource + ): IExternalGasStorageHandler = { + for (x <- handler) { + if (x.canHandle(te, opposite, mySrc)) return x } null diff --git a/src/main/scala/extracells/util/GasUtil.java b/src/main/scala/extracells/util/GasUtil.java index 16c187727..2f644e801 100644 --- a/src/main/scala/extracells/util/GasUtil.java +++ b/src/main/scala/extracells/util/GasUtil.java @@ -1,157 +1,147 @@ package extracells.util; -import appeng.api.AEApi; -import appeng.api.storage.data.IAEFluidStack; -import extracells.integration.mekanism.gas.MekanismGas; -import mekanism.api.gas.Gas; -import mekanism.api.gas.GasStack; -import mekanism.api.gas.IGasItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; + import org.apache.commons.lang3.tuple.MutablePair; +import appeng.api.AEApi; +import appeng.api.storage.data.IAEFluidStack; +import extracells.integration.mekanism.gas.MekanismGas; +import mekanism.api.gas.Gas; +import mekanism.api.gas.GasStack; +import mekanism.api.gas.IGasItem; + public class GasUtil { - public static IAEFluidStack createAEFluidStack(Gas gas) { - return createAEFluidStack(new FluidStack(MekanismGas.getFluidGasMap().get(gas), - FluidContainerRegistry.BUCKET_VOLUME)); - } - - public static IAEFluidStack createAEFluidStack(GasStack gasStack) { - return gasStack == null ? null : createAEFluidStack(new FluidStack(MekanismGas.getFluidGasMap().get(gasStack.getGas()), gasStack.amount)); - } - - - public static IAEFluidStack createAEFluidStack(FluidStack fluid) { - return AEApi.instance().storage().createFluidStack(fluid); - } - - public static IAEFluidStack createAEFluidStack(Gas gas, long amount) { - return createAEFluidStack(new FluidStack(MekanismGas.getFluidGasMap().get(gas), 1)).setStackSize( - amount); - } - - public static MutablePair drainStack(ItemStack itemStack, GasStack gas) { - if (itemStack == null) - return null; - Item item = itemStack.getItem(); - if (item instanceof IGasItem) { - GasStack drained = ((IGasItem) item).removeGas(itemStack, - gas.amount); - int amountDrained = drained != null - && drained.getGas() == gas.getGas() ? drained.amount - : 0; - return new MutablePair(amountDrained, itemStack); - } - return null; - } - - public static MutablePair fillStack( - ItemStack itemStack, GasStack gas) { - if (itemStack == null) - return null; - Item item = itemStack.getItem(); - if (item instanceof IGasItem) { - int filled = ((IGasItem) item).addGas(itemStack, gas); - return new MutablePair(filled, itemStack); - } - - return null; - } - - public static int getCapacity(ItemStack itemStack) { - if (itemStack == null) - return 0; - Item item = itemStack.getItem(); - if (item instanceof IGasItem) { - return ((IGasItem) item).getMaxGas(itemStack); - } - return 0; - } - - public static GasStack getGasFromContainer(ItemStack itemStack) { - if (itemStack == null) - return null; - - ItemStack container = itemStack.copy(); - Item item = container.getItem(); - if (item instanceof IGasItem) { - return ((IGasItem) item).getGas(itemStack); - } - return null; - } - - public static boolean isEmpty(ItemStack itemStack) { - if (itemStack == null) - return false; - Item item = itemStack.getItem(); - if (item instanceof IGasItem) { - GasStack content = ((IGasItem) item).getGas(itemStack); - return content == null || content.amount <= 0; - } - return false; - } - - public static boolean isFilled(ItemStack itemStack) { - if (itemStack == null) - return false; - Item item = itemStack.getItem(); - if (item instanceof IGasItem) { - GasStack content = ((IGasItem) item).getGas(itemStack); - return content != null && content.amount > 0; - } - return FluidContainerRegistry.isFilledContainer(itemStack); - } - - public static boolean isGasContainer(ItemStack itemStack) { - if (itemStack == null) - return false; - Item item = itemStack.getItem(); - return item instanceof IGasItem; - } - - public static GasStack getGasStack(FluidStack fluidStack) { - if(fluidStack == null) return null; - Fluid fluid = fluidStack.getFluid(); - if(fluid instanceof MekanismGas.GasFluid){ - return new GasStack(((MekanismGas.GasFluid)fluid).getGas(), fluidStack.amount); - } - return null; - } - - public static GasStack getGasStack(IAEFluidStack fluidStack) { - if(fluidStack == null) return null; - Fluid fluid = fluidStack.getFluid(); - if(fluid instanceof MekanismGas.GasFluid){ - return new GasStack(((MekanismGas.GasFluid)fluid).getGas(), (int) fluidStack.getStackSize()); - } - return null; - } - - public static FluidStack getFluidStack(GasStack gasStack) { - if (gasStack == null) return null; - Fluid fluid = MekanismGas.getFluidGasMap().get(gasStack.getGas()); - if (fluid == null) return null; - return new FluidStack(fluid, gasStack.amount); - } - - public static boolean isGas(FluidStack fluidStack){ - return fluidStack != null && isGas(fluidStack.getFluid()); - } - - public static boolean isGas(Fluid fluid){ - return fluid != null && fluid instanceof MekanismGas.GasFluid; - } - - public static Gas getGas(Fluid fluid){ - if(fluid == null) - return null; - if(fluid instanceof MekanismGas.GasFluid){ - return ((MekanismGas.GasFluid)fluid).getGas(); - } - return null; - } + public static IAEFluidStack createAEFluidStack(Gas gas) { + return createAEFluidStack( + new FluidStack(MekanismGas.getFluidGasMap().get(gas), FluidContainerRegistry.BUCKET_VOLUME)); + } + + public static IAEFluidStack createAEFluidStack(GasStack gasStack) { + return gasStack == null ? null + : createAEFluidStack( + new FluidStack(MekanismGas.getFluidGasMap().get(gasStack.getGas()), gasStack.amount)); + } + + public static IAEFluidStack createAEFluidStack(FluidStack fluid) { + return AEApi.instance().storage().createFluidStack(fluid); + } + + public static IAEFluidStack createAEFluidStack(Gas gas, long amount) { + return createAEFluidStack(new FluidStack(MekanismGas.getFluidGasMap().get(gas), 1)).setStackSize(amount); + } + + public static MutablePair drainStack(ItemStack itemStack, GasStack gas) { + if (itemStack == null) return null; + Item item = itemStack.getItem(); + if (item instanceof IGasItem) { + GasStack drained = ((IGasItem) item).removeGas(itemStack, gas.amount); + int amountDrained = drained != null && drained.getGas() == gas.getGas() ? drained.amount : 0; + return new MutablePair(amountDrained, itemStack); + } + return null; + } + + public static MutablePair fillStack(ItemStack itemStack, GasStack gas) { + if (itemStack == null) return null; + Item item = itemStack.getItem(); + if (item instanceof IGasItem) { + int filled = ((IGasItem) item).addGas(itemStack, gas); + return new MutablePair(filled, itemStack); + } + + return null; + } + + public static int getCapacity(ItemStack itemStack) { + if (itemStack == null) return 0; + Item item = itemStack.getItem(); + if (item instanceof IGasItem) { + return ((IGasItem) item).getMaxGas(itemStack); + } + return 0; + } + + public static GasStack getGasFromContainer(ItemStack itemStack) { + if (itemStack == null) return null; + + ItemStack container = itemStack.copy(); + Item item = container.getItem(); + if (item instanceof IGasItem) { + return ((IGasItem) item).getGas(itemStack); + } + return null; + } + + public static boolean isEmpty(ItemStack itemStack) { + if (itemStack == null) return false; + Item item = itemStack.getItem(); + if (item instanceof IGasItem) { + GasStack content = ((IGasItem) item).getGas(itemStack); + return content == null || content.amount <= 0; + } + return false; + } + + public static boolean isFilled(ItemStack itemStack) { + if (itemStack == null) return false; + Item item = itemStack.getItem(); + if (item instanceof IGasItem) { + GasStack content = ((IGasItem) item).getGas(itemStack); + return content != null && content.amount > 0; + } + return FluidContainerRegistry.isFilledContainer(itemStack); + } + + public static boolean isGasContainer(ItemStack itemStack) { + if (itemStack == null) return false; + Item item = itemStack.getItem(); + return item instanceof IGasItem; + } + + public static GasStack getGasStack(FluidStack fluidStack) { + if (fluidStack == null) return null; + Fluid fluid = fluidStack.getFluid(); + if (fluid instanceof MekanismGas.GasFluid) { + return new GasStack(((MekanismGas.GasFluid) fluid).getGas(), fluidStack.amount); + } + return null; + } + + public static GasStack getGasStack(IAEFluidStack fluidStack) { + if (fluidStack == null) return null; + Fluid fluid = fluidStack.getFluid(); + if (fluid instanceof MekanismGas.GasFluid) { + return new GasStack(((MekanismGas.GasFluid) fluid).getGas(), (int) fluidStack.getStackSize()); + } + return null; + } + + public static FluidStack getFluidStack(GasStack gasStack) { + if (gasStack == null) return null; + Fluid fluid = MekanismGas.getFluidGasMap().get(gasStack.getGas()); + if (fluid == null) return null; + return new FluidStack(fluid, gasStack.amount); + } + + public static boolean isGas(FluidStack fluidStack) { + return fluidStack != null && isGas(fluidStack.getFluid()); + } + + public static boolean isGas(Fluid fluid) { + return fluid != null && fluid instanceof MekanismGas.GasFluid; + } + + public static Gas getGas(Fluid fluid) { + if (fluid == null) return null; + if (fluid instanceof MekanismGas.GasFluid) { + return ((MekanismGas.GasFluid) fluid).getGas(); + } + return null; + } } diff --git a/src/main/scala/extracells/util/GuiUtil.java b/src/main/scala/extracells/util/GuiUtil.java index 267563a00..1e1eaa8dc 100644 --- a/src/main/scala/extracells/util/GuiUtil.java +++ b/src/main/scala/extracells/util/GuiUtil.java @@ -1,80 +1,79 @@ package extracells.util; -import extracells.gui.widget.fluid.WidgetFluidSlot; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; + import org.lwjgl.opengl.GL11; +import extracells.gui.widget.fluid.WidgetFluidSlot; + public class GuiUtil { - public static void drawGradientRect(float zLevel, int par1, int par2, - int par3, int par4, int par5, int par6) { - float f = (par5 >> 24 & 255) / 255.0F; - float f1 = (par5 >> 16 & 255) / 255.0F; - float f2 = (par5 >> 8 & 255) / 255.0F; - float f3 = (par5 & 255) / 255.0F; - float f4 = (par6 >> 24 & 255) / 255.0F; - float f5 = (par6 >> 16 & 255) / 255.0F; - float f6 = (par6 >> 8 & 255) / 255.0F; - float f7 = (par6 & 255) / 255.0F; - GL11.glDisable(GL11.GL_TEXTURE_2D); - GL11.glEnable(GL11.GL_BLEND); - GL11.glDisable(GL11.GL_ALPHA_TEST); - OpenGlHelper.glBlendFunc(770, 771, 1, 0); - GL11.glShadeModel(GL11.GL_SMOOTH); - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.setColorRGBA_F(f1, f2, f3, f); - tessellator.addVertex(par3, par2, zLevel); - tessellator.addVertex(par1, par2, zLevel); - tessellator.setColorRGBA_F(f5, f6, f7, f4); - tessellator.addVertex(par1, par4, zLevel); - tessellator.addVertex(par3, par4, zLevel); - tessellator.draw(); - GL11.glShadeModel(GL11.GL_FLAT); - GL11.glDisable(GL11.GL_BLEND); - GL11.glEnable(GL11.GL_ALPHA_TEST); - GL11.glEnable(GL11.GL_TEXTURE_2D); - } + public static void drawGradientRect(float zLevel, int par1, int par2, int par3, int par4, int par5, int par6) { + float f = (par5 >> 24 & 255) / 255.0F; + float f1 = (par5 >> 16 & 255) / 255.0F; + float f2 = (par5 >> 8 & 255) / 255.0F; + float f3 = (par5 & 255) / 255.0F; + float f4 = (par6 >> 24 & 255) / 255.0F; + float f5 = (par6 >> 16 & 255) / 255.0F; + float f6 = (par6 >> 8 & 255) / 255.0F; + float f7 = (par6 & 255) / 255.0F; + GL11.glDisable(GL11.GL_TEXTURE_2D); + GL11.glEnable(GL11.GL_BLEND); + GL11.glDisable(GL11.GL_ALPHA_TEST); + OpenGlHelper.glBlendFunc(770, 771, 1, 0); + GL11.glShadeModel(GL11.GL_SMOOTH); + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.setColorRGBA_F(f1, f2, f3, f); + tessellator.addVertex(par3, par2, zLevel); + tessellator.addVertex(par1, par2, zLevel); + tessellator.setColorRGBA_F(f5, f6, f7, f4); + tessellator.addVertex(par1, par4, zLevel); + tessellator.addVertex(par3, par4, zLevel); + tessellator.draw(); + GL11.glShadeModel(GL11.GL_FLAT); + GL11.glDisable(GL11.GL_BLEND); + GL11.glEnable(GL11.GL_ALPHA_TEST); + GL11.glEnable(GL11.GL_TEXTURE_2D); + } - public static void drawIcon(IIcon icon, int x, int y, int z, float width, - float height) { - if (icon == null) - return; - Tessellator tessellator = Tessellator.instance; - tessellator.startDrawingQuads(); - tessellator.addVertexWithUV(x, y + height, z, icon.getMinU(), - icon.getMaxV()); - tessellator.addVertexWithUV(x + width, y + height, z, icon.getMaxU(), - icon.getMaxV()); - tessellator.addVertexWithUV(x + width, y, z, icon.getMaxU(), - icon.getMinV()); - tessellator.addVertexWithUV(x, y, z, icon.getMinU(), icon.getMinV()); - tessellator.draw(); - } + public static void drawIcon(IIcon icon, int x, int y, int z, float width, float height) { + if (icon == null) return; + Tessellator tessellator = Tessellator.instance; + tessellator.startDrawingQuads(); + tessellator.addVertexWithUV(x, y + height, z, icon.getMinU(), icon.getMaxV()); + tessellator.addVertexWithUV(x + width, y + height, z, icon.getMaxU(), icon.getMaxV()); + tessellator.addVertexWithUV(x + width, y, z, icon.getMaxU(), icon.getMinV()); + tessellator.addVertexWithUV(x, y, z, icon.getMinU(), icon.getMinV()); + tessellator.draw(); + } - public static boolean isPointInRegion(float guiLeft, int guiTop, int top, - int left, int height, int width, int pointX, int pointY) { - pointX -= guiLeft; - pointY -= guiTop; - return pointX >= top - 1 && pointX < top + height + 1 - && pointY >= left - 1 && pointY < left + width + 1; - } + public static boolean isPointInRegion(float guiLeft, int guiTop, int top, int left, int height, int width, + int pointX, int pointY) { + pointX -= guiLeft; + pointY -= guiTop; + return pointX >= top - 1 && pointX < top + height + 1 && pointY >= left - 1 && pointY < left + width + 1; + } - public static boolean renderOverlay(float zLevel, int guiLeft, int guiTop, - WidgetFluidSlot fluidSlot, int mouseX, int mouseY) { - if (isPointInRegion(guiLeft, guiTop, fluidSlot.getPosX(), - fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { - GL11.glDisable(GL11.GL_LIGHTING); - GL11.glDisable(GL11.GL_DEPTH_TEST); - drawGradientRect(zLevel, fluidSlot.getPosX() + 1, - fluidSlot.getPosY() + 1, fluidSlot.getPosX() + 17, - fluidSlot.getPosY() + 17, -0x7F000001, -0x7F000001); - GL11.glEnable(GL11.GL_LIGHTING); - GL11.glEnable(GL11.GL_DEPTH_TEST); - return true; - } - return false; - } + public static boolean renderOverlay(float zLevel, int guiLeft, int guiTop, WidgetFluidSlot fluidSlot, int mouseX, + int mouseY) { + if (isPointInRegion(guiLeft, guiTop, fluidSlot.getPosX(), fluidSlot.getPosY(), 18, 18, mouseX, mouseY)) { + GL11.glDisable(GL11.GL_LIGHTING); + GL11.glDisable(GL11.GL_DEPTH_TEST); + drawGradientRect( + zLevel, + fluidSlot.getPosX() + 1, + fluidSlot.getPosY() + 1, + fluidSlot.getPosX() + 17, + fluidSlot.getPosY() + 17, + -0x7F000001, + -0x7F000001); + GL11.glEnable(GL11.GL_LIGHTING); + GL11.glEnable(GL11.GL_DEPTH_TEST); + return true; + } + return false; + } } diff --git a/src/main/scala/extracells/util/HandlerUniversalWirelessTerminal.scala b/src/main/scala/extracells/util/HandlerUniversalWirelessTerminal.scala index 9fe2dd144..9d4730890 100644 --- a/src/main/scala/extracells/util/HandlerUniversalWirelessTerminal.scala +++ b/src/main/scala/extracells/util/HandlerUniversalWirelessTerminal.scala @@ -7,19 +7,37 @@ import extracells.item.ItemWirelessTerminalUniversal import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack - -object HandlerUniversalWirelessTerminal extends IWirelessTermHandler with IWirelessFluidTermHandler with IWirelessGasTermHandler{ - override def getConfigManager(is: ItemStack): IConfigManager = ItemWirelessTerminalUniversal.getConfigManager(is) - - override def canHandle(is: ItemStack): Boolean = ItemWirelessTerminalUniversal.canHandle(is) - - override def usePower(player: EntityPlayer, amount: Double, is: ItemStack): Boolean = ItemWirelessTerminalUniversal.usePower(player, amount, is) - - override def hasPower(player: EntityPlayer, amount: Double, is: ItemStack): Boolean = ItemWirelessTerminalUniversal.hasPower(player, amount, is) - - override def isItemNormalWirelessTermToo(is: ItemStack): Boolean = ItemWirelessTerminalUniversal.isItemNormalWirelessTermToo(is) - - override def setEncryptionKey(item: ItemStack, encKey: String, name: String): Unit = ItemWirelessTerminalUniversal.setEncryptionKey(item, encKey, name) - - override def getEncryptionKey(item: ItemStack): String = ItemWirelessTerminalUniversal.getEncryptionKey(item) +object HandlerUniversalWirelessTerminal + extends IWirelessTermHandler + with IWirelessFluidTermHandler + with IWirelessGasTermHandler { + override def getConfigManager(is: ItemStack): IConfigManager = + ItemWirelessTerminalUniversal.getConfigManager(is) + + override def canHandle(is: ItemStack): Boolean = + ItemWirelessTerminalUniversal.canHandle(is) + + override def usePower( + player: EntityPlayer, + amount: Double, + is: ItemStack + ): Boolean = ItemWirelessTerminalUniversal.usePower(player, amount, is) + + override def hasPower( + player: EntityPlayer, + amount: Double, + is: ItemStack + ): Boolean = ItemWirelessTerminalUniversal.hasPower(player, amount, is) + + override def isItemNormalWirelessTermToo(is: ItemStack): Boolean = + ItemWirelessTerminalUniversal.isItemNormalWirelessTermToo(is) + + override def setEncryptionKey( + item: ItemStack, + encKey: String, + name: String + ): Unit = ItemWirelessTerminalUniversal.setEncryptionKey(item, encKey, name) + + override def getEncryptionKey(item: ItemStack): String = + ItemWirelessTerminalUniversal.getEncryptionKey(item) } diff --git a/src/main/scala/extracells/util/ItemUtils.java b/src/main/scala/extracells/util/ItemUtils.java index f3f42a88e..78547b61c 100644 --- a/src/main/scala/extracells/util/ItemUtils.java +++ b/src/main/scala/extracells/util/ItemUtils.java @@ -3,17 +3,14 @@ import net.minecraft.item.ItemStack; public class ItemUtils { - - public static boolean areItemEqualsIgnoreStackSize(ItemStack stack1, ItemStack stack2){ - if(stack1 == null && stack2 == null) - return true; - else if(stack1 == null || stack2 == null) - return false; - ItemStack s1 = stack1.copy(); - ItemStack s2 = stack2.copy(); - s1.stackSize = 1; - s2.stackSize = 1; - return ItemStack.areItemStacksEqual(s1, s2); - } + public static boolean areItemEqualsIgnoreStackSize(ItemStack stack1, ItemStack stack2) { + if (stack1 == null && stack2 == null) return true; + else if (stack1 == null || stack2 == null) return false; + ItemStack s1 = stack1.copy(); + ItemStack s2 = stack2.copy(); + s1.stackSize = 1; + s2.stackSize = 1; + return ItemStack.areItemStacksEqual(s1, s2); + } } diff --git a/src/main/scala/extracells/util/NameHandler.java b/src/main/scala/extracells/util/NameHandler.java index 1cbdec47c..9e5a5ac96 100644 --- a/src/main/scala/extracells/util/NameHandler.java +++ b/src/main/scala/extracells/util/NameHandler.java @@ -8,181 +8,164 @@ public class NameHandler implements ISubItemResolver { - @Override - public Object resolveItemByName(String namespace, String fullName) { - if (!namespace.equals("extracells")) - return null; + @Override + public Object resolveItemByName(String namespace, String fullName) { + if (!namespace.equals("extracells")) return null; - // Fluid Cells - if (fullName.equals("fluidCell1k")) - return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 0); - if (fullName.equals("fluidCell4k")) - return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 1); - if (fullName.equals("fluidCell16k")) - return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 2); - if (fullName.equals("fluidCell64k")) - return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 3); - if (fullName.equals("fluidCell256k")) - return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 4); - if (fullName.equals("fluidCell1024k")) - return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 5); - if (fullName.equals("fluidCell4096k")) - return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 6); - if (fullName.equals("fluidCellPortable")) - return new ResolverResult(ItemEnum.FLUIDSTORAGEPORTABLE.getInternalName(), 0); + // Fluid Cells + if (fullName.equals("fluidCell1k")) return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 0); + if (fullName.equals("fluidCell4k")) return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 1); + if (fullName.equals("fluidCell16k")) return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 2); + if (fullName.equals("fluidCell64k")) return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 3); + if (fullName.equals("fluidCell256k")) return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 4); + if (fullName.equals("fluidCell1024k")) return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 5); + if (fullName.equals("fluidCell4096k")) return new ResolverResult(ItemEnum.FLUIDSTORAGE.getInternalName(), 6); + if (fullName.equals("fluidCellPortable")) + return new ResolverResult(ItemEnum.FLUIDSTORAGEPORTABLE.getInternalName(), 0); - // Gas Cells - if (fullName.equals("gasCell1k")) - return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 0); - if (fullName.equals("gasCell4k")) - return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 1); - if (fullName.equals("gasCell16k")) - return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 2); - if (fullName.equals("gasCell64k")) - return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 3); - if (fullName.equals("gasCell256k")) - return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 4); - if (fullName.equals("gasCell1024k")) - return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 5); - if (fullName.equals("gasCell4096k")) - return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 6); - if (fullName.equals("gasCellPortable")) - return new ResolverResult(ItemEnum.GASSTORAGEPORTABLE.getInternalName(), 0); + // Gas Cells + if (fullName.equals("gasCell1k")) return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 0); + if (fullName.equals("gasCell4k")) return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 1); + if (fullName.equals("gasCell16k")) return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 2); + if (fullName.equals("gasCell64k")) return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 3); + if (fullName.equals("gasCell256k")) return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 4); + if (fullName.equals("gasCell1024k")) return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 5); + if (fullName.equals("gasCell4096k")) return new ResolverResult(ItemEnum.GASSTORAGE.getInternalName(), 6); + if (fullName.equals("gasCellPortable")) + return new ResolverResult(ItemEnum.GASSTORAGEPORTABLE.getInternalName(), 0); - // Physical Cells - if (fullName.equals("physCell256k")) - return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 0); - if (fullName.equals("physCell1024k")) - return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 1); - if (fullName.equals("physCell4096k")) - return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 2); - if (fullName.equals("physCell16384k")) - return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 3); - if (fullName.equals("physCellContainer")) - return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 4); + // Physical Cells + if (fullName.equals("physCell256k")) return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 0); + if (fullName.equals("physCell1024k")) return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 1); + if (fullName.equals("physCell4096k")) return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 2); + if (fullName.equals("physCell16384k")) return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 3); + if (fullName.equals("physCellContainer")) + return new ResolverResult(ItemEnum.PHYSICALSTORAGE.getInternalName(), 4); + if (fullName.equals("physCellAdvancedSingularity")) + return new ResolverResult(ItemEnum.PHYSICALSTORAGESINGULARITY.getInternalName(), 0); + if (fullName.equals("physCellAdvancedQuantum")) + return new ResolverResult(ItemEnum.PHYSICALSTORAGEQUANTUM.getInternalName(), 0); + if (fullName.equals("physCellVoid")) + return new ResolverResult(ItemEnum.PHYSICALSTORAGEVOID.getInternalName(), 0); - // Fluid Storage Components - if (fullName.equals("cell1kPartFluid")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 4); - if (fullName.equals("cell4kPartFluid")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 5); - if (fullName.equals("cell16kPartFluid")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 6); - if (fullName.equals("cell64kPartFluid")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 7); - if (fullName.equals("cell256kPartFluid")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 8); - if (fullName.equals("cell1024kPartFluid")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 9); - if (fullName.equals("cell4096kPartFluid")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 10); + // Fluid Storage Components + if (fullName.equals("cell1kPartFluid")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 4); + if (fullName.equals("cell4kPartFluid")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 5); + if (fullName.equals("cell16kPartFluid")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 6); + if (fullName.equals("cell64kPartFluid")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 7); + if (fullName.equals("cell256kPartFluid")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 8); + if (fullName.equals("cell1024kPartFluid")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 9); + if (fullName.equals("cell4096kPartFluid")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 10); - // Gas Storage Components - if (fullName.equals("cell1kPartGas")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 11); - if (fullName.equals("cell4kPartGas")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 12); - if (fullName.equals("cell16kPartGas")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 13); - if (fullName.equals("cell64kPartGas")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 14); - if (fullName.equals("cell256kPartGas")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 15); - if (fullName.equals("cell1024kPartGas")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 16); - if (fullName.equals("cell4096kPartGas")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 17); + // Gas Storage Components + if (fullName.equals("cell1kPartGas")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 11); + if (fullName.equals("cell4kPartGas")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 12); + if (fullName.equals("cell16kPartGas")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 13); + if (fullName.equals("cell64kPartGas")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 14); + if (fullName.equals("cell256kPartGas")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 15); + if (fullName.equals("cell1024kPartGas")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 16); + if (fullName.equals("cell4096kPartGas")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 17); - // Physical Storage Components - if (fullName.equals("cell256kPart")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 0); - if (fullName.equals("cell1024kPart")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 1); - if (fullName.equals("cell4096kPart")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 2); - if (fullName.equals("cell16384kPart")) - return new ResolverResult(ItemEnum.STORAGECOMPONET.getInternalName(), 3); + // Physical Storage Components + if (fullName.equals("cell256kPart")) return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 0); + if (fullName.equals("cell1024kPart")) return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 1); + if (fullName.equals("cell4096kPart")) return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 2); + if (fullName.equals("cell16384kPart")) + return new ResolverResult(ItemEnum.STORAGECOMPONENT.getInternalName(), 3); - // Physical Storage Casing - if (fullName.equals("physCasing")) - return new ResolverResult(ItemEnum.STORAGECASING.getInternalName(), 0); + // Physical Storage Casing + if (fullName.equals("physCasing")) return new ResolverResult(ItemEnum.STORAGECASING.getInternalName(), 0); - // Fluid Storage Casing - if (fullName.equals("fluidCasing")) - return new ResolverResult(ItemEnum.STORAGECASING.getInternalName(), 1); + // Fluid Storage Casing + if (fullName.equals("fluidCasing")) return new ResolverResult(ItemEnum.STORAGECASING.getInternalName(), 1); - // Fluid Storage Casing - if (fullName.equals("gasCasing")) - return new ResolverResult(ItemEnum.STORAGECASING.getInternalName(), 2); + // Fluid Storage Casing + if (fullName.equals("gasCasing")) return new ResolverResult(ItemEnum.STORAGECASING.getInternalName(), 2); - // Parts - if (fullName.equals("partFluidImportBus")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDIMPORT.ordinal()); - if (fullName.equals("partFluidExportBus")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDEXPORT.ordinal()); - if (fullName.equals("partFluidStorageBus")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDSTORAGE.ordinal()); - if (fullName.equals("partFluidTerminal")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDTERMINAL.ordinal()); - if (fullName.equals("partFluidLevelEmitter")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDLEVELEMITTER.ordinal()); - if (fullName.equals("partFluidAnnihilationPlane")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDPANEANNIHILATION.ordinal()); - if (fullName.equals("partFluidFormationPlane")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDPANEFORMATION.ordinal()); - if (fullName.equals("partBattery")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.BATTERY.ordinal()); - if (fullName.equals("partDrive")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.DRIVE.ordinal()); - if (fullName.equals("partInterface")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.INTERFACE.ordinal()); - if (fullName.equals("partStorageMonitor"))//TODO: Remve - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDMONITOR.ordinal()); - if (fullName.equals("partConversionMonitor"))//TODO: Remve - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDCONVERSIONMONITOR.ordinal()); - if (fullName.equals("partFluidStorageMonitor")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDMONITOR.ordinal()); - if (fullName.equals("partFluidConversionMonitor")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDCONVERSIONMONITOR.ordinal()); - if (fullName.equals("partOreDictExportBus")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.OREDICTEXPORTBUS.ordinal()); - if (fullName.equals("partGasImportBus")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASIMPORT.ordinal()); - if (fullName.equals("partGasExportBus")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASEXPORT.ordinal()); - if (fullName.equals("partGasStorageBus")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASSTORAGE.ordinal()); - if (fullName.equals("partGasTerminal")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASTERMINAL.ordinal()); - if (fullName.equals("partGasLevelEmitter")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASLEVELEMITTER.ordinal()); - if (fullName.equals("partGasStorageMonitor")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASMONITOR.ordinal()); - if (fullName.equals("partGasConversionMonitor")) - return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASCONVERSIONMONITOR.ordinal()); + // Parts + if (fullName.equals("partFluidImportBus")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDIMPORT.ordinal()); + if (fullName.equals("partFluidExportBus")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDEXPORT.ordinal()); + if (fullName.equals("partFluidStorageBus")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDSTORAGE.ordinal()); + if (fullName.equals("partFluidTerminal")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDTERMINAL.ordinal()); + if (fullName.equals("partFluidLevelEmitter")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDLEVELEMITTER.ordinal()); + if (fullName.equals("partFluidAnnihilationPlane")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDPANEANNIHILATION.ordinal()); + if (fullName.equals("partFluidFormationPlane")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDPANEFORMATION.ordinal()); + if (fullName.equals("partBattery")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.BATTERY.ordinal()); + if (fullName.equals("partDrive")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.DRIVE.ordinal()); + if (fullName.equals("partInterface")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.INTERFACE.ordinal()); + if (fullName.equals("partStorageMonitor")) // TODO: Remve + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDMONITOR.ordinal()); + if (fullName.equals("partConversionMonitor")) // TODO: Remve + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDCONVERSIONMONITOR.ordinal()); + if (fullName.equals("partFluidStorageMonitor")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDMONITOR.ordinal()); + if (fullName.equals("partFluidConversionMonitor")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.FLUIDCONVERSIONMONITOR.ordinal()); + if (fullName.equals("partOreDictExportBus")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.OREDICTEXPORTBUS.ordinal()); + if (fullName.equals("partGasImportBus")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASIMPORT.ordinal()); + if (fullName.equals("partGasExportBus")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASEXPORT.ordinal()); + if (fullName.equals("partGasStorageBus")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASSTORAGE.ordinal()); + if (fullName.equals("partGasTerminal")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASTERMINAL.ordinal()); + if (fullName.equals("partGasLevelEmitter")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASLEVELEMITTER.ordinal()); + if (fullName.equals("partGasStorageMonitor")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASMONITOR.ordinal()); + if (fullName.equals("partGasConversionMonitor")) + return new ResolverResult(ItemEnum.PARTITEM.getInternalName(), PartEnum.GASCONVERSIONMONITOR.ordinal()); - // MISC - if (fullName.equals("certusTank")) - return new ResolverResult(BlockEnum.CERTUSTANK.getInternalName(), 0); - if (fullName.equals("fluidPattern")) - return new ResolverResult(ItemEnum.FLUIDPATTERN.getInternalName(), 0); - if (fullName.equals("fluidCrafter")) - return new ResolverResult(BlockEnum.FLUIDCRAFTER.getInternalName(), 0); - if (fullName.equals("wirelessFluidTerminal")) - return new ResolverResult(ItemEnum.FLUIDWIRELESSTERMINAL.getInternalName(), 0); - if (fullName.equals("wirelessGasTerminal")) - return new ResolverResult(ItemEnum.GASWIRELESSTERMINAL.getInternalName(), 0); - if (fullName.equals("walrus")) - return new ResolverResult(BlockEnum.WALRUS.getInternalName(), 0); - if (fullName.equals("interface")) - return new ResolverResult(BlockEnum.ECBASEBLOCK.getInternalName(), 0); - if (fullName.equals("fluidFiller")) - return new ResolverResult(BlockEnum.ECBASEBLOCK.getInternalName(), 1); - if (fullName.equals("blockVibrationChamberFluid")) - return new ResolverResult(BlockEnum.VIBRANTCHAMBERFLUID.getInternalName(), 0); - if (fullName.equals("hardMEDrive")) - return new ResolverResult(BlockEnum.BLASTRESISTANTMEDRIVE.getInternalName(), 0); + // MISC + if (fullName.equals("certusTank")) return new ResolverResult(BlockEnum.CERTUSTANK.getInternalName(), 0); + if (fullName.equals("fluidPattern")) return new ResolverResult(ItemEnum.FLUIDPATTERN.getInternalName(), 0); + if (fullName.equals("fluidCrafter")) return new ResolverResult(BlockEnum.FLUIDCRAFTER.getInternalName(), 0); + if (fullName.equals("wirelessFluidTerminal")) + return new ResolverResult(ItemEnum.FLUIDWIRELESSTERMINAL.getInternalName(), 0); + if (fullName.equals("wirelessGasTerminal")) + return new ResolverResult(ItemEnum.GASWIRELESSTERMINAL.getInternalName(), 0); + if (fullName.equals("walrus")) return new ResolverResult(BlockEnum.WALRUS.getInternalName(), 0); + if (fullName.equals("interface")) return new ResolverResult(BlockEnum.ECBASEBLOCK.getInternalName(), 0); + if (fullName.equals("fluidFiller")) return new ResolverResult(BlockEnum.ECBASEBLOCK.getInternalName(), 1); + if (fullName.equals("blockVibrationChamberFluid")) + return new ResolverResult(BlockEnum.VIBRANTCHAMBERFLUID.getInternalName(), 0); + if (fullName.equals("hardMEDrive")) + return new ResolverResult(BlockEnum.BLASTRESISTANTMEDRIVE.getInternalName(), 0); + if (fullName.equals("craftingStorage256k")) + return new ResolverResult(BlockEnum.CRAFTINGSTORAGE.getInternalName(), 0); + if (fullName.equals("craftingStorage1024k")) + return new ResolverResult(BlockEnum.CRAFTINGSTORAGE.getInternalName(), 1); + if (fullName.equals("craftingStorage4096k")) + return new ResolverResult(BlockEnum.CRAFTINGSTORAGE.getInternalName(), 2); + if (fullName.equals("craftingStorage16384k")) + return new ResolverResult(BlockEnum.CRAFTINGSTORAGE.getInternalName(), 3); - return null; - } + return null; + } } diff --git a/src/main/scala/extracells/util/PermissionUtil.java b/src/main/scala/extracells/util/PermissionUtil.java index 8d3424b3c..183a93e93 100644 --- a/src/main/scala/extracells/util/PermissionUtil.java +++ b/src/main/scala/extracells/util/PermissionUtil.java @@ -1,54 +1,45 @@ package extracells.util; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraftforge.common.util.ForgeDirection; + import appeng.api.config.SecurityPermissions; import appeng.api.networking.IGrid; import appeng.api.networking.IGridHost; import appeng.api.networking.IGridNode; import appeng.api.networking.security.ISecurityGrid; import appeng.api.parts.IPart; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraftforge.common.util.ForgeDirection; public class PermissionUtil { - public static boolean hasPermission(EntityPlayer player, - SecurityPermissions permission, IGrid grid) { - if (grid != null) - return hasPermission(player, permission, - (ISecurityGrid) grid.getCache(ISecurityGrid.class)); - return true; - } - - public static boolean hasPermission(EntityPlayer player, - SecurityPermissions permission, IGridHost host) { - return hasPermission(player, permission, host, ForgeDirection.UNKNOWN); - } - - public static boolean hasPermission(EntityPlayer player, - SecurityPermissions permission, IGridHost host, ForgeDirection side) { - if (host != null) - return hasPermission(player, permission, host.getGridNode(side)); - return true; - } - - public static boolean hasPermission(EntityPlayer player, - SecurityPermissions permission, IGridNode host) { - if (host != null) - return hasPermission(player, permission, host.getGrid()); - return true; - } - - public static boolean hasPermission(EntityPlayer player, - SecurityPermissions permission, IPart part) { - if (part != null) - return hasPermission(player, permission, part.getGridNode()); - return true; - } - - public static boolean hasPermission(EntityPlayer player, - SecurityPermissions permission, ISecurityGrid securityGrid) { - if (player == null || permission == null || securityGrid == null) - return true; - return securityGrid.hasPermission(player, permission); - } + public static boolean hasPermission(EntityPlayer player, SecurityPermissions permission, IGrid grid) { + if (grid != null) return hasPermission(player, permission, (ISecurityGrid) grid.getCache(ISecurityGrid.class)); + return true; + } + + public static boolean hasPermission(EntityPlayer player, SecurityPermissions permission, IGridHost host) { + return hasPermission(player, permission, host, ForgeDirection.UNKNOWN); + } + + public static boolean hasPermission(EntityPlayer player, SecurityPermissions permission, IGridHost host, + ForgeDirection side) { + if (host != null) return hasPermission(player, permission, host.getGridNode(side)); + return true; + } + + public static boolean hasPermission(EntityPlayer player, SecurityPermissions permission, IGridNode host) { + if (host != null) return hasPermission(player, permission, host.getGrid()); + return true; + } + + public static boolean hasPermission(EntityPlayer player, SecurityPermissions permission, IPart part) { + if (part != null) return hasPermission(player, permission, part.getGridNode()); + return true; + } + + public static boolean hasPermission(EntityPlayer player, SecurityPermissions permission, + ISecurityGrid securityGrid) { + if (player == null || permission == null || securityGrid == null) return true; + return securityGrid.hasPermission(player, permission); + } } diff --git a/src/main/scala/extracells/util/UniversalTErminal.scala b/src/main/scala/extracells/util/UniversalTErminal.scala index e66a8cd52..1a7443d9a 100644 --- a/src/main/scala/extracells/util/UniversalTErminal.scala +++ b/src/main/scala/extracells/util/UniversalTErminal.scala @@ -8,144 +8,162 @@ import extracells.item.TerminalType import extracells.registries.{ItemEnum, PartEnum} import net.minecraft.item.ItemStack - object UniversalTerminal { val isMekLoaded = Mods.MEKANISMGAS.isEnabled val isThaLoaded = Mods.THAUMATICENERGISTICS.isEnabled val isWcLLoaded = Mods.WIRELESSCRAFTING.isEnabled val arrayLength = { var length = 2 - if(isMekLoaded) + if (isMekLoaded) length += 1 - if(isThaLoaded) + if (isThaLoaded) length += 1 - if(isWcLLoaded) + if (isWcLLoaded) length += 1 length } - val wirelessTerminals : Array[ItemStack] = { + val wirelessTerminals: Array[ItemStack] = { val terminals = new Array[ItemStack](arrayLength) - terminals.update(0, AEApi.instance.definitions.items.wirelessTerminal.maybeStack(1).get()) + terminals.update( + 0, + AEApi.instance.definitions.items.wirelessTerminal.maybeStack(1).get() + ) terminals.update(1, ItemEnum.FLUIDWIRELESSTERMINAL.getSizedStack(1)) var next = 2 - if(isMekLoaded) { + if (isMekLoaded) { terminals.update(next, ItemEnum.GASWIRELESSTERMINAL.getSizedStack(1)) next += 1 } - if(isThaLoaded) { + if (isThaLoaded) { terminals.update(next, ThaumaticEnergistics.getWirelessTerminal) next += 1 } - if(isWcLLoaded) + if (isWcLLoaded) terminals.update(next, WirelessCrafting.getCraftingTerminal) terminals } - val terminals : Array[ItemStack] = { - val terminals = new Array[ItemStack](if (isWcLLoaded) arrayLength - 1 else arrayLength) - terminals.update(0, AEApi.instance.definitions.parts.terminal.maybeStack(1).get()) - terminals.update(1, ItemEnum.PARTITEM.getDamagedStack(PartEnum.FLUIDTERMINAL.ordinal)) - if(isMekLoaded) { - terminals.update(2, ItemEnum.PARTITEM.getDamagedStack(PartEnum.GASTERMINAL.ordinal)) - if(isThaLoaded) + val terminals: Array[ItemStack] = { + val terminals = + new Array[ItemStack](if (isWcLLoaded) arrayLength - 1 else arrayLength) + terminals.update( + 0, + AEApi.instance.definitions.parts.terminal.maybeStack(1).get() + ) + terminals.update( + 1, + ItemEnum.PARTITEM.getDamagedStack(PartEnum.FLUIDTERMINAL.ordinal) + ) + if (isMekLoaded) { + terminals.update( + 2, + ItemEnum.PARTITEM.getDamagedStack(PartEnum.GASTERMINAL.ordinal) + ) + if (isThaLoaded) terminals.update(3, ThaumaticEnergistics.getTerminal) - }else if(isThaLoaded) + } else if (isThaLoaded) terminals.update(2, ThaumaticEnergistics.getTerminal) terminals } def isTerminal(stack: ItemStack): Boolean = { - if(stack == null) + if (stack == null) return false val item = stack.getItem val meta = stack.getItemDamage - if(item == null) + if (item == null) return false val aeterm = AEApi.instance.definitions.parts.terminal.maybeStack(1).get - if(item == aeterm.getItem && meta == aeterm.getItemDamage) + if (item == aeterm.getItem && meta == aeterm.getItemDamage) return true - val ecterm = ItemEnum.PARTITEM.getDamagedStack(PartEnum.FLUIDTERMINAL.ordinal) - if(item == ecterm.getItem && meta == ecterm.getItemDamage) + val ecterm = + ItemEnum.PARTITEM.getDamagedStack(PartEnum.FLUIDTERMINAL.ordinal) + if (item == ecterm.getItem && meta == ecterm.getItemDamage) return true - val ectermgas = ItemEnum.PARTITEM.getDamagedStack(PartEnum.GASTERMINAL.ordinal) - if(item == ectermgas.getItem && meta == ectermgas.getItemDamage) + val ectermgas = + ItemEnum.PARTITEM.getDamagedStack(PartEnum.GASTERMINAL.ordinal) + if (item == ectermgas.getItem && meta == ectermgas.getItemDamage) return true - if(Mods.THAUMATICENERGISTICS.isEnabled){ + if (Mods.THAUMATICENERGISTICS.isEnabled) { val thterm = ThaumaticEnergistics.getTerminal - if(item == thterm.getItem && meta == thterm.getItemDamage) + if (item == thterm.getItem && meta == thterm.getItemDamage) return true } false } def isWirelessTerminal(stack: ItemStack): Boolean = { - if(stack == null) + if (stack == null) return false val item = stack.getItem val meta = stack.getItemDamage - if(item == null) + if (item == null) return false - val aeterm = AEApi.instance.definitions.items.wirelessTerminal.maybeStack(1).get - if(item == aeterm.getItem && meta == aeterm.getItemDamage) + val aeterm = + AEApi.instance.definitions.items.wirelessTerminal.maybeStack(1).get + if (item == aeterm.getItem && meta == aeterm.getItemDamage) return true val ecterm = ItemEnum.FLUIDWIRELESSTERMINAL.getDamagedStack(0) - if(item == ecterm.getItem && meta == ecterm.getItemDamage) + if (item == ecterm.getItem && meta == ecterm.getItemDamage) return true val ectermgas = ItemEnum.GASWIRELESSTERMINAL.getDamagedStack(0) - if(item == ectermgas.getItem && meta == ectermgas.getItemDamage) + if (item == ectermgas.getItem && meta == ectermgas.getItemDamage) return true - if(Mods.THAUMATICENERGISTICS.isEnabled){ + if (Mods.THAUMATICENERGISTICS.isEnabled) { val thterm = ThaumaticEnergistics.getWirelessTerminal - if(item == thterm.getItem && meta == thterm.getItemDamage) + if (item == thterm.getItem && meta == thterm.getItemDamage) return true } - if(isWcLLoaded){ + if (isWcLLoaded) { val wcTerm = WirelessCrafting.getCraftingTerminal - if(item == wcTerm.getItem && meta == wcTerm.getItemDamage) + if (item == wcTerm.getItem && meta == wcTerm.getItemDamage) return true } false } def getTerminalType(stack: ItemStack): TerminalType = { - if(stack == null) + if (stack == null) return null val item = stack.getItem val meta = stack.getItemDamage - if(item == null) + if (item == null) return null val aeterm = AEApi.instance.definitions.parts.terminal.maybeStack(1).get - if(item == aeterm.getItem && meta == aeterm.getItemDamage) + if (item == aeterm.getItem && meta == aeterm.getItemDamage) return TerminalType.ITEM - val ecterm = ItemEnum.PARTITEM.getDamagedStack(PartEnum.FLUIDTERMINAL.ordinal) - if(item == ecterm.getItem && meta == ecterm.getItemDamage) + val ecterm = + ItemEnum.PARTITEM.getDamagedStack(PartEnum.FLUIDTERMINAL.ordinal) + if (item == ecterm.getItem && meta == ecterm.getItemDamage) return TerminalType.FLUID - val ectermgas = ItemEnum.PARTITEM.getDamagedStack(PartEnum.GASTERMINAL.ordinal) - if(item == ectermgas.getItem && meta == ectermgas.getItemDamage) + val ectermgas = + ItemEnum.PARTITEM.getDamagedStack(PartEnum.GASTERMINAL.ordinal) + if (item == ectermgas.getItem && meta == ectermgas.getItemDamage) return TerminalType.GAS - if(Mods.THAUMATICENERGISTICS.isEnabled){ + if (Mods.THAUMATICENERGISTICS.isEnabled) { val thterm = ThaumaticEnergistics.getTerminal - if(item == thterm.getItem && meta == thterm.getItemDamage) + if (item == thterm.getItem && meta == thterm.getItemDamage) return TerminalType.ESSENTIA } - val aeterm2 = AEApi.instance.definitions.items.wirelessTerminal.maybeStack(1).get - if(item == aeterm2.getItem && meta == aeterm2.getItemDamage) + val aeterm2 = + AEApi.instance.definitions.items.wirelessTerminal.maybeStack(1).get + if (item == aeterm2.getItem && meta == aeterm2.getItemDamage) return TerminalType.ITEM val ecterm2 = ItemEnum.FLUIDWIRELESSTERMINAL.getDamagedStack(0) - if(item == ecterm2.getItem && meta == ecterm2.getItemDamage) + if (item == ecterm2.getItem && meta == ecterm2.getItemDamage) return TerminalType.FLUID val ectermgas2 = ItemEnum.GASWIRELESSTERMINAL.getDamagedStack(0) - if(item == ectermgas2.getItem && meta == ectermgas2.getItemDamage) + if (item == ectermgas2.getItem && meta == ectermgas2.getItemDamage) return TerminalType.GAS - if(Mods.THAUMATICENERGISTICS.isEnabled){ + if (Mods.THAUMATICENERGISTICS.isEnabled) { val thterm = ThaumaticEnergistics.getWirelessTerminal - if(item == thterm.getItem && meta == thterm.getItemDamage) + if (item == thterm.getItem && meta == thterm.getItemDamage) return TerminalType.ESSENTIA } - if(isWcLLoaded){ + if (isWcLLoaded) { val wcTerm = WirelessCrafting.getCraftingTerminal - if(item == wcTerm.getItem && meta == wcTerm.getItemDamage) + if (item == wcTerm.getItem && meta == wcTerm.getItemDamage) return TerminalType.CRAFTING } null diff --git a/src/main/scala/extracells/util/VoidCellHandler.java b/src/main/scala/extracells/util/VoidCellHandler.java new file mode 100644 index 000000000..b3b226fd4 --- /dev/null +++ b/src/main/scala/extracells/util/VoidCellHandler.java @@ -0,0 +1,66 @@ +package extracells.util; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.util.IIcon; + +import appeng.api.implementations.tiles.IChestOrDrive; +import appeng.api.storage.*; +import appeng.client.texture.ExtraBlockTextures; +import appeng.core.sync.GuiBridge; +import appeng.util.Platform; +import extracells.inventory.VoidCellInventory; +import extracells.inventory.VoidCellInventoryHandler; + +public class VoidCellHandler implements ICellHandler { + + @Override + public boolean isCell(final ItemStack is) { + return VoidCellInventory.isCell(is); + } + + @Override + public IMEInventoryHandler getCellInventory(final ItemStack is, final ISaveProvider container, + final StorageChannel channel) { + if (channel == StorageChannel.ITEMS) { + return VoidCellInventory.getCell(is, container); + } + return null; + } + + @Override + public IIcon getTopTexture_Light() { + return ExtraBlockTextures.BlockMEChestItems_Light.getIcon(); + } + + @Override + public IIcon getTopTexture_Medium() { + return ExtraBlockTextures.BlockMEChestItems_Medium.getIcon(); + } + + @Override + public IIcon getTopTexture_Dark() { + return ExtraBlockTextures.BlockMEChestItems_Dark.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 int getStatusForCell(final ItemStack is, final IMEInventory handler) { + if (handler instanceof VoidCellInventoryHandler) { + final VoidCellInventoryHandler ci = (VoidCellInventoryHandler) handler; + return ci.getStatusForCell(); + } + return 0; + } + + @Override + public double cellIdleDrain(final ItemStack is, final IMEInventory handler) { + return 10.0; + } +} diff --git a/src/main/scala/extracells/util/WrenchUtil.java b/src/main/scala/extracells/util/WrenchUtil.java index 0323dda95..d94fee23a 100644 --- a/src/main/scala/extracells/util/WrenchUtil.java +++ b/src/main/scala/extracells/util/WrenchUtil.java @@ -1,34 +1,31 @@ package extracells.util; -import appeng.api.implementations.items.IAEWrench; -import buildcraft.api.tools.IToolWrench; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; +import appeng.api.implementations.items.IAEWrench; +import buildcraft.api.tools.IToolWrench; + public class WrenchUtil { - public static boolean canWrench(ItemStack wrench, EntityPlayer player, - int x, int y, int z) { - if (wrench == null || wrench.getItem() == null) - return false; - try { - IToolWrench w = (IToolWrench) wrench.getItem(); - return w.canWrench(player, x, y, z); - } catch (Throwable e) {} - if (wrench.getItem() instanceof IAEWrench) { - IAEWrench w = (IAEWrench) wrench.getItem(); - return w.canWrench(wrench, player, x, y, z); - } - return false; - } + public static boolean canWrench(ItemStack wrench, EntityPlayer player, int x, int y, int z) { + if (wrench == null || wrench.getItem() == null) return false; + try { + IToolWrench w = (IToolWrench) wrench.getItem(); + return w.canWrench(player, x, y, z); + } catch (Throwable e) {} + if (wrench.getItem() instanceof IAEWrench) { + IAEWrench w = (IAEWrench) wrench.getItem(); + return w.canWrench(wrench, player, x, y, z); + } + return false; + } - public static void wrenchUsed(ItemStack wrench, EntityPlayer player, int x, - int y, int z) { - if (wrench == null || wrench.getItem() == null) - return; - try { - IToolWrench w = (IToolWrench) wrench.getItem(); - w.wrenchUsed(player, x, y, z); - } catch (Throwable e) {} - } + public static void wrenchUsed(ItemStack wrench, EntityPlayer player, int x, int y, int z) { + if (wrench == null || wrench.getItem() == null) return; + try { + IToolWrench w = (IToolWrench) wrench.getItem(); + w.wrenchUsed(player, x, y, z); + } catch (Throwable e) {} + } } diff --git a/src/main/scala/extracells/util/inventory/ECCellInventory.java b/src/main/scala/extracells/util/inventory/ECCellInventory.java index 4b8331050..d804b26ac 100644 --- a/src/main/scala/extracells/util/inventory/ECCellInventory.java +++ b/src/main/scala/extracells/util/inventory/ECCellInventory.java @@ -7,130 +7,121 @@ public class ECCellInventory implements IInventory { - private ItemStack storage; - private String tagId; - private NBTTagCompound tagCompound; - private int size; - private int stackLimit; - private ItemStack[] slots; - private boolean dirty = false; - - public ECCellInventory(ItemStack _storage, String _tagId, int _size, - int _stackLimit) { - this.storage = _storage; - this.tagId = _tagId; - this.size = _size; - this.stackLimit = _stackLimit; - if (!this.storage.hasTagCompound()) - this.storage.setTagCompound(new NBTTagCompound()); - this.storage.getTagCompound().setTag(this.tagId, - this.storage.getTagCompound().getCompoundTag(this.tagId)); - this.tagCompound = this.storage.getTagCompound().getCompoundTag( - this.tagId); - openInventory(); - } - - @Override - public void closeInventory() { - if (this.dirty) { - for (int i = 0; i < this.slots.length; i++) { - this.tagCompound.removeTag("ItemStack#" + i); - ItemStack content = this.slots[i]; - if (content != null) { - this.tagCompound.setTag("ItemStack#" + i, - new NBTTagCompound()); - content.writeToNBT(this.tagCompound - .getCompoundTag("ItemStack#" + i)); - } - } - } - } - - @Override - public ItemStack decrStackSize(int slotId, int amount) { - ItemStack slotContent = this.slots[slotId]; - if (slotContent == null) - return null; - int stackSize = slotContent.stackSize; - if (stackSize <= 0) - return null; - int newAmount; - if (amount >= stackSize) { - newAmount = stackSize; - this.slots[slotId] = null; - } else { - this.slots[slotId].stackSize -= amount; - newAmount = amount; - } - ItemStack toReturn = slotContent.copy(); - toReturn.stackSize = amount; - markDirty(); - - return toReturn; - } - - @Override - public String getInventoryName() { - return ""; - } - - @Override - public int getInventoryStackLimit() { - return this.stackLimit; - } - - @Override - public int getSizeInventory() { - return this.size; - } - - @Override - public ItemStack getStackInSlot(int slotId) { - return this.slots[slotId]; - } - - @Override - public ItemStack getStackInSlotOnClosing(int slotId) { - return getStackInSlot(slotId); - } - - @Override - public boolean hasCustomInventoryName() { - return false; - } - - @Override - public boolean isItemValidForSlot(int slotId, ItemStack itemStack) { - return true; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer entityPlayer) { - return true; - } - - @Override - public void markDirty() { - this.dirty = true; - closeInventory(); - this.dirty = false; - } - - @Override - public void openInventory() { - this.slots = new ItemStack[this.size]; - for (int i = 0; i < this.slots.length; i++) { - this.slots[i] = ItemStack.loadItemStackFromNBT(this.tagCompound - .getCompoundTag("ItemStack#" + i)); - } - } - - @Override - public void setInventorySlotContents(int slotId, ItemStack content) { - ItemStack slotContent = this.slots[slotId]; - if (slotContent != content) { - this.slots[slotId] = content; - markDirty(); - } - } + private ItemStack storage; + private String tagId; + private NBTTagCompound tagCompound; + private int size; + private int stackLimit; + private ItemStack[] slots; + private boolean dirty = false; + + public ECCellInventory(ItemStack _storage, String _tagId, int _size, int _stackLimit) { + this.storage = _storage; + this.tagId = _tagId; + this.size = _size; + this.stackLimit = _stackLimit; + if (!this.storage.hasTagCompound()) this.storage.setTagCompound(new NBTTagCompound()); + this.storage.getTagCompound().setTag(this.tagId, this.storage.getTagCompound().getCompoundTag(this.tagId)); + this.tagCompound = this.storage.getTagCompound().getCompoundTag(this.tagId); + openInventory(); + } + + @Override + public void closeInventory() { + if (this.dirty) { + for (int i = 0; i < this.slots.length; i++) { + this.tagCompound.removeTag("ItemStack#" + i); + ItemStack content = this.slots[i]; + if (content != null) { + this.tagCompound.setTag("ItemStack#" + i, new NBTTagCompound()); + content.writeToNBT(this.tagCompound.getCompoundTag("ItemStack#" + i)); + } + } + } + } + + @Override + public ItemStack decrStackSize(int slotId, int amount) { + ItemStack slotContent = this.slots[slotId]; + if (slotContent == null) return null; + int stackSize = slotContent.stackSize; + if (stackSize <= 0) return null; + int newAmount; + if (amount >= stackSize) { + newAmount = stackSize; + this.slots[slotId] = null; + } else { + this.slots[slotId].stackSize -= amount; + newAmount = amount; + } + ItemStack toReturn = slotContent.copy(); + toReturn.stackSize = amount; + markDirty(); + + return toReturn; + } + + @Override + public String getInventoryName() { + return ""; + } + + @Override + public int getInventoryStackLimit() { + return this.stackLimit; + } + + @Override + public int getSizeInventory() { + return this.size; + } + + @Override + public ItemStack getStackInSlot(int slotId) { + return this.slots[slotId]; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slotId) { + return getStackInSlot(slotId); + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + @Override + public boolean isItemValidForSlot(int slotId, ItemStack itemStack) { + return true; + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityPlayer) { + return true; + } + + @Override + public void markDirty() { + this.dirty = true; + closeInventory(); + this.dirty = false; + } + + @Override + public void openInventory() { + this.slots = new ItemStack[this.size]; + for (int i = 0; i < this.slots.length; i++) { + this.slots[i] = ItemStack.loadItemStackFromNBT(this.tagCompound.getCompoundTag("ItemStack#" + i)); + } + } + + @Override + public void setInventorySlotContents(int slotId, ItemStack content) { + ItemStack slotContent = this.slots[slotId]; + if (slotContent != content) { + this.slots[slotId] = content; + markDirty(); + } + } } diff --git a/src/main/scala/extracells/util/inventory/ECFluidFilterInventory.java b/src/main/scala/extracells/util/inventory/ECFluidFilterInventory.java index 09bcfe5ae..b39b25405 100644 --- a/src/main/scala/extracells/util/inventory/ECFluidFilterInventory.java +++ b/src/main/scala/extracells/util/inventory/ECFluidFilterInventory.java @@ -1,93 +1,78 @@ package extracells.util.inventory; -import extracells.registries.ItemEnum; -import extracells.util.FluidUtil; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -public class ECFluidFilterInventory extends ECPrivateInventory { +import extracells.registries.ItemEnum; +import extracells.util.FluidUtil; - private final ItemStack cellItem; +public class ECFluidFilterInventory extends ECPrivateInventory { - public ECFluidFilterInventory(String _customName, int _size, - ItemStack _cellItem) { - super(_customName, _size, 1); - this.cellItem = _cellItem; - if (this.cellItem.hasTagCompound()) - if (this.cellItem.getTagCompound().hasKey("filter")) - readFromNBT(this.cellItem.getTagCompound().getTagList("filter", - 10)); - } + private final ItemStack cellItem; - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - if (itemstack == null) - return false; - if (itemstack.getItem() == ItemEnum.FLUIDITEM.getItem()) { - int fluidID = itemstack.getItemDamage(); - for (ItemStack s : this.slots) { - if (s == null) - continue; - if (s.getItemDamage() == fluidID) - return false; - } - return true; - } - if (!FluidUtil.isFilled(itemstack)) - return false; - FluidStack stack = FluidUtil.getFluidFromContainer(itemstack); - if (stack == null) - return false; - int fluidID = stack.getFluidID(); - for (ItemStack s : this.slots) { - if (s == null) - continue; - if (s.getItemDamage() == fluidID) - return false; - } - return true; - } + public ECFluidFilterInventory(String _customName, int _size, ItemStack _cellItem) { + super(_customName, _size, 1); + this.cellItem = _cellItem; + if (this.cellItem.hasTagCompound()) if (this.cellItem.getTagCompound().hasKey("filter")) + readFromNBT(this.cellItem.getTagCompound().getTagList("filter", 10)); + } - @Override - public void markDirty() { - NBTTagCompound tag; - if (this.cellItem.hasTagCompound()) - tag = this.cellItem.getTagCompound(); - else - tag = new NBTTagCompound(); - tag.setTag("filter", writeToNBT()); - } + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + if (itemstack == null) return false; + if (itemstack.getItem() == ItemEnum.FLUIDITEM.getItem()) { + int fluidID = itemstack.getItemDamage(); + for (ItemStack s : this.slots) { + if (s == null) continue; + if (s.getItemDamage() == fluidID) return false; + } + return true; + } + if (!FluidUtil.isFilled(itemstack)) return false; + FluidStack stack = FluidUtil.getFluidFromContainer(itemstack); + if (stack == null) return false; + int fluidID = stack.getFluidID(); + for (ItemStack s : this.slots) { + if (s == null) continue; + if (s.getItemDamage() == fluidID) return false; + } + return true; + } - @Override - public void setInventorySlotContents(int slotId, ItemStack itemstack) { - if (itemstack == null) { - super.setInventorySlotContents(slotId, null); - return; - } - Fluid fluid; - if (itemstack.getItem() == ItemEnum.FLUIDITEM.getItem()) { - fluid = FluidRegistry.getFluid(itemstack.getItemDamage()); - if (fluid == null) - return; - } else { - if (!isItemValidForSlot(slotId, itemstack)) - return; - FluidStack fluidStack = FluidUtil.getFluidFromContainer(itemstack); - if (fluidStack == null) { - super.setInventorySlotContents(slotId, null); - return; - } - fluid = fluidStack.getFluid(); - if (fluid == null) { - super.setInventorySlotContents(slotId, null); - return; - } - } - super.setInventorySlotContents(slotId, - new ItemStack(ItemEnum.FLUIDITEM.getItem(), 1, fluid.getID())); - } + @Override + public void markDirty() { + NBTTagCompound tag; + if (this.cellItem.hasTagCompound()) tag = this.cellItem.getTagCompound(); + else tag = new NBTTagCompound(); + tag.setTag("filter", writeToNBT()); + } + @Override + public void setInventorySlotContents(int slotId, ItemStack itemstack) { + if (itemstack == null) { + super.setInventorySlotContents(slotId, null); + return; + } + Fluid fluid; + if (itemstack.getItem() == ItemEnum.FLUIDITEM.getItem()) { + fluid = FluidRegistry.getFluid(itemstack.getItemDamage()); + if (fluid == null) return; + } else { + if (!isItemValidForSlot(slotId, itemstack)) return; + FluidStack fluidStack = FluidUtil.getFluidFromContainer(itemstack); + if (fluidStack == null) { + super.setInventorySlotContents(slotId, null); + return; + } + fluid = fluidStack.getFluid(); + if (fluid == null) { + super.setInventorySlotContents(slotId, null); + return; + } + } + super.setInventorySlotContents(slotId, new ItemStack(ItemEnum.FLUIDITEM.getItem(), 1, fluid.getID())); + } } diff --git a/src/main/scala/extracells/util/inventory/ECPrivateInventory.java b/src/main/scala/extracells/util/inventory/ECPrivateInventory.java index 5e2c1f256..c671d5569 100644 --- a/src/main/scala/extracells/util/inventory/ECPrivateInventory.java +++ b/src/main/scala/extracells/util/inventory/ECPrivateInventory.java @@ -8,165 +8,158 @@ public class ECPrivateInventory implements IInventory { - public ItemStack[] slots; - public String customName; - private int stackLimit; - private IInventoryUpdateReceiver receiver; - - public ECPrivateInventory(String _customName, int _size, int _stackLimit) { - this(_customName, _size, _stackLimit, null); - } - - public ECPrivateInventory(String _customName, int _size, int _stackLimit, - IInventoryUpdateReceiver _receiver) { - this.slots = new ItemStack[_size]; - this.customName = _customName; - this.stackLimit = _stackLimit; - this.receiver = _receiver; - } - - @Override - public void closeInventory() { - // NOBODY needs this! - } - - @Override - public ItemStack decrStackSize(int slotId, int amount) { - if (this.slots[slotId] == null) - return null; - ItemStack itemstack; - if (this.slots[slotId].stackSize <= amount) { - itemstack = this.slots[slotId]; - this.slots[slotId] = null; - markDirty(); - return itemstack; - } else { - ItemStack temp = this.slots[slotId]; - itemstack = temp.splitStack(amount); - this.slots[slotId] = temp; - if (temp.stackSize == 0) { - this.slots[slotId] = null; - } else { - this.slots[slotId] = temp; - } - markDirty(); - return itemstack; - } - } - - @Override - public String getInventoryName() { - return this.customName; - } - - @Override - public int getInventoryStackLimit() { - return this.stackLimit; - } - - @Override - public int getSizeInventory() { - return this.slots.length; - } - - @Override - public ItemStack getStackInSlot(int i) { - return this.slots[i]; - } - - @Override - public ItemStack getStackInSlotOnClosing(int slotId) { - return this.slots[slotId]; - } - - @Override - public boolean hasCustomInventoryName() { - return false; - } - - /** - * Increases the stack size of a slot. - * - * @param slotId - * ID of the slot - * @param amount - * amount to be drained - * - * @return the added Stack - */ - public ItemStack incrStackSize(int slotId, int amount) { - ItemStack slot = this.slots[slotId]; - if (slot == null) - return null; - int stackLimit = getInventoryStackLimit(); - if (stackLimit > slot.getMaxStackSize()) - stackLimit = slot.getMaxStackSize(); - ItemStack added = slot.copy(); - added.stackSize = slot.stackSize + amount > stackLimit ? stackLimit - : amount; - slot.stackSize += added.stackSize; - return added; - } - - @Override - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return true; - } - - @Override - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return true; - } - - @Override - public void markDirty() { - if (this.receiver != null) - this.receiver.onInventoryChanged(); - } - - @Override - public void openInventory() { - // NOBODY needs this! - } - - public void readFromNBT(NBTTagList nbtList) { - if(nbtList == null){ - for(int i = 0; i < slots.length; i++){ - slots[i] = null; - } - return; - } - for (int i = 0; i < nbtList.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbtList.getCompoundTagAt(i); - int j = nbttagcompound.getByte("Slot") & 255; - - if (j >= 0 && j < this.slots.length) { - this.slots[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); - } - } - } - - @Override - public void setInventorySlotContents(int slotId, ItemStack itemstack) { - if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { - itemstack.stackSize = getInventoryStackLimit(); - } - this.slots[slotId] = itemstack; - - markDirty(); - } - - public NBTTagList writeToNBT() { - NBTTagList nbtList = new NBTTagList(); - - for (int i = 0; i < this.slots.length; ++i) { - if (this.slots[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setByte("Slot", (byte) i); - this.slots[i].writeToNBT(nbttagcompound); - nbtList.appendTag(nbttagcompound); - } - } - return nbtList; - } + public ItemStack[] slots; + public String customName; + private int stackLimit; + private IInventoryUpdateReceiver receiver; + + public ECPrivateInventory(String _customName, int _size, int _stackLimit) { + this(_customName, _size, _stackLimit, null); + } + + public ECPrivateInventory(String _customName, int _size, int _stackLimit, IInventoryUpdateReceiver _receiver) { + this.slots = new ItemStack[_size]; + this.customName = _customName; + this.stackLimit = _stackLimit; + this.receiver = _receiver; + } + + @Override + public void closeInventory() { + // NOBODY needs this! + } + + @Override + public ItemStack decrStackSize(int slotId, int amount) { + if (this.slots[slotId] == null) return null; + ItemStack itemstack; + if (this.slots[slotId].stackSize <= amount) { + itemstack = this.slots[slotId]; + this.slots[slotId] = null; + markDirty(); + return itemstack; + } else { + ItemStack temp = this.slots[slotId]; + itemstack = temp.splitStack(amount); + this.slots[slotId] = temp; + if (temp.stackSize == 0) { + this.slots[slotId] = null; + } else { + this.slots[slotId] = temp; + } + markDirty(); + return itemstack; + } + } + + @Override + public String getInventoryName() { + return this.customName; + } + + @Override + public int getInventoryStackLimit() { + return this.stackLimit; + } + + @Override + public int getSizeInventory() { + return this.slots.length; + } + + @Override + public ItemStack getStackInSlot(int i) { + return this.slots[i]; + } + + @Override + public ItemStack getStackInSlotOnClosing(int slotId) { + return this.slots[slotId]; + } + + @Override + public boolean hasCustomInventoryName() { + return false; + } + + /** + * Increases the stack size of a slot. + * + * @param slotId ID of the slot + * @param amount amount to be drained + * + * @return the added Stack + */ + public ItemStack incrStackSize(int slotId, int amount) { + ItemStack slot = this.slots[slotId]; + if (slot == null) return null; + int stackLimit = getInventoryStackLimit(); + if (stackLimit > slot.getMaxStackSize()) stackLimit = slot.getMaxStackSize(); + ItemStack added = slot.copy(); + added.stackSize = slot.stackSize + amount > stackLimit ? stackLimit : amount; + slot.stackSize += added.stackSize; + markDirty(); + return added; + } + + @Override + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return true; + } + + @Override + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return true; + } + + @Override + public void markDirty() { + if (this.receiver != null) this.receiver.onInventoryChanged(); + } + + @Override + public void openInventory() { + // NOBODY needs this! + } + + public void readFromNBT(NBTTagList nbtList) { + if (nbtList == null) { + for (int i = 0; i < slots.length; i++) { + slots[i] = null; + } + return; + } + for (int i = 0; i < nbtList.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbtList.getCompoundTagAt(i); + int j = nbttagcompound.getByte("Slot") & 255; + + if (j >= 0 && j < this.slots.length) { + this.slots[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + } + } + } + + @Override + public void setInventorySlotContents(int slotId, ItemStack itemstack) { + if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) { + itemstack.stackSize = getInventoryStackLimit(); + } + this.slots[slotId] = itemstack; + + markDirty(); + } + + public NBTTagList writeToNBT() { + NBTTagList nbtList = new NBTTagList(); + + for (int i = 0; i < this.slots.length; ++i) { + if (this.slots[i] != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setByte("Slot", (byte) i); + this.slots[i].writeToNBT(nbttagcompound); + nbtList.appendTag(nbttagcompound); + } + } + return nbtList; + } } diff --git a/src/main/scala/extracells/util/inventory/IInventoryUpdateReceiver.java b/src/main/scala/extracells/util/inventory/IInventoryUpdateReceiver.java index d33699c0f..c15fd9408 100644 --- a/src/main/scala/extracells/util/inventory/IInventoryUpdateReceiver.java +++ b/src/main/scala/extracells/util/inventory/IInventoryUpdateReceiver.java @@ -2,5 +2,5 @@ public interface IInventoryUpdateReceiver { - public void onInventoryChanged(); + public void onInventoryChanged(); } diff --git a/src/main/scala/extracells/util/recipe/RecipeUniversalTerminal.scala b/src/main/scala/extracells/util/recipe/RecipeUniversalTerminal.scala index 8a8e206fe..05479297f 100644 --- a/src/main/scala/extracells/util/recipe/RecipeUniversalTerminal.scala +++ b/src/main/scala/extracells/util/recipe/RecipeUniversalTerminal.scala @@ -11,14 +11,13 @@ import net.minecraft.item.crafting.IRecipe import net.minecraft.nbt.NBTTagCompound import net.minecraft.world.World - -object RecipeUniversalTerminal extends IRecipe{ +object RecipeUniversalTerminal extends IRecipe { val THIS = this val itemUniversal = ItemWirelessTerminalUniversal - override def matches(inventory : InventoryCrafting, world : World): Boolean = { + override def matches(inventory: InventoryCrafting, world: World): Boolean = { var hasWireless = false var isUniversal = false var hasTerminal = false @@ -26,108 +25,113 @@ object RecipeUniversalTerminal extends IRecipe{ var terminal: ItemStack = null val size = inventory.getSizeInventory var i = 0 - for(i <- 0 until size){ + for (i <- 0 until size) { val stack = inventory.getStackInSlot(i) - if(stack != null){ + if (stack != null) { val item = stack.getItem - if(item == itemUniversal){ - if(hasWireless) + if (item == itemUniversal) { + if (hasWireless) return false - else{ + else { hasWireless = true isUniversal = true terminal = stack } - }else if(UniversalTerminal.isWirelessTerminal(stack)){ - if(hasWireless) + } else if (UniversalTerminal.isWirelessTerminal(stack)) { + if (hasWireless) return false hasWireless = true terminal = stack - }else if(UniversalTerminal.isTerminal(stack)){ + } else if (UniversalTerminal.isTerminal(stack)) { hasTerminal = true val typeTerminal = UniversalTerminal.getTerminalType(stack) - if(terminals.contains(typeTerminal)){ + if (terminals.contains(typeTerminal)) { return false - }else{ + } else { terminals ++= List(typeTerminal) } } } } - if(!(hasTerminal && hasWireless)) - return false - if(isUniversal){ - for(x <- terminals){ - if(itemUniversal.isInstalled(terminal, x)) + if (!(hasTerminal && hasWireless)) + return false + if (isUniversal) { + for (x <- terminals) { + if (itemUniversal.isInstalled(terminal, x)) return false } true - }else{ + } else { val terminalType = UniversalTerminal.getTerminalType(terminal) - for(x <- terminals){ - if(x == terminalType) + for (x <- terminals) { + if (x == terminalType) return false } true } } - override def getRecipeOutput: ItemStack = ItemEnum.UNIVERSALTERMINAL.getDamagedStack(0) + override def getRecipeOutput: ItemStack = + ItemEnum.UNIVERSALTERMINAL.getDamagedStack(0) override def getRecipeSize: Int = 2 - override def getCraftingResult(inventory : InventoryCrafting): ItemStack = { + override def getCraftingResult(inventory: InventoryCrafting): ItemStack = { var isUniversal = false var terminals = List[TerminalType]() var terminal: ItemStack = null val size = inventory.getSizeInventory var i = 0 - for(i <- 0 until size){ + for (i <- 0 until size) { val stack = inventory.getStackInSlot(i) - if(stack != null){ + if (stack != null) { val item = stack.getItem - if(item == itemUniversal){ - isUniversal = true - terminal = stack.copy - }else if(UniversalTerminal.isWirelessTerminal(stack)){ + if (item == itemUniversal) { + isUniversal = true + terminal = stack.copy + } else if (UniversalTerminal.isWirelessTerminal(stack)) { terminal = stack.copy - }else if(UniversalTerminal.isTerminal(stack)){ + } else if (UniversalTerminal.isTerminal(stack)) { val typeTerminal = UniversalTerminal.getTerminalType(stack) - terminals ++= List(typeTerminal) + terminals ++= List(typeTerminal) } } } - if(isUniversal){ - for(x <- terminals) + if (isUniversal) { + for (x <- terminals) itemUniversal.installModule(terminal, x) - }else{ + } else { val terminalType = UniversalTerminal.getTerminalType(terminal) val itemTerminal = terminal.getItem val t = new ItemStack(itemUniversal) - if(itemTerminal.isInstanceOf[INetworkEncodable]){ - val key = itemTerminal.asInstanceOf[INetworkEncodable].getEncryptionKey(terminal) - if(key != null) + if (itemTerminal.isInstanceOf[INetworkEncodable]) { + val key = itemTerminal + .asInstanceOf[INetworkEncodable] + .getEncryptionKey(terminal) + if (key != null) itemUniversal.setEncryptionKey(t, key, null) } - if(itemTerminal.isInstanceOf[IAEItemPowerStorage]){ - val power = itemTerminal.asInstanceOf[IAEItemPowerStorage].getAECurrentPower(terminal) + if (itemTerminal.isInstanceOf[IAEItemPowerStorage]) { + val power = itemTerminal + .asInstanceOf[IAEItemPowerStorage] + .getAECurrentPower(terminal) itemUniversal.injectAEPower(t, power) } - if(terminal.hasTagCompound){ + if (terminal.hasTagCompound) { val nbt = terminal.getTagCompound - if(!t.hasTagCompound) + if (!t.hasTagCompound) t.setTagCompound(new NBTTagCompound) - if(nbt.hasKey("BoosterSlot")){ + if (nbt.hasKey("BoosterSlot")) { t.getTagCompound.setTag("BoosterSlot", nbt.getTag("BoosterSlot")) } - if(nbt.hasKey("MagnetSlot")) + if (nbt.hasKey("MagnetSlot")) t.getTagCompound.setTag("MagnetSlot", nbt.getTag("MagnetSlot")); } itemUniversal.installModule(t, terminalType) t.getTagCompound.setByte("type", terminalType.ordinal.toByte) terminal = t - for(x <- terminals) + for (x <- terminals) itemUniversal.installModule(terminal, x) } terminal diff --git a/src/main/scala/extracells/wireless/AEWirelessTermHandler.java b/src/main/scala/extracells/wireless/AEWirelessTermHandler.java index 65a486429..7ff2a4587 100644 --- a/src/main/scala/extracells/wireless/AEWirelessTermHandler.java +++ b/src/main/scala/extracells/wireless/AEWirelessTermHandler.java @@ -1,59 +1,51 @@ package extracells.wireless; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.item.ItemStack; + import appeng.api.features.IWirelessTermHandler; import appeng.api.util.IConfigManager; import extracells.api.IWirelessGasFluidTermHandler; -import net.minecraft.entity.player.EntityPlayer; -import net.minecraft.item.ItemStack; public class AEWirelessTermHandler implements IWirelessTermHandler { - @Override - public boolean canHandle(ItemStack is) { - IWirelessGasFluidTermHandler handler = WirelessTermRegistry - .getWirelessTermHandler(is); - if (handler == null) - return false; - return !handler.isItemNormalWirelessTermToo(is); - } - - @Override - public IConfigManager getConfigManager(ItemStack is) { - return new ConfigManager(); - } - - @Override - public String getEncryptionKey(ItemStack item) { - IWirelessGasFluidTermHandler handler = WirelessTermRegistry - .getWirelessTermHandler(item); - if (handler == null) - return null; - return handler.getEncryptionKey(item); - } - - @Override - public boolean hasPower(EntityPlayer player, double amount, ItemStack is) { - IWirelessGasFluidTermHandler handler = WirelessTermRegistry - .getWirelessTermHandler(is); - if (handler == null) - return false; - return handler.hasPower(player, amount, is); - } - - @Override - public void setEncryptionKey(ItemStack item, String encKey, String name) { - IWirelessGasFluidTermHandler handler = WirelessTermRegistry.getWirelessTermHandler(item); - if (handler == null) - return; - handler.setEncryptionKey(item, encKey, name); - } - - @Override - public boolean usePower(EntityPlayer player, double amount, ItemStack is) { - IWirelessGasFluidTermHandler handler = WirelessTermRegistry.getWirelessTermHandler(is); - if (handler == null) - return false; - return handler.usePower(player, amount, is); - } - + @Override + public boolean canHandle(ItemStack is) { + IWirelessGasFluidTermHandler handler = WirelessTermRegistry.getWirelessTermHandler(is); + if (handler == null) return false; + return !handler.isItemNormalWirelessTermToo(is); + } + + @Override + public IConfigManager getConfigManager(ItemStack is) { + return new ConfigManager(); + } + + @Override + public String getEncryptionKey(ItemStack item) { + IWirelessGasFluidTermHandler handler = WirelessTermRegistry.getWirelessTermHandler(item); + if (handler == null) return null; + return handler.getEncryptionKey(item); + } + + @Override + public boolean hasPower(EntityPlayer player, double amount, ItemStack is) { + IWirelessGasFluidTermHandler handler = WirelessTermRegistry.getWirelessTermHandler(is); + if (handler == null) return false; + return handler.hasPower(player, amount, is); + } + + @Override + public void setEncryptionKey(ItemStack item, String encKey, String name) { + IWirelessGasFluidTermHandler handler = WirelessTermRegistry.getWirelessTermHandler(item); + if (handler == null) return; + handler.setEncryptionKey(item, encKey, name); + } + + @Override + public boolean usePower(EntityPlayer player, double amount, ItemStack is) { + IWirelessGasFluidTermHandler handler = WirelessTermRegistry.getWirelessTermHandler(is); + if (handler == null) return false; + return handler.usePower(player, amount, is); + } } diff --git a/src/main/scala/extracells/wireless/ConfigManager.java b/src/main/scala/extracells/wireless/ConfigManager.java index 144869093..b972ff0d4 100644 --- a/src/main/scala/extracells/wireless/ConfigManager.java +++ b/src/main/scala/extracells/wireless/ConfigManager.java @@ -1,98 +1,87 @@ package extracells.wireless; +import java.util.EnumMap; +import java.util.Map; +import java.util.Set; + +import net.minecraft.nbt.NBTTagCompound; import appeng.api.config.Settings; import appeng.api.config.SortDir; import appeng.api.config.SortOrder; import appeng.api.config.ViewItems; import appeng.api.util.IConfigManager; -import net.minecraft.nbt.NBTTagCompound; - -import java.util.EnumMap; -import java.util.Map; -import java.util.Set; public class ConfigManager implements IConfigManager { - private final Map> settings = new EnumMap>( Settings.class ); + private final Map> settings = new EnumMap>(Settings.class); private final NBTTagCompound tagCompound; - public ConfigManager(){ + public ConfigManager() { this(null); } - public ConfigManager(NBTTagCompound tag){ + public ConfigManager(NBTTagCompound tag) { this.tagCompound = tag; if (tag != null) { - registerSetting( Settings.SORT_BY, SortOrder.NAME ); - registerSetting( Settings.VIEW_MODE, ViewItems.ALL ); - registerSetting( Settings.SORT_DIRECTION, SortDir.ASCENDING ); + registerSetting(Settings.SORT_BY, SortOrder.NAME); + registerSetting(Settings.VIEW_MODE, ViewItems.ALL); + registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING); readFromNBT((NBTTagCompound) tag.copy()); } - } @Override - public Set getSettings() - { + public Set getSettings() { return this.settings.keySet(); } @Override - public void registerSetting(Settings settingName, Enum defaultValue) - { - this.settings.put( settingName, defaultValue ); + public void registerSetting(Settings settingName, Enum defaultValue) { + this.settings.put(settingName, defaultValue); } @Override - public Enum getSetting(Settings settingName) - { - final Enum oldValue = this.settings.get( settingName ); + public Enum getSetting(Settings settingName) { + final Enum oldValue = this.settings.get(settingName); - if( oldValue != null ) - { + if (oldValue != null) { return oldValue; } - throw new IllegalStateException( "Invalid Config setting. Expected a non-null value for " + settingName ); + throw new IllegalStateException("Invalid Config setting. Expected a non-null value for " + settingName); } @Override public Enum putSetting(Settings settingName, Enum newValue) { - final Enum oldValue = this.getSetting( settingName ); - this.settings.put( settingName, newValue ); - if(tagCompound != null) - this.writeToNBT(tagCompound); + final Enum oldValue = this.getSetting(settingName); + this.settings.put(settingName, newValue); + if (tagCompound != null) this.writeToNBT(tagCompound); return oldValue; } @Override public void writeToNBT(NBTTagCompound tagCompound) { - for( final Map.Entry> entry : this.settings.entrySet() ) - { - tagCompound.setString( entry.getKey().name(), this.settings.get( entry.getKey() ).toString() ); + for (final Map.Entry> entry : this.settings.entrySet()) { + tagCompound.setString(entry.getKey().name(), this.settings.get(entry.getKey()).toString()); } } @Override public void readFromNBT(NBTTagCompound tagCompound) { - for( final Map.Entry> entry : this.settings.entrySet() ) { + for (final Map.Entry> entry : this.settings.entrySet()) { try { - if( tagCompound.hasKey( entry.getKey().name() ) ) { - String value = tagCompound.getString( entry.getKey().name() ); + if (tagCompound.hasKey(entry.getKey().name())) { + String value = tagCompound.getString(entry.getKey().name()); - final Enum oldValue = this.settings.get( entry.getKey() ); + final Enum oldValue = this.settings.get(entry.getKey()); - final Enum newValue = Enum.valueOf( oldValue.getClass(), value ); + final Enum newValue = Enum.valueOf(oldValue.getClass(), value); - this.putSetting( entry.getKey(), newValue ); + this.putSetting(entry.getKey(), newValue); } - } - catch( final IllegalArgumentException e ) - {} + } catch (final IllegalArgumentException e) {} } } - - -} \ No newline at end of file +} diff --git a/src/main/scala/extracells/wireless/WirelessTermRegistry.java b/src/main/scala/extracells/wireless/WirelessTermRegistry.java index d2aeb18ef..e67e2d1db 100644 --- a/src/main/scala/extracells/wireless/WirelessTermRegistry.java +++ b/src/main/scala/extracells/wireless/WirelessTermRegistry.java @@ -1,39 +1,33 @@ package extracells.wireless; -import extracells.api.IWirelessGasFluidTermHandler; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.List; -public class WirelessTermRegistry { +import net.minecraft.item.ItemStack; + +import extracells.api.IWirelessGasFluidTermHandler; - public static IWirelessGasFluidTermHandler getWirelessTermHandler(ItemStack is) { - if (is == null) - return null; - for (IWirelessGasFluidTermHandler handler : handlers) { - if (handler.canHandle(is)) - return handler; - } - return null; - } - - public static boolean isWirelessItem(ItemStack is) { - if (is == null) - return false; - for (IWirelessGasFluidTermHandler handler : handlers) { - if (handler.canHandle(is)) - return true; - } - return false; - } - - public static void registerWirelessTermHandler( - IWirelessGasFluidTermHandler handler) { - if (!handlers.contains(handler)) - handlers.add(handler); - } - - static List handlers = new ArrayList(); +public class WirelessTermRegistry { + public static IWirelessGasFluidTermHandler getWirelessTermHandler(ItemStack is) { + if (is == null) return null; + for (IWirelessGasFluidTermHandler handler : handlers) { + if (handler.canHandle(is)) return handler; + } + return null; + } + + public static boolean isWirelessItem(ItemStack is) { + if (is == null) return false; + for (IWirelessGasFluidTermHandler handler : handlers) { + if (handler.canHandle(is)) return true; + } + return false; + } + + public static void registerWirelessTermHandler(IWirelessGasFluidTermHandler handler) { + if (!handlers.contains(handler)) handlers.add(handler); + } + + static List handlers = new ArrayList(); }