diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..fd2792b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,44 @@ +* text eol=lf + +*.[jJ][aA][rR] binary + +*.[pP][nN][gG] binary +*.[jJ][pP][gG] binary +*.[jJ][pP][eE][gG] binary +*.[gG][iI][fF] binary +*.[tT][iI][fF] binary +*.[tT][iI][fF][fF] binary +*.[iI][cC][oO] binary +*.[sS][vV][gG] text +*.[eE][pP][sS] binary +*.[xX][cC][fF] binary + +*.[kK][aA][rR] binary +*.[mM]4[aA] binary +*.[mM][iI][dD] binary +*.[mM][iI][dD][iI] binary +*.[mM][pP]3 binary +*.[oO][gG][gG] binary +*.[rR][aA] binary + +*.7[zZ] binary +*.[gG][zZ] binary +*.[tT][aA][rR] binary +*.[tT][gG][zZ] binary +*.[zZ][iI][pP] binary + +*.[tT][cC][nN] binary +*.[sS][oO] binary +*.[dD][lL][lL] binary +*.[dD][yY][lL][iI][bB] binary +*.[pP][sS][dD] binary +*.[tT][tT][fF] binary +*.[oO][tT][fF] binary + +*.[pP][aA][tT][cC][hH] -text + +*.[bB][aA][tT] text eol=crlf +*.[cC][mM][dD] text eol=crlf +*.[pP][sS]1 text eol=crlf + +*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary diff --git a/build.gradle b/build.gradle index 4b17076..bf14610 100644 --- a/build.gradle +++ b/build.gradle @@ -1,58 +1,88 @@ -//version: 1644349045 +//version: 1665425597 /* -DO NOT CHANGE THIS FILE! - -Also, you may replace this file at any time if there is an update available. -Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates. -*/ + DO NOT CHANGE THIS FILE! + Also, you may replace this file at any time if there is an update available. + Please check https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/build.gradle for updates. + */ import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar - +import com.matthewprenger.cursegradle.CurseArtifact +import com.matthewprenger.cursegradle.CurseRelation +import com.modrinth.minotaur.dependencies.ModDependency +import com.modrinth.minotaur.dependencies.VersionDependency +import org.gradle.internal.logging.text.StyledTextOutput.Style +import org.gradle.internal.logging.text.StyledTextOutputFactory + +import java.nio.file.Files +import java.nio.file.Paths import java.util.concurrent.TimeUnit +import java.util.zip.ZipEntry +import java.util.zip.ZipInputStream +import java.util.zip.ZipOutputStream buildscript { repositories { + mavenCentral() + maven { - name = "forge" - url = "https://maven.minecraftforge.net" + name 'forge' + url 'https://maven.minecraftforge.net' } maven { - name = "sonatype" - url = "https://oss.sonatype.org/content/repositories/snapshots/" + // GTNH ForgeGradle Fork + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" } maven { - name = "Scala CI dependencies" - url = "https://repo1.maven.org/maven2/" + name 'sonatype' + url 'https://oss.sonatype.org/content/repositories/snapshots/' } maven { - name = "jitpack" - url = "https://jitpack.io" + name 'Scala CI dependencies' + url 'https://repo1.maven.org/maven2/' } } dependencies { - classpath 'com.github.GTNewHorizons:ForgeGradle:1.2.7' + classpath 'net.minecraftforge.gradle:ForgeGradle:1.2.9' } } - plugins { + id 'java-library' id 'idea' id 'eclipse' id 'scala' id 'maven-publish' - id 'java-library' - id('org.jetbrains.kotlin.jvm') version ('1.6.10') apply false - id('org.ajoberstar.grgit') version('4.1.1') - id('com.github.johnrengelman.shadow') version('4.0.4') - id('com.palantir.git-version') version('0.13.0') apply false - id('de.undercouch.download') version('5.0.1') + id 'org.jetbrains.kotlin.jvm' version '1.5.30' apply false + id 'org.jetbrains.kotlin.kapt' version '1.5.30' apply false + id 'com.google.devtools.ksp' version '1.5.30-1.0.0' apply false + id 'org.ajoberstar.grgit' version '4.1.1' + id 'com.github.johnrengelman.shadow' version '4.0.4' + id 'com.palantir.git-version' version '0.13.0' apply false + id 'de.undercouch.download' version '5.0.1' + id 'com.github.gmazzo.buildconfig' version '3.0.3' apply false + 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 +} +boolean settingsupdated = verifySettingsGradle() +settingsupdated = verifyGitAttributes() || settingsupdated +if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") + +dependencies { + implementation 'com.diffplug:blowdryer:1.6.0' } +apply plugin: 'com.diffplug.blowdryer' + if (project.file('.git/HEAD').isFile()) { apply plugin: 'com.palantir.git-version' } +def out = services.get(StyledTextOutputFactory).create('an-output') + apply plugin: 'forge' def projectJavaVersion = JavaLanguageVersion.of(8) @@ -71,7 +101,14 @@ idea { } } -if(JavaVersion.current() != JavaVersion.VERSION_1_8) { +boolean disableSpotless = project.hasProperty("disableSpotless") ? project.disableSpotless.toBoolean() : false + +if (!disableSpotless) { + apply plugin: 'com.diffplug.spotless' + apply from: Blowdryer.file('spotless.gradle') +} + +if (JavaVersion.current() != JavaVersion.VERSION_1_8) { throw new GradleException("This project requires Java 8, but it's running on " + JavaVersion.current()) } @@ -96,62 +133,79 @@ checkPropertyExists("containsMixinsAndOrCoreModOnly") checkPropertyExists("usesShadowedDependencies") checkPropertyExists("developmentEnvironmentUserName") -boolean noPublishedSources = project.findProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false +propertyDefaultIfUnset("noPublishedSources", false) +propertyDefaultIfUnset("usesMixinDebug", project.usesMixins) +propertyDefaultIfUnset("forceEnableMixins", false) +propertyDefaultIfUnset("channel", "stable") +propertyDefaultIfUnset("mappingsVersion", "12") +propertyDefaultIfUnset("modrinthProjectId", "") +propertyDefaultIfUnset("modrinthRelations", "") +propertyDefaultIfUnset("curseForgeProjectId", "") +propertyDefaultIfUnset("curseForgeRelations", "") String javaSourceDir = "src/main/java/" String scalaSourceDir = "src/main/scala/" String kotlinSourceDir = "src/main/kotlin/" -String targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") -String targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") -String targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") -if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + +final String modGroupPath = modGroup.toString().replaceAll("\\.", "/") +final String apiPackagePath = apiPackage.toString().replaceAll("\\.", "/") + +String targetPackageJava = javaSourceDir + modGroupPath +String targetPackageScala = scalaSourceDir + modGroupPath +String targetPackageKotlin = kotlinSourceDir + modGroupPath +if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { throw new GradleException("Could not resolve \"modGroup\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } -if(apiPackage) { - targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") - targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") - targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") - if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { +if (apiPackage) { + targetPackageJava = javaSourceDir + modGroupPath + "/" + apiPackagePath + targetPackageScala = scalaSourceDir + modGroupPath + "/" + apiPackagePath + targetPackageKotlin = kotlinSourceDir + modGroupPath + "/" + apiPackagePath + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { throw new GradleException("Could not resolve \"apiPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } } -if(accessTransformersFile) { +if (accessTransformersFile) { String targetFile = "src/main/resources/META-INF/" + accessTransformersFile - if(!getFile(targetFile).exists()) { + if (!getFile(targetFile).exists()) { throw new GradleException("Could not resolve \"accessTransformersFile\"! Could not find " + targetFile) } } -if(usesMixins.toBoolean()) { - if(mixinsPackage.isEmpty() || mixinPlugin.isEmpty()) { - throw new GradleException("\"mixinPlugin\" requires \"mixinsPackage\" and \"mixinPlugin\" to be set!") +if (usesMixins.toBoolean()) { + if (mixinsPackage.isEmpty()) { + throw new GradleException("\"usesMixins\" requires \"mixinsPackage\" to be set!") } - - targetPackageJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") - targetPackageScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") - targetPackageKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinsPackage.toString().replaceAll("\\.", "/") - if(!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { - throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) + final String mixinPackagePath = mixinsPackage.toString().replaceAll("\\.", "/") + final String mixinPluginPath = mixinPlugin.toString().replaceAll("\\.", "/") + + targetPackageJava = javaSourceDir + modGroupPath + "/" + mixinPackagePath + targetPackageScala = scalaSourceDir + modGroupPath + "/" + mixinPackagePath + targetPackageKotlin = kotlinSourceDir + modGroupPath + "/" + mixinPackagePath + if (!(getFile(targetPackageJava).exists() || getFile(targetPackageScala).exists() || getFile(targetPackageKotlin).exists())) { + throw new GradleException("Could not resolve \"mixinsPackage\"! Could not find " + targetPackageJava + " or " + targetPackageScala + " or " + targetPackageKotlin) } - String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java" - String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".scala" - String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".java" - String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + mixinPlugin.toString().replaceAll("\\.", "/") + ".kt" - if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { - throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) + if (!mixinPlugin.isEmpty()) { + String targetFileJava = javaSourceDir + modGroupPath + "/" + mixinPluginPath + ".java" + String targetFileScala = scalaSourceDir + modGroupPath + "/" + mixinPluginPath + ".scala" + String targetFileScalaJava = scalaSourceDir + modGroupPath + "/" + mixinPluginPath + ".java" + String targetFileKotlin = kotlinSourceDir + modGroupPath + "/" + mixinPluginPath + ".kt" + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { + throw new GradleException("Could not resolve \"mixinPlugin\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) + } } } -if(coreModClass) { - String targetFileJava = javaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java" - String targetFileScala = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".scala" - String targetFileScalaJava = scalaSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".java" - String targetFileKotlin = kotlinSourceDir + modGroup.toString().replaceAll("\\.", "/") + "/" + coreModClass.toString().replaceAll("\\.", "/") + ".kt" - if(!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { +if (coreModClass) { + final String coreModPath = coreModClass.toString().replaceAll("\\.", "/") + String targetFileJava = javaSourceDir + modGroupPath + "/" + coreModPath + ".java" + String targetFileScala = scalaSourceDir + modGroupPath + "/" + coreModPath + ".scala" + String targetFileScalaJava = scalaSourceDir + modGroupPath + "/" + coreModPath + ".java" + String targetFileKotlin = kotlinSourceDir + modGroupPath + "/" + coreModPath + ".kt" + if (!(getFile(targetFileJava).exists() || getFile(targetFileScala).exists() || getFile(targetFileScalaJava).exists() || getFile(targetFileKotlin).exists())) { throw new GradleException("Could not resolve \"coreModClass\"! Could not find " + targetFileJava + " or " + targetFileScala + " or " + targetFileScalaJava + " or " + targetFileKotlin) } } @@ -168,8 +222,8 @@ configurations.all { try { 'git config core.fileMode false'.execute() } -catch (Exception e) { - logger.error("\u001B[31mgit isn't installed at all\u001B[0m") +catch (Exception ignored) { + out.style(Style.Failure).println("git isn't installed at all") } // Pulls version first from the VERSION env and then git tag @@ -178,58 +232,63 @@ String versionOverride = System.getenv("VERSION") ?: null try { identifiedVersion = versionOverride == null ? gitVersion() : versionOverride } -catch (Exception e) { - logger.error("\n\u001B[1;31mThis mod must be version controlled by Git AND the repository must provide at least one tag,\n" + - "or the VERSION override must be set! \u001B[32m(Don't download from GitHub using the ZIP option, instead\n" + - "clone the repository, see\u001B[33m https://gtnh.miraheze.org/wiki/Development \u001B[32mfor details.)\u001B[0m\n"); +catch (Exception ignored) { + out.style(Style.Failure).text( + 'This mod must be version controlled by Git AND the repository must provide at least one tag,\n' + + 'or the VERSION override must be set! ').style(Style.SuccessHeader).text('(Do NOT download from GitHub using the ZIP option, instead\n' + + 'clone the repository, see ').style(Style.Info).text('https://gtnh.miraheze.org/wiki/Development').style(Style.SuccessHeader).println(' for details.)' + ) versionOverride = 'NO-GIT-TAG-SET' identifiedVersion = versionOverride } version = minecraftVersion + '-' + identifiedVersion -String modVersion = identifiedVersion +ext { + modVersion = identifiedVersion +} -if( identifiedVersion.equals(versionOverride) ) { - logger.error('\u001B[31m\u001B[7mWe hope you know what you\'re doing using\u001B[0m\u001B[1;34m ' + modVersion + '\u001B[0m\n'); - logger.error('\7\u001B[31mGoing to blindly try to use\u001B[1;34m ' + modVersion + '\u001B[0m\u001B[31m, this probably won\'t work the way you expect!!\u001B[0m\n'); +if (identifiedVersion == versionOverride) { + out.style(Style.Failure).text('Override version to ').style(Style.Identifier).text(modVersion).style(Style.Failure).println('!\7') } group = modGroup -if(project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { +if (project.hasProperty("customArchiveBaseName") && customArchiveBaseName) { archivesBaseName = customArchiveBaseName -} -else { +} else { archivesBaseName = modId } - def arguments = [] def jvmArguments = [] -if(usesMixins.toBoolean()) { +if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { arguments += [ - "--tweakClass org.spongepowered.asm.launch.MixinTweaker" - ] - jvmArguments += [ - "-Dmixin.debug.countInjections=true", "-Dmixin.debug.verbose=true", "-Dmixin.debug.export=true" + "--tweakClass org.spongepowered.asm.launch.MixinTweaker" ] + if (usesMixinDebug.toBoolean()) { + jvmArguments += [ + "-Dmixin.debug.countInjections=true", + "-Dmixin.debug.verbose=true", + "-Dmixin.debug.export=true" + ] + } } minecraft { - version = minecraftVersion + "-" + forgeVersion + "-" + minecraftVersion - runDir = "run" + version = minecraftVersion + '-' + forgeVersion + '-' + minecraftVersion + runDir = 'run' if (replaceGradleTokenInFile) { replaceIn replaceGradleTokenInFile - if(gradleTokenModId) { + if (gradleTokenModId) { replace gradleTokenModId, modId } - if(gradleTokenModName) { + if (gradleTokenModName) { replace gradleTokenModName, modName } - if(gradleTokenVersion) { + if (gradleTokenVersion) { replace gradleTokenVersion, modVersion } - if(gradleTokenGroupName) { + if (gradleTokenGroupName) { replace gradleTokenGroupName, modGroup } } @@ -238,7 +297,7 @@ minecraft { args(arguments) jvmArgs(jvmArguments) - if(developmentEnvironmentUserName) { + if (developmentEnvironmentUserName) { args("--username", developmentEnvironmentUserName) } } @@ -249,8 +308,8 @@ minecraft { } } -if(file("addon.gradle").exists()) { - apply from: "addon.gradle" +if (file('addon.gradle').exists()) { + apply from: 'addon.gradle' } apply from: 'repositories.gradle' @@ -263,58 +322,58 @@ configurations { repositories { maven { - name = "Overmind forge repo mirror" - url = "https://gregtech.overminddl1.com/" + name 'Overmind forge repo mirror' + url 'https://gregtech.overminddl1.com/' } - if(usesMixins.toBoolean()) { - maven { - name = "sponge" - url = "https://repo.spongepowered.org/repository/maven-public" - } + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { maven { - url = "https://jitpack.io" + name = "GTNH Maven" + url = "http://jenkins.usrv.eu:8081/nexus/content/groups/public/" } } } dependencies { - if(usesMixins.toBoolean()) { - 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("org.spongepowered:mixin:0.8-SNAPSHOT") - // using 0.8 to workaround a issue in 0.7 which fails mixin application - compile("com.github.GTNewHorizons:SpongePoweredMixin:0.7.12-GTNH") { - // Mixin includes a lot of dependencies that are too up-to-date - exclude module: "launchwrapper" - exclude module: "guava" - exclude module: "gson" - exclude module: "commons-io" - exclude module: "log4j-core" - } - compile("com.github.GTNewHorizons:SpongeMixins:1.5.0") + if (usesMixins.toBoolean()) { + 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('org.spongepowered:mixin:0.8.5-GTNH:processor') + } + if (usesMixins.toBoolean() || forceEnableMixins.toBoolean()) { + compile('com.gtnewhorizon:gtnhmixins:2.0.1') } } apply from: 'dependencies.gradle' -def mixingConfigRefMap = "mixins." + modId + ".refmap.json" +def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' def refMap = "${tasks.compileJava.temporaryDir}" + File.separator + mixingConfigRefMap def mixinSrg = "${tasks.reobf.temporaryDir}" + File.separator + "mixins.srg" task generateAssets { - if(usesMixins.toBoolean()) { - getFile("/src/main/resources/mixins." + modId + ".json").text = """{ + if (usesMixins.toBoolean()) { + def mixinConfigFile = getFile("/src/main/resources/mixins." + modId + ".json") + if (!mixinConfigFile.exists()) { + def mixinPluginLine = "" + if(!mixinPlugin.isEmpty()) { + // We might not have a mixin plugin if we're using early/late mixins + mixinPluginLine += """\n "plugin": "${modGroup}.${mixinPlugin}", """ + } + + mixinConfigFile.text = """{ "required": true, - "minVersion": "0.7.11", - "package": "${modGroup}.${mixinsPackage}", - "plugin": "${modGroup}.${mixinPlugin}", + "minVersion": "0.8.5-GTNH", + "package": "${modGroup}.${mixinsPackage}",${mixinPluginLine} "refmap": "${mixingConfigRefMap}", "target": "@env(DEFAULT)", - "compatibilityLevel": "JAVA_8" + "compatibilityLevel": "JAVA_8", + "mixins": [], + "client": [], + "server": [] } - """ + } } } @@ -335,7 +394,10 @@ shadowJar { } minimize() // This will only allow shading for actually used classes - configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile] + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] dependsOn(relocateShadowJar) } @@ -350,38 +412,38 @@ jar { attributes(getManifestAttributes()) } - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { dependsOn(shadowJar) enabled = false } } reobf { - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { addExtraSrgFile mixinSrg } } afterEvaluate { - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { tasks.compileJava { options.compilerArgs += [ - "-AreobfSrgFile=${tasks.reobf.srg}", - "-AoutSrgFile=${mixinSrg}", - "-AoutRefMapFile=${refMap}", - // Elan: from what I understand they are just some linter configs so you get some warning on how to properly code - "-XDenableSunApiLintControl", - "-XDignore.symbol.file" + "-AreobfSrgFile=${tasks.reobf.srg}", + "-AoutSrgFile=${mixinSrg}", + "-AoutRefMapFile=${refMap}", + // Elan: from what I understand they are just some linter configs so you get some warning on how to properly code + "-XDenableSunApiLintControl", + "-XDignore.symbol.file" ] } } } runClient { - if(developmentEnvironmentUserName) { + if (developmentEnvironmentUserName) { arguments += [ - "--username", - developmentEnvironmentUserName + "--username", + developmentEnvironmentUserName ] } @@ -396,18 +458,18 @@ runServer { tasks.withType(JavaExec).configureEach { javaLauncher.set( - javaToolchains.launcherFor { - languageVersion = projectJavaVersion - } + javaToolchains.launcherFor { + languageVersion = projectJavaVersion + } ) } -processResources -{ +processResources { // this will ensure that this task is redone when the versions change. inputs.property "version", project.version inputs.property "mcversion", project.minecraft.version - + exclude("spotless.gradle") + // replace stuff in mcmod.info, nothing else from(sourceSets.main.resources.srcDirs) { include 'mcmod.info' @@ -419,43 +481,44 @@ processResources "modName": modName } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { from refMap } // copy everything else that's not the mcmod.info from(sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' + exclude 'spotless.gradle' } } def getManifestAttributes() { def manifestAttributes = [:] - if(containsMixinsAndOrCoreModOnly.toBoolean() == false && (usesMixins.toBoolean() || coreModClass)) { + if (!containsMixinsAndOrCoreModOnly.toBoolean() && (usesMixins.toBoolean() || coreModClass)) { manifestAttributes += ["FMLCorePluginContainsFMLMod": true] } - if(accessTransformersFile) { - manifestAttributes += ["FMLAT" : accessTransformersFile.toString()] + if (accessTransformersFile) { + manifestAttributes += ["FMLAT": accessTransformersFile.toString()] } - if(coreModClass) { + if (coreModClass) { manifestAttributes += ["FMLCorePlugin": modGroup + "." + coreModClass] } - if(usesMixins.toBoolean()) { + if (usesMixins.toBoolean()) { manifestAttributes += [ - "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", - "MixinConfigs" : "mixins." + modId + ".json", - "ForceLoadAsMod" : containsMixinsAndOrCoreModOnly.toBoolean() == false + "TweakClass" : "org.spongepowered.asm.launch.MixinTweaker", + "MixinConfigs" : "mixins." + modId + ".json", + "ForceLoadAsMod": !containsMixinsAndOrCoreModOnly.toBoolean() ] } return manifestAttributes } task sourcesJar(type: Jar) { - from (sourceSets.main.allJava) - from (file("$projectDir/LICENSE")) + from(sourceSets.main.allSource) + from(file("$projectDir/LICENSE")) getArchiveClassifier().set('sources') } @@ -474,7 +537,10 @@ task shadowDevJar(type: ShadowJar) { } minimize() // This will only allow shading for actually used classes - configurations = [project.configurations.shadowImplementation, project.configurations.shadowCompile] + configurations = [ + project.configurations.shadowImplementation, + project.configurations.shadowCompile + ] } task relocateShadowDevJar(type: ConfigureShadowRelocation) { @@ -502,22 +568,22 @@ task devJar(type: Jar) { attributes(getManifestAttributes()) } - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { dependsOn(circularResolverJar) enabled = false } } task apiJar(type: Jar) { - from (sourceSets.main.allJava) { - include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**' + from(sourceSets.main.allSource) { + include modGroupPath + "/" + apiPackagePath + '/**' } - from (sourceSets.main.output) { - include modGroup.toString().replaceAll("\\.", "/") + "/" + apiPackage.toString().replaceAll("\\.", "/") + '/**' + from(sourceSets.main.output) { + include modGroupPath + "/" + apiPackagePath + '/**' } - from (sourceSets.main.resources.srcDirs) { + from(sourceSets.main.resources.srcDirs) { include("LICENSE") } @@ -525,30 +591,33 @@ task apiJar(type: Jar) { } artifacts { - if(!noPublishedSources) { + if (!noPublishedSources) { archives sourcesJar } archives devJar - if(apiPackage) { + if (apiPackage) { archives apiJar } } -// The gradle metadata includes all of the additional deps that we disabled from POM generation (including forgeBin with no groupID), +// The gradle metadata includes all of the additional deps that we disabled from POM generation (including forgeBin with no groupID), // and isn't strictly needed with the POM so just disable it. tasks.withType(GenerateModuleMetadata) { enabled = false } +// workaround variable hiding in pom processing +def projectConfigs = project.configurations + publishing { publications { maven(MavenPublication) { from components.java - if(usesShadowedDependencies.toBoolean()) { + if (usesShadowedDependencies.toBoolean()) { artifact source: shadowJar, classifier: "" } - if(!noPublishedSources) { - artifact source: sourcesJar, classifier: "src" + if (!noPublishedSources) { + artifact source: sourcesJar, classifier: "sources" } artifact source: usesShadowedDependencies.toBoolean() ? shadowDevJar : devJar, classifier: "dev" if (apiPackage) { @@ -559,17 +628,24 @@ publishing { artifactId = System.getenv("ARTIFACT_ID") ?: project.name // Using the identified version, not project.version as it has the prepended 1.7.10 version = System.getenv("RELEASE_VERSION") ?: identifiedVersion - - // remove extra garbage from who knows where + + // remove extra garbage from minecraft and minecraftDeps configuration pom.withXml { - def badPomGroup = ['net.minecraft', 'com.google.code.findbugs', 'org.ow2.asm', 'com.typesafe.akka', 'com.typesafe', 'org.scala-lang', - 'org.scala-lang.plugins', 'net.sf.jopt-simple', 'lzma', 'com.mojang', 'org.apache.commons', 'org.apache.httpcomponents', - 'commons-logging', 'java3d', 'net.sf.trove4j', 'com.ibm.icu', 'com.paulscode', 'io.netty', 'com.google.guava', - 'commons-io', 'commons-codec', 'net.java.jinput', 'net.java.jutils', 'com.google.code.gson', 'org.apache.logging.log4j', - 'org.lwjgl.lwjgl', 'tv.twitch', ''] + def badArtifacts = [:].withDefault { [] as Set } + for (configuration in [ + projectConfigs.minecraft, + projectConfigs.minecraftDeps + ]) { + for (dependency in configuration.allDependencies) { + badArtifacts[dependency.group == null ? "" : dependency.group] += dependency.name + } + } + // example for specifying extra stuff to ignore + // badArtifacts["org.example.group"] += "artifactName" + Node pomNode = asNode() pomNode.dependencies.'*'.findAll() { - badPomGroup.contains(it.groupId.text()) + badArtifacts[it.groupId.text()].contains(it.artifactId.text()) }.each() { it.parent().remove(it) } @@ -588,6 +664,107 @@ publishing { } } +if (modrinthProjectId.size() != 0 && System.getenv("MODRINTH_TOKEN") != null) { + apply plugin: 'com.modrinth.minotaur' + + File changelogFile = new File(System.getenv("CHANGELOG_FILE") ?: "CHANGELOG.md") + + modrinth { + token = System.getenv("MODRINTH_TOKEN") + projectId = modrinthProjectId + versionNumber = identifiedVersion + versionType = identifiedVersion.endsWith("-pre") ? "beta" : "release" + changelog = changelogFile.exists() ? changelogFile.getText("UTF-8") : "" + uploadFile = jar + additionalFiles = getSecondaryArtifacts() + gameVersions = [minecraftVersion] + loaders = ["forge"] + debugMode = false + } + + if (modrinthRelations.size() != 0) { + String[] deps = modrinthRelations.split(";") + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(":") + String[] qual = parts[0].split("-") + addModrinthDep(qual[0], qual[1], parts[1]) + } + } + tasks.modrinth.dependsOn(build) + tasks.publish.dependsOn(tasks.modrinth) +} + +if (curseForgeProjectId.size() != 0 && System.getenv("CURSEFORGE_TOKEN") != null) { + apply plugin: 'com.matthewprenger.cursegradle' + + File changelogFile = new File(System.getenv("CHANGELOG_FILE") ?: "CHANGELOG.md") + + curseforge { + apiKey = System.getenv("CURSEFORGE_TOKEN") + project { + id = curseForgeProjectId + if (changelogFile.exists()) { + changelogType = "markdown" + changelog = changelogFile + } + releaseType = identifiedVersion.endsWith("-pre") ? "beta" : "release" + addGameVersion minecraftVersion + addGameVersion "Forge" + mainArtifact jar + for (artifact in getSecondaryArtifacts()) addArtifact artifact + } + + options { + javaIntegration = false + forgeGradleIntegration = false + debug = false + } + } + + if (curseForgeRelations.size() != 0) { + String[] deps = curseForgeRelations.split(";") + deps.each { dep -> + if (dep.size() == 0) { + return + } + String[] parts = dep.split(":") + addCurseForgeRelation(parts[0], parts[1]) + } + } + tasks.curseforge.dependsOn(build) + tasks.publish.dependsOn(tasks.curseforge) +} + +def addModrinthDep(scope, type, name) { + com.modrinth.minotaur.dependencies.Dependency dep; + if (!(scope in ["required", "optional", "incompatible", "embedded"])) { + throw new Exception("Invalid modrinth dependency scope: " + scope) + } + switch (type) { + case "project": + dep = new ModDependency(name, scope) + break + case "version": + dep = new VersionDependency(name, scope) + break + default: + throw new Exception("Invalid modrinth dependency type: " + type) + } + project.modrinth.dependencies.add(dep) +} + +def addCurseForgeRelation(type, name) { + if (!(type in ["requiredDependency", "embeddedLibrary", "optionalDependency", "tool", "incompatible"])) { + throw new Exception("Invalid CurseForge relation type: " + type) + } + CurseArtifact artifact = project.curseforge.curseProjects[0].mainArtifact + CurseRelation rel = (artifact.curseRelations ?: (artifact.curseRelations = new CurseRelation())) + rel."$type"(name) +} + // Updating task updateBuildScript { doLast { @@ -597,23 +774,60 @@ task updateBuildScript { } } -if (isNewBuildScriptVersionAvailable(projectDir.toString())) { +if (!project.getGradle().startParameter.isOffline() && isNewBuildScriptVersionAvailable(projectDir.toString())) { if (autoUpdateBuildScript.toBoolean()) { performBuildScriptUpdate(projectDir.toString()) } else { - println("Build script update available! Run 'gradle updateBuildScript'") + out.style(Style.SuccessHeader).println("Build script update available! Run 'gradle updateBuildScript'") } } static URL availableBuildScriptUrl() { - new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/main/build.gradle") + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/build.gradle") +} + +static URL exampleSettingsGradleUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/settings.gradle.example") +} + +static URL exampleGitAttributesUrl() { + new URL("https://raw.githubusercontent.com/GTNewHorizons/ExampleMod1.7.10/master/.gitattributes") +} + + +boolean verifyGitAttributes() { + def gitattributesFile = getFile(".gitattributes") + if (!gitattributesFile.exists()) { + println("Downloading default .gitattributes") + exampleGitAttributesUrl().withInputStream { i -> gitattributesFile.withOutputStream { it << i } } + exec { + workingDir '.' + commandLine 'git', 'add', '--renormalize', '.' + } + return true + } + return false +} + +boolean verifySettingsGradle() { + def settingsFile = getFile("settings.gradle") + if (!settingsFile.exists()) { + println("Downloading default settings.gradle") + exampleSettingsGradleUrl().withInputStream { i -> settingsFile.withOutputStream { it << i } } + return true + } + return false } boolean performBuildScriptUpdate(String projectDir) { if (isNewBuildScriptVersionAvailable(projectDir)) { def buildscriptFile = getFile("build.gradle") availableBuildScriptUrl().withInputStream { i -> buildscriptFile.withOutputStream { it << i } } - print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + out.style(Style.Success).print("Build script updated. Please REIMPORT the project or RESTART your IDE!") + boolean settingsupdated = verifySettingsGradle() + settingsupdated = verifyGitAttributes() || settingsupdated + if (settingsupdated) + throw new GradleException("Settings has been updated, please re-run task.") return true } return false @@ -633,7 +847,7 @@ boolean isNewBuildScriptVersionAvailable(String projectDir) { static String getVersionHash(String buildScriptContent) { String versionLine = buildScriptContent.find("^//version: [a-z0-9]*") - if(versionLine != null) { + if (versionLine != null) { return versionLine.split(": ").last() } return "" @@ -644,7 +858,103 @@ configure(updateBuildScript) { description = 'Updates the build script to the latest version' } -// Deobfuscation +// Parameter Deobfuscation + +task deobfParams { + doLast { + + String mcpDir = "$project.gradle.gradleUserHomeDir/caches/minecraft/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion" + String mcpZIP = "$mcpDir/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + String paramsCSV = "$mcpDir/params.csv" + + download.run { + src "https://maven.minecraftforge.net/de/oceanlabs/mcp/mcp_$channel/$mappingsVersion-$minecraftVersion/mcp_$channel-$mappingsVersion-${minecraftVersion}.zip" + dest mcpZIP + overwrite false + } + + if (!file(paramsCSV).exists()) { + println("Extracting MCP archive ...") + unzip(mcpZIP, mcpDir) + } + + println("Parsing params.csv ...") + Map params = new HashMap<>() + Files.lines(Paths.get(paramsCSV)).forEach { line -> + String[] cells = line.split(",") + if (cells.length > 2 && cells[0].matches("p_i?\\d+_\\d+_")) { + params.put(cells[0], cells[1]) + } + } + + out.style(Style.Success).println("Modified ${replaceParams(file("$projectDir/src/main/java"), params)} files!") + out.style(Style.Failure).println("Don't forget to verify that the code still works as before!\n It could be broken due to duplicate variables existing now\n or parameters taking priority over other variables.") + } +} + +static int replaceParams(File file, Map params) { + int fileCount = 0 + + if (file.isDirectory()) { + for (File f : file.listFiles()) { + fileCount += replaceParams(f, params) + } + return fileCount + } + println("Visiting ${file.getName()} ...") + try { + String content = new String(Files.readAllBytes(file.toPath())) + int hash = content.hashCode() + params.forEach { key, value -> + content = content.replaceAll(key, value) + } + if (hash != content.hashCode()) { + Files.write(file.toPath(), content.getBytes("UTF-8")) + return 1 + } + } catch (Exception e) { + e.printStackTrace() + } + return 0 +} + +// Credit: bitsnaps (https://gist.github.com/bitsnaps/00947f2dce66f4bbdabc67d7e7b33681) +static unzip(String zipFileName, String outputDir) { + byte[] buffer = new byte[16384] + ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName)) + ZipEntry zipEntry = zis.getNextEntry() + while (zipEntry != null) { + File newFile = new File(outputDir + File.separator, zipEntry.name) + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory $newFile") + } + } else { + // fix for Windows-created archives + File parent = newFile.parentFile + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory $parent") + } + // write file content + FileOutputStream fos = new FileOutputStream(newFile) + int len = 0 + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len) + } + fos.close() + } + zipEntry = zis.getNextEntry() + } + zis.closeEntry() + zis.close() +} + +configure(deobfParams) { + group = 'forgegradle' + description = 'Rename all obfuscated parameter names inherited from Minecraft classes' +} + +// Dependency Deobfuscation def deobf(String sourceURL) { try { @@ -653,42 +963,57 @@ def deobf(String sourceURL) { //get rid of directories: int lastSlash = fileName.lastIndexOf("/") - if(lastSlash > 0) { + if (lastSlash > 0) { fileName = fileName.substring(lastSlash + 1) } //get rid of extension: - if(fileName.endsWith(".jar")) { + if (fileName.endsWith(".jar") || fileName.endsWith(".litemod")) { fileName = fileName.substring(0, fileName.lastIndexOf(".")) } String hostName = url.getHost() - if(hostName.startsWith("www.")) { + if (hostName.startsWith("www.")) { hostName = hostName.substring(4) } List parts = Arrays.asList(hostName.split("\\.")) Collections.reverse(parts) hostName = String.join(".", parts) - return deobf(sourceURL, hostName + "/" + fileName) - } catch(Exception e) { - return deobf(sourceURL, "deobf/" + String.valueOf(sourceURL.hashCode())) + return deobf(sourceURL, "$hostName/$fileName") + } catch (Exception e) { + return deobf(sourceURL, "deobf/${sourceURL.hashCode()}") } } // The method above is to be preferred. Use this method if the filename is not at the end of the URL. -def deobf(String sourceURL, String fileName) { - String cacheDir = System.getProperty("user.home") + "/.gradle/caches/" - String bon2Dir = cacheDir + "forge_gradle/deobf" - String bon2File = bon2Dir + "/BON2-2.5.0.jar" - String obfFile = cacheDir + "modules-2/files-2.1/" + fileName + ".jar" - String deobfFile = cacheDir + "modules-2/files-2.1/" + fileName + "-deobf.jar" - - if(file(deobfFile).exists()) { +def deobf(String sourceURL, String rawFileName) { + String bon2Version = "2.5.1" + String fileName = URLDecoder.decode(rawFileName, "UTF-8") + String cacheDir = "$project.gradle.gradleUserHomeDir/caches" + String bon2Dir = "$cacheDir/forge_gradle/deobf" + String bon2File = "$bon2Dir/BON2-${bon2Version}.jar" + String obfFile = "$cacheDir/modules-2/files-2.1/${fileName}.jar" + String deobfFile = "$cacheDir/modules-2/files-2.1/${fileName}-deobf.jar" + + if (file(deobfFile).exists()) { return files(deobfFile) } + String mappingsVer + String remoteMappings = project.hasProperty('remoteMappings') ? project.remoteMappings : 'https://raw.githubusercontent.com/MinecraftForge/FML/1.7.10/conf/' + if (remoteMappings) { + String id = "${forgeVersion.split("\\.")[3]}-$minecraftVersion" + String mappingsZIP = "$cacheDir/forge_gradle/maven_downloader/de/oceanlabs/mcp/mcp_snapshot_nodoc/$id/mcp_snapshot_nodoc-${id}.zip" + + zipMappings(mappingsZIP, remoteMappings, bon2Dir) + + mappingsVer = "snapshot_$id" + } else { + mappingsVer = "${channel}_$mappingsVersion" + } + download.run { - src 'https://github.com/GTNewHorizons/BON2/releases/download/2.5.0/BON2-2.5.0.CUSTOM-all.jar' + src "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases/com/github/parker8283/BON2/$bon2Version-CUSTOM/BON2-$bon2Version-CUSTOM-all.jar" dest bon2File quiet true overwrite false @@ -702,22 +1027,71 @@ def deobf(String sourceURL, String fileName) { } exec { - commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', '1.7.10', '--mappingsVer', 'stable_12', '--notch' + commandLine 'java', '-jar', bon2File, '--inputJar', obfFile, '--outputJar', deobfFile, '--mcVer', minecraftVersion, '--mappingsVer', mappingsVer, '--notch' workingDir bon2Dir - standardOutput = new ByteArrayOutputStream() + standardOutput = new FileOutputStream("${deobfFile}.log") } return files(deobfFile) } +def zipMappings(String zipPath, String url, String bon2Dir) { + File zipFile = new File(zipPath) + if (zipFile.exists()) { + return + } + + String fieldsCache = "$bon2Dir/data/fields.csv" + String methodsCache = "$bon2Dir/data/methods.csv" + + download.run { + src "${url}fields.csv" + dest fieldsCache + quiet true + } + download.run { + src "${url}methods.csv" + dest methodsCache + quiet true + } + + zipFile.getParentFile().mkdirs() + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)) + + zos.putNextEntry(new ZipEntry("fields.csv")) + Files.copy(Paths.get(fieldsCache), zos) + zos.closeEntry() + + zos.putNextEntry(new ZipEntry("methods.csv")) + Files.copy(Paths.get(methodsCache), zos) + zos.closeEntry() + + zos.close() +} + // Helper methods def checkPropertyExists(String propertyName) { - if (project.hasProperty(propertyName) == false) { + if (!project.hasProperty(propertyName)) { throw new GradleException("This project requires a property \"" + propertyName + "\"! Please add it your \"gradle.properties\". You can find all properties and their description here: https://github.com/GTNewHorizons/ExampleMod1.7.10/blob/main/gradle.properties") } } +def propertyDefaultIfUnset(String propertyName, defaultValue) { + if (!project.hasProperty(propertyName) || project.property(propertyName) == "") { + project.ext.setProperty(propertyName, defaultValue) + } +} + def getFile(String relativePath) { return new File(projectDir, relativePath) } + +def getSecondaryArtifacts() { + // Because noPublishedSources from the beginning of the script is somehow not visible here... + boolean noPublishedSources = project.hasProperty("noPublishedSources") ? project.noPublishedSources.toBoolean() : false + def secondaryArtifacts = [devJar] + if (!noPublishedSources) secondaryArtifacts += [sourcesJar] + if (apiPackage) secondaryArtifacts += [apiJar] + return secondaryArtifacts +} diff --git a/dependencies.gradle b/dependencies.gradle index 67a923f..7b6c62c 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -3,6 +3,6 @@ dependencies { api('com.github.GTNewHorizons:NotEnoughItems:2.2.6-GTNH:dev') - implementation('com.github.GTNewHorizons:ForestryMC:4.4.5:dev') + implementation('com.github.GTNewHorizons:ForestryMC:4.5.3:dev') implementation('com.github.GTNewHorizons:waila:1.5.18:dev') } diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..93c852a --- /dev/null +++ b/settings.gradle @@ -0,0 +1,10 @@ +plugins { + id 'com.diffplug.blowdryerSetup' version '1.6.0' +} + +apply plugin: 'com.diffplug.blowdryerSetup' + +blowdryerSetup { + github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.5') + //devLocal '.' // Use this when testing config updates locally +} diff --git a/src/main/scala/net/bdew/neiaddons/BaseAddon.java b/src/main/scala/net/bdew/neiaddons/BaseAddon.java index 25bec82..3d3f106 100644 --- a/src/main/scala/net/bdew/neiaddons/BaseAddon.java +++ b/src/main/scala/net/bdew/neiaddons/BaseAddon.java @@ -15,12 +15,11 @@ import cpw.mods.fml.common.versioning.ArtifactVersion; import cpw.mods.fml.common.versioning.VersionParser; import cpw.mods.fml.relauncher.Side; +import java.util.Map; import net.bdew.neiaddons.api.NEIAddon; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; -import java.util.Map; - public abstract class BaseAddon implements NEIAddon { protected boolean active = false; @@ -98,12 +97,16 @@ protected boolean verifyModVersion(String spec) { ArtifactVersion found = modlist.get(modid).getProcessedVersion(); if (found == null) { - logInfo("Unable to determine version of required mod %s, dependent features will be unavailable", req.getLabel()); + logInfo( + "Unable to determine version of required mod %s, dependent features will be unavailable", + req.getLabel()); return false; } if (!req.containsVersion(found)) { - logInfo("Version mismatch: %s is required while %s was detected, dependent features will be unavailable", req.toString(), found.getVersionString()); + logInfo( + "Version mismatch: %s is required while %s was detected, dependent features will be unavailable", + req.toString(), found.getVersionString()); return false; } @@ -115,4 +118,4 @@ protected boolean verifyModVersion(String spec) { public boolean isEnabledByDefault() { return true; } -} \ No newline at end of file +} diff --git a/src/main/scala/net/bdew/neiaddons/NEIAddons.java b/src/main/scala/net/bdew/neiaddons/NEIAddons.java index fb2c23a..e10cd64 100644 --- a/src/main/scala/net/bdew/neiaddons/NEIAddons.java +++ b/src/main/scala/net/bdew/neiaddons/NEIAddons.java @@ -15,6 +15,8 @@ import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.relauncher.Side; +import java.util.ArrayList; +import java.util.List; import net.bdew.neiaddons.api.NEIAddon; import net.bdew.neiaddons.network.ClientHandler; import net.bdew.neiaddons.network.NetChannel; @@ -23,10 +25,11 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; -import java.util.ArrayList; -import java.util.List; - -@Mod(modid = NEIAddons.modId, name = NEIAddons.modName, version = NEIAddons.modVersion, dependencies = "after:NotEnoughItems") +@Mod( + modid = NEIAddons.modId, + name = NEIAddons.modName, + version = NEIAddons.modVersion, + dependencies = "after:NotEnoughItems") public class NEIAddons { public static final String modVersion = "GRADLETOKEN_VERSION"; @@ -85,7 +88,8 @@ public void preInit(FMLPreInitializationEvent event) { public void init(FMLInitializationEvent event) { logInfo("Loading NEI Addons"); for (NEIAddon addon : addons) { - if (config.get("Addons", addon.getName(), addon.isEnabledByDefault()).getBoolean(false)) { + if (config.get("Addons", addon.getName(), addon.isEnabledByDefault()) + .getBoolean(false)) { logInfo("Loading %s Addon...", addon.getName()); try { addon.init(event.getSide()); diff --git a/src/main/scala/net/bdew/neiaddons/Utils.java b/src/main/scala/net/bdew/neiaddons/Utils.java index 01bdc24..583f498 100644 --- a/src/main/scala/net/bdew/neiaddons/Utils.java +++ b/src/main/scala/net/bdew/neiaddons/Utils.java @@ -10,18 +10,18 @@ package net.bdew.neiaddons; import codechicken.nei.api.API; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.item.ItemStack; - import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.FontRenderer; +import net.minecraft.item.ItemStack; public class Utils { @SuppressWarnings("unchecked") - public static Class getAndCheckClass(String cls, Class sup) throws ClassNotFoundException { + public static Class getAndCheckClass(String cls, Class sup) + throws ClassNotFoundException { Class c = Class.forName(cls); if (c != null) { if (sup.isAssignableFrom(c)) { @@ -35,7 +35,8 @@ public static Class getAndCheckClass(String cls, Class T getAndCheckStaicField(String cls, String field, Class sup) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { + public static T getAndCheckStaicField(String cls, String field, Class sup) + throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { Class c = Class.forName(cls); if (c == null) throw new RuntimeException("Can't get " + cls); @@ -47,7 +48,8 @@ public static T getAndCheckStaicField(String cls, String field, Class sup if (sup.isInstance(v)) { return (T) v; } else { - throw new RuntimeException(String.format("%s.%s is of wrong type, expected: %s, got: %s", cls, field, sup, v.getClass())); + throw new RuntimeException( + String.format("%s.%s is of wrong type, expected: %s, got: %s", cls, field, sup, v.getClass())); } } @@ -57,8 +59,7 @@ public static void drawCenteredString(String s, int x, int y, int color) { } public static void safeAddNBTItem(ItemStack item) { - if (item == null) - return; + if (item == null) return; API.addItemListEntry(item); } @@ -66,16 +67,11 @@ public static void safeAddNBTItem(ItemStack item) { * Like ItemStack.isItemStackEqual but ignores stack size */ public static boolean isSameItem(ItemStack s1, ItemStack s2) { - if ((s1 == null) || (s2 == null)) - return false; - if (s1.getItem() != s2.getItem()) - return false; - if (s1.getItemDamage() != s2.getItemDamage()) - return false; - if ((s1.getTagCompound() == null) && (s2.getTagCompound() == null)) - return true; - if ((s1.getTagCompound() == null) || (s2.getTagCompound() == null)) - return false; + if ((s1 == null) || (s2 == null)) return false; + if (s1.getItem() != s2.getItem()) return false; + if (s1.getItemDamage() != s2.getItemDamage()) return false; + if ((s1.getTagCompound() == null) && (s2.getTagCompound() == null)) return true; + if ((s1.getTagCompound() == null) || (s2.getTagCompound() == null)) return false; return s1.getTagCompound().equals(s2.getTagCompound()); } @@ -88,7 +84,8 @@ public static Map mergeStacks(Map stacks) { continue; } for (Entry mergedStack : merged.entrySet()) { - if (isSameItem(stack.getKey(), mergedStack.getKey()) && (stack.getValue().equals(mergedStack.getValue()))) { + if (isSameItem(stack.getKey(), mergedStack.getKey()) + && (stack.getValue().equals(mergedStack.getValue()))) { mergedStack.getKey().stackSize += 1; continue outer; } diff --git a/src/main/scala/net/bdew/neiaddons/appeng/AddonAppeng.java b/src/main/scala/net/bdew/neiaddons/appeng/AddonAppeng.java index 23afd80..0476f7d 100644 --- a/src/main/scala/net/bdew/neiaddons/appeng/AddonAppeng.java +++ b/src/main/scala/net/bdew/neiaddons/appeng/AddonAppeng.java @@ -15,6 +15,7 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.lang.reflect.Method; import net.bdew.neiaddons.BaseAddon; import net.bdew.neiaddons.NEIAddons; import net.bdew.neiaddons.Utils; @@ -23,9 +24,11 @@ import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; -import java.lang.reflect.Method; - -@Mod(modid = NEIAddons.modId + "|AppEng", name = NEIAddons.modName + ": Applied Energistics 2", version = NEIAddons.modVersion, dependencies = "after:NEIAddons;after:appliedenergistics2") +@Mod( + modid = NEIAddons.modId + "|AppEng", + name = NEIAddons.modName + ": Applied Energistics 2", + version = NEIAddons.modVersion, + dependencies = "after:NEIAddons;after:appliedenergistics2") public class AddonAppeng extends BaseAddon { @Instance(NEIAddons.modId + "|AppEng") @@ -45,7 +48,7 @@ public String getName() { @Override public String[] getDependencies() { - return new String[]{"appliedenergistics2"}; + return new String[] {"appliedenergistics2"}; } @Override diff --git a/src/main/scala/net/bdew/neiaddons/appeng/AppEngGuiHandler.java b/src/main/scala/net/bdew/neiaddons/appeng/AppEngGuiHandler.java index 173c51e..31e0669 100644 --- a/src/main/scala/net/bdew/neiaddons/appeng/AppEngGuiHandler.java +++ b/src/main/scala/net/bdew/neiaddons/appeng/AppEngGuiHandler.java @@ -27,32 +27,33 @@ public boolean handleDragNDrop(GuiContainer gui, int mouseX, int mouseY, ItemSta if (AddonAppeng.clsBaseGui.isInstance(gui)) { final Slot currentSlot = getSlotAtPosition(gui, mouseX, mouseY); - if (currentSlot != null && AddonAppeng.clsSlotFake.isInstance(currentSlot) && SlotHelper.isSlotEnabled(currentSlot)) { + if (currentSlot != null + && AddonAppeng.clsSlotFake.isInstance(currentSlot) + && SlotHelper.isSlotEnabled(currentSlot)) { if (ClientHandler.enabledCommands.contains(AddonAppeng.setWorkbenchCommand)) { final ItemStack stack = draggedStack.copy(); stack.stackSize = Math.min(stack.stackSize, 127); - if (button == 0) { //left + if (button == 0) { // left setWorkbenchCommand(currentSlot.slotNumber, stack, true); - } else if (button == 1) { //right + } else if (button == 1) { // right stack.stackSize = 1; setWorkbenchCommand(currentSlot.slotNumber, stack, false); - } else if (button == 2) { //middle + } else if (button == 2) { // middle setWorkbenchCommand(currentSlot.slotNumber, stack, true); draggedStack.stackSize -= stack.stackSize; } - + return true; } else { - Minecraft.getMinecraft().thePlayer.addChatMessage( - new ChatComponentTranslation("bdew.neiaddons.noserver").setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED)) - ); + Minecraft.getMinecraft() + .thePlayer + .addChatMessage(new ChatComponentTranslation("bdew.neiaddons.noserver") + .setChatStyle(new ChatStyle().setColor(EnumChatFormatting.RED))); } - } - } return super.handleDragNDrop(gui, mouseX, mouseY, draggedStack, button); @@ -68,8 +69,7 @@ private boolean isMouseOverSlot(GuiContainer gui, Slot slot, int mouseX, int mou return mouseX >= slotX - 1 && mouseX < slotX + slotW + 1 && mouseY >= slotY - 1 && mouseY < slotY + slotH + 1; } - private void setWorkbenchCommand(int slotNum, ItemStack stack, boolean replace) - { + private void setWorkbenchCommand(int slotNum, ItemStack stack, boolean replace) { NBTTagCompound message = new NBTTagCompound(); message.setInteger("slot", slotNum); message.setBoolean("replace", replace); @@ -81,17 +81,15 @@ private void setWorkbenchCommand(int slotNum, ItemStack stack, boolean replace) PacketHelper.sendToServer(AddonAppeng.setWorkbenchCommand, message); } - private Slot getSlotAtPosition(GuiContainer gui, int x, int y) - { - for (int k = 0; k < gui.inventorySlots.inventorySlots.size(); ++k) { - Slot slot = (Slot)gui.inventorySlots.inventorySlots.get(k); - - if (isMouseOverSlot(gui, slot, x, y)) { - return slot; - } - } + private Slot getSlotAtPosition(GuiContainer gui, int x, int y) { + for (int k = 0; k < gui.inventorySlots.inventorySlots.size(); ++k) { + Slot slot = (Slot) gui.inventorySlots.inventorySlots.get(k); - return null; - } + if (isMouseOverSlot(gui, slot, x, y)) { + return slot; + } + } + return null; + } } diff --git a/src/main/scala/net/bdew/neiaddons/botany/AddonBotany.java b/src/main/scala/net/bdew/neiaddons/botany/AddonBotany.java index ad232b9..0fea4de 100644 --- a/src/main/scala/net/bdew/neiaddons/botany/AddonBotany.java +++ b/src/main/scala/net/bdew/neiaddons/botany/AddonBotany.java @@ -21,7 +21,11 @@ import net.bdew.neiaddons.botany.flowers.FlowerHelper; import net.minecraft.client.resources.I18n; -@Mod(modid = NEIAddons.modId + "|Botany", name = NEIAddons.modName + ": Botany", version = NEIAddons.modVersion, dependencies = "after:NEIAddons;after:Botany") +@Mod( + modid = NEIAddons.modId + "|Botany", + name = NEIAddons.modName + ": Botany", + version = NEIAddons.modVersion, + dependencies = "after:NEIAddons;after:Botany") public class AddonBotany extends BaseAddon { public static boolean showFlowerMutations; public static boolean loadBlacklisted; @@ -41,7 +45,7 @@ public String getName() { @Override public String[] getDependencies() { - return new String[]{"Botany"}; + return new String[] {"Botany"}; } @Override @@ -52,15 +56,27 @@ public void preInit(FMLPreInitializationEvent ev) { @Override public void init(Side side) throws Exception { - showFlowerMutations = NEIAddons.config.get(getName(), "Show Flower Mutations", true, "Set to false to disable flower mutations browsing").getBoolean(false); + showFlowerMutations = NEIAddons.config + .get(getName(), "Show Flower Mutations", true, "Set to false to disable flower mutations browsing") + .getBoolean(false); - loadBlacklisted = NEIAddons.config.get(getName(), "Load blacklisted", false, "Set to true to load blacklisted species and alleles, it's dangerous and (mostly) useless").getBoolean(false); + loadBlacklisted = NEIAddons.config + .get( + getName(), + "Load blacklisted", + false, + "Set to true to load blacklisted species and alleles, it's dangerous and (mostly) useless") + .getBoolean(false); active = true; } public void registerWithNEIPlugins(String name, String id) { - FMLInterModComms.sendRuntimeMessage(this, "NEIPlugins", "register-crafting-handler", String.format("%s@%s@%s", I18n.format("bdew.neiaddons.genetics"), name, id)); + FMLInterModComms.sendRuntimeMessage( + this, + "NEIPlugins", + "register-crafting-handler", + String.format("%s@%s@%s", I18n.format("bdew.neiaddons.genetics"), name, id)); } @Override diff --git a/src/main/scala/net/bdew/neiaddons/botany/flowers/FlowerHelper.java b/src/main/scala/net/bdew/neiaddons/botany/flowers/FlowerHelper.java index e9f8fd1..f8a450b 100644 --- a/src/main/scala/net/bdew/neiaddons/botany/flowers/FlowerHelper.java +++ b/src/main/scala/net/bdew/neiaddons/botany/flowers/FlowerHelper.java @@ -44,7 +44,8 @@ public static void setup() { FlowerBreedingHandler breedingRecipeHandler = new FlowerBreedingHandler(); API.registerRecipeHandler(breedingRecipeHandler); API.registerUsageHandler(breedingRecipeHandler); - AddonBotany.instance.registerWithNEIPlugins(breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); + AddonBotany.instance.registerWithNEIPlugins( + breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); } API.addOption(new MutationDumper(root, "flower_mutation")); diff --git a/src/main/scala/net/bdew/neiaddons/crafting/AddonCraftingTables.java b/src/main/scala/net/bdew/neiaddons/crafting/AddonCraftingTables.java index dcf77c8..fe32e82 100644 --- a/src/main/scala/net/bdew/neiaddons/crafting/AddonCraftingTables.java +++ b/src/main/scala/net/bdew/neiaddons/crafting/AddonCraftingTables.java @@ -14,16 +14,18 @@ import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; +import java.util.ArrayList; +import java.util.Collection; import net.bdew.neiaddons.BaseAddon; import net.bdew.neiaddons.NEIAddons; import net.bdew.neiaddons.Utils; -import net.bdew.neiaddons.api.NEIAddon; import net.minecraft.client.gui.inventory.GuiContainer; -import java.util.ArrayList; -import java.util.Collection; - -@Mod(modid = NEIAddons.modId + "|CraftingTables", name = NEIAddons.modName + ": Crafting Tables", version = NEIAddons.modVersion, dependencies = "after:NEIAddons") +@Mod( + modid = NEIAddons.modId + "|CraftingTables", + name = NEIAddons.modName + ": Crafting Tables", + version = NEIAddons.modVersion, + dependencies = "after:NEIAddons") public class AddonCraftingTables extends BaseAddon { public static Collection> craftingTables; @@ -62,13 +64,13 @@ public void init(Side side) throws Exception { tryLoadTableClass("EE3", "com.pahimar.ee3.client.gui.inventory.GuiPortableCrafting", "EE3 Minium Stone"); tryLoadTableClass("BuildCraft|Factory", "buildcraft.factory.gui.GuiAutoCrafting", "BC Autorcrafting Table"); - tryLoadTableClass("powersuitaddons", "com.qmxtech.powersuitaddons.client.PortableCraftingGui", "MPSA In-Place Assembler"); + tryLoadTableClass( + "powersuitaddons", "com.qmxtech.powersuitaddons.client.PortableCraftingGui", "MPSA In-Place Assembler"); tryLoadTableClass("ProjectE", "moze_intel.projecte.gameObjs.gui.GUIPhilosStone", "ProjectE Philosopher Stone"); tryLoadTableClass("BiblioCraft", "jds.bibliocraft.gui.GuiFancyWorkbench", "BiblioCraft Fancy Workbench"); tryLoadTableClass("RIO", "remoteio.client.gui.GuiIntelligentWorkbench", "RemoteIO Intelligent Workbench"); tryLoadTableClass("Railcraft", "mods.railcraft.client.gui.GuiCartWork", "Railcraft Work Cart"); - if (craftingTables.size() > 0) { logInfo("%d crafting tables registered", craftingTables.size()); active = true; diff --git a/src/main/scala/net/bdew/neiaddons/developer/AddonDeveloper.java b/src/main/scala/net/bdew/neiaddons/developer/AddonDeveloper.java index c7a4b5c..be0aef5 100644 --- a/src/main/scala/net/bdew/neiaddons/developer/AddonDeveloper.java +++ b/src/main/scala/net/bdew/neiaddons/developer/AddonDeveloper.java @@ -18,7 +18,11 @@ import net.bdew.neiaddons.BaseAddon; import net.bdew.neiaddons.NEIAddons; -@Mod(modid = NEIAddons.modId + "|Developer", name = NEIAddons.modName + ": Developer Tools", version = NEIAddons.modVersion, dependencies = "after:NEIAddons") +@Mod( + modid = NEIAddons.modId + "|Developer", + name = NEIAddons.modName + ": Developer Tools", + version = NEIAddons.modVersion, + dependencies = "after:NEIAddons") public class AddonDeveloper extends BaseAddon { @Instance(NEIAddons.modId + "|Developer") diff --git a/src/main/scala/net/bdew/neiaddons/developer/DeveloperGuiHandler.java b/src/main/scala/net/bdew/neiaddons/developer/DeveloperGuiHandler.java index bed0df6..7968738 100644 --- a/src/main/scala/net/bdew/neiaddons/developer/DeveloperGuiHandler.java +++ b/src/main/scala/net/bdew/neiaddons/developer/DeveloperGuiHandler.java @@ -10,13 +10,12 @@ package net.bdew.neiaddons.developer; import codechicken.nei.guihook.IContainerTooltipHandler; +import java.util.List; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; -import java.util.List; - public class DeveloperGuiHandler implements IContainerTooltipHandler { @Override public List handleTooltip(GuiContainer gui, int x, int y, List tip) { @@ -36,8 +35,7 @@ public List handleTooltip(GuiContainer gui, int x, int y, List t tip.add("S: " + slot.getClass().getSimpleName()); if (slot.inventory != null) tip.add(String.format("I: %s (#%d)", slot.inventory.getClass().getSimpleName(), slot.getSlotIndex())); - else - tip.add(String.format("%sI: NULL", EnumChatFormatting.RED)); + else tip.add(String.format("%sI: NULL", EnumChatFormatting.RED)); tip.add(String.format("%d/%d", slot.xDisplayPosition, slot.yDisplayPosition)); } return tip; @@ -49,7 +47,8 @@ public List handleItemDisplayName(GuiContainer guiContainer, ItemStack i } @Override - public List handleItemTooltip(GuiContainer guiContainer, ItemStack itemStack, int i, int i1, List list) { + public List handleItemTooltip( + GuiContainer guiContainer, ItemStack itemStack, int i, int i1, List list) { return list; } diff --git a/src/main/scala/net/bdew/neiaddons/exnihilo/AddonExnihilo.java b/src/main/scala/net/bdew/neiaddons/exnihilo/AddonExnihilo.java index baa826a..9c3f131 100644 --- a/src/main/scala/net/bdew/neiaddons/exnihilo/AddonExnihilo.java +++ b/src/main/scala/net/bdew/neiaddons/exnihilo/AddonExnihilo.java @@ -18,7 +18,11 @@ import net.bdew.neiaddons.BaseAddon; import net.bdew.neiaddons.NEIAddons; -@Mod(modid = NEIAddons.modId + "|ExNihilo", name = NEIAddons.modName + ": Ex Nihilo", version = NEIAddons.modVersion, dependencies = "after:exnihilo") +@Mod( + modid = NEIAddons.modId + "|ExNihilo", + name = NEIAddons.modName + ": Ex Nihilo", + version = NEIAddons.modVersion, + dependencies = "after:exnihilo") public class AddonExnihilo extends BaseAddon { @Mod.Instance(NEIAddons.modId + "|ExNihilo") public static AddonExnihilo instance; @@ -35,7 +39,7 @@ public boolean checkSide(Side side) { @Override public String[] getDependencies() { - return new String[]{"exnihilo", "Waila"}; + return new String[] {"exnihilo", "Waila"}; } @EventHandler diff --git a/src/main/scala/net/bdew/neiaddons/exnihilo/WailaHandler.java b/src/main/scala/net/bdew/neiaddons/exnihilo/WailaHandler.java index c9ded16..e1e0919 100644 --- a/src/main/scala/net/bdew/neiaddons/exnihilo/WailaHandler.java +++ b/src/main/scala/net/bdew/neiaddons/exnihilo/WailaHandler.java @@ -17,17 +17,17 @@ import net.minecraft.tileentity.TileEntity; public class WailaHandler { - static public Class clsTeBarrel; - static public Class clsTeCrucible; - static public Class clsTeBeeTrap; + public static Class clsTeBarrel; + public static Class clsTeCrucible; + public static Class clsTeBeeTrap; - static private void loadClasses() throws ClassNotFoundException { + private static void loadClasses() throws ClassNotFoundException { clsTeBarrel = Utils.getAndCheckClass("exnihilo.blocks.tileentities.TileEntityBarrel", TileEntity.class); clsTeCrucible = Utils.getAndCheckClass("exnihilo.blocks.tileentities.TileEntityCrucible", TileEntity.class); clsTeBeeTrap = Utils.getAndCheckClass("exnihilo.blocks.tileentities.TileEntityBeeTrap", TileEntity.class); } - static public void loadCallback(IWailaRegistrar reg) { + public static void loadCallback(IWailaRegistrar reg) { try { loadClasses(); reg.registerBodyProvider(new CrucibleHandler(), clsTeCrucible); diff --git a/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BarrelHandler.java b/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BarrelHandler.java index 54fe546..26feeba 100644 --- a/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BarrelHandler.java +++ b/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BarrelHandler.java @@ -9,6 +9,8 @@ package net.bdew.neiaddons.exnihilo.waila; +import java.text.DecimalFormat; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; @@ -22,14 +24,12 @@ import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; -import java.text.DecimalFormat; -import java.util.List; - public class BarrelHandler implements IWailaDataProvider { private DecimalFormat decFormat = new DecimalFormat("0.0"); @Override - public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) { + public NBTTagCompound getNBTData( + EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) { return tag; } @@ -39,27 +39,35 @@ public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler } @Override - public List getWailaHead(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaHead( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { return currenttip; } @Override - public List getWailaBody(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaBody( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { NBTTagCompound tag = accessor.getNBTData(); float volume = tag.getFloat("volume"); int timer = tag.getInteger("timer"); Fluid fluid = FluidRegistry.getFluid(tag.getShort("fluid")); - if (fluid != null && fluid.getID() == FluidRegistry.LAVA.getID() && volume > 0 && (accessor.getBlock().getMaterial().getCanBurn())) { - currenttip.add(EnumChatFormatting.RED + I18n.format("bdew.exnihilo.barrel.burn", decFormat.format((400F - timer) / 20)) + EnumChatFormatting.RESET); + if (fluid != null + && fluid.getID() == FluidRegistry.LAVA.getID() + && volume > 0 + && (accessor.getBlock().getMaterial().getCanBurn())) { + currenttip.add(EnumChatFormatting.RED + + I18n.format("bdew.exnihilo.barrel.burn", decFormat.format((400F - timer) / 20)) + + EnumChatFormatting.RESET); } return currenttip; } @Override - public List getWailaTail(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaTail( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { return currenttip; } } diff --git a/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BeeTrapHandler.java b/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BeeTrapHandler.java index 3333a43..1cb6340 100644 --- a/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BeeTrapHandler.java +++ b/src/main/scala/net/bdew/neiaddons/exnihilo/waila/BeeTrapHandler.java @@ -9,6 +9,8 @@ package net.bdew.neiaddons.exnihilo.waila; +import java.text.DecimalFormat; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; @@ -19,15 +21,13 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -import java.text.DecimalFormat; -import java.util.List; - public class BeeTrapHandler implements IWailaDataProvider { private static int TIMER_MAX = 6000; private DecimalFormat decFormat = new DecimalFormat("0.0"); @Override - public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) { + public NBTTagCompound getNBTData( + EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) { return tag; } @@ -37,12 +37,14 @@ public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler } @Override - public List getWailaHead(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaHead( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { return currenttip; } @Override - public List getWailaBody(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaBody( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { NBTTagCompound tag = accessor.getNBTData(); @@ -56,7 +58,8 @@ public List getWailaBody(ItemStack itemStack, List currenttip, I } @Override - public List getWailaTail(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaTail( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { return currenttip; } } diff --git a/src/main/scala/net/bdew/neiaddons/exnihilo/waila/CrucibleHandler.java b/src/main/scala/net/bdew/neiaddons/exnihilo/waila/CrucibleHandler.java index e53f095..95f31d2 100644 --- a/src/main/scala/net/bdew/neiaddons/exnihilo/waila/CrucibleHandler.java +++ b/src/main/scala/net/bdew/neiaddons/exnihilo/waila/CrucibleHandler.java @@ -9,6 +9,8 @@ package net.bdew.neiaddons.exnihilo.waila; +import java.text.DecimalFormat; +import java.util.List; import mcp.mobius.waila.api.IWailaConfigHandler; import mcp.mobius.waila.api.IWailaDataAccessor; import mcp.mobius.waila.api.IWailaDataProvider; @@ -23,14 +25,12 @@ import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; -import java.text.DecimalFormat; -import java.util.List; - public class CrucibleHandler implements IWailaDataProvider { private final DecimalFormat dec = new DecimalFormat("#,##0"); @Override - public NBTTagCompound getNBTData(EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) { + public NBTTagCompound getNBTData( + EntityPlayerMP player, TileEntity te, NBTTagCompound tag, World world, int x, int y, int z) { return tag; } @@ -40,12 +40,14 @@ public ItemStack getWailaStack(IWailaDataAccessor accessor, IWailaConfigHandler } @Override - public List getWailaHead(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaHead( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { return currenttip; } @Override - public List getWailaBody(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaBody( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { NBTTagCompound tag = accessor.getNBTData(); float solidVolume = tag.getFloat("solidVolume"); float fluidVolume = tag.getFloat("fluidVolume"); @@ -54,18 +56,23 @@ public List getWailaBody(ItemStack itemStack, List currenttip, I Fluid fluid = FluidRegistry.getFluid(tag.getShort("fluid")); if (fluid != null && fluidVolume > 0) - currenttip.add(I18n.format("bdew.exnihilo.crucible.fluid", fluid.getLocalizedName(new FluidStack(fluid, 1)), dec.format(fluidVolume))); + currenttip.add(I18n.format( + "bdew.exnihilo.crucible.fluid", + fluid.getLocalizedName(new FluidStack(fluid, 1)), + dec.format(fluidVolume))); if (!content.isEmpty() && solidVolume > 0) { ItemStack stack = new ItemStack((Block) Block.blockRegistry.getObject(content), 1, contentMeta); - currenttip.add(I18n.format("bdew.exnihilo.crucible.solid", stack.getDisplayName(), dec.format(solidVolume))); + currenttip.add( + I18n.format("bdew.exnihilo.crucible.solid", stack.getDisplayName(), dec.format(solidVolume))); } return currenttip; } @Override - public List getWailaTail(ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { + public List getWailaTail( + ItemStack itemStack, List currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) { return currenttip; } } diff --git a/src/main/scala/net/bdew/neiaddons/forestry/AddonForestry.java b/src/main/scala/net/bdew/neiaddons/forestry/AddonForestry.java index b178bce..d9f9954 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/AddonForestry.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/AddonForestry.java @@ -23,7 +23,11 @@ import net.bdew.neiaddons.forestry.trees.TreeHelper; import net.minecraft.client.resources.I18n; -@Mod(modid = NEIAddons.modId + "|Forestry", name = NEIAddons.modName + ": Forestry", version = NEIAddons.modVersion, dependencies = "after:NEIAddons;after:Forestry") +@Mod( + modid = NEIAddons.modId + "|Forestry", + name = NEIAddons.modName + ": Forestry", + version = NEIAddons.modVersion, + dependencies = "after:NEIAddons;after:Forestry") public class AddonForestry extends BaseAddon { public static boolean showSecret; public static boolean addBees; @@ -48,7 +52,7 @@ public String getName() { @Override public String[] getDependencies() { - return new String[]{"Forestry@[4.0.8.36,)"}; + return new String[] {"Forestry@[4.0.8.36,)"}; } @Override @@ -59,31 +63,76 @@ public void preInit(FMLPreInitializationEvent ev) { @Override public void init(Side side) throws Exception { - showBeeMutations = NEIAddons.config.get(getName(), "Show Bee Mutations", true, "Set to false to disable bee mutations browsing").getBoolean(false); - showBeeProducts = NEIAddons.config.get(getName(), "Show Bee Products", true, "Set to false to disable bee products browsing").getBoolean(false); - - showTreeMutations = NEIAddons.config.get(getName(), "Show Tree Mutations", true, "Set to false to disable tree mutations browsing").getBoolean(false); - showTreeProducts = NEIAddons.config.get(getName(), "Show Tree Products", true, "Set to false to disable tree products browsing").getBoolean(false); - - showButterflyMutations = NEIAddons.config.get(getName(), "Show Butterfly Mutations", true, "Set to false to disable butterfly mutations browsing").getBoolean(false); - //showButterflyProducts = NEIAddons.config.get(getName(), "Show Butterfly Products", true, "Set to false to disable butterfly products browsing").getBoolean(false); - - showSecret = NEIAddons.config.get(getName(), "Show Secret Mutations", false, "Set to true to show secret mutations").getBoolean(false); - - showReqs = NEIAddons.config.get(getName(), "Show Mutation Requirements", true, "Set to false disable display of mutation requirements").getBoolean(false); - - addBees = NEIAddons.config.get(getName(), "Add Bees to Search", true, "Set to true to add all bees to NEI search").getBoolean(false); - addCombs = NEIAddons.config.get(getName(), "Add Combs to Search", false, "Set to true to add all combs that are produced by bees to NEI search").getBoolean(false); - addSaplings = NEIAddons.config.get(getName(), "Add Saplings to Search", true, "Set to true to add all saplings to NEI search").getBoolean(false); - addPollen = NEIAddons.config.get(getName(), "Add Pollen to Search", true, "Set to true to add all pollen types to NEI search").getBoolean(false); - - loadBlacklisted = NEIAddons.config.get(getName(), "Load blacklisted", false, "Set to true to load blacklisted species and alleles, it's dangerous and (mostly) useless").getBoolean(false); + showBeeMutations = NEIAddons.config + .get(getName(), "Show Bee Mutations", true, "Set to false to disable bee mutations browsing") + .getBoolean(false); + showBeeProducts = NEIAddons.config + .get(getName(), "Show Bee Products", true, "Set to false to disable bee products browsing") + .getBoolean(false); + + showTreeMutations = NEIAddons.config + .get(getName(), "Show Tree Mutations", true, "Set to false to disable tree mutations browsing") + .getBoolean(false); + showTreeProducts = NEIAddons.config + .get(getName(), "Show Tree Products", true, "Set to false to disable tree products browsing") + .getBoolean(false); + + showButterflyMutations = NEIAddons.config + .get( + getName(), + "Show Butterfly Mutations", + true, + "Set to false to disable butterfly mutations browsing") + .getBoolean(false); + // showButterflyProducts = NEIAddons.config.get(getName(), "Show Butterfly Products", true, "Set to false to + // disable butterfly products browsing").getBoolean(false); + + showSecret = NEIAddons.config + .get(getName(), "Show Secret Mutations", false, "Set to true to show secret mutations") + .getBoolean(false); + + showReqs = NEIAddons.config + .get( + getName(), + "Show Mutation Requirements", + true, + "Set to false disable display of mutation requirements") + .getBoolean(false); + + addBees = NEIAddons.config + .get(getName(), "Add Bees to Search", true, "Set to true to add all bees to NEI search") + .getBoolean(false); + addCombs = NEIAddons.config + .get( + getName(), + "Add Combs to Search", + false, + "Set to true to add all combs that are produced by bees to NEI search") + .getBoolean(false); + addSaplings = NEIAddons.config + .get(getName(), "Add Saplings to Search", true, "Set to true to add all saplings to NEI search") + .getBoolean(false); + addPollen = NEIAddons.config + .get(getName(), "Add Pollen to Search", true, "Set to true to add all pollen types to NEI search") + .getBoolean(false); + + loadBlacklisted = NEIAddons.config + .get( + getName(), + "Load blacklisted", + false, + "Set to true to load blacklisted species and alleles, it's dangerous and (mostly) useless") + .getBoolean(false); active = true; } public void registerWithNEIPlugins(String name, String id) { - FMLInterModComms.sendRuntimeMessage(this, "NEIPlugins", "register-crafting-handler", String.format("%s@%s@%s", I18n.format("bdew.neiaddons.genetics"), name, id)); + FMLInterModComms.sendRuntimeMessage( + this, + "NEIPlugins", + "register-crafting-handler", + String.format("%s@%s@%s", I18n.format("bdew.neiaddons.genetics"), name, id)); } @Override diff --git a/src/main/scala/net/bdew/neiaddons/forestry/BaseBreedingRecipeHandler.java b/src/main/scala/net/bdew/neiaddons/forestry/BaseBreedingRecipeHandler.java index 3e0e7a2..f71b971 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/BaseBreedingRecipeHandler.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/BaseBreedingRecipeHandler.java @@ -18,17 +18,16 @@ import forestry.api.genetics.IIndividual; import forestry.api.genetics.IMutation; import forestry.api.genetics.ISpeciesRoot; -import net.bdew.neiaddons.Utils; -import net.bdew.neiaddons.utils.LabeledPositionedStack; -import net.minecraft.client.resources.I18n; -import net.minecraft.item.ItemStack; -import net.minecraft.util.EnumChatFormatting; - import java.awt.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; +import net.bdew.neiaddons.Utils; +import net.bdew.neiaddons.utils.LabeledPositionedStack; +import net.minecraft.client.resources.I18n; +import net.minecraft.item.ItemStack; +import net.minecraft.util.EnumChatFormatting; public abstract class BaseBreedingRecipeHandler extends TemplateRecipeHandler { @@ -45,27 +44,39 @@ public class CachedBreedingRecipe extends CachedRecipe { public Boolean derp = false; public CachedBreedingRecipe(IMutation mutation) { - ItemStack stackParent1 = GeneticsUtils.stackFromSpecies(mutation.getAllele0(), GeneticsUtils.RecipePosition.Parent1); - ItemStack stackParent2 = GeneticsUtils.stackFromSpecies(mutation.getAllele1(), GeneticsUtils.RecipePosition.Parent2); - ItemStack stackResult = GeneticsUtils.stackFromSpecies((IAlleleSpecies) mutation.getTemplate()[0], GeneticsUtils.RecipePosition.Offspring); - - parrent1 = new LabeledPositionedStack(stackParent1, 22, 19, mutation.getAllele0().getName(), 13); - parrent2 = new LabeledPositionedStack(stackParent2, 75, 19, mutation.getAllele1().getName(), 13); + ItemStack stackParent1 = + GeneticsUtils.stackFromSpecies(mutation.getAllele0(), GeneticsUtils.RecipePosition.Parent1); + ItemStack stackParent2 = + GeneticsUtils.stackFromSpecies(mutation.getAllele1(), GeneticsUtils.RecipePosition.Parent2); + ItemStack stackResult = GeneticsUtils.stackFromSpecies( + (IAlleleSpecies) mutation.getTemplate()[0], GeneticsUtils.RecipePosition.Offspring); + + parrent1 = new LabeledPositionedStack( + stackParent1, 22, 19, mutation.getAllele0().getName(), 13); + parrent2 = new LabeledPositionedStack( + stackParent2, 75, 19, mutation.getAllele1().getName(), 13); result = new LabeledPositionedStack(stackResult, 129, 19, mutation.getTemplate()[0].getName(), 13); chance = mutation.getBaseChance(); try { requirements = mutation.getSpecialConditions(); } catch (Throwable t) { - AddonForestry.instance.logSevereExc(t, "Error in mutation.getSpecialConditions for mutation %s + %s -> %s", - mutation.getAllele0().getUID(), mutation.getAllele1().getUID(), mutation.getTemplate()[0].getUID()); + AddonForestry.instance.logSevereExc( + t, + "Error in mutation.getSpecialConditions for mutation %s + %s -> %s", + mutation.getAllele0().getUID(), + mutation.getAllele1().getUID(), + mutation.getTemplate()[0].getUID()); requirements = Collections.singletonList(EnumChatFormatting.RED + "Error! See log for details"); derp = true; } if (requirements == null) { - AddonForestry.instance.logWarning("Mutation %s + %s -> %s is returning null from getSpecialConditions", - mutation.getAllele0().getUID(), mutation.getAllele1().getUID(), mutation.getTemplate()[0].getUID()); + AddonForestry.instance.logWarning( + "Mutation %s + %s -> %s is returning null from getSpecialConditions", + mutation.getAllele0().getUID(), + mutation.getAllele1().getUID(), + mutation.getTemplate()[0].getUID()); requirements = new ArrayList(); } } @@ -191,7 +202,10 @@ public String getGuiTexture() { @Override public List handleTooltip(GuiRecipe gui, List currenttip, int recipe) { CachedBreedingRecipe rec = (CachedBreedingRecipe) arecipes.get(recipe); - if (AddonForestry.showReqs && rec.requirements.size() > 0 && GuiContainerManager.shouldShowTooltip(gui) && currenttip.size() == 0) { + if (AddonForestry.showReqs + && rec.requirements.size() > 0 + && GuiContainerManager.shouldShowTooltip(gui) + && currenttip.size() == 0) { Point offset = gui.getRecipePosition(recipe); Point pos = GuiDraw.getMousePosition(); Point relMouse = new Point(pos.x - gui.guiLeft - offset.x, pos.y - gui.guiTop - offset.y); diff --git a/src/main/scala/net/bdew/neiaddons/forestry/BaseProduceRecipeHandler.java b/src/main/scala/net/bdew/neiaddons/forestry/BaseProduceRecipeHandler.java index 56e8c73..b92337b 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/BaseProduceRecipeHandler.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/BaseProduceRecipeHandler.java @@ -11,10 +11,19 @@ import codechicken.nei.NEIClientUtils; import codechicken.nei.PositionedStack; +import codechicken.nei.recipe.GuiRecipe; import codechicken.nei.recipe.TemplateRecipeHandler; +import forestry.api.apiculture.IAlleleBeeSpeciesCustom; +import forestry.api.apiculture.IJubilanceProvider; import forestry.api.genetics.IAlleleSpecies; import forestry.api.genetics.IIndividual; import forestry.api.genetics.ISpeciesRoot; +import java.awt.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; import net.bdew.neiaddons.Utils; import net.bdew.neiaddons.utils.LabeledPositionedStack; import net.minecraft.client.Minecraft; @@ -22,12 +31,7 @@ import net.minecraft.client.resources.I18n; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; - -import java.awt.*; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; +import net.minecraft.util.EnumChatFormatting; public abstract class BaseProduceRecipeHandler extends TemplateRecipeHandler { @@ -54,15 +58,25 @@ public CachedProduceRecipe(IAlleleSpecies species) { products = new ArrayList(); int i = 0; - for (Entry product : Utils.mergeStacks(GeneticsUtils.getProduceFromSpecies(species)).entrySet()) { + for (Entry product : Utils.mergeStacks(GeneticsUtils.getProduceFromSpecies(species)) + .entrySet()) { String label = String.format("%.1f%%", product.getValue() * 100F); products.add(new LabeledPositionedStack(product.getKey(), 96 + 22 * i++, 8, label, 10)); } i = 0; - for (Entry product : Utils.mergeStacks(GeneticsUtils.getSpecialtyFromSpecies(species)).entrySet()) { + for (Entry product : Utils.mergeStacks(GeneticsUtils.getSpecialtyFromSpecies(species)) + .entrySet()) { String label = String.format("%.1f%%", product.getValue() * 100F); - products.add(new LabeledPositionedStack(product.getKey(), 96 + 22 * i++, 36, label, 10)); + String jubilance = null; + if (species instanceof IAlleleBeeSpeciesCustom) { + IJubilanceProvider provider = ((IAlleleBeeSpeciesCustom) species).getJubilanceProvider(); + if (provider != null) jubilance = provider.getDescription(); + } + if (jubilance != null) + products.add(new LabeledPositionedStack( + product.getKey(), 96 + 22 * i++, 36, label, 10, EnumChatFormatting.GRAY + jubilance)); + else products.add(new LabeledPositionedStack(product.getKey(), 96 + 22 * i++, 36, label, 10)); } } @@ -117,6 +131,17 @@ public void loadCraftingRecipes(String outputId, Object... results) { } } + @Override + public List handleItemTooltip(GuiRecipe gui, ItemStack stack, List currenttip, int recipe) { + CachedProduceRecipe crecipe = (CachedProduceRecipe) this.arecipes.get(recipe); + for (PositionedStack positionedStack : crecipe.getOtherStacks()) { + if (stack == positionedStack.item) { + currenttip.addAll(((LabeledPositionedStack) positionedStack).getTooltip()); + } + } + return currenttip; + } + @Override public void loadCraftingRecipes(ItemStack result) { if (cache == null) return; @@ -145,7 +170,8 @@ public void loadUsageRecipes(ItemStack ingredient) { } IIndividual member = speciesRoot.getMember(ingredient); if (member == null || member.getGenome() == null || member.getGenome().getPrimary() == null) { - AddonForestry.instance.logWarning("Individual or genome is null searching recipe for %s", ingredient.toString()); + AddonForestry.instance.logWarning( + "Individual or genome is null searching recipe for %s", ingredient.toString()); return; } arecipes.add(new CachedProduceRecipe(member.getGenome().getPrimary())); diff --git a/src/main/scala/net/bdew/neiaddons/forestry/GeneticsUtils.java b/src/main/scala/net/bdew/neiaddons/forestry/GeneticsUtils.java index 628f675..5462626 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/GeneticsUtils.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/GeneticsUtils.java @@ -18,18 +18,20 @@ import forestry.api.arboriculture.ITreeRoot; import forestry.api.genetics.*; import forestry.api.lepidopterology.IAlleleButterflySpecies; -import net.bdew.neiaddons.Utils; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; +import net.bdew.neiaddons.Utils; +import net.minecraft.item.ItemStack; public class GeneticsUtils { public enum RecipePosition { - Parent1, Parent2, Offspring, Producer + Parent1, + Parent2, + Offspring, + Producer } public static Map beePositionToType; @@ -91,9 +93,12 @@ public static Collection getAllTreeSpecies(boolean includeBl @SuppressWarnings("unchecked") public static Collection getAllTypedSpecies(Class type, boolean includeBlacklisted) { ArrayList list = new ArrayList(); - for (Entry entry : AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { + for (Entry entry : + AlleleManager.alleleRegistry.getRegisteredAlleles().entrySet()) { if (type.isInstance(entry.getValue())) { - if (includeBlacklisted || !AlleleManager.alleleRegistry.isBlacklisted(entry.getValue().getUID())) { + if (includeBlacklisted + || !AlleleManager.alleleRegistry.isBlacklisted( + entry.getValue().getUID())) { list.add((T) entry.getValue()); } } @@ -101,7 +106,7 @@ public static Collection getAllTypedSpecies(Class type, bool return list; } - static public Map getProduceFromSpecies(IAlleleSpecies species) { + public static Map getProduceFromSpecies(IAlleleSpecies species) { if (species instanceof IAlleleBeeSpecies) { return Utils.sanitizeDrops(((IAlleleBeeSpecies) species).getProductChances(), species.getUID() + " drops"); } else if (species instanceof IAlleleTreeSpecies) { @@ -125,9 +130,10 @@ static public Map getProduceFromSpecies(IAlleleSpecies species return new HashMap(); } - static public Map getSpecialtyFromSpecies(IAlleleSpecies species) { + public static Map getSpecialtyFromSpecies(IAlleleSpecies species) { if (species instanceof IAlleleBeeSpecies) { - return Utils.sanitizeDrops(((IAlleleBeeSpecies) species).getSpecialtyChances(), species.getUID() + " specialty"); + return Utils.sanitizeDrops( + ((IAlleleBeeSpecies) species).getSpecialtyChances(), species.getUID() + " specialty"); } else if (species instanceof IAlleleTreeSpecies) { Map result = new HashMap(); ITreeRoot root = (ITreeRoot) species.getRoot(); diff --git a/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeHelper.java b/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeHelper.java index 6ae9a68..3659c55 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeHelper.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeHelper.java @@ -17,6 +17,7 @@ import forestry.api.apiculture.IBeeRoot; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; +import java.util.*; import net.bdew.neiaddons.Utils; import net.bdew.neiaddons.forestry.AddonForestry; import net.bdew.neiaddons.forestry.GeneticsUtils; @@ -24,8 +25,6 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.util.*; - public class BeeHelper { public static Collection allSpecies; @@ -45,14 +44,16 @@ private static void addHandlers() { BeeBreedingHandler breedingRecipeHandler = new BeeBreedingHandler(); API.registerRecipeHandler(breedingRecipeHandler); API.registerUsageHandler(breedingRecipeHandler); - AddonForestry.instance.registerWithNEIPlugins(breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); + AddonForestry.instance.registerWithNEIPlugins( + breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); } if (AddonForestry.showBeeProducts) { BeeProduceHandler productsRecipeHandler = new BeeProduceHandler(); API.registerRecipeHandler(productsRecipeHandler); API.registerUsageHandler(productsRecipeHandler); - AddonForestry.instance.registerWithNEIPlugins(productsRecipeHandler.getRecipeName(), productsRecipeHandler.getRecipeIdent()); + AddonForestry.instance.registerWithNEIPlugins( + productsRecipeHandler.getRecipeName(), productsRecipeHandler.getRecipeIdent()); } } @@ -104,7 +105,9 @@ public static void setup() { for (ItemStack item : combs) { subitems.add(item.getItemDamage()); - AddonForestry.instance.logInfo("Registering comb variant for %s: %s", combItem.getClass().getName(), item.toString()); + AddonForestry.instance.logInfo( + "Registering comb variant for %s: %s", + combItem.getClass().getName(), item.toString()); API.addItemListEntry(item); } } diff --git a/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeProduceHandler.java b/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeProduceHandler.java index a70d101..e1d448a 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeProduceHandler.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/bees/BeeProduceHandler.java @@ -11,11 +11,10 @@ import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.genetics.IAlleleSpecies; -import net.bdew.neiaddons.forestry.BaseProduceRecipeHandler; -import net.minecraft.item.Item; - import java.util.Collection; import java.util.Map; +import net.bdew.neiaddons.forestry.BaseProduceRecipeHandler; +import net.minecraft.item.Item; public class BeeProduceHandler extends BaseProduceRecipeHandler { diff --git a/src/main/scala/net/bdew/neiaddons/forestry/butterflies/ButterflyHelper.java b/src/main/scala/net/bdew/neiaddons/forestry/butterflies/ButterflyHelper.java index 9f5eaca..3898b09 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/butterflies/ButterflyHelper.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/butterflies/ButterflyHelper.java @@ -14,31 +14,31 @@ import forestry.api.lepidopterology.EnumFlutterType; import forestry.api.lepidopterology.IAlleleButterflySpecies; import forestry.api.lepidopterology.IButterflyRoot; +import java.util.Collection; import net.bdew.neiaddons.Utils; import net.bdew.neiaddons.forestry.AddonForestry; import net.bdew.neiaddons.forestry.GeneticsUtils; -import java.util.Collection; - public class ButterflyHelper { public static Collection allSpecies; -// public static Map> productsCache; + // public static Map> productsCache; public static IButterflyRoot root; -// private static void addProductToCache(int id, IAlleleBeeSpecies species) { -// if (!productsCache.containsKey(id)) { -// productsCache.put(id, new ArrayList()); -// } -// productsCache.get(id).add(species); -// } + // private static void addProductToCache(int id, IAlleleBeeSpecies species) { + // if (!productsCache.containsKey(id)) { + // productsCache.put(id, new ArrayList()); + // } + // productsCache.get(id).add(species); + // } public static void setup() { root = (IButterflyRoot) AlleleManager.alleleRegistry.getSpeciesRoot("rootButterflies"); if (root == null) { - AddonForestry.instance.logWarning("Butterfly Species Root not found, some functionality will be unavailable"); + AddonForestry.instance.logWarning( + "Butterfly Species Root not found, some functionality will be unavailable"); return; } @@ -48,10 +48,11 @@ public static void setup() { ButterflyBreedingHandler breedingRecipeHandler = new ButterflyBreedingHandler(); API.registerRecipeHandler(breedingRecipeHandler); API.registerUsageHandler(breedingRecipeHandler); - AddonForestry.instance.registerWithNEIPlugins(breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); + AddonForestry.instance.registerWithNEIPlugins( + breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); } -// productsCache = new HashMap>(); + // productsCache = new HashMap>(); for (IAlleleButterflySpecies species : allSpecies) { if (AddonForestry.addBees) { diff --git a/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeHelper.java b/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeHelper.java index 22a10eb..8b5f484 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeHelper.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeHelper.java @@ -15,6 +15,10 @@ import forestry.api.arboriculture.ITreeRoot; import forestry.api.genetics.AlleleManager; import forestry.api.genetics.IAlleleSpecies; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; import net.bdew.neiaddons.Utils; import net.bdew.neiaddons.forestry.AddonForestry; import net.bdew.neiaddons.forestry.GeneticsUtils; @@ -22,11 +26,6 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - public class TreeHelper { public static Collection allSpecies; public static Map> productsCache = new HashMap>(); @@ -54,14 +53,16 @@ public static void setup() { TreeBreedingHandler breedingRecipeHandler = new TreeBreedingHandler(); API.registerRecipeHandler(breedingRecipeHandler); API.registerUsageHandler(breedingRecipeHandler); - AddonForestry.instance.registerWithNEIPlugins(breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); + AddonForestry.instance.registerWithNEIPlugins( + breedingRecipeHandler.getRecipeName(), breedingRecipeHandler.getRecipeIdent()); } if (AddonForestry.showTreeProducts) { TreeProduceHandler produceRecipeHandler = new TreeProduceHandler(); API.registerRecipeHandler(produceRecipeHandler); API.registerUsageHandler(produceRecipeHandler); - AddonForestry.instance.registerWithNEIPlugins(produceRecipeHandler.getRecipeName(), produceRecipeHandler.getRecipeIdent()); + AddonForestry.instance.registerWithNEIPlugins( + produceRecipeHandler.getRecipeName(), produceRecipeHandler.getRecipeIdent()); } for (IAlleleTreeSpecies species : allSpecies) { diff --git a/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeProduceHandler.java b/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeProduceHandler.java index 21a82d4..7de4493 100644 --- a/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeProduceHandler.java +++ b/src/main/scala/net/bdew/neiaddons/forestry/trees/TreeProduceHandler.java @@ -11,11 +11,10 @@ import forestry.api.arboriculture.IAlleleTreeSpecies; import forestry.api.genetics.IAlleleSpecies; -import net.bdew.neiaddons.forestry.BaseProduceRecipeHandler; -import net.minecraft.item.Item; - import java.util.Collection; import java.util.Map; +import net.bdew.neiaddons.forestry.BaseProduceRecipeHandler; +import net.minecraft.item.Item; public class TreeProduceHandler extends BaseProduceRecipeHandler { diff --git a/src/main/scala/net/bdew/neiaddons/network/ClientHandler.java b/src/main/scala/net/bdew/neiaddons/network/ClientHandler.java index b6583b1..dccc9fb 100644 --- a/src/main/scala/net/bdew/neiaddons/network/ClientHandler.java +++ b/src/main/scala/net/bdew/neiaddons/network/ClientHandler.java @@ -14,13 +14,12 @@ import cpw.mods.fml.common.network.FMLNetworkEvent; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; -import net.bdew.neiaddons.NEIAddons; -import net.minecraft.nbt.NBTTagCompound; -import org.apache.commons.lang3.StringUtils; - import java.util.Arrays; import java.util.HashSet; import java.util.Set; +import net.bdew.neiaddons.NEIAddons; +import net.minecraft.nbt.NBTTagCompound; +import org.apache.commons.lang3.StringUtils; public class ClientHandler extends SimpleChannelInboundHandler { public static Set enabledCommands = new HashSet(); @@ -44,7 +43,9 @@ protected void channelRead0(ChannelHandlerContext ctx, NBTTagCompound msg) throw NEIAddons.logInfo("Received handshake from server"); enabledCommands.clear(); if (data.getInteger("version") != NEIAddons.netVersion) { - NEIAddons.logWarning("Client/Server version mismatch! client=%d server=%d", data.getInteger("version"), NEIAddons.netVersion); + NEIAddons.logWarning( + "Client/Server version mismatch! client=%d server=%d", + data.getInteger("version"), NEIAddons.netVersion); return; } String cmds = data.getString("commands"); diff --git a/src/main/scala/net/bdew/neiaddons/network/NBTMessageCodec.java b/src/main/scala/net/bdew/neiaddons/network/NBTMessageCodec.java index bbe3ce9..5157a8f 100644 --- a/src/main/scala/net/bdew/neiaddons/network/NBTMessageCodec.java +++ b/src/main/scala/net/bdew/neiaddons/network/NBTMessageCodec.java @@ -18,13 +18,12 @@ import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageCodec; -import net.bdew.neiaddons.NEIAddons; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; - import java.io.DataInputStream; import java.io.DataOutputStream; import java.util.List; +import net.bdew.neiaddons.NEIAddons; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; @ChannelHandler.Sharable public class NBTMessageCodec extends MessageToMessageCodec { @@ -33,7 +32,8 @@ protected void encode(ChannelHandlerContext ctx, NBTTagCompound msg, List channels; diff --git a/src/main/scala/net/bdew/neiaddons/network/ServerHandler.java b/src/main/scala/net/bdew/neiaddons/network/ServerHandler.java index 25646e4..9a64a4b 100644 --- a/src/main/scala/net/bdew/neiaddons/network/ServerHandler.java +++ b/src/main/scala/net/bdew/neiaddons/network/ServerHandler.java @@ -15,6 +15,8 @@ import cpw.mods.fml.common.network.NetworkRegistry; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; +import java.util.HashMap; +import java.util.Map; import net.bdew.neiaddons.NEIAddons; import net.bdew.neiaddons.api.SubPacketHandler; import net.minecraft.entity.player.EntityPlayer; @@ -23,9 +25,6 @@ import net.minecraft.network.NetHandlerPlayServer; import org.apache.commons.lang3.StringUtils; -import java.util.HashMap; -import java.util.Map; - public class ServerHandler extends SimpleChannelInboundHandler { private static Map handlers = new HashMap(); @@ -35,7 +34,9 @@ public ServerHandler() { public static void registerHandler(String command, SubPacketHandler handler) { if (handlers.containsKey(command)) { - throw new RuntimeException(String.format("Tried to register handler for command %s that's already registered for %s", command, handler.toString())); + throw new RuntimeException(String.format( + "Tried to register handler for command %s that's already registered for %s", + command, handler.toString())); } handlers.put(command, handler); } @@ -44,13 +45,16 @@ public static void registerHandler(String command, SubPacketHandler handler) { protected void channelRead0(ChannelHandlerContext ctx, NBTTagCompound msg) throws Exception { String cmd = msg.getString("cmd"); NBTTagCompound data = msg.getCompoundTag("data"); - NetHandlerPlayServer nh = (NetHandlerPlayServer) (ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()); + NetHandlerPlayServer nh = (NetHandlerPlayServer) + (ctx.channel().attr(NetworkRegistry.NET_HANDLER).get()); processCommand(cmd, data, nh.playerEntity); } public void processCommand(String cmd, NBTTagCompound data, EntityPlayerMP from) { if (handlers.containsKey(cmd)) { - NEIAddons.logInfo("Handling %s from %s -> %s", cmd, from.getDisplayName(), handlers.get(cmd).toString()); + NEIAddons.logInfo( + "Handling %s from %s -> %s", + cmd, from.getDisplayName(), handlers.get(cmd).toString()); try { handlers.get(cmd).handle(data, from); } catch (Throwable e) { diff --git a/src/main/scala/net/bdew/neiaddons/utils/CustomOverlayHandler.java b/src/main/scala/net/bdew/neiaddons/utils/CustomOverlayHandler.java index 596c81b..d397523 100644 --- a/src/main/scala/net/bdew/neiaddons/utils/CustomOverlayHandler.java +++ b/src/main/scala/net/bdew/neiaddons/utils/CustomOverlayHandler.java @@ -9,6 +9,8 @@ package net.bdew.neiaddons.utils; +import static codechicken.nei.NEIServerUtils.areStacksSameType; + import codechicken.nei.LayoutManager; import codechicken.nei.NEIClientUtils; import codechicken.nei.OffsetPositioner; @@ -18,6 +20,7 @@ import codechicken.nei.api.IStackPositioner; import codechicken.nei.guihook.GuiContainerManager; import codechicken.nei.recipe.IRecipeHandler; +import java.util.List; import net.bdew.neiaddons.NEIAddons; import net.bdew.neiaddons.network.ClientHandler; import net.bdew.neiaddons.network.PacketHelper; @@ -28,17 +31,14 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import java.util.List; - -import static codechicken.nei.NEIServerUtils.areStacksSameType; - public class CustomOverlayHandler implements IOverlayHandler { private boolean invert; private String command; private int xOffs, yOffs; private Class craftingSlot; - public CustomOverlayHandler(String command, int xOffs, int yOffs, boolean invert, Class craftingSlot) { + public CustomOverlayHandler( + String command, int xOffs, int yOffs, boolean invert, Class craftingSlot) { super(); this.command = command; this.xOffs = xOffs; @@ -54,7 +54,9 @@ private Slot findMatchingSlot(GuiContainer cont, PositionedStack pstack) { return slot; } } - NEIAddons.logWarning("Failed to find matching slot - (%d,%d) in %s", pstack.relx + xOffs, pstack.rely + yOffs, cont.toString()); + NEIAddons.logWarning( + "Failed to find matching slot - (%d,%d) in %s", + pstack.relx + xOffs, pstack.rely + yOffs, cont.toString()); return null; } @@ -133,14 +135,14 @@ public void overlayRecipe(GuiContainer cont, IRecipeHandler recipe, int recipeIn if (pstack != null) { Slot slotTo = findMatchingSlot(cont, pstack); - if (slotTo == null) - continue; + if (slotTo == null) continue; Slot slotFrom = findItem(cont, pstack); - if (slotFrom == null) - continue; + if (slotFrom == null) continue; - NEIAddons.logInfo("Moving from slot %s[%d] to %s[%d]", slotFrom.toString(), slotFrom.slotNumber, slotTo.toString(), slotTo.slotNumber); + NEIAddons.logInfo( + "Moving from slot %s[%d] to %s[%d]", + slotFrom.toString(), slotFrom.slotNumber, slotTo.toString(), slotTo.slotNumber); // pick up item manager.handleSlotClick(slotFrom.slotNumber, 0, 0); diff --git a/src/main/scala/net/bdew/neiaddons/utils/ItemStackWithTip.java b/src/main/scala/net/bdew/neiaddons/utils/ItemStackWithTip.java index 10b3bc4..313820f 100644 --- a/src/main/scala/net/bdew/neiaddons/utils/ItemStackWithTip.java +++ b/src/main/scala/net/bdew/neiaddons/utils/ItemStackWithTip.java @@ -9,10 +9,9 @@ package net.bdew.neiaddons.utils; -import net.minecraft.item.ItemStack; - import java.util.ArrayList; import java.util.List; +import net.minecraft.item.ItemStack; public class ItemStackWithTip { public ItemStack itemStack; diff --git a/src/main/scala/net/bdew/neiaddons/utils/LabeledPositionedStack.java b/src/main/scala/net/bdew/neiaddons/utils/LabeledPositionedStack.java index e6ecbdf..631f1ce 100644 --- a/src/main/scala/net/bdew/neiaddons/utils/LabeledPositionedStack.java +++ b/src/main/scala/net/bdew/neiaddons/utils/LabeledPositionedStack.java @@ -10,12 +10,16 @@ package net.bdew.neiaddons.utils; import codechicken.nei.PositionedStack; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import net.bdew.neiaddons.Utils; public class LabeledPositionedStack extends PositionedStack { private final String label; private final int yoffs; + private final ArrayList tooltip = new ArrayList<>(); public LabeledPositionedStack(Object stack, int x, int y, String label, int yoffs) { super(stack, x, y); @@ -23,6 +27,13 @@ public LabeledPositionedStack(Object stack, int x, int y, String label, int yoff this.yoffs = yoffs; } + public LabeledPositionedStack(Object stack, int x, int y, String label, int yoffs, String... tooltip) { + super(stack, x, y); + this.label = label; + this.yoffs = yoffs; + this.tooltip.addAll(Arrays.asList(tooltip)); + } + public void drawLabel() { if (label.contains(" ")) { String[] parts = label.split(" "); @@ -33,4 +44,8 @@ public void drawLabel() { Utils.drawCenteredString(label, relx + 8, rely + 8 + yoffs, 0xFFFFFF); } } + + public List getTooltip() { + return tooltip; + } } diff --git a/src/main/scala/net/bdew/neiaddons/utils/PositionedStackWithTip.java b/src/main/scala/net/bdew/neiaddons/utils/PositionedStackWithTip.java index 02d3822..c909c21 100644 --- a/src/main/scala/net/bdew/neiaddons/utils/PositionedStackWithTip.java +++ b/src/main/scala/net/bdew/neiaddons/utils/PositionedStackWithTip.java @@ -10,7 +10,6 @@ package net.bdew.neiaddons.utils; import codechicken.nei.PositionedStack; - import java.util.List; public class PositionedStackWithTip extends PositionedStack { diff --git a/src/main/scala/net/bdew/neiaddons/utils/SetRecipeCommandHandler.java b/src/main/scala/net/bdew/neiaddons/utils/SetRecipeCommandHandler.java index 2831215..99338c9 100644 --- a/src/main/scala/net/bdew/neiaddons/utils/SetRecipeCommandHandler.java +++ b/src/main/scala/net/bdew/neiaddons/utils/SetRecipeCommandHandler.java @@ -9,6 +9,7 @@ package net.bdew.neiaddons.utils; +import java.util.HashMap; import net.bdew.neiaddons.api.SubPacketHandler; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; @@ -17,8 +18,6 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -import java.util.HashMap; - public class SetRecipeCommandHandler implements SubPacketHandler { private Class ContainerClass; private Class SlotClass; diff --git a/src/main/scala/net/bdew/neiaddons/utils/TypedField.java b/src/main/scala/net/bdew/neiaddons/utils/TypedField.java index 23c8274..21d322e 100644 --- a/src/main/scala/net/bdew/neiaddons/utils/TypedField.java +++ b/src/main/scala/net/bdew/neiaddons/utils/TypedField.java @@ -24,8 +24,7 @@ public TypedField(Field field, Class cls) { public T get(Object obj) { try { Object res = field.get(obj); - if (cls.isInstance(res)) - return (T) res; + if (cls.isInstance(res)) return (T) res; else throw new RuntimeException(String.format("Wrong field type. Expected %s, got %s", cls, res.getClass())); } catch (IllegalAccessException e) { diff --git a/src/main/scala/net/bdew/neiaddons/utils/TypedMethod.java b/src/main/scala/net/bdew/neiaddons/utils/TypedMethod.java index 4cd4470..dc13616 100644 --- a/src/main/scala/net/bdew/neiaddons/utils/TypedMethod.java +++ b/src/main/scala/net/bdew/neiaddons/utils/TypedMethod.java @@ -25,10 +25,10 @@ public TypedMethod(Method method, Class cls) { public T call(Object obj, Object... args) { try { Object res = field.invoke(obj, args); - if (cls.isInstance(res)) - return (T) res; + if (cls.isInstance(res)) return (T) res; else - throw new RuntimeException(String.format("Wrong return type. Expected %s, got %s", cls, res.getClass())); + throw new RuntimeException( + String.format("Wrong return type. Expected %s, got %s", cls, res.getClass())); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) {