Compare commits

..
Author SHA1 Message Date
Martin Robertz 7c41a6eb04 Merge remote-tracking branch 'asdflj/master' into dev 2023-02-27 07:40:25 +01:00
asdflj 008b4eee1f Certus Quartz Tank add waila support
fluid packet decode add support to use conduit to export fluid
2023-02-27 13:20:35 +08:00
48 changed files with 1356 additions and 1350 deletions

No files matched your search

+19 -290
View File
@@ -1,4 +1,4 @@
//version: 1678003329
//version: 1675173326
/*
DO NOT CHANGE THIS FILE!
Also, you may replace this file at any time if there is an update available.
@@ -9,18 +9,13 @@
import com.diffplug.blowdryer.Blowdryer
import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import com.gtnewhorizons.retrofuturagradle.ObfuscationAttribute
import com.gtnewhorizons.retrofuturagradle.mcp.ReobfuscatedJar
import com.gtnewhorizons.retrofuturagradle.minecraft.RunMinecraftTask
import com.matthewprenger.cursegradle.CurseArtifact
import com.matthewprenger.cursegradle.CurseRelation
import com.modrinth.minotaur.dependencies.ModDependency
import com.modrinth.minotaur.dependencies.VersionDependency
import cpw.mods.fml.relauncher.Side
import org.gradle.api.tasks.options.Option;
import org.gradle.internal.logging.text.StyledTextOutput.Style
import org.gradle.internal.logging.text.StyledTextOutputFactory
import org.gradle.internal.xml.XmlTransformer
import org.jetbrains.gradle.ext.*
import java.nio.file.Files
@@ -28,10 +23,10 @@ import java.nio.file.Paths
import java.util.concurrent.TimeUnit
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import javax.inject.Inject
buildscript {
repositories {
mavenLocal()
mavenCentral()
maven {
@@ -52,8 +47,6 @@ buildscript {
name 'Scala CI dependencies'
url 'https://repo1.maven.org/maven2/'
}
mavenLocal()
}
}
plugins {
@@ -73,7 +66,7 @@ plugins {
id 'com.diffplug.spotless' version '6.7.2' apply false
id 'com.modrinth.minotaur' version '2.+' apply false
id 'com.matthewprenger.cursegradle' version '1.4.0' apply false
id 'com.gtnewhorizons.retrofuturagradle' version '1.2.3'
id 'com.gtnewhorizons.retrofuturagradle' version '1.1.3'
}
boolean settingsupdated = verifySettingsGradle()
settingsupdated = verifyGitAttributes() || settingsupdated
@@ -129,9 +122,6 @@ propertyDefaultIfUnset("gradleTokenGroupName", "")
propertyDefaultIfUnset("enableModernJavaSyntax", false) // On by default for new projects only
propertyDefaultIfUnset("enableGenericInjection", false) // On by default for new projects only
// this is meant to be set using the user wide property file. by default we do nothing.
propertyDefaultIfUnset("ideaOverrideBuildType", "") // Can be nothing, "gradle" or "idea"
project.extensions.add(Blowdryer, "Blowdryer", Blowdryer) // Make blowdryer available in "apply from:" scripts
if (!disableSpotless) {
apply plugin: 'com.diffplug.spotless'
@@ -153,7 +143,7 @@ java {
} else {
languageVersion.set(projectJavaVersion)
}
vendor.set(JvmVendorSpec.AZUL)
vendor.set(JvmVendorSpec.ADOPTIUM)
}
if (!noPublishedSources) {
withSourcesJar()
@@ -196,21 +186,11 @@ configurations {
}
if (enableModernJavaSyntax.toBoolean()) {
repositories {
mavenCentral {
mavenContent {
includeGroup("me.eigenraven.java8unsupported")
}
}
}
dependencies {
annotationProcessor 'com.github.bsideup.jabel:jabel-javac-plugin:1.0.0'
compileOnly('com.github.bsideup.jabel:jabel-javac-plugin:1.0.0') {
transitive = false // We only care about the 1 annotation class
}
// Allow using jdk.unsupported classes like sun.misc.Unsafe in the compiled code, working around JDK-8206937.
patchedMinecraft('me.eigenraven.java8unsupported:java-8-unsupported-shim:1.0.0')
}
tasks.withType(JavaCompile).configureEach {
@@ -222,7 +202,7 @@ if (enableModernJavaSyntax.toBoolean()) {
javaCompiler.set(javaToolchains.compilerFor {
languageVersion.set(JavaLanguageVersion.of(17))
vendor.set(JvmVendorSpec.AZUL)
vendor.set(JvmVendorSpec.ADOPTIUM)
})
}
}
@@ -254,14 +234,12 @@ if (apiPackage) {
}
if (accessTransformersFile) {
for (atFile in accessTransformersFile.split(",")) {
String targetFile = "src/main/resources/META-INF/" + atFile.trim()
if (!getFile(targetFile).exists()) {
throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile)
}
tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(targetFile)
tasks.srgifyBinpatchedJar.accessTransformerFiles.from(targetFile)
String targetFile = "src/main/resources/META-INF/" + accessTransformersFile
if (!getFile(targetFile).exists()) {
throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile)
}
tasks.deobfuscateMergedJarToSrg.accessTransformerFiles.from(targetFile)
tasks.srgifyBinpatchedJar.accessTransformerFiles.from(targetFile)
} else {
boolean atsFound = false
for (File at : sourceSets.getByName("main").resources.files) {
@@ -389,10 +367,6 @@ minecraft {
injectMissingGenerics.set(true)
}
username = developmentEnvironmentUserName.toString()
lwjgl3Version = "3.3.2-SNAPSHOT"
// Enable assertions in the current mod
extraRunJvmArguments.add("-ea:${modGroup}")
@@ -427,16 +401,6 @@ configurations.configureEach {
}
}
}
def obfuscationAttr = it.attributes.getAttribute(ObfuscationAttribute.OBFUSCATION_ATTRIBUTE)
if (obfuscationAttr != null && obfuscationAttr.name == ObfuscationAttribute.SRG) {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
// Remap CoFH core cursemaven dev jar to the obfuscated version for runObfClient/Server
if (details.requested.group == 'curse.maven' && details.requested.name.endsWith('-69162') && details.requested.version == '2388751') {
details.useVersion '2388750'
details.because 'Pick obfuscated jar'
}
}
}
}
// Ensure tests have access to minecraft classes
@@ -466,9 +430,8 @@ repositories.configureEach { repo ->
apply from: 'repositories.gradle'
configurations {
runtimeClasspath.extendsFrom(runtimeOnlyNonPublishable)
testRuntimeClasspath.extendsFrom(runtimeOnlyNonPublishable)
for (config in [compileClasspath, runtimeClasspath, testCompileClasspath, testRuntimeClasspath]) {
config.extendsFrom(runtimeOnlyNonPublishable)
if (usesShadowedDependencies.toBoolean()) {
config.extendsFrom(shadowImplementation)
// TODO: remove Compile after all uses are refactored to Implementation
@@ -521,13 +484,6 @@ repositories {
}
}
}
maven {
name 'sonatype'
url 'https://oss.sonatype.org/content/repositories/snapshots/'
content {
includeGroup "org.lwjgl"
}
}
if (includeWellKnownRepositories.toBoolean()) {
maven {
name "CurseMaven"
@@ -564,20 +520,20 @@ dependencies {
annotationProcessor('org.ow2.asm:asm-debug-all:5.0.3')
annotationProcessor('com.google.guava:guava:24.1.1-jre')
annotationProcessor('com.google.code.gson:gson:2.8.6')
annotationProcessor('com.gtnewhorizon:gtnhmixins:2.1.13:processor')
annotationProcessor('com.gtnewhorizon:gtnhmixins:2.1.10:processor')
if (usesMixinDebug.toBoolean()) {
runtimeOnlyNonPublishable('org.jetbrains:intellij-fernflower:1.2.1.16')
}
}
if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) {
implementation('com.gtnewhorizon:gtnhmixins:2.1.13')
implementation('com.gtnewhorizon:gtnhmixins:2.1.10')
}
}
pluginManager.withPlugin('org.jetbrains.kotlin.kapt') {
if (usesMixins.toBoolean()) {
dependencies {
kapt('com.gtnewhorizon:gtnhmixins:2.1.13:processor')
kapt('com.gtnewhorizon:gtnhmixins:2.1.10:processor')
}
}
}
@@ -677,150 +633,9 @@ tasks.named("processResources", ProcessResources).configure {
if (usesMixins.toBoolean()) {
from refMap
dependsOn("compileJava", "compileScala")
}
}
ext.java17Toolchain = (JavaToolchainSpec spec) -> {
spec.languageVersion.set(JavaLanguageVersion.of(17))
spec.vendor.set(JvmVendorSpec.matching("jetbrains"))
}
ext.java17DependenciesCfg = configurations.create("java17Dependencies") {
extendsFrom(configurations.getByName("runtimeClasspath")) // Ensure consistent transitive dependency resolution
canBeConsumed = false
}
ext.java17PatchDependenciesCfg = configurations.create("java17PatchDependencies") {
canBeConsumed = false
}
dependencies {
def lwjgl3ifyVersion = '1.1.35'
def asmVersion = '9.4'
if (modId != 'lwjgl3ify') {
java17Dependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}")
}
if (modId != 'hodgepodge') {
java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.0.40')
}
java17PatchDependencies('net.minecraft:launchwrapper:1.15') {transitive = false}
java17PatchDependencies("org.ow2.asm:asm:${asmVersion}")
java17PatchDependencies("org.ow2.asm:asm-commons:${asmVersion}")
java17PatchDependencies("org.ow2.asm:asm-tree:${asmVersion}")
java17PatchDependencies("org.ow2.asm:asm-analysis:${asmVersion}")
java17PatchDependencies("org.ow2.asm:asm-util:${asmVersion}")
java17PatchDependencies('org.ow2.asm:asm-deprecated:7.1')
java17PatchDependencies("org.apache.commons:commons-lang3:3.12.0")
java17PatchDependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}:forgePatches") {transitive = false}
}
ext.java17JvmArgs = [
// Java 9+ support
"--illegal-access=warn",
"-Djava.security.manager=allow",
"-Dfile.encoding=UTF-8",
"--add-opens", "java.base/jdk.internal.loader=ALL-UNNAMED",
"--add-opens", "java.base/java.net=ALL-UNNAMED",
"--add-opens", "java.base/java.nio=ALL-UNNAMED",
"--add-opens", "java.base/java.io=ALL-UNNAMED",
"--add-opens", "java.base/java.lang=ALL-UNNAMED",
"--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED",
"--add-opens", "java.base/java.text=ALL-UNNAMED",
"--add-opens", "java.base/java.util=ALL-UNNAMED",
"--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED",
"--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED",
"--add-opens", "jdk.naming.dns/com.sun.jndi.dns=ALL-UNNAMED,java.naming",
"--add-opens", "java.desktop/sun.awt.image=ALL-UNNAMED",
"--add-modules", "jdk.dynalink",
"--add-opens", "jdk.dynalink/jdk.dynalink.beans=ALL-UNNAMED",
"--add-modules", "java.sql.rowset",
"--add-opens", "java.sql.rowset/javax.sql.rowset.serial=ALL-UNNAMED"
]
ext.hotswapJvmArgs = [
// DCEVM advanced hot reload
"-XX:+AllowEnhancedClassRedefinition",
"-XX:HotswapAgent=fatjar"
]
ext.setupHotswapAgentTask = tasks.register("setupHotswapAgent") {
group = "GTNH Buildscript"
description = "Installs a recent version of HotSwapAgent into the Java 17 JetBrains runtime directory"
def hsaUrl = 'https://github.com/HotswapProjects/HotswapAgent/releases/download/1.4.2-SNAPSHOT/hotswap-agent-1.4.2-SNAPSHOT.jar'
def targetFolderProvider = javaToolchains.launcherFor(java17Toolchain).map {it.metadata.installationPath.dir("lib/hotswap")}
def targetFilename = "hotswap-agent.jar"
onlyIf {
!targetFolderProvider.get().file(targetFilename).asFile.exists()
}
doLast {
def targetFolder = targetFolderProvider.get()
targetFolder.asFile.mkdirs()
download.run {
src hsaUrl
dest targetFolder.file(targetFilename).asFile
overwrite false
tempAndMove true
}
}
}
public abstract class RunHotswappableMinecraftTask extends RunMinecraftTask {
// IntelliJ doesn't seem to allow commandline arguments so we also support an env variable
private boolean enableHotswap = Boolean.valueOf(System.getenv("HOTSWAP"));
@Input
public boolean getEnableHotswap() { return enableHotswap }
@Option(option = "hotswap", description = "Enables HotSwapAgent for enhanced class reloading under a debugger")
public boolean setEnableHotswap(boolean enable) { enableHotswap = enable }
@Inject
public RunHotswappableMinecraftTask(Side side, String superTask, org.gradle.api.invocation.Gradle gradle) {
super(side, gradle)
this.lwjglVersion = 3
this.javaLauncher = project.javaToolchains.launcherFor(project.java17Toolchain)
this.extraJvmArgs.addAll(project.java17JvmArgs)
this.extraJvmArgs.addAll(project.provider(() -> enableHotswap ? project.hotswapJvmArgs : []))
this.classpath(project.java17PatchDependenciesCfg)
if (side == Side.CLIENT) {
this.classpath(project.minecraftTasks.lwjgl3Configuration)
}
// Use a raw provider instead of map to not create a dependency on the task
this.classpath(project.provider(() -> project.tasks.named(superTask, RunMinecraftTask).get().classpath))
this.classpath.filter { file ->
!file.path.contains("2.9.4-nightly-20150209") // Remove lwjgl2
}
this.classpath(project.java17DependenciesCfg)
if (!(project.usesMixins.toBoolean() || project.forceEnableMixins.toBoolean())) {
this.extraArgs.addAll("--tweakClass", "org.spongepowered.asm.launch.MixinTweaker")
}
}
}
def runClient17Task = tasks.register("runClient17", RunHotswappableMinecraftTask, Side.CLIENT, "runClient")
runClient17Task.configure {
setup(project)
group = "Modded Minecraft"
description = "Runs the modded client using Java 17, lwjgl3ify and Hodgepodge"
dependsOn(setupHotswapAgentTask, mcpTasks.launcherSources.classesTaskName, minecraftTasks.taskDownloadVanillaAssets, mcpTasks.taskPackagePatchedMc, 'jar')
mainClass = "GradleStart"
username = minecraft.username
userUUID = minecraft.userUUID
}
def runServer17Task = tasks.register("runServer17", RunHotswappableMinecraftTask, Side.SERVER, "runServer")
runServer17Task.configure {
setup(project)
group = "Modded Minecraft"
description = "Runs the modded server using Java 17, lwjgl3ify and Hodgepodge"
dependsOn(setupHotswapAgentTask, mcpTasks.launcherSources.classesTaskName, minecraftTasks.taskDownloadVanillaAssets, mcpTasks.taskPackagePatchedMc, 'jar')
mainClass = "GradleStartServer"
extraArgs.add("nogui")
}
def getManifestAttributes() {
def manifestAttributes = [:]
if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) {
@@ -855,7 +670,7 @@ if (usesShadowedDependencies.toBoolean()) {
tasks.register('relocateShadowJar', ConfigureShadowRelocation) {
target = tasks.shadowJar
prefix = modGroup + ".shadow"
enabled = relocateShadowedDependencies.toBoolean()
enabled = minimizeShadowedDependencies.toBoolean()
}
tasks.named("shadowJar", ShadowJar).configure {
manifest {
@@ -871,7 +686,7 @@ if (usesShadowedDependencies.toBoolean()) {
project.configurations.shadeCompile
]
archiveClassifier.set('dev')
if (relocateShadowedDependencies.toBoolean()) {
if (minimizeShadowedDependencies.toBoolean()) {
dependsOn(relocateShadowJar)
}
}
@@ -890,7 +705,7 @@ if (usesShadowedDependencies.toBoolean()) {
javaComponent.withVariantsFromConfiguration(configurations.shadowRuntimeElements) {
skip()
}
for (runTask in ["runClient", "runServer", "runClient17", "runServer17"]) {
for (runTask in ["runClient", "runServer"]) {
tasks.named(runTask).configure {
dependsOn("shadowJar")
}
@@ -932,19 +747,6 @@ idea {
}
project {
settings {
if (ideaOverrideBuildType != "") {
delegateActions {
if ("gradle".equalsIgnoreCase(ideaOverrideBuildType)) {
delegateBuildRunToGradle = true
testRunner = org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.GRADLE
} else if ("idea".equalsIgnoreCase(ideaOverrideBuildType)) {
delegateBuildRunToGradle = false
testRunner = org.jetbrains.gradle.ext.ActionDelegationConfig.TestRunner.PLATFORM
} else {
throw GradleScriptException('Accepted value for ideaOverrideBuildType is one of gradle or idea.')
}
}
}
runConfigurations {
"1. Run Client"(Gradle) {
taskNames = ["runClient"]
@@ -952,20 +754,6 @@ idea {
"2. Run Server"(Gradle) {
taskNames = ["runServer"]
}
"1a. Run Client (Java 17)"(Gradle) {
taskNames = ["runClient17"]
}
"2a. Run Server (Java 17)"(Gradle) {
taskNames = ["runServer17"]
}
"1b. Run Client (Java 17, Hotswap)"(Gradle) {
taskNames = ["runClient17"]
envs = ["HOTSWAP": "true"]
}
"2b. Run Server (Java 17, Hotswap)"(Gradle) {
taskNames = ["runServer17"]
envs = ["HOTSWAP": "true"]
}
"3. Run Obfuscated Client"(Gradle) {
taskNames = ["runObfClient"]
}
@@ -983,7 +771,7 @@ idea {
}
"Run Client (IJ Native)"(Application) {
mainClass = "GradleStart"
moduleName = project.name + ".ideVirtualMain"
moduleName = project.name + ".main"
afterEvaluate {
workingDirectory = tasks.runClient.workingDir.absolutePath
programParameters = tasks.runClient.calculateArgs(project).collect { '"' + it + '"' }.join(' ')
@@ -994,7 +782,7 @@ idea {
}
"Run Server (IJ Native)"(Application) {
mainClass = "GradleStartServer"
moduleName = project.name + ".ideVirtualMain"
moduleName = project.name + ".main"
afterEvaluate {
workingDirectory = tasks.runServer.workingDir.absolutePath
programParameters = tasks.runServer.calculateArgs(project).collect { '"' + it + '"' }.join(' ')
@@ -1011,51 +799,6 @@ idea {
]
}
}
withIDEADir { File ideaDir ->
if (!ideaDir.path.contains(".idea")) {
// If an .ipr file exists, the project root directory is passed here instead of the .idea subdirectory
ideaDir = new File(ideaDir, ".idea")
}
if (ideaDir.isDirectory()) {
def miscFile = new File(ideaDir, "misc.xml")
if (miscFile.isFile()) {
boolean dirty = false
def miscTransformer = new XmlTransformer()
miscTransformer.addAction { root ->
Node rootNode = root.asNode()
def rootManager = rootNode
.component.find { it.@name == 'ProjectRootManager' }
if (!rootManager) {
rootManager = rootNode.appendNode('component', ['name': 'ProjectRootManager', 'version': '2'])
dirty = true
}
def output = rootManager.output
if (!output) {
output = rootManager.appendNode('output')
dirty = true
}
if (!output.@url) {
// Only modify the output url if it doesn't yet have one, or if the existing one is blank somehow.
// This is a sensible default for most setups
output.@url = 'file://$PROJECT_DIR$/build/ideaBuild'
dirty = true
}
}
def result = miscTransformer.transform(miscFile.text)
if (dirty) {
miscFile.write(result)
}
} else {
miscFile.text = """<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2">
<output url="file://\$PROJECT_DIR\$/out" />
</component>
</project>
"""
}
}
}
}
}
}
@@ -1203,21 +946,10 @@ def addCurseForgeRelation(String type, String name) {
}
// Updating
def buildscriptGradleVersion = "8.0.1"
tasks.named('wrapper', Wrapper).configure {
gradleVersion = buildscriptGradleVersion
}
tasks.register('updateBuildScript') {
group = 'GTNH Buildscript'
description = 'Updates the build script to the latest version'
if (gradle.gradleVersion != buildscriptGradleVersion && !Boolean.getBoolean('DISABLE_BUILDSCRIPT_GRADLE_UPDATE')) {
dependsOn('wrapper')
}
doLast {
if (performBuildScriptUpdate()) return
@@ -1230,9 +962,6 @@ if (!project.getGradle().startParameter.isOffline() && !Boolean.getBoolean('DISA
performBuildScriptUpdate()
} else {
out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'")
if (gradle.gradleVersion != buildscriptGradleVersion) {
out.style(Style.SuccessHeader).println("updateBuildScript can update gradle from ${gradle.gradleVersion} to ${buildscriptGradleVersion}\n")
}
}
}
+6 -6
View File
@@ -1,12 +1,12 @@
// Add your dependencies here
dependencies {
api('com.github.GTNewHorizons:NotEnoughItems:2.3.39-GTNH:dev')
api('com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-180-GTNH:dev')
api('curse.maven:cofh-core-69162:2388751')
api('com.github.GTNewHorizons:waila:1.5.22:dev')
compile('com.github.GTNewHorizons:NotEnoughItems:2.3.32-GTNH:dev')
compile('com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-160-GTNH:dev')
compile('curse.maven:cofh-core-69162:2388751')
compile('com.github.GTNewHorizons:waila:1.5.22:dev')
compileOnly('com.github.GTNewHorizons:ExtraCells2:2.5.32:dev') { transitive = false }
compileOnly("com.github.GTNewHorizons:WirelessCraftingTerminal:1.8.9.3:dev")
compileOnly("com.github.GTNewHorizons:WirelessCraftingTerminal:1.8.9.2:dev")
compileOnly('com.github.GTNewHorizons:ForestryMC:4.5.6:dev')
compileOnly('com.github.GTNewHorizons:EnderIO:2.3.1.49:dev')
@@ -23,5 +23,5 @@ dependencies {
compileOnly('com.github.GTNewHorizons:GTplusplus:1.7.191:dev') { transitive = false }
compileOnly('com.github.GTNewHorizons:KekzTech:0.6.25:dev')
api('com.github.GTNewHorizons:Baubles:1.0.1.14:dev')
compile('com.github.GTNewHorizons:Baubles:1.0.1.14:dev')
}
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+2 -2
View File
@@ -144,7 +144,7 @@ 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=SC3045
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -152,7 +152,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
+27
View File
@@ -1,4 +1,31 @@
// 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 'ic2'
url 'https://maven.ic2.player.to/'
metadataSources {
mavenPom()
artifact()
}
}
maven {
name 'gt'
url 'https://gregtech.overminddl1.com/'
}
maven {
url 'https://cursemaven.com'
content {
includeGroup 'curse.maven'
}
}
maven {
url 'https://jitpack.io'
}
}
@@ -13,14 +13,15 @@ import com.glodblock.github.loader.CalculatorV2PluginLoader;
import com.glodblock.github.loader.ChannelLoader;
import com.glodblock.github.loader.ItemAndBlockHolder;
import com.glodblock.github.loader.RecipeLoader;
import com.glodblock.github.loader.filter.FluidFilter;
import com.glodblock.github.network.SPacketMEUpdateBuffer;
import com.glodblock.github.proxy.CommonProxy;
import com.glodblock.github.util.ModAndClassUtil;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.*;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLLoadCompleteEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkRegistry;
@Mod(
@@ -76,23 +77,10 @@ public class FluidCraft {
if (ModAndClassUtil.isV2) {
CalculatorV2PluginLoader.installCalculatorV2Plugins();
}
if (ModAndClassUtil.isTypeFilter) {
FluidFilter.installFilter();
}
proxy.postInit(event);
}
@Mod.EventHandler
public void onServerStart(FMLServerStartingEvent event) {
SPacketMEUpdateBuffer.init();
}
@Mod.EventHandler
public void onServerStop(FMLServerStoppedEvent event) {
SPacketMEUpdateBuffer.disable();
}
@Mod.EventHandler
public void onLoadComplete(FMLLoadCompleteEvent event) {}
@@ -1,27 +1,68 @@
package com.glodblock.github.client.gui;
import java.text.NumberFormat;
import java.util.*;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import appeng.api.AEApi;
import appeng.api.storage.ITerminalHost;
import appeng.client.gui.implementations.GuiCraftConfirm;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.client.gui.AEBaseGui;
import appeng.client.gui.widgets.GuiScrollbar;
import appeng.core.AELog;
import appeng.core.localization.GuiText;
import appeng.integration.modules.NEI;
import appeng.util.Platform;
import com.glodblock.github.FluidCraft;
import com.glodblock.github.client.gui.container.ContainerFluidCraftConfirm;
import com.glodblock.github.common.item.ItemWirelessUltraTerminal;
import com.glodblock.github.common.parts.PartFluidPatternTerminal;
import com.glodblock.github.common.parts.PartFluidPatternTerminalEx;
import com.glodblock.github.coremod.hooker.CoreModHooks;
import com.glodblock.github.inventory.gui.GuiType;
import com.glodblock.github.inventory.item.IWirelessTerminal;
import com.glodblock.github.inventory.item.WirelessPatternTerminalInventory;
import com.glodblock.github.network.CPacketFluidPatternTermBtns;
import com.glodblock.github.network.CPacketSwitchGuis;
import com.glodblock.github.util.ModAndClassUtil;
import com.google.common.base.Joiner;
public class GuiFluidCraftConfirm extends GuiCraftConfirm {
public class GuiFluidCraftConfirm extends AEBaseGui {
private final ContainerFluidCraftConfirm ccc;
private final int rows = 5;
private final IItemList<IAEItemStack> storage = AEApi.instance().storage().createItemList();
private final IItemList<IAEItemStack> pending = AEApi.instance().storage().createItemList();
private final IItemList<IAEItemStack> missing = AEApi.instance().storage().createItemList();
private final List<IAEItemStack> visual = new ArrayList<IAEItemStack>();
private GuiType OriginalGui;
private GuiButton cancel;
private GuiButton start;
private GuiButton selectCPU;
private int tooltip = -1;
private ItemStack hoveredStack;
public GuiFluidCraftConfirm(final InventoryPlayer inventoryPlayer, final ITerminalHost te) {
super(inventoryPlayer, te);
super(new ContainerFluidCraftConfirm(inventoryPlayer, te));
this.xSize = 238;
this.ySize = 206;
final GuiScrollbar scrollbar = new GuiScrollbar();
this.setScrollBar(scrollbar);
this.ccc = (ContainerFluidCraftConfirm) this.inventorySlots;
if (te instanceof PartFluidPatternTerminal) {
this.OriginalGui = GuiType.FLUID_PATTERN_TERMINAL;
} else if (te instanceof PartFluidPatternTerminalEx) {
@@ -33,8 +74,483 @@ public class GuiFluidCraftConfirm extends GuiCraftConfirm {
}
}
boolean isAutoStart() {
return ((ContainerFluidCraftConfirm) this.inventorySlots).isAutoStart();
}
@Override
public void switchToOriginalGUI() {
FluidCraft.proxy.netHandler.sendToServer(new CPacketSwitchGuis(this.OriginalGui));
public void initGui() {
super.initGui();
this.start = new GuiButton(
0,
this.guiLeft + 162,
this.guiTop + this.ySize - 25,
50,
20,
GuiText.Start.getLocal());
this.start.enabled = false;
this.buttonList.add(this.start);
this.selectCPU = new GuiButton(
0,
this.guiLeft + (219 - 180) / 2,
this.guiTop + this.ySize - 68,
180,
20,
GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic);
this.selectCPU.enabled = false;
this.buttonList.add(this.selectCPU);
if (this.OriginalGui != null) {
this.cancel = new GuiButton(
0,
this.guiLeft + 6,
this.guiTop + this.ySize - 25,
50,
20,
GuiText.Cancel.getLocal());
}
this.buttonList.add(this.cancel);
}
@Override
public void drawScreen(final int mouseX, final int mouseY, final float btn) {
this.updateCPUButtonText();
this.start.enabled = !(this.ccc.hasNoCPU() || this.isSimulation());
this.selectCPU.enabled = !this.isSimulation();
final int gx = (this.width - this.xSize) / 2;
final int gy = (this.height - this.ySize) / 2;
this.tooltip = -1;
final int offY = 23;
int y = 0;
int x = 0;
for (int z = 0; z <= 4 * 5; z++) {
final int minX = gx + 9 + x * 67;
final int minY = gy + 22 + y * offY;
if (minX < mouseX && minX + 67 > mouseX) {
if (minY < mouseY && minY + offY - 2 > mouseY) {
this.tooltip = z;
break;
}
}
x++;
if (x > 2) {
y++;
x = 0;
}
}
super.drawScreen(mouseX, mouseY, btn);
}
private void updateCPUButtonText() {
String btnTextText = GuiText.CraftingCPU.getLocal() + ": " + GuiText.Automatic.getLocal();
if (this.ccc.getSelectedCpu() >= 0) // && status.selectedCpu < status.cpus.size() )
{
if (this.ccc.getName().length() > 0) {
final String name = this.ccc.getName().substring(0, Math.min(20, this.ccc.getName().length()));
btnTextText = GuiText.CraftingCPU.getLocal() + ": " + name;
} else {
btnTextText = GuiText.CraftingCPU.getLocal() + ": #" + this.ccc.getSelectedCpu();
}
}
if (this.ccc.hasNoCPU()) {
btnTextText = GuiText.NoCraftingCPUs.getLocal();
}
this.selectCPU.displayString = btnTextText;
}
private boolean isSimulation() {
return ((ContainerFluidCraftConfirm) this.inventorySlots).isSimulation();
}
@Override
public void drawFG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) {
final long BytesUsed = this.ccc.getUsedBytes();
final String byteUsed = NumberFormat.getInstance().format(BytesUsed);
final String Add = BytesUsed > 0 ? (byteUsed + ' ' + GuiText.BytesUsed.getLocal())
: GuiText.CalculatingWait.getLocal();
this.fontRendererObj.drawString(GuiText.CraftingPlan.getLocal() + " - " + Add, 8, 7, 4210752);
String dsp = null;
if (this.isSimulation()) {
dsp = GuiText.Simulation.getLocal();
} else {
dsp = this.ccc.getCpuAvailableBytes() > 0
? (GuiText.Bytes.getLocal() + ": "
+ this.ccc.getCpuAvailableBytes()
+ " : "
+ GuiText.CoProcessors.getLocal()
+ ": "
+ this.ccc.getCpuCoProcessors())
: GuiText.Bytes.getLocal() + ": N/A : " + GuiText.CoProcessors.getLocal() + ": N/A";
}
final int offset = (219 - this.fontRendererObj.getStringWidth(dsp)) / 2;
this.fontRendererObj.drawString(dsp, offset, 165, 4210752);
final int sectionLength = 67;
int x = 0;
int y = 0;
final int xo = 9;
final int yo = 22;
final int viewStart = this.getScrollBar().getCurrentScroll() * 3;
final int viewEnd = viewStart + 3 * this.rows;
String dspToolTip = "";
final List<String> lineList = new LinkedList<String>();
int toolPosX = 0;
int toolPosY = 0;
hoveredStack = null;
final int offY = 23;
for (int z = viewStart; z < Math.min(viewEnd, this.visual.size()); z++) {
final IAEItemStack refStack = this.visual.get(z); // repo.getReferenceItem( z );
if (refStack != null) {
GL11.glPushMatrix();
GL11.glScaled(0.5, 0.5, 0.5);
final IAEItemStack stored = this.storage.findPrecise(refStack);
final IAEItemStack pendingStack = this.pending.findPrecise(refStack);
final IAEItemStack missingStack = this.missing.findPrecise(refStack);
int lines = 0;
if (stored != null && stored.getStackSize() > 0) {
lines++;
}
if (pendingStack != null && pendingStack.getStackSize() > 0) {
lines++;
}
if (pendingStack != null && pendingStack.getStackSize() > 0) {
lines++;
}
final int negY = ((lines - 1) * 5) / 2;
int downY = 0;
if (stored != null && stored.getStackSize() > 0) {
String str = Long.toString(stored.getStackSize());
if (stored.getStackSize() >= 10000) {
str = Long.toString(stored.getStackSize() / 1000) + 'k';
}
if (stored.getStackSize() >= 10000000) {
str = Long.toString(stored.getStackSize() / 1000000) + 'm';
}
str = GuiText.FromStorage.getLocal() + ": " + str;
final int w = 4 + this.fontRendererObj.getStringWidth(str);
this.fontRendererObj.drawString(
str,
(int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2),
(y * offY + yo + 6 - negY + downY) * 2,
4210752);
if (this.tooltip == z - viewStart) {
lineList.add(GuiText.FromStorage.getLocal() + ": " + stored.getStackSize());
}
downY += 5;
}
boolean red = false;
if (missingStack != null && missingStack.getStackSize() > 0) {
String str = Long.toString(missingStack.getStackSize());
if (missingStack.getStackSize() >= 10000) {
str = Long.toString(missingStack.getStackSize() / 1000) + 'k';
}
if (missingStack.getStackSize() >= 10000000) {
str = Long.toString(missingStack.getStackSize() / 1000000) + 'm';
}
str = GuiText.Missing.getLocal() + ": " + str;
final int w = 4 + this.fontRendererObj.getStringWidth(str);
this.fontRendererObj.drawString(
str,
(int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2),
(y * offY + yo + 6 - negY + downY) * 2,
4210752);
if (this.tooltip == z - viewStart) {
lineList.add(GuiText.Missing.getLocal() + ": " + missingStack.getStackSize());
}
red = true;
downY += 5;
}
if (pendingStack != null && pendingStack.getStackSize() > 0) {
String str = Long.toString(pendingStack.getStackSize());
if (pendingStack.getStackSize() >= 10000) {
str = Long.toString(pendingStack.getStackSize() / 1000) + 'k';
}
if (pendingStack.getStackSize() >= 10000000) {
str = Long.toString(pendingStack.getStackSize() / 1000000) + 'm';
}
str = GuiText.ToCraft.getLocal() + ": " + str;
final int w = 4 + this.fontRendererObj.getStringWidth(str);
this.fontRendererObj.drawString(
str,
(int) ((x * (1 + sectionLength) + xo + sectionLength - 19 - (w * 0.5)) * 2),
(y * offY + yo + 6 - negY + downY) * 2,
4210752);
if (this.tooltip == z - viewStart) {
lineList.add(GuiText.ToCraft.getLocal() + ": " + Long.toString(pendingStack.getStackSize()));
}
}
GL11.glPopMatrix();
final int posX = x * (1 + sectionLength) + xo + sectionLength - 19;
final int posY = y * offY + yo;
final ItemStack is = CoreModHooks.displayFluid(refStack.copy());
if (this.tooltip == z - viewStart) {
dspToolTip = Platform.getItemDisplayName(is);
if (lineList.size() > 0) {
addItemTooltip(is, lineList);
dspToolTip = dspToolTip + '\n' + Joiner.on("\n").join(lineList);
}
toolPosX = x * (1 + sectionLength) + xo + sectionLength - 8;
toolPosY = y * offY + yo;
hoveredStack = is;
}
this.drawItem(posX, posY, is);
if (red) {
final int startX = x * (1 + sectionLength) + xo;
final int startY = posY - 4;
drawRect(startX, startY, startX + sectionLength, startY + offY, 0x1AFF0000);
}
x++;
if (x > 2) {
y++;
x = 0;
}
}
}
if (this.tooltip >= 0 && dspToolTip.length() > 0) {
this.drawTooltip(toolPosX, toolPosY + 10, 0, dspToolTip);
}
}
@Override
public void drawBG(final int offsetX, final int offsetY, final int mouseX, final int mouseY) {
this.setScrollBar();
this.bindTexture("guis/craftingreport.png");
this.drawTexturedModalRect(offsetX, offsetY, 0, 0, this.xSize, this.ySize);
}
private void setScrollBar() {
final int size = this.visual.size();
this.getScrollBar().setTop(19).setLeft(218).setHeight(114);
this.getScrollBar().setRange(0, (size + 2) / 3 - this.rows, 1);
}
public void postUpdate(final List<IAEItemStack> list, final byte ref) {
switch (ref) {
case 0:
for (final IAEItemStack l : list) {
this.handleInput(this.storage, l);
}
break;
case 1:
for (final IAEItemStack l : list) {
this.handleInput(this.pending, l);
}
break;
case 2:
for (final IAEItemStack l : list) {
this.handleInput(this.missing, l);
}
break;
}
for (final IAEItemStack l : list) {
final long amt = this.getTotal(l);
if (amt <= 0) {
this.deleteVisualStack(l);
} else {
final IAEItemStack is = this.findVisualStack(l);
is.setStackSize(amt);
}
}
this.sortItems();
this.setScrollBar();
}
Comparator<IAEItemStack> comparator = (i1, i2) -> {
if (missing.findPrecise(i1) != null) {
if (missing.findPrecise(i2) != null) return 0;
return -1;
} else if (missing.findPrecise(i2) != null) {
return 1;
} else {
return 0;
}
};
private void sortItems() {
if (!this.missing.isEmpty()) {
this.visual.sort(comparator);
}
}
private void handleInput(final IItemList<IAEItemStack> s, final IAEItemStack l) {
IAEItemStack a = s.findPrecise(l);
if (l.getStackSize() <= 0) {
if (a != null) {
a.reset();
}
} else {
if (a == null) {
s.add(l.copy());
a = s.findPrecise(l);
}
if (a != null) {
a.setStackSize(l.getStackSize());
}
}
}
private long getTotal(final IAEItemStack is) {
final IAEItemStack a = this.storage.findPrecise(is);
final IAEItemStack c = this.pending.findPrecise(is);
final IAEItemStack m = this.missing.findPrecise(is);
long total = 0;
if (a != null) {
total += a.getStackSize();
}
if (c != null) {
total += c.getStackSize();
}
if (m != null) {
total += m.getStackSize();
}
return total;
}
private void deleteVisualStack(final IAEItemStack l) {
final Iterator<IAEItemStack> i = this.visual.iterator();
while (i.hasNext()) {
final IAEItemStack o = i.next();
if (o.equals(l)) {
i.remove();
return;
}
}
}
private IAEItemStack findVisualStack(final IAEItemStack l) {
for (final IAEItemStack o : this.visual) {
if (o.equals(l)) {
return o;
}
}
final IAEItemStack stack = l.copy();
this.visual.add(stack);
return stack;
}
@Override
protected void keyTyped(final char character, final int key) {
if (!this.checkHotbarKeys(key)) {
if (key == 28) {
this.actionPerformed(this.start);
}
super.keyTyped(character, key);
}
}
@Override
protected void actionPerformed(final GuiButton btn) {
super.actionPerformed(btn);
final boolean backwards = Mouse.isButtonDown(1);
if (btn == this.selectCPU) {
FluidCraft.proxy.netHandler
.sendToServer(new CPacketFluidPatternTermBtns("Terminal.Cpu", backwards ? "Prev" : "Next"));
}
if (btn == this.cancel) {
this.addMissingItemsToBookMark();
FluidCraft.proxy.netHandler.sendToServer(new CPacketSwitchGuis(this.OriginalGui));
}
if (btn == this.start) {
try {
FluidCraft.proxy.netHandler.sendToServer(new CPacketFluidPatternTermBtns("Terminal.Start", "Start"));
} catch (final Throwable e) {
AELog.debug(e);
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void addItemTooltip(ItemStack is, List<String> lineList) {
if (isShiftKeyDown()) {
List l = is.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips);
if (!l.isEmpty()) l.remove(0);
lineList.addAll(l);
} else if (ModAndClassUtil.isShiftTooltip) {
lineList.add(GuiText.HoldShiftForTooltip.getLocal());
}
}
public ItemStack getHoveredStack() {
return hoveredStack;
}
protected void addMissingItemsToBookMark() {
if (!this.missing.isEmpty() && isShiftKeyDown()) {
for (IAEItemStack iaeItemStack : this.missing) {
NEI.instance.addItemToBookMark(iaeItemStack.getItemStack());
}
}
}
public IItemList<IAEItemStack> getStorage() {
return this.storage;
}
public IItemList<IAEItemStack> getPending() {
return this.pending;
}
public IItemList<IAEItemStack> getMissing() {
return this.missing;
}
}
@@ -25,16 +25,13 @@ public class GuiFluidMonitor extends FCGuiMonitor<IAEFluidStack> {
this.repo = new FluidRepo(getScrollBar(), this);
}
@Override
public void postUpdate(final List<IAEFluidStack> list, boolean resort) {
public void postUpdate(final List<IAEFluidStack> list) {
for (final IAEFluidStack is : list) {
IAEItemStack stack = AEItemStack.create(ItemFluidDrop.newDisplayStack(is.getFluidStack()));
stack.setStackSize(is.getStackSize());
this.repo.postUpdate(stack);
}
if (resort) {
this.repo.updateView();
}
this.repo.updateView();
this.setScrollBar();
}
@@ -22,14 +22,11 @@ public class GuiItemMonitor extends FCGuiMonitor<IAEItemStack> {
this.repo = new ItemRepo(getScrollBar(), this);
}
@Override
public void postUpdate(final List<IAEItemStack> list, boolean resort) {
public void postUpdate(final List<IAEItemStack> list) {
for (final IAEItemStack is : list) {
this.repo.postUpdate(is);
}
if (resort) {
this.repo.updateView();
}
this.repo.updateView();
this.setScrollBar();
}
@@ -84,7 +84,6 @@ public abstract class FCGuiMonitor<T extends IAEStack<T>> extends FCBaseMEGui
protected GuiImgButton searchBoxSettings;
protected GuiImgButton terminalStyleBox;
protected GuiImgButton searchStringSave;
protected GuiImgButton typeFilter;
@SuppressWarnings("unchecked")
public FCGuiMonitor(final InventoryPlayer inventoryPlayer, final ITerminalHost te, final FCContainerMonitor<T> c) {
@@ -107,7 +106,7 @@ public abstract class FCGuiMonitor<T extends IAEStack<T>> extends FCBaseMEGui
offsetY = y;
}
public abstract void postUpdate(final List<T> list, boolean resort);
public abstract void postUpdate(final List<T> list);
protected void setScrollBar() {
this.getScrollBar().setTop(18).setLeft(175).setHeight(this.rows * 18 - 2);
@@ -229,15 +228,6 @@ public abstract class FCGuiMonitor<T extends IAEStack<T>> extends FCBaseMEGui
this.configSrc.getSetting(Settings.VIEW_MODE)));
this.offsetY += 20;
}
if (ModAndClassUtil.isTypeFilter && this instanceof GuiItemMonitor) {
this.buttonList.add(
this.typeFilter = new GuiImgButton(
this.guiLeft - 18,
this.offsetY,
Settings.TYPE_FILTER,
this.configSrc.getSetting(Settings.TYPE_FILTER)));
this.offsetY += 20;
}
this.buttonList.add(
this.SortDirBox = new GuiImgButton(
@@ -668,11 +658,6 @@ public abstract class FCGuiMonitor<T extends IAEStack<T>> extends FCBaseMEGui
return this.configSrc.getSetting(Settings.VIEW_MODE);
}
@Override
public Enum getTypeFilter() {
return this.configSrc.getSetting(Settings.TYPE_FILTER);
}
@Override
public void updateSetting(final IConfigManager manager, final Enum settingName, final Enum newValue) {
if (this.SortByBox != null) {
@@ -686,9 +671,6 @@ public abstract class FCGuiMonitor<T extends IAEStack<T>> extends FCBaseMEGui
if (this.ViewBox != null) {
this.ViewBox.set(this.configSrc.getSetting(Settings.VIEW_MODE));
}
if (this.typeFilter != null) {
this.typeFilter.set(this.configSrc.getSetting(Settings.TYPE_FILTER));
}
this.repo.updateView();
}
@@ -1,31 +1,269 @@
package com.glodblock.github.client.gui.container;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;
import java.util.concurrent.Future;
import javax.annotation.Nonnull;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.ICrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentText;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.SecurityPermissions;
import appeng.api.networking.IGrid;
import appeng.api.networking.crafting.ICraftingCPU;
import appeng.api.networking.crafting.ICraftingGrid;
import appeng.api.networking.crafting.ICraftingJob;
import appeng.api.networking.crafting.ICraftingLink;
import appeng.api.networking.security.BaseActionSource;
import appeng.api.networking.security.IActionHost;
import appeng.api.networking.security.PlayerSource;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.ITerminalHost;
import appeng.container.implementations.ContainerCraftConfirm;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.container.AEBaseContainer;
import appeng.container.guisync.GuiSync;
import appeng.container.implementations.CraftingCPURecord;
import appeng.core.AELog;
import appeng.util.Platform;
import com.glodblock.github.FluidCraft;
import com.glodblock.github.common.item.ItemBaseWirelessTerminal;
import com.glodblock.github.common.parts.PartFluidPatternTerminal;
import com.glodblock.github.common.parts.PartFluidPatternTerminalEx;
import com.glodblock.github.inventory.InventoryHandler;
import com.glodblock.github.inventory.gui.GuiType;
import com.glodblock.github.inventory.item.IWirelessTerminal;
import com.glodblock.github.network.SPacketMEInventoryUpdate;
import com.glodblock.github.util.Ae2Reflect;
import com.glodblock.github.util.BlockPos;
import com.google.common.collect.ImmutableSet;
public class ContainerFluidCraftConfirm extends ContainerCraftConfirm {
public class ContainerFluidCraftConfirm extends AEBaseContainer {
private final ArrayList<CraftingCPURecord> cpus = new ArrayList<CraftingCPURecord>();
private Future<ICraftingJob> job;
private ICraftingJob result;
@GuiSync(0)
public long bytesUsed;
@GuiSync(1)
public long cpuBytesAvail;
@GuiSync(2)
public int cpuCoProcessors;
@GuiSync(3)
public boolean autoStart = false;
@GuiSync(4)
public boolean simulation = true;
@GuiSync(5)
public int selectedCpu = -1;
@GuiSync(6)
public boolean noCPU = true;
@GuiSync(7)
public String myName = "";
public ContainerFluidCraftConfirm(final InventoryPlayer ip, final ITerminalHost te) {
super(ip, te);
}
public void cycleCpu(final boolean next) {
if (next) {
this.setSelectedCpu(this.getSelectedCpu() + 1);
} else {
this.setSelectedCpu(this.getSelectedCpu() - 1);
}
if (this.getSelectedCpu() < -1) {
this.setSelectedCpu(this.cpus.size() - 1);
} else if (this.getSelectedCpu() >= this.cpus.size()) {
this.setSelectedCpu(-1);
}
if (this.getSelectedCpu() == -1) {
this.setCpuAvailableBytes(0);
this.setCpuCoProcessors(0);
this.setName("");
} else {
this.setName(Ae2Reflect.getName(this.cpus.get(this.getSelectedCpu())));
this.setCpuAvailableBytes(Ae2Reflect.getSize(this.cpus.get(this.getSelectedCpu())));
this.setCpuCoProcessors(Ae2Reflect.getProcessors(this.cpus.get(this.getSelectedCpu())));
}
}
@Override
public void switchToOriginalGUI() {
public void detectAndSendChanges() {
if (Platform.isClient()) {
return;
}
if (getGrid() == null) return;
final ICraftingGrid cc = this.getGrid().getCache(ICraftingGrid.class);
final ImmutableSet<ICraftingCPU> cpuSet = cc.getCpus();
int matches = 0;
boolean changed = false;
for (final ICraftingCPU c : cpuSet) {
boolean found = false;
for (final CraftingCPURecord ccr : this.cpus) {
if (Ae2Reflect.getCPU(ccr) == c) {
found = true;
}
}
final boolean matched = this.cpuMatches(c);
if (matched) {
matches++;
}
if (found == !matched) {
changed = true;
}
}
if (changed || this.cpus.size() != matches) {
this.cpus.clear();
for (final ICraftingCPU c : cpuSet) {
if (this.cpuMatches(c)) {
this.cpus.add(new CraftingCPURecord(c.getAvailableStorage(), c.getCoProcessors(), c));
}
}
this.sendCPUs();
}
this.setNoCPU(this.cpus.isEmpty());
super.detectAndSendChanges();
if (this.getJob() != null && this.getJob().isDone()) {
try {
this.result = this.getJob().get();
if (!this.result.isSimulation()) {
this.setSimulation(false);
if (this.isAutoStart()) {
this.startJob();
return;
}
} else {
this.setSimulation(true);
}
final SPacketMEInventoryUpdate a = new SPacketMEInventoryUpdate((byte) 0);
final SPacketMEInventoryUpdate b = new SPacketMEInventoryUpdate((byte) 1);
final SPacketMEInventoryUpdate c = this.result.isSimulation() ? new SPacketMEInventoryUpdate((byte) 2)
: null;
final IItemList<IAEItemStack> plan = AEApi.instance().storage().createItemList();
this.result.populatePlan(plan);
this.setUsedBytes(this.result.getByteTotal());
for (final IAEItemStack out : plan) {
IAEItemStack o = out.copy();
o.reset();
o.setStackSize(out.getStackSize());
final IAEItemStack p = out.copy();
p.reset();
p.setStackSize(out.getCountRequestable());
final IStorageGrid sg = this.getGrid().getCache(IStorageGrid.class);
final IMEInventory<IAEItemStack> items = sg.getItemInventory();
IAEItemStack m = null;
if (c != null && this.result.isSimulation()) {
m = o.copy();
o = items.extractItems(o, Actionable.SIMULATE, this.getActionSource());
if (o == null) {
o = m.copy();
o.setStackSize(0);
}
m.setStackSize(m.getStackSize() - o.getStackSize());
}
if (o.getStackSize() > 0) {
a.appendItem(o);
}
if (p.getStackSize() > 0) {
b.appendItem(p);
}
if (c != null && m != null && m.getStackSize() > 0) {
c.appendItem(m);
}
}
for (final Object g : this.crafters) {
if (g instanceof EntityPlayer) {
FluidCraft.proxy.netHandler.sendTo(a, (EntityPlayerMP) g);
FluidCraft.proxy.netHandler.sendTo(b, (EntityPlayerMP) g);
if (c != null) {
FluidCraft.proxy.netHandler.sendTo(c, (EntityPlayerMP) g);
}
}
}
} catch (final Throwable e) {
this.getPlayerInv().player.addChatMessage(new ChatComponentText("Error: " + e.toString()));
AELog.debug(e);
this.setValidContainer(false);
this.result = null;
}
this.setJob(null);
}
this.verifyPermissions(SecurityPermissions.CRAFT, false);
}
private IGrid getGrid() {
final IActionHost h = ((IActionHost) this.getTarget());
if (h == null || h.getActionableNode() == null) return null;
return h.getActionableNode().getGrid();
}
private boolean cpuMatches(final ICraftingCPU c) {
return c.getAvailableStorage() >= this.getUsedBytes() && !c.isBusy();
}
private void sendCPUs() {
Collections.sort(this.cpus);
if (this.getSelectedCpu() >= this.cpus.size()) {
this.setSelectedCpu(-1);
this.setCpuAvailableBytes(0);
this.setCpuCoProcessors(0);
this.setName("");
} else if (this.getSelectedCpu() != -1) {
this.setName(Ae2Reflect.getName(this.cpus.get(this.getSelectedCpu())));
this.setCpuAvailableBytes(Ae2Reflect.getSize(this.cpus.get(this.getSelectedCpu())));
this.setCpuCoProcessors(Ae2Reflect.getProcessors(this.cpus.get(this.getSelectedCpu())));
}
}
public void startJob() {
GuiType originalGui = null;
final IActionHost ah = this.getActionHost();
@@ -41,20 +279,131 @@ public class ContainerFluidCraftConfirm extends ContainerCraftConfirm {
originalGui = ((ItemBaseWirelessTerminal) terminal.getItem()).guiGuiType(terminal);
}
}
if (ah instanceof IWirelessTerminal) {
InventoryHandler.openGui(
this.getInventoryPlayer().player,
getWorld(),
new BlockPos(((IWirelessTerminal) ah).getInventorySlot(), 0, 0),
ForgeDirection.UNKNOWN,
originalGui);
} else if (this.getOpenContext() != null) {
InventoryHandler.openGui(
this.getInventoryPlayer().player,
getWorld(),
new BlockPos(this.getOpenContext().getTile()),
Objects.requireNonNull(this.getOpenContext().getSide()),
originalGui);
if (this.result != null && !this.isSimulation() && getGrid() != null) {
final ICraftingGrid cc = this.getGrid().getCache(ICraftingGrid.class);
final ICraftingLink g = cc.submitJob(
this.result,
null,
this.getSelectedCpu() == -1 ? null : Ae2Reflect.getCPU(this.cpus.get(this.getSelectedCpu())),
true,
this.getActionSrc());
this.setAutoStart(false);
if (g != null && originalGui != null) {
if (ah instanceof IWirelessTerminal) {
InventoryHandler.openGui(
this.getInventoryPlayer().player,
getWorld(),
new BlockPos(((IWirelessTerminal) ah).getInventorySlot(), 0, 0),
ForgeDirection.UNKNOWN,
originalGui);
} else if (this.getOpenContext() != null) {
InventoryHandler.openGui(
this.getInventoryPlayer().player,
getWorld(),
new BlockPos(this.getOpenContext().getTile()),
Objects.requireNonNull(this.getOpenContext().getSide()),
originalGui);
}
}
}
}
private BaseActionSource getActionSrc() {
return new PlayerSource(this.getPlayerInv().player, (IActionHost) this.getTarget());
}
@Override
public void removeCraftingFromCrafters(final ICrafting c) {
super.removeCraftingFromCrafters(c);
if (this.getJob() != null) {
this.getJob().cancel(true);
this.setJob(null);
}
}
@Override
public void onContainerClosed(final EntityPlayer par1EntityPlayer) {
super.onContainerClosed(par1EntityPlayer);
if (this.getJob() != null) {
this.getJob().cancel(true);
this.setJob(null);
}
}
public World getWorld() {
return this.getPlayerInv().player.worldObj;
}
public boolean isAutoStart() {
return this.autoStart;
}
public void setAutoStart(final boolean autoStart) {
this.autoStart = autoStart;
}
public long getUsedBytes() {
return this.bytesUsed;
}
private void setUsedBytes(final long bytesUsed) {
this.bytesUsed = bytesUsed;
}
public long getCpuAvailableBytes() {
return this.cpuBytesAvail;
}
private void setCpuAvailableBytes(final long cpuBytesAvail) {
this.cpuBytesAvail = cpuBytesAvail;
}
public int getCpuCoProcessors() {
return this.cpuCoProcessors;
}
private void setCpuCoProcessors(final int cpuCoProcessors) {
this.cpuCoProcessors = cpuCoProcessors;
}
public int getSelectedCpu() {
return this.selectedCpu;
}
private void setSelectedCpu(final int selectedCpu) {
this.selectedCpu = selectedCpu;
}
public String getName() {
return this.myName;
}
private void setName(@Nonnull final String myName) {
this.myName = myName;
}
public boolean hasNoCPU() {
return this.noCPU;
}
private void setNoCPU(final boolean noCPU) {
this.noCPU = noCPU;
}
public boolean isSimulation() {
return this.simulation;
}
private void setSimulation(final boolean simulation) {
this.simulation = simulation;
}
private Future<ICraftingJob> getJob() {
return this.job;
}
public void setJob(final Future<ICraftingJob> job) {
this.job = job;
}
}
@@ -1,8 +1,7 @@
package com.glodblock.github.client.gui.container;
import java.util.ArrayList;
import java.nio.BufferOverflowException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.minecraft.entity.player.EntityPlayer;
@@ -15,8 +14,12 @@ import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.IFluidContainerItem;
import org.apache.commons.lang3.tuple.MutablePair;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.implementations.guiobjects.IPortableCell;
import appeng.api.implementations.tiles.IMEChest;
import appeng.api.implementations.tiles.IViewCellStorage;
import appeng.api.networking.IGrid;
import appeng.api.networking.IGridHost;
@@ -25,7 +28,6 @@ import appeng.api.networking.energy.IEnergyGrid;
import appeng.api.networking.energy.IEnergySource;
import appeng.api.networking.security.BaseActionSource;
import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.storage.ITerminalHost;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IItemList;
@@ -40,9 +42,10 @@ import appeng.util.item.AEItemStack;
import com.glodblock.github.FluidCraft;
import com.glodblock.github.client.gui.container.base.FCContainerMonitor;
import com.glodblock.github.common.item.ItemFluidDrop;
import com.glodblock.github.inventory.item.IFluidPortableCell;
import com.glodblock.github.network.CPacketFluidUpdate;
import com.glodblock.github.network.SPacketFluidUpdate;
import com.glodblock.github.network.SPacketMEUpdateBuffer;
import com.glodblock.github.network.SPacketMEInventoryUpdate;
import com.glodblock.github.util.Util;
public class ContainerFluidMonitor extends FCContainerMonitor<IAEFluidStack> {
@@ -58,28 +61,27 @@ public class ContainerFluidMonitor extends FCContainerMonitor<IAEFluidStack> {
super(ip, monitorable, bindInventory);
if (Platform.isServer()) {
this.serverCM = monitorable.getConfigManager();
if (monitorable instanceof IGridHost) {
final IGridNode node = ((IGridHost) monitorable).getGridNode(ForgeDirection.UNKNOWN);
if (node != null) {
this.networkNode = node;
final IGrid g = node.getGrid();
if (g != null) {
this.setPowerSource(new ChannelPowerSrc(this.networkNode, g.getCache(IEnergyGrid.class)));
IStorageGrid storageGrid = g.getCache(IStorageGrid.class);
this.monitor = storageGrid.getFluidInventory();
if (this.monitor == null) {
this.setValidContainer(false);
} else {
this.monitor.addListener(this, null);
this.monitor = monitorable.getFluidInventory();
if (this.monitor != null) {
this.monitor.addListener(this, null);
if (monitorable instanceof IFluidPortableCell) {
this.setPowerSource((IEnergySource) monitorable);
} else if (monitorable instanceof IPortableCell) {
this.setPowerSource((IEnergySource) monitorable);
} else if (monitorable instanceof IMEChest) {
this.setPowerSource((IEnergySource) monitorable);
} else if (monitorable instanceof IGridHost) {
final IGridNode node = ((IGridHost) monitorable).getGridNode(ForgeDirection.UNKNOWN);
if (node != null) {
this.networkNode = node;
final IGrid g = node.getGrid();
if (g != null) {
this.setPowerSource(new ChannelPowerSrc(this.networkNode, g.getCache(IEnergyGrid.class)));
}
}
} else {
this.setValidContainer(false);
}
} else {
this.monitor = monitorable.getFluidInventory();
this.monitor.addListener(this, null);
this.setPowerSource((IEnergySource) monitorable);
this.setValidContainer(false);
}
} else {
this.monitor = null;
@@ -125,34 +127,51 @@ public class ContainerFluidMonitor extends FCContainerMonitor<IAEFluidStack> {
protected void processItemList() {
if (!this.fluids.isEmpty()) {
final IItemList<IAEFluidStack> monitorCache = this.monitor.getStorageList();
List<IAEFluidStack> toSend = new ArrayList<>();
final SPacketMEInventoryUpdate piu = new SPacketMEInventoryUpdate(true);
for (final IAEFluidStack is : this.fluids) {
final IAEFluidStack send = monitorCache.findPrecise(is);
if (send != null) {
toSend.add(send);
} else {
if (send == null) {
is.setStackSize(0);
toSend.add(is);
piu.appendFluid(is);
} else {
piu.appendFluid(send);
}
}
for (final Object c : this.crafters) {
if (c instanceof EntityPlayerMP) {
SPacketMEUpdateBuffer.scheduleFluidUpdate((EntityPlayerMP) c, toSend);
if (!piu.isEmpty()) {
this.fluids.resetStatus();
for (final Object c : this.crafters) {
if (c instanceof EntityPlayer) {
FluidCraft.proxy.netHandler.sendTo(piu, (EntityPlayerMP) c);
}
}
}
this.fluids.resetStatus();
}
}
@Override
protected boolean isInvalid() {
return this.monitor != this.host.getFluidInventory();
}
@Override
protected void queueInventory(final ICrafting c) {
if (Platform.isServer() && c instanceof EntityPlayerMP && this.monitor != null) {
if (Platform.isServer() && c instanceof EntityPlayer && this.monitor != null) {
SPacketMEInventoryUpdate piu = new SPacketMEInventoryUpdate(true);
final IItemList<IAEFluidStack> monitorCache = this.monitor.getStorageList();
List<IAEFluidStack> toSend = new ArrayList<>();
for (final IAEFluidStack is : monitorCache) {
toSend.add(is);
for (final IAEFluidStack send : monitorCache) {
try {
piu.appendFluid(send);
} catch (final BufferOverflowException boe) {
FluidCraft.proxy.netHandler.sendTo(piu, (EntityPlayerMP) c);
piu = new SPacketMEInventoryUpdate(true);
piu.appendFluid(send);
}
}
SPacketMEUpdateBuffer.scheduleFluidUpdate((EntityPlayerMP) c, toSend);
FluidCraft.proxy.netHandler.sendTo(piu, (EntityPlayerMP) c);
}
}
@@ -192,275 +211,122 @@ public class ContainerFluidMonitor extends FCContainerMonitor<IAEFluidStack> {
this.dropItem(is);
}
/**
* Two operations, insert and extract.
*
* @param slotIndex The slot. If index == -1, the cursor held itemstack. Else, slotIndex indicates which slot was
* shift clicked on.
*/
public void postChange(Iterable<IAEFluidStack> change, ItemStack fluidContainer, EntityPlayer player,
int slotIndex) {
int cursorItems;
if (slotIndex == -1) {
cursorItems = player.inventory.getItemStack().stackSize;
} else {
cursorItems = player.inventory.getStackInSlot(slotIndex).stackSize;
}
for (IAEFluidStack fluid : change) {
// The primary output itemstack
IAEFluidStack nfluid = this.monitor.getStorageList().findPrecise(fluid);
ItemStack out = fluidContainer.copy();
out.stackSize = 1;
if (Util.FluidUtil.isEmpty(fluidContainer) && fluid != null) {
// Situation 1.a: Empty fluid container, and nonnull slot
extractFluid(fluid, fluidContainer, player, cursorItems);
// add fluid to tanks
if (nfluid.getStackSize() <= 0) continue;
final IAEFluidStack toExtract = nfluid.copy();
MutablePair<Integer, ItemStack> fillStack = Util.FluidUtil.fillStack(out, toExtract.getFluidStack());
if (fillStack.right == null || fillStack.left <= 0) continue;
toExtract.setStackSize((long) fillStack.left * fluidContainer.stackSize);
// The real result may don't match simulation result.
if (fillStack.right.getItem() instanceof IFluidContainerItem) {
IAEFluidStack real = this.host.getFluidInventory()
.extractItems(toExtract, Actionable.MODULATE, this.getActionSource());
if (real == null) continue;
// Refill the container
out = fluidContainer.copy();
out.stackSize = 1;
fillStack = Util.FluidUtil.fillStack(out, real.getFluidStack());
fillStack.right.stackSize = (int) (real.getStackSize() / fillStack.left);
out.stackSize = fillStack.right.stackSize;
if ((int) (real.getStackSize() % fillStack.left) > 0) {
this.dropItem(
Util.FluidUtil.setFluidContainerAmount(
fillStack.right,
(int) (real.getStackSize() % fillStack.left)),
1);
out.stackSize++;
}
} else if (FluidContainerRegistry.isContainer(fillStack.right)) {
IAEFluidStack real = this.host.getFluidInventory()
.extractItems(toExtract, Actionable.MODULATE, this.getActionSource());
if (real == null) continue;
// Refill the container
out = fluidContainer.copy();
out.stackSize = 1;
fillStack = Util.FluidUtil.fillStack(out, real.getFluidStack());
fillStack.right.stackSize = (int) (real.getStackSize() / fillStack.left);
out.stackSize = fillStack.right.stackSize;
toExtract.setStackSize((long) fillStack.right.stackSize * fillStack.left);
}
this.dropItem(fillStack.right);
} else if (!Util.FluidUtil.isEmpty(fluidContainer)) {
// Situation 2.a: We are holding a non-empty container.
insertFluid(fluidContainer, player, slotIndex, cursorItems);
// End of situation 2.a
// add fluid to ae network
AEFluidStack fluidStack = Util.getAEFluidFromItem(fluidContainer);
final IAEFluidStack aeFluidStack = fluidStack.copy();
// simulate result is incorrect. so I'm using other solution and ec2 both mod have same issues
final IAEFluidStack notInserted = this.host.getFluidInventory()
.injectItems(aeFluidStack, Actionable.MODULATE, this.getActionSource());
MutablePair<Integer, ItemStack> drainStack = Util.FluidUtil
.drainStack(out.copy(), aeFluidStack.getFluidStack());
if (notInserted != null && notInserted.getStackSize() > 0) {
if (fluidStack.getStackSize() == notInserted.getStackSize()) continue;
aeFluidStack.decStackSize(notInserted.getStackSize());
if (drainStack.left > aeFluidStack.getStackSize()
&& FluidContainerRegistry.isContainer(drainStack.right)) {
aeFluidStack.setStackSize(drainStack.left - aeFluidStack.getStackSize());
this.host.getFluidInventory()
.extractItems(aeFluidStack, Actionable.MODULATE, this.getActionSource());
continue;
}
this.dropItem(drainStack.right, (int) (aeFluidStack.getStackSize() / drainStack.left)); // drop
// empty
// item
out.stackSize = (int) (notInserted.getStackSize() / drainStack.left);
if (drainStack.right.getItem() instanceof IFluidContainerItem) {
if (notInserted.getStackSize() % drainStack.left > 0) {
fluidStack.setStackSize((notInserted.getStackSize() % drainStack.left));
((IFluidContainerItem) drainStack.right.getItem())
.fill(drainStack.right, fluidStack.getFluidStack(), true);
this.dropItem(drainStack.right, 1);
}
} else if (FluidContainerRegistry.isContainer(drainStack.right)) {
if (notInserted.getStackSize() % drainStack.left > 0) {
aeFluidStack.setStackSize(aeFluidStack.getStackSize() % drainStack.left);
this.host.getFluidInventory()
.extractItems(aeFluidStack, Actionable.MODULATE, this.getActionSource());
out.stackSize++;
}
}
if (slotIndex == -1) out.stackSize = fluidContainer.stackSize - out.stackSize;
} else {
if (slotIndex == -1) {
out.stackSize = fluidContainer.stackSize;
} else {
out.stackSize = (int) (fluidContainer.stackSize
- (aeFluidStack.getStackSize() / drainStack.left));
}
this.dropItem(drainStack.right, fluidContainer.stackSize); // drop empty item
}
} else {
continue;
}
if (slotIndex == -1) {
player.inventory.getItemStack().stackSize = player.inventory.getItemStack().stackSize - out.stackSize;
if (player.inventory.getItemStack().stackSize > 0) {
FluidCraft.proxy.netHandler.sendTo(
new SPacketFluidUpdate(new HashMap<>(), player.inventory.getItemStack()),
(EntityPlayerMP) player);
} else {
player.inventory.setItemStack(null);
FluidCraft.proxy.netHandler
.sendTo(new SPacketFluidUpdate(new HashMap<>()), (EntityPlayerMP) player);
}
} else {
player.inventory.setInventorySlotContents(slotIndex, out.stackSize > 0 ? out : null);
}
// No op (Any other situation)
}
this.detectAndSendChanges();
}
/**
* The insert operation. For input, we have an filled container stack. For outputs, we have the following: 1.
* Leftover filled container stack - primary output. 2. Empty containers 3. Partially filled container x1 In order
* above, the itemstack at `slotIndex` is transformed into the output.
*/
private void insertFluid(ItemStack fluidContainer, EntityPlayer player, int slotIndex, int heldContainers) {
IAEFluidStack fluid;
int fluidInTank;
if (fluidContainer.getItem() instanceof IFluidContainerItem) {
fluid = AEFluidStack.create(((IFluidContainerItem) fluidContainer.getItem()).getFluid(fluidContainer));
fluidInTank = (int) fluid.getStackSize();
} else if (FluidContainerRegistry.isContainer(fluidContainer)) {
fluid = AEFluidStack.create(FluidContainerRegistry.getFluidForFilledItem(fluidContainer));
fluidInTank = (int) fluid.getStackSize();
} else {
return;
}
// Simulate to know how much will not be inserted
long toInsert = (long) fluidInTank * fluidContainer.stackSize;
IAEFluidStack canSend = fluid.copy();
canSend.setStackSize(toInsert);
final IAEFluidStack notInserted = this.host.getFluidInventory()
.injectItems(canSend, Actionable.SIMULATE, this.getActionSource());
int emptyTanks = fluidContainer.stackSize;
ItemStack partialStack = fluidContainer.copy();
if (notInserted != null && notInserted.getStackSize() > 0) {
// Here, we cannot insert everything into the system.
if (canSend.getStackSize() == notInserted.getStackSize()) return; // System was full, no op
// Now "refill" the buckets that couldn't enter the system
int refilled = (int) (notInserted.getStackSize() / fluidInTank); // # of full tanks left
emptyTanks -= refilled;
toInsert -= (long) fluidInTank * refilled;
final int remainder = (int) (notInserted.getStackSize() % fluidInTank); // partial tank
// Now handle remaining if applicable
if (remainder > 0) {
notInserted.setStackSize(remainder);
partialStack.stackSize = 1;
if (partialStack.getItem() instanceof IFluidContainerItem) {
int filled = ((IFluidContainerItem) partialStack.getItem())
.fill(partialStack, notInserted.getFluidStack(), true);
toInsert -= filled;
assert filled == remainder;
emptyTanks--;
} else if (FluidContainerRegistry.isContainer(fluidContainer)) {
// For "whole containers" (need to round down, no remainders)
ItemStack container = FluidContainerRegistry
.fillFluidContainer(notInserted.getFluidStack(), fluidContainer);
if (container == null) {
// whatever, lets just not have the ME system get filled with any of its fluid
emptyTanks++;
toInsert -= remainder;
partialStack.stackSize = 0;
} else {
toInsert -= FluidContainerRegistry.getContainerCapacity(partialStack);
partialStack = container;
}
}
} else {
partialStack.stackSize = 0;
}
} else {
partialStack.stackSize = 0;
}
// Now that the 3 outputs are handled, we can now actually put the fluids in
canSend.setStackSize(toInsert);
IAEFluidStack extra = this.host.getFluidInventory()
.injectItems(canSend, Actionable.MODULATE, this.getActionSource());
assert extra == null || extra.getStackSize() <= 0;
ItemStack emptyStack = fluidContainer.copy();
emptyStack.stackSize = 1;
if (emptyStack.getItem() instanceof IFluidContainerItem) {
((IFluidContainerItem) emptyStack.getItem()).drain(emptyStack, fluidInTank, true);
} else {
emptyStack = FluidContainerRegistry.drainFluidContainer(emptyStack);
}
emptyStack.stackSize = emptyTanks;
int extraTanks = heldContainers - emptyTanks;
// Done. Put the output in the inventory or ground, and update stack size.
boolean shouldSendStack = true;
if (slotIndex == -1) {
if (extraTanks > 0) {
player.inventory.getItemStack().stackSize = extraTanks;
dropItem(emptyStack);
dropItem(partialStack);
} else if (emptyTanks != 0) {
player.inventory.setItemStack(emptyStack);
dropItem(partialStack);
} else if (partialStack.stackSize != 0) {
player.inventory.setItemStack(partialStack);
} else {
player.inventory.setItemStack(null);
shouldSendStack = false;
}
} else {
ItemStack extraTanksStack = player.inventory.getStackInSlot(slotIndex);
if (extraTanks > 0) {
if (extraTanks > extraTanksStack.getMaxStackSize()) {
dropItem(extraTanksStack, extraTanksStack.stackSize - extraTanksStack.getMaxStackSize());
extraTanksStack.stackSize = extraTanksStack.getMaxStackSize();
}
dropItem(emptyStack);
dropItem(partialStack);
} else if (emptyTanks != 0) {
if (emptyTanks > emptyStack.getMaxStackSize()) {
dropItem(emptyStack, emptyTanks - emptyStack.getMaxStackSize());
emptyStack.stackSize = emptyStack.getMaxStackSize();
}
player.inventory.setInventorySlotContents(slotIndex, emptyStack);
dropItem(partialStack);
} else if (partialStack.stackSize != 0) {
player.inventory.setInventorySlotContents(slotIndex, partialStack);
} else {
player.inventory.setItemStack(null);
shouldSendStack = false;
}
}
if (shouldSendStack) {
FluidCraft.proxy.netHandler.sendTo(
new SPacketFluidUpdate(new HashMap<>(), player.inventory.getItemStack()),
(EntityPlayerMP) player);
} else {
FluidCraft.proxy.netHandler.sendTo(new SPacketFluidUpdate(new HashMap<>()), (EntityPlayerMP) player);
}
}
/**
* The extract operation. For input, we have an empty container stack. For outputs, we have the following: 1.
* Leftover empty container stack - primary output. 2. Filled containers (full) 3. Partially filled container x1 In
* order above, the itemstack at `slotIndex` is transformed into the output.
*/
private void extractFluid(IAEFluidStack fluid, ItemStack fluidContainer, EntityPlayer player, int heldContainers) {
IAEFluidStack storedFluid = this.monitor.getStorageList().findPrecise(fluid);
if (storedFluid == null || storedFluid.getStackSize() <= 0) return;
int capacity;
if (fluidContainer.getItem() instanceof IFluidContainerItem) {
capacity = ((IFluidContainerItem) fluidContainer.getItem()).getCapacity(fluidContainer);
} else if (FluidContainerRegistry.isContainer(fluidContainer)) {
// Fill with fluid container registry, or abort if it failed
ItemStack dummy = FluidContainerRegistry.fillFluidContainer(storedFluid.getFluidStack(), fluidContainer);
capacity = FluidContainerRegistry.getContainerCapacity(dummy);
} else {
return;
}
if (capacity == 0) return;
// The fluidstack that we will try to extract from the system.
final IAEFluidStack canExtract = storedFluid.copy();
// Maximum amount of fluid we can extract with the given container(s). Guarantees that we won't
// run into issues w/ remainder fluid later.
canExtract.setStackSize((long) capacity * fluidContainer.stackSize);
IAEFluidStack actualExtract = this.host.getFluidInventory()
.extractItems(canExtract, Actionable.SIMULATE, this.getActionSource());
if (actualExtract == null) return;
// Calculate the number of full fluid containers we extracted
long toExtract = actualExtract.getStackSize();
int filledTanks = (int) (toExtract / capacity);
int remainder = (int) (toExtract % capacity);
int emptyTanks = heldContainers - filledTanks;
// Fill the filled tanks
ItemStack filledStack = fluidContainer.copy();
filledStack.stackSize = 1;
if (filledTanks > 0) {
if (filledStack.getItem() instanceof IFluidContainerItem) {
int amt = ((IFluidContainerItem) filledStack.getItem())
.fill(filledStack, actualExtract.getFluidStack(), true);
assert amt == capacity;
} else {
// Should not be NPE since we affirmed that we have enough capacity.
filledStack = FluidContainerRegistry.fillFluidContainer(actualExtract.getFluidStack(), filledStack);
assert capacity == FluidContainerRegistry.getContainerCapacity(filledStack);
}
filledStack.stackSize = filledTanks;
} else {
filledStack.stackSize = 0;
}
// Calculate the remaining fluid to extract, if any
ItemStack partialStack = fluidContainer.copy();
if (remainder > 0) {
actualExtract.setStackSize(remainder);
partialStack.stackSize = 1;
if (partialStack.getItem() instanceof IFluidContainerItem) {
int amt = ((IFluidContainerItem) partialStack.getItem())
.fill(partialStack, actualExtract.getFluidStack(), true);
assert amt == remainder;
emptyTanks--;
} else {
ItemStack dummy = FluidContainerRegistry
.fillFluidContainer(actualExtract.getFluidStack(), partialStack);
if (dummy == null) {
// Failed to fill partial...
partialStack.stackSize = 0;
toExtract -= remainder;
} else {
partialStack = dummy;
toExtract -= FluidContainerRegistry.getContainerCapacity(partialStack);
emptyTanks--;
}
}
} else {
partialStack.stackSize = 0;
}
// Now perform the real extraction.
actualExtract.setStackSize(toExtract);
this.host.getFluidInventory().extractItems(canExtract, Actionable.MODULATE, this.getActionSource());
// Done. Put the output in the inventory or ground, and update stack size.
// We can assume slotIndex == -1, since we don't actually allow extraction via shift click.
boolean shouldSendStack = true;
if (emptyTanks > 0) {
ItemStack emptyStack = player.inventory.getItemStack();
if (emptyTanks > emptyStack.stackSize) {
dropItem(emptyStack, emptyStack.stackSize - emptyStack.getMaxStackSize());
emptyStack.stackSize = emptyStack.getMaxStackSize();
}
dropItem(filledStack);
dropItem(partialStack);
} else if (filledStack.stackSize != 0) {
if (filledStack.stackSize > filledStack.getMaxStackSize()) {
dropItem(filledStack, filledStack.stackSize - filledStack.getMaxStackSize());
filledStack.stackSize = filledStack.getMaxStackSize();
}
player.inventory.setItemStack(filledStack);
dropItem(partialStack);
} else if (partialStack.stackSize != 0) {
player.inventory.setItemStack(partialStack);
} else {
player.inventory.setItemStack(null);
shouldSendStack = false;
}
if (shouldSendStack) {
FluidCraft.proxy.netHandler.sendTo(
new SPacketFluidUpdate(new HashMap<>(), player.inventory.getItemStack()),
(EntityPlayerMP) player);
} else {
FluidCraft.proxy.netHandler.sendTo(new SPacketFluidUpdate(new HashMap<>()), (EntityPlayerMP) player);
}
}
protected boolean isEssentiaMode() {
return false;
}
@@ -1,7 +1,6 @@
package com.glodblock.github.client.gui.container;
import java.util.ArrayList;
import java.util.List;
import java.nio.BufferOverflowException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -10,6 +9,8 @@ import net.minecraft.inventory.ICrafting;
import net.minecraftforge.common.util.ForgeDirection;
import appeng.api.AEApi;
import appeng.api.implementations.guiobjects.IPortableCell;
import appeng.api.implementations.tiles.IMEChest;
import appeng.api.implementations.tiles.IViewCellStorage;
import appeng.api.networking.IGrid;
import appeng.api.networking.IGridHost;
@@ -18,7 +19,6 @@ import appeng.api.networking.energy.IEnergyGrid;
import appeng.api.networking.energy.IEnergySource;
import appeng.api.networking.security.BaseActionSource;
import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.storage.ITerminalHost;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
@@ -26,8 +26,9 @@ import appeng.container.slot.SlotRestrictedInput;
import appeng.me.helpers.ChannelPowerSrc;
import appeng.util.Platform;
import com.glodblock.github.FluidCraft;
import com.glodblock.github.client.gui.container.base.FCContainerMonitor;
import com.glodblock.github.network.SPacketMEUpdateBuffer;
import com.glodblock.github.network.SPacketMEInventoryUpdate;
public class ContainerItemMonitor extends FCContainerMonitor<IAEItemStack> {
@@ -42,30 +43,26 @@ public class ContainerItemMonitor extends FCContainerMonitor<IAEItemStack> {
super(ip, monitorable, bindInventory);
if (Platform.isServer()) {
this.serverCM = monitorable.getConfigManager();
if (monitorable instanceof IGridHost) {
final IGridNode node = ((IGridHost) monitorable).getGridNode(ForgeDirection.UNKNOWN);
if (node != null) {
this.networkNode = node;
final IGrid g = node.getGrid();
if (g != null) {
this.setPowerSource(new ChannelPowerSrc(this.networkNode, g.getCache(IEnergyGrid.class)));
IStorageGrid storageGrid = g.getCache(IStorageGrid.class);
this.monitor = storageGrid.getItemInventory();
if (this.monitor == null) {
this.setValidContainer(false);
} else {
this.monitor.addListener(this, null);
this.setCellInventory(this.monitor);
}
}
} else {
this.setValidContainer(false);
}
} else {
this.monitor = monitorable.getItemInventory();
this.monitor = monitorable.getItemInventory();
if (this.monitor != null) {
this.monitor.addListener(this, null);
this.setCellInventory(this.monitor);
this.setPowerSource((IEnergySource) monitorable);
if (monitorable instanceof IPortableCell) {
this.setPowerSource((IEnergySource) monitorable);
} else if (monitorable instanceof IMEChest) {
this.setPowerSource((IEnergySource) monitorable);
} else if (monitorable instanceof IGridHost) {
final IGridNode node = ((IGridHost) monitorable).getGridNode(ForgeDirection.UNKNOWN);
if (node != null) {
this.networkNode = node;
final IGrid g = node.getGrid();
if (g != null) {
this.setPowerSource(new ChannelPowerSrc(this.networkNode, g.getCache(IEnergyGrid.class)));
}
}
}
} else {
this.setValidContainer(false);
}
} else {
this.monitor = null;
@@ -95,34 +92,46 @@ public class ContainerItemMonitor extends FCContainerMonitor<IAEItemStack> {
protected void processItemList() {
if (!this.items.isEmpty()) {
final IItemList<IAEItemStack> monitorCache = this.monitor.getStorageList();
List<IAEItemStack> toSend = new ArrayList<>();
final SPacketMEInventoryUpdate piu = new SPacketMEInventoryUpdate();
for (final IAEItemStack is : this.items) {
final IAEItemStack send = monitorCache.findPrecise(is);
if (send != null) {
toSend.add(send);
} else {
if (send == null) {
is.setStackSize(0);
toSend.add(is);
piu.appendItem(is);
} else {
piu.appendItem(send);
}
}
for (final Object c : this.crafters) {
if (c instanceof EntityPlayer) {
SPacketMEUpdateBuffer.scheduleItemUpdate((EntityPlayerMP) c, toSend);
if (!piu.isEmpty()) {
this.items.resetStatus();
for (final Object c : this.crafters) {
if (c instanceof EntityPlayer) {
FluidCraft.proxy.netHandler.sendTo(piu, (EntityPlayerMP) c);
}
}
}
this.items.resetStatus();
}
}
@Override
protected void queueInventory(final ICrafting c) {
if (Platform.isServer() && c instanceof EntityPlayer && this.monitor != null) {
SPacketMEInventoryUpdate piu = new SPacketMEInventoryUpdate();
final IItemList<IAEItemStack> monitorCache = this.monitor.getStorageList();
List<IAEItemStack> toSend = new ArrayList<>();
for (final IAEItemStack is : monitorCache) {
toSend.add(is);
for (final IAEItemStack send : monitorCache) {
try {
piu.appendItem(send);
} catch (final BufferOverflowException boe) {
FluidCraft.proxy.netHandler.sendTo(piu, (EntityPlayerMP) c);
piu = new SPacketMEInventoryUpdate();
piu.appendItem(send);
}
}
SPacketMEUpdateBuffer.scheduleItemUpdate((EntityPlayerMP) c, toSend);
FluidCraft.proxy.netHandler.sendTo(piu, (EntityPlayerMP) c);
}
}
@@ -131,9 +140,6 @@ public class ContainerItemMonitor extends FCContainerMonitor<IAEItemStack> {
super.removeCraftingFromCrafters(c);
if (this.crafters.isEmpty() && this.monitor != null) {
this.monitor.removeListener(this);
if (c instanceof EntityPlayerMP) {
SPacketMEUpdateBuffer.clear((EntityPlayerMP) c);
}
}
}
@@ -30,7 +30,6 @@ import appeng.util.IConfigManagerHost;
import appeng.util.Platform;
import com.glodblock.github.inventory.item.IWirelessTerminal;
import com.glodblock.github.network.SPacketMEUpdateBuffer;
public abstract class FCContainerMonitor<T extends IAEStack<T>> extends FCBaseContainer
implements IConfigManagerHost, IConfigurableObject, IMEMonitorHandlerReceiver<T> {
@@ -62,11 +61,6 @@ public abstract class FCContainerMonitor<T extends IAEStack<T>> extends FCBaseCo
this.clientCM.registerSetting(Settings.SORT_BY, SortOrder.NAME);
this.clientCM.registerSetting(Settings.VIEW_MODE, ViewItems.ALL);
this.clientCM.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING);
this.clientCM.registerSetting(Settings.TYPE_FILTER, TypeFilter.ALL);
}
public IMEMonitor<T> getMonitor() {
return this.monitor;
}
public IGridNode getNetworkNode() {
@@ -118,7 +112,7 @@ public abstract class FCContainerMonitor<T extends IAEStack<T>> extends FCBaseCo
protected abstract void processItemList();
protected boolean isInvalid() {
return this.monitor == null;
return this.monitor != this.host.getItemInventory();
}
protected void updatePowerStatus() {
@@ -159,10 +153,6 @@ public abstract class FCContainerMonitor<T extends IAEStack<T>> extends FCBaseCo
super.onContainerClosed(player);
if (this.monitor != null) {
this.monitor.removeListener(this);
if (player instanceof EntityPlayerMP && Platform.isServer()) {
SPacketMEUpdateBuffer.clear((EntityPlayerMP) player);
}
}
}
@@ -17,8 +17,6 @@ public class Config {
public static boolean removeRecipe;
public static boolean blacklistEssentiaGas;
public static double portableCellBattery;
public static int packetSize;
public static int packetRate;
public static void run() {
loadCategory();
@@ -53,13 +51,7 @@ public class Config {
"Blacklist Essentia Gas from Thaumic Energistics, so they won't be stored in Fluid Storage Cells.");
portableCellBattery = Config.get("Fluid Craft for AE2", "Portable Fluid Cell Battery Capacity", 20000D)
.getDouble();
packetSize = Config.get("Fluid Craft for AE2", "packetSize", 256, "Number of items to be sent per packet")
.getInt();
if (packetSize <= 0) packetSize = 256;
packetRate = Config
.get("Fluid Craft for AE2", "packetRate", 50, "Period at which packets are dispatched, in ms.")
.getInt();
if (packetRate <= 0) packetRate = 50;
if (Config.hasChanged()) Config.save();
}
@@ -37,10 +37,6 @@ public class ItemFluidDrop extends FCBaseItem {
@SideOnly(Side.CLIENT)
public IIcon shape;
public ItemFluidDrop() {
setUnlocalizedName(NameConst.ITEM_FLUID_DROP);
}
@Override
@SuppressWarnings("unchecked")
@SideOnly(Side.CLIENT)
@@ -51,12 +47,6 @@ public class ItemFluidDrop extends FCBaseItem {
}
}
@Override
public String getUnlocalizedName(ItemStack stack) {
FluidStack fluid = getFluidStack(stack);
return fluid != null ? fluid.getUnlocalizedName() : getUnlocalizedName();
}
@Override
public String getItemStackDisplayName(ItemStack stack) {
FluidStack fluid = getFluidStack(stack);
@@ -44,12 +44,6 @@ public class ItemFluidPacket extends FCBaseItem {
return (fluid != null && fluid.amount > 0) ? fluid : null;
}
@Override
public String getUnlocalizedName(ItemStack stack) {
FluidStack fluid = getFluidStack(stack);
return fluid != null ? fluid.getUnlocalizedName() : getUnlocalizedName();
}
@Override
public String getItemStackDisplayName(ItemStack stack) {
FluidStack fluid = getFluidStack(stack);
@@ -137,9 +137,8 @@ public class PartFluidExportBus extends FCSharedFluidBus implements ICraftingReq
this.source);
}
int space = fh.fill(this.getSide().getOpposite(), toExtract.getFluidStack(), false);
toExtract.setStackSize(space);
final IAEFluidStack real = inv.extractItems(toExtract, Actionable.MODULATE, this.source);
if (real != null && isAllowed) {
int realInserted = fh.fill(this.getSide().getOpposite(), real.getFluidStack(), true);
if (realInserted < real.getStackSize()) {
@@ -82,7 +82,6 @@ public abstract class FCPart extends AEBasePart
this.cm.registerSetting(Settings.SORT_BY, SortOrder.NAME);
this.cm.registerSetting(Settings.VIEW_MODE, ViewItems.ALL);
this.cm.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING);
this.cm.registerSetting(Settings.TYPE_FILTER, TypeFilter.ALL);
}
@MENetworkEventSubscribe
@@ -35,7 +35,6 @@ import appeng.client.texture.CableBusTextures;
import appeng.core.AELog;
import appeng.core.localization.PlayerMessages;
import appeng.helpers.Reflected;
import appeng.hooks.TickHandler;
import appeng.me.GridAccessException;
import appeng.parts.reporting.AbstractPartDisplay;
import appeng.parts.reporting.PartPanel;
@@ -200,7 +199,7 @@ public abstract class FCPartMonitor extends AbstractPartDisplay implements IPart
super.finalize();
if (this.dspList != null) {
TickHandler.INSTANCE.scheduleCallListDelete(this.dspList);
GLAllocation.deleteDisplayLists(this.dspList);
}
}
@@ -1,17 +1,14 @@
package com.glodblock.github.common.tile;
import net.minecraft.block.Block;
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;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.*;
import com.glodblock.github.loader.ChannelLoader;
import com.glodblock.github.util.BlockPos;
public class TileCertusQuartzTank extends TileEntity implements IFluidHandler {
@@ -29,7 +26,6 @@ public class TileCertusQuartzTank extends TileEntity implements IFluidHandler {
return this;
}
};
private boolean hasUpdate;
@Override
public boolean canDrain(ForgeDirection from, Fluid fluid) {
@@ -195,40 +191,6 @@ public class TileCertusQuartzTank extends TileEntity implements IFluidHandler {
return (float) this.tank.getFluidAmount() / this.tank.getCapacity();
}
private void onComparatorUpdate(World world, int x, int y, int z, Block block) {
world.func_147453_f(x, y, z, block);
}
@Override
public void updateEntity() {
super.updateEntity();
if (this.tank.getFluid() != null) {
TileCertusQuartzTank below = getTankBelow(this);
if (below != null) {
FluidStack filled = this.tank.getFluid().copy();
filled.amount = below.fill(this.tank.getFluid(), true, true);
if (filled.amount >= 0) {
this.drain(filled, true, true);
this.hasUpdate = true;
below.hasUpdate = true;
}
}
}
if (this.hasUpdate) {
onComparatorUpdate(this.worldObj, this.xCoord, this.yCoord, this.zCoord, this.getBlockType());
this.hasUpdate = false;
}
}
private TileCertusQuartzTank getTankBelow(TileEntity tile) {
TileEntity tank = new BlockPos(tile).getOffSet(0, -1, 0).getTileEntity();
if (tank != null && tank instanceof TileCertusQuartzTank) {
return (TileCertusQuartzTank) tank;
}
return null;
}
public FluidTankInfo[] getTankInfo(boolean goToMainTank) {
if (!goToMainTank) return new FluidTankInfo[] { this.tank.getInfo() };
@@ -250,12 +212,12 @@ public class TileCertusQuartzTank extends TileEntity implements IFluidHandler {
break;
}
yOff -= 1;
offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord - yOff, this.zCoord);
yOff = 0;
offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + yOff, this.zCoord);
while (true) {
if (offTE instanceof TileCertusQuartzTank) {
mainTank = (TileCertusQuartzTank) offTE;
if (mainTank.getFluid() == null || getFluid() == null || mainTank.getFluid() == getFluid()) {
if (mainTank.getFluid() == null || mainTank.getFluid() == getFluid()) {
FluidTankInfo info = mainTank.getTankInfo(false)[0];
if (info != null) {
capacity += info.capacity;
@@ -264,7 +226,8 @@ public class TileCertusQuartzTank extends TileEntity implements IFluidHandler {
if (info.fluid.getFluid() != null) fluid = info.fluid.getFluid();
}
}
offTE = new BlockPos(offTE).getOffSet(0, 1, 0).getTileEntity();
yOff++;
offTE = this.worldObj.getTileEntity(this.xCoord, this.yCoord + yOff, this.zCoord);
continue;
}
}
@@ -311,8 +274,4 @@ public class TileCertusQuartzTank extends TileEntity implements IFluidHandler {
public void writeToNBTWithoutCoords(NBTTagCompound tag) {
this.tank.writeToNBT(tag);
}
public FluidTankInfo[] getInternalFluid() {
return this.getTankInfo(true);
}
}
@@ -182,7 +182,6 @@ public class TileFluidPacketDecoder extends AENetworkTile
ItemStack fluidPacket = this.inventory.getStackInSlot(0);
if (fluidPacket != null) {
FluidStack fs = ItemFluidPacket.getFluidStack(fluidPacket);
if (fs == null) return null;
if (fs.isFluidEqual(requestFluid)) {
if (fs.amount > requestFluid.amount) {
fs.amount -= requestFluid.amount;
@@ -202,7 +201,6 @@ public class TileFluidPacketDecoder extends AENetworkTile
ItemStack fluidPacket = this.inventory.getStackInSlot(0);
if (fluidPacket != null) {
FluidStack requestFluid = ItemFluidPacket.getFluidStack(fluidPacket);
if (requestFluid == null) return null;
requestFluid.amount = maxDrain;
return this.drain(requestFluid, doDrain);
}
@@ -226,7 +224,6 @@ public class TileFluidPacketDecoder extends AENetworkTile
return new FluidTankInfo[0];
} else {
FluidStack fs = ItemFluidPacket.getFluidStack(fluidPacket);
if (fs == null) return new FluidTankInfo[0];
return new FluidTankInfo[] { new FluidTankInfo(fs, fs.amount) };
}
}
@@ -15,14 +15,6 @@ public class Tooltip {
return String.format("%s: %s mB", name, NumberFormat.getInstance().format(amount));
}
public static String fluidFormat(String name, long amount, long capacity) {
return String.format(
"%s: %s mB / %s mB",
name,
NumberFormat.getInstance().format(amount),
NumberFormat.getInstance().format(capacity));
}
public static String partFluidBusFormat(int amount) {
return String
.format("%s: %s mB/t", I18n.format(NameConst.WAILA_SPEED), NumberFormat.getInstance().format(amount));
@@ -10,13 +10,14 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import appeng.integration.modules.waila.BaseWailaDataProvider;
import com.glodblock.github.common.tile.TileCertusQuartzTank;
import com.glodblock.github.crossmod.waila.Tooltip;
import com.glodblock.github.util.Util;
public class FluidInvWailaDataProvider extends BaseWailaDataProvider {
@@ -25,13 +26,9 @@ public class FluidInvWailaDataProvider extends BaseWailaDataProvider {
final IWailaDataAccessor accessor, final IWailaConfigHandler config) {
final TileEntity te = accessor.getTileEntity();
if (te instanceof TileCertusQuartzTank) {
if (accessor.getNBTData().hasKey("fluidInv")) {
NBTTagCompound data = (NBTTagCompound) accessor.getNBTData().getTag("fluidInv");
for (FluidTankInfo info : Util.FluidUtil.fluidTankInfoReadFromNBT(data)) {
if (info.fluid == null) continue;
currentToolTip
.add(Tooltip.fluidFormat(info.fluid.getLocalizedName(), info.fluid.amount, info.capacity));
}
for (FluidTankInfo info : ((IFluidHandler) te).getTankInfo(ForgeDirection.UNKNOWN)) {
if (info.fluid == null) continue;
currentToolTip.add(Tooltip.fluidFormat(info.fluid.getLocalizedName(), info.fluid.amount));
}
}
return currentToolTip;
@@ -41,9 +38,6 @@ public class FluidInvWailaDataProvider extends BaseWailaDataProvider {
public NBTTagCompound getNBTData(final EntityPlayerMP player, final TileEntity te, final NBTTagCompound tag,
final World world, final int x, final int y, final int z) {
if (te instanceof TileCertusQuartzTank) {
NBTTagCompound data = new NBTTagCompound();
Util.FluidUtil.fluidTankInfoWriteToNBT(((TileCertusQuartzTank) te).getInternalFluid(), data);
tag.setTag("fluidInv", data);
te.writeToNBT(tag);
}
return tag;
@@ -95,7 +95,6 @@ public class WirelessCraftingTerminalInventory extends MEMonitorHandler<IAEItemS
out.registerSetting(Settings.SORT_BY, SortOrder.NAME);
out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL);
out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING);
out.registerSetting(Settings.TYPE_FILTER, TypeFilter.ALL);
out.readFromNBT((NBTTagCompound) Platform.openNbtData(this.target).copy());
return out;
}
@@ -135,7 +135,6 @@ public class WirelessPatternTerminalExInventory extends MEMonitorHandler<IAEItem
out.registerSetting(Settings.SORT_BY, SortOrder.NAME);
out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL);
out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING);
out.registerSetting(Settings.TYPE_FILTER, TypeFilter.ALL);
out.readFromNBT((NBTTagCompound) Platform.openNbtData(this.target).copy());
this.readFromNBT();
return out;
@@ -133,7 +133,6 @@ public class WirelessPatternTerminalInventory extends MEMonitorHandler<IAEItemSt
out.registerSetting(Settings.SORT_BY, SortOrder.NAME);
out.registerSetting(Settings.VIEW_MODE, ViewItems.ALL);
out.registerSetting(Settings.SORT_DIRECTION, SortDir.ASCENDING);
out.registerSetting(Settings.TYPE_FILTER, TypeFilter.ALL);
out.readFromNBT((NBTTagCompound) Platform.openNbtData(this.target).copy());
this.readFromNBT();
return out;
@@ -25,11 +25,9 @@ public class ChannelLoader implements Runnable {
Side.SERVER);
FluidCraft.proxy.netHandler
.registerMessage(new CPacketEncodePattern.Handler(), CPacketEncodePattern.class, id++, Side.SERVER);
FluidCraft.proxy.netHandler
.registerMessage(new SPacketMEItemInvUpdate.Handler(), SPacketMEItemInvUpdate.class, id++, Side.CLIENT);
FluidCraft.proxy.netHandler.registerMessage(
new SPacketMEFluidInvUpdate.Handler(),
SPacketMEFluidInvUpdate.class,
new SPacketMEInventoryUpdate.Handler(),
SPacketMEInventoryUpdate.class,
id++,
Side.CLIENT);
FluidCraft.proxy.netHandler
@@ -1,35 +0,0 @@
package com.glodblock.github.loader.filter;
import static appeng.api.config.TypeFilter.*;
import net.minecraft.item.Item;
import appeng.api.config.TypeFilter;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.client.me.ItemRepo;
import com.glodblock.github.common.item.ItemFluidDrop;
public class FluidFilter {
public static void installFilter() {
ItemRepo.registerTypeHandler(FluidFilter::filter, FLUIDS);
}
private static boolean filter(IAEStack<?> stack, TypeFilter typeFilter) {
if (typeFilter == ALL) return true;
if (stack instanceof IAEItemStack) {
Item item = ((IAEItemStack) stack).getItem();
if (item != null) {
switch (typeFilter) {
case ITEMS:
return !(item instanceof ItemFluidDrop);
case FLUIDS:
return item instanceof ItemFluidDrop;
}
}
}
return true;
}
}
@@ -1,7 +1,9 @@
package com.glodblock.github.nei;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import net.minecraft.item.ItemStack;
@@ -41,11 +43,24 @@ public class NEIUtils {
}
public static List<OrderStack<?>> clearNull(List<OrderStack<?>> list) {
AtomicInteger i = new AtomicInteger(0);
return list.stream().filter(Objects::nonNull)
.filter(
orderStack -> !(orderStack.getStack() != null && orderStack.getStack() instanceof ItemStack
&& ((ItemStack) orderStack.getStack()).stackSize == 0))
.peek(orderStack -> orderStack.setIndex(i.getAndIncrement())).collect(Collectors.toList());
List<OrderStack<?>> cleared = new LinkedList<>();
HashMap<Integer, Object> map = new HashMap<>();
int upper = 0;
for (OrderStack<?> orderStack : list) {
if (orderStack != null && orderStack.getStack() != null) {
if (orderStack.getStack() instanceof ItemStack && ((ItemStack) orderStack.getStack()).stackSize == 0)
continue;
map.put(orderStack.getIndex(), orderStack.getStack());
upper = Math.max(upper, orderStack.getIndex());
}
}
int id = 0;
for (int i = 0; i <= upper; i++) {
if (map.containsKey(i)) {
cleared.add(new OrderStack<>(map.get(i), id));
id++;
}
}
return cleared;
}
}
@@ -1,14 +1,10 @@
package com.glodblock.github.nei.object;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.oredict.OreDictionary;
@@ -19,8 +15,7 @@ import com.glodblock.github.util.Util;
public class OrderStack<T> {
private T RealStack;
private int index;
private ItemStack[] items;
private final int index;
public static final int ITEM = 1;
public static final int FLUID = 2;
@@ -33,29 +28,10 @@ public class OrderStack<T> {
this.index = order;
}
public OrderStack(T stack, int order, ItemStack[] items) {
this(stack, order);
if (items.length > 1) {
this.items = items;
}
}
public void putStack(T stack) {
this.RealStack = stack;
}
public void putItems(ItemStack[] items) {
this.items = items;
}
public ItemStack[] getItems() {
return this.items;
}
public final void setIndex(int i) {
this.index = i;
}
public T getStack() {
return RealStack;
}
@@ -95,16 +71,6 @@ public class OrderStack<T> {
NBTTagCompound tmp = new NBTTagCompound();
tmp.setByte("t", (byte) ITEM);
((ItemStack) RealStack).writeToNBT(tmp);
// replacement items
if (items != null) {
NBTTagList list = new NBTTagList();
for (ItemStack is : this.items) {
NBTTagCompound t = new NBTTagCompound();
is.writeToNBT(t);
list.appendTag(t);
}
tmp.setTag(index + ":", list);
}
buf.setTag(index + ":", tmp);
} else if (RealStack instanceof FluidStack) {
NBTTagCompound tmp = new NBTTagCompound();
@@ -125,15 +91,7 @@ public class OrderStack<T> {
byte id = info.getByte("t");
switch (id) {
case ITEM:
List<ItemStack> list = new ArrayList<>();
if (info.hasKey(index + ":")) {
NBTTagList items = info.getTagList(index + ":", 10);
for (int x = 0; x < items.tagCount(); x++) {
final NBTTagCompound item = items.getCompoundTagAt(x);
list.add(ItemStack.loadItemStackFromNBT(item));
}
}
return new OrderStack<>(ItemStack.loadItemStackFromNBT(info), index, list.toArray(new ItemStack[0]));
return new OrderStack<>(ItemStack.loadItemStackFromNBT(info), index);
case FLUID:
return new OrderStack<>(FluidStack.loadFluidStackFromNBT(info), index);
case CUSTOM:
@@ -1,7 +1,9 @@
package com.glodblock.github.nei.recipes;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
@@ -28,8 +30,7 @@ public final class FluidRecipe {
public static List<OrderStack<?>> getPackageInputs(IRecipeHandler recipe, int index, boolean priority) {
TemplateRecipeHandler tRecipe = (TemplateRecipeHandler) recipe;
if (tRecipe == null) return new ArrayList<>();
if (!IdentifierMap.containsKey(tRecipe.getOverlayIdentifier())) return getDefaultPackageInputs(tRecipe, index);
if (tRecipe == null || !IdentifierMap.containsKey(tRecipe.getOverlayIdentifier())) return new ArrayList<>();
if (tRecipe.getOverlayIdentifier() == null) return getPackageInputsLegacy(recipe, index);
IRecipeExtractor extractor = IdentifierMap.get(tRecipe.getOverlayIdentifier());
if (extractor == null) return new ArrayList<>();
@@ -53,26 +54,9 @@ public final class FluidRecipe {
return out;
}
private static List<OrderStack<?>> getDefaultPackageInputs(TemplateRecipeHandler tRecipe, int index) {
List<OrderStack<?>> tmp = new LinkedList<>();
AtomicInteger i = new AtomicInteger(0);
tRecipe.getIngredientStacks(index)
.forEach(ps -> tmp.add(new OrderStack<>(ps.item, i.getAndIncrement(), ps.items)));
return tmp;
}
private static List<OrderStack<?>> getDefaultPackageOutputs(TemplateRecipeHandler tRecipe, int index) {
List<OrderStack<?>> tmp = new LinkedList<>();
AtomicInteger i = new AtomicInteger(0);
tmp.add(new OrderStack<>(tRecipe.getResultStack(index).item, i.getAndIncrement()));
tRecipe.getOtherStacks(index).forEach(ps -> tmp.add(new OrderStack<>(ps.item, i.getAndIncrement())));
return tmp;
}
public static List<OrderStack<?>> getPackageOutputs(IRecipeHandler recipe, int index, boolean useOther) {
TemplateRecipeHandler tRecipe = (TemplateRecipeHandler) recipe;
if (tRecipe == null) return new ArrayList<>();
if (!IdentifierMap.containsKey(tRecipe.getOverlayIdentifier())) return getDefaultPackageOutputs(tRecipe, index);
if (tRecipe == null || !IdentifierMap.containsKey(tRecipe.getOverlayIdentifier())) return new ArrayList<>();
if (tRecipe.getOverlayIdentifier() == null) return getPackageOutputsLegacy(recipe, index, useOther);
IRecipeExtractor extractor = IdentifierMap.get(tRecipe.getOverlayIdentifier());
if (extractor == null) return new ArrayList<>();
@@ -26,7 +26,7 @@ public final class ExtractorUtil {
return items.stream().map(item -> {
index.getAndIncrement();
Object o = transformer.apply(item);
return o != null ? new OrderStack<>(o, index.get(), item.items) : null;
return o != null ? new OrderStack<>(o, index.get()) : null;
}).filter(Objects::nonNull).collect(Collectors.toList());
}
}
@@ -16,9 +16,9 @@ import appeng.api.networking.crafting.ICraftingGrid;
import appeng.api.networking.crafting.ICraftingJob;
import appeng.container.ContainerOpenContext;
import appeng.container.implementations.ContainerCraftAmount;
import appeng.container.implementations.ContainerCraftConfirm;
import appeng.core.AELog;
import com.glodblock.github.client.gui.container.ContainerFluidCraftConfirm;
import com.glodblock.github.inventory.InventoryHandler;
import com.glodblock.github.inventory.gui.GuiType;
import com.glodblock.github.inventory.item.IWirelessTerminal;
@@ -107,8 +107,8 @@ public class CPacketCraftRequest implements IMessage {
GuiType.FLUID_CRAFTING_CONFIRM_ITEM);
}
if (player.openContainer instanceof ContainerCraftConfirm) {
final ContainerCraftConfirm ccc = (ContainerCraftConfirm) player.openContainer;
if (player.openContainer instanceof ContainerFluidCraftConfirm) {
final ContainerFluidCraftConfirm ccc = (ContainerFluidCraftConfirm) player.openContainer;
ccc.setAutoStart(message.heldShift);
ccc.setJob(futureJob);
cca.detectAndSendChanges();
@@ -2,6 +2,7 @@ package com.glodblock.github.network;
import net.minecraft.inventory.Container;
import com.glodblock.github.client.gui.container.ContainerFluidCraftConfirm;
import com.glodblock.github.client.gui.container.ContainerFluidStorageBus;
import com.glodblock.github.client.gui.container.base.FCContainerEncodeTerminal;
@@ -120,6 +121,12 @@ public class CPacketFluidPatternTermBtns implements IMessage {
break;
}
cpt.getPatternTerminal().saveSettings();
} else if (Name.equals("Terminal.Cpu") && c instanceof ContainerFluidCraftConfirm) {
final ContainerFluidCraftConfirm qk = (ContainerFluidCraftConfirm) c;
qk.cycleCpu(Value.equals("Next"));
} else if (Name.equals("Terminal.Start") && c instanceof ContainerFluidCraftConfirm) {
final ContainerFluidCraftConfirm qk = (ContainerFluidCraftConfirm) c;
qk.startJob();
} else if (Name.startsWith("StorageBus.") && c instanceof ContainerFluidStorageBus) {
final ContainerFluidStorageBus ccw = (ContainerFluidStorageBus) c;
if (Name.equals("StorageBus.Action")) {
@@ -1,8 +1,5 @@
package com.glodblock.github.network;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -12,6 +9,7 @@ import net.minecraft.nbt.NBTTagCompound;
import appeng.api.storage.data.IAEItemStack;
import appeng.util.item.AEItemStack;
import com.glodblock.github.FluidCraft;
import com.glodblock.github.client.gui.container.ContainerLevelMaintainer;
import com.glodblock.github.common.tile.TileLevelMaintainer;
@@ -90,7 +88,7 @@ public class CPacketLevelMaintainer implements IMessage {
public static class Handler implements IMessageHandler<CPacketLevelMaintainer, IMessage> {
private void refresh(ContainerLevelMaintainer cca, EntityPlayerMP player) {
List<IAEItemStack> toSend = new ArrayList<>(TileLevelMaintainer.REQ_COUNT);
SPacketMEInventoryUpdate piu = new SPacketMEInventoryUpdate(false);
for (int i = 0; i < TileLevelMaintainer.REQ_COUNT; i++) {
IAEItemStack is = cca.getTile().requests.getRequestQtyStack(i);
IAEItemStack is1 = cca.getTile().requests.getRequestBatches().getStack(i);
@@ -98,7 +96,7 @@ public class CPacketLevelMaintainer implements IMessage {
if (is1 != null) {
NBTTagCompound data;
data = is1.getItemStack().getTagCompound();
toSend.add(
piu.appendItem(
setTag(
is,
is1.getStackSize(),
@@ -106,11 +104,11 @@ public class CPacketLevelMaintainer implements IMessage {
data.getBoolean("Enable"),
cca.getTile().requests.getState(i).ordinal()));
} else {
toSend.add(setTag(is, 0, i, true, 0));
piu.appendItem(setTag(is, 0, i, true, 0));
}
}
}
SPacketMEUpdateBuffer.scheduleItemUpdate(player, toSend);
FluidCraft.proxy.netHandler.sendTo(piu, player);
}
@Nullable
@@ -12,7 +12,8 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.fluids.FluidStack;
import appeng.api.AEApi;
import appeng.api.storage.IMEMonitor;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.ITerminalHost;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
@@ -96,10 +97,12 @@ public class CPacketTransferRecipe implements IMessage {
public IMessage onMessage(CPacketTransferRecipe message, MessageContext ctx) {
Container c = ctx.getServerHandler().playerEntity.openContainer;
if (c instanceof ContainerItemMonitor) {
IMEMonitor<IAEItemStack> monitor = ((ContainerItemMonitor) c).getMonitor();
IItemList<IAEItemStack> storageList = AEApi.instance().storage().createItemList();
if (monitor != null) {
storageList = monitor.getStorageList();
ITerminalHost host = ((ContainerItemMonitor) c).getHost();
IItemList<IAEItemStack> storageList;
if (host != null) {
storageList = host.getItemInventory().getStorageList();
} else {
storageList = AEApi.instance().storage().createItemList();
}
if (c instanceof FCContainerEncodeTerminal) {
// pattern terminal only
@@ -127,15 +130,16 @@ public class CPacketTransferRecipe implements IMessage {
// using exists item to fill slot
if (message.shift && !storageList.isEmpty()) {
for (OrderStack stack : message.inputs) {
if (stack.getStack() instanceof FluidStack || stack.getItems() == null) continue;
IAEItemStack iaeItemStack = AEApi.instance().storage()
.createItemStack((ItemStack) stack.getStack());
if (stack.getStack() instanceof FluidStack) continue;
ItemStack is = (ItemStack) stack.getStack();
IAEItemStack iaeItemStack = AEApi.instance().storage().createItemStack(is);
if (storageList.findPrecise(iaeItemStack) == null) {
// try to replace item
for (ItemStack replaceItemStack : stack.getItems()) {
if (storageList.findPrecise(
AEApi.instance().storage().createItemStack(replaceItemStack)) != null) {
stack.putStack(replaceItemStack);
for (IAEItemStack tmp : storageList.findFuzzy(iaeItemStack, FuzzyMode.IGNORE_ALL)) {
if (iaeItemStack.sameOre(tmp)) {
ItemStack substitute = tmp.getItemStack().copy();
substitute.stackSize = is.stackSize;
stack.putStack(substitute);
break;
}
}
}
@@ -1,109 +0,0 @@
package com.glodblock.github.network;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import appeng.api.storage.data.IAEFluidStack;
import appeng.util.item.AEFluidStack;
import com.glodblock.github.client.gui.GuiFluidCraftConfirm;
import com.glodblock.github.client.gui.GuiFluidMonitor;
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 io.netty.buffer.ByteBuf;
/**
* Dedicated packet for fluid updates.
*/
public class SPacketMEFluidInvUpdate implements IMessage {
private List<IAEFluidStack> list = new ArrayList<>();
private byte ref = (byte) 0;
private boolean resort = true;
public SPacketMEFluidInvUpdate() {}
/**
* Used for the GUI to confirm crafting. 0 = available 1 = pending 2 = missing
*/
public SPacketMEFluidInvUpdate(byte b) {
ref = b;
}
/**
* If resort, call "updateView()". Used when multiple packets are sent to open an inventory; only the last packet
* should resort. <<<<<<< HEAD
*
* =======
*
* >>>>>>> 669eb96... Network throttle: Force ME update packets to be sent once every 50ms.
*
* @param resort whether this packet should resort the term or not
*/
public SPacketMEFluidInvUpdate(boolean resort) {
this.resort = resort;
}
@Override
public void fromBytes(ByteBuf buf) {
ref = buf.readByte();
resort = buf.readBoolean();
int amount = buf.readInt();
list = new ArrayList<>(amount);
try {
for (int i = 0; i < amount; i++) {
list.add(AEFluidStack.loadFluidStackFromPacket(buf));
}
} catch (Exception io) {
System.out.println("Error handling payload w/ " + amount + " items.");
io.printStackTrace();
}
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeByte(ref);
buf.writeBoolean(resort);
buf.writeInt(list.size());
try {
for (IAEFluidStack is : list) {
is.writeToPacket(buf);
}
} catch (IOException io) {
io.printStackTrace();
}
}
public void setResort(boolean resort) {
this.resort = resort;
}
public void appendFluid(final IAEFluidStack is) {
list.add(is);
}
public boolean isEmpty() {
return this.list.isEmpty();
}
public static class Handler implements IMessageHandler<SPacketMEFluidInvUpdate, IMessage> {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public IMessage onMessage(SPacketMEFluidInvUpdate message, MessageContext ctx) {
final GuiScreen gs = Minecraft.getMinecraft().currentScreen;
if (gs instanceof GuiFluidMonitor) {
((GuiFluidMonitor) gs).postUpdate(message.list, message.resort);
} else if (gs instanceof GuiFluidCraftConfirm) {
((GuiFluidCraftConfirm) gs).postUpdate((List) message.list, message.ref);
}
return null;
}
}
}
@@ -0,0 +1,112 @@
package com.glodblock.github.network;
import java.io.IOException;
import java.nio.BufferOverflowException;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEItemStack;
import appeng.util.item.AEFluidStack;
import appeng.util.item.AEItemStack;
import com.glodblock.github.client.gui.GuiFluidCraftConfirm;
import com.glodblock.github.client.gui.GuiFluidMonitor;
import com.glodblock.github.client.gui.GuiItemMonitor;
import com.glodblock.github.client.gui.GuiLevelMaintainer;
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 io.netty.buffer.ByteBuf;
public class SPacketMEInventoryUpdate implements IMessage {
private List<Object> list;
private byte ref;
private boolean isFluid = false;
public SPacketMEInventoryUpdate() {
ref = 0;
list = new LinkedList<>();
}
public SPacketMEInventoryUpdate(Boolean isFluid) {
ref = 0;
list = new LinkedList<>();
this.isFluid = isFluid;
}
public SPacketMEInventoryUpdate(byte b) {
ref = b;
list = new LinkedList<>();
}
@Override
public void fromBytes(ByteBuf buf) {
isFluid = buf.readBoolean();
long amount = buf.readLong();
ref = buf.readByte();
list = new LinkedList<>();
try {
for (int i = 0; i < amount; i++) {
if (isFluid) {
list.add(AEFluidStack.loadFluidStackFromPacket(buf));
} else {
list.add(AEItemStack.loadItemStackFromPacket(buf));
}
}
} catch (IOException io) {
io.printStackTrace();
}
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeBoolean(isFluid);
buf.writeLong(list.size());
buf.writeByte(ref);
try {
for (Object is : list) {
if (is instanceof IAEItemStack) ((IAEItemStack) is).writeToPacket(buf);
if (is instanceof IAEFluidStack) ((IAEFluidStack) is).writeToPacket(buf);
}
} catch (IOException io) {
io.printStackTrace();
}
}
public void appendItem(final IAEItemStack is) throws BufferOverflowException {
list.add(is);
}
public void appendFluid(final IAEFluidStack is) throws BufferOverflowException {
list.add(is);
}
public boolean isEmpty() {
return this.list.isEmpty();
}
public static class Handler implements IMessageHandler<SPacketMEInventoryUpdate, IMessage> {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public IMessage onMessage(SPacketMEInventoryUpdate message, MessageContext ctx) {
final GuiScreen gs = Minecraft.getMinecraft().currentScreen;
if (gs instanceof GuiFluidMonitor) {
((GuiFluidMonitor) gs).postUpdate((List) message.list);
} else if (gs instanceof GuiItemMonitor) {
((GuiItemMonitor) gs).postUpdate((List) message.list);
} else if (gs instanceof GuiFluidCraftConfirm) {
((GuiFluidCraftConfirm) gs).postUpdate((List) message.list, message.ref);
} else if (gs instanceof GuiLevelMaintainer) {
((GuiLevelMaintainer) gs).postUpdate((List) message.list);
}
return null;
}
}
}
@@ -1,108 +0,0 @@
package com.glodblock.github.network;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import appeng.api.storage.data.IAEItemStack;
import appeng.util.item.AEItemStack;
import com.glodblock.github.client.gui.GuiFluidCraftConfirm;
import com.glodblock.github.client.gui.GuiItemMonitor;
import com.glodblock.github.client.gui.GuiLevelMaintainer;
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 io.netty.buffer.ByteBuf;
/**
* Packet dedicated to item inventory update.
*/
public class SPacketMEItemInvUpdate implements IMessage {
private List<IAEItemStack> list = new ArrayList<>();
private byte ref = (byte) 0;
private boolean resort = true;
public SPacketMEItemInvUpdate() {}
/**
* Used for the GUI to confirm crafting. 0 = available 1 = pending 2 = missing
*/
public SPacketMEItemInvUpdate(byte b) {
ref = b;
}
/**
* If resort, call "updateView()". Used when multiple packets are sent to open an inventory; only the last packet
* should resort.
*
* @param resort whether this packet should resort the term or not
*/
public SPacketMEItemInvUpdate(boolean resort) {
this.resort = resort;
}
@Override
public void fromBytes(ByteBuf buf) {
ref = buf.readByte();
resort = buf.readBoolean();
int amount = buf.readInt();
list = new ArrayList<>(amount);
try {
for (int i = 0; i < amount; i++) {
list.add(AEItemStack.loadItemStackFromPacket(buf));
}
} catch (Exception io) {
System.out.println("Error handling payload w/ " + amount + " items.");
io.printStackTrace();
}
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeByte(ref);
buf.writeBoolean(resort);
buf.writeInt(list.size());
try {
for (IAEItemStack is : list) {
is.writeToPacket(buf);
}
} catch (IOException io) {
io.printStackTrace();
}
}
public void setResort(boolean resort) {
this.resort = resort;
}
public void appendItem(final IAEItemStack is) {
list.add(is);
}
public boolean isEmpty() {
return this.list.isEmpty();
}
public static class Handler implements IMessageHandler<SPacketMEItemInvUpdate, IMessage> {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public IMessage onMessage(SPacketMEItemInvUpdate message, MessageContext ctx) {
final GuiScreen gs = Minecraft.getMinecraft().currentScreen;
if (gs instanceof GuiItemMonitor) {
((GuiItemMonitor) gs).postUpdate(message.list, message.resort);
} else if (gs instanceof GuiFluidCraftConfirm) {
((GuiFluidCraftConfirm) gs).postUpdate(message.list, message.ref);
} else if (gs instanceof GuiLevelMaintainer) {
((GuiLevelMaintainer) gs).postUpdate(message.list);
}
return null;
}
}
}
@@ -1,130 +0,0 @@
package com.glodblock.github.network;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import net.minecraft.entity.player.EntityPlayerMP;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEItemStack;
import com.glodblock.github.FluidCraft;
import com.glodblock.github.common.Config;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.PlayerEvent;
/**
* Only should exist on the server side! Schedules packets to be sent every `packetRate` ms.
*/
public class SPacketMEUpdateBuffer {
private static ScheduledExecutorService executor;
private static ScheduledFuture<?> task;
private static final Map<EntityPlayerMP, LinkedHashSet<IAEItemStack>> itemBuffer = new HashMap<>();
private static final Map<EntityPlayerMP, LinkedHashSet<IAEFluidStack>> fluidBuffer = new HashMap<>();
public static void init() {
executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r);
thread.setName("AE2FC Network worker");
thread.setDaemon(true);
thread.setPriority(6);
return thread;
});
task = executor
.scheduleAtFixedRate(SPacketMEUpdateBuffer::sendBuffer, 0, Config.packetRate, TimeUnit.MILLISECONDS);
}
public static void disable() {
task.cancel(false);
executor.shutdown();
}
public static void scheduleItemUpdate(EntityPlayerMP player, List<IAEItemStack> stacks) {
synchronized (itemBuffer) {
if (!itemBuffer.containsKey(player)) {
itemBuffer.put(player, new LinkedHashSet<>(1024));
}
LinkedHashSet<IAEItemStack> buffer = itemBuffer.get(player);
stacks.forEach(s -> buffer.add(s.copy()));
}
}
public static void scheduleFluidUpdate(EntityPlayerMP player, List<IAEFluidStack> stacks) {
synchronized (itemBuffer) {
if (!fluidBuffer.containsKey(player)) {
fluidBuffer.put(player, new LinkedHashSet<>(1024));
}
LinkedHashSet<IAEFluidStack> buffer = fluidBuffer.get(player);
stacks.forEach(s -> buffer.add(s.copy()));
}
}
public static void sendBuffer() {
synchronized (itemBuffer) {
itemBuffer.forEach((player, updates) -> {
if (updates.isEmpty()) return;
int i = 0;
SPacketMEItemInvUpdate packet = new SPacketMEItemInvUpdate(false);
Iterator<IAEItemStack> it = updates.iterator();
while (it.hasNext()) {
if (i < Config.packetSize) {
packet.appendItem(it.next());
it.remove();
i++;
} else {
FluidCraft.proxy.netHandler.sendTo(packet, player);
packet = new SPacketMEItemInvUpdate(false);
i = 0;
}
}
packet.setResort(true);
FluidCraft.proxy.netHandler.sendTo(packet, player);
});
fluidBuffer.forEach((player, updates) -> {
if (updates.isEmpty()) return;
int i = 0;
SPacketMEFluidInvUpdate packet = new SPacketMEFluidInvUpdate(false);
Iterator<IAEFluidStack> it = updates.iterator();
while (it.hasNext()) {
if (i < Config.packetSize) {
packet.appendFluid(it.next());
it.remove();
i++;
} else {
FluidCraft.proxy.netHandler.sendTo(packet, player);
packet = new SPacketMEFluidInvUpdate(false);
i = 0;
}
}
packet.setResort(true);
FluidCraft.proxy.netHandler.sendTo(packet, player);
});
}
}
public static void clear(EntityPlayerMP player) {
synchronized (itemBuffer) {
if (itemBuffer.containsKey(player)) {
itemBuffer.get(player).clear();
}
if (fluidBuffer.containsKey(player)) {
fluidBuffer.get(player).clear();
}
}
}
@SubscribeEvent
public void onPlayerLeave(PlayerEvent.PlayerLoggedOutEvent event) {
if (event.player instanceof EntityPlayerMP) {
clear((EntityPlayerMP) event.player);
}
}
}
@@ -11,10 +11,8 @@ import com.glodblock.github.common.Config;
import com.glodblock.github.common.tile.TileWalrus;
import com.glodblock.github.inventory.external.AEFluidInterfaceHandler;
import com.glodblock.github.loader.ItemAndBlockHolder;
import com.glodblock.github.network.SPacketMEUpdateBuffer;
import com.glodblock.github.util.ModAndClassUtil;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
@@ -29,7 +27,6 @@ public class CommonProxy {
public void init(FMLInitializationEvent event) {
this.registerMovables();
FMLCommonHandler.instance().bus().register(SPacketMEUpdateBuffer.class);
}
public void postInit(FMLPostInitializationEvent event) {
@@ -40,10 +40,6 @@ public class BlockPos {
return new BlockPos(this.x + face.offsetX, this.y + face.offsetY, this.z + face.offsetZ, this.w);
}
public BlockPos getOffSet(int x, int y, int z) {
return new BlockPos(this.x + x, this.y + y, this.z + z, this.w);
}
public TileEntity getTileEntity() {
if (w != null) {
return w.getTileEntity(x, y, z);
@@ -27,7 +27,6 @@ public final class ModAndClassUtil {
public static boolean WAILA = false;
public static boolean AVARITIA = false;
public static boolean isV2;
public static boolean isTypeFilter;
public static boolean isDoubleButton;
public static boolean isSaveText;
public static boolean isSearchStringTooltip;
@@ -112,13 +111,6 @@ public final class ModAndClassUtil {
} catch (ClassNotFoundException e) {
isV2 = false;
}
try {
Field filters = Class.forName("appeng.client.me.ItemRepo").getDeclaredField("filters");
if (filters == null) isTypeFilter = false;
isTypeFilter = true;
} catch (ClassNotFoundException | NoSuchFieldException e) {
isTypeFilter = false;
}
try {
essentiaGas = Class.forName("thaumicenergistics.common.fluids.GaseousEssentia");
@@ -3,8 +3,6 @@ package com.glodblock.github.util;
import static com.glodblock.github.common.item.ItemBaseWirelessTerminal.infinityBoosterCard;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.minecraft.entity.player.EntityPlayer;
@@ -417,36 +415,6 @@ public final class Util {
public static class FluidUtil {
public static void fluidTankInfoWriteToNBT(FluidTankInfo[] infos, NBTTagCompound data) {
int i = 0;
for (FluidTankInfo info : infos) {
if (info.fluid != null && info.fluid.amount > 0) {
NBTTagCompound fs = new NBTTagCompound();
info.fluid.writeToNBT(fs);
fs.setInteger("capacity", info.capacity);
data.setTag("#" + i, fs);
}
i++;
}
data.setInteger("fluidInvSize", i);
}
public static FluidTankInfo[] fluidTankInfoReadFromNBT(NBTTagCompound data) {
int i = 0;
List<FluidTankInfo> infos = new ArrayList<>();
while (data.hasKey("fluidInvSize") && i < data.getInteger("fluidInvSize")) {
if (data.hasKey("#" + i)) {
NBTTagCompound tag = (NBTTagCompound) data.getTag("#" + i);
FluidStack fs = FluidStack.loadFluidStackFromNBT(tag);
infos.add(new FluidTankInfo(fs, tag.getInteger("capacity")));
} else {
infos.add(new FluidTankInfo(null, 0));
}
i++;
}
return infos.toArray(new FluidTankInfo[0]);
}
public static IAEFluidStack createAEFluidStack(Fluid fluid) {
return createAEFluidStack(new FluidStack(fluid, FluidContainerRegistry.BUCKET_VOLUME));
}
@@ -126,9 +126,9 @@ ae2fc.tooltip.pattern_terminal_ex_w=Processing Pattern Terminal
ae2fc.tooltip.wireless.installed=Installed Card:
ae2fc.tooltip.not_prio=Allow fluids to be placed first
ae2fc.tooltip.not_prio.hint=Disabled
ae2fc.tooltip.not_prio.hint=Enabled
ae2fc.tooltip.prio=Allow fluids to be placed first
ae2fc.tooltip.prio.hint=Enabled
ae2fc.tooltip.prio.hint=Disabled
ae2fc.tooltip.submit=Submit
ae2fc.tooltip.enable=Enabled
ae2fc.tooltip.disable=Disabled
@@ -126,9 +126,9 @@ ae2fc.tooltip.pattern_terminal_ex_w=增广样板终端
ae2fc.tooltip.wireless.installed=已安装的卡:
ae2fc.tooltip.not_prio=优先放置流体
ae2fc.tooltip.not_prio.hint=禁用
ae2fc.tooltip.not_prio.hint=启用
ae2fc.tooltip.prio=优先放置流体
ae2fc.tooltip.prio.hint=启用
ae2fc.tooltip.prio.hint=禁用
ae2fc.tooltip.submit=提交
ae2fc.tooltip.enable=启用
ae2fc.tooltip.disable=禁用